• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python numpy.complex_函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中numpy.complex_函数的典型用法代码示例。如果您正苦于以下问题:Python complex_函数的具体用法?Python complex_怎么用?Python complex_使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了complex_函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_init

    def test_init(self):
        import numpy as np
        import math
        import sys

        assert np.intp() == np.intp(0)
        assert np.intp("123") == np.intp(123)
        raises(TypeError, np.intp, None)
        assert np.float64() == np.float64(0)
        assert math.isnan(np.float64(None))
        assert np.bool_() == np.bool_(False)
        assert np.bool_("abc") == np.bool_(True)
        assert np.bool_(None) == np.bool_(False)
        assert np.complex_() == np.complex_(0)
        # raises(TypeError, np.complex_, '1+2j')
        assert math.isnan(np.complex_(None))
        for c in ["i", "I", "l", "L", "q", "Q"]:
            assert np.dtype(c).type().dtype.char == c
        for c in ["l", "q"]:
            assert np.dtype(c).type(sys.maxint) == sys.maxint
        for c in ["L", "Q"]:
            assert np.dtype(c).type(sys.maxint + 42) == sys.maxint + 42
        assert np.float32(np.array([True, False])).dtype == np.float32
        assert type(np.float32(np.array([True]))) is np.ndarray
        assert type(np.float32(1.0)) is np.float32
        a = np.array([True, False])
        assert np.bool_(a) is a
开发者ID:GaussDing,项目名称:pypy,代码行数:27,代码来源:test_scalar.py


示例2: fun

	def fun(self,t, args):
		"""Maximum likelihood function to be minimized.

		:param numpy_array t: t values.
		:param numpy_array args: first entry contains correlation counts, second the corresponding basis as string.
		:param numpy_array args: PSIs, all possible basis as Jones vectors.

		:return: Function value. See for further information D. F. V. James et al. Phys. Rev. A, 64, 052312 (2001).
		:rtype: numpy float
		"""
		corr_counts=args[0]
		basis=args[1]
		PSI=args[2]
		nbrOfElements=len(basis)

		rho_phys = self.rho_phys(t)

		#Estimate NormFactor
		estNormFactor=[]

		for i in range(len(corr_counts)):
			estNormFactor.append(np.dot(np.dot(np.conj(PSI[i]), rho_phys),PSI[i]))

		NormFactor=np.sum(corr_counts)/np.sum(estNormFactor)

		#Optimize density matrix
		BraRoh_physKet = np.complex_(np.zeros(nbrOfElements))

		for i in range(nbrOfElements):
			rhoket = np.array(np.dot(rho_phys,PSI[i]).flat) #Convert 2d to 1d array with flat
			BraRoh_physKet[i] = np.complex_(np.dot(np.conj(PSI[i]), rhoket))

		return np.real(np.sum((NormFactor*BraRoh_physKet-corr_counts)**2.0/(2.0*NormFactor*BraRoh_physKet)))
开发者ID:afognini,项目名称:Tomography,代码行数:33,代码来源:Tomography.py


示例3: test_init

 def test_init(self):
     import numpy as np
     import math
     import sys
     assert np.intp() == np.intp(0)
     assert np.intp('123') == np.intp(123)
     raises(TypeError, np.intp, None)
     assert np.float64() == np.float64(0)
     assert math.isnan(np.float64(None))
     assert np.bool_() == np.bool_(False)
     assert np.bool_('abc') == np.bool_(True)
     assert np.bool_(None) == np.bool_(False)
     assert np.complex_() == np.complex_(0)
     #raises(TypeError, np.complex_, '1+2j')
     assert math.isnan(np.complex_(None))
     for c in ['i', 'I', 'l', 'L', 'q', 'Q']:
         assert np.dtype(c).type().dtype.char == c
     for c in ['l', 'q']:
         assert np.dtype(c).type(sys.maxint) == sys.maxint
     for c in ['L', 'Q']:
         assert np.dtype(c).type(sys.maxint + 42) == sys.maxint + 42
     assert np.float32(np.array([True, False])).dtype == np.float32
     assert type(np.float32(np.array([True]))) is np.ndarray
     assert type(np.float32(1.0)) is np.float32
     a = np.array([True, False])
     assert np.bool_(a) is a
开发者ID:abhinavthomas,项目名称:pypy,代码行数:26,代码来源:test_scalar.py


