本文整理汇总了Python中scipy.sparse.linalg.eigsh方法的典型用法代码示例。如果您正苦于以下问题:Python linalg.eigsh方法的具体用法?Python linalg.eigsh怎么用?Python linalg.eigsh使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.sparse.linalg
的用法示例。
在下文中一共展示了linalg.eigsh方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: solve_modal
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def solve_modal(model,k:int):
"""
Solve eigen mode of the MDOF system
params:
model: FEModel.
k: number of modes to extract.
"""
K_,M_=model.K_,model.M_
if k>model.DOF:
logger.info('Warning: the modal number to extract is larger than the system DOFs, only %d modes are available'%model.DOF)
k=model.DOF
omega2s,modes = sl.eigsh(K_,k,M_,sigma=0,which='LM')
delta = modes/np.sum(modes,axis=0)
model.is_solved=True
model.mode_=delta
model.omega_=np.sqrt(omega2s).reshape((k,1))
示例2: _calculate_sf
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def _calculate_sf(self, graph):
"""
Calculating the features of a graph.
Arg types:
* **graph** *(NetworkX graph)* - A graph to be embedded.
Return types:
* **embedding** *(Numpy array)* - The embedding of a single graph.
"""
number_of_nodes = graph.number_of_nodes()
L_tilde = nx.normalized_laplacian_matrix(graph, nodelist=range(number_of_nodes))
if number_of_nodes <= self.dimensions:
embedding = eigsh(L_tilde, k=number_of_nodes-1, which='LM',
ncv=10*self.dimensions, return_eigenvectors=False)
shape_diff = self.dimensions - embedding.shape[0] - 1
embedding = np.pad(embedding, (1, shape_diff), 'constant', constant_values=0)
else:
embedding = eigsh(L_tilde, k=self.dimensions, which='LM',
ncv=10*self.dimensions, return_eigenvectors=False)
return embedding
示例3: test_cXY_E0
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def test_cXY_E0(nr_sites, gamma, rgen, ldim=2):
if sys.version_info[:2] == (3, 3) and gamma == -0.5:
# Skip this test on Python 3.3 because it fails on Travis (but
# only for Python 3.3). eigsh() fails with:
# scipy.sparse.linalg.eigen.arpack.arpack.ArpackNoConvergence:
# ARPACK error -1: No convergence (xxx iterations, 0/1
# eigenvectors converged) [ARPACK error -14: ZNAUPD did not
# find any eigenvalues to sufficient accuracy.]
pt.skip("Test fails on Travis for unknown reason")
return
# Verify that the analytical solution of the ground state energy
# matches the numerical value from eigsh()
E0 = physics.cXY_E0(nr_sites, gamma)
H = physics.sparse_cH(physics.cXY_local_terms(nr_sites, gamma))
# Fix start vector for eigsh()
v0 = rgen.randn(ldim**nr_sites) + 1j * rgen.randn(ldim**nr_sites)
ev = eigsh(H, k=1, which='SR', v0=v0, return_eigenvectors=False).min()
assert abs(E0 - ev) <= 1e-13
示例4: _cov_eigen
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def _cov_eigen(self, X):
"""
Perform direct computation of covariance matrix eigen{values,vectors},
given a scipy.sparse matrix.
Parameters
----------
X : WRITEME
Returns
-------
WRITEME
"""
v, W = eigen_symmetric(X.T.dot(X) / X.shape[0], k=self.num_components)
# The resulting components are in *ascending* order of eigenvalue, and
# W contains eigenvectors in its *columns*, so we simply reverse both.
return v[::-1], W[:, ::-1]
示例5: manifold_harmonics
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def manifold_harmonics(verts, tris, K, scaled=True, return_D=False, return_eigenvalues=False):
Q, vertex_area = compute_mesh_laplacian(
verts, tris, 'cotangent',
return_vertex_area=True, area_type='lumped_mass'
)
if scaled:
D = sparse.spdiags(vertex_area, 0, len(verts), len(verts))
else:
D = sparse.spdiags(np.ones_like(vertex_area), 0, len(verts), len(verts))
try:
lambda_dense, Phi_dense = eigsh(-Q, M=D, k=K, sigma=0)
except RuntimeError, e:
if e.message == 'Factor is exactly singular':
logging.warn("factor is singular, trying some regularization and cholmod")
chol_solve = factorized(-Q + sparse.eye(Q.shape[0]) * 1.e-9)
OPinv = sparse.linalg.LinearOperator(Q.shape, matvec=chol_solve)
lambda_dense, Phi_dense = eigsh(-Q, M=D, k=K, sigma=0, OPinv=OPinv)
else:
raise e
示例6: test_eigs_truss
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def test_eigs_truss():
"""Eigenvalues of a bar"""
nnodes = 513
x = np.linspace(0, np.pi, nnodes)
nodes = np.zeros((nnodes, 3))
nodes[:, 0] = range(nnodes)
nodes[:, 1] = x
cons = np.zeros((nnodes, 2))
cons[:, 1] = -1
cons[0, 0] = -1
cons[-1, 0] = -1
mats = np.array([[1.0, 1.0, 1.0]])
elements = np.zeros((nnodes - 1, 5 ), dtype=int)
elements[:, 0] = range(nnodes - 1)
elements[:, 1] = 6
elements[:, 3] = range(nnodes - 1)
elements[:, 4] = range(1, nnodes)
assem_op, bc_array, neq = ass.DME(cons, elements)
stiff, mass = ass.assembler(elements, mats, nodes, neq, assem_op)
vals, _ = eigsh(stiff, M=mass, which="SM")
assert np.allclose(vals, np.linspace(1, 6, 6)**2, rtol=1e-2)
示例7: _method_1
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def _method_1(data, num_pcs=None):
"""Compute OPCA when num_observations > num_dimensions."""
data = np.nan_to_num(data - nanmean(data, axis=0))
T = data.shape[0]
corr_offset = np.dot(data[1:].T, data[:-1])
corr_offset += corr_offset.T
if num_pcs is None:
eivals, eivects = eigh(corr_offset)
else:
eivals, eivects = eigsh(corr_offset, num_pcs, which='LA')
eivals = np.real(eivals)
eivects = np.real(eivects)
idx = np.argsort(-eivals) # sort the eigenvectors and eigenvalues
eivals = old_div(eivals[idx], (2. * (T - 1)))
eivects = eivects[:, idx]
return eivals, eivects, np.dot(data, eivects)
示例8: ldos0d_wf
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def ldos0d_wf(h,e=0.0,delta=0.01,num_wf = 10,robust=False,tol=0):
"""Calculates the local density of states of a hamiltonian and
writes it in file, using arpack"""
if h.dimensionality==0: # only for 0d
intra = csc_matrix(h.intra) # matrix
else: raise # not implemented...
if robust: # go to the imaginary axis for stability
eig,eigvec = slg.eigs(intra,k=int(num_wf),which="LM",
sigma=e+1j*delta,tol=tol)
eig = eig.real # real part only
else: # Hermitic Hamiltonian
eig,eigvec = slg.eigsh(intra,k=int(num_wf),which="LM",sigma=e,tol=tol)
d = np.array([0.0 for i in range(intra.shape[0])]) # initialize
for (v,ie) in zip(eigvec.transpose(),eig): # loop over wavefunctions
v2 = (np.conjugate(v)*v).real # square of wavefunction
fac = delta/((e-ie)**2 + delta**2) # factor to create a delta
d += fac*v2 # add contribution
# d /= num_wf # normalize
d /= np.pi # normalize
d = spatial_dos(h,d) # resum if necessary
g = h.geometry # store geometry
write_ldos(g.x,g.y,d,z=g.z) # write in file
示例9: ldos_arpack
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def ldos_arpack(intra,num_wf=10,robust=False,tol=0,e=0.0,delta=0.01):
"""Use arpack to calculate hte local density of states at a certain energy"""
if robust: # go to the imaginary axis for stability
eig,eigvec = slg.eigs(intra,k=int(num_wf),which="LM",
sigma=e+1j*delta,tol=tol)
eig = eig.real # real part only
else: # Hermitic Hamiltonian
eig,eigvec = slg.eigsh(intra,k=int(num_wf),which="LM",sigma=e,tol=tol)
d = np.array([0.0 for i in range(intra.shape[0])]) # initialize
for (v,ie) in zip(eigvec.transpose(),eig): # loop over wavefunctions
v2 = (np.conjugate(v)*v).real # square of wavefunction
fac = delta/((e-ie)**2 + delta**2) # factor to create a delta
d += fac*v2 # add contribution
# d /= num_wf # normalize
d /= np.pi # normalize
return d
示例10: occupied_states
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def occupied_states(hkgen,k,window=None,max_waves=None):
""" Returns the WF of the occupied states in a 2d hamiltonian"""
hk = hkgen(k) # get hamiltonian
if max_waves is None: es,wfs = algebra.eigh(hk) # diagonalize all waves
else: es,wfs = slg.eigsh(csc_matrix(hk),k=max_waves,which="SA",
sigma=0.0,tol=arpack_tol,maxiter=arpack_maxiter)
wfs = np.conjugate(wfs.transpose()) # wavefunctions
occwf = []
for (ie,iw) in zip(es,wfs): # loop over states
if window is None: # no energy window
if ie < 0: # if below fermi
occwf.append(iw) # add to the list
else: # energy window provided
if -abs(window)< ie < 0: # between energy window and fermi
occwf.append(iw) # add to the list
return np.array(occwf)
示例11: fsr_rankR
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def fsr_rankR(qsims, Wn, alpha = 0.99, R = 2000):
vals, vecs = s_linalg.eigsh(Wn, k = R)
p2 = diags((1.0 - alpha) / (1.0 - alpha*vals))
vc = csr_matrix(vecs)
p3 = vc.dot(p2)
vc_norm = (vc.multiply(vc)).sum(axis = 0)
out_sims = []
for i in range(qsims.shape[0]):
qsims_sparse = csr_matrix(qsims[i:i+1,:])
p1 =(vc.T).dot(qsims_sparse.T)
diff_sim = csr_matrix(p3)*csr_matrix(p1)
out_sims.append(diff_sim.todense().reshape(-1,1))
out_sims = np.concatenate(out_sims, axis = 1)
ranks = np.argsort(-out_sims, axis = 0)
return ranks
示例12: eigensolve
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def eigensolve( self, A , B , count=5 ):
C = self.getConstraintsMatrix()
A_constrained = dot( dot( C.transpose(), A ), C )
B_constrained = dot( dot( C.transpose(), B ), C )
eigvals , eigvecs = eigsh( A_constrained, count , B_constrained , sigma = 0. , which = 'LM' )
x = zeros(shape=(len(self),count))
for i,psi in enumerate(eigvecs.transpose()):
x[:,i] = C * psi
return eigvals,x
示例13: _svd
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def _svd(self, array, n_components, n_discard):
"""Returns first `n_components` left and right singular
vectors u and v, discarding the first `n_discard`.
"""
if self.svd_method == 'randomized':
kwargs = {}
if self.n_svd_vecs is not None:
kwargs['n_oversamples'] = self.n_svd_vecs
u, _, vt = randomized_svd(array, n_components,
random_state=self.random_state,
**kwargs)
elif self.svd_method == 'arpack':
u, _, vt = svds(array, k=n_components, ncv=self.n_svd_vecs)
if np.any(np.isnan(vt)):
# some eigenvalues of A * A.T are negative, causing
# sqrt() to be np.nan. This causes some vectors in vt
# to be np.nan.
A = safe_sparse_dot(array.T, array)
random_state = check_random_state(self.random_state)
# initialize with [-1,1] as in ARPACK
v0 = random_state.uniform(-1, 1, A.shape[0])
_, v = eigsh(A, ncv=self.n_svd_vecs, v0=v0)
vt = v.T
if np.any(np.isnan(u)):
A = safe_sparse_dot(array, array.T)
random_state = check_random_state(self.random_state)
# initialize with [-1,1] as in ARPACK
v0 = random_state.uniform(-1, 1, A.shape[0])
_, u = eigsh(A, ncv=self.n_svd_vecs, v0=v0)
assert_all_finite(u)
assert_all_finite(vt)
u = u[:, n_discard:]
vt = vt[n_discard:]
return u, vt.T
示例14: test_eig
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def test_eig(nr_sites, local_dim, rank, which, var_sites, rgen, request):
if nr_sites <= var_sites:
pt.skip("Nothing to test")
return # No local optimization can be defined
if not (_pytest_want_long(request) or
(nr_sites, local_dim, rank, var_sites, which) in {
(3, 2, 4, 1, 'SA'), (4, 3, 5, 1, 'LM'), (5, 2, 1, 2, 'LA'),
(6, 2, 4, 2, 'SA'),
}):
pt.skip("Should only be run in long tests")
# With startvec_rank = 2 * rank and this seed, eig() gets
# stuck in a local minimum. With startvec_rank = 3 * rank,
# it does not.
mpo = factory.random_mpo(nr_sites, local_dim, rank, randstate=rgen,
hermitian=True, normalized=True)
mpo.canonicalize()
op = mpo.to_array_global().reshape((local_dim**nr_sites,) * 2)
v0 = factory._zrandn([local_dim**nr_sites], rgen)
eigval, eigvec = eigsh(op, k=1, which=which, v0=v0)
eigval, eigvec = eigval[0], eigvec[:, 0]
eig_rank = (4 - var_sites) * rank
eigval_mp, eigvec_mp = mp.eig(
mpo, num_sweeps=5, var_sites=1, startvec_rank=eig_rank, randstate=rgen,
eigs=ft.partial(eigsh, k=1, which=which, tol=1e-6, maxiter=250))
eigvec_mp = eigvec_mp.to_array().flatten()
overlap = np.inner(eigvec.conj(), eigvec_mp)
assert_almost_equal(eigval, eigval_mp, decimal=14)
assert_almost_equal(1, abs(overlap), decimal=14)
示例15: test_eig_sum
# 需要导入模块: from scipy.sparse import linalg [as 别名]
# 或者: from scipy.sparse.linalg import eigsh [as 别名]
def test_eig_sum(nr_sites, local_dim, rank, rgen):
# Need at least three sites for var_sites = 2
if nr_sites < 3:
pt.skip("Nothing to test")
return
rank = max(1, rank // 2)
mpo = factory.random_mpo(nr_sites, local_dim, rank, randstate=rgen,
hermitian=True, normalized=True)
mpo.canonicalize()
mps = factory.random_mpa(nr_sites, local_dim, rank, randstate=rgen,
dtype=np.complex_, normalized=True)
mpas = [mpo, mps]
vec = mps.to_array().ravel()
op = mpo.to_array_global().reshape((local_dim**nr_sites,) * 2)
op += np.outer(vec, vec.conj())
eigvals, eigvec = np.linalg.eigh(op)
# Eigenvals should be real for a hermitian matrix
assert (np.abs(eigvals.imag) < 1e-10).all(), str(eigvals.imag)
mineig_pos = eigvals.argmin()
mineig, mineig_eigvec = eigvals[mineig_pos], eigvec[:, mineig_pos]
mineig_mp, mineig_eigvec_mp = mp.eig_sum(
mpas, num_sweeps=5, startvec_rank=5 * rank, randstate=rgen,
eigs=ft.partial(eigsh, k=1, which='SA', tol=1e-6),
var_sites=2)
mineig_eigvec_mp = mineig_eigvec_mp.to_array().flatten()
overlap = np.inner(mineig_eigvec.conj(), mineig_eigvec_mp)
assert_almost_equal(mineig_mp, mineig)
assert_almost_equal(abs(overlap), 1)