本文整理汇总了Python中scipy.linalg.eigh方法的典型用法代码示例。如果您正苦于以下问题:Python linalg.eigh方法的具体用法?Python linalg.eigh怎么用?Python linalg.eigh使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.linalg
的用法示例。
在下文中一共展示了linalg.eigh方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_newton_step_aug_hess
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def get_newton_step_aug_hess(jac,hess):
#lamb = 1.0 / alpha
ah = np.zeros((hess.shape[0]+1,hess.shape[1]+1))
ah[1:,0] = jac
ah[0,1:] = jac.conj()
ah[1:,1:] = hess
eigval, eigvec = la.eigh(ah)
idx = None
for i in xrange(len(eigvec)):
if abs(eigvec[0,i]) > 0.1 and eigval[i] > 0.0:
idx = i
break
if idx is None:
print("WARNING: ALL EIGENVALUESS in AUG-HESSIAN are NEGATIVE!!! ")
return np.zeros_like(jac)
deltax = eigvec[1:,idx] / eigvec[0,idx]
return deltax
示例2: test_jw_restrict_operator
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def test_jw_restrict_operator(self):
"""Test the scheme for restricting JW encoded operators to number"""
# Make a Hamiltonian that cares mostly about number of electrons
n_qubits = 6
target_electrons = 3
penalty_const = 100.
number_sparse = jordan_wigner_sparse(number_operator(n_qubits))
bias_sparse = jordan_wigner_sparse(
sum([FermionOperator(((i, 1), (i, 0)), 1.0) for i
in range(n_qubits)], FermionOperator()))
hamiltonian_sparse = penalty_const * (
number_sparse - target_electrons *
scipy.sparse.identity(2**n_qubits)).dot(
number_sparse - target_electrons *
scipy.sparse.identity(2**n_qubits)) + bias_sparse
restricted_hamiltonian = jw_number_restrict_operator(
hamiltonian_sparse, target_electrons, n_qubits)
true_eigvals, _ = eigh(hamiltonian_sparse.A)
test_eigvals, _ = eigh(restricted_hamiltonian.A)
self.assertAlmostEqual(norm(true_eigvals[:20] - test_eigvals[:20]),
0.0)
示例3: test_spectral_embedding_unnormalized
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def test_spectral_embedding_unnormalized():
# Test that spectral_embedding is also processing unnormalized laplacian
# correctly
random_state = np.random.RandomState(36)
data = random_state.randn(10, 30)
sims = rbf_kernel(data)
n_components = 8
embedding_1 = spectral_embedding(sims,
norm_laplacian=False,
n_components=n_components,
drop_first=False)
# Verify using manual computation with dense eigh
laplacian, dd = csgraph.laplacian(sims, normed=False,
return_diag=True)
_, diffusion_map = eigh(laplacian)
embedding_2 = diffusion_map.T[:n_components]
embedding_2 = _deterministic_vector_sign_flip(embedding_2).T
assert_array_almost_equal(embedding_1, embedding_2)
示例4: _eigen_decompose_covariance
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def _eigen_decompose_covariance(self, X, y, sqrt_sw):
"""Eigendecomposition of X^T.X, used when n_samples > n_features."""
n_samples, n_features = X.shape
cov = np.empty((n_features + 1, n_features + 1), dtype=X.dtype)
cov[:-1, :-1], X_mean = self._compute_covariance(X, sqrt_sw)
if not self.fit_intercept:
cov = cov[:-1, :-1]
# to emulate centering X with sample weights,
# ie removing the weighted average, we add a column
# containing the square roots of the sample weights.
# by centering, it is orthogonal to the other columns
# when all samples have the same weight we add a column of 1
else:
cov[-1] = 0
cov[:, -1] = 0
cov[-1, -1] = sqrt_sw.dot(sqrt_sw)
nullspace_dim = max(0, X.shape[1] - X.shape[0])
s, V = linalg.eigh(cov)
# remove eigenvalues and vectors in the null space of X^T.X
s = s[nullspace_dim:]
V = V[:, nullspace_dim:]
return X_mean, s, V, X
示例5: test_eigsh_for_k_greater
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def test_eigsh_for_k_greater():
# Test eigsh() for k beyond limits.
A_sparse = diags([1, -2, 1], [-1, 0, 1], shape=(4, 4)) # sparse
A = generate_matrix(4, sparse=False)
M_dense = generate_matrix_symmetric(4, pos_definite=True)
M_sparse = generate_matrix_symmetric(4, pos_definite=True, sparse=True)
M_linop = aslinearoperator(M_dense)
eig_tuple1 = eigh(A, b=M_dense)
eig_tuple2 = eigh(A, b=M_sparse)
with suppress_warnings() as sup:
sup.filter(RuntimeWarning)
assert_equal(eigsh(A, M=M_dense, k=4), eig_tuple1)
assert_equal(eigsh(A, M=M_dense, k=5), eig_tuple1)
assert_equal(eigsh(A, M=M_sparse, k=5), eig_tuple2)
# M as LinearOperator
assert_raises(TypeError, eigsh, A, M=M_linop, k=4)
# Test 'A' for different types
assert_raises(TypeError, eigsh, aslinearoperator(A), k=4)
assert_raises(TypeError, eigsh, A_sparse, M=M_dense, k=4)
示例6: excitedStateManifold
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def excitedStateManifold(self,gL,gI,I,A_hyp_coeff,B_hyp_coeff,Bfield):
"""Function to produce the excited state manifold"""
dp = int(3*(2*S+1)*(2*I+1)) # total dimension of matrix
# The actual value of FS is unimportant.
FS = self.atom.FS # Fine structure splitting
Ap = A_hyp_coeff
Bp = B_hyp_coeff
# Add P-term fine and hyperfine interactions
if Bp==0.0:
P_StateHamiltonian=FS*Hfs(1.0,S,I)+FS*identity(dp)+Ap*Hhfs(1.0,S,I)
if Bp!=0.0:
P_StateHamiltonian=FS*Hfs(1.0,S,I)-(FS/2.0)*identity(dp)+Ap*Hhfs(1.0,S,I)
P_StateHamiltonian+=Bp*Bbhfs(1.0,S,I) # add p state quadrupole
E=muB*(Bfield*1.0e-4)/(hbar*2.0*pi*1.0e6)
# Add magnetic interaction
P_StateHamiltonian+=E*(gL*lz(1.0,S,I)+gs*sz(1.0,S,I)+gI*Iz(1.0,S,I))
ep=eigh(P_StateHamiltonian)
EigenValues=ep[0].real
EigenVectors=ep[1]
stateManifold=append([EigenValues],EigenVectors,axis=0)
sortedManifold=sorted(transpose(stateManifold),key=(lambda i:i[0]))
return sortedManifold, EigenValues
示例7: Bmatrix
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def Bmatrix(C):
"""
Calculate a matrix which is effectively the square root of the correlation matrix C
Parameters
----------
C : 2d array
A covariance matrix
Returns
-------
B : 2d array
A matrix B such the B.dot(B') = inv(C)
"""
# this version of finding the square root of the inverse matrix
# suggested by Cath Trott
L, Q = eigh(C)
# force very small eigenvalues to have some minimum non-zero value
minL = 1e-9*L[-1]
L[L < minL] = minL
S = np.diag(1 / np.sqrt(L))
B = Q.dot(S)
return B
示例8: _visibilities
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def _visibilities(self, X):
visi_noisy_all = []
for band_count in range(self.num_freq):
# Estimate the covariance matrix and extract off-diagonal entries
fn = self.freq_bins[band_count]
energy = np.var(X[:, fn, :], axis=0)
I = np.where(energy > self.stft_noise_margin * self.stft_noise_floor)
R = cov_mtx_est(X[:, fn, I[0]])
# impose low rank constraint
if self.low_rank_cleaning:
w, vl = la.eigh(R)
w = np.abs(w)
k = self.num_src
sigma = w.min() # estimate the noise by minimum statistics
Rhat = np.dot(vl[:,-k:] * (w[None,-k:] - sigma), np.conj(vl[:,-k:].T))
else:
Rhat = R
visi_noisy = extract_off_diag(Rhat)
visi_noisy_all.append(visi_noisy)
return visi_noisy_all
示例9: _cov_eigen
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def _cov_eigen(self, X):
"""
Perform direct computation of covariance matrix eigen{values,vectors}.
Parameters
----------
X : WRITEME
Returns
-------
WRITEME
"""
v, W = linalg.eigh(self.cov(X.T))
# 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]
示例10: _sample_gaussian
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def _sample_gaussian(mean, covar, covariance_type='diag', n_samples=1,
random_state=None):
rng = check_random_state(random_state)
n_dim = len(mean)
rand = rng.randn(n_dim, n_samples)
if n_samples == 1:
rand.shape = (n_dim,)
if covariance_type == 'spherical':
rand *= np.sqrt(covar)
elif covariance_type == 'diag':
rand = np.dot(np.diag(np.sqrt(covar)), rand)
else:
s, U = linalg.eigh(covar)
s.clip(0, out=s) # get rid of tiny negatives
np.sqrt(s, out=s)
U *= s
rand = np.dot(U, rand)
return (rand.T + mean).T
示例11: test_linear_operator
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def test_linear_operator():
"""Test linear operator."""
n_times, n_atoms, n_times_atom = 64, 16, 32
n_times_valid = n_times - n_times_atom + 1
rng = check_random_state(42)
ds = rng.randn(n_atoms, n_times_atom)
some_sample_weights = np.abs(rng.randn(n_times))
for sample_weights in [None, some_sample_weights]:
gbc = partial(gram_block_circulant, ds=ds, n_times_valid=n_times_valid,
sample_weights=sample_weights)
DTD_full = gbc(method='full')
DTD_scipy = gbc(method='scipy')
DTD_custom = gbc(method='custom')
z = rng.rand(DTD_full.shape[1])
assert np.allclose(DTD_full.dot(z), DTD_scipy.dot(z))
assert np.allclose(DTD_full.dot(z), DTD_custom.dot(z))
# test power iterations with linear operator
mu, _ = linalg.eigh(DTD_full)
for DTD in [DTD_full, DTD_scipy, DTD_custom]:
mu_hat = power_iteration(DTD)
assert np.allclose(np.max(mu), mu_hat, rtol=1e-2)
示例12: __init__
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def __init__(self,L,d,T,name = None):
if name is None:
name = "Ising_l"+str(L)+"_d" +str(d)+"_t"+str(T)
super(Ising,self).__init__([L**d],name)
self.beta = 1.0
self.lattice = Hypercube(L, d, 'periodic')
self.K = self.lattice.Adj/T
w, v = eigh(self.K)
offset = 0.1-w.min()
self.K += np.eye(w.size)*offset
sign, logdet = np.linalg.slogdet(self.K)
#print (sign)
#print (0.5*self.nvars[0] *(np.log(4.)-offset - np.log(2.*np.pi)) - 0.5*logdet)
Kinv = torch.from_numpy(inv(self.K)).to(torch.float32)
self.register_buffer("Kinv",Kinv)
示例13: test_eigh1
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def test_eigh1():
np.random.seed(1204982)
a = np.random.rand(10, 10)
# Symmetrize
a = a + a.T
ac = a.copy()
xs, vs = sl.eigh(a)
x, v = eigh(a)
assert np.allclose(xs, x)
assert np.allclose(vs, v)
assert np.allclose(a, ac)
x, v = eigh_dc(a)
assert np.allclose(xs, x)
assert np.allclose(vs, v)
assert np.allclose(a, ac)
x, v = eigh_qr(a)
assert np.allclose(xs, x)
assert np.allclose(vs, v)
assert np.allclose(a, ac)
示例14: proj_choi_to_completely_positive
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def proj_choi_to_completely_positive(choi: np.ndarray, check_finite: bool = True) -> np.ndarray:
"""
Projects the Choi representation of a process into the nearest Choi matrix in the space of
completely positive maps.
Equation 8 of [PGD]_
:param choi: Choi representation of a process
:param check_finite: check that the input matrices contain only finite numbers.
:return: closest Choi matrix in the space of completely positive maps
"""
hermitian_choi = (choi + choi.conj().T) / 2 # enforce Hermiticity
evals, v = linalg.eigh(hermitian_choi, check_finite=check_finite)
evals[evals < 0] = 0 # enforce completely positive by removing negative eigenvalues
diag = np.diag(evals)
return v @ diag @ v.conj().T
示例15: proj_choi_to_trace_non_increasing
# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import eigh [as 别名]
def proj_choi_to_trace_non_increasing(choi: np.ndarray) -> np.ndarray:
"""
Projects the Choi matrix of a process into the space of trace non-increasing maps.
Equation 33 of [PGD]_
:param choi: Choi representation of a process
:return: Choi representation of the projected trace non-increasing process
"""
dim = int(np.sqrt(choi.shape[0]))
# trace out the output Hilbert space
pt = partial_trace(choi, dims=[dim, dim], keep=[0])
hermitian = (pt + pt.conj().T) / 2 # enforce Hermiticity
d, v = linalg.eigh(hermitian)
d[d > 1] = 1 # enforce trace preserving
D = np.diag(d)
projection = v @ D @ v.conj().T
trace_increasing_part = np.kron((pt - projection) / dim, np.eye(dim))
return choi - trace_increasing_part