示例4: fft_deriv

def fft_deriv ( var ):
    #on_error, 2
                 
    n = numpy.size(var)

    F = old_div(numpy.fft.fft(var),n)  #different definition between IDL - python
                 
    imag = numpy.complex(0.0, 1.0)
    imag = numpy.complex_(imag)

    F[0] = 0.0
          
                
    if (n % 2) == 0 :
      # even number
        for i in range (1, old_div(n,2)) :
          a = imag*2.0*numpy.pi*numpy.float(i)/numpy.float(n)
          F[i] = F[i] * a         # positive frequencies
          F[n-i] = - F[n-i] * a   # negative frequencies
           
        F[old_div(n,2)] = F[old_div(n,2)] * (imag*numpy.pi)
    else:
      # odd number
        for i in range (1, old_div((n-1),2)+1) :
          a = imag*2.0*numpy.pi*numpy.float(i)/numpy.float(n)
          F[i] = F[i] * a
          F[n-i] = - F[n-i] * a 
        
    

    result = numpy.fft.ifft(F)*n  #different definition between IDL - python
    
      
    return result 
开发者ID:JosephThomasParker,项目名称:BOUT-dev,代码行数:34,代码来源:fft_deriv.py


示例5: test_gamma

	def test_gamma(self,gamma):
		"""Test if :math:`\Gamma_i, {i=1,...,16}` matrices are properly defined.

		:param array GAMMA: Gamma matrices.

		Test for:

			:math:`\mathrm{Tr}(\Gamma_i\Gamma_j)= \delta_{i,j}`

		:return: True if equation fullfilled for all gamma matrices, False otherwise.
		:rtype: bool
		"""

		#initialize empty test matrix
		test_matrix = np.complex_(np.zeros((16,16)))

		for i in range(len(gamma)):
			for j in range(len(gamma)):
				test_matrix[i,j] = np.trace(np.dot(gamma[i], gamma[j]))

		diag_matrix = np.diag(np.ones(16))


		test_result = np.einsum('ij,ij',test_matrix - diag_matrix, test_matrix - diag_matrix)-16

		if np.abs(test_result) < 10**-6:
			return True
		else:
			False
开发者ID:afognini,项目名称:Tomography,代码行数:29,代码来源:Tomography.py


示例6: __new__

 def __new__(cls, x=0):
     if isinstance(x, afnumpy.ndarray):
         return x.astype(cls)
     elif isinstance(x, numbers.Number):
         return numpy.complex_(x)
     else:
         return afnumpy.array(x).astype(cls)
开发者ID:Brainiarc7,项目名称:afnumpy,代码行数:7,代码来源:dtypes.py


示例7: test_against_cmath

    def test_against_cmath(self):
        import cmath, sys

        # cmath.asinh is broken in some versions of Python, see
        # http://bugs.python.org/issue1381
        broken_cmath_asinh = False
        if sys.version_info < (2, 6):
            broken_cmath_asinh = True

        points = [-1 - 1j, -1 + 1j, +1 - 1j, +1 + 1j]
        name_map = {
            "arcsin": "asin",
            "arccos": "acos",
            "arctan": "atan",
            "arcsinh": "asinh",
            "arccosh": "acosh",
            "arctanh": "atanh",
        }
        atol = 4 * np.finfo(np.complex).eps
        for func in self.funcs:
            fname = func.__name__.split(".")[-1]
            cname = name_map.get(fname, fname)
            try:
                cfunc = getattr(cmath, cname)
            except AttributeError:
                continue
            for p in points:
                a = complex(func(np.complex_(p)))
                b = cfunc(p)

                if cname == "asinh" and broken_cmath_asinh:
                    continue

                assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b))
开发者ID:jarrodmillman,项目名称:numpy,代码行数:34,代码来源:test_umath.py


示例8: halo_transform

