def __radd__(self, other): # First check if argument is a scalar if isscalarlike(other): new = dok_matrix(self.shape, dtype=self.dtype) # Add this scalar to every element. M, N = self.shape for i in xrange(M): for j in xrange(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij elif isinstance(other, dok_matrix): if other.shape != self.shape: raise ValueError("matrix dimensions are not equal") new = dok_matrix(self.shape, dtype=self.dtype) new.update(self) for key in other: new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other elif isdense(other): new = other + self.todense() else: raise TypeError("data type not understood") return new
def __add__(self, other): # First check if argument is a scalar if isscalarlike(other): new = dok_matrix(self.shape, dtype=self.dtype) # Add this scalar to every element. M, N = self.shape for i in xrange(M): for j in xrange(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): if other.shape != self.shape: raise ValueError("matrix dimensions are not equal") # We could alternatively set the dimensions to the the largest of # the two matrices to be summed. Would this be a good idea? new = dok_matrix(self.shape, dtype=self.dtype) new.update(self) for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other elif isdense(other): new = self.todense() + other else: raise TypeError("data type not understood") return new
def __init__(self, arg1, shape=None, dtype=None, copy=False): dict.__init__(self) spmatrix.__init__(self) self.dtype = getdtype(dtype, default=float) if isinstance(arg1, tuple) and isshape(arg1): # (M,N) M, N = arg1 self.shape = (M, N) elif isspmatrix(arg1): # Sparse ctor if isspmatrix_dok(arg1) and copy: arg1 = arg1.copy() else: arg1 = arg1.todok() if dtype is not None: arg1 = arg1.astype(dtype) self.update(arg1) self.shape = arg1.shape self.dtype = arg1.dtype else: # Dense ctor try: arg1 = np.asarray(arg1) except: raise TypeError('invalid input format') if len(arg1.shape)!=2: raise TypeError('expected rank <=2 dense array or matrix') from coo import coo_matrix self.update( coo_matrix(arg1, dtype=dtype).todok() ) self.shape = arg1.shape self.dtype = arg1.dtype
def __init__(self, arg1, shape=None, dtype=None, copy=False): dict.__init__(self) spmatrix.__init__(self) self.dtype = getdtype(dtype, default=float) if isinstance(arg1, tuple) and isshape(arg1): # (M,N) M, N = arg1 self.shape = (M, N) elif isspmatrix(arg1): # Sparse ctor if isspmatrix_dok(arg1) and copy: arg1 = arg1.copy() else: arg1 = arg1.todok() if dtype is not None: arg1 = arg1.astype(dtype) self.update(arg1) self.shape = arg1.shape self.dtype = arg1.dtype else: # Dense ctor try: arg1 = np.asarray(arg1) except: raise TypeError('invalid input format') if len(arg1.shape) != 2: raise TypeError('expected rank <=2 dense array or matrix') from coo import coo_matrix self.update(coo_matrix(arg1, dtype=dtype).todok()) self.shape = arg1.shape self.dtype = arg1.dtype
def __truediv__(self,other): if isscalarlike(other): return self * (1./other) elif isspmatrix(other): if other.shape != self.shape: raise ValueError('inconsistent shapes') return self._binopt(other,'_eldiv_') else: raise NotImplementedError
def __truediv__(self, other): if isscalarlike(other): return self * (1. / other) elif isspmatrix(other): if other.shape != self.shape: raise ValueError('inconsistent shapes') return self._binopt(other, '_eldiv_') else: raise NotImplementedError
def __sub__(self,other): # First check if argument is a scalar if isscalarlike(other): # Now we would add this scalar to every element. raise NotImplementedError, 'adding a scalar to a sparse ' \ 'matrix is not supported' elif isspmatrix(other): if (other.shape != self.shape): raise ValueError, "inconsistent shapes" return self._binopt(other,'_minus_') elif isdense(other): # Convert this matrix to a dense matrix and subtract them return self.todense() - other else: raise NotImplementedError
def __add__(self,other): # First check if argument is a scalar if isscalarlike(other): # Now we would add this scalar to every element. raise NotImplementedError('adding a scalar to a CSC or CSR ' 'matrix is not supported') elif isspmatrix(other): if (other.shape != self.shape): raise ValueError("inconsistent shapes") return self._binopt(other,'_plus_') elif isdense(other): # Convert this matrix to a dense matrix and add them return self.todense() + other else: raise NotImplementedError
def __setitem__(self, index, x): try: i, j = index except (ValueError, TypeError): raise IndexError('invalid index') # shortcut for common case of single entry assign: if np.isscalar(x) and np.isscalar(i) and np.isscalar(j): self._insertat2(self.rows[i], self.data[i], j, x) return # shortcut for common case of full matrix assign: if isspmatrix(x): if isinstance(i, slice) and i == slice(None) and \ isinstance(j, slice) and j == slice(None): x = lil_matrix(x, dtype=self.dtype) self.rows = x.rows self.data = x.data return if isinstance(i, tuple): # can't index lists with tuple i = list(i) if np.isscalar(i): rows = [self.rows[i]] datas = [self.data[i]] else: rows = self.rows[i] datas = self.data[i] x = lil_matrix(x, copy=False) xrows, xcols = x.shape if xrows == len(rows): # normal rectangular copy for row, data, xrow, xdata in zip(rows, datas, x.rows, x.data): self._setitem_setrow(row, data, j, xrow, xdata, xcols) elif xrows == 1: # OK, broadcast down column for row, data in zip(rows, datas): self._setitem_setrow(row, data, j, x.rows[0], x.data[0], xcols) # needed to pass 'test_lil_sequence_assignement' unit test: # -- set row from column of entries -- elif xcols == len(rows): x = x.T for row, data, xrow, xdata in zip(rows, datas, x.rows, x.data): self._setitem_setrow(row, data, j, xrow, xdata, xrows) else: raise IndexError('invalid index')
def __sub__(self, other): # First check if argument is a scalar if isscalarlike(other): if other == 0: return self.copy() else: # Now we would add this scalar to every element. raise NotImplementedError("adding a nonzero scalar to a " "sparse matrix is not supported") elif isspmatrix(other): if other.shape != self.shape: raise ValueError("inconsistent shapes") return self._binopt(other, "_minus_") elif isdense(other): # Convert this matrix to a dense matrix and subtract them return self.todense() - other else: raise NotImplementedError
def __init__(self, arg1, shape=None, dtype=None, copy=False): spmatrix.__init__(self) self.dtype = getdtype(dtype, arg1, default=float) # First get the shape if isspmatrix(arg1): if isspmatrix_lil(arg1) and copy: A = arg1.copy() else: A = arg1.tolil() if dtype is not None: A = A.astype(dtype) self.shape = A.shape self.dtype = A.dtype self.rows = A.rows self.data = A.data elif isinstance(arg1,tuple): if isshape(arg1): if shape is not None: raise ValueError('invalid use of shape parameter') M, N = arg1 self.shape = (M,N) self.rows = np.empty((M,), dtype=object) self.data = np.empty((M,), dtype=object) for i in range(M): self.rows[i] = [] self.data[i] = [] else: raise TypeError('unrecognized lil_matrix constructor usage') else: #assume A is dense try: A = np.asmatrix(arg1) except TypeError: raise TypeError('unsupported matrix type') else: from csr import csr_matrix A = csr_matrix(A, dtype=dtype).tolil() self.shape = A.shape self.dtype = A.dtype self.rows = A.rows self.data = A.data
def __init__(self, arg1, shape=None, dtype=None, copy=False): spmatrix.__init__(self) self.dtype = getdtype(dtype, arg1, default=float) # First get the shape if isspmatrix(arg1): if isspmatrix_lil(arg1) and copy: A = arg1.copy() else: A = arg1.tolil() if dtype is not None: A = A.astype(dtype) self.shape = A.shape self.dtype = A.dtype self.rows = A.rows self.data = A.data elif isinstance(arg1, tuple): if isshape(arg1): if shape is not None: raise ValueError('invalid use of shape parameter') M, N = arg1 self.shape = (M, N) self.rows = np.empty((M, ), dtype=object) self.data = np.empty((M, ), dtype=object) for i in range(M): self.rows[i] = [] self.data[i] = [] else: raise TypeError('unrecognized lil_matrix constructor usage') else: #assume A is dense try: A = np.asmatrix(arg1) except TypeError: raise TypeError('unsupported matrix type') else: from csr import csr_matrix A = csr_matrix(A, dtype=dtype).tolil() self.shape = A.shape self.dtype = A.dtype self.rows = A.rows self.data = A.data
def __setitem__(self, index, x): if np.isscalar(x): x = self.dtype.type(x) elif not isinstance(x, spmatrix): x = lil_matrix(x) try: i, j = index except (ValueError, TypeError): raise IndexError('invalid index') if isspmatrix(x): if (isinstance(i, slice) and (i == slice(None))) and \ (isinstance(j, slice) and (j == slice(None))): # self[:,:] = other_sparse x = lil_matrix(x) self.rows = x.rows self.data = x.data return if np.isscalar(i): row = self.rows[i] data = self.data[i] self._insertat3(row, data, j, x) elif issequence(i) and issequence(j): if np.isscalar(x): for ii, jj in zip(i, j): self._insertat(ii, jj, x) else: for ii, jj, xx in zip(i, j, x): self._insertat(ii, jj, xx) elif isinstance(i, slice) or issequence(i): rows = self.rows[i] datas = self.data[i] if np.isscalar(x): for row, data in zip(rows, datas): self._insertat3(row, data, j, x) else: for row, data, xx in zip(rows, datas, x): self._insertat3(row, data, j, xx) else: raise ValueError('invalid index value: %s' % str((i, j)))
def __init__(self, arg1, shape=None, dtype=None, copy=False): _data_matrix.__init__(self) if isspmatrix(arg1): if arg1.format == self.format and copy: arg1 = arg1.copy() else: arg1 = arg1.asformat(self.format) self._set_self(arg1) elif isinstance(arg1, tuple): if isshape(arg1): # It's a tuple of matrix dimensions (M, N) # create empty matrix self.shape = arg1 #spmatrix checks for errors here M, N = self.shape self.data = np.zeros(0, getdtype(dtype, default=float)) self.indices = np.zeros(0, np.intc) self.indptr = np.zeros(self._swap((M, N))[0] + 1, dtype=np.intc) else: if len(arg1) == 2: # (data, ij) format from coo import coo_matrix other = self.__class__(coo_matrix(arg1, shape=shape)) self._set_self(other) elif len(arg1) == 3: # (data, indices, indptr) format (data, indices, indptr) = arg1 self.indices = np.array(indices, copy=copy) self.indptr = np.array(indptr, copy=copy) self.data = np.array(data, copy=copy, dtype=getdtype(dtype, data)) else: raise ValueError( "unrecognized %s_matrix constructor usage" % self.format) else: #must be dense try: arg1 = np.asarray(arg1) except: raise ValueError("unrecognized %s_matrix constructor usage" % self.format) from coo import coo_matrix self._set_self(self.__class__(coo_matrix(arg1, dtype=dtype))) # Read matrix dimensions given, if any if shape is not None: self.shape = shape # spmatrix will check for errors else: if self.shape is None: # shape not already set, try to infer dimensions try: major_dim = len(self.indptr) - 1 minor_dim = self.indices.max() + 1 except: raise ValueError('unable to infer matrix dimensions') else: self.shape = self._swap((major_dim, minor_dim)) if dtype is not None: self.data = self.data.astype(dtype) self.check_format(full_check=False)
def __init__(self, arg1, shape=None, dtype=None, copy=False): _data_matrix.__init__(self) if isspmatrix_dia(arg1): if copy: arg1 = arg1.copy() self.data = arg1.data self.offsets = arg1.offsets self.shape = arg1.shape elif isspmatrix(arg1): if isspmatrix_dia(arg1) and copy: A = arg1.copy() else: A = arg1.todia() self.data = A.data self.offsets = A.offsets self.shape = A.shape elif isinstance(arg1, tuple): if isshape(arg1): # It's a tuple of matrix dimensions (M, N) # create empty matrix self.shape = arg1 #spmatrix checks for errors here self.data = np.zeros((0, 0), getdtype(dtype, default=float)) self.offsets = np.zeros((0), dtype=np.intc) else: try: # Try interpreting it as (data, offsets) data, offsets = arg1 except: raise ValueError( 'unrecognized form for dia_matrix constructor') else: if shape is None: raise ValueError('expected a shape argument') self.data = np.atleast_2d( np.array(arg1[0], dtype=dtype, copy=copy)) self.offsets = np.atleast_1d( np.array(arg1[1], dtype=np.intc, copy=copy)) self.shape = shape else: #must be dense, convert to COO first, then to DIA try: arg1 = np.asarray(arg1) except: raise ValueError("unrecognized form for" \ " %s_matrix constructor" % self.format) from coo import coo_matrix A = coo_matrix(arg1, dtype=dtype).todia() self.data = A.data self.offsets = A.offsets self.shape = A.shape if dtype is not None: self.data = self.data.astype(dtype) #check format if self.offsets.ndim != 1: raise ValueError('offsets array must have rank 1') if self.data.ndim != 2: raise ValueError('data array must have rank 2') if self.data.shape[0] != len(self.offsets): raise ValueError('number of diagonals (%d) ' \ 'does not match the number of offsets (%d)' \ % (self.data.shape[0], len(self.offsets))) if len(np.unique(self.offsets)) != len(self.offsets): raise ValueError('offset array contains duplicate values')
def __init__(self, arg1, shape=None, dtype=None, copy=False, blocksize=None): _data_matrix.__init__(self) if isspmatrix(arg1): if isspmatrix_bsr(arg1) and copy: arg1 = arg1.copy() else: arg1 = arg1.tobsr(blocksize=blocksize) self._set_self(arg1) elif isinstance(arg1, tuple): if isshape(arg1): #it's a tuple of matrix dimensions (M,N) self.shape = arg1 M, N = self.shape #process blocksize if blocksize is None: blocksize = (1, 1) else: if not isshape(blocksize): raise ValueError('invalid blocksize=%s' % blocksize) blocksize = tuple(blocksize) self.data = np.zeros((0, ) + blocksize, getdtype(dtype, default=float)) self.indices = np.zeros(0, dtype=np.intc) R, C = blocksize if (M % R) != 0 or (N % C) != 0: raise ValueError, 'shape must be multiple of blocksize' self.indptr = np.zeros(M / R + 1, dtype=np.intc) elif len(arg1) == 2: # (data,(row,col)) format from coo import coo_matrix self._set_self( coo_matrix(arg1, dtype=dtype).tobsr(blocksize=blocksize)) elif len(arg1) == 3: # (data,indices,indptr) format (data, indices, indptr) = arg1 self.indices = np.array(indices, copy=copy) self.indptr = np.array(indptr, copy=copy) self.data = np.array(data, copy=copy, dtype=getdtype(dtype, data)) else: raise ValueError('unrecognized bsr_matrix constructor usage') else: #must be dense try: arg1 = np.asarray(arg1) except: raise ValueError("unrecognized form for" \ " %s_matrix constructor" % self.format) from coo import coo_matrix arg1 = coo_matrix(arg1, dtype=dtype).tobsr(blocksize=blocksize) self._set_self(arg1) if shape is not None: self.shape = shape # spmatrix will check for errors else: if self.shape is None: # shape not already set, try to infer dimensions try: M = len(self.indptr) - 1 N = self.indices.max() + 1 except: raise ValueError('unable to infer matrix dimensions') else: R, C = self.blocksize self.shape = (M * R, N * C) if self.shape is None: if shape is None: #TODO infer shape here raise ValueError('need to infer shape') else: self.shape = shape if dtype is not None: self.data = self.data.astype(dtype) self.check_format(full_check=False)
def cs_graph_components(x): """ Determine connected compoments of a graph stored as a compressed sparse row or column matrix. For speed reasons, the symmetry of the matrix x is not checked. A nonzero at index `(i, j)` means that node `i` is connected to node `j` by an edge. The number of rows/columns of the matrix thus corresponds to the number of nodes in the graph. Parameters ----------- x: ndarray-like, 2 dimensions, or sparse matrix The adjacency matrix of the graph. Only the upper triangular part is used. Returns -------- n_comp: int The number of connected components. label: ndarray (ints, 1 dimension): The label array of each connected component (-2 is used to indicate empty rows in the matrix: 0 everywhere, including diagonal). This array has the length of the number of nodes, i.e. one label for each node of the graph. Nodes having the same label belong to the same connected component. Notes ------ The matrix is assumed to be symmetric and the upper triangular part of the matrix is used. The matrix is converted to a CSR matrix unless it is already a CSR. Example ------- >>> from scipy.sparse import cs_graph_components >>> import numpy as np >>> D = np.eye(4) >>> D[0,1] = D[1,0] = 1 >>> cs_graph_components(D) (3, array([0, 0, 1, 2])) >>> from scipy.sparse import dok_matrix >>> cs_graph_components(dok_matrix(D)) (3, array([0, 0, 1, 2])) """ try: shape = x.shape except AttributeError: raise ValueError(_msg0) if not ((len(x.shape) == 2) and (x.shape[0] == x.shape[1])): raise ValueError(_msg1 % x.shape) if isspmatrix(x): x = x.tocsr() else: x = csr_matrix(x) label = np.empty((shape[0],), dtype=x.indptr.dtype) n_comp = _cs_graph_components(shape[0], x.indptr, x.indices, label) return n_comp, label
def cs_graph_components(x): """ Determine connected compoments of a graph stored as a compressed sparse row or column matrix. For speed reasons, the symmetry of the matrix x is not checked. A nonzero at index `(i, j)` means that node `i` is connected to node `j` by an edge. The number of rows/columns of the matrix thus corresponds to the number of nodes in the graph. Parameters ----------- x: ndarray-like, 2 dimensions, or sparse matrix The adjacency matrix of the graph. Only the upper triangular part is used. Returns -------- n_comp: int The number of connected components. label: ndarray (ints, 1 dimension): The label array of each connected component (-2 is used to indicate empty rows in the matrix: 0 everywhere, including diagonal). This array has the length of the number of nodes, i.e. one label for each node of the graph. Nodes having the same label belong to the same connected component. Notes ------ The matrix is assumed to be symmetric and the upper triangular part of the matrix is used. The matrix is converted to a CSR matrix unless it is already a CSR. Example ------- >>> from scipy.sparse import cs_graph_components >>> import numpy as np >>> D = np.eye(4) >>> D[0,1] = D[1,0] = 1 >>> cs_graph_components(D) (3, array([0, 0, 1, 2])) >>> from scipy.sparse import dok_matrix >>> cs_graph_components(dok_matrix(D)) (3, array([0, 0, 1, 2])) """ try: shape = x.shape except AttributeError: raise ValueError(_msg0) if not ((len(x.shape) == 2) and (x.shape[0] == x.shape[1])): raise ValueError(_msg1 % x.shape) if isspmatrix(x): x = x.tocsr() else: x = csr_matrix(x) label = np.empty((shape[0], ), dtype=x.indptr.dtype) n_comp = _cs_graph_components(shape[0], x.indptr, x.indices, label) return n_comp, label
def __init__(self, arg1, shape=None, dtype=None, copy=False): _data_matrix.__init__(self) if isinstance(arg1, tuple): if isshape(arg1): M, N = arg1 self.shape = (M, N) self.row = np.array([], dtype=np.intc) self.col = np.array([], dtype=np.intc) self.data = np.array([], getdtype(dtype, default=float)) else: try: obj, ij = arg1 except: raise TypeError('invalid input format') try: if len(ij) != 2: raise TypeError except TypeError: raise TypeError('invalid input format') self.row = np.array(ij[0], copy=copy, dtype=np.intc) self.col = np.array(ij[1], copy=copy, dtype=np.intc) self.data = np.array(obj, copy=copy) if shape is None: if len(self.row) == 0 or len(self.col) == 0: raise ValueError( 'cannot infer dimensions from zero sized index arrays' ) M = self.row.max() + 1 N = self.col.max() + 1 self.shape = (M, N) else: # Use 2 steps to ensure shape has length 2. M, N = shape self.shape = (M, N) elif arg1 is None: # Initialize an empty matrix. if not isinstance(shape, tuple) or not isintlike(shape[0]): raise TypeError('dimensions not understood') warn('coo_matrix(None, shape=(M,N)) is deprecated, ' \ 'use coo_matrix( (M,N) ) instead', DeprecationWarning) self.shape = shape self.data = np.array([], getdtype(dtype, default=float)) self.row = np.array([], dtype=np.intc) self.col = np.array([], dtype=np.intc) else: if isspmatrix(arg1): if isspmatrix_coo(arg1) and copy: self.row = arg1.row.copy() self.col = arg1.col.copy() self.data = arg1.data.copy() self.shape = arg1.shape else: coo = arg1.tocoo() self.row = coo.row self.col = coo.col self.data = coo.data self.shape = coo.shape else: #dense argument try: M = np.atleast_2d(np.asarray(arg1)) except: raise TypeError('invalid input format') if np.rank(M) != 2: raise TypeError('expected rank <= 2 array or matrix') self.shape = M.shape self.row, self.col = M.nonzero() self.data = M[self.row, self.col] if dtype is not None: self.data = self.data.astype(dtype) self._check()
def __init__(self, arg1, shape=None, dtype=None, copy=False): _data_matrix.__init__(self) if isspmatrix_dia(arg1): if copy: arg1 = arg1.copy() self.data = arg1.data self.offsets = arg1.offsets self.shape = arg1.shape elif isspmatrix(arg1): if isspmatrix_dia(arg1) and copy: A = arg1.copy() else: A = arg1.todia() self.data = A.data self.offsets = A.offsets self.shape = A.shape elif isinstance(arg1, tuple): if isshape(arg1): # It's a tuple of matrix dimensions (M, N) # create empty matrix self.shape = arg1 #spmatrix checks for errors here self.data = np.zeros( (0,0), getdtype(dtype, default=float)) self.offsets = np.zeros( (0), dtype=np.intc) else: try: # Try interpreting it as (data, offsets) data, offsets = arg1 except: raise ValueError('unrecognized form for dia_matrix constructor') else: if shape is None: raise ValueError('expected a shape argument') self.data = np.atleast_2d(np.array(arg1[0], dtype=dtype, copy=copy)) self.offsets = np.atleast_1d(np.array(arg1[1], dtype=np.intc, copy=copy)) self.shape = shape else: #must be dense, convert to COO first, then to DIA try: arg1 = np.asarray(arg1) except: raise ValueError("unrecognized form for" \ " %s_matrix constructor" % self.format) from coo import coo_matrix A = coo_matrix(arg1, dtype=dtype).todia() self.data = A.data self.offsets = A.offsets self.shape = A.shape if dtype is not None: self.data = self.data.astype(dtype) #check format if self.offsets.ndim != 1: raise ValueError('offsets array must have rank 1') if self.data.ndim != 2: raise ValueError('data array must have rank 2') if self.data.shape[0] != len(self.offsets): raise ValueError('number of diagonals (%d) ' \ 'does not match the number of offsets (%d)' \ % (self.data.shape[0], len(self.offsets))) if len(np.unique(self.offsets)) != len(self.offsets): raise ValueError('offset array contains duplicate values')
def __init__(self, arg1, shape=None, dtype=None, copy=False): _data_matrix.__init__(self) if isspmatrix(arg1): if arg1.format == self.format and copy: arg1 = arg1.copy() else: arg1 = arg1.asformat(self.format) self._set_self( arg1 ) elif isinstance(arg1, tuple): if isshape(arg1): # It's a tuple of matrix dimensions (M, N) # create empty matrix self.shape = arg1 #spmatrix checks for errors here M, N = self.shape self.data = np.zeros(0, getdtype(dtype, default=float)) self.indices = np.zeros(0, np.intc) self.indptr = np.zeros(self._swap((M,N))[0] + 1, dtype=np.intc) else: if len(arg1) == 2: # (data, ij) format from coo import coo_matrix other = self.__class__( coo_matrix(arg1, shape=shape) ) self._set_self( other ) elif len(arg1) == 3: # (data, indices, indptr) format (data, indices, indptr) = arg1 self.indices = np.array(indices, copy=copy) self.indptr = np.array(indptr, copy=copy) self.data = np.array(data, copy=copy, dtype=getdtype(dtype, data)) else: raise ValueError("unrecognized %s_matrix constructor usage" % self.format) else: #must be dense try: arg1 = np.asarray(arg1) except: raise ValueError("unrecognized %s_matrix constructor usage" % self.format) from coo import coo_matrix self._set_self( self.__class__(coo_matrix(arg1, dtype=dtype)) ) # Read matrix dimensions given, if any if shape is not None: self.shape = shape # spmatrix will check for errors else: if self.shape is None: # shape not already set, try to infer dimensions try: major_dim = len(self.indptr) - 1 minor_dim = self.indices.max() + 1 except: raise ValueError('unable to infer matrix dimensions') else: self.shape = self._swap((major_dim,minor_dim)) if dtype is not None: self.data = self.data.astype(dtype) self.check_format(full_check=False)
def __init__(self, arg1, shape=None, dtype=None, copy=False): _data_matrix.__init__(self) if isinstance(arg1, tuple): if isshape(arg1): M, N = arg1 self.shape = (M,N) self.row = np.array([], dtype=np.intc) self.col = np.array([], dtype=np.intc) self.data = np.array([], getdtype(dtype, default=float)) else: try: obj, ij = arg1 except: raise TypeError('invalid input format') try: if len(ij) != 2: raise TypeError except TypeError: raise TypeError('invalid input format') self.row = np.array(ij[0], copy=copy, dtype=np.intc) self.col = np.array(ij[1], copy=copy, dtype=np.intc) self.data = np.array( obj, copy=copy) if shape is None: if len(self.row) == 0 or len(self.col) == 0: raise ValueError('cannot infer dimensions from zero sized index arrays') M = self.row.max() + 1 N = self.col.max() + 1 self.shape = (M, N) else: # Use 2 steps to ensure shape has length 2. M, N = shape self.shape = (M, N) elif arg1 is None: # Initialize an empty matrix. if not isinstance(shape, tuple) or not isintlike(shape[0]): raise TypeError('dimensions not understood') warn('coo_matrix(None, shape=(M,N)) is deprecated, ' \ 'use coo_matrix( (M,N) ) instead', DeprecationWarning) self.shape = shape self.data = np.array([], getdtype(dtype, default=float)) self.row = np.array([], dtype=np.intc) self.col = np.array([], dtype=np.intc) else: if isspmatrix(arg1): if isspmatrix_coo(arg1) and copy: self.row = arg1.row.copy() self.col = arg1.col.copy() self.data = arg1.data.copy() self.shape = arg1.shape else: coo = arg1.tocoo() self.row = coo.row self.col = coo.col self.data = coo.data self.shape = coo.shape else: #dense argument try: M = np.atleast_2d(np.asarray(arg1)) except: raise TypeError('invalid input format') if np.rank(M) != 2: raise TypeError('expected rank <= 2 array or matrix') self.shape = M.shape self.row,self.col = (M != 0).nonzero() self.data = M[self.row,self.col] if dtype is not None: self.data = self.data.astype(dtype) self._check()
def __init__(self, arg1, shape=None, dtype=None, copy=False, blocksize=None): _data_matrix.__init__(self) if isspmatrix(arg1): if isspmatrix_bsr(arg1) and copy: arg1 = arg1.copy() else: arg1 = arg1.tobsr(blocksize=blocksize) self._set_self( arg1 ) elif isinstance(arg1,tuple): if isshape(arg1): #it's a tuple of matrix dimensions (M,N) self.shape = arg1 M,N = self.shape #process blocksize if blocksize is None: blocksize = (1,1) else: if not isshape(blocksize): raise ValueError('invalid blocksize=%s' % blocksize) blocksize = tuple(blocksize) self.data = np.zeros( (0,) + blocksize, getdtype(dtype, default=float) ) self.indices = np.zeros( 0, dtype=np.intc ) R,C = blocksize if (M % R) != 0 or (N % C) != 0: raise ValueError('shape must be multiple of blocksize') self.indptr = np.zeros(M//R + 1, dtype=np.intc ) elif len(arg1) == 2: # (data,(row,col)) format from coo import coo_matrix self._set_self( coo_matrix(arg1, dtype=dtype).tobsr(blocksize=blocksize) ) elif len(arg1) == 3: # (data,indices,indptr) format (data, indices, indptr) = arg1 self.indices = np.array(indices, copy=copy) self.indptr = np.array(indptr, copy=copy) self.data = np.array(data, copy=copy, dtype=getdtype(dtype, data)) else: raise ValueError('unrecognized bsr_matrix constructor usage') else: #must be dense try: arg1 = np.asarray(arg1) except: raise ValueError("unrecognized form for" \ " %s_matrix constructor" % self.format) from coo import coo_matrix arg1 = coo_matrix(arg1, dtype=dtype).tobsr(blocksize=blocksize) self._set_self( arg1 ) if shape is not None: self.shape = shape # spmatrix will check for errors else: if self.shape is None: # shape not already set, try to infer dimensions try: M = len(self.indptr) - 1 N = self.indices.max() + 1 except: raise ValueError('unable to infer matrix dimensions') else: R,C = self.blocksize self.shape = (M*R,N*C) if self.shape is None: if shape is None: #TODO infer shape here raise ValueError('need to infer shape') else: self.shape = shape if dtype is not None: self.data = self.data.astype(dtype) self.check_format(full_check=False)