本文整理匯總了Python中numpy.kron方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.kron方法的具體用法?Python numpy.kron怎麽用?Python numpy.kron使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.kron方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: non_redundant_rotation_generators
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def non_redundant_rotation_generators(
rhf_objective: RestrictedHartreeFockObjective) -> List[FermionOperator]: # testpragma: no cover
# coverage: ignore
"""
Generate the fermionic representation of all non-redundant rotation
generators for restricted Hartree-fock
:param rhf_objective: openfermioncirq.experiments.hfvqe.RestrictedHartreeFock object
:return: list of fermionic generators.
"""
rotation_generators = []
for p in range(rhf_objective.nocc * rhf_objective.nvirt):
grad_params = np.zeros(rhf_objective.nocc * rhf_objective.nvirt)
grad_params[p] = 1
kappa_spatial_orbital = rhf_params_to_matrix(grad_params,
len(rhf_objective.occ) + len(rhf_objective.virt),
rhf_objective.occ,
rhf_objective.virt)
p0 = np.array([[1, 0], [0, 1]])
kappa_spin_orbital = np.kron(kappa_spatial_orbital, p0)
fermion_op = get_one_body_fermion_operator(kappa_spin_orbital)
rotation_generators.append(fermion_op)
return rotation_generators
示例2: energy_from_opdm
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def energy_from_opdm(opdm, constant, one_body_tensor, two_body_tensor):
"""
Evaluate the energy of an opdm assuming the 2-RDM is opdm ^ opdm
:param opdm: single spin-component of the full spin-orbital opdm.
:param constant: constant shift to the Hamiltonian. Commonly this is the
nuclear repulsion energy.
:param one_body_tensor: spatial one-body integrals
:param two_body_tensor: spatial two-body integrals
:return:
"""
spin_opdm = np.kron(opdm, np.eye(2))
spin_tpdm = 2 * wedge(spin_opdm, spin_opdm, (1, 1), (1, 1))
molecular_hamiltonian = generate_hamiltonian(constant=constant,
one_body_integrals=one_body_tensor,
two_body_integrals=two_body_tensor)
rdms = InteractionRDM(spin_opdm, spin_tpdm)
return rdms.expectation(molecular_hamiltonian).real
示例3: test_simulate_trotter_simulate_controlled
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def test_simulate_trotter_simulate_controlled(
hamiltonian, time, initial_state, exact_state, order, n_steps,
algorithm, result_fidelity):
n_qubits = openfermion.count_qubits(hamiltonian)
qubits = cirq.LineQubit.range(n_qubits)
control = cirq.LineQubit(-1)
zero = [1, 0]
one = [0, 1]
start_state = (numpy.kron(zero, initial_state)
+ numpy.kron(one, initial_state)) / numpy.sqrt(2)
circuit = cirq.Circuit(simulate_trotter(
qubits, hamiltonian, time, n_steps, order, algorithm, control))
final_state = circuit.final_wavefunction(start_state)
correct_state = (numpy.kron(zero, initial_state)
+ numpy.kron(one, exact_state)) / numpy.sqrt(2)
assert fidelity(final_state, correct_state) > result_fidelity
# Make sure the time wasn't too small
assert fidelity(final_state, start_state) < 0.95 * result_fidelity
示例4: state_to_stdmx
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def state_to_stdmx(state_vec):
"""
Convert a state vector into a density matrix.
Parameters
----------
state_vec : list or tuple
State vector in the standard (sigma-z) basis.
Returns
-------
numpy.ndarray
A density matrix of shape (d,d), corresponding to the pure state
given by the length-`d` array, `state_vec`.
"""
st_vec = state_vec.view(); st_vec.shape = (len(st_vec), 1) # column vector
dm_mx = _np.kron(_np.conjugate(_np.transpose(st_vec)), st_vec)
return dm_mx # density matrix in standard (sigma-z) basis
示例5: unitary_to_process_mx
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def unitary_to_process_mx(U):
"""
Compute the super-operator which acts on (row)-vectorized
density matrices from a unitary operator (matrix) U which
acts on state vectors. This super-operator is given by
the tensor product of U and conjugate(U), i.e. kron(U,U.conj).
Parameters
----------
U : numpy array
The unitary matrix which acts on state vectors.
Returns
-------
numpy array
The super-operator process matrix.
"""
# U -> kron(U,Uc) since U rho U_dag -> kron(U,Uc)
# since AXB --row-vectorize--> kron(A,B.T)*vec(X)
return _np.kron(U, _np.conjugate(U))
示例6: dictionary_from_transform
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def dictionary_from_transform(transform, n, K, normalized=True, inverse=True):
"""
Builds a Dictionary matrix from a given transform
Args:
transform: A valid transform (e.g. Haar, DCT-II)
n: number of rows transform dictionary
K: number of columns transform dictionary
normalized: If True, the columns will be l2-normalized
inverse: Uses the inverse transform (as usually needed in applications)
Returns:
Dictionary build from the Kronecker-Delta of the transform applied to the identity.
"""
H = np.zeros((K, n))
for i in range(n):
v = np.zeros(n)
v[i] = 1.0
H[:, i] = transform(v, sampling_factor=K)
if inverse:
H = H.T
return np.kron(H.T, H.T)
示例7: random_dictionary
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def random_dictionary(n, K, normalized=True, seed=None):
"""
Build a random dictionary matrix with K = n
Args:
n: square of signal dimension
K: square of desired dictionary atoms
normalized: If true, columns will be l2-normalized
seed: Random seed
Returns:
Random dictionary
"""
if seed:
np.random.seed(seed)
H = np.random.rand(n, K) * 255
if normalized:
for k in range(K):
H[:, k] *= 1 / np.linalg.norm(H[:, k])
return np.kron(H, H)
示例8: middle_bond_hamiltonian
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def middle_bond_hamiltonian(Jx, Jz, hx, hz, L):
"""" Returns the spin operators sigma_x and sigma_z for L sites."""
sx = np.array([[0., 1.], [1., 0.]])
sz = np.array([[1., 0.], [0., -1.]])
H_bond = Jx * np.kron(sx, sx) + Jz * np.kron(sz, sz)
H_bond = H_bond + hx / 2 * np.kron(sx, np.eye(2)) + hx / 2 * np.kron(np.eye(2), sx)
H_bond = H_bond + hz / 2 * np.kron(sz, np.eye(2)) + hz / 2 * np.kron(np.eye(2), sz)
H_bond = H_bond.reshape(2, 2, 2, 2).transpose(0, 2, 1, 3).reshape(4, 4) #i1 i2 i1' i2' -->
U, s, V = np.linalg.svd(H_bond)
M1 = np.dot(U, np.diag(s)).reshape(2, 2, 1, 4).transpose(2, 3, 0, 1)
M2 = V.reshape(4, 1, 2, 2)
M0 = np.tensordot(np.tensordot([1], [1], axes=0), np.eye(2), axes=0)
W = []
for i in range(L):
if i == L / 2 - 1:
W.append(M1)
elif i == L / 2:
W.append(M2)
else:
W.append(M0)
return W
示例9: init_H_bonds
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def init_H_bonds(self):
"""Initialize `H_bonds` hamiltonian.
Called by __init__().
"""
sx, sz, id = self.sigmax, self.sigmaz, self.id
d = self.d
nbonds = self.L - 1 if self.bc == 'finite' else self.L
H_list = []
for i in range(nbonds):
gL = gR = 0.5 * self.g
if self.bc == 'finite':
if i == 0:
gL = self.g
if i + 1 == self.L - 1:
gR = self.g
H_bond = -self.J * np.kron(sx, sx) - gL * np.kron(sz, id) - gR * np.kron(id, sz)
# H_bond has legs ``i, j, i*, j*``
H_list.append(np.reshape(H_bond, [d, d, d, d]))
self.H_bonds = H_list
# (note: not required for TEBD)
示例10: test_Kroneker
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def test_Kroneker(par):
"""Dot-test, inversion and comparison with np.kron for Kronecker operator
"""
np.random.seed(10)
G1 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
G2 = np.random.normal(0, 10, (par['ny'], par['nx'])).astype(par['dtype'])
x = np.ones(par['nx']**2) + par['imag']*np.ones(par['nx']**2)
Kop = Kronecker(MatrixMult(G1, dtype=par['dtype']),
MatrixMult(G2, dtype=par['dtype']),
dtype=par['dtype'])
assert dottest(Kop, par['ny']**2, par['nx']**2,
complexflag=0 if par['imag'] == 0 else 3)
xlsqr = lsqr(Kop, Kop * x, damp=1e-20, iter_lim=300, show=0)[0]
assert_array_almost_equal(x, xlsqr, decimal=2)
# Comparison with numpy
assert_array_almost_equal(np.kron(G1, G2), Kop * np.eye(par['nx']**2),
decimal=3)
示例11: graymap
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def graymap(x):
x = x[..., np.newaxis]
return np.concatenate([x, x, x], axis=-1)*0.5+0.5
# --------------------------------------
# Visualizing data
# --------------------------------------
# def visualize(x,colormap,name):
#
# N = len(x)
# assert(N <= 16)
#
# x = colormap(x/np.abs(x).max())
#
# # Create a mosaic and upsample
# x = x.reshape([1, N, 29, 29, 3])
# x = np.pad(x, ((0, 0), (0, 0), (2, 2), (2, 2), (0, 0)), 'constant', constant_values=1)
# x = x.transpose([0, 2, 1, 3, 4]).reshape([1*33, N*33, 3])
# x = np.kron(x, np.ones([2, 2, 1]))
#
# PIL.Image.fromarray((x*255).astype('byte'), 'RGB').save(name)
示例12: plt_vector
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def plt_vector(x, colormap, num_headers):
N = len(x)
assert (N <= 16)
len_x = 54
len_y = num_headers
# size = int(np.ceil(np.sqrt(len(x[0]))))
length = len_y*len_x
data = np.zeros((N, length), dtype=np.float64)
data[:, :x.shape[1]] = x
data = colormap(data / np.abs(data).max())
# data = data.reshape([1, N, size, size, 3])
data = data.reshape([1, N, len_y, len_x, 3])
# data = np.pad(data, ((0, 0), (0, 0), (2, 2), (2, 2), (0, 0)), 'constant', constant_values=1)
data = data.transpose([0, 2, 1, 3, 4]).reshape([1 * (len_y), N * (len_x), 3])
return data
# data = np.kron(data, np.ones([2, 2, 1])) # scales
示例13: test_perform
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def test_perform(self):
if not imported_scipy:
raise SkipTest('kron tests need the scipy package to be installed')
for shp0 in [(2,), (2, 3), (2, 3, 4), (2, 3, 4, 5)]:
x = tensor.tensor(dtype='floatX',
broadcastable=(False,) * len(shp0))
a = numpy.asarray(self.rng.rand(*shp0)).astype(config.floatX)
for shp1 in [(6,), (6, 7), (6, 7, 8), (6, 7, 8, 9)]:
if len(shp0) + len(shp1) == 2:
continue
y = tensor.tensor(dtype='floatX',
broadcastable=(False,) * len(shp1))
f = function([x, y], kron(x, y))
b = self.rng.rand(*shp1).astype(config.floatX)
out = f(a, b)
# Newer versions of scipy want 4 dimensions at least,
# so we have to add a dimension to a and flatten the result.
if len(shp0) + len(shp1) == 3:
scipy_val = scipy.linalg.kron(
a[numpy.newaxis, :], b).flatten()
else:
scipy_val = scipy.linalg.kron(a, b)
utt.assert_allclose(out, scipy_val)
示例14: cov_params_default
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def cov_params_default(self): # p.296 (7.2.21)
# Sigma_co described on p. 287
beta = self.beta
if self.det_coef_coint.size > 0:
beta = vstack((beta, self.det_coef_coint))
dt = self.deterministic
num_det = ("co" in dt) + ("lo" in dt)
num_det += (self.seasons-1) if self.seasons else 0
if self.exog is not None:
num_det += self.exog.shape[1]
b_id = scipy.linalg.block_diag(beta,
np.identity(self.neqs * (self.k_ar-1) +
num_det))
y_lag1 = self._y_lag1
b_y = beta.T.dot(y_lag1)
omega11 = b_y.dot(b_y.T)
omega12 = b_y.dot(self._delta_x.T)
omega21 = omega12.T
omega22 = self._delta_x.dot(self._delta_x.T)
omega = np.bmat([[omega11, omega12],
[omega21, omega22]]).A
mat1 = b_id.dot(inv(omega)).dot(b_id.T)
return np.kron(mat1, self.sigma_u)
示例15: _orth_cov
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import kron [as 別名]
def _orth_cov(self):
# Lutkepohl 3.7.8
Ik = np.eye(self.neqs)
PIk = np.kron(self.P.T, Ik)
H = self.H
covs = self._empty_covm(self.periods + 1)
for i in range(self.periods + 1):
if i == 0:
apiece = 0
else:
Ci = np.dot(PIk, self.G[i-1])
apiece = chain_dot(Ci, self.cov_a, Ci.T)
Cibar = np.dot(np.kron(Ik, self.irfs[i]), H)
bpiece = chain_dot(Cibar, self.cov_sig, Cibar.T) / self.T
# Lutkepohl typo, cov_sig correct
covs[i] = apiece + bpiece
return covs