def vdot(a, b):
"""Returns the dot product of two vectors.
The input arrays are flattened into 1-D vectors and then it performs inner
product of these vectors.
Args:
a (cupy.ndarray): The first argument.
b (cupy.ndarray): The second argument.
Returns:
cupy.ndarray: Zero-dimensional array of the dot product result.
.. seealso:: :func:`numpy.vdot`
"""
if a.size != b.size:
raise ValueError('Axis dimension mismatch')
if a.dtype.kind == 'c':
a = a.conj()
return core.tensordot_core(a, b, None, 1, 1, a.size, ())
python类vdot()的实例源码
def test_sandwich(nr_sites, local_dim, rank, rgen, dtype):
mps = factory.random_mpa(nr_sites, local_dim, rank,
randstate=rgen, dtype=dtype, normalized=True)
mps2 = factory.random_mpa(nr_sites, local_dim, rank,
randstate=rgen, dtype=dtype, normalized=True)
mpo = factory.random_mpa(nr_sites, [local_dim] * 2, rank,
randstate=rgen, dtype=dtype)
mpo.canonicalize()
mpo /= mp.trace(mpo)
vec = mps.to_array().ravel()
op = mpo.to_array_global().reshape([local_dim**nr_sites] * 2)
res_arr = np.vdot(vec, np.dot(op, vec))
res_mpo = mp.inner(mps, mp.dot(mpo, mps))
res_sandwich = mp.sandwich(mpo, mps)
assert_almost_equal(res_mpo, res_arr)
assert_almost_equal(res_sandwich, res_arr)
vec2 = mps2.to_array().ravel()
res_arr = np.vdot(vec2, np.dot(op, vec))
res_mpo = mp.inner(mps2, mp.dot(mpo, mps))
res_sandwich = mp.sandwich(mpo, mps, mps2)
assert_almost_equal(res_mpo, res_arr)
assert_almost_equal(res_sandwich, res_arr)
def test_adjoint(dtype, shearletSystem):
"""Validate the adjoint."""
shape = tuple(shearletSystem['size'])
# load data
X = np.random.randn(*shape).astype(dtype)
# decomposition
coeffs = pyshearlab.SLsheardec2D(X, shearletSystem)
# adjoint
Xadj = pyshearlab.SLshearadjoint2D(coeffs, shearletSystem)
assert Xadj.dtype == X.dtype
assert Xadj.shape == X.shape
# <Ax, Ax> should equal <x, AtAx>
assert (pytest.approx(np.vdot(coeffs, coeffs), rel=1e-3, abs=0) ==
np.vdot(X, Xadj))
def test_adjoint_of_inverse(dtype, shearletSystem):
"""Validate the adjoint of the inverse."""
X = np.random.randn(*shearletSystem['size']).astype(dtype)
# decomposition
coeffs = pyshearlab.SLsheardec2D(X, shearletSystem)
# reconstruction
Xrec = pyshearlab.SLshearrec2D(coeffs, shearletSystem)
Xrecadj = pyshearlab.SLshearrecadjoint2D(Xrec, shearletSystem)
assert Xrecadj.dtype == X.dtype
assert Xrecadj.shape == coeffs.shape
# <A^-1x, A^-1x> = <A^-* A^-1 x, x>.
assert (pytest.approx(np.vdot(Xrec, Xrec), rel=1e-3, abs=0) ==
np.vdot(Xrecadj, coeffs))
def test_basic(self):
dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
dt_complex = np.typecodes['Complex']
# test real
a = np.eye(3)
for dt in dt_numeric + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test complex
a = np.eye(3) * 1j
for dt in dt_complex + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test boolean
b = np.eye(3, dtype=np.bool)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), True)
def test_vdot_uncontiguous(self):
for size in [2, 1000]:
# Different sizes match different branches in vdot.
a = np.zeros((size, 2, 2))
b = np.zeros((size, 2, 2))
a[:, 0, 0] = np.arange(size)
b[:, 0, 0] = np.arange(size) + 1
# Make a and b uncontiguous:
a = a[..., 0]
b = b[..., 0]
assert_equal(np.vdot(a, b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy()),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy(), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy('F'), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy('F')),
np.vdot(a.flatten(), b.flatten()))
def test_basic(self):
dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
dt_complex = np.typecodes['Complex']
# test real
a = np.eye(3)
for dt in dt_numeric + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test complex
a = np.eye(3) * 1j
for dt in dt_complex + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test boolean
b = np.eye(3, dtype=np.bool)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), True)
def test_vdot_uncontiguous(self):
for size in [2, 1000]:
# Different sizes match different branches in vdot.
a = np.zeros((size, 2, 2))
b = np.zeros((size, 2, 2))
a[:, 0, 0] = np.arange(size)
b[:, 0, 0] = np.arange(size) + 1
# Make a and b uncontiguous:
a = a[..., 0]
b = b[..., 0]
assert_equal(np.vdot(a, b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy()),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy(), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy('F'), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy('F')),
np.vdot(a.flatten(), b.flatten()))
def vdot(a, b):
"""Returns the dot product of two vectors.
The input arrays are flattened into 1-D vectors and then it performs inner
product of these vectors.
Args:
a (cupy.ndarray): The first argument.
b (cupy.ndarray): The second argument.
Returns:
cupy.ndarray: Zero-dimensional array of the dot product result.
.. seealso:: :func:`numpy.vdot`
"""
if a.size != b.size:
raise ValueError('Axis dimension mismatch')
return core.tensordot_core(a, b, None, 1, 1, a.size, ())
test_multiarray.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def test_basic(self):
dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
dt_complex = np.typecodes['Complex']
# test real
a = np.eye(3)
for dt in dt_numeric + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test complex
a = np.eye(3) * 1j
for dt in dt_complex + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test boolean
b = np.eye(3, dtype=np.bool)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), True)
test_multiarray.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 34
收藏 0
点赞 0
评论 0
def test_vdot_uncontiguous(self):
for size in [2, 1000]:
# Different sizes match different branches in vdot.
a = np.zeros((size, 2, 2))
b = np.zeros((size, 2, 2))
a[:, 0, 0] = np.arange(size)
b[:, 0, 0] = np.arange(size) + 1
# Make a and b uncontiguous:
a = a[..., 0]
b = b[..., 0]
assert_equal(np.vdot(a, b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy()),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy(), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy('F'), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy('F')),
np.vdot(a.flatten(), b.flatten()))
def rotation_matrix(a, b):
"""
Create rotation matrix to rotate vector a into b.
After http://math.stackexchange.com/a/476311
Parameters
----------
a,b
xyz-vectors
"""
v = np.cross(a, b)
sin = np.linalg.norm(v)
if sin == 0:
return np.identity(3)
cos = np.vdot(a, b)
vx = np.mat([[0, -v[2], v[1]], [v[2], 0., -v[0]], [-v[1], v[0], 0.]])
R = np.identity(3) + vx + vx * vx * (1 - cos) / (sin ** 2)
return R
def test_basic(self):
dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
dt_complex = np.typecodes['Complex']
# test real
a = np.eye(3)
for dt in dt_numeric + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test complex
a = np.eye(3) * 1j
for dt in dt_complex + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test boolean
b = np.eye(3, dtype=np.bool)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), True)
def test_vdot_uncontiguous(self):
for size in [2, 1000]:
# Different sizes match different branches in vdot.
a = np.zeros((size, 2, 2))
b = np.zeros((size, 2, 2))
a[:, 0, 0] = np.arange(size)
b[:, 0, 0] = np.arange(size) + 1
# Make a and b uncontiguous:
a = a[..., 0]
b = b[..., 0]
assert_equal(np.vdot(a, b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy()),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy(), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy('F'), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy('F')),
np.vdot(a.flatten(), b.flatten()))
def test_basic(self):
dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
dt_complex = np.typecodes['Complex']
# test real
a = np.eye(3)
for dt in dt_numeric + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test complex
a = np.eye(3) * 1j
for dt in dt_complex + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test boolean
b = np.eye(3, dtype=np.bool)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), True)
def test_vdot_uncontiguous(self):
for size in [2, 1000]:
# Different sizes match different branches in vdot.
a = np.zeros((size, 2, 2))
b = np.zeros((size, 2, 2))
a[:, 0, 0] = np.arange(size)
b[:, 0, 0] = np.arange(size) + 1
# Make a and b uncontiguous:
a = a[..., 0]
b = b[..., 0]
assert_equal(np.vdot(a, b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy()),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy(), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy('F'), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy('F')),
np.vdot(a.flatten(), b.flatten()))
def test_basic(self):
dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
dt_complex = np.typecodes['Complex']
# test real
a = np.eye(3)
for dt in dt_numeric + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test complex
a = np.eye(3) * 1j
for dt in dt_complex + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test boolean
b = np.eye(3, dtype=np.bool)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), True)
def test_vdot_uncontiguous(self):
for size in [2, 1000]:
# Different sizes match different branches in vdot.
a = np.zeros((size, 2, 2))
b = np.zeros((size, 2, 2))
a[:, 0, 0] = np.arange(size)
b[:, 0, 0] = np.arange(size) + 1
# Make a and b uncontiguous:
a = a[..., 0]
b = b[..., 0]
assert_equal(np.vdot(a, b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy()),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy(), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy('F'), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy('F')),
np.vdot(a.flatten(), b.flatten()))
def get_expectation_value(self, terms_dict, ids):
"""
Return the expectation value of a qubit operator w.r.t. qubit ids.
Args:
terms_dict (dict): Operator dictionary (see QubitOperator.terms)
ids (list[int]): List of qubit ids upon which the operator acts.
Returns:
Expectation value
"""
expectation = 0.
current_state = _np.copy(self._state)
for (term, coefficient) in terms_dict:
self._apply_term(term, ids)
delta = coefficient * _np.vdot(current_state, self._state).real
expectation += delta
self._state = _np.copy(current_state)
return expectation
def berry_curvature(H,kx,ky,mu,d=10**-6):
'''
Calculate the Berry curvature of the occupied bands for a Hamiltonian with the given chemical potential using the Kubo formula.
Parameters
----------
H : callable
Input function which returns the Hamiltonian as a 2D array.
kx,ky : float
The two parameters which specify the 2D point at which the Berry curvature is to be calculated.
They are also the input parameters to be conveyed to the function H.
mu : float
The chemical potential.
d : float, optional
The spacing to be used to calculate the derivatives.
Returns
-------
float
The calculated Berry curvature for function H at point kx,ky with chemical potential mu.
'''
result=0
Vx=(H(kx+d,ky)-H(kx-d,ky))/(2*d)
Vy=(H(kx,ky+d)-H(kx,ky-d))/(2*d)
Es,Evs=eigh(H(kx,ky))
for n in xrange(Es.shape[0]):
for m in xrange(Es.shape[0]):
if Es[n]<=mu and Es[m]>mu:
result-=2*(np.vdot(np.dot(Vx,Evs[:,n]),Evs[:,m])*np.vdot(Evs[:,m],np.dot(Vy,Evs[:,n]))/(Es[n]-Es[m])**2).imag
return result
def FBFMPOS(engine,app):
'''
This method calculates the profiles of spin-1-excitation states.
'''
result=[]
table=engine.config.table(mask=['spin','nambu'])
U1,U2,vs=engine.basis.U1,engine.basis.U2,sl.eigh(engine.matrix(k=app.k),eigvals_only=False)[1]
for i,index in enumerate(sorted(table,key=table.get)):
result.append([i])
gs=np.vdot(U2[table[index],:,:].reshape(-1),U2[table[index],:,:].reshape(-1))*(1 if engine.basis.polarization=='up' else -1)
dw=optrep(HP.FQuadratic(1.0,(index.replace(spin=0,nambu=HP.CREATION),index.replace(spin=0,nambu=HP.ANNIHILATION)),seqs=(table[index],table[index])),app.k,engine.basis)
up=optrep(HP.FQuadratic(1.0,(index.replace(spin=1,nambu=HP.CREATION),index.replace(spin=1,nambu=HP.ANNIHILATION)),seqs=(table[index],table[index])),app.k,engine.basis)
for pos in app.ns or (0,):
result[-1].append((np.vdot(vs[:,pos],up.dot(vs[:,pos]))-np.vdot(vs[:,pos],dw.dot(vs[:,pos]))-gs)*(-1 if engine.basis.polarization=='up' else 1))
result=np.asarray(result)
assert nl.norm(np.asarray(result).imag)<HP.RZERO
result=result.real
name='%s_%s'%(engine,app.name)
if app.savedata: np.savetxt('%s/%s.dat'%(engine.dout,name),result)
if app.plot: app.figure('L',result,'%s/%s'%(engine.dout,name),legend=['Level %s'%n for n in app.ns or (0,)])
if app.returndata: return result
def overlap(*args):
'''
Calculate the overlap between two vectors or among a matrix and two vectors.
Usage:
* ``overlap(vector1,vector2)``, with
vector1,vector2: 1d ndarray
The vectors between which the overlap is to calculate.
* ``overlap(vector1,matrix,vector2)``, with
vector1,vector2: 1d ndarray
The ket and bra in the overlap.
matrix: 2d ndarray-like
The matrix between the two vectors.
'''
assert len(args) in (2,3)
if len(args)==2:
return np.vdot(args[0],args[1])
else:
return np.vdot(args[0],args[1].dot(args[2]))
def test_basic(self):
dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
dt_complex = np.typecodes['Complex']
# test real
a = np.eye(3)
for dt in dt_numeric + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test complex
a = np.eye(3) * 1j
for dt in dt_complex + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test boolean
b = np.eye(3, dtype=np.bool)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), True)
def test_vdot_uncontiguous(self):
for size in [2, 1000]:
# Different sizes match different branches in vdot.
a = np.zeros((size, 2, 2))
b = np.zeros((size, 2, 2))
a[:, 0, 0] = np.arange(size)
b[:, 0, 0] = np.arange(size) + 1
# Make a and b uncontiguous:
a = a[..., 0]
b = b[..., 0]
assert_equal(np.vdot(a, b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy()),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy(), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy('F'), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy('F')),
np.vdot(a.flatten(), b.flatten()))
def test_inner_vec(nr_sites, local_dim, rank, rgen, dtype):
mp_psi1 = factory.random_mpa(nr_sites, local_dim, rank, randstate=rgen,
dtype=dtype)
psi1 = mp_psi1.to_array().ravel()
mp_psi2 = factory.random_mpa(nr_sites, local_dim, rank, randstate=rgen,
dtype=dtype)
psi2 = mp_psi2.to_array().ravel()
inner_np = np.vdot(psi1, psi2)
inner_mp = mp.inner(mp_psi1, mp_psi2)
assert_almost_equal(inner_mp, inner_np)
assert inner_mp.dtype == dtype
def test_refcount_vdot(self, level=rlevel):
# Changeset #3443
_assert_valid_refcount(np.vdot)
def test_vdot_array_order(self):
a = np.array([[1, 2], [3, 4]], order='C')
b = np.array([[1, 2], [3, 4]], order='F')
res = np.vdot(a, a)
# integer arrays are exact
assert_equal(np.vdot(a, b), res)
assert_equal(np.vdot(b, a), res)
assert_equal(np.vdot(b, b), res)
def get_shortest_bases_from_extented_bases(extended_bases, tolerance):
def mycmp(x, y):
return cmp(np.vdot(x,x), np.vdot(y,y))
basis = np.zeros((7,3), dtype=float)
basis[:4] = extended_bases
basis[4] = extended_bases[0] + extended_bases[1]
basis[5] = extended_bases[1] + extended_bases[2]
basis[6] = extended_bases[2] + extended_bases[0]
# Sort bases by the lengthes (shorter is earlier)
basis = sorted(basis, cmp=mycmp)
# Choose shortest and linearly independent three bases
# This algorithm may not be perfect.
for i in range(7):
for j in range(i+1, 7):
for k in range(j+1, 7):
if abs(np.linalg.det([basis[i],basis[j],basis[k]])) > tolerance:
return np.array([basis[i],basis[j],basis[k]])
print ("Delaunary reduction is failed.")
return basis[:3]
#
# Other tiny tools
#
def get_angles( lattice ):
"""
Get alpha, beta and gamma angles from lattice vectors.
>>> get_angles( np.diag([1,2,3]) )
(90.0, 90.0, 90.0)
"""
a, b, c = get_cell_parameters( lattice )
alpha = np.arccos(np.vdot(lattice[1], lattice[2]) / b / c ) / np.pi * 180
beta = np.arccos(np.vdot(lattice[2], lattice[0]) / c / a ) / np.pi * 180
gamma = np.arccos(np.vdot(lattice[0], lattice[1]) / a / b ) / np.pi * 180
return alpha, beta, gamma
def check_duality_gap(a, b, M, G, u, v, cost):
cost_dual = np.vdot(a, u) + np.vdot(b, v)
# Check that dual and primal cost are equal
np.testing.assert_almost_equal(cost_dual, cost)
[ind1, ind2] = np.nonzero(G)
# Check that reduced cost is zero on transport arcs
np.testing.assert_array_almost_equal((M - u.reshape(-1, 1) - v.reshape(1, -1))[ind1, ind2],
np.zeros(ind1.size))