def halo_transform(image):

    na=image.shape[0]
    nb=image.shape[1]
    ko= 5.336
    delta = (2.*np.sqrt(-2.*np.log(.75)))/ko

    x=np.arange(nb)
    y=np.arange(na)
    x,y=np.meshgrid(x,y)
    if (nb % 2) == 0:
        x=(1.*x - (nb)/2.)/nb
        shiftx = (nb)/2.
    else:
       x= (1.*x - (nb-1)/2.)/nb 
       shiftx=(nb-1.)/2.+1

    if (na % 2) == 0:
        y=(1.*y-(na/2.))/na
        shifty=(na)/2.
    else:
        y= (1.*y - (na-1)/2.)/ na
        shifty=(na-1.)/2.+1

    #--------------Spectral Logarithm--------------------
    M=int(np.log(nb)/delta)
    a2= np.zeros(M)
    a2[0]=np.log(nb)

    for i in range(M-1):
        a2[i+1]=a2[i]-delta

    a2=np.exp(a2)
    tab_k = 1. / (a2)
    wt= np.complex_(np.zeros(((na,nb,M))))


    a= ko*a2

    imageFT= np.fft.fft2(image)
    #imageFT=np.fft.fftshift(image)
    imageFT= np.roll(imageFT,int( shiftx), axis=1)
    imageFT= np.roll(imageFT,int(shifty), axis=0)

    for j in range(M):
        uv = 0

        uv=np.exp(-0.5*((abs(a[j]*np.sqrt(x**2.+y**2.))**2.  - abs(ko))**2.))

        uv = uv * a[j]

        W1FT=imageFT*(uv)
        W1F2=np.roll(W1FT,int(shiftx), axis =1)
        W1F2=np.roll(W1F2,int(shifty),axis=0)
       #W1F2=np.fft.ifftshift(W1FT)
        W1=np.fft.ifft2(W1F2)
        wt[:,:,j]=wt[:,:,j]+ W1

    return wt, tab_k
开发者ID:ArloParker,项目名称:SummerProject2016,代码行数:59,代码来源:halo_transform.py


示例9: test_params_to_array_inconsistent_types

 def test_params_to_array_inconsistent_types(self):
     """
     Tests if an assertion error is raised when parameters of different
     types are passed in
     """
     guess_params_adj = self.guess_params
     guess_params_adj[-1] = np.complex_(guess_params_adj[-1])
     self.assertRaises(AssertionError, self.affine_obj.params_to_array,
                       guess_params_adj)
开发者ID:bartbkr,项目名称:affine,代码行数:9,代码来源:test_model.py


示例10: test_opt_gen_pred_coef_complex

 def test_opt_gen_pred_coef_complex(self):
     """
     Tests if complex values are return properly
     """
     # DOC: Need to make sure that the arrays are also np.complex
     guess_params = [np.complex_(el) for el in self.guess_params]
     params = self.affine_obj.params_to_array(guess_params)
     arrays_gpc = self.affine_obj.opt_gen_pred_coef(*params)
     for array in arrays_gpc:
         self.assertEqual(array.dtype, np.complex_)
开发者ID:bartbkr,项目名称:affine,代码行数:10,代码来源:test_model.py


示例11: imdct

    def imdct(self,y,i):
        """imdct: inverse mdct
            y(np.array) -> mdct signal
            i -> index frame size
        """
        # frame size
        L = self.sizes[i]
        # signal size
        N = y.size
        # Number of frequency channels
        K = L/2
        # Number of frames
        P = N/K

        # Reshape y
        tmp = y.reshape(P,K)
        y = np.zeros( (P,L) )
        y[:,:K] = tmp

        # Pre-twidle
        y = np.complex_(y)
        y *= np.tile(np.exp(1j*2.*np.pi*np.arange(L)*(L/2+1)/2./L), (P,1))

        # IFFT
        x = np.fft.ifft(y);

        # Post-twidle
        x *= np.tile(np.exp((1./2.)*1j*2*np.pi*(np.arange(L)+((L/2+1)/2.))/L),(P,1));

        # Windowing
        win = self.window(np.arange(L))
        winL = np.copy(win)
        winL[:L/4] = 0
        winL[L/4:L/2] = 1
        winR = np.copy(win)
        winR[L/2:3*L/4] = 1
        winR[3*L/4:] = 0
        x[0,:] *= winL
        x[1:-1,:] *= np.tile(win,(P-2,1))
        x[-1,:] *= winR

        # Real part & scaling
        x = np.sqrt(2./K)*L*x.real

        # Overlap and add
        b = np.repeat(np.arange(P),L)
        a = np.tile(np.arange(L),P) + b*K
        x = sparse.coo_matrix((x.ravel(),(b,a)),shape=(P,N+K)).sum(axis=0).A1

        # Cut edges
        return x[K/2:-K/2]
