本文整理汇总了Python中numpy.trace方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.trace方法的具体用法?Python numpy.trace怎么用?Python numpy.trace使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.trace方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_circuit_generation_and_accuracy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def test_circuit_generation_and_accuracy():
for dim in range(2, 10):
qubits = cirq.LineQubit.range(dim)
u_generator = numpy.random.random(
(dim, dim)) + 1j * numpy.random.random((dim, dim))
u_generator = u_generator - numpy.conj(u_generator).T
assert numpy.allclose(-1 * u_generator, numpy.conj(u_generator).T)
unitary = scipy.linalg.expm(u_generator)
circuit = cirq.Circuit()
circuit.append(optimal_givens_decomposition(qubits, unitary))
fermion_generator = QubitOperator(()) * 0.0
for i, j in product(range(dim), repeat=2):
fermion_generator += jordan_wigner(
FermionOperator(((i, 1), (j, 0)), u_generator[i, j]))
true_unitary = scipy.linalg.expm(
get_sparse_operator(fermion_generator).toarray())
assert numpy.allclose(true_unitary.conj().T.dot(true_unitary),
numpy.eye(2 ** dim, dtype=complex))
test_unitary = cirq.unitary(circuit)
assert numpy.isclose(
abs(numpy.trace(true_unitary.conj().T.dot(test_unitary))), 2 ** dim)
示例2: read_neci_1dms
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def read_neci_1dms(fciqmcci, norb, nelec, filename='OneRDM.1', directory='.'):
''' Read spinned rdms, as they are in the neci output '''
f = open(os.path.join(directory, filename),'r')
dm1a = numpy.zeros((norb,norb))
dm1b = numpy.zeros((norb,norb))
for line in f.readlines():
linesp = line.split()
i, j = int(linesp[0]), int(linesp[1])
assert((i % 2) == (j % 2))
if i % 2 == 1:
# alpha
assert(all(x<norb for x in (i/2,j/2)))
dm1a[i/2,j/2] = float(linesp[2])
dm1a[j/2,i/2] = float(linesp[2])
else:
assert(all(x<norb for x in (i/2 - 1,j/2 - 1)))
dm1b[i/2 - 1,j/2 - 1] = float(linesp[2])
dm1b[j/2 - 1,i/2 - 1] = float(linesp[2])
f.close()
assert(numpy.allclose(dm1a.trace()+dm1b.trace(),sum(nelec)))
return dm1a, dm1b
示例3: is_normalized
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def is_normalized(self):
'''
Check if a basis is normalized, meaning that Tr(Bi Bi) = 1.0.
Available only to bases whose elements are *matrices* for now.
Returns
-------
bool
'''
if self.elndim == 2:
for i, mx in enumerate(self.elements):
t = _np.trace(_np.dot(mx, mx))
t = _np.real(t)
if not _np.isclose(t, 1.0): return False
return True
elif self.elndim == 1:
raise NotImplementedError("TODO: add code so this works for *vector*-valued bases too!")
else:
raise ValueError("I don't know what normalized means for elndim == %d!" % self.elndim)
示例4: tracenorm
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def tracenorm(A):
"""
Compute the trace norm of matrix A given by:
Tr( sqrt{ A^dagger * A } )
Parameters
----------
A : numpy array
The matrix to compute the trace norm of.
"""
if _np.linalg.norm(A - _np.conjugate(A.T)) < 1e-8:
#Hermitian, so just sum eigenvalue magnitudes
return _np.sum(_np.abs(_np.linalg.eigvals(A)))
else:
#Sum of singular values (positive by construction)
return _np.sum(_np.linalg.svd(A, compute_uv=False))
示例5: jtracedist
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def jtracedist(A, B, mxBasis='pp'): # Jamiolkowski trace distance: Tr(|J(A)-J(B)|)
"""
Compute the Jamiolkowski trace distance between operation matrices A and B,
given by:
D = 0.5 * Tr( sqrt{ (J(A)-J(B))^2 } )
where J(.) is the Jamiolkowski isomorphism map that maps a operation matrix
to it's corresponding Choi Matrix.
Parameters
----------
A, B : numpy array
The matrices to compute the distance between.
mxBasis : {'std', 'gm', 'pp', 'qt'} or Basis object
The source and destination basis, respectively. Allowed
values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp),
and Qutrit (qt) (or a custom basis object).
"""
JA = _jam.fast_jamiolkowski_iso_std(A, mxBasis)
JB = _jam.fast_jamiolkowski_iso_std(B, mxBasis)
return tracedist(JA, JB)
示例6: povm_jtracedist
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def povm_jtracedist(model, targetModel, povmlbl):
"""
Computes the Jamiolkowski trace distance between POVM maps using :func:`jtracedist`.
Parameters
----------
model, targetModel : Model
Models containing the two POVMs to compare.
povmlbl : str
The POVM label
Returns
-------
float
"""
povm_mx = get_povm_map(model, povmlbl)
target_povm_mx = get_povm_map(targetModel, povmlbl)
return jtracedist(povm_mx, target_povm_mx, targetModel.basis)
示例7: reflection_matrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def reflection_matrix(point, normal):
"""Return matrix to mirror at plane defined by point and normal vector.
>>> v0 = numpy.random.random(4) - 0.5
>>> v0[3] = 1.0
>>> v1 = numpy.random.random(3) - 0.5
>>> R = reflection_matrix(v0, v1)
>>> numpy.allclose(2., numpy.trace(R))
True
>>> numpy.allclose(v0, numpy.dot(R, v0))
True
>>> v2 = v0.copy()
>>> v2[:3] += v1
>>> v3 = v0.copy()
>>> v2[:3] -= v1
>>> numpy.allclose(v2, numpy.dot(R, v3))
True
"""
normal = unit_vector(normal[:3])
M = numpy.identity(4)
M[:3, :3] -= 2.0 * numpy.outer(normal, normal)
M[:3, 3] = (2.0 * numpy.dot(point[:3], normal)) * normal
return M
示例8: axisangle_from_rotm
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def axisangle_from_rotm(R):
# logarithm of rotation matrix
# R = R.reshape(-1,3,3)
# tr = np.trace(R, axis1=1, axis2=2)
# phi = np.arccos(np.clip((tr - 1) / 2, -1, 1))
# scale = np.zeros_like(phi)
# div = 2 * np.sin(phi)
# np.divide(phi, div, out=scale, where=np.abs(div) > 1e-6)
# A = (R - R.transpose(0,2,1)) * scale.reshape(-1,1,1)
# aa = np.stack((A[:,2,1], A[:,0,2], A[:,1,0]), axis=1)
# return aa.squeeze()
R = R.reshape(-1,3,3)
omega = np.empty((R.shape[0], 3), dtype=R.dtype)
omega[:,0] = R[:,2,1] - R[:,1,2]
omega[:,1] = R[:,0,2] - R[:,2,0]
omega[:,2] = R[:,1,0] - R[:,0,1]
r = np.linalg.norm(omega, axis=1).reshape(-1,1)
t = np.trace(R, axis1=1, axis2=2).reshape(-1,1)
omega = np.arctan2(r, t-1) * omega
aa = np.zeros_like(omega)
np.divide(omega, r, out=aa, where=r != 0)
return aa.squeeze()
示例9: reflection_matrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def reflection_matrix(point, normal):
"""Return matrix to mirror at plane defined by point and normal vector.
>>> v0 = numpy.random.random(4) - 0.5
>>> v0[3] = 1.0
>>> v1 = numpy.random.random(3) - 0.5
>>> R = reflection_matrix(v0, v1)
>>> numpy.allclose(2., numpy.trace(R))
True
>>> numpy.allclose(v0, numpy.dot(R, v0))
True
>>> v2 = v0.copy()
>>> v2[:3] += v1
>>> v3 = v0.copy()
>>> v2[:3] -= v1
>>> numpy.allclose(v2, numpy.dot(R, v3))
True
"""
normal = unit_vector(normal[:3])
M = numpy.identity(4)
M[:3, :3] -= 2.0 * numpy.outer(normal, normal)
M[:3, 3] = (2.0 * numpy.dot(point[:3], normal)) * normal
return M
示例10: compute_pose_error
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def compute_pose_error(gt, pred):
RE = 0
snippet_length = gt.shape[0]
scale_factor = np.sum(gt[:,:,-1] * pred[:,:,-1])/np.sum(pred[:,:,-1] ** 2)
ATE = np.linalg.norm((gt[:,:,-1] - scale_factor * pred[:,:,-1]).reshape(-1))
for gt_pose, pred_pose in zip(gt, pred):
# Residual matrix to which we compute angle's sin and cos
R = gt_pose[:,:3] @ np.linalg.inv(pred_pose[:,:3])
s = np.linalg.norm([R[0,1]-R[1,0],
R[1,2]-R[2,1],
R[0,2]-R[2,0]])
c = np.trace(R) - 1
# Note: we actually compute double of cos and sin, but arctan2 is invariant to scale
RE += np.arctan2(s,c)
return ATE/snippet_length, RE/snippet_length
示例11: reflection_matrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def reflection_matrix(point, normal):
"""Return matrix to mirror at plane defined by point and normal vector.
>>> v0 = numpy.random.random(4) - 0.5
>>> v0[3] = 1.
>>> v1 = numpy.random.random(3) - 0.5
>>> R = reflection_matrix(v0, v1)
>>> numpy.allclose(2, numpy.trace(R))
True
>>> numpy.allclose(v0, numpy.dot(R, v0))
True
>>> v2 = v0.copy()
>>> v2[:3] += v1
>>> v3 = v0.copy()
>>> v2[:3] -= v1
>>> numpy.allclose(v2, numpy.dot(R, v3))
True
"""
normal = unit_vector(normal[:3])
M = numpy.identity(4)
M[:3, :3] -= 2.0 * numpy.outer(normal, normal)
M[:3, 3] = (2.0 * numpy.dot(point[:3], normal)) * normal
return M
示例12: test_trace
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def test_trace():
rng = numpy.random.RandomState(utt.fetch_seed())
x = theano.tensor.matrix()
g = trace(x)
f = theano.function([x], g)
for shp in [(2, 3), (3, 2), (3, 3)]:
m = rng.rand(*shp).astype(config.floatX)
v = numpy.trace(m)
assert v == f(m)
xx = theano.tensor.vector()
ok = False
try:
trace(xx)
except TypeError:
ok = True
assert ok
示例13: test_reconstruction
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def test_reconstruction():
dim = 20
np.random.seed(42)
mat = np.random.random((dim, dim))
mat = 0.5 * (mat + mat.T)
test_mat = np.zeros_like(mat)
w, v = np.linalg.eigh(mat)
for i in range(w.shape[0]):
test_mat += w[i] * v[:, [i]].dot(v[:, [i]].T)
assert np.allclose(test_mat - mat, 0.0)
test_mat = fixed_trace_positive_projection(mat, np.trace(mat))
assert np.isclose(np.trace(test_mat), np.trace(mat))
w, v = np.linalg.eigh(test_mat)
assert np.all(w >= -(float(4.0E-15)))
mat = np.arange(16).reshape((4, 4))
mat = 0.5 * (mat + mat.T)
mat_tensor = map_to_tensor(mat)
trace_mat = np.trace(mat)
true_mat = fixed_trace_positive_projection(mat, trace_mat)
test_mat = map_to_matrix(fixed_trace_positive_projection(mat_tensor,
trace_mat))
assert np.allclose(true_mat, test_mat)
w, v = np.linalg.eigh(true_mat)
assert np.allclose(true_mat, fixed_trace_positive_projection(true_mat,
trace_mat))
示例14: test_rdm1
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def test_rdm1(self):
cell = pbcgto.Cell()
cell.atom = '''Al 0 0 0'''
cell.basis = 'gth-szv'
cell.pseudo = 'gth-pade'
cell.a = '''
2.47332919 0 1.42797728
0.82444306 2.33187713 1.42797728
0, 0, 2.85595455
'''
cell.unit = 'angstrom'
cell.build()
cell.verbose = 4
cell.incore_anyway = True
abs_kpts = cell.make_kpts((2, 1, 1), scaled_center=(.1, .2, .3))
kmf = pbcscf.KRHF(cell, abs_kpts)
kmf.conv_tol = 1e-12
kmf.kernel()
mp = pyscf.pbc.mp.kmp2.KMP2(kmf)
mp.kernel(with_t2=True)
self.assertAlmostEqual(mp.e_corr, -0.00162057921874043)
dm = mp.make_rdm1()
np.testing.assert_allclose(np.trace(dm[0]) + np.trace(dm[1]), 6)
for kdm in dm:
np.testing.assert_allclose(kdm, kdm.conj().T)
示例15: test_det_ovlp
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import trace [as 别名]
def test_det_ovlp(self):
s, x = mf.det_ovlp(mf.mo_coeff, mf.mo_coeff, mf.mo_occ, mf.mo_occ)
self.assertAlmostEqual(s, 1.000000000, 9)
self.assertAlmostEqual(numpy.trace(x[0]), mol.nelec[0]*1.000000000, 9)
self.assertAlmostEqual(numpy.trace(x[0]), mol.nelec[1]*1.000000000, 9)