本文整理匯總了Python中numpy.diag_indices方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.diag_indices方法的具體用法?Python numpy.diag_indices怎麽用?Python numpy.diag_indices使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.diag_indices方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: energy_nuc
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def energy_nuc(mol):
atom_charges = mol.atom_charges()
atom_coords = mol.atom_coords()
distances = numpy.linalg.norm(atom_coords[:,None,:] - atom_coords, axis=2)
distances_in_AA = distances * lib.param.BOHR
# numerically exclude atomic self-interaction terms
distances_in_AA[numpy.diag_indices(mol.natm)] = 1e60
# one atom is H, another atom is N or O
where_NO = (atom_charges == 7) | (atom_charges == 8)
mask = (atom_charges[:,None] == 1) & where_NO
mask = mask | mask.T
scale = alpha = _get_alpha(atom_charges[:,None], atom_charges)
scale[mask] *= numpy.exp(-distances_in_AA[mask])
scale[~mask] = numpy.exp(-alpha[~mask] * distances_in_AA[~mask])
gamma = _get_gamma(mol)
z_eff = mopac_param.CORE[atom_charges]
e_nuc = .5 * numpy.einsum('i,ij,j->', z_eff, gamma, z_eff)
e_nuc += .5 * numpy.einsum('i,j,ij,ij->', z_eff, z_eff, scale,
mopac_param.E2/distances_in_AA - gamma)
return e_nuc
示例2: test_field_gradients
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def test_field_gradients(self):
mol = gto.M(atom='H1 0.5 -0.6 0.4; H2 -0.5, 0.4, -0.3; H -0.4 -0.3 0.5; H 0.3 0.5 -0.6',
unit='B',
basis={'H': [[0,[2., 1]]], 'H1':[[1,[.5, 1]]], 'H2':[[1,[1,1]]]})
grids = dft.gen_grid.Grids(mol)
grids.build()
ao = mol.eval_gto('GTOval', grids.coords)
r0 = mol.atom_coord(0)
dr = grids.coords - r0
dd = numpy.linalg.norm(dr, axis=1)
rr = 3 * numpy.einsum('ix,iy->ixy', dr, dr)
for i in range(3):
rr[:,i,i] -= dd**2
h1ref = lib.einsum('i,ixy,ip,iq->xypq', grids.weights/dd**5, rr, ao, ao)
h1ao = rhf_ssc._get_integrals_fcsd(mol, 0)
h1ao[numpy.diag_indices(3)] += rhf_ssc._get_integrals_fc(mol, 0)
self.assertAlmostEqual(abs(h1ref - h1ao).max(), 0, 5)
示例3: dist_diff
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def dist_diff(self, other=None):
r"""
Calculate distances and vectors between atoms.
Args:
other (:class:`~berny.Geometry`): calculate distances between two
geometries if given or within a geometry if not
Returns:
:math:`R_{ij}:=|\mathbf R_i-\mathbf R_j|` and
:math:`R_{ij\alpha}:=(\mathbf R_i)_\alpha-(\mathbf R_j)_\alpha`.
"""
if other is None:
other = self
diff = self.coords[:, None, :] - other.coords[None, :, :]
dist = np.sqrt(np.sum(diff ** 2, 2))
dist[np.diag_indices(len(self))] = np.inf
return dist, diff
示例4: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def __init__(self, features, using_cache=False, identity_init=True, eps=1e-3):
super().__init__(features, using_cache)
self.eps = eps
self.lower_indices = np.tril_indices(features, k=-1)
self.upper_indices = np.triu_indices(features, k=1)
self.diag_indices = np.diag_indices(features)
n_triangular_entries = ((features - 1) * features) // 2
self.lower_entries = nn.Parameter(torch.zeros(n_triangular_entries))
self.upper_entries = nn.Parameter(torch.zeros(n_triangular_entries))
self.unconstrained_upper_diag = nn.Parameter(torch.zeros(features))
self._initialize(identity_init)
示例5: _get_knmat
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def _get_knmat(exog, xcov, sl):
# Utility function, see equation 2.2 of Barber & Candes.
nobs, nvar = exog.shape
ash = np.linalg.inv(xcov)
ash *= -np.outer(sl, sl)
i, j = np.diag_indices(nvar)
ash[i, j] += 2 * sl
umat = np.random.normal(size=(nobs, nvar))
u, _ = np.linalg.qr(exog)
umat -= np.dot(u, np.dot(u.T, umat))
umat, _ = np.linalg.qr(umat)
ashr, xc, _ = np.linalg.svd(ash, 0)
ashr *= np.sqrt(xc)
ashr = ashr.T
ex = (sl[:, None] * np.linalg.solve(xcov, exog.T)).T
exogn = exog - ex + np.dot(umat, ashr)
return exogn
示例6: test_get_data_dst_nodata
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def test_get_data_dst_nodata(rast, dst_nodata, dst_arr):
fp = rast.fp.dilate(1)
inner_slice = rast.fp.slice_in(fp)
rast.set_data(dst_arr, channels=None)
arr = rast.get_data(band=[-1], dst_nodata=dst_nodata, fp=fp)
arr2 = rast.get_data(band=[-1], dst_nodata=dst_nodata, fp=fp.erode(1))
assert np.all(arr2 == arr[inner_slice])
if rast.nodata is not None:
assert np.all(arr[inner_slice][np.diag_indices(dst_arr.shape[0])] == dst_nodata)
arr[inner_slice][np.diag_indices(dst_arr.shape[0])] = rast.nodata
assert np.all(arr[inner_slice] == dst_arr)
outer_mask = np.ones(fp.shape, bool)
outer_mask[inner_slice] = False
assert np.all(arr[outer_mask] == dst_nodata)
示例7: compute_outflow_pdf
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def compute_outflow_pdf(self):
"""
Lifetime model. The method compute outflow_pdf returns an array year-by-cohort of the probability of a item added to stock in year m (aka cohort m) leaves in in year n. This value equals pdf(n,m).
This is the only method for the inflow-driven model where the lifetime distribution directly enters the computation. All other stock variables are determined by mass balance.
The shape of the output pdf array is NoofYears * NoofYears, but the meaning is years by age-cohorts.
The method does nothing if the pdf alreay exists.
"""
if self.pdf is None:
self.compute_sf() # computation of pdfs moved to this method: compute survival functions sf first, then calculate pdfs from sf.
self.pdf = np.zeros((len(self.t), len(self.t)))
self.pdf[np.diag_indices(len(self.t))] = np.ones(len(self.t)) - self.sf.diagonal(0)
for m in range(0,len(self.t)):
self.pdf[np.arange(m+1,len(self.t)),m] = -1 * np.diff(self.sf[np.arange(m,len(self.t)),m])
return self.pdf
else:
# pdf already exists
return self.pdf
示例8: _initialize_error_cov_diagonal
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def _initialize_error_cov_diagonal(self, scalar=False):
# Initialize the parameters
self.parameters['error_cov'] = 1 if scalar else self.k_endog
# Setup fixed components of state space matrices
# Setup indices of state space matrices
k_endog = self.k_endog
k_factors = self.k_factors
idx = np.diag_indices(k_endog)
if self.error_order > 0:
matrix = 'state_cov'
idx = (idx[0] + k_factors, idx[1] + k_factors)
else:
matrix = 'obs_cov'
self._idx_error_cov = (matrix,) + idx
示例9: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def __init__(self, one_body, two_body, constant=0.):
if two_body.dtype != numpy.float:
raise ValueError('Two-body tensor has invalid dtype. Expected {} '
'but was {}'.format(numpy.float, two_body.dtype))
if not numpy.allclose(two_body, two_body.T):
raise ValueError('Two-body tensor must be symmetric.')
if not numpy.allclose(one_body, one_body.T.conj()):
raise ValueError('One-body tensor must be Hermitian.')
# Move the diagonal of two_body to one_body
diag_indices = numpy.diag_indices(one_body.shape[0])
one_body[diag_indices] += two_body[diag_indices]
numpy.fill_diagonal(two_body, 0.)
self.one_body = one_body
self.two_body = two_body
self.constant = constant
示例10: test_antidiagonal
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def test_antidiagonal(self):
m, n = (3, 3)
Q = numpy.zeros((m, n), dtype=complex)
Q[0, 2] = 1.
Q[1, 1] = 1.
Q[2, 0] = 1.
givens_rotations, V, diagonal = givens_decomposition(Q)
# There should be no Givens rotations
self.assertEqual(givens_rotations, list())
# VQ should equal the diagonal
VQ = V.dot(Q)
D = numpy.zeros((m, n), dtype=complex)
D[numpy.diag_indices(m)] = diagonal
for i in range(n):
for j in range(n):
self.assertAlmostEqual(VQ[i, j], D[i, j])
示例11: test_square
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def test_square(self):
m, n = (3, 3)
# Obtain a random matrix of orthonormal rows
Q = random_unitary_matrix(n)
Q = Q[:m, :]
Q = Q[:m, :]
# Get Givens decomposition of Q
givens_rotations, V, diagonal = givens_decomposition(Q)
# There should be no Givens rotations
self.assertEqual(givens_rotations, list())
# Compute V * Q * U^\dagger
W = V.dot(Q)
# Construct the diagonal matrix
D = numpy.zeros((m, n), dtype=complex)
D[numpy.diag_indices(m)] = diagonal
# Assert that W and D are the same
for i in range(m):
for j in range(n):
self.assertAlmostEqual(D[i, j], W[i, j])
示例12: diag_indices_from
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def diag_indices_from(arr):
"""
Return the indices to access the main diagonal of an n-dimensional array.
See `diag_indices` for full details.
Args:
arr (cupy.ndarray): At least 2-D.
.. seealso:: :func:`numpy.diag_indices_from`
"""
if not isinstance(arr, cupy.ndarray):
raise TypeError("Argument must be cupy.ndarray")
if not arr.ndim >= 2:
raise ValueError("input array must be at least 2-d")
# For more than d=2, the strided formula is only valid for arrays with
# all dimensions equal, so we check first.
if not cupy.all(cupy.diff(arr.shape) == 0):
raise ValueError("All dimensions of input must be of equal length")
return diag_indices(arr.shape[0], arr.ndim)
示例13: test_orth
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def test_orth(self):
numpy.random.seed(10)
n = 100
a = numpy.random.random((n,n))
s = numpy.dot(a.T, a)
c = orth.lowdin(s)
self.assertTrue(numpy.allclose(reduce(numpy.dot, (c.T, s, c)),
numpy.eye(n)))
x1 = numpy.dot(a, c)
x2 = orth.vec_lowdin(a)
d = numpy.dot(x1.T,x2)
d[numpy.diag_indices(n)] = 0
self.assertAlmostEqual(numpy.linalg.norm(d), 0, 9)
self.assertAlmostEqual(numpy.linalg.norm(c), 36.56738258719514, 9)
self.assertAlmostEqual(abs(c).sum(), 2655.5580057303964, 7)
示例14: test_schmidt
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def test_schmidt(self):
numpy.random.seed(10)
n = 100
a = numpy.random.random((n,n))
s = numpy.dot(a.T, a)
c = orth.schmidt(s)
self.assertTrue(numpy.allclose(reduce(numpy.dot, (c.T, s, c)),
numpy.eye(n)))
x1 = numpy.dot(a, c)
x2 = orth.vec_schmidt(a)
d = numpy.dot(x1.T,x2)
d[numpy.diag_indices(n)] = 0
self.assertAlmostEqual(numpy.linalg.norm(d), 0, 9)
self.assertAlmostEqual(numpy.linalg.norm(c), 36.56738258719514, 9)
self.assertAlmostEqual(abs(c).sum(), 1123.2089785000373, 7)
示例15: _from_rhf_init_dm
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import diag_indices [as 別名]
def _from_rhf_init_dm(dm, breaksym=True):
dma = dm * .5
dm = scipy.linalg.block_diag(dma, dma)
if breaksym:
nao = dma.shape[0]
idx, idy = numpy.diag_indices(nao)
dm[idx+nao,idy] = dm[idx,idy+nao] = dma.diagonal() * .05
return dm