def compute_exact_solution(outdir='./_output',frame=0): #------------------------------------ from scipy.integrate import fixed_quad, quad from pyclaw.plotters.data import ClawPlotData plotdata = ClawPlotData() plotdata.outdir=outdir #Read in the solution dat = plotdata.getframe(frame) ap=ac.AcousticsProblem('setprob.data','sharpclaw.data') t = dat.t print t grid = dat.grids[0] xc = dat.center[0] dx=dat.d xe = dat.edge[0] print "Computing exact solution for mx = ",dat.n qq=zeros([2,size(xc)]) for ii in range(size(xc)): qq[0,ii],dummy = fixed_quad(ap.pvec,xe[ii],xe[ii+1],args=(t,)) qq[1,ii],dummy = fixed_quad(ap.uvec,xe[ii],xe[ii+1],args=(t,)) #qq[0,ii],dummy= quad(ap.pvec,xe[ii],xe[ii+1],args=(t,),epsabs=1.e-11,epsrel=1.e-11) #qq[1,ii],dummy= quad(ap.uvec,xe[ii],xe[ii+1],args=(t,),epsabs=1.e-11,epsrel=1.e-11) qq/=dx return qq
def FM(self,m,Q,M,alpha,r2bar): if self.presentation==True: #for the presentation period # self consistent equation for m if self.fam==True: #familiar stimuli fun=lambda x:self.distRates(x)*r2bar(x,m,Q,M,alpha) if self.adap_quad==True: var,err=integrate.quad(fun,0.,self.rmax) else: var,err=integrate.fixed_quad(fun,0.,self.rmax,n=self.nquad) return var else: # novel stimuli fun=lambda x:self.distRates(x)*r2bar(x,Q,M,alpha) if self.adap_quad==True: var,err=integrate.quad(fun,0.,self.rmax) else: var,err=integrate.fixed_quad(fun,0.,self.rmax,n=self.nquad) return var else: #for the delay period if self.fam==True: #familiar stimuli fun=lambda x:self.distRates(x)*r2bar(x,m,M,alpha) if self.adap_quad==True: var,err=integrate.quad(fun,0.,self.rmax) else: var,err=integrate.fixed_quad(fun,0.,self.rmax,n=self.nquad) return var else: #novel stimuli fun=lambda x:self.distRates(x)*r2bar(x,M,alpha) if self.adap_quad==True: var,err=integrate.quad(fun,0.,self.rmax) else: var,err=integrate.fixed_quad(fun,0.,self.rmax,n=self.nquad) return var
def _calc_or(self,Rmean,rperi,rap,E,L,fixed_quad,**kwargs): Tr= 0. if Rmean > rperi and not fixed_quad: Tr+= nu.array(integrate.quadrature(_TrSphericalIntegrandSmall, 0.,m.sqrt(Rmean-rperi), args=(E,L,self._2dpot, rperi), **kwargs))[0] elif Rmean > rperi and fixed_quad: Tr+= integrate.fixed_quad(_TrSphericalIntegrandSmall, 0.,m.sqrt(Rmean-rperi), args=(E,L,self._2dpot, rperi), n=10,**kwargs)[0] if Rmean < rap and not fixed_quad: Tr+= nu.array(integrate.quadrature(_TrSphericalIntegrandLarge, 0.,m.sqrt(rap-Rmean), args=(E,L,self._2dpot, rap), **kwargs))[0] elif Rmean < rap and fixed_quad: Tr+= integrate.fixed_quad(_TrSphericalIntegrandLarge, 0.,m.sqrt(rap-Rmean), args=(E,L,self._2dpot, rap), n=10,**kwargs)[0] Tr= 2.*Tr return 2.*nu.pi/Tr
def f_dmags(self, dmag, s): """Calculates the joint probability density of dMag and projected separation Args: dmag (float): Value of dMag s (float): Value of projected separation (AU) Returns: f (float): Value of joint probability density """ if (dmag < self.mindmag(s)) or (dmag > self.maxdmag(s)): f = 0.0 else: ztest = (s/self.x)**2*10.**(-0.4*dmag)/self.val if ztest >= self.zmax: f = 0.0 elif (self.pconst & self.Rconst): f = self.f_dmagsz(self.zmin,dmag,s) else: if ztest < self.zmin: f = integrate.fixed_quad(self.f_dmagsz, self.zmin, self.zmax, args=(dmag, s), n=61)[0] else: f = integrate.fixed_quad(self.f_dmagsz, ztest, self.zmax, args=(dmag, s), n=61)[0] return f
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 _calc_op(self,Or,Rmean,rperi,rap,E,L,fixed_quad,**kwargs): #Azimuthal period I= 0. if Rmean > rperi and not fixed_quad: I+= nu.array(integrate.quadrature(_ISphericalIntegrandSmall, 0.,m.sqrt(Rmean-rperi), args=(E,L,self._2dpot, rperi), **kwargs))[0] elif Rmean > rperi and fixed_quad: I+= integrate.fixed_quad(_ISphericalIntegrandSmall, 0.,m.sqrt(Rmean-rperi), args=(E,L,self._2dpot,rperi), n=10,**kwargs)[0] if Rmean < rap and not fixed_quad: I+= nu.array(integrate.quadrature(_ISphericalIntegrandLarge, 0.,m.sqrt(rap-Rmean), args=(E,L,self._2dpot, rap), **kwargs))[0] elif Rmean < rap and fixed_quad: I+= integrate.fixed_quad(_ISphericalIntegrandLarge, 0.,m.sqrt(rap-Rmean), args=(E,L,self._2dpot,rap), n=10,**kwargs)[0] I*= 2*L return I*Or/2./nu.pi
def compute_errors(odir='.',frame=0): #------------------------------------ from scipy.integrate import fixed_quad # change to output directory and read in solution from fort.q000N # for frame N. # read in clawpack solution for this frame: ap=ac.AcousticsProblem('setprob.data','claw.data') os.chdir(odir) clawframe = read_clawframe(frame) t = clawframe.t # Assume there is only one grid (AMR not used): grid = clawframe.grids[0] print "Computing errors for mx = ",grid.mx xc = grid.xcenter qq=zeros([2,size(xc)]) for ii in range(size(xc)): qq[0,ii],dummy = fixed_quad(ap.pvec,grid.xedge[ii],grid.xedge[ii+1],args=(t,)) qq[1,ii],dummy = fixed_quad(ap.uvec,grid.xedge[ii],grid.xedge[ii+1],args=(t,)) dx=grid.xedge[1]-grid.xedge[0] qq/=dx errors = qq[0,:] - grid.q[:,0] ion() clf() plot(xc,qq[0,:],'k',xc,grid.q[:,0],'+b') draw() ioff() return errors
def Gamma(view, sun, arch, refl, trans): '''The one angle Area Scattering Phase Function based on Myneni V.18 and Shultis (17) isotropic scattering assumption. This is the phase function of the scattering in a particular direction based also on the amount of interception in the direction. ------------------------------------------------------------- Input: view - view zenith angle, sun - the solar zenith angle, arch - archetype, see gl function for description, refl - fraction reflected, trans - fraction transmitted. Output: Area Scattering Phase function value. ''' ''' # uncomment/comment the code below for bi-lambetian Gamma. B = sun - view # uncomment these lines to run test plot gam = (refl + trans)/np.pi/3.*(np.sin(B) - B*np.cos(B)) +\ trans/np.pi*np.cos(B) # Myneni V.15 ''' func = lambda leaf, view, sun, arch, refl, trans: gl(leaf, arch)\ *(refl*Big_psi(view,sun,leaf,'r') + (trans*Big_psi(view,sun,leaf,'t'))) # the integral as defined in Myneni V.18. if isinstance(sun, np.ndarray): # to remove singularity at sun==0. sun = np.where(sun==0.,1.0e-10,sun) gam = np.zeros_like(sun) for j,s in enumerate(sun): gam[j] = fixed_quad(func, 0., np.pi/2.,\ args=(view,s,arch,refl,trans),n=16)[0] else: if sun==0.: sun = 1.0e-10 # to remove singularity at sun==0. gam = fixed_quad(func, 0., np.pi/2.,\ args=(view,sun,arch,refl,trans),n=16)[0] # integrate leaf angles between 0 to pi/2. return gam
def G(view, arch): '''The Geometry factor for a specific view or solar direction based on Myneni III.16. The projection of 1 unit area of leaves within a unit volume onto the plane perpen- dicular to the view or solar direction. ------------------------------------------------------------ Input: view - the view or solar zenith angle in radians, arch - archetype, see gl function for description of each. Output: The integral of the Geometry function (G). ''' g = lambda angle, view, arch: gl(angle, arch)\ *psi(angle,view) # the G function as defined in Myneni III.16. if isinstance(view, np.ndarray): if arch == 's': # avoid integration in case of isometric distr. G = np.ones_like(view) * 0.5 return G view = np.where(view > np.pi, 2.*np.pi - view, view) G = np.zeros_like(view) for j,v in enumerate(view): G[j] = fixed_quad(g, 0., np.pi/2., args=(v, arch),n=16)[0] else: if arch == 's': # avoid integration, see above... G = 0.5 return G if view > np.pi: # symmetry of distribution about z axis view = np.pi - view G = fixed_quad(g, 0., np.pi/2., args=(view, arch),n=16)[0] # integrate g function between 0 to pi/2. return G
def _calc_angler(self,Or,r,Rmean,rperi,rap,E,L,vr,fixed_quad,**kwargs): if r < Rmean: if r > rperi and not fixed_quad: wr= Or*integrate.quadrature(_TrSphericalIntegrandSmall, 0.,m.sqrt(r-rperi), args=(E,L,self._2dpot,rperi), **kwargs)[0] elif r > rperi and fixed_quad: wr= Or*integrate.fixed_quad(_TrSphericalIntegrandSmall, 0.,m.sqrt(r-rperi), args=(E,L,self._2dpot,rperi), n=10,**kwargs)[0] else: wr= 0. if vr < 0.: wr= 2*m.pi-wr else: if r < rap and not fixed_quad: wr= Or*integrate.quadrature(_TrSphericalIntegrandLarge, 0.,m.sqrt(rap-r), args=(E,L,self._2dpot,rap), **kwargs)[0] elif r < rap and fixed_quad: wr= Or*integrate.fixed_quad(_TrSphericalIntegrandLarge, 0.,m.sqrt(rap-r), args=(E,L,self._2dpot,rap), n=10,**kwargs)[0] else: wr= m.pi if vr < 0.: wr= m.pi+wr else: wr= m.pi-wr return wr
def onef_dmags(dmag, s, ranges, val, pdfs, funcs, x): """Returns joint probability density of s and dmag Args: dmag (float): Value of difference in brightness magnitude s (float): Value of planet-star separation ranges (tuple): pmin (float): minimum value of geometric albedo pmax (float): maximum value of geometric albedo Rmin (float): minimum value of planetary radius (km) Rmax (float): maximum value of planetary radius (km) rmin (float): minimum value of orbital radius (AU) rmax (float): maximum value of orbital radius (AU) zmin (float): minimum value of pR^2 (km^2) zmax (float): maximum value of pR^2 (km^2) val (float): Value of sin(bstar)**2*Phi(bstar) pdfs (tuple): Probability density functions for pR^2 and orbital radius funcs (tuple): Inverse functions of sin(b)**2*Phi(b) x (float): Conversion factor between AU and km Returns: f (float): Joint probability density of s and dmag """ pmin, pmax, Rmin, Rmax, rmin, rmax, zmin, zmax = ranges minrange = (pmax, Rmax, rmin, rmax) maxrange = (pmin, Rmin, rmax) pconst = pmin == pmax Rconst = Rmin == Rmax if (dmag < util.mindmag(s, minrange, x)) or (dmag > util.maxdmag(s, maxrange, x)): f = 0.0 elif (pconst & Rconst): ranges2 = (rmin, rmax) f = onef_dmagsz(pmin*Rmin**2, dmag, s, val, pdfs, ranges2, funcs, x) else: ztest = (s/x)**2*10.0**(-0.4*dmag)/val ranges2 = (rmin, rmax) if ztest >= zmax: f = 0.0 else: if ztest < zmin: f = integrate.fixed_quad(onef_dmagsz, zmin, zmax, args=(dmag, s, val, pdfs, ranges2, funcs, x), n=61)[0] else: f = integrate.fixed_quad(onef_dmagsz, ztest, zmax, args=(dmag, s, val, pdfs, ranges2, funcs, x), n=61)[0] return f
def calc_stream(k, nk, beta, sigma, flag): stream = k*0.0+1.0 if(flag=='exp'): for cc in range(0,nk): tempi = integrate.fixed_quad(pmu_exp,-1,1,args=(k[cc],sigma,beta),n=8) stream[cc] = 0.5*tempi[0] #0.5* to normalize Legendre L_0 elif(flag=='Gauss'): for cc in range(0,nk): tempi = integrate.fixed_quad(pmu_gauss,-1,1,args=(k[cc],sigma,beta),n=8) stream[cc] = 0.5*tempi[0] #0.5* to normalize Legendre L_0 return stream
def Expectation(model,dist,distparam1,distparam2,Aproj,distparamextra = 0): from scipy import integrate import numpy as np # this routine takes in the name of the roof model desired, the distibution of mass to be integrated with respect to, # and parameters needed to define the distribution #fwood,fsteel,fconcrete,fcomposite,flightMetal,ftile= getModel() functions = getModel() if model.lower()=='all': # HERE COMES AN ASSUMPTION TO GIVE ROOF CASUALTY AREA TO ROOF TYPES FOR WHICH DATA IS NOT AVAILABLE: # assuming that all roof of similar types have the same casualty areas. e.g all wood roofs are the same # the order of models is assumed to be as follows # Wood Roof, Wood 1st, Wood 2nd, Steel Roof, Steel 1st, Steel 2nd, Concrete, Concrete 1st, Concrete 2nd, Composite # Light Metal, Tile Roof, Tile 1st, Tile 2nd, Car, Open if dist.lower() =='uniform': lowbound = distparam1 highbound = distparam2 denc = highbound-lowbound if denc>0.: c = 1./denc elif denc<0.: print 'Check bounds in upper and lower bound. roofPenetration.Expectation' exit(1) elif dist.lower() =='gaussian' or dist.lower() == 'normal' or dist.lower()=='gauss': mu = distparam1 sigma = distparam2 lowbound = max(-1e3,mu-5.*sigma) highbound = min(1e6,mu+5.*sigma) fgauss = lambda x: np.exp(-.5*((x-mu)/sigma)**2)/(sigma*(2.*np.pi)**.5) EretMain = np.zeros((len(functions))) for index in range(len(functions)): froof = functions[index] if dist.lower() =='uniform': if denc ==0.0: retval = froof(lowbound) else: invals = integrate.fixed_quad(froof,lowbound,highbound,n=50) retval = invals[0]*c elif dist.lower() =='gaussian' or dist.lower() == 'normal' or dist.lower()=='gauss': fvals = lambda x: fgauss(x)*froof(x) invals = integrate.fixed_quad(fvals,lowbound,highbound,n=50) retval = invals[0] EretMain[index] = retval Eret = np.zeros((16)) Eret = np.concatenate((3*[EretMain[0]],3*[EretMain[1]],3*[EretMain[2]],[EretMain[3]],[EretMain[4]],3*[EretMain[5]],[EretMain[4]],[Aproj]),1) return Eret
def _calc_anglez(self,Or,Op,ar,z,r,Rmean,rperi,rap,E,L,Lz,vr,axivz, fixed_quad,**kwargs): #First calculate psi i= nu.arccos(Lz/L) sinpsi= z/r/nu.sin(i) if sinpsi > 1. and sinpsi < (1.+10.**-7.): sinpsi= 1. if sinpsi < -1. and sinpsi > (-1.-10.**-7.): sinpsi= -1. psi= nu.arcsin(sinpsi) if axivz > 0.: psi= nu.pi-psi psi= psi % (2.*nu.pi) #Calculate dSr/dL dpsi= Op/Or*2.*nu.pi #this is the full I integral if r < Rmean: if not fixed_quad: wz= L*integrate.quadrature(_ISphericalIntegrandSmall, 0.,m.sqrt(r-rperi), args=(E,L,self._2dpot, rperi), **kwargs)[0] elif fixed_quad: wz= L*integrate.fixed_quad(_ISphericalIntegrandSmall, 0.,m.sqrt(r-rperi), args=(E,L,self._2dpot, rperi), n=10,**kwargs)[0] if vr < 0.: wz= dpsi-wz else: if not fixed_quad: wz= L*integrate.quadrature(_ISphericalIntegrandLarge, 0.,m.sqrt(rap-r), args=(E,L,self._2dpot, rap), **kwargs)[0] elif fixed_quad: wz= L*integrate.fixed_quad(_ISphericalIntegrandLarge, 0.,m.sqrt(rap-r), args=(E,L,self._2dpot, rap), n=10,**kwargs)[0] if vr < 0.: wz= dpsi/2.+wz else: wz= dpsi/2.-wz #Add everything wz= -wz+psi+Op/Or*ar return wz
def comp_s(self, smin, smax, dMag): """Calculates completeness by first integrating over dMag and then projected separation. Args: smin (ndarray): Values of minimum projected separation (AU) from instrument smax (ndarray): Value of maximum projected separation (AU) from instrument dMag (ndarray): Planet delta magnitude Returns: comp (ndarray): Completeness values """ # cast to arrays smin = np.array(smin, ndmin=1, copy=False) smax = np.array(smax, ndmin=1, copy=False) dMag = np.array(dMag, ndmin=1, copy=False) comp = np.zeros(smin.shape) for i in xrange(len(smin)): comp[i] = integrate.fixed_quad(self.f_sv, smin[i], smax[i], args=(dMag[i],), n=50)[0] # ensure completeness values are between 0 and 1 comp = np.clip(comp, 0., 1.) return comp
def res_wage_operator(self, phi): """ Updates the reservation wage function guess phi via the operator Q. Parameters ---------- phi : array_like(float, ndim=1, length=len(pi_grid)) This is reservation wage guess Returns ------- new_phi : array_like(float, ndim=1, length=len(pi_grid)) The updated reservation wage guess. """ # == Simplify names == # beta, c, f, g, q = self.beta, self.c, self.f, self.g, self.q # == Turn phi into a function == # phi_f = lambda p: interp(p, self.pi_grid, phi) new_phi = np.empty(len(phi)) for i, pi in enumerate(self.pi_grid): def integrand(x): "Integral expression on right-hand side of operator" return npmax(x, phi_f(q(x,pi))) * (pi*f(x) + (1 - pi)*g(x)) integral, error = fixed_quad(integrand, 0, self.w_max) new_phi[i] = (1 - beta) * c + beta * integral return new_phi
def get_greedy(self, v): """ Compute optimal actions taking v as the value function. Parameters ---------- v : array_like(float, ndim=1, length=len(pi_grid)) An approximate value function represented as a one-dimensional array. Returns ------- policy : array_like(float, ndim=1, length=len(pi_grid)) The decision to accept or reject an offer where 1 indicates accept and 0 indicates reject """ # == Simplify names == # f, g, beta, c, q = self.f, self.g, self.beta, self.c, self.q vf = LinearNDInterpolator(self.grid_points, v) N = len(v) policy = np.zeros(N, dtype=int) for i in range(N): w, pi = self.grid_points[i,:] v1 = w / (1 - beta) integrand = lambda m: vf(m, q(m, pi)) * (pi * f(m) + \ (1 - pi) * g(m)) integral, error = fixed_quad(integrand, 0, self.w_max) v2 = c + beta * integral policy[i] = v1 > v2 # Evaluates to 1 or 0 return policy
def test_scalar(self): n = 4 func = lambda x: x**(2*n - 1) expected = 1/(2*n) got, _ = fixed_quad(func, 0, 1, n=n) # quadrature exact for this input assert_allclose(got, expected, rtol=1e-12)
def test_vector(self): n = 4 p = np.arange(1, 2*n) func = lambda x: x**p[:,None] expected = 1/(p + 1) got, _ = fixed_quad(func, 0, 1, n=n) assert_allclose(got, expected, rtol=1e-12)
def Ef2(self):# mean of f**2 fun=lambda x:self.distRates(x)*self.f(x)*self.f(x) if self.adap_quad==True: var,err=integrate.quad(fun,0.,self.rmax) else: var,err=integrate.fixed_quad(fun,0.,self.rmax,n=self.nquad) return var
def get_A(self,x,mub2,zetaD,bT2,flav): # Eqs. A10 & A11 of PRD83 114042 D=self.D factor1 = 0.5*np.log(4/(mub2*bT2))-D['gamma'] factor2 =-0.5*(np.log(bT2*mub2)-2*(np.log(2)-D['gamma']))**2\ -(np.log(bT2*mub2) - 2*(np.log(2)-D['gamma'])) * np.log(zetaD/mub2) if flav.startswith('g'): C0 = 0 C1 = lambda z: 0 C2 = lambda z: D['TF']*(2*(1-2*z*(1-z))*factor1 + 2*z*(1-z)) C3 = factor2 else: C0 = 1 C1 = lambda z: D['CF']*2*factor1*2 C2 = lambda z: D['CF']*(2*factor1*(-1-z) + 1-z) C3 = factor2 # get alpha strong alphaS=self.SC.get_alphaS(mub2) D['DI'] = lambda z: C0 +alphaS/(2*np.pi)*(-(1-x)*C1(z)/z**2/(1-z)\ + C1(1)*np.log(1-x) + C3) D['DII'] = lambda z: alphaS/(2*np.pi)*(1-x)*(C1(z)/z**2/(1-z) + C2(z)/z**2) D['ff'] = lambda x: self.CFF.get_FF(x,D['muF2'],flav,D['charge']) D['x'] = x func=np.vectorize(self.integrand4A) return fixed_quad(func,0,1,n=40)[0]
def grand2(a, r, emin, emax, f_e, f_a): """Returns second integrand for determining probability density of orbital radius Args: a (float): Value of semi-major axis (AU) r (float): Value of orbital radius (AU) emin (float): Minimum eccentricity emax (float): Maximum eccentricity f_e (callable(e)): Probability density function for eccentricity f_a (callable(a)): Probability density function for semi-major axis """ emin1 = np.abs(1.0 - r/a) if emin1 < emin: emin1 = emin if emin1 > emax: f = 0.0 else: f = integrate.fixed_quad(grand1, emin1, emax, args=(a,r,f_e,f_a), n=100)[0] return f
def bellman_operator(self, v): """ The Bellman operator. Including for comparison. Value function iteration is not recommended for this problem. See the reservation wage operator below. Parameters ============== v : An approximate value function represented as a one-dimensional array. """ # == Simplify names == # f, g, beta, c, q = self.f, self.g, self.beta, self.c, self.q vf = LinearNDInterpolator(self.grid_points, v) N = len(v) new_v = np.empty(N) for i in range(N): w, pi = self.grid_points[i,:] v1 = w / (1 - beta) integrand = lambda m: vf(m, q(m, pi)) * (pi * f(m) \ + (1 - pi) * g(m)) integral, error = fixed_quad(integrand, 0, self.w_max) v2 = c + beta * integral new_v[i] = max(v1, v2) return new_v
def f_dmag(self, dmag, smin, smax): """Calculates probability density of dMag by integrating over projected separation Args: dmag (float): Planet delta magnitude smin (float): Value of minimum projected separation (AU) from instrument smax (float): Value of maximum projected separation (AU) from instrument Returns: f (float): Value of probability density """ if dmag < self.mindmag(smin): f = 0.0 else: su = self.s_bound(dmag, smax) if su > smax: su = smax if su < smin: f = 0.0 else: f = integrate.fixed_quad(self.f_sdmagv, smin, su, args=(dmag,), n=50)[0] return f
def f_s(self, s, dMagMax): """Calculates probability density of projected separation marginalized up to dMagMax Args: s (float): Value of projected separation dMagMax (float): Maximum planet delta magnitude Returns: f (float): Probability density """ if (s == 0.0) or (s == self.rmax): f = 0.0 else: d1 = self.mindmag(s) d2 = self.maxdmag(s) if d2 > dMagMax: d2 = dMagMax if d1 > d2: f = 0.0 else: f = integrate.fixed_quad(self.f_dmagsv, d1, d2, args=(s,), n=50)[0] return f
def H_element(n, n_prim, problem, step_size, l = 0, j = .5): p, p_prim = [(x + 1)*step_size for x in (n, n_prim)] diagonal = p**2 / (2 * problem.mass) * (n == n_prim) V = problem.potential integral, _ = fixed_quad(integrand, 0, 10, \ n = 20, args=(p, p_prim, V, l, j)) return diagonal + 2 * p_prim**2 * step_size / sp.pi * integral
def onef_zeta(zetai, pdfs, ranges): """Determines probability density for zeta = p*R^2 Args: zetai (float): Value of zeta = pR^2 pdfs (tuple): Probability density functions f_p and f_R ranges (tuple): pmin (float): minimum value of geometric albedo pmax (float): maximum value of geometric albedo Rmin (float): minimum value of planetary radius (km) Rmax (float): maximum value of planetary radius (km) Returns: f (float): probability density of given zetai """ f_p, f_R = pdfs pmin, pmax, Rmin, Rmax = ranges p1 = zetai/Rmax**2 p2 = zetai/Rmin**2 if p1 < pmin: p1 = pmin if p2 > pmax: p2 = pmax f = integrate.fixed_quad(pgrand,p1,p2,args=(zetai,f_p,f_R),n=200)[0] return f
def integrate(self, g, int_min=None, int_max=None): """ Integrate the function g(z) * self.phi(z) from int_min to int_max. Parameters ---------- g : function The function which to integrate int_min, int_max : scalar(float), optional The bounds of integration. If either of these parameters are `None` (the default), they will be set to 4 standard deviations above and below the mean. Returns ------- result : scalar(float) The result of the integration """ # == Simplify notation == # phi = self.phi if int_min is None: int_min = self._int_min if int_max is None: int_max = self._int_max # == set up integrand and integrate == # integrand = lambda z: g(z) * phi.pdf(z) result, error = fixed_quad(integrand, int_min, int_max) return result
def Eg2(self):# mean of g**2 fun=lambda x:self.distRates2(x)*self.g(x)*self.g(x) if self.adap_quad==True: var,err=integrate.quad(fun,0.,self.rmaxSig) else: var,err=integrate.fixed_quad(fun,0.,self.rmaxSig,n=self.nquad) return var
def Function(self, x, param): Ktrans, ve = param #s = quadrature(lambda t: self.Aif(t) * scipy.exp(-Ktrans*(x-t)/ve), 0.0, x, tol=1.0e-03, vec_func=False) s = fixed_quad(lambda t: self.Aif(t) * scipy.exp(-Ktrans*(x-t)/ve), 0.0, x, n=5) y = Ktrans * s[0] return y
def predict_proba(self, X, interval=0.95, *args, **kwargs): # Expectation and variance in latent space Ey_t, Vy_t, ql, qu = super().predict_proba(X, interval) # Save computation if identity transform if type(self.target_transform) is transforms.Identity: return Ey_t, Vy_t, ql, qu # Save computation if standardise transform elif type(self.target_transform) is transforms.Standardise: Ey = self.target_transform.itransform(Ey_t) Vy = Vy_t * self.target_transform.ystd**2 ql, qu = norm.interval(interval, loc=Ey, scale=np.sqrt(Vy)) return Ey, Vy, ql, qu # All other transforms require quadrature Ey = np.empty_like(Ey_t) Vy = np.empty_like(Vy_t) # Used fixed order quadrature to transform prob. estimates for i, (Eyi, Vyi) in enumerate(zip(Ey_t, Vy_t)): # Establish bounds Syi = np.sqrt(Vyi) a, b = Eyi - 3 * Syi, Eyi + 3 * Syi # approx 99% bounds # Quadrature Ey[i], _ = fixed_quad(self.__expec_int, a, b, n=QUADORDER, args=(Eyi, Syi)) Vy[i], _ = fixed_quad(self.__var_int, a, b, n=QUADORDER, args=(Ey[i], Eyi, Syi)) ql, qu = norm.interval(interval, loc=Ey, scale=np.sqrt(Vy)) return Ey, Vy, ql, qu
def piecewise_ramp(step_func, t_channels, t_currents, currents, n=20, eps=1e-10): """ Computes response from piecewise linear current waveform with a single pulse. This basically evaluates the convolution between dI/dt and step-off response. step_func: function handle to evaluate step-off response t_channels: time channels when the current is on or off currents: input source currents n: Gaussian quadrature order """ dt = np.diff(t_currents) dI = np.diff(currents) dIdt = dI / dt nt = t_currents.size response = np.zeros(t_channels.size, dtype=float) pulse_time = t_currents.max() for i in range(1, nt): t_lag = pulse_time - t_currents[i] time = t_lag + t_channels t0 = dt[i - 1] const = -dIdt[i - 1] if abs(const) > eps: for j, t in enumerate(time): # on-time # TODO: this is only working when we have a single ramp... if t < 0.: print(t + t0) response[j] += (fixed_quad(step_func, 0, t + t0, n=n)[0] * const) # off-time else: response[j] += (fixed_quad(step_func, t, t + t0, n=n)[0] * const) return response
def integ_lens(total ,k1): f1 = interpolate.interp1d(k1, total) def func(x): return f1(x) * (2*x +1) kmin = np.min(k1) kmax = np.max(k1) intf,_ = integrate.fixed_quad(func, kmin, kmax, n = 200) return intf
def arc_length(tfinal, CTRL): degree = 3 knotvector = bs.Knotvector(CTRL, degree) length = integrate.fixed_quad(func_to_integrate, 0.0, tfinal, args=(CTRL, degree, knotvector), n=10) return length[0]
def slope_parameter(self, a): def kernel(x): return self.total_likelyhood(a, x) s = np.log( integrate.fixed_quad(kernel, self.b_min, self.b_max, n=self.Nquad)[0]) s = s - np.log(self.Normalization) s = np.exp(s) return s
def line_integral(function, p0, p1, singular): x0, y0, x1, y1 = *p0, *p1 length = np.sqrt((x1 - x0)**2 + (y1 - y0)**2) def to_quad(t): return function( np.array([(x1 + x0) / 2 + t * (x1 - x0) / 2, (y1 + y0) / 2 + t * (y1 - y0) / 2])) if singular: return length * complex_quad(to_quad, -1, 1, points=[0]) / 2 return length * fixed_quad(np.vectorize(to_quad), -1.0, 1.0)[0] / 2
def min_func_local(estimate): discrimination[ndx] = estimate _mml_abstract(difficulty[ndx, None], scalar[ndx, None], discrimination[ndx, None], theta, distribution, options) estimate_int = _compute_partial_integral(theta, difficulty[ndx, None], discrimination[ndx, None], the_sign[ndx, None]) estimate_int *= partial_int otpt = integrate.fixed_quad( lambda x: estimate_int, quad_start, quad_stop, n=quad_n)[0] return -np.log(otpt).dot(counts)
def _local_min_func(estimate): new_betas = estimate[2:] new_values = _unfold_partial_integral(theta, estimate[1], new_betas, estimate[0], fold_span[item_ndx], responses[item_ndx]) new_values *= partial_int otpt = integrate.fixed_quad( lambda x: new_values, quad_start, quad_stop, n=quad_n)[0] return -np.log(otpt).sum()
def integ(der1, der2 ,k, kmin, kmax): f1 = interpolate.interp1d(k, der1) f2 = interpolate.interp1d(k, der2) def func(x): return f1(x) * (x**2)* f2(x) intf,_ = integrate.fixed_quad(func, kmin, kmax, n = 200) return intf
def get_exact_moments(distribution, moments_fn): """ Get exact moments from given distribution :param distribution: Distribution object :param moments_fn: Function for generating moments :return: Exact moments """ integrand = lambda x: moments_fn(x).T * distribution.pdf(x) a, b = moments_fn.domain integral = integrate.fixed_quad(integrand, a, b, n=moments_fn.size * 5)[0] return integral[1:]
def _calc_jr(self,rperi,rap,E,L,fixed_quad,**kwargs): if fixed_quad: return integrate.fixed_quad(_JrSphericalIntegrand, rperi,rap, args=(E,L,self._2dpot), n=10, **kwargs)[0]/nu.pi else: return (nu.array(integrate.quad(_JrSphericalIntegrand, rperi,rap, args=(E,L,self._2dpot), **kwargs)))[0]/nu.pi
def MaxEnt(supp, g_X, restrictions): f = f_X(g_X) S = lambda v: integrate.fixed_quad( lambda x, v: f(x, v) * np.log(f(x, v)), supp[0], supp[1], args=(v, ))[0 ] moms = [moment(f, gi_X, supp) for gi_X in g_X] h = [ lambda v: moms[i](v) - restrictions[i] for i in range(len(restrictions)) ] v = ALM(S, h, np.zeros(len(restrictions)), 100) return f, v
def _calc_angler(self, Or, r, Rmean, rperi, rap, E, L, vr, fixed_quad, **kwargs): if r < Rmean: if r > rperi and not fixed_quad: wr = Or * integrate.quadrature(_TrSphericalIntegrandSmall, 0., m.sqrt(r - rperi), args=(E, L, self._2dpot, rperi), **kwargs)[0] elif r > rperi and fixed_quad: wr = Or * integrate.fixed_quad(_TrSphericalIntegrandSmall, 0., m.sqrt(r - rperi), args=(E, L, self._2dpot, rperi), n=10, **kwargs)[0] else: wr = 0. if vr < 0.: wr = 2 * m.pi - wr else: if r < rap and not fixed_quad: wr = Or * integrate.quadrature(_TrSphericalIntegrandLarge, 0., m.sqrt(rap - r), args=(E, L, self._2dpot, rap), **kwargs)[0] elif r < rap and fixed_quad: wr = Or * integrate.fixed_quad(_TrSphericalIntegrandLarge, 0., m.sqrt(rap - r), args=(E, L, self._2dpot, rap), n=10, **kwargs)[0] else: wr = m.pi if vr < 0.: wr = m.pi + wr else: wr = m.pi - wr return wr
def min_local_func(beta_estimate): difficulty[item_ndx] = beta_estimate estimate_int = _compute_partial_integral(theta, difficulty[item_ndx, None], discrimination[item_ndx, None], the_sign[item_ndx, None]) estimate_int *= partial_int otpt = integrate.fixed_quad( lambda x: estimate_int, quad_start, quad_stop, n=quad_n)[0] return -np.log(otpt).dot(counts)
def intaeE(self, a, e): """Returns integral over eccentric anomaly for probability density function for observed eccentricity""" # a is a scalar, e is a scalar if self.pconst and self.Rconst: intaebv = np.vectorize(self.intaeb) grand = lambda E: (1.0 - e * np.cos(E)) * intaebv( E, a, e, self.pop.prange[0] * self.pop.Rrange[0]**2) else: grand = lambda E: (1.0 - e * np.cos(E)) * self.intaezv(E, a, e) f = integrate.fixed_quad(grand, 0.0, 2.0 * np.pi, n=20)[0] return f
def snr_at_z(z): logzp1 = np.log(z + 1) integrand = lambda log_f: [ np.exp(num(log_f + logzp1) + denom(log_f)) for denom in denoms ] integrals, _ = fixed_quad(integrand, log_f_lo, log_f_hi - logzp1, n=1024) snr = get_decisive_snr(np.sqrt(4 * integrals)) with np.errstate(divide='ignore'): snr /= cosmo.angular_diameter_distance(z).to_value(units.Mpc) return snr
def eulerDiff(self, c, X): if (np.isscalar(c)): EuPrime = integrate.fixed_quad(self.EuPrimePart, self.yMin, self.yMax, args=(X, c), n=self.quad_order) return self.uPrime(c) - (self.beta * self.R * EuPrime[0]) diff = np.empty(len(c)) for ix, (cVal, XVal) in enumerate(zip(c, X)): EuPrime = integrate.fixed_quad(self.EuPrimePart, self.yMin, self.yMax, args=(XVal, cVal), n=self.quad_order) diff[ix] = self.uPrime(cVal) - (self.beta * self.R * EuPrime[0]) return diff
def get_L2_norm(cell_faces, function): # Integrate square of function over each cell. sq_int_parts = np.zeros(cell_faces.shape[0] + 1) for i in range(0, cell_faces.shape[0] - 1): sq_int_parts[i] = fixed_quad(func=lambda x_lam: (function(x_lam))**2, a=cell_faces[i], b=cell_faces[i + 1], n=5)[0] # Sum integrals of individual cells, and take sqrt of sum. norm = np.sqrt(np.sum(sq_int_parts)) return norm
def theoretical_prediction4( self, RRp, theta, rbin_min, rbin_max): # cen-sat_pairs model, no miscentering lnmparent_true, lnmsat_true, lnmstellar_true, conc_parent, conc_sat, mck = theta dsigma_sat = DeltaSigmaSatellite(10**lnmsat_true, conc_sat).dsigma(RRp) dsigma_parent = DeltaSigmaParent(10**lnmparent_true, conc_parent).dsigma(RRp) dsigma_stellar = DeltaSigmaStellar(10**lnmstellar_true).dsigma(RRp) dsigma_thp = dsigma_parent + dsigma_sat + dsigma_stellar spline_thpredict = interp1d(np.log10(RRp), dsigma_thp, fill_value="extrapolate") storing_delta_sigma1 = np.zeros(len(pairs_plot) - 1) if not len(RRp) == len(storing_delta_sigma1): print("You are not plotting with observational axis") sys.exit() for i in range(len(pairs_plot) - 1): a = pairs_plot[i] b = pairs_plot[i + 1] integration_numerator = fixed_quad( lambda x: (10**spline_totalpairs(np.log10(x)) ) * spline_thpredict(np.log10(x)), a, b, n=50)[0] integration_denominator = fixed_quad( lambda x: (10**spline_totalpairs(np.log10(x))), a, b, n=50)[0] delta_sigma_a_b = integration_numerator / integration_denominator storing_delta_sigma1[i] = delta_sigma_a_b #integration_numerator2=quad(lambda x: spline_thpredict(np.log10(x)),a,b)[0] #integration_denominator2=b-a #delta_sigma_a_b2=integration_numerator2/integration_denominator2 #storing_delta_sigma2[i] =delta_sigma_a_b2 #storing_sat_axis[i]=(a+b)/2 #print("delta_sigma averaged,not averaged,observed",delta_sigma_a_b,delta_sigma_a_b2) return storing_delta_sigma1
def get_x(func_val, n): if func_val >= 0.5: return 4.99999 a = 0 b = 5 while True: num = (fixed_quad(f, 0, (a + b) / 2, n=n)[0] / sqrt(2 * pi)) if num < func_val + 0.00000001 and num > func_val - 0.00000001: return round((a + b) / 2, 5) elif num < func_val: a = (a + b) / 2 elif num > func_val: b = (a + b) / 2
def direct_estimate_diff_var(self, level_sims, distr, moments_fn): """ Used in mlmc_test_run Calculate variances of level differences using numerical quadrature. :param moments_fn: :param domain: :return: """ mom_domain = moments_fn.domain means = [] vars = [] sim_l = None for l in range(len(level_sims)): # TODO: determine integration domain as _sample_fn ^{-1} ( mom_domain ) domain = mom_domain sim_0 = sim_l sim_l = lambda x, h=level_sims[l].step: level_sims[l]._sample_fn( x, h) if l == 0: md_fn = lambda x: moments_fn(sim_l(x)) else: md_fn = lambda x: moments_fn(sim_l(x)) - moments_fn(sim_0(x)) fn = lambda x: (md_fn(x)).T * distr.pdf(x) moment_means = integrate.fixed_quad(fn, domain[0], domain[1], n=100)[0] fn2 = lambda x: ( (md_fn(x) - moment_means[None, :])**2).T * distr.pdf(x) moment_vars = integrate.fixed_quad(fn2, domain[0], domain[1], n=100)[0] means.append(moment_means) vars.append(moment_vars) return means, vars
def rgrand2(self, a, r): """Calculates second integrand for determining probability density of orbital radius Args: a (float): Value of semi-major axis in AU r (float): Value of orbital radius in AU Returns: f (float): Value of second integrand """ emin1 = np.abs(1.0 - r / a) emin1 *= (1.0 + 1e-3) if emin1 < self.emin: emin1 = self.emin if emin1 >= self.emax: f = 0.0 else: if self.PlanetPopulation.constrainOrbits: if a <= 0.5 * (self.amin + self.amax): elim = 1.0 - self.amin / a else: elim = self.amax / a - 1.0 if emin1 > elim: f = 0.0 else: f = self.dist_sma(a) / a * integrate.fixed_quad( self.rgrand1, emin1, elim, args=(a, r), n=60)[0] else: f = self.dist_sma(a) / a * integrate.fixed_quad( self.rgrand1, emin1, self.emax, args=(a, r), n=60)[0] return f
def min_func(estimate): discrimination[:] = estimate _mml_abstract(difficulty, scalar, discrimination, theta, distribution, options) partial_int = _compute_partial_integral(theta, difficulty, discrimination, the_sign) # add distribution partial_int *= distribution otpt = integrate.fixed_quad( lambda x: partial_int, quad_start, quad_stop, n=quad_n)[0] return -np.log(otpt).dot(counts)
def inner_prod(self, f, i, quad_size=40): """ Compute the inner product \int f(x) h_i(x) \pi(x) dx where \pi is the standard normal distribution. """ integrand = lambda x: f(x) * self.__call__(i, x) * norm.pdf( x, loc=self.mu, scale=self.sig) std_devs = 5 # Integrate out to 5 std deviations in each direction a = self.mu - self.sig * std_devs b = self.mu + self.sig * std_devs return fixed_quad(integrand, a, b, n=quad_size)[0]
def alpha_min_func(alpha_estimate): discrimination[:] = alpha_estimate for iteration in range(options['max_iteration']): previous_difficulty = difficulty.copy() # Quadrature evaluation for values that do not change partial_int = _compute_partial_integral(theta, difficulty, discrimination, the_sign) partial_int *= distribution for item_ndx in range(n_items): # pylint: disable=cell-var-from-loop # remove contribution from current item local_int = _compute_partial_integral(theta, difficulty[item_ndx, None], discrimination[item_ndx, None], the_sign[item_ndx, None]) partial_int /= local_int def min_local_func(beta_estimate): difficulty[item_ndx] = beta_estimate estimate_int = _compute_partial_integral(theta, difficulty[item_ndx, None], discrimination[item_ndx, None], the_sign[item_ndx, None]) estimate_int *= partial_int otpt = integrate.fixed_quad( lambda x: estimate_int, quad_start, quad_stop, n=quad_n)[0] return -np.log(otpt).dot(counts) fminbound(min_local_func, -4, 4) # Update the partial integral based on the new found values estimate_int = _compute_partial_integral(theta, difficulty[item_ndx, None], discrimination[item_ndx, None], the_sign[item_ndx, None]) # update partial integral partial_int *= estimate_int if(np.abs(previous_difficulty - difficulty).max() < 1e-3): break cost = integrate.fixed_quad( lambda x: partial_int, quad_start, quad_stop, n=quad_n)[0] return -np.log(cost).dot(counts)
def negObjFunc(self, c, X): if (np.isscalar(c)): EV = integrate.fixed_quad(self.EVpart, self.yMin, self.yMax, args=(X, c), n=self.quad_order) return -(self.u(c) + (self.beta * EV[0])) obj = np.empty(len(c)) for ix, (cVal, XVal) in enumerate(zip(c, X)): EV = integrate.fixed_quad(self.EVpart, self.yMin, self.yMax, args=(XVal, cVal), n=self.quad_order) obj[ix] = -(self.u(cVal) + (self.beta * EV[0])) return obj
def PhotozProbabilities(zmin, zmax, membz, membzerr, fast=True): if fast: out = fastGaussianIntegration(membz, membzerr, zmin, zmax) else: out = [] for i in range(len(membz)): aux, err = integrate.fixed_quad(gaussian, zmin, zmax, args=(membz[i], membzerr[i])) out.append(aux) out = np.array(out) return out
def matter_correlation_function(self, r=None, rmin=10, rmax=200, pk=None, kh=None, redshifts=[ 0, ], npoints=200, bias_f=None): #print "Estimate Correlation function" if pk is None: self.camb_params.WantTransfer = True self.camb_params.set_matter_power(redshifts=redshifts, kmax=50.0) self.get_results() kh, z, pk = self.results.get_matter_power_spectrum(minkh=1.e-4, maxkh=50., npoints=npoints) #npoints = pk.shape[1] if r is None: r = np.linspace(rmin, rmax, npoints) xi = np.zeros([len(redshifts), r.shape[0]]) k_min = kh.min() k_max = kh.max() #lgk_min = np.log10(kh.min()) #lgk_max = np.log10(kh.max()) #pkf = lambda lgk, i: np.interp(lgk, np.log10(kh), pk[i]) #itf = lambda lgk, r, i: 10.**(lgk*3) * np.log(10.) * pkf(lgk, i)\ # * jn(0, (10.**lgk)*r) / 2. / np.pi**2 #xif = np.vectorize(lambda r, i: \ # fixed_quad(itf, lgk_min, lgk_max, args=(r, i), n=10000)[0]) if bias_f is not None: pkf = lambda k, i: np.interp(k, kh, pk[i]) * bias_f(k, i) else: pkf = lambda k, i: np.interp(k, kh, pk[i]) itf = lambda k, r, i: k**2 * pkf(k, i) * jn(0, k * r) / 2. / np.pi**2 xif = np.vectorize(lambda r, i: \ fixed_quad(itf, k_min, k_max, args=(r, i), n=20000)[0]) for i in range(len(redshifts)): #print "z = %3.1f"%redshifts[i] xi[i, :] = xif(r, i) return xi, r
def distance_quadrature(vol, p1, p2, axis, epsabs=1.49e-08, epsrel=1.49e-08): lb = p1[axis] ub = p2[axis] print(p1) print(p2) y = None if axis == 0: spat_dev = np.array([1,0,0]) y = integrate.fixed_quad(lambda x: integrand(x, p1[1], p1[2], vol, spat_dev), lb, ub, n=2) elif axis == 1: spat_dev = np.array([0,1,0]) args = (p1[1], p1[2], vol, spat_dev, axis)
def weighted_Delta_sigma_fixed_parent_final(self, RR): def integrand(Rsat, R): return number_density_spline(Rsat) * self.Delta_sigma_parent( R, Rsat) if np.isscalar(RR): RRR = np.array([RR]) else: RRR = RR ans = np.zeros(RRR.size) for i in range(RRR.size): ans[i] = fixed_quad(integrand, b_min, b_max, args=[RRR[i]])[0] return ans / factor