def calc_ck(kmax,wISM,mufn,SFR,tmin=0,tmax=1000,wISM2_0=None): """ normalized array of weights of how many SN enrich a star """ if wISM2_0==None: myarr = [quad(lambda t: wISM(k,mufn(t))*SFR(t),tmin,tmax)[0] for k in range(1,kmax+1)] else: myarr = [quad(lambda t: wISM(k,mufn(t))*wISM2_0(t)*SFR(t),tmin,tmax)[0] for k in range(1,kmax+1)] return np.array(myarr)/np.sum(myarr)
def generate_delta(params): print params D = params["D"] beta = params["beta"] npts = params["npts"] print "DOS half-bandwidth : ", D Gamma = params["gamma"] dos_prec = 0.1 omega_grid = np.arange(-2*D,2*D,dos_prec) dos_vals = dos_function(omega_grid) data = np.vstack([omega_grid,dos_vals]).transpose() np.savetxt("dos.dat",data) fermi = lambda w : 1. / (1.+np.exp(beta*w)) delta_wt = lambda tau, w : -fermi(w) * np.exp(tau*w) * dos_function(w) * Gamma delta_f = lambda tau : integrate.quad(lambda w: -fermi(w) * np.exp(tau*w) * dos_function(w) * Gamma, -2*D, 2*D) tau_grid = np.linspace(0,beta,npts+1) delta_vals = np.array([delta_f(x)[0] for x in tau_grid]) data_out = np.vstack([range(npts+1), delta_vals, delta_vals]) fname = "delta_tau.dat" np.savetxt("delta_tau.dat", data_out.transpose()) print "Saved", fname kramers_kronig_imag = lambda z : integrate.quad(lambda w: np.imag(dos_function(w) / (1j*z - w)), -2*D, 2*D) kramers_kronig_real = lambda z : integrate.quad(lambda w: np.real(dos_function(w) / (1j*z - w)), -2*D, 2*D) matsubara_grid = (2*np.arange(0, npts, 1, dtype=np.float) + 1)*np.pi/beta delta_iw = np.array([[x, kramers_kronig_real(x)[0], kramers_kronig_imag(x)[0]] for x in matsubara_grid]) fname = "delta_iw.dat" np.savetxt(fname, delta_iw) print "Saved", fname
def void_Fr(norm,r,cosm,vd,func,max_record): """ Cumulative void distribution Parameters ---------- norm : float normalisation factor r : array void radii ps : object PowSpec class instance max_record : bool direction of cumulative sum Notes ----- F(r) from Harrison & Coles (2012); known distribution of void radii for max_record=True, calculates the cumulative distribution *upto* a given radii, otherwise calculates EVS for small radii """ if max_record: integ = integrate.quad(func,0.,r,args=(cosm))[0] else: integ = integrate.quad(func,r,np.inf,args=(cosm))[0] return (1/norm)*integ
def Lookback(M1,L1,K1,function,p): if p == 1: file = open(function+'_'+str(M1)+'_'+str(L1)+'.txt','wt') LB=[] LB2=[] x=[] args = (M1,L1,K1) for z in drange(0,5,0.1): x.append(z) result, err = integrate.quad(E_z,0.0,z,args) # Lookback result2, err = integrate.quad(E_z2,z,inf,args) # Age of Universe LB.append(result) LB2.append(result2) if p ==1: file.writelines(str(z)+" "+str(result)+" "+str(result2)+"\n") if p ==1: file.close plot(x,LB) plot(x,LB2) print LB[-1], LB2[-1] ylabel('Lookback Time $T_L/T_H$') xlabel('Redshift $z$') if p!= 1: show()
def _calculate_levy(x, alpha, beta, cdf=False): """ Calculation of Levy stable distribution via numerical integration. This is used in the creation of the lookup table. """ # "0" parameterization as per http://academic2.american.edu/~jpnolan/stable/stable.html # Note: fails for alpha=1.0 # (so make sure alpha=1.0 isn't exactly on the interpolation grid) from scipy import integrate C = beta * N.tan(N.pi*0.5*alpha) def func_cos(u): ua = u ** alpha if ua > 700.0: return 0.0 return N.exp(-ua)*N.cos(C*ua-C*u) def func_sin(u): ua = u ** alpha if ua > 700.0: return 0.0 return N.exp(-ua)*N.sin(C*ua-C*u) if cdf: # Cumulative density function return (integrate.quad(lambda u: u and func_cos(u)/u or 0.0, 0.0, integrate.Inf, weight="sin", wvar=x, limlst=1000)[0] + integrate.quad(lambda u: u and func_sin(u)/u or 0.0, 0.0, integrate.Inf, weight="cos", wvar=x, limlst=1000)[0] ) / N.pi + 0.5 else: # Probability density function return ( integrate.quad(func_cos, 0.0, integrate.Inf, weight="cos", wvar=x, limlst=1000)[0] - integrate.quad(func_sin, 0.0, integrate.Inf, weight="sin", wvar=x, limlst=1000)[0] ) / N.pi
def BG(params,t,rho): K = params['K'].value Dt = params['Dt'].value rho_0 = params['rho_0'].value j = params['j'].value #Tk = params['Tk'].value a=numpy.ones(len(t)) b=numpy.ones(len(t)) c=numpy.ones(len(t)) for i in range(len(t)): func_ph = lambda x:(x**5)/((numpy.exp(x)-1)*(1-numpy.exp(-x)))#((numpy.sinh(x))**2) func_sd = lambda x:(x**3)/((numpy.exp(x)-1)*(1-numpy.exp(-x))) func_ee = lambda x:(x**2)/((numpy.exp(x)-1)*(1-numpy.exp(-x))) ph = quad(func_ph,0,(Dt/t[i])) sd = quad(func_sd,0,(Dt/t[i])) ee = quad(func_ee,0,(Dt/t[i])) a[i]=ph[0] b[i]=sd[0] c[i]=ee[0] #model3 = rho_0 + K * ((t/Dt)**5) * a + K * ((t/Dt)**3) * b + K * ((t/Dt)**2) * c #model2 = rho_0 + K * ((t/Dt)**5) * a + K * ((t/Dt)**3) * b model1 = rho_0 + K * ((t/Dt)**5) * a #x1 = numpy.log(t/Tk) #p = numpy.pi #x2 = ((x1**2) + (1.)*p**2)**0.5 mag = model1 -j*numpy.log(t) return mag-rho
def foc(gov_policies, psi, sig, start=0, end=10): # Initialize local variables for government policies for better # readability. tax = gov_policies[0] trans = gov_policies[1] result = [] # Compute different parts of first FOC (respect tax rate) and combine part_a = integrate.quad( lambda w: dell_u_tax(w, cons(w, tax, psi, trans), hours(w, tax, psi), psi, tax) * lognorm.pdf( w, s=sig, scale=np.exp(-sig**2 / 2)), 0, 10 # set integration borders )[0] part_b = integrate.quad( lambda w: w * hours(w, tax, psi), start, end )[0] # Compute first part of the second FOC (respect transfers) part_c = integrate.quad( lambda w: lognorm.pdf(w, s=sig, scale=np.exp(-sig**2 / 2)) * dell_u_trans(cons(w, tax, psi, trans), hours(w, tax, psi), psi), start, end )[0] # Store first foc in results vector result.append(part_a + part_c * part_b) # Compute budget constraint bud_const = trans - integrate.quad( lambda w: tax * w * hours(w, tax, psi), start, end )[0] result.append(bud_const) return result
def get_f_matrix(self): '''Calculate F-matrix for step iCSD method''' el_len = self.coord_electrode.size f_matrix = np.zeros((el_len, el_len)) for j in range(el_len): for i in range(el_len): lower_int = self.coord_electrode[i] - self.h[j] / 2 if lower_int < 0: lower_int = self.h[j].units upper_int = self.coord_electrode[i] + self.h[j] / 2 # components of f_matrix object f_cyl0 = si.quad(self._f_cylinder, a=lower_int, b=upper_int, args=(float(self.coord_electrode[j]), float(self.diam[j]), float(self.sigma)), epsabs=self.tol)[0] f_cyl1 = si.quad(self._f_cylinder, a=lower_int, b=upper_int, args=(-float(self.coord_electrode[j]), float(self.diam[j]), float(self.sigma)), epsabs=self.tol)[0] # method of images coefficient mom = (self.sigma - self.sigma_top) / (self.sigma + self.sigma_top) f_matrix[j, i] = f_cyl0 + mom * f_cyl1 # assume si.quad trash the units return f_matrix * self.h.units**2 / self.sigma.units
def phi(d, dp): """vdW-DF kernel.""" from scipy.integrate import quad kwargs = dict(epsabs=1.0e-6, epsrel=1.0e-6, limit=400) cut = 35 return quad(lambda y: quad(f, 0, cut, (y, d, dp), **kwargs)[0], 0, cut, **kwargs)[0]
def get_tmax(self, p, cutoff=None): if cutoff is None: cutoff = self.cutoff if self.quad: x = np.arange(1, 10000, 1) y = np.zeros_like(x) func = self.function(x, p) func_half = self.function(x[:-1] + 1 / 2, p) y[1:] = y[0] + np.cumsum(1 / 6 * (func[:-1] + 4 * func_half + func[1:])) y = y / quad(self.function, 0, np.inf, args=p)[0] return np.searchsorted(y, cutoff) else: t1 = -np.sqrt(3 / 5) t2 = 0 t3 = np.sqrt(3 / 5) w1 = 5 / 9 w2 = 8 / 9 w3 = 5 / 9 x = np.arange(1, 10000, 1) y = np.zeros_like(x) func = self.function(x, p) func_half = self.function(x[:-1] + 1 / 2, p) y[0] = 0.5 * (w1 * self.function(0.5 * t1 + 0.5, p) + w2 * self.function(0.5 * t2 + 0.5, p) + w3 * self.function(0.5 * t3 + 0.5, p)) y[1:] = y[0] + np.cumsum(1 / 6 * (func[:-1] + 4 * func_half + func[1:])) y = y / quad(self.function, 0, np.inf, args=p)[0] return np.searchsorted(y, cutoff)
def radEinstein(self, zs): ''' SDSSObject.radEinstein(z1, z2) ============================== Estimated Einstein Radius from Single Isothermal Sphere (SIS) model Parameters: zs: source redshift Returns: None ''' # Necessary parameter H0 = 72e3 c = 299792458.0 OmegaM = 0.258 OmegaL = 0.742 vdisp = self.vdisp * 1000.0 # Function needed for numerical computation of angular diameter distance def x12(z): return 1.0 / np.sqrt((1.0 - OmegaM - OmegaL) * (1.0 + z) * (1.0 + z) + OmegaM * (1.0 + z) ** 3.0 + OmegaL) # compute ang. diam. distances Ds = ((c / H0) * quad(x12, 0.0, zs)[0]) / (1.0 + zs) Dls = ((c / H0) * quad(x12, self.z, zs)[0]) / (1.0 + zs) # return value in arcsec coeff = 3600.0 * (180.0 / np.pi) return coeff * 4.0 * np.pi * vdisp * vdisp * Dls / (c * c * Ds)
def C_l(freq1, freq2, Pk_interp, l_vals): #freqs are entered in GHz f1 = freq1*10**9 #[Hz] f2 = freq2*10**9 #[Hz] z1 = (nu21/f1)-1 z2 = (nu21/f2)-1 one_over_Ez = lambda zprime:1/numpy.sqrt(omg_m*(1+zprime)**3+omg_lambda) Dc1 = (c/H0)*integrate.quad(one_over_Ez,0,z1)[0] Dc2 = (c/H0)*integrate.quad(one_over_Ez,0,z2)[0] C_ls = [] for i in range(len(l_vals)): ans2=0 for kk in range(len(k_data)): #val = (2/numpy.pi)*Pk_interp(k_data[kk])*(k_data[kk]**2)*scipy.special.sph_jn(l_vals[i],k_data[kk]*Dc1)[0][l_vals[i]]*scipy.special.sph_jn(l_vals[i],k_data[kk]*Dc2)[0][l_vals[i]] #ans2+=val J_sub = (1/2.)*(2*l_vals[i]+1) x1 = k_data[kk]*Dc1 x2 = k_data[kk]*Dc2 bessel1 = numpy.sqrt(numpy.pi/2)*scipy.special.jn(J_sub,x1)/(numpy.sqrt(x1)) bessel2 = numpy.sqrt(numpy.pi/2)*scipy.special.jn(J_sub,x2)/(numpy.sqrt(x2)) val = (2/numpy.pi)*Pk_interp(k_data[kk])*(k_data[kk]**2)*bessel1*bessel2 ans2 += val ans2*=(k_data[1]-k_data[0]) C_ls.append(ans2) return C_ls
def complex_quad(func, a, b, **kw_args): func_re = lambda t: np.real(func(t)) func_im = lambda t: np.imag(func(t)) I_re = quad(func_re, a, b, **kw_args)[0] I_im = quad(func_im, a, b, **kw_args)[0] return I_re + 1j*I_im
def potential_from_particles(self, nbins = None, r_bins = None): """ Uses the binned density profile from the particles to calculate (approximately) what the total gravitational potential should be. This should be compared to the exact potential generated by the N-body calculation. With enough particles, they should be the same. """ r, dens = self.density_profile(nbins, r_bins) nbins = np.size(r) dens_function = interpolate.interp1d(r, dens) integrand_1 = lambda x : x * x * dens_function(x) integrand_2 = lambda x : x * dens_function(x) rmin, rmax = np.min(r), np.max(r) pot = np.zeros(nbins) for i in np.arange(nbins): A = integrate.quad(integrand_1, rmin, r[i])[0] B = integrate.quad(integrand_2, r[i], rmax)[0] pot[i] = A/r[i] + B pot = - 4.0 * np.pi * cgs.G * pot return r, pot
def getConsumerWelfare(self, equilibriumValue): """ Calculate total consumer welfare W = \int_{A} u(t,A) dt +\int_{B} u(t,B) dt. Can break this up as: W = Network Effect Benefits + Heterogeneity Stuff W = t^{e} * \nu(t^{e}, A) + (1-t^{e}) * \nu(1-t^{e}) + Heterogeneity NB: we are assuming demand has been normalized to 1 @param equilibriumValue: the equilibrium to use when calculating social welfare @return: total consumer welfare """ networkAPart = equilibriumValue * self._nu_A(equilibriumValue) # Remember _nu_B defined a function of network A size ... networkBPart = (1.0 - equilibriumValue) * \ self._nu_B(equilibriumValue) hetAPart = integrate.quad(self._het_A, 0, equilibriumValue)[0] hetBPart = integrate.quad(self._het_B, equilibriumValue, 1)[0] priceAPart = equilibriumValue * self._priceFunction_A(self._price_A) priceBPart = equilibriumValue * self._priceFunction_B(self._price_B) # logger.debug('Welfare: (netA, netB, hetA, hetB): ' + \ # str((networkAPart, networkBPart, hetAPart, hetBPart))) totalWelfare = (networkAPart + networkBPart + hetAPart + hetBPart + priceAPart + priceBPart) return totalWelfare
def funclg(E,verbose=False): try: t = E.shape gans = [] problems = [] for i in range(len(E)): rapoval = rapo(E[i]) temp = intg.quad(lginterior,0,1./rapoval,args = E[i],full_output = 1) t = temp[0] try: if temp[3] != '': if verbose == True: print 'g, E = ',E[i], 'message = ', temp[3] problems.append(i) except (IndexError,TypeError): pass gans.append(-pi*t) return array(gans),problems except (AttributeError,TypeError) as e: problem = [] rapoval = rapo(E) temp = intg.quad(lginterior,0,1./rapoval,args = E,full_output = 1) t = temp[0] try: if temp[3] != '': if verbose == True: print 'g, E = ',E, 'message = ', temp[3] problem = [E] except (IndexError,TypeError): pass return -pi*t, problem
def funcf(E,verbose=False): epsilon = 0 try: t = E.shape fans = [] problems = [] for i in range(len(E)): print i+1, ' of ', len(E) rapoval = rapo(E[i]) prefactor = (1./(sqrt(8)*pi**2*(model.Mnorm + 10**Mencgood(log10(rapoval))))) temp = intg.quad(finterior,epsilon,1-epsilon,args=(E[i],rapoval),full_output = 1) t = temp[0] try: if temp[3] != '': if verbose == True: print 'f, E = ',E[i],'message = ',temp[3] problems.append(i) except IndexError: pass fans.append((prefactor*t)[0]) return array(fans),problems except AttributeError: rapoval = rapo(E) prefactor = (1./(sqrt(8)*pi**2*(model.Mnorm + 10**Mencgood(log10(rapoval))))) temp = intg.quad(finterior,epsilon,1-epsilon,args=(E,rapoval),full_output = 1) t = temp[0] problem = [] try: if temp1[3] != '': if verbose == True: print 'f, E = ',E,'message = ',temp1[3] problem = [E] except IndexError: pass return prefactor*t, problem
def funcMenc(r,verbose=False): try: problems = [] t = r.shape Mencs = [] for i in range(len(r)): temp = intg.quad(Minterior,0,r[i],full_output=1,epsabs = tol,epsrel = tol) try: if temp[3]!='': problems.append(i) if verbose==True: print 'Menc, r = ',r[i],'message = ',temp[3],'\n' except (IndexError, TypeError): pass Mencs.append(4*pi*temp[0]) return array(Mencs),array(problems) except (AttributeError,TypeError): problem = [] temp = 4*pi*intg.quad(Minterior,0,r)[0] try: if temp[3]!='': problems = [r] if verbose==True: print 'Menc, r = ',r,'message = ',temp[3],'\n' t = temp[0] except (IndexError,TypeError): t = temp return t,problem
def psi2(r,verbose=False): try: problems = [] t = r.shape psi2s = [] for i in range(len(r)): temp=intg.quad(psi2interior,r[i],inf,full_output=1,epsabs = tol,epsrel = tol) try: if temp[3]!='': if verbose==True: print 'psi2, index =',i,'r = ',r[i],'message = ',temp[3],'\n' problems.append(i) except (IndexError,TypeError): pass psi2s.append(4*pi*temp[0]) return array(psi2s),problems except AttributeError: problem = [] temp = 4*pi*intg.quad(psi2interior,r,inf)[0] try: if temp[3]!='': if verbose==True: print 'psi2, r = ',r,'message = ',temp[3],'\n' problem = [r] t = temp[0] except (IndexError,TypeError): t = temp return t, problem
def BG(params,t,rho): K = params['K'].value K2 = params['K2'].value Dt = params['Dt'].value rho_0 = params['rho_0'].value j1 = params['j1'].value Tk = params['Tk'].value a=numpy.ones(len(t)) b=numpy.ones(len(t)) c=numpy.ones(len(t)) for i in range(len(t)): func_ph = lambda x:(x**5)/((numpy.exp(x)-1)*(1-numpy.exp(-x)))#((numpy.sinh(x))**2) func_sd = lambda x:(x**3)/((numpy.exp(x)-1)*(1-numpy.exp(-x))) func_ee = lambda x:(x**2)/((numpy.exp(x)-1)*(1-numpy.exp(-x))) ph = quad(func_ph,0,(Dt/t[i])) sd = quad(func_sd,0,(Dt/t[i])) ee = quad(func_ee,0,(Dt/t[i])) a[i]=ph[0] #Phonon scattering b[i]=sd[0] # s-d scattering c[i]=ee[0] # e-e scattering model3 = rho_0 + K * ((t/Dt)**5) * a + K2 * ((t/Dt)**3) * b + K * ((t/Dt)**2) * c model2 = rho_0 + K * ((t/Dt)**5) * a + K2 * ((t/Dt)**3) * b model1 = rho_0 + K * ((t/Dt)**5) * a x1 = numpy.log(t/Tk) p = numpy.pi x2 = ((x1**2) + p**2)**0.5 Py = model1 + j1*(1-(x1/x2)) return Py-rho
def test_hrg(): ID, info = random.choice(list(species_dict.items())) m = info["mass"] g = info["degen"] sign = -1 if info["boson"] else 1 prefactor = g / (2 * np.pi ** 2 * hbarc ** 3) if info["has_anti"]: prefactor *= 2 T = np.random.uniform(0.13, 0.15) hrg = HRG(T, species=[ID], res_width=False) assert_almost_equal(hrg.T, T, delta=1e-15, msg="incorrect temperature") n = np.arange(1, 50) density = prefactor * m * m * T * ((-sign) ** (n - 1) / n * special.kn(2, n * m / T)).sum() assert_almost_equal(hrg.density(), density, delta=1e-12, msg="incorrect density") def integrand(p): E = np.sqrt(m * m + p * p) return p * p * E / (np.exp(E / T) + sign) energy_density = prefactor * integrate.quad(integrand, 0, 10)[0] assert_almost_equal(hrg.energy_density(), energy_density, delta=1e-12, msg="incorrect energy density") def integrand(p): E = np.sqrt(m * m + p * p) return p ** 4 / (3 * E) / (np.exp(E / T) + sign) pressure = prefactor * integrate.quad(integrand, 0, 10)[0] assert_almost_equal(hrg.pressure(), pressure, delta=1e-12, msg="incorrect pressure")
def modelFunc(ti, p, tau, t0): p = 0.078 z = abs(ti - t0) / tau def delta(p, r, z): if ((r >= (z + p)) or (r <= (z - p))): # print "boO" return 0 elif ((r + z) <= p): #print "boo dos" return 1 else: #print "ay" return ((1/pi) * acos((z**2 - p**2 + r**2)/(2*z*r))) def I(r): mu = (1 - r**2)**0.5 return 1 - (1 - (mu**0.5)) def function1(r): deltaresult = delta(p, r, z) # stored delta value in deltaresult return I(r) * (1 - deltaresult) * (2*r) def function2(r): return I(r) * 2*r func1 = integrate.quad(function1, 0, 1) func2 = integrate.quad(function2, 0, 1) flux = func1[0] / func2[0] return flux
def test_b_less_than_a_3(self): def f(x): return 1.0 val_1, err_1 = quad(f, 0, 1, weight='alg', wvar=(0, 0)) val_2, err_2 = quad(f, 1, 0, weight='alg', wvar=(0, 0)) assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
def test_b_less_than_a(self): def f(x, p, q): return p * np.exp(-q*x) val_1, err_1 = quad(f, 0, np.inf, args=(2, 3)) val_2, err_2 = quad(f, np.inf, 0, args=(2, 3)) assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
def test_b_less_than_a_2(self): def f(x, s): return np.exp(-x**2 / 2 / s) / np.sqrt(2.*s) val_1, err_1 = quad(f, -np.inf, np.inf, args=(2,)) val_2, err_2 = quad(f, np.inf, -np.inf, args=(2,)) assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
def nc_of_norm(): f1 = lambda x: x**4 f2 = lambda x: x**2-x+2 rv = norm(loc = 2 , scale=20) print rv.mean() print rv.var() print rv.moment(1) print rv.moment(4) # moments的参数可为m(均值),v(方差值),s(偏度),k(峰度),默认为mv print rv.stats(moments = 'mvsk') # 3)scipy.stats.norm.expect(func,loc=0,scale=1)函数返回func函数相对于正态分布的期望值,其中函数f(x)相对于分布dist的期望值定义为E[x]=Integral(f(x) * dist.pdf(x)) print(norm.expect(f1, loc=1, scale=2)) print(norm.expect(f2, loc=2, scale=5)) # (2)lambda argument_list:expression用来表示匿名函数 # (3)numpy.exp(x)计算x的指数 # (4)numpy.inf表示正无穷大 # (5)scipy.integrate.quad(func,a,b)计算func函数从a至b的积分 # (6)scipy.stats.expon(scale)函数返回符合指数分布的参数为scale的随机变量rv # (7)rv.moment(n,*args,*kwds)返回随机变量的n阶距 #1st non-center moment of expon distribution whose lambda is 0.5 E1 = lambda x: x*0.5*np.exp(-x/2) #2nd non-center moment of expon distribution whose lambda is 0.5 E2 = lambda x: x**2*0.5*np.exp(-x/2) print(integrate.quad(E1, 0, np.inf)) print(integrate.quad(E2, 0, np.inf))
def get_FO(self,x,y,z,Q2,qT2,muR2,muF2,charge,ps='dxdQ2dzdqT2',method='gauss'): D=self.D D['A1']=1+(2/y-1)**2 D['A2']=-2 w2=qT2/Q2*x*z w=w2**0.5 xia_=lambda xib: w2/(xib-z)+x xib_=lambda xia: w2/(xia-x)+z integrand_xia=lambda xia: self.get_M(xia,xib_(xia),x/xia,z/xib_(xia),Q2,muF2,qT2,charge) integrand_xib=lambda xib: self.get_M(xia_(xib),xib,x/xia_(xib),z/xib,Q2,muF2,qT2,charge) if method=='quad': FO = quad(integrand_xia,x+w,1)[0] + quad(integrand_xib,z+w,1)[0] elif method=='gauss': integrand_xia=np.vectorize(integrand_xia) integrand_xib=np.vectorize(integrand_xib) FO = fixed_quad(integrand_xia,x+w,1,n=40)[0] + fixed_quad(integrand_xib,z+w,1,n=40)[0] if ps=='dxdQ2dzdqT2': s=x*y*Q2 prefactor = D['alphaEM']**2 * self.SC.get_alphaS(muR2) prefactor/= 2*s**2*Q2*x**2 prefactor*= D['GeV**-2 -> nb'] return prefactor * FO else: print 'ps not inplemented' return None
def test_ctypes_variants(self): sin_0 = get_clib_test_routine('_sin_0', ctypes.c_double, ctypes.c_double, ctypes.c_void_p) sin_1 = get_clib_test_routine('_sin_1', ctypes.c_double, ctypes.c_int, ctypes.POINTER(ctypes.c_double), ctypes.c_void_p) sin_2 = get_clib_test_routine('_sin_2', ctypes.c_double, ctypes.c_double) sin_3 = get_clib_test_routine('_sin_3', ctypes.c_double, ctypes.c_int, ctypes.POINTER(ctypes.c_double)) sin_4 = get_clib_test_routine('_sin_3', ctypes.c_double, ctypes.c_int, ctypes.c_double) all_sigs = [sin_0, sin_1, sin_2, sin_3, sin_4] legacy_sigs = [sin_2, sin_4] legacy_only_sigs = [sin_4] # LowLevelCallables work for new signatures for j, func in enumerate(all_sigs): callback = LowLevelCallable(func) if func in legacy_only_sigs: assert_raises(ValueError, quad, callback, 0, pi) else: assert_allclose(quad(callback, 0, pi)[0], 2.0) # Plain ctypes items work only for legacy signatures for j, func in enumerate(legacy_sigs): if func in legacy_sigs: assert_allclose(quad(func, 0, pi)[0], 2.0) else: assert_raises(ValueError, quad, func, 0, pi)
def computeColor(self, filtX, filtY, z): """Compute color (flux in filter X - filter Y) of SED at redshift z, return color in magnitudes @param filtX lower wavelength filter @param filtY higher wavelength filter @param z redshift of SED """ if filtX not in self.filterDict: emsg = "Filter " + filtX + " is not in the filter dictionary" raise LookupError(emsg) if filtY not in self.filterDict: emsg = "Filter " + filtY + " is not in the filter dictionary" raise LookupError(emsg) if filtX == filtY: raise ValueError("ERROR! cannot have color as difference between same filter") # define integral limits by filter extents aX, bX = self.filterDict[filtX].returnFilterRange() aY, bY = self.filterDict[filtY].returnFilterRange() int1 = integ.quad(self._integrand1, aX, bX, args=(z, filtX))[0] int2 = integ.quad(self._integrand1, aX, bX, args=(z, filtY))[0] # Do we need this zero-point term? int3 = integ.quad(self._integrand2, aX, bX, args=(filtX))[0] int4 = integ.quad(self._integrand2, aX, bX, args=(filtY))[0] zp = -2.5*math.log10(int4/int3) return -2.5*math.log10(int1/int2) + zp
def complex_integral(func,a,b,args,intype='stupid'): real_func = lambda z: np.real(func(z,*args)) imag_func = lambda z: np.imag(func(z,*args)) if intype == 'quad': real_int = integ.quad(real_func,a,b) imag_int = integ.quad(imag_func,a,b) # print(real_int) # print(imag_int) return real_int[0] + 1j * imag_int[0] elif intype == 'quadrature': real_int = integ.quadrature(real_func,a,b) imag_int = integ.quadrature(imag_func,a,b) # print(real_int) # print(imag_int) return real_int[0] + 1j * imag_int[0] elif intype == 'romberg': real_int = integ.romberg(real_func,a,b) imag_int = integ.romberg(imag_func,a,b) # print(real_int) # print(imag_int) return real_int + 1j * imag_int elif intype == 'stupid': Npoints = 500 z,dz = np.linspace(a,b,Npoints,retstep=True) real_int = np.sum(real_func(z))*dz imag_int = np.sum(imag_func(z))*dz # print(real_int) # print(imag_int) return real_int + 1j*imag_int
print("MA548\nHW2\nHangquan Qian\n1/29/18") print("\n[Question 1A] \n ") q1(7182,20) print("\n[Question 1B] \n") q1(1009,30) print("\n[Question 2] \n") q2(16,5,3,7,20) print("\nYes, this LCG has a full cycle, each 15 numbers are a combo") print("\n[Question 3] \n") q3(23,66,14) print("\n[Question 4A] \n") for i in range(1,6): print(pow(10,i), ":", q4A(pow(10,i))) print("Exact Answer:", quad(q4AC,0,1)) print("\n[Question 4B] \n") for i in range(1,6): print(pow(10,i), ":", q4B(pow(10,i))) print("Exact Answer:", quad(q4BC,-2,2)) print("\n[Question 4C] \n") for i in range(1,6): print(pow(10,i), ":", q4C(pow(10,i))) print("Exact Answer:", quad(q4CC,-numpy.inf,numpy.inf)) print("\n[Question 4D] \n") for i in range(1,6): print(pow(10,i), ":", q4D(pow(10,i))) print("Exact Answer:", integrate.nquad(q4DC,[[0,1],[0,1]])) print("\n[Question 4E] \n\n\n\n\n") print("\n[Question 5] \n") for i in range(1,6):
return (cos(x) - (16 * sin(x) / (x + 1)) - (240 * cos(x) / (x + 1)**2) + (3360 * sin(x) / (x + 1)**3) + (43680 * cos(x) / (x + 1)**4) - (524160 * sin(x) / (x + 1)**5) - (5765760 * cos(x) / (x + 1)**6) + (57657600 * sin(x) / (x + 1)**7) + (518918400 * cos(x) / (x + 1)**8) - (4151347200 * sin(x) / (x + 1)**9) - (29059430400 * cos(x) / (x + 1)**10) + (174356582400 * sin(x) / (x + 1)**11) + (871782912000 * cos(x) / (x + 1)**12) - (3487131648000 * cos(x) / (x + 1)**13) + (10461394944000 * cos(x) / (x + 1)**14) + (20922789888000 * cos(x) / (x + 1)**15) + (20922789888000 * cos(x) / (x + 1)**16)) / (x + 1) np_integrate = integrate.quad(main_func, a, b)[0] def trapezium_method(a_limit: float, b_limit: float) -> float: """ Implementation of trapezium method :param a_limit: left limit :param b_limit: right limit :return: result """ parts, analytical_fault = trapezium_method_fault(a_limit, b_limit) result = (main_func(a_limit) + main_func(b_limit)) / 2 h = (b_limit - a_limit) / parts print(f'N = {parts}') print(f'Analytical fault = {analytical_fault}') index = a_limit + h
def length(self): """Integrates the Jacobian of the limits of the element to find the length""" return quad(self.J, self.limits[0], self.limits[1])[0]
def length(self, xi0=0, xi1=1): """Find length of curve in the interval [xi0,xi1]""" return quad(self.J, xi0, xi1)[0]
import seaborn as sns m = 1 @pymonad.curry def normal(mu, sigma, v): return 2*m*v/(sigma * np.sqrt(2 * np.pi)) * \ np.exp( - (0.5 * m * v**2 - mu)**2 / (2 * sigma**2) ) #integrate to check CDF mu, sigma = 0, 0.25 start, end = 0, mu + 16 * sigma print("check the integral of the CDF is 1") print(quad(normal(mu, sigma), start, end)) sns.set() plt.rc('text', usetex=True) for s in [0.25, 0.5, 1, 1.25]: mu, sigma = 0, s x = np.arange(0, mu + 3 * (1 / s) * sigma, 0.01) y = list(map(normal(mu, sigma), x)) plt.plot(x, y, label="$\displaystyle \sigma={}$".format(s)) plt.xlabel(r"$\displaystyle v$") plt.ylabel(r"$\displaystyle f_V(|v|)$") plt.legend() #plt.show() plt.savefig('figures/velocity.svg')
def get_Q(self): func = lambda h: self.rho * math.exp(-h / (self.H2 * 1000)) Q = Integrate.quad(func, 0, 100000) return Q[0] / 10000
def calc_flux(modelname, parameters, emin, emax, redshift=None, photonflux=False): """ This is for GENERAL USE ONLY! Most of the time you want to use these! Any time you are calculating flux, fluence, or eiso for the first time and reading results from a program's FITS files, you will want the functions within the xspec and rmfit directories! Parameters: ----------- modelname : str, model name. Full name with + between additive models. parameters : ordered dict, see below. emin : float, min energy integrand. emax : float, max energy integrand. redshift : float, redshift. Default is None. If redshift=None, then an un k-corrected energy flux or photon flux will be returned. photonflux : True or False. If photonflux=False, energy flux will be returned. If photonflux=True, a photon flux will be returned. ** Default is photonflux=False. parameters dict. ---------------- For each model component in the modelname, the fluxes are calculated separately and them summed together. For example, if you modelname is 'grbm+bbody+lpow', then the flux for 'grbm' is calcualted first and stroed in a Flux list, then 'bbody' flux is calculated second and stored in the Flux list, then 'lpow' flux is calculated and stored in the Flux list. At the end, the Total Flux is found by summing the values in the list together. TotalFlux = sum(Fluxlist) Hence the reason for passing the parameters for each model component in a sub-dict within the main parameters dict. E.g., parameters = {'grbm': {'alpha': -1.23, 'beta':-2.56, ...}, 'bbody': {'kT':54.3, ...}, 'lpow': {'plIndex':-1.49, ...} } we will provide more accurate examples of these in a moment. It is recommended that you use OrderedDict from collections from collections import OrderedDict parameters = OrderedDict() parameters['grbm'] = OrderedDict() # sub-dict for 'grbm' parameters['grbm']['alpha'] = -1.0 parameters['grbm']['beta'] = -2.5 parameters['grbm']['enterm'] = 500.0 parameters['grbm']['norm'] = 0.01 parameters['grbm']['entype'] = 'epeak' # This is how you determine which char. eng term. parameters['bbody'] = OrderedDict() parameters['bbody']['kT'] = 54.1 parameters['bbody']['norm'] = 0.1 parameters['lpow'] = OrderedDict() # sub-dict for lpow parameters['lpow']['plIndex']= -1.0 parameters['lpow']['norm']= 0.001 The exact parameter names are insignificant, just as long as they are in the correct order. They are flattened into a list and then passed to the functions. parameters['grbm']['entype'] !!!!!!!! WARNING !!!!!!!! The """ if isinstance(parameters, dict) is False: raise NotADictError("'parameters' must be a dictionary.") for m in modelname.split('+'): if m not in parameters.keys(): msg = (" Use nested dicts for passing model parameters via " "the 'parameters' attribute. " " Run \n\tparameter_dict_example('%s')" " for an example." % modelname) raise NotADictError(msg) keVtoerg = 1.60217657E-9 if redshift is not None: emin = emin / (1. + redshift) emax = emax / (1. + redshift) else: msg2 = ("\n *** WARNING: *** \n You are using observer-frame " "fluxes. Eiso requires rest-frame fluxes. Please use " "redshift if computing fluxes for Eiso. \n") print(msg2) # Each model component's flux is computed separately and then summed. model_parts = modelname.split('+') totalFlux = [] for m in model_parts: # parlst - list of parameter values in order that funciton needs them to be. pars = parameters[m].values() func = 'lambda x,values: x * %s(x, *values)' % (m) # x - energy func = eval(func) Flux = integrate.quad(func, emin, emax, args=(pars), limit=100)[0] if photonflux is True: totalFlux.append(Flux) else: nrgFlux = Flux * keVtoerg # photon flux to energy flux conversion. totalFlux.append(nrgFlux) return np.sum(totalFlux) modelOptions = ["lpow", "copl", "band", "grbm", "sbpl", "bbody"] keVtoerg = 1.60217657E-9 if redshift is not None: emin = emin / (1. + redshift) emax = emax / (1. + redshift) else: #warnings.warn(msg, UserWarning, stacklevel=1) # msg = ("\n *** WARNING: *** \n You are using observer-frame " # "fluxes. Eiso requires rest-frame fluxes. Please use " # "redshift if computing fluxes for Eiso. \n") msg = ("\nNo redshift provided, calculating observer-frame flux. " "If calculating for Eiso energy, pass a redshift. Eiso " "is a rest-frame energetic.") warnings.warn(msg, RedshiftWarning, stacklevel=1)
#Program to calculate the Stefan Boltzmann constant from scipy.integrate import quad import numpy as np #provided constants. hbar- Plank's constant, boltz- Boltz constant, c- Speed of light hbar = 1.054571e-34 boltz = 1.380649e-23 c = 2.99792e8 #Function to perform integration def Integration(x): t1 = x**3 t2 = np.exp(x) - 1 integral_value = t1 / t2 return integral_value # integrating the function from 0 to infinity integral_val, err = quad(Integration, 0, np.inf) #Calculating the Stefan-Boltzmann constant t3 = boltz**4 * integral_val t4 = 4 * np.pi**2 * c**2 * hbar**3 Stefan_Boltzmann_constant = t3 / t4 #Formatting the Stefan-Boltzmann constant Stefan_Boltzmann_constant = '{:.3e}'.format(Stefan_Boltzmann_constant) print("The Stefan Boltzmann constant is,", Stefan_Boltzmann_constant)
weight_photon = gamma/eta*h_planck*chi/1.7/(m0*v0**2)*137/dt ppx,ppy = pxpy_to_energy_rr(chi, weight_photon, eta) plt.plot(ppx, ppy, linestyle='-', color='g', marker='o',linewidth=3,markersize=3, label='my_classical') b0 = 205.0 g0 = 2.0 eta = g0*b0/4.1e5 #eta = 0.1 chi = np.logspace(np.log10(1e-5*eta**2),np.log10(0.499999*eta),2000) chi_c = np.logspace(np.log10(1e-5*eta**2),np.log10(1e1*eta**2),2000) y = 4*chi/(3*eta*(eta-2*chi)) y_c = 4*chi_c/(3*eta*eta) F_chi = np.zeros_like(chi) F_chi_c = np.zeros_like(chi_c) for i in range(np.size(chi)): result = integrate.quad(lambda x: kv(1.6666666667,x), y[i], 1e3*y[i]) F_chi[i] = 4*chi[i]**2/eta**2*y[i]*kv(0.6666666667,y[i])+(1-2*chi[i]/eta)*y[i]*result[0] # print(result) result = integrate.quad(lambda x: kv(1.6666666667,x), y_c[i], 1e3*y_c[i]) F_chi_c[i]=y_c[i]*result[0] #F_chi_s = 8*chi**2/3/(3)**0.5/np.pi/eta**4*((1+(1-2*chi/eta)**(-2))*0.921*(y)**(-5.0/3) + 2*(1-2*chi/eta)**(-1)*0.307*(y)**(-5.0/3) + (2*chi/eta)**2*(1-2*chi/eta)**(-2)*0.307*(y)**(-5.0/3) ) plt.plot(chi, F_chi, '-k', linewidth=3, label=r'$F(\eta,\chi)\approx\frac{4\chi^2}{\eta^2}yK_{2/3}(y)+(1-\frac{2\chi}{\eta})y\int_{y}^{\infty}K_{5/3}(t)dt;\ y=\frac{4\chi}{3\eta(\eta-2\chi)}$') plt.plot(chi_c, F_chi_c, '--k', linewidth=3, label=r'$f_{synch}\approx y_c\int_{y_c}^{\infty}K_{5/3}(u)du;\ y_c=\frac{4\chi}{3\eta^2}$') plt.grid(which='major',color='k', linestyle='--', linewidth=0.3) plt.legend(loc='best',fontsize=12,framealpha=0.0) plt.xticks(fontsize=font_size); plt.yticks(fontsize=font_size); plt.xlabel(r'$\chi$',fontdict=font) plt.ylabel(r'$F(\eta,\chi)$',fontdict=font) plt.xscale('log') plt.xlim(1e-5*eta**2,1e1*eta**2)
def sortino(risk_free,degree_of_freedom,growth_rate,minimum): v=np.sqrt(np.abs(integrate.quad(lambda g:((risk_free-g)**2)*t.pdf(g,degree_of_freedom),risk_free,minimum))) s=(growth_rate-risk_free)/v[0] return s
def angpowspec_integration_without_j(ell, redshift): return integrate.quad( lambda x: ((chi_s[redshift] - x) / chi_s[redshift])**2 * np.interp( ell / x, PS, dPS), 0, chi_s[redshift])[0]
def Tadiabatic(P, t0, p0, param): """ Compute the adiabatic profile from (T0,P0) to P""" intexp = quad(integrande_eq, p0, P, args=(t0, param)) intexp = intexp[0] return t0 * np.exp(intexp / param['Cp'])
@author: Blaze """ #Importando bibliotecas import scipy.stats as st import scipy.integrate as inte import numpy as np import pandas as pd #g é a probabilidade de um custo de produção x ser inferior ao valor mínimo de #uma amostra de 7 elementos com distribuição double weibull g= lambda x: (1-st.dweibull.cdf(x,2.29,41.57,24.71))**7 #Pegando os custos dados custos=np.matrix(pd.read_excel("custos_g7 (2).xlsx",index_col=0)) lcustos=[] for i in range(100): lcustos+=[custos[i,0]] #Escolhendo estratégia ótima para cada custo. #Obs.:Como a função scipy.integrate.quad só dá a integral em um intervalo e #não a equação da integral e se sabe que a integral de g tende a 0 no infinito, #a integral de g(x) é igual a -inte.quad(g,x,np.inf). lb=[] for i in range(100): lb+=[custos[i,0]+(inte.quad(g,custos[i,0],np.inf)[0]/g(custos[i,0]))] #Escrevendo planilha de lances d={'Custos': lcustos,"Lances": lb} df1=pd.DataFrame(d) df1.to_excel('Lances.xlsx')
def angpowspec_integration_with_j(ell, j, redshift): return integrate.quad( lambda x: ((chi_s[redshift] - x) / chi_s[redshift])**2 * np.interp( (2 * ((ell / x)**2 + (2 * 3.14 * j / chi_s[redshift])**2))**0.5, PS, dPS), 0, chi_s[redshift])[0]
def integral_bounded(fn, lb, ub): integral, _ = integrate.quad(fn, lb, ub) return integral
def PZTSalisNorm(pT,M_S,q,T,eta): y = (pT*np.power(1+(q-1)*np.sqrt(pT*pT+M_S*M_S)/T,-q/(q-1)))/integrate.quad(lambda x : x*np.power(1+(q-1)*np.sqrt(x*x+M_S*M_S)/T,-q/(q-1)),0,10000)[0] / np.tan(2*np.arctan(np.exp(-eta))) return y
def integrate_power_spectrum_cpp(self): """ Function to use the C++ routine for the power spectrum integration. This should offer a significant speed improvement by using the ctypes library, however it appears to not offer such improvements as imagined. """ ell_list = self.transfer.get_ell_list() c_ell_list = [] start_time = time.time() # Import required modules for integration using the C++ code import os import ctypes from scipy import LowLevelCallable # Use the ctypes library to initialise the functions correctly lib = ctypes.CDLL(os.path.abspath('../cpp/build/libCppIntegrand.so')) lib.get_twopf_data.restype = ctypes.c_double lib.get_transfer_data.restype = ctypes.c_double lib.get_integrand.restype = ctypes.c_double lib.get_integrand.argtypes = [ctypes.c_double] lib.get_log_integrand.restype = ctypes.c_double lib.get_log_integrand.argtypes = [ctypes.c_double, ctypes.c_void_p] print('--- Starting two-point function integral ---') twopf_k_range = np.logspace(-6, 1.7, num=401, dtype=float) twopf_data = np.array(self.database.get_data(), dtype=float) twopf_k_range_ctype = twopf_k_range.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) twopf_data_ctype = twopf_data.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) lib.set_twopf_data(twopf_k_range_ctype, twopf_data_ctype, len(twopf_data)) for index, ell in enumerate(ell_list): transfer_k, transfer_data = self.transfer.get_transfer(index) transfer_k = np.array(transfer_k, dtype=float) transfer_data = np.array(transfer_data, dtype=float) transfer_k_ctype = transfer_k.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) transfer_data_ctype = transfer_data.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) lib.set_transfer_data(transfer_k_ctype, transfer_data_ctype, len(transfer_k)) ell_c = ctypes.c_double(ell) user_data = ctypes.cast(ctypes.pointer(ell_c), ctypes.c_void_p) func = LowLevelCallable(lib.get_log_integrand, user_data) k_list = np.logspace(-15, 4, num=8024) integrand_list = [] for k in k_list: c_k = ctypes.c_double(k) integrand_list.append(lib.get_integrand(c_k)) result, err = sciint.quad(func, -10, 1, epsabs=1E-18, epsrel=1E-18, limit=5000) # result *= ell * (ell + 1) / (2 * np.pi) # Multiply by common factor when using C_ell values c_ell_list.append(result) print('--- Finished two-point function integral ---') end_time = time.time() print('Time taken = ' + str(end_time - start_time)) return ell_list, c_ell_list
from scipy.integrate import quad import numpy as np md = 3.3 R = 0.26 mr = 1.2 L = 0.74 mi_each_r = mr / L * quad(lambda x: x * x, 0, L)[0] print(mi_each_r) mi_d = 0.5 * md * R * R print(mi_d) mi = 5 * mi_each_r + mi_d print(mi) t = 3.3 a = 2 * 14 * 2 * np.pi / t / t print(a) w = a * t print(w) print(0.5 * 1.207 * w * w) print(w * 2**0.5 / 2) print((w - 37.697188) / 3.3)
def Calc_Flux(model, Pars, emin=10., emax=10000., redshift=None): ''' Calc_Flux(model, Pars, emin=10., emax=10000., redshift=None) model: str, model name. ex: 'grbm', 'grbm+bbody', 'grbm+bbody+lpow' all individual model options: grbm, sbpl, cutoffpl, lpow, and bbody Pars: dict, model parameters. SEE BELOW. emin: float, lower energy integration limit. Do not k-correct yourself. emax: float, upper energy integration limit. Do not k-correct yourself. redshift: float, redshift of GRB for k-correcting. If not k-correcting, do not enter anything. kcorrect: [True|False] True will use k-correction: emin/(1.+redshift) to emax/(1.+redshift) # REGARDLESS OF WHETHER THERE IS ONE MODEL OR MORE THAN ONE, PARAMETER DICTIONARIES SHOULD # ALWAYS BE SET UP THIS WAY. THIS IS TO ENSURE PARAMETERS BETWEEN TWO DIFFERENT MODELS DO NOT GET MIXED UP. pars = {'grbm': {'alpha': -1.0, 'beta': -2.5, 'enterm': 300.0, 'norm': 0.01, 'entype': 'epeak'}, 'sbpl': {'alpha': -1.0, 'beta': -2.5, 'enterm': 300.0, 'norm': 0.01, 'entype': 'epeak'}, 'cutoffpl': {'alpha': -1.0, 'enterm': 300.0, 'norm': 0.01, 'entype': 'epeak'}, 'lpow': {'index': -1.0, 'norm': 0.001}, 'bbody': {'kT': 10.0, 'norm': 0.001} } ''' keVtoerg = 1.60217657E-9 if redshift is not None: emin_K = emin / (1. + redshift) emax_K = emax / (1. + redshift) else: print('\n *** WARNING: NOT USING K-CORRECTED ENERGIES. *** \n') emin_K = emin emax_K = emax if 'grbm' == model: function = lambda energy: energy * BAND(energy, P['grbm']['alpha'], P['grbm']['beta'], P['grbm']['enterm'], P['grbm']['norm'], entype=P['grbm']['entype']) if 'sbpl' == model: function = lambda energy: energy * SBPL(energy, P['sbpl']['alpha'], P['sbpl']['beta'], P['sbpl']['enterm'], P['sbpl']['norm'], entype=P['sbpl']['entype']) if 'cutoffpl' == model: function = lambda energy: energy * COPL(energy, P['cutoffpl']['alpha'], P['cutoffpl']['enterm'], P['cutoffpl']['norm'], entype=P['cutoffpl']['entype']) if 'lpow' == model: function = lambda energy: energy * LPOW(energy, P['lpow']['alpha'], P[ 'lpow']['norm']) if 'bbody' == model: function = lambda energy: energy * BBODY(energy, P['bbody']['kT'], P[ 'bbody']['norm']) Flux = integrate.quad(function, emin_K, emax_K, limit=100)[0] * keVtoerg nrgFlux.append(Flux) nrgFlux = sum(nrgFlux) return nrgFlux
def integral_inf(fn): integral, _ = integrate.quad(fn, -np.inf, np.inf) return integral
###################################### #ルンゲクッタクラスのインスタンスを生成 rk4 = RK4(DIM, dt) #電磁波の角振動数 rk4.omega = omega #入射電磁波ベクトルポテンシャルの振幅 rk4.A0 = A0 ### Xnm の計算 for n1 in range(n_max + 1): for n2 in range(n_max + 1): #ガウス・ルジャンドル積分 result = integrate.quad( integral_Xnm, #被積分関数 x_min, x_max, #積分区間の下端と上端 args=(n1, n2) #被積分関数へ渡す引数 ) real = result[0] imag = 0 #行列要素 rk4.Xnm[n1][n2] = real + 1j * imag if( abs(real / L) < L ): real = 0 #ターミナルへ出力 print( "(" + str(n1) + ", " + str(n2) + ") " + str( real / L )) #初期状態の設定 rk4.bn = np.array( [ 1.0+0.0j, #基底状態 0.0+0.0j, #第1励起状態
def integrate_power_spectrum(self, use_splines=False, parallel=False): """ Function that integrates the CMB power spectrum, given the transfer function and inflationary power spectrum Args: use_splines (bool): Whether to use splines in the integration or not. By default, we use a sampled-based integration routine, and so we do not need to use splines. However, if we enable this, then we go to a functional-based integral solver using splines instead. parallel (bool): Whether we should use a parallel-based approach. By doing so, we get the speed increase of using multiple threads, however this disables the inflation power spectrum memoization, which decreases speed significantly. Returns: Two lists: - List of ell values at which the power spectrum is evaluated at - List of values of the power spectrum at these ell values. """ # Check that the database type is for a two-point function run and so can integrate the power spectrum if self.type != 'twopf': raise RuntimeError('Can not integrate the power spectrum on integration type that is not twopf.') ell_list = self.transfer.get_ell_list() c_ell_list = [] print('--- Starting two-point function integral ---') # Get the provided two-point function data twopf_dataframe = self.database.get_dataframe twopf_data = twopf_dataframe['twopf'] # Get the physical k values that are provided for the above twopf data k_data = pd.read_csv(str(self.database.k_table), sep='\t') # Ensure that each twopf value corresponds to each physical k value if twopf_data.shape[0] != k_data.shape[0]: raise RuntimeError('The length of the provided two-point function database and k_table are not equal, ' 'and so were not formed as part of the same task. Please ensure they were generated ' 'at the same time.') # Spline the twopf data over the physical k values twopf_spline = interp.CubicSpline(k_data['k_physical'], twopf_data) # If we are not using parallelization here, then we can use function memorisation on the twopf spline # to help increase the speed of the integration if not parallel: twopf_spline = memoize(twopf_spline) # Keep track on how long the integral takes using different methods. start_time = time.time() if not parallel: for index, ell in enumerate(ell_list): transfer_k, transfer_data = self.transfer.get_transfer(ell) if use_splines: # Build a spline out of the transfer function. Very important that we have it sent to return zero # for values outside the interpolated region, otherwise this induces large numerical errors. # TODO: compare with other spline methods and/or libraries to see if performance and/or accuracy # can be improved transfer_spline = interp.InterpolatedUnivariateSpline(transfer_k, transfer_data, ext='zeros') result, err = sciint.quad(log_integrand, -15, 4, args=(ell, transfer_spline, twopf_spline), epsabs=1E-10, epsrel=1E-10, limit=5000) result *= 2.725**2 # Use correct units of (mu K)^2 for the Cl's else: # If we are not using the transfer function splines, then use the points provided by CAMB # by which the transfer functions are evaluated at, then evaluate the rest of the integrand # at this point, and then use basic Simpson's rule integration to evaluate it. # This offers a significant speed improvement over using splines integrand_list = [] transfer_k = np.log(transfer_k) # Go into log space, which makes integral much nicer # Go through the points at which the transfer functions are evaluated at, and evaluate # the rest of the integrand for k_itter, transfer_data_itter in zip(transfer_k, transfer_data): integrand_list.append(2 * transfer_data_itter * transfer_data_itter * twopf_spline(np.exp(k_itter)) * 1E12 * ell * (ell + 1)) # Call SciPy Simpson's rule integration on the integrand result = sciint.simps(integrand_list, transfer_k) result *= 2.725 ** 2 # Use correct units of (mu K)^2 for the Cl's c_ell_list.append(result) else: import multiprocessing as multi big_list = [] for index, ell in enumerate(ell_list): transfer_k, transfer_data = self.transfer.get_transfer(index) temp = [ell, transfer_k, transfer_data, twopf_spline, use_splines] big_list.append(temp) pool = multi.Pool(multi.cpu_count()) c_ell_list = pool.map(integrate, big_list) print('--- Finished two-point function integral ---') end_time = time.time() print(' -- Time taken was ' + str(round(end_time - start_time, 2)) + ' seconds ---') return ell_list, c_ell_list
def Int_S(x, x_i, B, K, z_g, a, L0): var = integrate.quad(lambda nu: Snu_Model_A(nu, B, K, z_g, a, L0), x, x_i) return var[0] / (x_i - x)
def report_convergence(file1, file2): print(file1, "->", file2) stat1 = stat(file1) stat2 = stat(file2) print(stat1["dt"]["value"][0], "->", stat2["dt"]["value"][0]) errortop_l2_1 = sqrt( sum(stat1["Fluid"]["FreeSurfaceDifference"]["surface_l2norm%Top"][1:]** 2 * stat1["dt"]["value"][1:])) errortop_l2_2 = sqrt( sum(stat2["Fluid"]["FreeSurfaceDifference"]["surface_l2norm%Top"][1:]** 2 * stat2["dt"]["value"][1:])) convergencetop_l2 = log((errortop_l2_1 / errortop_l2_2), 2) print(' convergencetop_l2 = ', convergencetop_l2) print(' errortop_l2_1 = ', errortop_l2_1) print(' errortop_l2_2 = ', errortop_l2_2) errorbottom_l2_1 = sqrt( sum(stat1["Fluid"]["FreeSurfaceDifference"]["surface_l2norm%Bottom"] [1:]**2 * stat1["dt"]["value"][1:])) errorbottom_l2_2 = sqrt( sum(stat2["Fluid"]["FreeSurfaceDifference"]["surface_l2norm%Bottom"] [1:]**2 * stat2["dt"]["value"][1:])) convergencebottom_l2 = log((errorbottom_l2_1 / errorbottom_l2_2), 2) print(' convergencebottom_l2 = ', convergencebottom_l2) print(' errorbottom_l2_1 = ', errorbottom_l2_1) print(' errorbottom_l2_2 = ', errorbottom_l2_2) error_l2_1 = sqrt( sum(stat1["Fluid"]["FreeSurfaceDifference"]["surface_l2norm%Both"][1:] **2 * stat1["dt"]["value"][1:])) error_l2_2 = sqrt( sum(stat2["Fluid"]["FreeSurfaceDifference"]["surface_l2norm%Both"][1:] **2 * stat2["dt"]["value"][1:])) convergence_l2 = log((error_l2_1 / error_l2_2), 2) print(' convergence_l2 = ', convergence_l2) print(' error_l2_1 = ', error_l2_1) print(' error_l2_2 = ', error_l2_2) error_linf_1 = stat1["Fluid"]["FreeSurfaceDifference"]["max"].max() error_linf_2 = stat2["Fluid"]["FreeSurfaceDifference"]["max"].max() convergence_linf = log((error_linf_1 / error_linf_2), 2) print(' convergence_linf = ', convergence_linf) print(' error_linf_1 = ', error_linf_1) print(' error_linf_2 = ', error_linf_2) quad1 = quad(lambda t: solution.nond_error_amp(stat1, t)**2, stat1["ElapsedTime"]["value"][0], stat1["ElapsedTime"]["value"][-1], limit=1000) quad2 = quad(lambda t: solution.nond_error_amp(stat2, t)**2, stat2["ElapsedTime"]["value"][0], stat2["ElapsedTime"]["value"][-1], limit=1000) errormaxfs_l2_1 = sqrt(quad1[0]) errormaxfs_l2_2 = sqrt(quad2[0]) convergencemaxfs_l2 = log((errormaxfs_l2_1 / errormaxfs_l2_2), 2) print(' convergencemaxfs_l2 = ', convergencemaxfs_l2) print(' errormaxfs_l2_1 = ', errormaxfs_l2_1, '(', quad1[1], ')') print(' errormaxfs_l2_2 = ', errormaxfs_l2_2, '(', quad2[1], ')') return [convergencetop_l2, convergencebottom_l2, convergence_linf]
from sympy import Rational a = (-1, 0, 2, 1) b = (0, 3, 1, 0) s = 0 for i, ai in enumerate(a): si = 0 for j, bj in enumerate(b): si += Rational(bj, i + j + 1) s += ai * si print(s) s = 0 for p in range(len(a)): for i in range(p + 1): s += a[i] * b[p] # ----------------------------- p = lambda x, a: sum([ai * x**i for i, ai in enumerate(a)]) from scipy.integrate import quad print(quad(lambda x: p(x, a) * p(x, b), 0, 1)[0], 5. / 6.)
def r(z): return integrate.quad(chi, 0, z)[0]
def f(n, nc): I = quad(lambda x: kv(5. / 3., x), n / nc, +np.inf)[0] return I
#approximated equation Tinkham eq. 3.54 apprx = lambda tau: 1.74 * np.sqrt(1 - tau) #the function to be integrated / BCS temperature dependent energy gap; Tinkham eq. 3.53 #https://physics.stackexchange.com/questions/54200/superconducting-gap-temperature-dependence-how-to-calculate-this-integral #Equation to integrate funcToIntegrate = lambda z, sig, tau: np.divide( np.tanh( np.multiply( .882, np.multiply(np.divide(sig, tau), np.sqrt(1 + np.multiply(z, z))))), np.sqrt(1 + np.multiply(z, z))) #Equation to Solve funcToSolve = lambda sig, *tau: +quad( funcToIntegrate, 0, np.divide(hbar * omegaDebye, np.multiply(delta0, sig)), args=(sig, tau))[0] - np.arcsinh(hbar * omegaDebye / delta0) tTC = np.arange(0, 1.001, .001) # T/TC values deltaDelta0 = [] deltaDelta0apprx = [] for i in tTC: # probe for T/TC values deltaDelta0.append(fsolve(funcToSolve, .7, args=(i))) #.5 is a first guess deltaDelta0apprx = (apprx(tTC)) deltaDelta0apprx = np.hstack([deltaDelta0apprx, 0]) #add a little in normal state tTC = np.hstack([tTC, 1.2]) deltaDelta0.append(0) deltaDelta0 = np.array(deltaDelta0)
def Jtor(self, R, Z, psi, psi_bndry=None): """ Calculate toroidal plasma current Jtor = L * (Beta0*R/Raxis + (1-Beta0)*Raxis/R)*jtorshape where jtorshape is a shape function L and Beta0 are parameters which are set by constraints """ # Analyse the equilibrium, finding O- and X-points opt, xpt = critical.find_critical(R, Z, psi) if not opt: raise ValueError("No O-points found!") psi_axis = opt[0][2] if psi_bndry is not None: mask = critical.core_mask(R, Z, psi, opt, xpt, psi_bndry) elif xpt: psi_bndry = xpt[0][2] mask = critical.core_mask(R, Z, psi, opt, xpt) else: # No X-points psi_bndry = psi[0,0] mask = None dR = R[1,0] - R[0,0] dZ = Z[0,1] - Z[0,0] # Calculate normalised psi. # 0 = magnetic axis # 1 = plasma boundary psi_norm = (psi - psi_axis) / (psi_bndry - psi_axis) # Current profile shape jtorshape = (1. - np.clip(psi_norm, 0.0, 1.0)**self.alpha_m)**self.alpha_n if mask is not None: # If there is a masking function (X-points, limiters) jtorshape *= mask # Now apply constraints to define constants # Need integral of jtorshape to calculate paxis # Note factor to convert from normalised psi integral shapeintegral,_ = quad(lambda x: (1. - x**self.alpha_m)**self.alpha_n, 0.0, 1.0) shapeintegral *= (psi_bndry - psi_axis) # Pressure on axis is # # paxis = - (L*Beta0/Raxis) * shapeintegral # # Integrate current components IR = romb(romb(jtorshape * R/self.Raxis)) * dR*dZ I_R = romb(romb(jtorshape * self.Raxis/R)) * dR*dZ # Toroidal plasma current Ip is # # Ip = L * (Beta0 * IR + (1-Beta0)*I_R) # = L*Beta0*(IR - I_R) + L*I_R # LBeta0 = -self.paxis*self.Raxis / shapeintegral L = self.Ip/I_R - LBeta0*(IR/I_R - 1) Beta0 = LBeta0 / L #print("Constraints: L = %e, Beta0 = %e" % (L, Beta0)) # Toroidal current Jtor = L * (Beta0*R/self.Raxis + (1-Beta0)*self.Raxis/R)*jtorshape self.L = L self.Beta0 = Beta0 self.psi_bndry = psi_bndry self.psi_axis = psi_axis return Jtor
def ff(l,m,x2,num_poles): if l < m: print 'Error:\nabs(m) must be equal or less than l' return None else: # Kinematics q2 = ((2*np.pi/L)**2)*x2 cm_energy = np.sqrt(q2 + m1**2) + np.sqrt(q2 + m2**2) lab_energy = np.sqrt(cm_energy**2+lab_moment2) alpha = 1.0/2.0*(1.0+(np.square(m1)-np.square(m2))/np.square(cm_energy)) gamma = lab_energy/cm_energy # ----------------- # Finish triplets calculation (gamma dependent part) # rn triplets # Calculate array of r vectors r_arr = (1.0/gamma)*(n_par_arr-alpha*d_arr)+n_perp_arr # Calculate array with square of the magnitude of r, the azimuthal and polar angle r2_array = np.sum(r_arr*r_arr, axis = 1) r_azimuthal = np.arctan2(r_arr[:,1],r_arr[:,0]) r_polar = np.arctan2(np.sqrt(r_arr[:,0]**2 + r_arr[:,1]**2),r_arr[:,2]) #gw triplets # Calculate array of gw vectors gw_arr = gamma*w_par_arr+w_perp_arr # Calculate array with square of the magnitude of gw, the azimuthal and polar angle gw2_array = np.sum(gw_arr*gw_arr, axis = 1) gw_azimuthal = np.arctan2(gw_arr[:,1],gw_arr[:,0]) gw_polar = np.arctan2(np.sqrt(gw_arr[:,0]**2 + gw_arr[:,1]**2),gw_arr[:,2]) first_term = sum(np.exp(-r2_array+x2)*(1.0/(r2_array-x2))*(r2_array**(l/2.0))*special.sph_harm(m,l,r_azimuthal,r_polar)) # Calculate the second term if l == 0: second_term = special.sph_harm(0,0,0.0,0.0)*gamma*np.power(np.pi,3.0/2.0) second_term_bracket = 2 * x2 * integrate.quad(integr_second_term,0,1, args = (x2))[0] - 2 * np.exp(x2) second_term *= second_term_bracket else: second_term = 0 # Calculate the third term wd = np.inner(w_arr,d) t1 = np.exp(I*2*np.pi*alpha*wd) t2 = np.power(gw2_array,l/2.0) t3 = special.sph_harm(m,l,gw_azimuthal,gw_polar) coef_third_term = t1*t2*t3 third_term_r = integrate.quad(integr_third_term_r,0,1, args = (l,gw2_array,x2,coef_third_term))[0] third_term_i = integrate.quad(integr_third_term_i,0,1, args = (l,gw2_array,x2,coef_third_term))[0] third_term = gamma*np.power(I,l)* (third_term_r + I*third_term_i) factor = x2-poles[0:num_poles] gggg= np.prod(factor) total = gggg*(first_term + second_term + third_term) return total