本文整理匯總了Python中numpy.real_if_close方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.real_if_close方法的具體用法?Python numpy.real_if_close怎麽用?Python numpy.real_if_close使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.real_if_close方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: updateinternals
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def updateinternals(self, e, epos, mask=None):
"""Update any internals given that electron e moved to epos. mask is a Boolean array
which allows us to update only certain walkers"""
# MAY want to vectorize later if it really hangs here, shouldn't!
s = int(e >= self._nelec[0])
if mask is None:
mask = [True] * epos.configs.shape[0]
eeff = e - s * self._nelec[0]
ao = np.real_if_close(
self._mol.eval_gto(self.pbc_str + "GTOval_sph", epos.configs), tol=1e4
)
self._aovals[:, e, :] = ao
mo = ao.dot(self.parameters[self._coefflookup[s]])
mo_vals = mo[:, self._det_occup[s]]
det_ratio, self._inverse[s][mask, :, :, :] = sherman_morrison_ms(
eeff, self._inverse[s][mask, :, :, :], mo_vals[mask, :]
)
self._updateval(det_ratio, s, mask)
示例2: laplacian
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def laplacian(self, e, epos):
""" Compute the laplacian Psi/ Psi. """
s = int(e >= self._nelec[0])
ao = np.real_if_close(
self._mol.eval_gto(self.pbc_str + "GTOval_sph_deriv2", epos.configs)[
[0, 4, 7, 9]
],
tol=1e4,
)
molap = np.dot(
[ao[0], ao[1:].sum(axis=0)], self.parameters[self._coefflookup[s]]
)
molap_vals = self._testrow(e, molap[1][:, self._det_occup[s]])
testvalue = self._testrow(e, molap[0][:, self._det_occup[s]])
return molap_vals / testvalue
示例3: stdmx_to_vec
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def stdmx_to_vec(m, basis):
"""
Convert a matrix in the standard basis to
a vector in the Pauli basis.
Parameters
----------
m : numpy array
The matrix, shape 2x2 (1Q) or 4x4 (2Q)
Returns
-------
numpy array
The vector, length 4 or 16 respectively.
"""
assert(len(m.shape) == 2 and m.shape[0] == m.shape[1])
basis = Basis.cast(basis, m.shape[0]**2)
v = _np.empty((basis.size, 1))
for i, mx in enumerate(basis.elements):
if basis.real:
v[i, 0] = _np.real(_mt.trace(_np.dot(mx, m)))
else:
v[i, 0] = _np.real_if_close(_mt.trace(_np.dot(mx, m)))
return v
示例4: invpowerspd
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def invpowerspd(self, n):
'''autocovariance from spectral density
scaling is correct, but n needs to be large for numerical accuracy
maybe padding with zero in fft would be faster
without slicing it returns 2-sided autocovariance with fftshift
>>> ArmaFft([1, -0.5], [1., 0.4], 40).invpowerspd(2**8)[:10]
array([ 2.08 , 1.44 , 0.72 , 0.36 , 0.18 , 0.09 ,
0.045 , 0.0225 , 0.01125 , 0.005625])
>>> ArmaFft([1, -0.5], [1., 0.4], 40).acovf(10)
array([ 2.08 , 1.44 , 0.72 , 0.36 , 0.18 , 0.09 ,
0.045 , 0.0225 , 0.01125 , 0.005625])
'''
hw = self.fftarma(n)
return np.real_if_close(fft.ifft(hw*hw.conj()), tol=200)[:n]
示例5: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def __init__(self, cum, name='Edgeworth expanded normal', **kwds):
if len(cum) < 2:
raise ValueError("At least two cumulants are needed.")
self._coef, self._mu, self._sigma = self._compute_coefs_pdf(cum)
self._herm_pdf = HermiteE(self._coef)
if self._coef.size > 2:
self._herm_cdf = HermiteE(-self._coef[1:])
else:
self._herm_cdf = lambda x: 0.
# warn if pdf(x) < 0 for some values of x within 4 sigma
r = np.real_if_close(self._herm_pdf.roots())
r = (r - self._mu) / self._sigma
if r[(np.imag(r) == 0) & (np.abs(r) < 4)].any():
mesg = 'PDF has zeros at %s ' % r
warnings.warn(mesg, RuntimeWarning)
kwds.update({'name': name,
'momtype': 0}) # use pdf, not ppf in self.moment()
super(ExpandedNormal, self).__init__(**kwds)
示例6: test_graph_embed
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def test_graph_embed(self, setup_eng, tol):
"""Test that embedding a traceless adjacency matrix A
results in the property Amat/A = c J, where c is a real constant,
and J is the all ones matrix"""
N = 3
eng, prog = setup_eng(3)
with prog.context as q:
ops.GraphEmbed(A) | q
state = eng.run(prog).state
Amat = eng.backend.circuit.Amat()
# check that the matrix Amat is constructed to be of the form
# Amat = [[B^\dagger, 0], [0, B]]
assert np.allclose(Amat[:N, :N], Amat[N:, N:].conj().T, atol=tol)
assert np.allclose(Amat[:N, N:], np.zeros([N, N]), atol=tol)
assert np.allclose(Amat[N:, :N], np.zeros([N, N]), atol=tol)
ratio = np.real_if_close(Amat[N:, N:] / A)
ratio /= ratio[0, 0]
assert np.allclose(ratio, np.ones([N, N]), atol=tol)
示例7: _recast_dressed_eigendata
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def _recast_dressed_eigendata(self, dressed_eigendata):
"""
Parameters
----------
dressed_eigendata: list of tuple(evals, qutip evecs)
Returns
-------
SpectrumData
"""
evals_count = self.evals_count
energy_table = np.empty(shape=(self.param_count, evals_count), dtype=np.float_)
state_table = [] # for dressed states, entries are Qobj
for j in range(self.param_count):
energy_table[j] = np.real_if_close(dressed_eigendata[j][0])
state_table.append(dressed_eigendata[j][1])
specdata = storage.SpectrumData(energy_table, system_params={}, param_name=self.param_name,
param_vals=self.param_vals, state_table=state_table)
return specdata
示例8: spectral_radius
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def spectral_radius(self):
"""Compute the spectral radius of the matrix of l1 norm of Hawkes
kernels.
Notes
-----
If the spectral radius is greater that 1, the hawkes process is not
stable
"""
get_norm = np.vectorize(lambda kernel: kernel.get_norm())
norms = get_norm(self.kernels)
# It might happens that eig returns a complex number but with a
# negligible complex part, in this case we keep only the real part
spectral_radius = max(eig(norms)[0])
spectral_radius = np.real_if_close(spectral_radius)
return spectral_radius
示例9: test_displaced_single_mode_state_hafnian
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def test_displaced_single_mode_state_hafnian(self, sample_func):
"""Test the sampling routines by comparing the photon number frequencies and the exact
probability distribution of a single mode coherent state
"""
n_samples = 1000
n_cut = 6
sigma = np.identity(2)
mean = 10 * np.array([0.1, 0.25])
samples = sample_func(sigma, samples=n_samples, mean=mean, cutoff=n_cut)
probs = np.real_if_close(
np.array([density_matrix_element(mean, sigma, [i], [i]) for i in range(n_cut)])
)
freq, _ = np.histogram(samples[:, 0], bins=np.arange(0, n_cut + 1))
rel_freq = freq / n_samples
assert np.allclose(
rel_freq, probs, rtol=rel_tol / np.sqrt(n_samples), atol=rel_tol / np.sqrt(n_samples)
)
示例10: test_displaced_two_mode_state_hafnian
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def test_displaced_two_mode_state_hafnian(self, sample_func):
"""Test the sampling routines by comparing the photon number frequencies and the exact
probability distribution of a two mode coherent state
"""
n_samples = 1000
n_cut = 6
sigma = np.identity(4)
mean = 5 * np.array([0.1, 0.25, 0.1, 0.25])
samples = sample_func(sigma, samples=n_samples, mean=mean, cutoff=n_cut)
# samples = hafnian_sample_classical_state(sigma, mean = mean, samples = n_samples)
probs = np.real_if_close(
np.array(
[
[density_matrix_element(mean, sigma, [i, j], [i, j]) for i in range(n_cut)]
for j in range(n_cut)
]
)
)
freq, _, _ = np.histogram2d(samples[:, 1], samples[:, 0], bins=np.arange(0, n_cut + 1))
rel_freq = freq / n_samples
assert np.allclose(
rel_freq, probs, rtol=rel_tol / np.sqrt(n_samples), atol=rel_tol / np.sqrt(n_samples)
)
示例11: rectify_evecs
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def rectify_evecs(eigs):
"""
eigs: output of linalg.eig
normalizes evecs by L1 norm, truncates small complex components,
ensures things are positive
"""
evecs = eigs[1].T
l1_norm = np.abs(evecs).sum(axis=1)
norm_evecs = evecs / l1_norm[:, np.newaxis]
real_evals = [np.around(np.real_if_close(l), decimals=5) for l in eigs[0]]
real_evecs = []
for v in norm_evecs:
real_v = np.real_if_close(v)
if (real_v < 0).all():
real_v *= -1
real_evecs.append(real_v)
# skip sorting for now: argsort is pain because numpy will typecase to complex arr
# desc_idx = np.argsort(real_evals)[::-1]
# return real_evals[desc_idx], real_evecs[desc_idx]
return real_evals, real_evecs
示例12: purity
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def purity(rho: np.ndarray, dim_renorm=False, tol: float = 1000) -> float:
"""
Calculates the purity :math:`P = tr[ρ^2]` of a quantum state ρ.
As stated above lower value of the purity depends on the dimension of ρ's Hilbert space. For
some applications this can be undesirable. For this reason we introduce an optional dimensional
renormalization flag with the following behavior
If the dimensional renormalization flag is FALSE (default) then 1/dim ≤ P ≤ 1.
If the dimensional renormalization flag is TRUE then 0 ≤ P ≤ 1.
where dim is the dimension of ρ's Hilbert space.
:param rho: Is a dim by dim positive matrix with unit trace.
:param dim_renorm: Boolean, default False.
:param tol: Tolerance in machine epsilons for np.real_if_close.
:return: P the purity of the state.
"""
p = np.trace(rho @ rho)
if dim_renorm:
dim = rho.shape[0]
p = (dim / (dim - 1.0)) * (p - 1.0 / dim)
return np.ndarray.item(np.real_if_close(p, tol))
示例13: impurity
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def impurity(rho: np.ndarray, dim_renorm=False, tol: float = 1000) -> float:
"""
Calculates the impurity (or linear entropy) :math:`L = 1 - tr[ρ^2]` of a quantum state ρ.
As stated above the lower value of the impurity depends on the dimension of ρ's Hilbert space.
For some applications this can be undesirable. For this reason we introduce an optional
dimensional renormalization flag with the following behavior
If the dimensional renormalization flag is FALSE (default) then 0 ≤ L ≤ 1/dim.
If the dimensional renormalization flag is TRUE then 0 ≤ L ≤ 1.
where dim is the dimension of ρ's Hilbert space.
:param rho: Is a dim by dim positive matrix with unit trace.
:param dim_renorm: Boolean, default False.
:param tol: Tolerance in machine epsilons for np.real_if_close.
:return: L the impurity of the state.
"""
imp = 1 - np.trace(rho @ rho)
if dim_renorm:
dim = rho.shape[0]
imp = (dim / (dim - 1.0)) * imp
return np.ndarray.item(np.real_if_close(imp, tol))
示例14: fidelity
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def fidelity(rho: np.ndarray, sigma: np.ndarray, tol: float = 1000) -> float:
r"""
Computes the fidelity :math:`F(\rho, \sigma)` between two quantum states rho and sigma.
If the states are pure the expression reduces to
.. math::
F(|psi>,|phi>) = |<psi|phi>|^2
The fidelity obeys :math:`0 ≤ F(\rho, \sigma) ≤ 1`, where
:math:`F(\rho, \sigma)=1 iff \rho = \sigma`.
:param rho: Is a dim by dim positive matrix with unit trace.
:param sigma: Is a dim by dim positive matrix with unit trace.
:param tol: Tolerance in machine epsilons for np.real_if_close.
:return: Fidelity which is a scalar.
"""
sqrt_rho = sqrtm_psd(rho)
fid = (np.trace(sqrtm_psd(sqrt_rho @ sigma @ sqrt_rho))) ** 2
return np.ndarray.item(np.real_if_close(fid, tol))
示例15: hilbert_schmidt_ip
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import real_if_close [as 別名]
def hilbert_schmidt_ip(A: np.ndarray, B: np.ndarray, tol: float = 1000) -> float:
r"""
Computes the Hilbert-Schmidt (HS) inner product between two operators A and B.
This inner product is defined as
.. math::
HS = (A|B) = Tr[A^\dagger B]
where :math:`|B) = vec(B)` and :math:`(A|` is the dual vector to :math:`|A)`.
:param A: Is a dim by dim positive matrix with unit trace.
:param B: Is a dim by dim positive matrix with unit trace.
:param tol: Tolerance in machine epsilons for np.real_if_close.
:return: HS inner product which is a scalar.
"""
hs_ip = np.trace(np.matmul(np.transpose(np.conj(A)), B))
return np.ndarray.item(np.real_if_close(hs_ip, tol))