本文整理汇总了Python中numpy.real方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.real方法的具体用法?Python numpy.real怎么用?Python numpy.real使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.real方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: quadrature_cc_1D
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def quadrature_cc_1D(N):
""" Computes the Clenshaw Curtis nodes and weights """
N = np.int(N)
if N == 1:
knots = 0
weights = 2
else:
n = N - 1
C = np.zeros((N,2))
k = 2*(1+np.arange(np.floor(n/2)))
C[::2,0] = 2/np.hstack((1, 1-k*k))
C[1,1] = -n
V = np.vstack((C,np.flipud(C[1:n,:])))
F = np.real(ifft(V, n=None, axis=0))
knots = F[0:N,1]
weights = np.hstack((F[0,0],2*F[1:n,0],F[n,0]))
return knots, weights
示例2: test_dft_real_2d
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def test_dft_real_2d(self):
"""
Test the real discrete Fourier transform function on one-dimensional
data. Non-trivial because we need to keep only some of the negative
frequencies.
"""
Nx, Ny = 16, 32
da = xr.DataArray(np.random.rand(Nx, Ny), dims=['x', 'y'],
coords={'x': range(Nx), 'y': range(Ny)})
dx = float(da.x[1] - da.x[0])
dy = float(da.y[1] - da.y[0])
daft = xrft.dft(da, real='x')
npt.assert_almost_equal(daft.values,
np.fft.rfftn(da.transpose('y','x')).transpose())
npt.assert_almost_equal(daft.values,
xrft.dft(da, dim=['y'], real='x'))
actual_freq_x = daft.coords['freq_x'].values
expected_freq_x = np.fft.rfftfreq(Nx, dx)
npt.assert_almost_equal(actual_freq_x, expected_freq_x)
actual_freq_y = daft.coords['freq_y'].values
expected_freq_y = np.fft.fftfreq(Ny, dy)
npt.assert_almost_equal(actual_freq_y, expected_freq_y)
示例3: classical_mds
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def classical_mds(self, D):
'''
Classical multidimensional scaling
Parameters
----------
D : square 2D ndarray
Euclidean Distance Matrix (matrix containing squared distances between points
'''
# Apply MDS algorithm for denoising
n = D.shape[0]
J = np.eye(n) - np.ones((n,n))/float(n)
G = -0.5*np.dot(J, np.dot(D, J))
s, U = np.linalg.eig(G)
# we need to sort the eigenvalues in decreasing order
s = np.real(s)
o = np.argsort(s)
s = s[o[::-1]]
U = U[:,o[::-1]]
S = np.diag(s)[0:self.dim,:]
self.X = np.dot(np.sqrt(S),U.T)
示例4: get_cosine_dist
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def get_cosine_dist(A, B):
B = np.reshape(B, (1, -1))
if A.shape[1] == 1:
A = np.hstack((A, np.zeros((A.shape[0], 1))))
B = np.hstack((B, np.zeros((B.shape[0], 1))))
aa = np.sum(np.multiply(A, A), axis=1).reshape(-1, 1)
bb = np.sum(np.multiply(B, B), axis=1).reshape(-1, 1)
ab = A @ B.T
# to avoid NaN for zero norm
aa[aa==0] = 1
bb[bb==0] = 1
D = np.real(np.ones((A.shape[0], B.shape[0])) - np.multiply((1/np.sqrt(np.kron(aa, bb.T))), ab))
return D
示例5: fft_convolve
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def fft_convolve(*images):
"""Use FFT's to convove an image with a kernel
Parameters
----------
images: list of array-like
A list of images to convolve.
Returns
-------
result: array
The convolution in pixel space of `img` with `kernel`.
"""
from autograd.numpy.numpy_boxes import ArrayBox
Images = [np.fft.fft2(np.fft.ifftshift(img)) for img in images]
if np.any([isinstance(img, ArrayBox) for img in images]):
Convolved = Images[0]
for img in Images[1:]:
Convolved = Convolved * img
else:
Convolved = np.prod(Images, 0)
convolved = np.fft.ifft2(Convolved)
return np.fft.fftshift(np.real(convolved))
示例6: diagonalize_asymm
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def diagonalize_asymm(H):
"""
Diagonalize a real, *asymmetric* matrix and return sorted results.
Return the eigenvalues and eigenvectors (column matrix)
sorted from lowest to highest eigenvalue.
"""
E,C = np.linalg.eig(H)
#if np.allclose(E.imag, 0*E.imag):
# E = np.real(E)
#else:
# print "WARNING: Eigenvalues are complex, will be returned as such."
idx = E.real.argsort()
E = E[idx]
C = C[:,idx]
return E,C
示例7: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def __init__(self,matr_multiply,xStart,inPreCon,nroots=1,tol=1e-10):
self.matrMultiply = matr_multiply
self.size = xStart.shape[0]
self.nEigen = min(nroots, self.size)
self.maxM = min(30, self.size)
self.maxOuterLoop = 10
self.tol = tol
#
# Creating initial guess and preconditioner
#
self.x0 = xStart.real.copy()
self.iteration = 0
self.totalIter = 0
self.converged = False
self.preCon = inPreCon.copy()
#
# Allocating other vectors
#
self.allocateVecs()
示例8: solveSubspace
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def solveSubspace(self):
w, v = scipy.linalg.eig(self.subH[:self.currentSize,:self.currentSize])
idx = w.real.argsort()
v = v[:,idx]
w = w[idx].real
#
imag_norm = np.linalg.norm(w.imag)
if imag_norm > 1e-12:
print(" *************************************************** ")
print(" WARNING IMAGINARY EIGENVALUE OF NORM %.15g " % (imag_norm))
print(" *************************************************** ")
#print "Imaginary norm eigenvectors = ", np.linalg.norm(v.imag)
#print "Imaginary norm eigenvalue = ", np.linalg.norm(w.imag)
#print "eigenvalues = ", w[:min(self.currentSize,7)]
#
self.sol[:self.currentSize] = v[:,self.ciEig]
self.evecs[:self.currentSize,:self.currentSize] = v
self.eigs[:self.currentSize] = w[:self.currentSize]
self.outeigs[:self.nEigen] = w[:self.nEigen]
self.cvEig = self.eigs[self.ciEig]
示例9: energy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def energy(self, configs):
r"""
Compute Coulomb energy for a set of configs.
.. math:: E_{\rm Coulomb} &= E_{\rm real+reciprocal}^{ee}
+ E_{\rm self+charged}^{ee}
\\&+ E_{\rm real+reciprocal}^{e\text{-ion}}
+ E_{\rm self+charged}^{e\text{-ion}}
\\&+ E_{\rm real+reciprocal}^{\text{ion-ion}}
+ E_{\rm self+charged}^{\text{ion-ion}}
Inputs:
configs: pyqmc PeriodicConfigs object of shape (nconf, nelec, ndim)
Returns:
ee: electron-electron part
ei: electron-ion part
ii: ion-ion part
"""
nelec = configs.configs.shape[1]
ee, ei = self.ewald_electron(configs)
ee += self.ee_const(nelec)
ei += self.ei_const(nelec)
ii = self.ion_ion + self.ii_const
return ee, ei, ii
示例10: damp
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def damp(self):
'''Natural frequency, damping ratio of system poles
Returns
-------
wn : array
Natural frequencies for each system pole
zeta : array
Damping ratio for each system pole
poles : array
Array of system poles
'''
poles = self.pole()
if isdtime(self, strict=True):
splane_poles = np.log(poles)/self.dt
else:
splane_poles = poles
wn = absolute(splane_poles)
Z = -real(splane_poles)/wn
return wn, Z, poles
示例11: _break_points
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def _break_points(num, den):
"""Extract break points over real axis and gains given these locations"""
# type: (np.poly1d, np.poly1d) -> (np.array, np.array)
dnum = num.deriv(m=1)
dden = den.deriv(m=1)
polynom = den * dnum - num * dden
real_break_pts = polynom.r
# don't care about infinite break points
real_break_pts = real_break_pts[num(real_break_pts) != 0]
k_break = -den(real_break_pts) / num(real_break_pts)
idx = k_break >= 0 # only positives gains
k_break = k_break[idx]
real_break_pts = real_break_pts[idx]
if len(k_break) == 0:
k_break = [0]
real_break_pts = den.roots
return k_break, real_break_pts
示例12: control_output
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def control_output(t, x, u, params):
# Get the controller parameters
longpole = params.get('longpole', -2.)
latpole1 = params.get('latpole1', -1/2 + sqrt(-7)/2)
latpole2 = params.get('latpole2', -1/2 - sqrt(-7)/2)
l = params.get('wheelbase', 3)
# Extract the system inputs
ex, ey, etheta, vd, phid = u
# Determine the controller gains
alpha1 = -np.real(latpole1 + latpole2)
alpha2 = np.real(latpole1 * latpole2)
# Compute and return the control law
v = -longpole * ex # Note: no feedfwd (to make plot interesting)
if vd != 0:
phi = phid + (alpha1 * l) / vd * ey + (alpha2 * l) / vd * etheta
else:
# We aren't moving, so don't turn the steering wheel
phi = phid
return np.array([v, phi])
# Define the controller as an input/output system
示例13: compact
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def compact(self, complex_coeff_tape=True):
"""
Generate a compact form of this polynomial designed for fast evaluation.
The resulting "tapes" can be evaluated using
:function:`opcalc.bulk_eval_compact_polys`.
Parameters
----------
complex_coeff_tape : bool, optional
Whether the `ctape` returned array is forced to be of complex type.
If False, the real part of all coefficients is taken (even if they're
complex).
Returns
-------
vtape, ctape : numpy.ndarray
These two 1D arrays specify an efficient means for evaluating this
polynomial.
"""
if complex_coeff_tape:
return self._rep.compact_complex()
else:
return self._rep.compact_real()
示例14: safe_bulk_eval_compact_polys
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def safe_bulk_eval_compact_polys(vtape, ctape, paramvec, dest_shape):
"""Typechecking wrapper for :function:`bulk_eval_compact_polys`.
The underlying method has two implementations: one for real-valued
`ctape`, and one for complex-valued. This wrapper will dynamically
dispatch to the appropriate implementation method based on the
type of `ctape`. If the type of `ctape` is known prior to calling,
it's slightly faster to call the appropriate implementation method
directly; if not.
"""
if _np.iscomplexobj(ctape):
ret = bulk_eval_compact_polys_complex(vtape, ctape, paramvec, dest_shape)
im_norm = _np.linalg.norm(_np.imag(ret))
if im_norm > 1e-6:
print("WARNING: norm(Im part) = {:g}".format(im_norm))
else:
ret = bulk_eval_compact_polys(vtape, ctape, paramvec, dest_shape)
return _np.real(ret)
示例15: absdiff
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import real [as 别名]
def absdiff(self, constant_value, separate_re_im=False):
"""
Returns a ReportableQty that is the (element-wise in the vector case)
difference between `constant_value` and this one given by:
`abs(self - constant_value)`.
"""
if separate_re_im:
re_v = _np.fabs(_np.real(self.value) - _np.real(constant_value))
im_v = _np.fabs(_np.imag(self.value) - _np.imag(constant_value))
if self.has_eb():
return (ReportableQty(re_v, _np.fabs(_np.real(self.errbar)), self.nonMarkovianEBs),
ReportableQty(im_v, _np.fabs(_np.imag(self.errbar)), self.nonMarkovianEBs))
else:
return ReportableQty(re_v), ReportableQty(im_v)
else:
v = _np.absolute(self.value - constant_value)
if self.has_eb():
return ReportableQty(v, _np.absolute(self.errbar), self.nonMarkovianEBs)
else:
return ReportableQty(v)