开发者ID:vince91,项目名称:audiofingerprint,代码行数:51,代码来源:mdct.py


示例12: construct_b_matrix

	def construct_b_matrix(self, PSI, GAMMA):
		"""Construct B matrix as in D. F. V. James et al. Phys. Rev. A, 64, 052312 (2001).

		:param array PSI: :math:`\psi_\\nu` vector with :math:`\\nu=1,...,16`, computed in __init__
		:param array GAMMA: :math:`\Gamma` matrices, computed in __init__

		:return: :math:`B_{\\nu,\mu} = \\langle \psi_\\nu \\rvert  \Gamma_\mu  \\lvert \psi_\\nu \\rangle`
		:rtype: numpy array
		"""

		B = np.complex_(np.zeros((16,16)))

		for i in range(16):
			for j in range(16):
				B[i,j] = np.dot(np.conj(PSI[i]) , np.dot(GAMMA[j], PSI[i]))
		return B
开发者ID:afognini,项目名称:Tomography,代码行数:16,代码来源:Tomography.py


示例13: from_csv

	def from_csv(cls, csv, delimiter="\t"):
		'''Constructs class instance from the given csv table. Is used in testing mode. Method is able to construct only 2d space. Is supposed to read tables produced by 'to_csv' method
		
			csv string: path to csv table
			delimiter string: csv table delimiter
			
			Return Grid: class instance
		'''		
		def _converter(l):
			a = l.strip().split(delimiter)
			a = [x.replace("|", "+") + "j" for x in a]
			return delimiter.join(a);
			
		array = np.genfromtxt((_converter(x) for x in open(csv)), dtype=str, delimiter=delimiter)
		array = np.complex_(array)
		encoding_table = [dict([(x,x) for x in range(array.shape[0])]), dict([(x,x) for x in range(array.shape[1])])]
		return cls(array, encoding_table);
开发者ID:afilipch,项目名称:nrlbio,代码行数:17,代码来源:LRGFDR.py


示例14: besselj

def besselj(n, z):
    """Bessel function of first kind of order n at kr.
    Wraps scipy.special.jn(n, z).

    Parameters
    ----------
    n : array_like
       Order
    z: array_like
       Argument

    Returns
    -------
    J : array_like
       Values of Bessel function of order n at position z
    """
    return scy.jv(n, _np.complex_(z))
开发者ID:QULab,项目名称:sound_field_analysis-py,代码行数:17,代码来源:sph.py


示例15: test_against_cmath

    def test_against_cmath(self):
        import cmath, sys

        points = [-1-1j, -1+1j, +1-1j, +1+1j]
        name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
                    'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
        atol = 4*np.finfo(np.complex).eps
        for func in self.funcs:
            fname = func.__name__.split('.')[-1]
            cname = name_map.get(fname, fname)
            try:
                cfunc = getattr(cmath, cname)
            except AttributeError:
                continue
            for p in points:
                a = complex(func(np.complex_(p)))
                b = cfunc(p)
                assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s"%(fname, p, a, b))
开发者ID:Fematich,项目名称:article_browser,代码行数:18,代码来源:test_umath.py


示例16: test_generic_roundtrip

 def test_generic_roundtrip(self):
     values = [
         np.int_(1),
         np.int32(-2),
         np.float_(2.5),
         np.nan,
         -np.inf,
         np.inf,
         np.datetime64('2014-01-01'),
         np.str_('foo'),
         np.unicode_('bar'),
         np.object_({'a': 'b'}),
         np.complex_(1 - 2j)
     ]
     for value in values:
         decoded = self.roundtrip(value)
         assert_equal(decoded, value)
         self.assertTrue(isinstance(decoded, type(value)))
开发者ID:jaraco,项目名称:jsonpickle,代码行数:18,代码来源:test_ext.py


示例17: test_dataframe_roundtrip

 def test_dataframe_roundtrip(self):
     if self.should_skip:
         return self.skip('pandas is not importable')
     df = pd.DataFrame({
         'an_int': np.int_([1, 2, 3]),
         'a_float': np.float_([2.5, 3.5, 4.5]),
         'a_nan': np.array([np.nan] * 3),
         'a_minus_inf': np.array([-np.inf] * 3),
         'an_inf': np.array([np.inf] * 3),
         'a_str': np.str_('foo'),
         'a_unicode': np.unicode_('bar'),
         'date': np.array([np.datetime64('2014-01-01')] * 3),
         'complex': np.complex_([1 - 2j, 2 - 1.2j, 3 - 1.3j]),
         # TODO: the following dtypes are not currently supported.
         # 'object': np.object_([{'a': 'b'}]*3),
     })
     decoded_df = self.roundtrip(df)
     assert_frame_equal(decoded_df, df)
