Python scipy.sparse() Examples
The following are 30
code examples of scipy.sparse().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
scipy
, or try the search function
.
Example #1
Source File: operator.py From scarlet with MIT License | 7 votes |
def getOffsets(width, coords=None): """Get the offset and slices for a sparse band diagonal array For an operator that interacts with its neighbors we want a band diagonal matrix, where each row describes the 8 pixels that are neighbors for the reference pixel (the diagonal). Regardless of the operator, these 8 bands are always the same, so we make a utility function that returns the offsets (passed to scipy.sparse.diags). See `diagonalizeArray` for more on the slices and format of the array used to create NxN operators that act on a data vector. """ # Use the neighboring pixels by default if coords is None: coords = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] offsets = [width * y + x for y, x in coords] slices = [slice(None, s) if s < 0 else slice(s, None) for s in offsets] slicesInv = [slice(-s, None) if s < 0 else slice(None, -s) for s in offsets] return offsets, slices, slicesInv
Example #2
Source File: scipy_sparse.py From recruit with Apache License 2.0 | 6 votes |
def _sparse_series_to_coo(ss, row_levels=(0, ), column_levels=(1, ), sort_labels=False): """ Convert a SparseSeries to a scipy.sparse.coo_matrix using index levels row_levels, column_levels as the row and column labels respectively. Returns the sparse_matrix, row and column labels. """ import scipy.sparse if ss.index.nlevels < 2: raise ValueError('to_coo requires MultiIndex with nlevels > 2') if not ss.index.is_unique: raise ValueError('Duplicate index entries are not allowed in to_coo ' 'transformation.') # to keep things simple, only rely on integer indexing (not labels) row_levels = [ss.index._get_level_number(x) for x in row_levels] column_levels = [ss.index._get_level_number(x) for x in column_levels] v, i, j, rows, columns = _to_ijv(ss, row_levels=row_levels, column_levels=column_levels, sort_labels=sort_labels) sparse_matrix = scipy.sparse.coo_matrix( (v, (i, j)), shape=(len(rows), len(columns))) return sparse_matrix, rows, columns
Example #3
Source File: solve_foreground_background.py From closed-form-matting with MIT License | 6 votes |
def get_grad_operator(mask): """Returns sparse matrix computing horizontal, vertical, and two diagonal gradients.""" horizontal_left = np.ravel_multi_index(np.nonzero(mask[:, :-1] | mask[:, 1:]), mask.shape) horizontal_right = horizontal_left + 1 vertical_top = np.ravel_multi_index(np.nonzero(mask[:-1, :] | mask[1:, :]), mask.shape) vertical_bottom = vertical_top + mask.shape[1] diag_main_1 = np.ravel_multi_index(np.nonzero(mask[:-1, :-1] | mask[1:, 1:]), mask.shape) diag_main_2 = diag_main_1 + mask.shape[1] + 1 diag_sub_1 = np.ravel_multi_index(np.nonzero(mask[:-1, 1:] | mask[1:, :-1]), mask.shape) + 1 diag_sub_2 = diag_sub_1 + mask.shape[1] - 1 indices = np.stack(( np.concatenate((horizontal_left, vertical_top, diag_main_1, diag_sub_1)), np.concatenate((horizontal_right, vertical_bottom, diag_main_2, diag_sub_2)) ), axis=-1) return scipy.sparse.coo_matrix( (np.tile([-1, 1], len(indices)), (np.arange(indices.size) // 2, indices.flatten())), shape=(len(indices), mask.size))
Example #4
Source File: test_special_execute.py From mars with Apache License 2.0 | 6 votes |
def testEntrExecution(self): raw = np.random.rand(10, 8, 6) a = tensor(raw, chunk_size=3) r = entr(a) result = self.executor.execute_tensor(r, concat=True)[0] expected = scipy_entr(raw) np.testing.assert_array_equal(result, expected) # test sparse raw = sps.csr_matrix(np.array([0, 1.0, 1.01, np.nan])) a = tensor(raw, chunk_size=3) r = entr(a) result = self.executor.execute_tensor(r, concat=True)[0] data = scipy_entr(raw.data) expected = sps.csr_matrix((data, raw.indices, raw.indptr), raw.shape) np.testing.assert_array_equal(result.toarray(), expected.toarray())
Example #5
Source File: test_special_execute.py From mars with Apache License 2.0 | 6 votes |
def testRelEntrExecution(self): raw1 = np.random.rand(4, 3, 2) raw2 = np.random.rand(4, 3, 2) a = tensor(raw1, chunk_size=3) b = tensor(raw2, chunk_size=3) r = rel_entr(a, b) result = self.executor.execute_tensor(r, concat=True)[0] expected = scipy_rel_entr(raw1, raw2) np.testing.assert_array_equal(result, expected) # test sparse raw1 = sps.csr_matrix(np.array([0, 1.0, 1.01, np.nan] * 3).reshape(4, 3)) a = tensor(raw1, chunk_size=3) raw2 = np.random.rand(4, 3) b = tensor(raw2, chunk_size=3) r = rel_entr(a, b) result = self.executor.execute_tensor(r, concat=True)[0] expected = scipy_rel_entr(raw1.toarray(), raw2) np.testing.assert_array_equal(result.toarray(), expected)
Example #6
Source File: opt.py From D-VAE with MIT License | 6 votes |
def make_node(self, x, y): x, y = sparse.as_sparse_variable(x), tensor.as_tensor_variable(y) out_dtype = scalar.upcast(x.type.dtype, y.type.dtype) if self.inplace: assert out_dtype == y.dtype indices, indptr, data = csm_indices(x), csm_indptr(x), csm_data(x) # We either use CSC or CSR depending on the format of input assert self.format == x.type.format # The magic number two here arises because L{scipy.sparse} # objects must be matrices (have dimension 2) assert y.type.ndim == 2 out = tensor.TensorType(dtype=out_dtype, broadcastable=y.type.broadcastable)() return gof.Apply(self, [data, indices, indptr, y], [out])
Example #7
Source File: test_special_execute.py From mars with Apache License 2.0 | 6 votes |
def testErfExecution(self): raw = np.random.rand(10, 8, 6) a = tensor(raw, chunk_size=3) r = erf(a) result = self.executor.execute_tensor(r, concat=True)[0] expected = scipy_erf(raw) np.testing.assert_array_equal(result, expected) # test sparse raw = sps.csr_matrix(np.array([0, 1.0, 1.01, np.nan])) a = tensor(raw, chunk_size=3) r = erf(a) result = self.executor.execute_tensor(r, concat=True)[0] data = scipy_erf(raw.data) expected = sps.csr_matrix((data, raw.indices, raw.indptr), raw.shape) np.testing.assert_array_equal(result.toarray(), expected.toarray())
Example #8
Source File: convert.py From pytorch_geometric with MIT License | 6 votes |
def to_scipy_sparse_matrix(edge_index, edge_attr=None, num_nodes=None): r"""Converts a graph given by edge indices and edge attributes to a scipy sparse matrix. Args: edge_index (LongTensor): The edge indices. edge_attr (Tensor, optional): Edge weights or multi-dimensional edge features. (default: :obj:`None`) num_nodes (int, optional): The number of nodes, *i.e.* :obj:`max_val + 1` of :attr:`index`. (default: :obj:`None`) """ row, col = edge_index.cpu() if edge_attr is None: edge_attr = torch.ones(row.size(0)) else: edge_attr = edge_attr.view(-1).cpu() assert edge_attr.size(0) == row.size(0) N = maybe_num_nodes(edge_index, num_nodes) out = scipy.sparse.coo_matrix((edge_attr, (row, col)), (N, N)) return out
Example #9
Source File: covariancematrix.py From typhon with MIT License | 6 votes |
def to_dense(self): """Conversion to dense representation. Converts the covariance matrix to a 2-dimensional numpy.ndarray. Returns: The covariance matrix as dense matrix. """ m = max([b.row_start + b.matrix.shape[0] for b in self.blocks]) n = max([b.column_start + b.matrix.shape[1] for b in self.blocks]) mat = np.zeros((m, n)) for b in self.blocks: m0 = b.row_start n0 = b.column_start dm = b.matrix.shape[0] dn = b.matrix.shape[1] if sp.sparse.issparse(b.matrix): mat[m0 : m0 + dm, n0 : n0 + dn] = b.matrix.toarray() else: mat[m0 : m0 + dm, n0 : n0 + dn] = b.matrix return mat
Example #10
Source File: mio4.py From lambda-packs with MIT License | 6 votes |
def read_full_array(self, hdr): ''' Full (rather than sparse) matrix getter Read matrix (array) can be real or complex Parameters ---------- hdr : ``VarHeader4`` instance Returns ------- arr : ndarray complex array if ``hdr.is_complex`` is True, otherwise a real numeric array ''' if hdr.is_complex: # avoid array copy to save memory res = self.read_sub_array(hdr, copy=False) res_j = self.read_sub_array(hdr, copy=False) return res + (res_j * 1j) return self.read_sub_array(hdr)
Example #11
Source File: covariancematrix.py From typhon with MIT License | 6 votes |
def __init__(self, i, j, row_start, column_start, inverse, matrix): """ Parameters: i(int): The row-block index of the covariance matrix block. j(int): The column-block index of the covariance matrix block. row_start(int): Row index of the left- and uppermost element in in the block. column_start(int): Column index of the left- and uppermost element in the block inverse(bool): Flag indicating whether the block is part of the inverse of the covariance matrix or not. matrix(np.ndarray or sp.sparse): The matrix of which the block consists. """ self._i = i self._j = j self._row_start = row_start self._column_start = column_start self._inverse = inverse self._matrix = matrix # # Read-only properties #
Example #12
Source File: coarsening.py From dgl with Apache License 2.0 | 6 votes |
def laplacian(W, normalized=True): """Return graph Laplacian""" # Degree matrix. d = W.sum(axis=0) # Laplacian matrix. if not normalized: D = scipy.sparse.diags(d.A.squeeze(), 0) L = D - W else: d += np.spacing(np.array(0, W.dtype)) d = 1 / np.sqrt(d) D = scipy.sparse.diags(d.A.squeeze(), 0) I = scipy.sparse.identity(d.size, dtype=W.dtype) L = I - D * W * D assert np.abs(L - L.T).mean() < 1e-9 assert type(L) is scipy.sparse.csr.csr_matrix return L
Example #13
Source File: mio4.py From lambda-packs with MIT License | 6 votes |
def array_from_header(self, hdr, process=True): mclass = hdr.mclass if mclass == mxFULL_CLASS: arr = self.read_full_array(hdr) elif mclass == mxCHAR_CLASS: arr = self.read_char_array(hdr) if process and self.chars_as_strings: arr = chars_to_strings(arr) elif mclass == mxSPARSE_CLASS: # no current processing (below) makes sense for sparse return self.read_sparse_array(hdr) else: raise TypeError('No reader for class code %s' % mclass) if process and self.squeeze_me: return squeeze_element(arr) return arr
Example #14
Source File: opt.py From D-VAE with MIT License | 6 votes |
def local_structured_dot(node): if node.op == sparse._structured_dot: a, b = node.inputs if a.type.format == 'csc': a_val, a_ind, a_ptr, a_shape = csm_properties(a) a_nsparse = a_shape[0] return [sd_csc(a_val, a_ind, a_ptr, a_nsparse, b)] if a.type.format == 'csr': a_val, a_ind, a_ptr, a_shape = csm_properties(a) return [sd_csr(a_val, a_ind, a_ptr, b)] return False # Commented out because # a) it is only slightly faster than scipy these days, and sometimes a little # slower, and # b) the resulting graphs make it very difficult for an op to do size checking # on the matrices involved. dimension mismatches are hard to detect sensibly. # register_specialize(local_structured_dot)
Example #15
Source File: type.py From D-VAE with MIT License | 6 votes |
def filter(self, value, strict=False, allow_downcast=None): if isinstance(value, self.format_cls[self.format])\ and value.dtype == self.dtype: return value if strict: raise TypeError("%s is not sparse, or not the right dtype (is %s, " "expected %s)" % (value, value.dtype, self.dtype)) # The input format could be converted here if allow_downcast: sp = self.format_cls[self.format](value, dtype=self.dtype) else: sp = self.format_cls[self.format](value) if str(sp.dtype) != self.dtype: raise NotImplementedError("Expected %s dtype but got %s" % (self.dtype, str(sp.dtype))) if sp.format != self.format: raise NotImplementedError() return sp
Example #16
Source File: nonlin.py From lambda-packs with MIT License | 6 votes |
def setup(self, x, f, func): Jacobian.setup(self, x, f, func) self.x0 = x self.f0 = f self.op = scipy.sparse.linalg.aslinearoperator(self) if self.rdiff is None: self.rdiff = np.finfo(x.dtype).eps ** (1./2) self._update_diff_step() # Setup also the preconditioner, if possible if self.preconditioner is not None: if hasattr(self.preconditioner, 'setup'): self.preconditioner.setup(x, f, func) #------------------------------------------------------------------------------ # Wrapper functions #------------------------------------------------------------------------------
Example #17
Source File: nao.py From pyscf with Apache License 2.0 | 6 votes |
def comp_aos_csr(self, coords, tol=1e-8, ram=160e6): """ Compute the atomic orbitals for a given set of (Cartesian) coordinates. The sparse format CSR is used for output and the computation is organized block-wise. Thence, larger molecules can be tackled right away coords :: set of Cartesian coordinates tol :: tolerance for dropping the values ram :: size of the allowed block (in bytes) Returns co2v :: CSR matrix of shape (coordinate, atomic orbital) """ from pyscf.nao.m_aos_libnao import aos_libnao from pyscf import lib from scipy.sparse import csr_matrix if not self.init_sv_libnao_orbs : raise RuntimeError('not self.init_sv_libnao') assert coords.shape[-1] == 3 nc,no = len(coords), self.norbs bsize = int(min(max(ram / (no*8.0), 1), nc)) co2v = csr_matrix((nc,no)) for s,f in lib.prange(0,nc,bsize): ca2o = aos_libnao(coords[s:f], no) # compute values of atomic orbitals ab = np.where(abs(ca2o)>tol) co2v += csr_matrix((ca2o[ab].reshape(-1), (ab[0]+s, ab[1])), shape=(nc,no)) return co2v
Example #18
Source File: test_special_execute.py From mars with Apache License 2.0 | 6 votes |
def testGammalnExecution(self): raw = np.random.rand(10, 8, 6) a = tensor(raw, chunk_size=3) r = gammaln(a) result = self.executor.execute_tensor(r, concat=True)[0] expected = scipy_gammaln(raw) np.testing.assert_array_equal(result, expected) # test sparse raw = sps.csr_matrix(np.array([0, 1.0, 1.01, np.nan])) a = tensor(raw, chunk_size=3) r = gammaln(a) result = self.executor.execute_tensor(r, concat=True)[0] data = scipy_gammaln(raw.data) expected = sps.csr_matrix((data, raw.indices, raw.indptr), raw.shape) np.testing.assert_array_equal(result.toarray(), expected.toarray())
Example #19
Source File: mio4.py From lambda-packs with MIT License | 6 votes |
def write_sparse(self, arr, name): ''' Sparse matrices are 2D See docstring for VarReader4.read_sparse_array ''' A = arr.tocoo() # convert to sparse COO format (ijv) imagf = A.dtype.kind == 'c' ijv = np.zeros((A.nnz + 1, 3+imagf), dtype='f8') ijv[:-1,0] = A.row ijv[:-1,1] = A.col ijv[:-1,0:2] += 1 # 1 based indexing if imagf: ijv[:-1,2] = A.data.real ijv[:-1,3] = A.data.imag else: ijv[:-1,2] = A.data ijv[-1,0:2] = A.shape self.write_header( name, ijv.shape, P=miDOUBLE, T=mxSPARSE_CLASS) self.write_bytes(ijv)
Example #20
Source File: opt.py From D-VAE with MIT License | 5 votes |
def local_structured_add_s_v(node): if node.op == sparse.structured_add_s_v: x, y = node.inputs x_is_sparse_variable = _is_sparse_variable(x) # y_is_sparse_variable = _is_sparse_variable(y) if x_is_sparse_variable: svar = x dvar = y else: svar = y dvar = x if dvar.type.ndim != 1: return False elif svar.type.format == 'csr': CSx = sparse.CSR structured_add_s_v_csx = structured_add_s_v_csr else: return False s_val, s_ind, s_ptr, s_shape = sparse.csm_properties(svar) c_data = structured_add_s_v_csx(s_val, s_ind, s_ptr, dvar) return [CSx(c_data, s_ind, s_ptr, s_shape)] return False
Example #21
Source File: mio4.py From lambda-packs with MIT License | 5 votes |
def write(self, arr, name): ''' Write matrix `arr`, with name `name` Parameters ---------- arr : array_like array to write name : str name in matlab workspace ''' # we need to catch sparse first, because np.asarray returns an # an object array for scipy.sparse if scipy.sparse.issparse(arr): self.write_sparse(arr, name) return arr = np.asarray(arr) dt = arr.dtype if not dt.isnative: arr = arr.astype(dt.newbyteorder('=')) dtt = dt.type if dtt is np.object_: raise TypeError('Cannot save object arrays in Mat4') elif dtt is np.void: raise TypeError('Cannot save void type arrays') elif dtt in (np.unicode_, np.string_): self.write_char(arr, name) return self.write_numeric(arr, name)
Example #22
Source File: opt.py From D-VAE with MIT License | 5 votes |
def local_mul_s_v(node): if node.op == sparse.mul_s_v: x, y = node.inputs x_is_sparse_variable = _is_sparse_variable(x) if x_is_sparse_variable: svar = x dvar = y else: svar = y dvar = x if dvar.type.ndim != 1: return False elif svar.type.format == 'csr': CSx = sparse.CSR mul_s_v_csx = mul_s_v_csr else: return False s_val, s_ind, s_ptr, s_shape = sparse.csm_properties(svar) c_data = mul_s_v_csx(s_val, s_ind, s_ptr, dvar) return [CSx(c_data, s_ind, s_ptr, s_shape)] return False
Example #23
Source File: matfuncs.py From lambda-packs with MIT License | 5 votes |
def _smart_matrix_product(A, B, alpha=None, structure=None): """ A matrix product that knows about sparse and structured matrices. Parameters ---------- A : 2d ndarray First matrix. B : 2d ndarray Second matrix. alpha : float The matrix product will be scaled by this constant. structure : str, optional A string describing the structure of both matrices `A` and `B`. Only `upper_triangular` is currently supported. Returns ------- M : 2d ndarray Matrix product of A and B. """ if len(A.shape) != 2: raise ValueError('expected A to be a rectangular matrix') if len(B.shape) != 2: raise ValueError('expected B to be a rectangular matrix') f = None if structure == UPPER_TRIANGULAR: if not isspmatrix(A) and not isspmatrix(B): f, = scipy.linalg.get_blas_funcs(('trmm',), (A, B)) if f is not None: if alpha is None: alpha = 1. out = f(alpha, A, B) else: if alpha is None: out = A.dot(B) else: out = alpha * A.dot(B) return out
Example #24
Source File: mio4.py From lambda-packs with MIT License | 5 votes |
def read_sparse_array(self, hdr): ''' Read and return sparse matrix type Parameters ---------- hdr : ``VarHeader4`` instance Returns ------- arr : ``scipy.sparse.coo_matrix`` with dtype ``float`` and shape read from the sparse matrix data Notes ----- MATLAB 4 real sparse arrays are saved in a N+1 by 3 array format, where N is the number of non-zero values. Column 1 values [0:N] are the (1-based) row indices of the each non-zero value, column 2 [0:N] are the column indices, column 3 [0:N] are the (real) values. The last values [-1,0:2] of the rows, column indices are shape[0] and shape[1] respectively of the output matrix. The last value for the values column is a padding 0. mrows and ncols values from the header give the shape of the stored matrix, here [N+1, 3]. Complex data is saved as a 4 column matrix, where the fourth column contains the imaginary component; the last value is again 0. Complex sparse data do *not* have the header ``imagf`` field set to True; the fact that the data are complex is only detectable because there are 4 storage columns ''' res = self.read_sub_array(hdr) tmp = res[:-1,:] dims = res[-1,0:2] I = np.ascontiguousarray(tmp[:,0],dtype='intc') # fixes byte order also J = np.ascontiguousarray(tmp[:,1],dtype='intc') I -= 1 # for 1-based indexing J -= 1 if res.shape[1] == 3: V = np.ascontiguousarray(tmp[:,2],dtype='float') else: V = np.ascontiguousarray(tmp[:,2],dtype='complex') V.imag = tmp[:,3] return scipy.sparse.coo_matrix((V,(I,J)), dims)
Example #25
Source File: mio5.py From lambda-packs with MIT License | 5 votes |
def write(self, arr): ''' Write `arr` to stream at top and sub levels Parameters ---------- arr : array_like array-like object to create writer for ''' # store position, so we can update the matrix tag mat_tag_pos = self.file_stream.tell() # First check if these are sparse if scipy.sparse.issparse(arr): self.write_sparse(arr) self.update_matrix_tag(mat_tag_pos) return # Try to convert things that aren't arrays narr = to_writeable(arr) if narr is None: raise TypeError('Could not convert %s (type %s) to array' % (arr, type(arr))) if isinstance(narr, MatlabObject): self.write_object(narr) elif isinstance(narr, MatlabFunction): raise MatWriteError('Cannot write matlab functions') elif narr is EmptyStructMarker: # empty struct array self.write_empty_struct() elif narr.dtype.fields: # struct array self.write_struct(narr) elif narr.dtype.hasobject: # cell array self.write_cells(narr) elif narr.dtype.kind in ('U', 'S'): if self.unicode_strings: codec = 'UTF8' else: codec = 'ascii' self.write_char(narr, codec) else: self.write_numeric(narr) self.update_matrix_tag(mat_tag_pos)
Example #26
Source File: nonlin.py From lambda-packs with MIT License | 5 votes |
def __init__(self, rdiff=None, method='lgmres', inner_maxiter=20, inner_M=None, outer_k=10, **kw): self.preconditioner = inner_M self.rdiff = rdiff self.method = dict( bicgstab=scipy.sparse.linalg.bicgstab, gmres=scipy.sparse.linalg.gmres, lgmres=scipy.sparse.linalg.lgmres, cgs=scipy.sparse.linalg.cgs, minres=scipy.sparse.linalg.minres, ).get(method, method) self.method_kw = dict(maxiter=inner_maxiter, M=self.preconditioner) if self.method is scipy.sparse.linalg.gmres: # Replace GMRES's outer iteration with Newton steps self.method_kw['restrt'] = inner_maxiter self.method_kw['maxiter'] = 1 elif self.method is scipy.sparse.linalg.lgmres: self.method_kw['outer_k'] = outer_k # Replace LGMRES's outer iteration with Newton steps self.method_kw['maxiter'] = 1 # Carry LGMRES's `outer_v` vectors across nonlinear iterations self.method_kw.setdefault('outer_v', []) self.method_kw.setdefault('prepend_outer_v', True) # But don't carry the corresponding Jacobian*v products, in case # the Jacobian changes a lot in the nonlinear step # # XXX: some trust-region inspired ideas might be more efficient... # See eg. Brown & Saad. But needs to be implemented separately # since it's not an inexact Newton method. self.method_kw.setdefault('store_outer_Av', False) for key, value in kw.items(): if not key.startswith('inner_'): raise ValueError("Unknown parameter %s" % key) self.method_kw[key[6:]] = value
Example #27
Source File: matfuncs.py From lambda-packs with MIT License | 5 votes |
def __init__(self, A, structure=None, use_exact_onenorm=False): """ Initialize the object. Parameters ---------- A : a dense or sparse square numpy matrix or ndarray The matrix to be exponentiated. structure : str, optional A string describing the structure of matrix `A`. Only `upper_triangular` is currently supported. use_exact_onenorm : bool, optional If True then only the exact one-norm of matrix powers and products will be used. Otherwise, the one-norm of powers and products may initially be estimated. """ self.A = A self._A2 = None self._A4 = None self._A6 = None self._A8 = None self._A10 = None self._d4_exact = None self._d6_exact = None self._d8_exact = None self._d10_exact = None self._d4_approx = None self._d6_approx = None self._d8_approx = None self._d10_approx = None self.ident = _ident_like(A) self.structure = structure self.use_exact_onenorm = use_exact_onenorm
Example #28
Source File: matfuncs.py From lambda-packs with MIT License | 5 votes |
def _onenormest_product(operator_seq, t=2, itmax=5, compute_v=False, compute_w=False, structure=None): """ Efficiently estimate the 1-norm of the matrix product of the args. Parameters ---------- operator_seq : linear operator sequence Matrices whose 1-norm of product is to be computed. t : int, optional A positive parameter controlling the tradeoff between accuracy versus time and memory usage. Larger values take longer and use more memory but give more accurate output. itmax : int, optional Use at most this many iterations. compute_v : bool, optional Request a norm-maximizing linear operator input vector if True. compute_w : bool, optional Request a norm-maximizing linear operator output vector if True. structure : str, optional A string describing the structure of all operators. Only `upper_triangular` is currently supported. Returns ------- est : float An underestimate of the 1-norm of the sparse matrix. v : ndarray, optional The vector such that ||Av||_1 == est*||v||_1. It can be thought of as an input to the linear operator that gives an output with particularly large norm. w : ndarray, optional The vector Av which has relatively large 1-norm. It can be thought of as an output of the linear operator that is relatively large in norm compared to the input. """ return scipy.sparse.linalg.onenormest( ProductOperator(*operator_seq, structure=structure))
Example #29
Source File: matfuncs.py From lambda-packs with MIT License | 5 votes |
def _onenormest_matrix_power(A, p, t=2, itmax=5, compute_v=False, compute_w=False, structure=None): """ Efficiently estimate the 1-norm of A^p. Parameters ---------- A : ndarray Matrix whose 1-norm of a power is to be computed. p : int Non-negative integer power. t : int, optional A positive parameter controlling the tradeoff between accuracy versus time and memory usage. Larger values take longer and use more memory but give more accurate output. itmax : int, optional Use at most this many iterations. compute_v : bool, optional Request a norm-maximizing linear operator input vector if True. compute_w : bool, optional Request a norm-maximizing linear operator output vector if True. Returns ------- est : float An underestimate of the 1-norm of the sparse matrix. v : ndarray, optional The vector such that ||Av||_1 == est*||v||_1. It can be thought of as an input to the linear operator that gives an output with particularly large norm. w : ndarray, optional The vector Av which has relatively large 1-norm. It can be thought of as an output of the linear operator that is relatively large in norm compared to the input. """ return scipy.sparse.linalg.onenormest( MatrixPowerOperator(A, p, structure=structure))
Example #30
Source File: graphTools.py From graph-neural-networks with GNU General Public License v3.0 | 5 votes |
def perm_adjacency(A, indices): # Function written by M. Defferrard, taken verbatim, from # https://github.com/mdeff/cnn_graph/blob/master/lib/coarsening.py#L242 """ Permute adjacency matrix, i.e. exchange node ids, so that binary unions form the clustering tree. """ if indices is None: return A M, M = A.shape Mnew = len(indices) assert Mnew >= M A = A.tocoo() # Add Mnew - M isolated vertices. if Mnew > M: rows = scipy.sparse.coo_matrix((Mnew-M, M), dtype=np.float32) cols = scipy.sparse.coo_matrix((Mnew, Mnew-M), dtype=np.float32) A = scipy.sparse.vstack([A, rows]) A = scipy.sparse.hstack([A, cols]) # Permute the rows and the columns. perm = np.argsort(indices) A.row = np.array(perm)[A.row] A.col = np.array(perm)[A.col] # assert np.abs(A - A.T).mean() < 1e-9 assert type(A) is scipy.sparse.coo.coo_matrix return A