本文整理匯總了Python中scipy.sparse.dia_matrix方法的典型用法代碼示例。如果您正苦於以下問題:Python sparse.dia_matrix方法的具體用法?Python sparse.dia_matrix怎麽用?Python sparse.dia_matrix使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類scipy.sparse
的用法示例。
在下文中一共展示了sparse.dia_matrix方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _scale_normalize
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def _scale_normalize(X):
"""Normalize ``X`` by scaling rows and columns independently.
Returns the normalized matrix and the row and column scaling
factors.
"""
X = make_nonnegative(X)
row_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=1))).squeeze()
col_diag = np.asarray(1.0 / np.sqrt(X.sum(axis=0))).squeeze()
row_diag = np.where(np.isnan(row_diag), 0, row_diag)
col_diag = np.where(np.isnan(col_diag), 0, col_diag)
if issparse(X):
n_rows, n_cols = X.shape
r = dia_matrix((row_diag, [0]), shape=(n_rows, n_rows))
c = dia_matrix((col_diag, [0]), shape=(n_cols, n_cols))
an = r * X * c
else:
an = row_diag[:, np.newaxis] * X * col_diag
return an, row_diag, col_diag
示例2: _zeropi_operator_in_product_basis
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [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')
示例3: sparse_kinetic_mat
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [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
示例4: new_realization
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def new_realization(self):
"""
Generate a new channel realization and save the time-variant convolution matrix in "self.imp_convolution_matrix"
"""
if self.imp_pdp_string=='AWGN':
impulse_response_squeezed = np.ones((self.nr_samples,1))
elif self.imp_pdp_string=='Flat':
h = np.random.randn(1) + 1j * np.random.randn(1)
impulse_response_squeezed = h * np.ones((self.nr_samples,1))
else:
impulse_response_squeezed = np.zeros((self.nr_samples,self.imp_pdp_index.size), dtype=np.complex)
t = np.arange(self.nr_samples).reshape(self.nr_samples,1)*self.phy_dt
# Use a for loop because it is more memory efficient (but takes longer)
for i in range(self.imp_nr_paths_wssus):
doppler_shifts = np.cos(np.random.random((1,self.imp_pdp_index.size))*2*np.pi) * self.phy_max_doppler_shift
random_phase = np.random.random((1,self.imp_pdp_index.size))
argument = 2 * np.pi * (random_phase + doppler_shifts*t)
impulse_response_squeezed += np.cos(argument) + 1j*np.sin(argument)
impulse_response_squeezed *= np.sqrt(self.imp_pdp[self.imp_pdp_index]/self.imp_nr_paths_wssus)
self.imp_convolution_matrix = sparse.dia_matrix((np.transpose(impulse_response_squeezed), -self.imp_pdp_index), shape=(self.nr_samples, self.nr_samples)).tocsr()
示例5: _diagonalize_interslice_kernels
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def _diagonalize_interslice_kernels(interslice_kernels, method='dia'):
n = interslice_kernels[0].shape[0]
m = len(interslice_kernels)
if method == 'dia':
diags = np.zeros((2*n-1, n*m))
for vertex, A in enumerate(interslice_kernels):
diags[(np.tile(np.arange(n, 2*n), n) - np.repeat(np.arange(1, n+1), n),
np.tile(np.arange(0, n*m, m), n) + vertex)] = A.flatten()
offsets = np.arange(-n*m + m, n*m, m)
# set main diagonal to 0
diags[offsets == 0] = 0
K = sparse.dia_matrix((diags, offsets), shape=(n*m, n*m))
else:
assert method == 'csr'
# this is inefficient
K = sparse.csr_matrix((n*m, n*m))
for vertex, A in enumerate(interslice_kernels):
K = graphtools.matrix.set_submatrix(
K, np.arange(n) * m + vertex, np.arange(n) * m + vertex, A)
# set main diagonal to 0
K = graphtools.matrix.set_diagonal(K, 0)
return K
示例6: get_laplacian
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def get_laplacian(self, sims, ids, alpha=0.99):
"""Get Laplacian_alpha matrix
"""
logger.info('get_affinity')
affinity = self.get_affinity(sims, ids)
logger.info('get_affinity ... done')
num = affinity.shape[0]
degrees = affinity @ np.ones(num) + 1e-12
# mat: degree matrix ^ (-1/2)
mat = sparse.dia_matrix(
(degrees ** (-0.5), [0]), shape=(num, num), dtype=np.float32)
logger.info('calc stochastic = mat @ affinity @ mat')
stochastic = mat @ affinity @ mat
sparse_eye = sparse.dia_matrix(
(np.ones(num), [0]), shape=(num, num), dtype=np.float32)
lap_alpha = sparse_eye - alpha * stochastic
return lap_alpha
# @cache('affinity.jbl')
示例7: get_laplacian
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def get_laplacian(self, sims, ids, alpha=0.99):
"""Get Laplacian_alpha matrix
"""
affinity = self.get_affinity(sims, ids)
num = affinity.shape[0]
degrees = affinity @ np.ones(num) + 1e-12
# mat: degree matrix ^ (-1/2)
mat = sparse.dia_matrix(
(degrees ** (-0.5), [0]), shape=(num, num), dtype=np.float32)
stochastic = mat @ affinity @ mat
sparse_eye = sparse.dia_matrix(
(np.ones(num), [0]), shape=(num, num), dtype=np.float32)
lap_alpha = sparse_eye - alpha * stochastic
return lap_alpha
# @cache('affinity.jbl')
示例8: vnl_coo
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def vnl_coo(self):
""" Non-local part of the Hamiltonian due to Kleinman-Bylander projectors """
from pyscf.nao.m_overlap_am import overlap_am
from scipy.sparse import dia_matrix
sop = self.overlap_coo(ao_log=self.ao_log, ao_log2=self.kb_log, funct=overlap_am).tocsr()
nkb = sop.shape[1]
vkb_dia = dia_matrix( ( self.get_vkb(), [0] ), shape = (nkb,nkb) )
return ((sop*vkb_dia)*sop.T).tocoo()
示例9: _rescale_data
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def _rescale_data(X, weights):
if issparse(X):
size = weights.shape[0]
weight_dia = sparse.dia_matrix((1 - weights, 0), (size, size))
X_rescaled = X * weight_dia
else:
X_rescaled = X * (1 - weights)
return X_rescaled
示例10: _rescale_data
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def _rescale_data(X, y, sample_weight):
"""Rescale data so as to support sample_weight"""
n_samples = X.shape[0]
sample_weight = np.full(n_samples, sample_weight,
dtype=np.array(sample_weight).dtype)
sample_weight = np.sqrt(sample_weight)
sw_matrix = sparse.dia_matrix((sample_weight, 0),
shape=(n_samples, n_samples))
X = safe_sparse_dot(sw_matrix, X)
y = safe_sparse_dot(sw_matrix, y)
return X, y
示例11: get_subset_cpd
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def get_subset_cpd(self, sub_idx):
""" Get the cpd over a subset of the variables.
:param np.ndarray[int]|np.ndarray[bool] sub_idx: indices of variables to keep
:return: a new Gaussian CPD
:rtype: GaussianCPD
"""
if len(sub_idx) == 0 or (sub_idx.dtype == bool and not np.sum(sub_idx)):
raise ValueError("sub_idx must not be empty")
sub_mean = self.mean[sub_idx]
sub_dim = len(sub_mean)
if isinstance(self.precision, sp.dia_matrix):
sub_precision = sp.dia_matrix((self.precision.diagonal()[sub_idx], np.zeros(1)),
shape=(sub_dim, sub_dim))
elif np.isscalar(self.precision):
sub_precision = self.precision
elif isinstance(self.precision, np.ndarray):
if np.prod(self.precision.shape) == self.dim:
sub_precision = self.precision[sub_idx]
else:
# We do the indexing this way for performance reasons.
sub_precision = self.precision[sub_idx, :][:, sub_idx]
else:
# We do the indexing this way for performance reasons.
sub_precision = self.precision.tocsr()[sub_idx, :][:, sub_idx]
return GaussianCPD(dim=sub_dim, mean=sub_mean, precision=sub_precision,
mean_lin_op=get_subset_lin_op(self.mean_lin_op, sub_idx))
示例12: hamiltonian
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def hamiltonian(self, return_parts=False):
"""Returns Hamiltonian in basis obtained by discretizing phi, employing charge basis for theta, and Fock
basis for zeta.
Parameters
----------
return_parts: bool, optional
If set to true, `hamiltonian` returns [hamiltonian, evals, evecs, g_coupling_matrix]
Returns
-------
scipy.sparse.csc_matrix or list
"""
zeropi_dim = self.zeropi_cutoff
zeropi_evals, zeropi_evecs = self._zeropi.eigensys(evals_count=zeropi_dim)
zeropi_diag_hamiltonian = sparse.dia_matrix((zeropi_dim, zeropi_dim), dtype=np.complex_)
zeropi_diag_hamiltonian.setdiag(zeropi_evals)
zeta_dim = self.zeta_cutoff
prefactor = self.E_zeta
zeta_diag_hamiltonian = op.number_sparse(zeta_dim, prefactor)
hamiltonian_mat = sparse.kron(zeropi_diag_hamiltonian,
sparse.identity(zeta_dim, format='dia', dtype=np.complex_))
hamiltonian_mat += sparse.kron(sparse.identity(zeropi_dim, format='dia', dtype=np.complex_),
zeta_diag_hamiltonian)
gmat = self.g_coupling_matrix(zeropi_evecs)
zeropi_coupling = sparse.dia_matrix((zeropi_dim, zeropi_dim), dtype=np.complex_)
for l1 in range(zeropi_dim):
for l2 in range(zeropi_dim):
zeropi_coupling += gmat[l1, l2] * op.hubbard_sparse(l1, l2, zeropi_dim)
hamiltonian_mat += sparse.kron(zeropi_coupling,
op.annihilation_sparse(zeta_dim)) + sparse.kron(zeropi_coupling.conjugate().T,
op.creation_sparse(zeta_dim))
if return_parts:
return [hamiltonian_mat.tocsc(), zeropi_evals, zeropi_evecs, gmat]
return hamiltonian_mat.tocsc()
示例13: sparse_potential_mat
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def sparse_potential_mat(self):
"""
Potential energy portion of the Hamiltonian.
TODO: update this method to use single-variable operator methods
Returns
-------
scipy.sparse.csc_matrix
matrix representing the potential energy operator
"""
pt_count = self.grid.pt_count
grid_linspace = self.grid.make_linspace()
dim_theta = 2 * self.ncut + 1
phi_inductive_vals = self.EL * np.square(grid_linspace)
phi_inductive_potential = sparse.dia_matrix((phi_inductive_vals, [0]), shape=(pt_count, pt_count)).tocsc()
phi_cos_vals = np.cos(grid_linspace - 2.0 * np.pi * self.flux / 2.0)
phi_cos_potential = sparse.dia_matrix((phi_cos_vals, [0]), shape=(pt_count, pt_count)).tocsc()
phi_sin_vals = np.sin(grid_linspace - 2.0 * np.pi * self.flux / 2.0)
phi_sin_potential = sparse.dia_matrix((phi_sin_vals, [0]), shape=(pt_count, pt_count)).tocsc()
theta_cos_potential = (-self.EJ
* (sparse.dia_matrix(([1.0] * dim_theta, [-1]), shape=(dim_theta, dim_theta)) +
sparse.dia_matrix(([1.0] * dim_theta, [1]), shape=(dim_theta, dim_theta)))).tocsc()
potential_mat = (sparse.kron(phi_cos_potential, theta_cos_potential, format='csc')
+ sparse.kron(phi_inductive_potential, self._identity_theta(), format='csc')
+ 2 * self.EJ * sparse.kron(self._identity_phi(), self._identity_theta(), format='csc'))
potential_mat += (self.EJ * self.dEJ * sparse.kron(phi_sin_potential, self._identity_theta(), format='csc')
* self.sin_theta_operator())
return potential_mat
示例14: _phi_operator
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def _phi_operator(self):
r"""
Operator :math:`\varphi`, acting only on the `\varphi` Hilbert subspace.
Returns
-------
scipy.sparse.csc_matrix
"""
pt_count = self.grid.pt_count
phi_matrix = sparse.dia_matrix((pt_count, pt_count), dtype=np.complex_)
diag_elements = self.grid.make_linspace()
phi_matrix.setdiag(diag_elements)
return phi_matrix
示例15: _sin_phi_operator
# 需要導入模塊: from scipy import sparse [as 別名]
# 或者: from scipy.sparse import dia_matrix [as 別名]
def _sin_phi_operator(self, x=0):
r"""
Operator :math:`\sin(\phi + x)`, acting only on the `\phi` Hilbert subspace.
Returns
-------
scipy.sparse.csc_matrix
"""
pt_count = self.grid.pt_count
vals = np.sin(self.grid.make_linspace() + x)
sin_phi_matrix = sparse.dia_matrix((vals, [0]), shape=(pt_count, pt_count)).tocsc()
return sin_phi_matrix