def getNthOctagonalTriangularNumber( n ): sign = power( -1, real( n ) ) return nint( floor( fdiv( fmul( fsub( 7, fprod( [ 2, sqrt( 6 ), sign ] ) ), power( fadd( sqrt( 3 ), sqrt( 2 ) ), fsub( fmul( 4, real_int( n ) ), 2 ) ) ), 96 ) ) )
def zp(x): """ plasma dispersion function using complementary error function in mpmath library. """ return -mp.sqrt(mp.pi) * mp.exp(-x**2) * mp.erfi(x) + mpc(0, 1) * mp.sqrt(mp.pi) * mp.exp(-x**2)
def dfdb (y,x,b,c): global FT,XO,XT,XF ft=FT v=x[0] i=y[0] iss=IS=b[0] n=N=b[1] ikf=IKF=b[2] isr=ISR=b[3] nr=NR=b[4] vj=VJ=b[5] m=M=b[6] rs=RS=b[7] #ещё раз: ВСЕ константы должны быть в перспективе либо глобальными переменными, как FT, либо составляющими вектора c, но он кривой, потому лучше уж глобальными. return mpm.matrix ([[iss*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(-mpm.exp((-i*rs + v)/(ft*n)) + XO)*(mpm.exp((-i*rs + v)/(ft*n)) - XO)/(XT*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))) + mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(mpm.exp((-i*rs + v)/(ft*n)) - XO), iss**XT*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(-i*rs + v)*(mpm.exp((-i*rs + v)/(ft*n)) - XO)*mpm.exp((-i*rs + v)/(ft*n))/(XT*ft*n**XT*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))) - iss*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(-i*rs + v)*mpm.exp((-i*rs + v)/(ft*n))/(ft*n**XT), iss*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))*(-ikf/(XT*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))**XT) + XO/(XT*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))))*(mpm.exp((-i*rs + v)/(ft*n)) - XO)/ikf, ((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*(mpm.exp((-i*rs + v)/(ft*nr)) - XO), -isr*(-i*rs + v)*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*mpm.exp((-i*rs + v)/(ft*nr))/(ft*nr**XT), isr*m*(XO - (-i*rs + v)/vj)*(-i*rs + v)*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*(mpm.exp((-i*rs + v)/(ft*nr)) - XO)/(vj**XT*((XO - (-i*rs + v)/vj)**XT + XF)), isr*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*(mpm.exp((-i*rs + v)/(ft*nr)) - XO)*mpm.log((XO - (-i*rs + v)/vj)**XT + XF)/XT, i*iss**XT*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(mpm.exp((-i*rs + v)/(ft*n)) - XO)*mpm.exp((-i*rs + v)/(ft*n))/(XT*ft*n*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))) - i*iss*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*mpm.exp((-i*rs + v)/(ft*n))/(ft*n)+ \ i*isr*m*(XO - (-i*rs + v)/vj)*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*(mpm.exp((-i*rs + v)/(ft*nr)) - XO)/(vj*((XO - (-i*rs + v)/vj)**XT + XF)) - i*isr*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*mpm.exp((-i*rs + v)/(ft*nr))/(ft*nr) ]])
def getNthNonagonalOctagonalNumber( n ): sqrt6 = sqrt( 6 ) sqrt7 = sqrt( 7 ) return nint( floor( fdiv( fmul( fsub( fmul( 11, sqrt7 ), fmul( 9, sqrt6 ) ), power( fadd( sqrt6, sqrt7 ), fsub( fmul( 8, real_int( n ) ), 5 ) ) ), 672 ) ) )
def __cubic_roots(self,a,c,d): from mpmath import mpf, mpc, sqrt, cbrt assert(all([isinstance(_,mpf) for _ in [a,c,d]])) Delta = -4 * a * c*c*c - 27 * a*a * d*d self.__Delta = Delta # NOTE: this was the original function used for root finding. # proots, err = polyroots([a,0,c,d],error=True,maxsteps=5000000) # Computation of the cubic roots. u_list = [mpf(1),mpc(-1,sqrt(3))/2,mpc(-1,-sqrt(3))/2] Delta0 = -3 * a * c Delta1 = 27 * a * a * d # Here we have two choices for the value from sqrt, positive or negative. Since C # is used as a denominator below, we pick the choice with the greatest absolute value. # http://en.wikipedia.org/wiki/Cubic_function # This should handle the case g2 = 0 gracefully. C1 = cbrt((Delta1 + sqrt(Delta1 * Delta1 - 4 * Delta0 * Delta0 * Delta0)) / 2) C2 = cbrt((Delta1 - sqrt(Delta1 * Delta1 - 4 * Delta0 * Delta0 * Delta0)) / 2) if abs(C1) > abs(C2): C = C1 else: C = C2 proots = [(-1 / (3 * a)) * (u * C + Delta0 / (u * C)) for u in u_list] # NOTE: we ignore any residual imaginary part that we know must come from numerical artefacts. if Delta < 0: # Sort the roots following the convention: complex with negative imaginary, real, complex with positive imaginary. # Then assign the roots following the P convention (e2 real root, e1 complex with positive imaginary). e3,e2,e1 = sorted(proots,key = lambda c: c.imag) else: # The convention in this case is to sort in descending order. e1,e2,e3 = sorted([_.real for _ in proots],reverse = True) return e1,e2,e3
def gamma_shot(self, wrel, l, n, t, k, tc): """ Calculate 1, transfer gain 2, electron shot noise """ if wrel > 1.0 and wrel < 1.1: mp.mp.dps = 40 else: mp.mp.dps = 20 wc = wrel * mp.sqrt(1+n) za_val = self.za(wrel, l, n, t, k, tc) mp.mp.dps = 15 zr_val = self.zr(wc, l, tc) # below calculating shot noise: ldc = self.ant_len/l nc =permittivity * boltzmann * tc/ ldc**2 / echarge**2 vtc = np.sqrt(2 * boltzmann * tc/ emass) ne = nc * vtc * (1 + n * mp.sqrt(t)) * 2 * np.pi * self.ant_rad * self.ant_len / np.sqrt(4 * np.pi) ################################### ## a: coefficient in shot noise. ## ################################### scpot= 4 a = 1 + echarge * scpot / boltzmann/tc shot_noise = 2 * a * echarge**2 * mp.fabs(za_val)**2 * ne return [mp.fabs((zr_val+za_val)/zr_val)**2, shot_noise]
def resolver_equacao(a, b, c): u''' Resolve uma equação do segundo grau. ''' a, b, c = mpf(a), mpf(b), mpf(c) d = b ** 2 - 4 * a * c return ( (-b+sqrt(d))/(2*a), (-b-sqrt(d))/(2*a) )
def fermihalf(x, sgn): """ Series approximation to the F_{1/2}(x) or F_{-1/2}(x) Fermi-Dirac integral """ f = lambda k: mp.sqrt(x ** 2 + np.pi ** 2 * (2 * k - 1) ** 2) # if x < -100: # return 0.0 if x < -9 or True: if sgn > 0: return mp.exp(x) else: return mp.exp(x) if sgn > 0: # F_{1/2}(x) a = np.array((1.0 / 770751818298, -1.0 / 3574503105, -13.0 / 184757992, 85.0 / 3603084, 3923.0 / 220484, 74141.0 / 8289, -5990294.0 / 7995)) g = lambda k: mp.sqrt(f(k) - x) else: # F_{-1/2}(x) a = np.array((-1.0 / 128458636383, -1.0 / 714900621, -1.0 / 3553038, 27.0 / 381503, 3923.0 / 110242, 8220.0 / 919)) g = lambda k: -0.5 * mp.sqrt(f(k) - x) / f(k) F = np.polyval(a, x) + 2 * np.sqrt(2 * np.pi) * sum(map(g, range(1, 21))) return F
def getRobbinsConstant( ): robbins = fsub( fsub( fadd( 4, fmul( 17, sqrt( 2 ) ) ), fmul( 6, sqrt( 3 ) ) ), fmul( 7, pi ) ) robbins = fdiv( robbins, 105 ) robbins = fadd( robbins, fdiv( log( fadd( 1, sqrt( 2 ) ) ), 5 ) ) robbins = fadd( robbins, fdiv( fmul( 2, log( fadd( 2, sqrt( 3 ) ) ) ), 5 ) ) return robbins
def __compute_roots(self,a,c,d): from mpmath import mpf, mpc, sqrt, cbrt assert(all([isinstance(_,mpf) for _ in [a,c,d]])) Delta = self.__Delta # NOTE: this was the original function used for root finding. # proots, err = polyroots([a,0,c,d],error=True,maxsteps=5000000) # Computation of the cubic roots. # TODO special casing. u_list = [mpf(1),mpc(-1,sqrt(3))/2,mpc(-1,-sqrt(3))/2] Delta0 = -3 * a * c Delta1 = 27 * a * a * d C1 = cbrt((Delta1 + sqrt(Delta1 * Delta1 - 4 * Delta0 * Delta0 * Delta0)) / 2) C2 = cbrt((Delta1 - sqrt(Delta1 * Delta1 - 4 * Delta0 * Delta0 * Delta0)) / 2) if abs(C1) > abs(C2): C = C1 else: C = C2 proots = [(-1 / (3 * a)) * (u * C + Delta0 / (u * C)) for u in u_list] # NOTE: we ignore any residual imaginary part that we know must come from numerical artefacts. if Delta < 0: # Sort the roots following the convention: complex with negative imaginary, real, complex with positive imaginary. # Then assign the roots following the P convention (e2 real root, e1 complex with positive imaginary). e3,e2,e1 = sorted(proots,key = lambda c: c.imag) else: # The convention in this case is to sort in descending order. e1,e2,e3 = sorted([_.real for _ in proots],reverse = True) return e1,e2,e3
def __compute_t_r(self,n_lobes,lobe_idx,H_in,Hr,d_eval,p4roots,lead_cf): from pyranha import math from mpmath import asin, sqrt, ellipf, mpf assert(n_lobes == 1 or n_lobes == 2) C = -lead_cf assert(C > 0) # First determine if we are integrating in the upper or lower plane. # NOTE: we don't care about eps, we are only interested in the sign. if (self.__F1 * math.sin(pt('h_\\ast'))).trim().evaluate(d_eval) > 0: sign = 1 else: sign = -1 if n_lobes == 2: assert(lobe_idx == 0 or lobe_idx == 1) r0,r1,r2,r3 = p4roots # k is the same in both cases. k = sqrt(((r3-r2)*(r1-r0))/((r3-r1)*(r2-r0))) if lobe_idx == 0: assert(Hr == r0) phi = asin(sqrt(((r3-r1)*(H_in-r0))/((r1-r0)*(r3-H_in)))) else: assert(Hr == r2) phi = asin(sqrt(((r3-r1)*(H_in-r2))/((H_in-r1)*(r3-r2)))) return -sign * mpf(2) / sqrt(C * (r3 - r1) * (r2 - r0)) * ellipf(phi,k**2) else: # TODO: single lobe case. assert(False) pass
def gamma_shot(self, wrel, l, n, t, tc): """ Calculate 1, transfer gain 2, electron shot noise """ if wrel > 1.0 and wrel < 1.2: mp.mp.dps = 80 else: mp.mp.dps = 40 wc = wrel * mp.sqrt(1+n) za = self.za_l(wc, l, n, t, tc) mp.mp.dps = 15 zr = self.zr_mp(wc, l, tc) # below calculating shot noise: ldc = self.ant_len/l nc =permittivity * boltzmann * tc/ ldc**2 / echarge**2 vtc = np.sqrt(2 * boltzmann * tc/ emass) ne = nc * vtc * (1 + n * mp.sqrt(t)) * 2 * np.pi * self.ant_rad * self.ant_len / np.sqrt(4 * np.pi) ################### ## a: coefficient in shot noise. see Issautier et al. 1999 ################### a = 1 + echarge * 3.6 / boltzmann/tc shot_noise = 2 * a * echarge**2 * mp.fabs(za)**2 * ne return [mp.fabs((zr+za)/zr)**2, shot_noise]
def P(self,z): # A+S 18.9. from mpmath import sqrt, mpc, sin, ellipfun, mpf Delta = self.Delta e1, e2, e3 = self.__roots if self.__ng3: z = mpc(0,1) * z if Delta > 0: zs = sqrt(e1 - e3) * z m = (e2 - e3) / (e1 - e3) retval = e3 + (e1 - e3) / ellipfun('sn',u=zs,m=m)**2 elif Delta < 0: H2 = (sqrt((e2 - e3) * (e2 - e1))).real assert(H2 > 0) m = mpf(1) / mpf(2) - 3 * e2 / (4 * H2) zp = 2 * z * sqrt(H2) retval = e2 + H2 * (1 + ellipfun('cn',u=zp,m=m)) / (1 - ellipfun('cn',u=zp,m=m)) else: g2, g3 = self.__invariants if g2 == 0 and g3 == 0: retval = 1 / (z**2) else: c = e1 / 2 retval = -c + 3 * c / (sin(sqrt(3 * c) * z))**2 if self.__ng3: return -retval else: return retval
def __compute_periods(self): # A+S 18.9. from mpmath import sqrt, ellipk, mpc, pi, mpf Delta = self.Delta e1, e2, e3 = self.__roots if Delta > 0: m = (e2 - e3) / (e1 - e3) Km = ellipk(m) Kpm = ellipk(1 - m) om = Km / sqrt(e1 - e3) omp = mpc(0,1) * om * Kpm / Km elif Delta < 0: # NOTE: the expression in the sqrt has to be real and positive, as e1 and e3 are # complex conjugate and e2 is real. H2 = (sqrt((e2 - e3) * (e2 - e1))).real assert(H2 > 0) m = mpf(1) / mpf(2) - 3 * e2 / (4 * H2) Km = ellipk(m) Kpm = ellipk(1 - m) om2 = Km / sqrt(H2) om2p = mpc(0,1) * Kpm * om2 / Km om = (om2 - om2p) / 2 omp = (om2 + om2p) / 2 else: g2, g3 = self.__invariants if g2 == 0 and g3 == 0: om = mpf('+inf') omp = mpc(0,'+inf') else: # NOTE: here there is no need for the dichotomy on the sign of g3 because # we are already working in a regime in which g3 >= 0 by definition. c = e1 / 2 om = 1 / sqrt(12 * c) * pi() omp = mpc(0,'+inf') return 2 * om, 2 * omp
def BSLaplace(S,K,T,t,r,sig,N,phi): """Solving the Black Scholes PDE in the Laplace domain""" x = ln(S/K) r = mpf(r);sig = mpf(sig);T = mpf(T);t=mpf(t) S = mpf(S);K = mpf(K);x=mpf(x) mu = r - 0.5*(sig**2) tau = T - t c1 = mpf('0.5017') c2 = mpf('0.6407') c3 = mpf('0.6122') c4 = mpc('0','0.2645') ans = 0.0 h = 2*pi/N h = mpf(h) for k in range(N/2): # Use symmetry theta = -pi + (k+0.5)*h z = N/tau*(c1*theta/tan(c2*theta) - c3 + c4*theta) dz = N/tau*(-c1*c2*theta/(sin(c2*theta)**2) + c1/tan(c2*theta)+c4) eps1 = (-mu + sqrt(mu**2 + 2*(sig**2)*(z+r)))/(sig**2) eps2 = (-mu - sqrt(mu**2 + 2*(sig**2)*(z+r)))/(sig**2) b1 = 1/(eps1-eps2)*(eps2/(z+r) + (1 - eps2)/z) b2 = 1/(eps1-eps2)*(eps1/(z+r) + (1 - eps1)/z) ans += exp(z*tau)*bs(x,b1,b2,eps1,eps2,z,r,phi)*dz val = (K*(h/(2j*pi)*ans)).real return 2*val
def find_Y_and_M(G,R,ndigs=12,Yset=None,Mset=None): r""" Compute a good value of M and Y for Maass forms on G INPUT: - ''G'' -- group - ''R'' -- real - ''ndigs'' -- integer (number of desired digits of precision) - ''Yset'' -- real (default None) if set we return M corr. to this Y - ''Mset'' -- integer (default None) if set we return Y corr. to this M OUTPUT: - [Y,M] -- good values of Y (real) and M (integer) EXAMPLES:: TODO: Better and more effective bound """ l=G._level if(Mset <> None): # then we get Y corr. to this M Y0=mpmath.sqrt(3.0)/mpmath.mpf(2*l) if(Yset==None): Y0=mpmath.sqrt(3.0)/mpmath.mpf(2*l) Y=mpmath.mpf(0.95*Y0) else: Y=Yset #print "Y=",Y,"Yset=",Yset IR=mpmath.mpc(0,R) eps=mpmath.mpf(10 **-ndigs) twopiY=mpmath.pi()*Y*mpmath.mpf(2) M0=get_M_for_maass(R,Y,eps) if(M0<10): M0=10 ## Do this in low precision dold=mpmath.mp.dps #print "Start M=",M0 #print "dold=",dold #mpmath.mp.dps=100 try: for n in range(M0,10000 ): X=mpmath.pi()*Y*mpmath.mpf(2 *n) #print "X,IR=",X,IR test=mpmath.fp.besselk(IR,X) if(abs(test)<eps): raise StopIteration() except StopIteration: M=n else: M=n raise Exception,"Error: Did not get small enough error:=M=%s gave err=%s" % (M,test) mpmath.mp.dps=dold return [Y,M]
def mobility(self, z=1000, E=0, T=300, pn=None): if pn is None: Eg = self.band_gap(T, symbolic=False, electron_volts=False) # print Eg, self.__to_numeric(-Eg/(k*T)), mp.exp(self.__to_numeric(-Eg/(k*T))) pn = self.Nc(T, symbolic=False) * self.Nv(T, symbolic=False) * mp.exp( self.__to_numeric(-Eg / (k * T))) * 1e-12 # print pn N = 0 for dopant in self.dopants: N += dopant.concentration(z) N *= 1e-6 # print N mobility = {'mobility_e': {'mu_L': 0, 'mu_I': 0, 'mu_ccs': 0, 'mu_tot': 0}, 'mobility_h': {'mu_L': 0, 'mu_I': 0, 'mu_ccs': 0, 'mu_tot': 0}} for key in mobility.keys(): mu_L = self.reference[key]['mu_L0'] * (T / 300.0) ** (-self.reference[key]['alpha']) mu_I = (self.reference[key]['A'] * (T ** (3 / 2)) / N) / ( mp.log(1 + self.reference[key]['B'] * (T ** 2) / N) - self.reference[key]['B'] * (T ** 2) / ( self.reference[key]['B'] * (T ** 2) + N)) try: mu_ccs = (2e17 * (T ** (3 / 2)) / mp.sqrt(pn)) / (mp.log(1 + 8.28e8 * (T ** 2) * (pn ** (-1 / 3)))) X = mp.sqrt(6 * mu_L * (mu_I + mu_ccs) / (mu_I * mu_ccs)) except: mu_ccs = np.nan X = 0 # print X mu_tot = mu_L * (1.025 / (1 + ((X / 1.68) ** (1.43))) - 0.025) Field_coeff = (1 + (mu_tot * E * 1e-2 / self.reference[key]['v_s']) ** self.reference[key]['beta']) ** ( -1 / self.reference[key]['beta']) mobility[key]['mu_L'] = mu_L * 1e-4 mobility[key]['mu_I'] = mu_I * 1e-4 mobility[key]['mu_ccs'] = mu_ccs * 1e-4 mobility[key]['mu_tot'] = mu_tot * 1e-4 * Field_coeff return mobility
def bimax_integrand(self, z, wc, l, n, t): """ Integrand of electron-noise integral. """ return f1(wc*l/z/mp.sqrt(2)) * z * \ (mp.exp(-z**2) + n/mp.sqrt(t)*mp.exp(-z**2 / t)) / \ (mp.fabs(BiMax.d_l(z, wc, n, t))**2 * wc**2)
def eta(lam): """Function from DLMF 8.12.1 shifted to be centered at 0.""" if lam > 0: return mp.sqrt(2*(lam - mp.log(lam + 1))) elif lam < 0: return -mp.sqrt(2*(lam - mp.log(lam + 1))) else: return 0
def fp(ne): """ Return the plasma frequency. ~ 8.98 * sqrt(ne) """ return mp.sqrt(echarge**2/emass/permittivity)/2/mp.pi * mp.sqrt(ne)
def findCenteredPolygonalNumber( n, k ): if real_int( k ) < 3: raise ValueError( 'the number of sides of the polygon cannot be less than 3,' ) s = fdiv( k, 2 ) return nint( fdiv( fadd( sqrt( s ), sqrt( fsum( [ fmul( 4, real( n ) ), s, -4 ] ) ) ), fmul( 2, sqrt( s ) ) ) )
def zk(z, k): """ modified dispersion function for Kappa distribution. (Mace and Hellberg, 1995) """ i = mp.mpc(0, 1) coeff = i * (k + 0.5) * (k-0.5) / (mp.sqrt(k**3) * (k+1)) return coeff * hyp2f1(1, 2*k+2, k+2, (1-z/(i * mp.sqrt(k)))/2)
def getNthDecagonalNonagonalNumber( n ): dps = 8 * int( real_int( n ) ) if mp.dps < dps: mp.dps = dps return nint( floor( fdiv( fmul( fadd( 15, fmul( 2, sqrt( 14 ) ) ), power( fadd( fmul( 2, sqrt( 2 ) ), sqrt( 7 ) ), fsub( fmul( 8, n ), 6 ) ) ), 448 ) ) )
def getNthNonagonalPentagonalNumber( n ): sqrt21 = sqrt( 21 ) sign = power( -1, real_int( n ) ) return nint( floor( fdiv( fprod( [ fadd( 25, fmul( 4, sqrt21 ) ), fsub( 5, fmul( sqrt21, sign ) ), power( fadd( fmul( 2, sqrt( 7 ) ), fmul( 3, sqrt( 3 ) ) ), fsub( fmul( 4, n ), 4 ) ) ] ), 336 ) ) )
def temp(t, x=mpf(1), Q=mpf(1), A=mpf(1), Ti=mpf(10)): u''' Definição da função temperatura temp = T(t, x) ''' t = mpf(t) colchete1 = mpf(2) * sqrt(t*A/pi) * exp(-x**2/(t*4*A)) colchete2 = x * erfc(x/( mpf(2) * sqrt(t*A))) return Ti + Q * (colchete1 - colchete2)
def getNthNonagonalTriangularNumber( n ): a = fmul( 3, sqrt( 7 ) ) b = fadd( 8, a ) c = fsub( 8, a ) return nint( fsum( [ fdiv( 5, 14 ), fmul( fdiv( 9, 28 ), fadd( power( b, real_int( n ) ), power( c, n ) ) ), fprod( [ fdiv( 3, 28 ), sqrt( 7 ), fsub( power( b, n ), power( c, n ) ) ] ) ] ) )
def temp_t(t, x=mpf(1), Q=mpf(1), A=mpf(1), Ti=mpf(10)): u''' Definição da derivada da temperatura em relação ao tempo, temp_t = T_t(t, x) ''' t = mpf(t) termo1 = sqrt(A/(t*pi)) * exp(-x**2/(t*4*A)) termo2 = sqrt(A/(t*pi)) * (x**2/(t**2 * 2 * A)) * exp(-x**2/(t*4*A)) termo3 = (x**2/(sqrt(t**3 * A) * 4)) * erfc_z(x / (mpf(2) * sqrt(t * A))) return Q * (termo1 + termo2 + termo3)
def ldeb(ne, te): """ Return the Debye length. ne: electron density te: electron temperature SI units ~ 69.01 * sqrt(te/ne) """ return mp.sqrt(permittivity * boltzmann/ echarge**2) * mp.sqrt(te/ne)
def bimax(self, wrel, l, n, t, tc): """ electron noise. w: f/f_p, where f_p is the total plasma frequency. """ wc = wrel * mp.sqrt(1+n) limits = self.long_interval(wc, n, t) #print(limits) result = mp.quad(lambda z: self.bimax_integrand(z, wc, l, n, t), limits) return result * self.v_unit * mp.sqrt(tc)
def obliquity(t): from mpmath import acos, cos, sqrt H = self.__H_time(t) hs = self.__hs_time(t) G = d_eval['G'] Gt = d_eval['\\tilde{G}'] Hts = d_eval['\\tilde{H}_\\ast'] Gxy = sqrt(G**2-H**2) Gtxys = sqrt(Gt**2-(Hts-H)**2) retval = (Gxy*Gtxys*cos(hs)+H*(Hts-H))/(G*Gt) return acos(retval)
def mino_freqs_kerr(r1, r2, r3, r4, En, Lz, Q, aa, slr, ecc, x, M=1): """ Mino frequencies for the Kerr case (aa != 0) Parameters: r1 (float): radial root r2 (float): radial root r3 (float): radial root r4 (float): radial root En (float): energy Lz (float): angular momentum Q (float): Carter constant aa (float): spin slr (float): semi-latus rectum ecc (float): eccentricity x (float): inclincation Keyword Args: M (float): mass Returns: ups_r (float): radial Mino frequency ups_theta (float): polar Mino frequency ups_phi (float): azimuthal Mino frequency gamma (float): time Mino frequency """ # En, Lz, Q = calc_eq_constants(aa, slr, ecc) # r1, r2, r3, r4 = radial_roots(En, Q, aa, slr, ecc, M) pi = mp.pi L2 = Lz * Lz aa2 = aa * aa En2 = En * En M2 = M * M # polar pieces zm = 1 - x * x # a2zp = (L2 + aa2*(-1 + En2)*(-1 + zm))/((-1 + En2)*(-1 + zm)) eps0zp = -((L2 + aa2 * (-1 + En2) * (-1 + zm)) / (L2 * (-1 + zm))) zmOverzp = (aa2 * (-1 + En2) * (-1 + zm) * zm) / (L2 + aa2 * (-1 + En2) * (-1 + zm)) kr = sqrt(((r1 - r2) * (r3 - r4)) / ((r1 - r3) * (r2 - r4))) ktheta = sqrt(zmOverzp) kr2 = kr * kr ktheta2 = ktheta * ktheta ellipticK_r = ellipk(kr2) ellipticK_theta = ellipk(ktheta2) rp = M + sqrt(M2 - aa2) rm = M - sqrt(M2 - aa2) hr = (r1 - r2) / (r1 - r3) hp = ((r1 - r2) * (r3 - rp)) / ((r1 - r3) * (r2 - rp)) hm = ((r1 - r2) * (r3 - rm)) / ((r1 - r3) * (r2 - rm)) ellipticPi_hmkr = ellippi(hm, kr2) ellipticPi_hpkr = ellippi(hp, kr2) ellipticPi_hrkr = ellippi(hr, kr2) ellipticPi_zmktheta = ellippi(zm, ktheta2) ellipticE_kr = ellipe(kr2) ellipticE_ktheta = ellipe(ktheta2) ups_r = (pi * sqrt((1 - En2) * (r1 - r3) * (r2 - r4))) / (2 * ellipticK_r) ups_theta = (sqrt(eps0zp) * Lz * pi) / (2.0 * ellipticK_theta) ups_phi = (2 * aa * ups_r * (-( ((-(aa * Lz) + 2 * En * M * rm) * (ellipticK_r - ((r2 - r3) * ellipticPi_hmkr) / (r2 - rm))) / (r3 - rm)) + ( (-(aa * Lz) + 2 * En * M * rp) * (ellipticK_r - ((r2 - r3) * ellipticPi_hpkr) / (r2 - rp))) / (r3 - rp))) / (pi * sqrt( (1 - En2) * (r1 - r3) * (r2 - r4)) * (-rm + rp)) + ( 2 * ups_theta * ellipticPi_zmktheta) / (sqrt(eps0zp) * pi) gamma = (4 * En * M2 + (2 * En * ups_theta * (L2 + aa2 * (-1 + En2) * (-1 + zm)) * (-ellipticE_ktheta + ellipticK_theta)) / ((-1 + En2) * sqrt(eps0zp) * Lz * pi * (-1 + zm)) + (2 * ups_r * ((2 * M * (-(((-2 * aa2 * En * M + (-(aa * Lz) + 4 * En * M2) * rm) * (ellipticK_r - ((r2 - r3) * ellipticPi_hmkr) / (r2 - rm))) / (r3 - rm)) + ((-2 * aa2 * En * M + (-(aa * Lz) + 4 * En * M2) * rp) * (ellipticK_r - ((r2 - r3) * ellipticPi_hpkr) / (r2 - rp))) / (r3 - rp))) / (-rm + rp) + 2 * En * M * (r3 * ellipticK_r + (r2 - r3) * ellipticPi_hrkr) + (En * ((r1 - r3) * (r2 - r4) * ellipticE_kr + (-(r1 * r2) + r3 * (r1 + r2 + r3)) * ellipticK_r + (r2 - r3) * (r1 + r2 + r3 + r4) * ellipticPi_hrkr)) / 2.0)) / (pi * sqrt( (1 - En2) * (r1 - r3) * (r2 - r4)))) return ups_r, ups_theta, ups_phi, gamma
def compute_g(n): """g_k from DLMF 5.11.3/5.11.5""" a = compute_a(2 * n) g = [mp.sqrt(2) * mp.rf(0.5, k) * a[2 * k] for k in range(n)] return g
def calc(r, t): return floor(1 + (.25 * (-3 - (2 * r) + sqrt(1 - (4 * r) + (4 * (r**2)) + (8 * t)))))
def sph_kn_bessel(n, z): out = besselk(n + mpf(1) / 2, z) * sqrt(pi / (2 * z)) return out
def move(self, alpha, v, t): if alpha == 0: self.x1 += v * t self.x2 += v * t return reverse_alpha = False reverse_v = False alpha = mpmath.radians(alpha) if alpha < 0: alpha = -alpha reverse_alpha = True if v < 0: v = -v reverse_v = True R = self.l * mpmath.cot(alpha) + 0.5 * self.d # outer radius r = self.l * mpmath.cot(alpha) - 0.5 * self.d # inner radius w = v / R # angular velocity beta = w * t # angle that has been turned after the move viewed from the center of the circle assert (beta < mpmath.pi) # make sure it still forms a triangle theta = 0.5 * beta # the angle of deviation from the original orientation m = 2 * R * mpmath.sin(theta) # displacement of outer rear wheel n = 2 * r * mpmath.sin(theta) # displacement of inner rear wheel if not reverse_alpha and not reverse_v: delta_x1, delta_y1 = mpmath.cos(theta) * m, mpmath.sin(theta) * m delta_x2, delta_y2 = mpmath.cos(theta) * n, mpmath.sin(theta) * n elif reverse_alpha and not reverse_v: delta_x2, delta_y2 = mpmath.cos(theta) * m, -mpmath.sin(theta) * m delta_x1, delta_y1 = mpmath.cos(theta) * n, -mpmath.sin(theta) * n elif not reverse_alpha and reverse_v: delta_x1, delta_y1 = -mpmath.cos(theta) * m, mpmath.sin(theta) * m delta_x2, delta_y2 = -mpmath.cos(theta) * n, mpmath.sin(theta) * n else: delta_x2, delta_y2 = -mpmath.cos(theta) * m, -mpmath.sin(theta) * m delta_x1, delta_y1 = -mpmath.cos(theta) * n, -mpmath.sin(theta) * n delta_x1 = float(delta_x1) delta_y1 = float(delta_y1) delta_x2 = float(delta_x2) delta_y2 = float(delta_y2) # the current calculation is based on this relative reference system # we need to map this coordinate in the relative reference system back to the absolute system # use the dot product of the rear wheel line to find the rotation from the relative reference system to the absolute system if self.y1 != 0 or self.y2 != 10: # no rotation is needed bottom = np.sqrt(((self.x2 - self.x1) * (self.x2 - self.x1) + (self.y2 - self.y1) * (self.y2 - self.y1))) * 10 top = (self.y2 - self.y1) * 10 cosine_value = float(top / bottom) rotation = mpmath.acos(cosine_value) # print(rotation) if self.x1 < self.x2: # since arccos does not give direction, we need to do a check here rotation = -rotation # let A be the linear transformation that maps a relative referenced coordinate to an absolute referenced coordinate A = np.asarray( [[float(mpmath.cos(rotation)), float(-mpmath.sin(rotation))], [float(mpmath.sin(rotation)), float(mpmath.cos(rotation))]]) # then we map delta_1 and delta_2 to the absolute reference system relative_delta_1 = np.asarray([delta_x1, delta_y1]) relative_delta_2 = np.asarray([delta_x2, delta_y2]) absolute_delta_1 = np.matmul(A, relative_delta_1) absolute_delta_2 = np.matmul(A, relative_delta_2) delta_x1 = absolute_delta_1[0] delta_y1 = absolute_delta_1[1] delta_x2 = absolute_delta_2[0] delta_y2 = absolute_delta_2[1] # make vector addition in the absolute reference system self.x1 += delta_x1 self.x2 += delta_x2 self.y1 += delta_y1 self.y2 += delta_y2 dist = mpmath.sqrt((self.x1 - self.x2) * (self.x1 - self.x2) + (self.y2 - self.y1) * (self.y2 - self.y1)) assert abs(dist - self.d) <= self.d * 1e-4
def radius(x, y, z): return mp.sqrt(mp.power(x, 2) + mp.power(y, 2) + mp.power(z, 2))
def f(x, y, z): x = mp.mpmathify(x) y = mp.mpmathify(y) z = mp.mpmathify(z) R = radius(x, y, z) # solving 0 division problem here if x == 0 and z == 0 or y == 0: part1 = mp.mpmathify(0) else: part1 = mp.mpf('0.5') * y * (mp.power(z, 2) - mp.power(x, 2)) * mp.asinh(y / (mp.sqrt(mp.power(x, 2) + mp.power(z, 2)))) if x == 0 and y == 0 or z == 0: part2 = 0 else: part2 = mp.mpf('0.5') * z * (mp.power(y, 2) - mp.power(x, 2)) * mp.asinh(z / (mp.sqrt(mp.power(x, 2) + mp.power(y, 2)))) if x == 0 or y == 0 or z == 0: part3 = 0 else: part3 = x * y * z * mp.atan((y * z) / (x * R)) # solving 0 division problem here part4 = mp.mpf('1 / 6') * R * (2 * mp.power(x, 2) - mp.power(y, 2) - mp.power(z, 2)) return mp.mpmathify(part1 + part2 - part3 + part4)
return 0.5*mp.erfc(x/mp.sqrt(2)) snrlen = 13 snrdb = np.linspace(0,13,13) simlen = int(1e5) #Simulated BER declaration err = [] #Analytical BER declaration ber = [] #for SNR 0 to 10 dB for i in range(0,snrlen): awgn = np.random.normal(0,1,simlen) snr = 10**(0.1*snrdb[i]) rx = mp.sqrt(snr) + awgn err_ind = np.nonzero(rx < 0)#condition for a misinterpreted bit #calculating the total number of errors err_n = np.size(err_ind) #calcuating the simulated BER err.append(err_n/simlen) #calculating the analytical BER ber.append(qfunc(mp.sqrt(snr))) plt.semilogy(snrdb.T,ber,label='AWGN theory') plt.semilogy(snrdb.T,err,'o',label='Simulated') plt.xlabel('SNR in dB') plt.ylabel('$P_B$') plt.legend() plt.grid() plt.show()
def qfunc(x): return 0.5*mp.erfc(x/mp.sqrt(2))
def pdf_gauss_mp(x, sigma, mean): return mp.mpf(1.) / mp.sqrt(mp.mpf("2.") * sigma**2 * mp.pi) * mp.exp( -(x - mean)**2 / (mp.mpf("2.") * sigma**2))
shap = shap[18:68] for i in shap: xlist.append(i[0]) ylist.append(i[1]) forx = [] fory = [] for x in xlist: forx.append((x - centre_x)**2) for y in ylist: fory.append((y - centre_y)**2) listsum = [sum(x) for x in zip(forx, fory)] features = [] for i in listsum: k = mpmath.sqrt(float(i)) features.append(float(k)) maxx = (max(features)) final = [] for i in features: if (i == 0.0): continue F = i / maxx final.append(F) # print(final) numpy_array = np.array(final) # features_vector.append(numpy_array) for (x, y) in shap: cv2.circle(tasveer, (x, y), 1, (0, 0, 255), 2) cv2.circle(tasveer, (centre_x, centre_y), 1, (0, 0, 0), 5) # print(features_vector)
def pval(x): return float(1 - 0.5 * (1 + mpmath.erf(x / mpmath.sqrt(2))))
def _noncentral_chi_pdf(t, df, nc): res = mpmath.besseli(df / 2 - 1, mpmath.sqrt(nc * t)) res *= mpmath.exp(-(t + nc) / 2) * (t / nc)**(df / 4 - 1 / 2) / 2 return res
''' Generate code from cartesian coordinates. ''' import numpy import mpmath # set precision mpmath.mp.dps = 15 # reference tet: t0 = [-1, -1 / mpmath.sqrt(3), -1 / mpmath.sqrt(6)] t1 = [+0, +2 / mpmath.sqrt(3), -1 / mpmath.sqrt(6)] t2 = [+1, -1 / mpmath.sqrt(3), -1 / mpmath.sqrt(6)] t3 = [+0, +0, 3 / mpmath.sqrt(6)] def is_float(value): try: float(value) return True except ValueError: return False # read data from file, # e.g., # <https://people.sc.fsu.edu/~jburkardt/f_src/tetrahedron_arbq_rule/tetrahedron_arbq_rule.f90> def read_data(filename, blocks='xyzw'): data = [] current_block = None next_block = 0 with open(filename) as f:
def ub_psi_(self, a, b, x): return 1/mp.gamma(a) * \ mp.sqrt(mp.power(2, a) * mp.power(x, -a) * mp.gamma(a) * mp.exp(x/2) * mp.expint(1 + a - b, x/2))
def safeHasSquareRoot(num): return mpmath.isint(mpmath.sqrt(num))
snrdb = np.linspace(0, 9, 10) #Number of samples simlen = int(1e5) #Simulated BER declaration err = [] #Analytical BER declaration ber = [] #for SNR 0 to 10 dB for i in range(0, snrlen): #Generating AWGN, 0 mean unit variance noise = np.random.normal(0, 1, simlen) #from dB to actual SNR snr = 10**(0.1 * snrdb[i]) #Received symbol in baseband rx = mp.sqrt(snr) + noise #storing the index for the received symbol #in error err_ind = np.nonzero(rx < 0) #calculating the total number of errors err_n = np.size(err_ind) #calcuating the simulated BER err.append(err_n / simlen) #calculating the analytical BER ber.append(qfunc(mp.sqrt(snr))) #plt.semilogy(snrdb.T,ber,label='Analysis') plt.plot(snrdb.T, err) plt.xlabel('SNR$\\left(\\frac{E_b}{N_0}\\right)$') plt.ylabel('$P_e$') plt.legend()
def analytic_solution_helper(x, tau, x_0): result = float((1 - tau) * 1 / (x * mpmath.sqrt(tau)) * mpmath.besseli(1, 2 * x / x_0 * mpmath.sqrt(tau)) * mpmath.exp(-(1 + tau) * x / x_0)) return result
def gauss_pdf(x): return 1/mp.sqrt(2*np.pi)*np.exp(-x**2/2.0)
def get_frame(self): pickle_in = open("New_testing_dlib_normalized.pickle", "rb") model = pickle.load(pickle_in) while (self.video.isOpened()): self.frame += 1 ret, frame = self.video.read() if ret is True: if self.frame % 5 == 0: # print(str(self.frame)+" frame") #ret, frame = self.video.read() # if ret == True: self.frame += 1 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) file = open("Expressions.csv", "w") face = detector(gray, 0) # print("Number of Faces {}".format(len(face))) my_list = [] count_interested = 0 count_bore = 0 count_neutral = 0 for (J, rect) in enumerate(face): shap = predictor(frame, rect) xlist = [] ylist = [] shap = face_utils.shape_to_np(shap) Centre = (shap[30]) centre_x = Centre[0] centre_y = Centre[1] shap = shap[18:68] for i in shap: xlist.append(i[0]) ylist.append(i[1]) forx = [] fory = [] for x in xlist: forx.append((x - centre_x)**2) for y in ylist: fory.append((y - centre_y)**2) listsum = [sum(x) for x in zip(forx, fory)] features = [] for i in listsum: k = mpmath.sqrt(float(i)) features.append(float(k)) maxx = (max(features)) final = [] for i in features: if (i == 0.0): continue F = i / maxx final.append(F) # print(final) numpy_array = np.array(final) prediction = model.predict([numpy_array])[0] # print(prediction) # print("done") (x, y, w, h) = face_utils.rect_to_bb(rect) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # display the image and the prediction cv2.putText(frame, prediction, (x - 7, y - 6), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 255, 0), 2) cv2.circle(frame, (centre_x, centre_y), 1, (0, 0, 0), 10) for (x, y) in shap: cv2.circle(frame, (x, y), 1, (0, 0, 255), 2) cv2.line(frame, (centre_x, centre_y), (x, y), (0, 255, 1)) cv2.waitKey(100) if prediction == "INTERESTED": count_interested += 1 # self.Expression.append(1) elif prediction == "BORE": count_bore += 1 else: count_neutral += 1 ret, jpeg = cv2.imencode('.jpg', frame) my_list.append(jpeg.tobytes) if (count_interested > count_bore) and (count_interested > count_neutral): self.Expression.append(1) elif (count_bore > count_interested) and (count_bore > count_neutral): self.Expression.append(-1) else: self.Expression.append(0) with file: writter = csv.writer(file) writter.writerow(self.Expression) return (my_list) else: break
def cse_simplify_and_evaluate_sympy_expressions(self): # If an empty variable dict is passed, return an empty dictionary if self.variable_dict == {}: return {} # Call expand_variable_dict expanded_variable_dict = expand_variable_dict(self.variable_dict) # Setting precision mp.dps = precision # Creating free_symbols_set, which stores all free symbols from all expressions. logging.debug(' Getting all free symbols...') free_symbols_set = set() for val in expanded_variable_dict.values(): try: free_symbols_set = free_symbols_set | val.free_symbols except AttributeError: pass # Initializing free_symbols_dict free_symbols_dict = dict() logging.debug(' ...Setting each free symbol to a random value...') # Setting each variable in free_symbols_set to a random number in [0, 1) according to the hashed string # representation of each variable. for var in free_symbols_set: # Make sure M_PI is set to its correct value, pi if str(var) == "M_PI": free_symbols_dict[var] = mpf(pi) # Then make sure M_SQRT1_2 is set to its correct value, 1/sqrt(2) elif str(var) == "M_SQRT1_2": free_symbols_dict[var] = mpf(1/sqrt(2)) # All other free variables are set to random numbers else: # Take the variable [var], turn it into a string, encode the string, hash the string using the md5 # algorithm, turn the hash into a hex number, turn the hex number into an int, set the random seed to # that int. This ensures each variable gets a unique but consistent value. random.seed(int(hashlib.md5(str(var).encode()).hexdigest(), 16)) # Store the random value in free_symbols_dict as a mpf free_symbols_dict[var] = mpf(random.random()) # Warning: might slow Travis CI too much: logging.debug(' ...Setting '+str(var)+' to the random value: '+str(free_symbols_dict[var])) # Initialize calculated_dict and simplified_expression_dict calculated_dict = dict() simplified_expression_dict = dict() logging.debug(' ...Calculating values for each variable based on free symbols...') # Evaluating each expression using the values in var_dict for var, expression in expanded_variable_dict.items(): # Using SymPy's cse algorithm to optimize our value substitution replaced, reduced = cse(expression, order='none') # Warning: might slow Travis CI too much: logging.debug(' var = '+str(var)+' |||| replaced = '+str(replaced)) # Calculate our result_value result_value = calculate_value(free_symbols_dict, replaced, reduced) # Check if result_value is near-zero, and double checking if it should be zero if fabs(result_value) != mpf('0.0') and fabs(result_value) < 10 ** ((-2.0/3)*precision): logging.info("Found |result| (" + str(fabs(result_value)) + ") close to zero. " "Checking if indeed it should be zero.") new_result_value = calculate_value(free_symbols_dict, replaced, reduced, precision_factor=2) if fabs(new_result_value) < 10 ** (-(4.0/3) * precision): logging.info("After re-evaluating with twice the digits of precision, |result| dropped to " + str(new_result_value) + ". Setting value to zero") result_value = mpf('0.0') # Store result_value in calculated_dict calculated_dict[var] = result_value return calculated_dict
def sph_h2n_bessel(n, z): return hankel2(n + mpf(1) / 2, z) * sqrt(pi / (2 * z))
def sph_i2n_bessel(n, z): out = besseli(-n - mpf(1) / 2, z) * sqrt(pi / (2 * z)) return out
def sph_jn_bessel(n, z): out = besselj(n + mpf(1) / 2, z) * sqrt(pi / (2 * z)) if mpmathify(z).imag == 0: return out.real # Small imaginary parts are spurious else: return out
def sph_i1n_bessel(n, z): out = besseli(n + mpf(1) / 2, z) * sqrt(pi / (2 * z)) if mpmathify(z).imag == 0: return out.real else: return out