本文整理汇总了Python中scipy.sparse.kron方法的典型用法代码示例。如果您正苦于以下问题:Python sparse.kron方法的具体用法?Python sparse.kron怎么用?Python sparse.kron使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.sparse
的用法示例。
在下文中一共展示了sparse.kron方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: whiten
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def whiten(self, X):
"""
SUR whiten method.
Parameters
-----------
X : list of arrays
Data to be whitened.
Returns
-------
If X is the exogenous RHS of the system.
``np.dot(np.kron(cholsigmainv,np.eye(M)),np.diag(X))``
If X is the endogenous LHS of the system.
"""
nobs = self.nobs
if X is self.endog: # definitely not a robust check
return np.dot(np.kron(self.cholsigmainv,np.eye(nobs)),
X.reshape(-1,1))
elif X is self.sp_exog:
return (sparse.kron(self.cholsigmainv,
sparse.eye(nobs,nobs))*X).toarray()#*=dot until cast to array
示例2: test_diagonal
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def test_diagonal(self):
# Does the matrix's .diagonal() method work?
mats = []
mats.append([[1,0,2]])
mats.append([[1],[0],[2]])
mats.append([[0,1],[0,2],[0,3]])
mats.append([[0,0,1],[0,0,2],[0,3,0]])
mats.append(kron(mats[0],[[1,2]]))
mats.append(kron(mats[0],[[1],[2]]))
mats.append(kron(mats[1],[[1,2],[3,4]]))
mats.append(kron(mats[2],[[1,2],[3,4]]))
mats.append(kron(mats[3],[[1,2],[3,4]]))
mats.append(kron(mats[3],[[1,2,3,4]]))
for m in mats:
assert_equal(self.spmatrix(m).diagonal(),diag(m))
示例3: test_sparse_format_conversions
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def test_sparse_format_conversions(self):
A = sparse.kron([[1,0,2],[0,3,4],[5,0,0]], [[1,2],[0,3]])
D = A.todense()
A = self.spmatrix(A)
for format in ['bsr','coo','csc','csr','dia','dok','lil']:
a = A.asformat(format)
assert_equal(a.format,format)
assert_array_equal(a.todense(), D)
b = self.spmatrix(D+3j).asformat(format)
assert_equal(b.format,format)
assert_array_equal(b.todense(), D+3j)
c = eval(format + '_matrix')(A)
assert_equal(c.format,format)
assert_array_equal(c.todense(), D)
示例4: test_constructor1
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def test_constructor1(self):
# check native BSR format constructor
indptr = array([0,2,2,4])
indices = array([0,2,2,3])
data = zeros((4,2,3))
data[0] = array([[0, 1, 2],
[3, 0, 5]])
data[1] = array([[0, 2, 4],
[6, 0, 10]])
data[2] = array([[0, 4, 8],
[12, 0, 20]])
data[3] = array([[0, 5, 10],
[15, 0, 25]])
A = kron([[1,0,2,0],[0,0,0,0],[0,0,4,5]], [[0,1,2],[3,0,5]])
Asp = bsr_matrix((data,indices,indptr),shape=(6,12))
assert_equal(Asp.todense(),A)
# infer shape from arrays
Asp = bsr_matrix((data,indices,indptr))
assert_equal(Asp.todense(),A)
示例5: get_measurements
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def get_measurements(model, domain_shape):
# model is a set of contingency tables to calculate
# each contingency table is a list of [(attribute, size)]
M = []
for table in model:
Q = [np.ones((1,size)) for size in domain_shape]
for attribute, size in table:
full_size = domain_shape[attribute]
I = sparse.identity(size)
if size != full_size:
P = PrivBayesSelect.domain_transform(size, full_size)
Q[attribute] = I * P
elif size == full_size:
Q[attribute] = I
else:
print('bug here')
M.append(reduce(sparse.kron, Q))
return sparse.vstack(M)
示例6: _zeropi_operator_in_product_basis
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def _zeropi_operator_in_product_basis(self, zeropi_operator, zeropi_evecs=None):
"""Helper method that converts a zeropi operator into one in the product basis.
Returns
-------
scipy.sparse.csc_matrix
operator written in the product basis
"""
zeropi_dim = self.zeropi_cutoff
zeta_dim = self.zeta_cutoff
if zeropi_evecs is None:
_, zeropi_evecs = self._zeropi.eigensys(evals_count=zeropi_dim)
op_eigen_basis = sparse.dia_matrix((zeropi_dim, zeropi_dim),
dtype=np.complex_) # is this guaranteed to be zero?
op_zeropi = spec_utils.get_matrixelement_table(zeropi_operator, zeropi_evecs)
for n in range(zeropi_dim):
for m in range(zeropi_dim):
op_eigen_basis += op_zeropi[n, m] * op.hubbard_sparse(n, m, zeropi_dim)
return sparse.kron(op_eigen_basis, sparse.identity(zeta_dim, format='csc', dtype=np.complex_), format='csc')
示例7: sparse_kinetic_mat
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def sparse_kinetic_mat(self):
"""
Kinetic energy portion of the Hamiltonian.
TODO: update this method to use single-variable operator methods
Returns
-------
scipy.sparse.csc_matrix
matrix representing the kinetic energy operator
"""
pt_count = self.grid.pt_count
dim_theta = 2 * self.ncut + 1
identity_phi = sparse.identity(pt_count, format='csc', dtype=np.complex_)
identity_theta = sparse.identity(dim_theta, format='csc', dtype=np.complex_)
kinetic_matrix_phi = self.grid.second_derivative_matrix(prefactor=-2.0 * self.ECJ)
diag_elements = 2.0 * self.ECS * np.square(np.arange(-self.ncut + self.ng, self.ncut + 1 + self.ng))
kinetic_matrix_theta = sparse.dia_matrix((diag_elements, [0]), shape=(dim_theta, dim_theta)).tocsc()
kinetic_matrix = (sparse.kron(kinetic_matrix_phi, identity_theta, format='csc')
+ sparse.kron(identity_phi, kinetic_matrix_theta, format='csc'))
kinetic_matrix -= 2.0 * self.ECS * self.dCJ * self.i_d_dphi_operator() * self.n_theta_operator()
return kinetic_matrix
示例8: sparse_d_potential_d_flux_mat
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def sparse_d_potential_d_flux_mat(self):
r"""Calculates a of the potential energy w.r.t flux, at the current value of flux,
as stored in the object.
The flux is assumed to be given in the units of the ratio \Phi_{ext}/\Phi_0.
So if \frac{\partial U}{ \partial \Phi_{\rm ext}}, is needed, the expression returned
by this function, needs to be multiplied by 1/\Phi_0.
Returns
-------
scipy.sparse.csc_matrix
matrix representing the derivative of the potential energy
"""
op_1 = sparse.kron(self._sin_phi_operator(x=- 2.0 * np.pi * self.flux / 2.0),
self._cos_theta_operator(), format='csc')
op_2 = sparse.kron(self._cos_phi_operator(x=- 2.0 * np.pi * self.flux / 2.0),
self._sin_theta_operator(), format='csc')
return - 2.0 * np.pi * self.EJ * op_1 - np.pi * self.EJ * self.dEJ * op_2
示例9: test_diagonal
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def test_diagonal(self):
# Does the matrix's .diagonal() method work?
mats = []
mats.append([[1,0,2]])
mats.append([[1],[0],[2]])
mats.append([[0,1],[0,2],[0,3]])
mats.append([[0,0,1],[0,0,2],[0,3,0]])
mats.append(kron(mats[0],[[1,2]]))
mats.append(kron(mats[0],[[1],[2]]))
mats.append(kron(mats[1],[[1,2],[3,4]]))
mats.append(kron(mats[2],[[1,2],[3,4]]))
mats.append(kron(mats[3],[[1,2],[3,4]]))
mats.append(kron(mats[3],[[1,2,3,4]]))
for m in mats:
rows, cols = array(m).shape
sparse_mat = self.spmatrix(m)
for k in range(-rows + 1, cols):
assert_equal(sparse_mat.diagonal(k=k), diag(m, k=k))
assert_raises(ValueError, sparse_mat.diagonal, -rows)
assert_raises(ValueError, sparse_mat.diagonal, cols)
# Test all-zero matrix.
assert_equal(self.spmatrix((40, 16130)).diagonal(), np.zeros(40))
示例10: test_constructor2
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def test_constructor2(self):
# construct from dense
# test zero mats
for shape in [(1,1), (5,1), (1,10), (10,4), (3,7), (2,1)]:
A = zeros(shape)
assert_equal(bsr_matrix(A).todense(),A)
A = zeros((4,6))
assert_equal(bsr_matrix(A,blocksize=(2,2)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(2,3)).todense(),A)
A = kron([[1,0,2,0],[0,0,0,0],[0,0,4,5]], [[0,1,2],[3,0,5]])
assert_equal(bsr_matrix(A).todense(),A)
assert_equal(bsr_matrix(A,shape=(6,12)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(1,1)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(2,3)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(2,6)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(2,12)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(3,12)).todense(),A)
assert_equal(bsr_matrix(A,blocksize=(6,12)).todense(),A)
A = kron([[1,0,2,0],[0,1,0,0],[0,0,0,0]], [[0,1,2],[3,0,5]])
assert_equal(bsr_matrix(A,blocksize=(2,3)).todense(),A)
示例11: sparse_cH
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def sparse_cH(terms, ldim=2):
"""Construct a sparse cyclic nearest-neighbour Hamiltonian
:param terms: List of nearst-neighbour terms (square array or MPO,
see return value of :func:`cXY_local_terms`)
:param ldim: Local dimension
:returns: The Hamiltonian as sparse matrix
"""
H = 0
N = len(terms)
for pos, term in enumerate(terms[:-1]):
if hasattr(term, 'lt'):
# Convert MPO to regular matrix
term = term.to_array_global().reshape((ldim**2, ldim**2))
left = sp.eye(ldim**pos)
right = sp.eye(ldim**(N - pos - 2))
H += sp.kron(left, sp.kron(term, right))
# The last term acts on the first and last site.
cyc = terms[-1]
middle = sp.eye(ldim**pos)
for i in range(cyc.ranks[0]):
H += sp.kron(cyc.lt[0][0, ..., i], sp.kron(middle, cyc.lt[1][i, ..., 0]))
return H
示例12: test_kron
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def test_kron(a_ndim, b_ndim):
a_shape = (2, 3, 4)[:a_ndim]
b_shape = (5, 6, 7)[:b_ndim]
sa = sparse.random(a_shape, density=0.5)
a = sa.todense()
sb = sparse.random(b_shape, density=0.5)
b = sb.todense()
sol = np.kron(a, b)
assert_eq(sparse.kron(sa, sb), sol)
assert_eq(sparse.kron(sa, b), sol)
assert_eq(sparse.kron(a, sb), sol)
with pytest.raises(ValueError):
assert_eq(sparse.kron(a, b), sol)
示例13: test_kron_spmatrix
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def test_kron_spmatrix(a_spmatrix, b_spmatrix):
sa = sparse.random((3, 4), density=0.5)
a = sa.todense()
sb = sparse.random((5, 6), density=0.5)
b = sb.todense()
if a_spmatrix:
sa = sa.tocsr()
if b_spmatrix:
sb = sb.tocsr()
sol = np.kron(a, b)
assert_eq(sparse.kron(sa, sb), sol)
assert_eq(sparse.kron(sa, b), sol)
assert_eq(sparse.kron(a, sb), sol)
with pytest.raises(ValueError):
assert_eq(sparse.kron(a, b), sol)
示例14: get2DMatrix
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def get2DMatrix(N, h, bc_hor, bc_ver, order):
assert np.size(N) == 2, 'N needs to be an array with two entries: N[0]=Nx and N[1]=Nz'
assert np.size(h) == 2, 'h needs to be an array with two entries: h[0]=dx and h[1]=dz'
Ax = getMatrix(N[0], h[0], bc_hor[0], bc_hor[1], order)
Az = getMatrix(N[1], h[1], bc_ver[0], bc_ver[1], order)
Dx = sp.kron(Ax, sp.eye(N[1]), format="csr")
Dz = sp.kron(sp.eye(N[0]), Az, format="csr")
return Dx, Dz
#
# NOTE: So far only constant dirichlet values can be prescribed, i.e. one fixed value for a whole segment
#
示例15: _compute
# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import kron [as 别名]
def _compute(self, data_1, data_2):
data_1 = basic.graphs_to_adjacency_lists(data_1)
data_2 = basic.graphs_to_adjacency_lists(data_2)
res = np.zeros((len(data_1), len(data_2)))
N = len(data_1) * len(data_2)
for i, graph1 in enumerate(data_1):
for j, graph2 in enumerate(data_2):
# norm1, norm2 - normalized adjacency matrixes
norm1 = _norm(graph1)
norm2 = _norm(graph2)
# if graph is unweighted, W_prod = kron(a_norm(g1)*a_norm(g2))
w_prod = kron(lil_matrix(norm1), lil_matrix(norm2))
starting_prob = np.ones(w_prod.shape[0]) / (w_prod.shape[0])
stop_prob = starting_prob
# first solve (I - lambda * W_prod) * x = p_prod
A = identity(w_prod.shape[0]) - (w_prod * self._lmb)
x = lsqr(A, starting_prob)
res[i, j] = stop_prob.T.dot(x[0])
# print float(len(data_2)*i + j)/float(N), "%"
return res