开发者ID:davvid,项目名称:jsonpickle,代码行数:18,代码来源:pandas_test.py


示例18: test_series_roundtrip

 def test_series_roundtrip(self):
     if self.should_skip:
         return self.skip('pandas is not importable')
     ser = pd.Series({
         'an_int': np.int_(1),
         'a_float': np.float_(2.5),
         'a_nan': np.nan,
         'a_minus_inf': -np.inf,
         'an_inf': np.inf,
         'a_str': np.str_('foo'),
         'a_unicode': np.unicode_('bar'),
         'date': np.datetime64('2014-01-01'),
         'complex': np.complex_(1 - 2j),
         # TODO: the following dtypes are not currently supported.
         # 'object': np.object_({'a': 'b'}),
     })
     decoded_ser = self.roundtrip(ser)
     assert_series_equal(decoded_ser, ser)
开发者ID:davvid,项目名称:jsonpickle,代码行数:18,代码来源:pandas_test.py


示例19: frequencies

def frequencies(mol, H):
  
  mol = mol.copy()
  mol.to_angstrom()

  # 3. build mass-weighted Hessian matrix
  natom = mol.natom
  m     = np.repeat(mol.masses, 3) ** -0.5
  M     = np.broadcast_to(m, (3*natom, 3*natom)).T
  tH    = M.T * H * M

  # 4. compute eigenvalues and eigenvectors of the mass-weighted Hessian matrix
  k, tQ  = np.linalg.eigh(tH)

  # 5. un-mass-weight the normal coordinates
  Q = M * tQ

  # 6. get wavenumbers from a.u. force constants
  hartree2J = 4.3597443e-18
  amu2kg = 1.6605389e-27
  bohr2m = 5.2917721e-11
  c = 29979245800.0 # speed of light in cm/s
  v = np.sqrt(np.complex_(k)) * np.sqrt(hartree2J/(amu2kg*bohr2m*bohr2m))/(c*2*np.pi)

  ret = ''
  fmt = '{:2s}' + '{: >15.10f}'*6 + '\n'
  for A in range(3*natom):
    if np.isreal(v[A]):
      ret += '{:d}\n{: >7.2f}  cm^-1\n'.format(natom, np.absolute(v[A]))
    else:
      ret += '{:d}\n{: >7.2f}i cm^-1\n'.format(natom, np.absolute(v[A]))
    for B in range(natom):
      label      = mol.labels[B]
      x ,  y,  z = mol.geom[B]
      dx, dy, dz = Q[3*B:3*B+3, A]
      ret += fmt.format(label, x, y, z, dx, dy, dz)
    ret += '\n'

  # 7. save the normal modes to a file
  outfile = open('modes.xyz', 'w+')
  outfile.write(ret)
  outfile.close()

  return v, Q
开发者ID:CCQC,项目名称:summer-program,代码行数:44,代码来源:frequencies.py


示例20: rho_phys

	def rho_phys(self, t):
		"""Positive semidefinite matrix based on t values.

		:param numpy_array t: tvalues

		:return: A positive semidefinite matrix which is an estimation of the actual density matrix.
		:rtype: numpy matrix
		"""
		T = np.complex_(np.matrix([
						[t[0], 				0, 				0, 				0],
						[t[4]+1j*t[5], 		t[1], 			0, 				0],
						[t[10]+1j*t[11], 	t[6]+1j*t[7], 	t[2], 			0],
						[t[14]+1j*t[15], 	t[12]+1j*t[13], t[8]+1j*t[9], 	t[3]]
						]))

		TdagT = np.dot(T.conj().T , T)
		norm = np.trace(TdagT)

		return TdagT/norm
开发者ID:afognini,项目名称:Tomography,代码行数:19,代码来源:Tomography.py



注:本文中的numpy.complex_函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python numpy.compress函数代码示例发布时间:2022-05-27
下一篇:
Python numpy.complex64函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap