from__future__importwith_statementimportsysfrompypy.conftestimportoptionfrompypy.interpreter.errorimportOperationErrorfrompypy.interpreter.gatewayimportinterp2appfrompypy.module.micronumpy.test.test_baseimportBaseNumpyAppTestfromrpython.rlib.rfloatimportisnan,isinf,copysignfromrpython.rlib.rcompleximportc_powdefrAlmostEqual(a,b,rel_err=2e-15,abs_err=5e-323,msg='',isnumpy=False):"""Fail if the two floating-point numbers are not almost equal. Determine whether floating-point values a and b are equal to within a (small) rounding error. The default values for rel_err and abs_err are chosen to be suitable for platforms where a float is represented by an IEEE 754 double. They allow an error of between 9 and 19 ulps. """# special values testingifisnan(a):ifisnan(b):returnTrue,''raiseAssertionError(msg+'%r should be nan'%(b,))ifisinf(a):ifa==b:returnTrue,''raiseAssertionError(msg+'finite result where infinity expected: '+ \
'expected %r, got %r'%(a,b))# if both a and b are zero, check whether they have the same sign# (in theory there are examples where it would be legitimate for a# and b to have opposite signs; in practice these hardly ever# occur).ifnotaandnotbandnotisnumpy:# only check it if we are running on top of CPython >= 2.6ifsys.version_info>=(2,6)andcopysign(1.,a)!=copysign(1.,b):raiseAssertionError(msg+ \
'zero has wrong sign: expected %r, got %r'%(a,b))# if a-b overflows, or b is infinite, return False. Again, in# theory there are examples where a is within a few ulps of the# max representable float, and then b could legitimately be# infinite. In practice these examples are rare.try:absolute_error=abs(b-a)exceptOverflowError:passelse:# test passes if either the absolute error or the relative# error is sufficiently small. The defaults amount to an# error of between 9 ulps and 19 ulps on an IEEE-754 compliant# machine.ifabsolute_error<=max(abs_err,rel_err*abs(a)):returnTrue,''raiseAssertionError(msg+ \
'%r and %r are not sufficiently close, %g > %g'%\
(a,b,absolute_error,max(abs_err,rel_err*abs(a))))defparse_testfile(fname):"""Parse a file with test values Empty lines or lines starting with -- are ignored yields id, fn, arg_real, arg_imag, exp_real, exp_imag """withopen(fname)asfp:forlineinfp:# skip comment lines and blank linesifline.startswith('--')ornotline.strip():continuelhs,rhs=line.split('->')id,fn,arg_real,arg_imag=lhs.split()rhs_pieces=rhs.split()exp_real,exp_imag=rhs_pieces[0],rhs_pieces[1]flags=rhs_pieces[2:]yield(id,fn,float(arg_real),float(arg_imag),float(exp_real),float(exp_imag),flags)classAppTestUfuncs(BaseNumpyAppTest):defsetup_class(cls):importosBaseNumpyAppTest.setup_class.im_func(cls)fname128=os.path.join(os.path.dirname(__file__),'complex_testcases.txt')fname64=os.path.join(os.path.dirname(__file__),'complex64_testcases.txt')cls.w_testcases128=cls.space.wrap(list(parse_testfile(fname128)))cls.w_testcases64=cls.space.wrap(list(parse_testfile(fname64)))cls.w_runAppDirect=cls.space.wrap(option.runappdirect)cls.w_isWindows=cls.space.wrap(os.name=='nt')ifcls.runappdirect:defcls_rAlmostEqual(space,*args,**kwargs):returnrAlmostEqual(*args,**kwargs)cls.w_rAlmostEqual=cls.space.wrap(cls_rAlmostEqual)defcls_c_pow(space,*args):returnc_pow(*args)cls.w_c_pow=cls.space.wrap(cls_c_pow)else:defcls_rAlmostEqual(space,__args__):args,kwargs=__args__.unpack()args=map(space.unwrap,args)kwargs=dict([(k,space.unwrap(v))fork,vinkwargs.iteritems()])if'__pypy__'notinsys.builtin_module_names:kwargs['isnumpy']=Truereturnspace.wrap(rAlmostEqual(*args,**kwargs))cls.w_rAlmostEqual=cls.space.wrap(interp2app(cls_rAlmostEqual))defcls_c_pow(space,args_w):try:retVal=c_pow(*map(space.unwrap,args_w))returnspace.wrap(retVal)exceptZeroDivisionError,e:raiseOperationError(cls.space.w_ZeroDivisionError,cls.space.wrap(e.message))exceptOverflowError,e:raiseOperationError(cls.space.w_OverflowError,cls.space.wrap(e.message))exceptValueError,e:raiseOperationError(cls.space.w_ValueError,cls.space.wrap(e.message))cls.w_c_pow=cls.space.wrap(interp2app(cls_c_pow))deftest_fabs(self):from_numpypyimportfabs,complex128a=complex128(complex(-5.,5.))raises(TypeError,fabs,a)deftest_fmax(self):from_numpypyimportfmax,arraynnan,nan,inf,ninf=float('-nan'),float('nan'),float('inf'),float('-inf')a=array((complex(ninf,10),complex(10,ninf),complex(inf,10),complex(10,inf),5+5j,5-5j,-5+5j,-5-5j,0+5j,0-5j,5,-5,complex(nan,0),complex(0,nan)),dtype=complex)b=[ninf]*a.sizeres=[a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10],a[11],b[12],b[13]]assert(fmax(a,b)==res).all()b=[inf]*a.sizeres=[b[0],b[1],a[2],b[3],b[4],b[5],b[6],b[7],b[8],b[9],b[10],b[11],b[12],b[13]]assert(fmax(a,b)==res).all()b=[0]*a.sizeres=[b[0],a[1],a[2],a[3],a[4],a[5],b[6],b[7],a[8],b[9],a[10],b[11],b[12],b[13]]assert(fmax(a,b)==res).all()deftest_fmin(self):from_numpypyimportfmin,arraynnan,nan,inf,ninf=float('-nan'),float('nan'),float('inf'),float('-inf')a=array((complex(ninf,10),complex(10,ninf),complex(inf,10),complex(10,inf),5+5j,5-5j,-5+5j,-5-5j,0+5j,0-5j,5,-5,complex(nan,0),complex(0,nan)),dtype=complex)b=[inf]*a.sizeres=[a[0],a[1],b[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10],a[11],b[12],b[13]]assert(fmin(a,b)==res).all()b=[ninf]*a.sizeres=[b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8],b[9],b[10],b[11],b[12],b[13]]assert(fmin(a,b)==res).all()b=[0]*a.sizeres=[a[0],b[1],b[2],b[3],b[4],b[5],a[6],a[7],b[8],a[9],b[10],a[11],b[12],b[13]]assert(fmin(a,b)==res).all()deftest_signbit(self):from_numpypyimportsignbitraises(TypeError,signbit,complex(1,1))deftest_reciprocal(self):from_numpypyimportarray,reciprocal,complex64,complex128,clongdoubleinf=float('inf')nan=float('nan')#complex orig=[2.+4.j,-2.+4.j,2.-4.j,-2.-4.j,complex(inf,3),complex(inf,-3),complex(inf,-inf),complex(nan,3),0+0j,0-0j]a2=2.**2+4.**2r=2./a2i=4./a2cnan=complex(nan,nan)expected=[complex(r,-i),complex(-r,-i),complex(r,i),complex(-r,i),-0j,0j,cnan,cnan,cnan,cnan]forc,rel_errin((complex64,2e-7),(complex128,2e-15),(clongdouble,2e-15)):actual=reciprocal(array([orig],dtype=c))forb,a,einzip(orig,actual,expected):assert(a[0].real-e.real)<rel_errassert(a[0].imag-e.imag)<rel_errdeftest_floorceiltrunc(self):from_numpypyimportarray,floor,ceil,trunca=array([complex(-1.4,-1.4),complex(-1.5,-1.5)])raises(TypeError,floor,a)raises(TypeError,ceil,a)raises(TypeError,trunc,a)deftest_copysign(self):from_numpypyimportcopysign,complex128a=complex128(complex(-5.,5.))b=complex128(complex(0.,0.))raises(TypeError,copysign,a,b)deftest_exp2(self):from_numpypyimportarray,exp2,complex128,complex64,clongfloatinf=float('inf')ninf=-float('inf')nan=float('nan')cmpl=complexforc,rel_errin((complex128,2e-15),(complex64,1e-7),(clongfloat,2e-15)):a=[cmpl(-5.,0),cmpl(-5.,-5.),cmpl(-5.,5.),cmpl(0.,-5.),cmpl(0.,0.),cmpl(0.,5.),cmpl(-0.,-5.),cmpl(-0.,0.),cmpl(-0.,5.),cmpl(-0.,-0.),cmpl(inf,0.),cmpl(inf,5.),cmpl(inf,-0.),cmpl(ninf,0.),cmpl(ninf,5.),cmpl(ninf,-0.),cmpl(ninf,inf),cmpl(inf,inf),cmpl(ninf,ninf),cmpl(5.,inf),cmpl(5.,ninf),cmpl(nan,5.),cmpl(5.,nan),cmpl(nan,nan),]b=exp2(array(a,dtype=c))foriinrange(len(a)):try:res=self.c_pow((2,0),(a[i].real,a[i].imag))exceptOverflowError:res=(inf,nan)exceptValueError:res=(nan,nan)msg='result of 2**%r(%r) got %r expected %r\n '% \
(c,a[i],b[i],res)# cast untranslated boxed results to float,# does no harm when translatedt1=float(res[0])t2=float(b[i].real)self.rAlmostEqual(t1,t2,rel_err=rel_err,msg=msg)t1=float(res[1])t2=float(b[i].imag)self.rAlmostEqual(t1,t2,rel_err=rel_err,msg=msg)deftest_expm1(self):importmath,cmathfrom_numpypyimportarray,expm1,complex128,complex64inf=float('inf')ninf=-float('inf')nan=float('nan')cmpl=complexforc,rel_errin((complex128,2e-15),(complex64,1e-7)):a=[cmpl(-5.,0),cmpl(-5.,-5.),cmpl(-5.,5.),cmpl(0.,-5.),cmpl(0.,0.),cmpl(0.,5.),cmpl(-0.,-5.),cmpl(-0.,0.),cmpl(-0.,5.),cmpl(-0.,-0.),cmpl(inf,0.),cmpl(inf,5.),cmpl(inf,-0.),cmpl(ninf,0.),cmpl(ninf,5.),cmpl(ninf,-0.),cmpl(ninf,inf),cmpl(inf,inf),cmpl(ninf,ninf),cmpl(5.,inf),cmpl(5.,ninf),cmpl(nan,5.),cmpl(5.,nan),cmpl(nan,nan),]b=expm1(array(a,dtype=c))foriinrange(len(a)):try:res=cmath.exp(a[i])-1.ifa[i].imag==0.andmath.copysign(1.,a[i].imag)<0:res=cmpl(res.real,-0.)elifa[i].imag==0.:res=cmpl(res.real,0.)exceptOverflowError:res=cmpl(inf,nan)exceptValueError:res=cmpl(nan,nan)msg='result of expm1(%r(%r)) got %r expected %r\n '% \
(c,a[i],b[i],res)# cast untranslated boxed results to float,# does no harm when translatedt1=float(res.real)t2=float(b[i].real)self.rAlmostEqual(t1,t2,rel_err=rel_err,msg=msg)t1=float(res.imag)t2=float(b[i].imag)self.rAlmostEqual(t1,t2,rel_err=rel_err,msg=msg)deftest_not_complex(self):from_numpypyimport(radians,deg2rad,degrees,rad2deg,isneginf,isposinf,logaddexp,logaddexp2,fmod,arctan2)raises(TypeError,radians,complex(90,90))raises(TypeError,deg2rad,complex(90,90))raises(TypeError,degrees,complex(90,90))raises(TypeError,rad2deg,complex(90,90))raises(TypeError,isneginf,complex(1,1))raises(TypeError,isposinf,complex(1,1))raises(TypeError,logaddexp,complex(1,1),complex(3,3))raises(TypeError,logaddexp2,complex(1,1),complex(3,3))raises(TypeError,arctan2,complex(1,1),complex(3,3))raises(TypeError,fmod,complex(90,90),3)deftest_isnan_isinf(self):from_numpypyimportisnan,isinf,arrayassert(isnan(array([0.2+2j,complex(float('inf'),0),complex(0,float('inf')),complex(0,float('nan')),complex(float('nan'),0)],dtype=complex))== \
[False,False,False,True,True]).all()assert(isinf(array([0.2+2j,complex(float('inf'),0),complex(0,float('inf')),complex(0,float('nan')),complex(float('nan'),0)],dtype=complex))== \
[False,True,True,False,False]).all()deftest_square(self):from_numpypyimportsquareassertsquare(complex(3,4))==complex(3,4)*complex(3,4)deftest_power_complex(self):inf=float('inf')ninf=-float('inf')nan=float('nan')cmpl=complexfrommathimportcopysignfrom_numpypyimportpower,array,complex128,complex64# note: in some settings (namely a x86-32 build without the JIT),# gcc optimizes the code in rlib.rcomplex.c_pow() to not truncate# the 10-byte values down to 8-byte values. It ends up with more# imprecision than usual (hence 2e-13 instead of 2e-15).forc,rel_errin((complex128,2e-13),(complex64,4e-7)):a=array([cmpl(-5.,0),cmpl(-5.,-5.),cmpl(-5.,5.),cmpl(0.,-5.),cmpl(0.,0.),cmpl(0.,5.),cmpl(-0.,-5.),cmpl(-0.,0.),cmpl(-0.,5.),cmpl(-0.,-0.),cmpl(inf,0.),cmpl(inf,5.),cmpl(inf,-0.),cmpl(ninf,0.),cmpl(ninf,5.),cmpl(ninf,-0.),cmpl(ninf,inf),cmpl(inf,inf),cmpl(ninf,ninf),cmpl(5.,inf),cmpl(5.,ninf),cmpl(nan,5.),cmpl(5.,nan),cmpl(nan,nan),],dtype=c)forpin(3,-1,10000,2.3,-10000,10+3j):b=power(a,p)foriinrange(len(a)):try:r=self.c_pow((float(a[i].real),float(a[i].imag)),(float(p.real),float(p.imag)))exceptZeroDivisionError:r=(nan,nan)exceptOverflowError:r=(inf,-copysign(inf,a[i].imag))exceptValueError:r=(nan,nan)msg='result of %r(%r)**%r got %r expected %r\n '% \
(c,a[i],p,b[i],r)t1=float(r[0])t2=float(b[i].real)self.rAlmostEqual(t1,t2,rel_err=rel_err,msg=msg)t1=float(r[1])t2=float(b[i].imag)self.rAlmostEqual(t1,t2,rel_err=rel_err,msg=msg)deftest_conjugate(self):from_numpypyimportconj,conjugate,complex128,complex64importnumpypyasnpc0=complex128(complex(2.5,0))c1=complex64(complex(1,2))assertconjisconjugateassertconj(c0)==c0assertconj(c1)==complex(1,-2)assertconj(1)==1assertconj(-3)==-3assertconj(float('-inf'))==float('-inf')assertnp.conjugate(1+2j)==1-2jx=np.eye(2)+1j*np.eye(2)fora,binzip(np.conjugate(x),np.array([[1.-1.j,0.-0.j],[0.-0.j,1.-1.j]])):asserta[0]==b[0]asserta[1]==b[1]deftest_logn(self):importmath,cmath# log and log10 are tested in math (1:1 from rcomplex)from_numpypyimportlog2,array,complex128,complex64,log1pinf=float('inf')ninf=-float('inf')nan=float('nan')cmpl=complexlog_2=math.log(2)a=[cmpl(-5.,0),cmpl(-5.,-5.),cmpl(-5.,5.),cmpl(0.,-5.),cmpl(0.,0.),cmpl(0.,5.),cmpl(-0.,-5.),cmpl(-0.,0.),cmpl(-0.,5.),cmpl(-0.,-0.),cmpl(inf,0.),cmpl(inf,5.),cmpl(inf,-0.),cmpl(ninf,0.),cmpl(ninf,5.),cmpl(ninf,-0.),cmpl(ninf,inf),cmpl(inf,inf),cmpl(ninf,ninf),cmpl(5.,inf),cmpl(5.,ninf),cmpl(nan,5.),cmpl(5.,nan),cmpl(nan,nan),]forc,rel_errin((complex128,2e-15),(complex64,1e-7)):b=log2(array(a,dtype=c))foriinrange(len(a)):try:_res=cmath.log(a[i])res=cmpl(_res.real/log_2,_res.imag/log_2)exceptOverflowError:res=cmpl(inf,nan)exceptValueError:res=cmpl(ninf,0)msg='result of log2(%r(%r)) got %r expected %r\n '% \
(c,a[i],b[i],res)# cast untranslated boxed results to float,# does no harm when translatedt1=float(res.real)t2=float(b[i].real)self.rAlmostEqual(t1,t2,rel_err=rel_err,msg=msg)t1=float(res.imag)t2=float(b[i].imag)self.rAlmostEqual(t1,t2,rel_err=rel_err,msg=msg)forc,rel_errin((complex128,2e-15),(complex64,1e-7)):b=log1p(array(a,dtype=c))foriinrange(len(a)):try:#be careful, normal addition wipes out +-0jres=cmath.log(cmpl(a[i].real+1,a[i].imag))exceptOverflowError:res=cmpl(inf,nan)exceptValueError:res=cmpl(ninf,0)msg='result of log1p(%r(%r)) got %r expected %r\n '% \
(c,a[i],b[i],res)# cast untranslated boxed results to float,# does no harm when translatedt1=float(res.real)t2=float(b[i].real)self.rAlmostEqual(t1,t2,rel_err=rel_err,msg=msg)t1=float(res.imag)t2=float(b[i].imag)self.rAlmostEqual(t1,t2,rel_err=rel_err,msg=msg)deftest_logical_ops(self):from_numpypyimportlogical_and,logical_or,logical_xor,logical_notc1=complex(1,1)c3=complex(3,0)c0=complex(0,0)assert(logical_and([True,False,True,True],[c1,c1,c3,c0])==[True,False,True,False]).all()assert(logical_or([True,False,True,False],[c1,c3,c0,c0])==[True,True,True,False]).all()assert(logical_xor([True,False,True,False],[c1,c3,c0,c0])==[False,True,True,False]).all()assert(logical_not([c1,c0])==[False,True]).all()deftest_minimum(self):from_numpypyimportarray,minimuma=array([-5.0+5j,-5.0-5j,-0.0-10j,1.0+10j])b=array([3.0+10.0j,3.0,-2.0+2.0j,-3.0+4.0j])c=minimum(a,b)foriinrange(4):assertc[i]==min(a[i],b[i])deftest_maximum(self):from_numpypyimportarray,maximuma=array([-5.0+5j,-5.0-5j,-0.0-10j,1.0+10j])b=array([3.0+10.0j,3.0,-2.0+2.0j,-3.0+4.0j])c=maximum(a,b)foriinrange(4):assertc[i]==max(a[i],b[i])deftest_basic(self):from_numpypyimport(complex128,complex64,add,array,dtype,subtractassub,multiply,divide,negative,absoluteasabs,floor_divide,real,imag,sign,clongfloat)from_numpypyimport(equal,not_equal,greater,greater_equal,less,less_equal,isnan)assertreal(4.0)==4.0assertimag(0.0)==0.0a=array([complex(3.0,4.0)])b=a.realassertb.dtype==dtype(float)forcomplex_incomplex64,complex128,clongfloat:O=complex(0,0)c0=complex_(complex(2.5,0))c1=complex_(complex(1,2))c2=complex_(complex(3,4))c3=complex_(complex(-3,-3))assertequal(c0,2.5)assertequal(c1,complex_(complex(1,2)))assertequal(c1,complex(1,2))assertequal(c1,c1)assertnot_equal(c1,c2)assertnotequal(c1,c2)assertless(c1,c2)assertless_equal(c1,c2)assertless_equal(c1,c1)assertnotless(c1,c1)assertgreater(c2,c1)assertgreater_equal(c2,c1)assertnotgreater(c1,c2)assertadd(c1,c2)==complex_(complex(4,6))assertadd(c1,c2)==complex(4,6)assertsub(c0,c0)==sub(c1,c1)==0assertsub(c1,c2)==complex(-2,-2)assertnegative(complex(1,1))==complex(-1,-1)assertnegative(complex(0,0))==0assertmultiply(1,c1)==c1assertmultiply(2,c2)==complex(6,8)assertmultiply(c1,c2)==complex(-5,10)assertdivide(c0,1)==c0assertdivide(c2,-1)==negative(c2)assertdivide(c1,complex(0,1))==complex(2,-1)n=divide(c1,O)assertrepr(n.real)=='inf'assertrepr(n.imag).startswith('inf')#can be inf*j or infjassertdivide(c0,c0)==1res=divide(c2,c1)assertabs(res.real-2.2)<0.001assertabs(res.imag+0.4)<0.001assertfloor_divide(c0,c0)==complex(1,0)assertisnan(floor_divide(c0,complex(0,0)).real)assertfloor_divide(c0,complex(0,0)).imag==0.0assertabs(c0)==2.5assertabs(c2)==5assertsign(complex(0,0))==0assertsign(complex(-42,0))==-1assertsign(complex(42,0))==1assertsign(complex(-42,2))==-1assertsign(complex(42,2))==1assertsign(complex(-42,-3))==-1assertsign(complex(42,-3))==1assertsign(complex(0,-42))==-1assertsign(complex(0,42))==1inf_c=complex_(complex(float('inf'),0.))assertrepr(abs(inf_c))=='inf'assertrepr(abs(complex(float('nan'),float('nan'))))=='nan'# numpy actually raises an AttributeError, # but _numpypy raises a TypeErrorraises((TypeError,AttributeError),'c2.real = 10.')raises((TypeError,AttributeError),'c2.imag = 10.')assert(real(c2)==3.0)assert(imag(c2)==4.0)deftest_conj(self):from_numpypyimportarraya=array([1+2j,1-2j])assert(a.conj()==[1-2j,1+2j]).all()deftest_math(self):ifself.isWindows:skip('windows does not support c99 complex')importsysimport_numpypyasnprAlmostEqual=self.rAlmostEqualforcomplex_,abs_err,testcasesin(\
(np.complex128,5e-323,self.testcases128),# (np.complex64, 5e-32, self.testcases64), ):forid,fn,ar,ai,er,ei,flagsintestcases:arg=complex_(complex(ar,ai))expected=(er,ei)iffn.startswith('acos'):fn='arc'+fn[1:]eliffn.startswith('asin'):fn='arc'+fn[1:]eliffn.startswith('atan'):fn='arc'+fn[1:]eliffnin('rect','polar'):continuefunction=getattr(np,fn)_actual=function(arg)actual=(_actual.real,_actual.imag)if'ignore-real-sign'inflags:actual=(abs(actual[0]),actual[1])expected=(abs(expected[0]),expected[1])if'ignore-imag-sign'inflags:actual=(actual[0],abs(actual[1]))expected=(expected[0],abs(expected[1]))# for the real part of the log function, we allow an# absolute error of up to 2e-15.iffnin('log','log10'):real_abs_err=2e-15else:real_abs_err=abs_errerror_message=('%s: %s(%r(%r, %r))\n''Expected: complex(%r, %r)\n''Received: complex(%r, %r)\n')%(id,fn,complex_,ar,ai,expected[0],expected[1],actual[0],actual[1])# since rAlmostEqual is a wrapped function,# convert arguments to avoid boxed valuesrAlmostEqual(float(expected[0]),float(actual[0]),abs_err=real_abs_err,msg=error_message)rAlmostEqual(float(expected[1]),float(actual[1]),msg=error_message)sys.stderr.write('.')sys.stderr.write('\n')