本文整理匯總了Python中scipy.sparse方法的典型用法代碼示例。如果您正苦於以下問題:Python scipy.sparse方法的具體用法?Python scipy.sparse怎麽用?Python scipy.sparse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類scipy
的用法示例。
在下文中一共展示了scipy.sparse方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: getOffsets
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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
示例2: comp_aos_csr
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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
示例3: _sparse_series_to_coo
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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
示例4: __init__
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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
#
示例5: to_dense
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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
示例6: to_scipy_sparse_matrix
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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
示例7: get_grad_operator
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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))
示例8: testGammalnExecution
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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())
示例9: testErfExecution
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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())
示例10: testEntrExecution
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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())
示例11: testRelEntrExecution
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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)
示例12: laplacian
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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
示例13: setup
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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
#------------------------------------------------------------------------------
示例14: array_from_header
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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
示例15: read_full_array
# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import sparse [as 別名]
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)