sparseUtil provides useful sparse matrix operations for incremental construction of large sparse matrices from its block elements. Class csc_matrixPlus derives from sparse.csc_matrix and makes it possible to set elements outside the matrix dimensions by resizing the matrix whenever necessary. Class csr_matrixPlus does the same thing with sparse.csr_matrix.
Function sparseConcat() concatenates two sparse matrices regardless of their dimension alignments. Fills with zeros where necessary.
Set the item in row i and column j to val. Increases matrix’s size if necessary
Usage
>>> from CyLP.py.utils.sparseUtil import csc_matrixPlus
>>> import numpy as np
>>> indptr = np.array([0, 2, 3, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> s = csc_matrixPlus((data, indices, indptr), shape=(3, 3))
>>> s[2, 5] = 11
>>> s.todense()
matrix([[ 1, 0, 4, 0, 0, 0],
[ 0, 0, 5, 0, 0, 0],
[ 2, 3, 6, 0, 0, 11]])
Sets the item in row i and col j to val. Increases matrix’s shape[1] if necessary
Usage
>>> from CyLP.py.utils.sparseUtil import csr_matrixPlus
>>> import numpy as np
>>> indptr = np.array([0, 2, 3, 6])
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> s = csr_matrixPlus((data, indices, indptr), shape=(3, 3))
>>> s[5,2] = 11
>>> print s.todense()
[[ 1 0 2]
[ 0 0 3]
[ 4 5 6]
[ 0 0 0]
[ 0 0 0]
[ 0 0 11]]
Concatenate two sparse matrices, a and b, horizontally if how = 'h', and vertically if how = 'v'. Add zero rows and columns if dimensions don’t align. v_offset specifies how to align b along side a. The value of v_offset will be added to each row index of b. v_offset=-1 means that we want the greatest possible offset without changeing the dimensions. h_offset is a similar argument but to specify horizontal offset.
Usage
>>> from scipy import sparse
>>> from CyLP.py.utils.sparseUtil import sparseConcat, csc_matrixPlus
>>> s1 = csc_matrixPlus.getMatrixForTest()
>>> s2 = sparse.lil_matrix([[1,0,2],[0,5,0]])
>>> sparseConcat(s1, s2, 'v').todense()
matrix([[1, 0, 4],
[0, 0, 5],
[2, 3, 6],
[1, 0, 2],
[0, 5, 0]])
>>> sparseConcat(s1, s2, 'h').todense()
matrix([[1, 0, 4, 1, 0, 2],
[0, 0, 5, 0, 5, 0],
[2, 3, 6, 0, 0, 0]])
If a = None then return b. This makes possible an incremental construction of large sparse matrices from scratch without the hassle of the initial value check.
>>> s3 = None
>>> ((sparseConcat(s3, s1, 'h').todense() == s1.todense()).all() and
... (sparseConcat(s3, s1, 'v').todense() == s1.todense()).all())
True