def joint_optical_mag_fn_atten(hm, mag1, mag2, band1, band2, z, params): """ Number density per unit observed (extincted) optical magnitude, in two given bands. Uses an analytic marginalisation for extinction. """ # FIXME: Needs testing for correctness mstar = np.logspace(params['mass_mstar_min'], params['mass_mstar_max'], params['nsamp_mstar']) sfr = np.logspace(params['sfr_min'], params['sfr_max'], params['nsamp_sfr']) # Calculate passive fraction and stellar mass function fpass = f_passive(mstar, z, params=params) dndlogms = stellar_mass_fn(hm, mstar, z, params=params) # Evaluate p(mag1 | SFR, M*) p(mag2 | SFR, M*) p(SFR | M*) n(M*) # and integrate over M*. Assumes magnitude pdfs are independent. n_sfms = []; n_pass = [] for _sfr in sfr: pdf_om1 = pdf_optical_mag_atten(mag1, _sfr, mstar, band1, z, params) pdf_om2 = pdf_optical_mag_atten(mag2, _sfr, mstar, band2, z, params) n_sfms.append( integrate( (1. - fpass) * dndlogms * pdf_om1 * pdf_om2 * pdf_sfr_sfms(_sfr, mstar, z, params), np.log(mstar) ) ) n_pass.append( integrate( fpass * dndlogms * pdf_om1 * pdf_om2 * pdf_sfr_passive(_sfr, mstar, z, params), np.log(mstar) ) ) # Integrate over SFR to get n(mag) n_mag_sfms = integrate(n_sfms, sfr) n_mag_pass = integrate(n_pass, sfr) # Return total function (dn/dmag1/dmag2) ~ Mpc^-3 mag^-1 return n_mag_sfms, n_mag_pass
def __init__(self, beta, w, dos): try: nw, norbitals, nspins = dos.shape except ValueError: raise ValueError("dos must be a nw, norbital, nspins array") if w.shape != (nw, ): raise ValueError("w and dos are not consistent in shape") Lattice.__init__(self, beta, norbitals, nspins) integrate = lambda fw: scipy.integrate.trapz(fw, w) cum_int = lambda fw: scipy.integrate.cumtrapz(fw, w, initial=0) if (dos < 0).any() or dos.imag.any(): warn("dos is not a positive real function.", UserWarning, 2) dos_w_last = dos.transpose(1, 2, 0) norm = integrate(dos_w_last) if not np.allclose(norm, 1): warn("dos seems not to be properly normalised.\n Norms: %s" % norm, UserWarning, 2) self.w = w self.dos = dos self.int_dos = cum_int(dos_w_last).transpose(2, 0, 1) self.hloc = integrate(dos_w_last * w) self.hmom2 = integrate(dos_w_last * w**2) self.hloc = orbspin.promote_diagonal(self.hloc) self.hmom2 = orbspin.promote_diagonal(self.hmom2)
def sfr_fn(hm, sfr, z, params): """ Number density for a given SFR, found by integrating the stellar mass function weighted by p(SFR|M*). """ mstar = np.logspace(params['mass_mstar_min'], params['mass_mstar_max'], params['nsamp_mstar']) # Calculate passive fraction and stellar mass function fpass = f_passive(mstar, z, params=params) dndlogms = stellar_mass_fn(hm, mstar, z, params=params) # Integrate over stellar mass function, weighted by p(SFR | M_*), # to get n(SFR); do this for each population n_sfr_sfms = [ integrate( (1.-fpass) * dndlogms * pdf_sfr_sfms(_sfr, mstar, z, params=params), np.log(mstar) ) for _sfr in sfr] n_sfr_pass = [ integrate( fpass * dndlogms * pdf_sfr_passive(_sfr, mstar, z, params=params), np.log(mstar) ) for _sfr in sfr] n_sfr_sfms = np.array(n_sfr_sfms) n_sfr_pass = np.array(n_sfr_pass) # Return total function (dn/dlog(SFR)) #return sfr * (n_sfr_sfms + n_sfr_pass) return sfr * n_sfr_sfms, sfr * n_sfr_pass
def edot_times_r3_orbit_averaged_corotating(delta=0.0, eccentricity=1e-3, radius=10, order='exact'): def edot_exact(f): x = radius * np.cos(f + delta) y = radius * np.sin(f + delta) return edot_times_r3_from_unit_point_mass_at_position( eccentricity, f, x, y) def edot_first_order(f): return edot_times_r3_limit_in_small_e_and_large_r(f, f + delta) def edot_second_order(f): return edot_times_r3_second_order_in_e_at_large_r(f, f + delta) def integrate(g): return g(np.linspace(0.0, 2 * np.pi, 10000)).mean() if order == 'exact': return integrate(edot_exact) / 2 / np.pi if order == 1: return integrate(edot_first_order) / 2 / np.pi if order == 2: return integrate(edot_second_order) / 2 / np.pi
def calc_m_matrix(is_tapered): mij_f = np.zeros((func_num, func_num)) # mij行列用のarrayを確保 for i in range(func_num): for j in range(func_num): if i <= j: mij_f[i, j] = float(integrate(calc_mu(x, is_tapered) * phi_list[i] * phi_list[j], (x, 0, l))) # integral = scipy.integrate.quad(calc_integ_f_mij, 0, l, args=(is_tapered, i, j)) # mij_f[i, j] = integral[0] if i > j: mij_f[i, j] = float(integrate(calc_mu(x, is_tapered) * phi_list[j] * phi_list[i], (x, 0, l))) # integral = scipy.integrate.quad(calc_integ_f_mij, 0, l, args=(is_tapered, j, i)) # mij_f[i, j] = integral[0] return mij_f
def calc_k_matrix(is_tapered): kij_f = np.zeros((func_num, func_num)) # kij行列用のarrayを確保 for i in range(func_num): for j in range(func_num): if i <= j: kij_f[i, j] = float(integrate(calc_EI(x, is_tapered) * dd_phi_list[i] * dd_phi_list[j], (x, 0, l))) # integral = scipy.integrate.quad(calc_integ_f_kij, 0, l, args=(is_tapered, i, j)) # kij_f[i, j] = integral[0] # o番目が積分値,1番目はerror if i > j: kij_f[i, j] = float(integrate(calc_EI(x, is_tapered) * dd_phi_list[j] * dd_phi_list[i], (x, 0, l))) # integral = scipy.integrate.quad(calc_integ_f_kij, 0, l, args=(is_tapered, j, i)) # kij_f[i, j] = integral[0] return kij_f
def adaptive(a, b, tol): c = (a + b) / 2. l = (b - a) * 1. global count whole, f = integrate(a, b) part1, f1 = integrate(a, c) part2, f2 = integrate(c, b) even = f1 == f2[::-1] error = numpy.abs(whole - part1 - part2) if (not (any(numpy.transpose(even)[0])) and error < tol * (l)): return (numpy.array([whole, error])) else: count = count + 1 return (adaptive(a, c, tol) + adaptive(c, b, tol))
def rphitrue( pmt = 0, zs = [-230., 0., 230.] ): x0, y0 = pmt_map[pmt] z0 = -250.#-382. xm, xp = x0 - 32., x0 + 32. titles = { z : 'true z = {0};r (mm);phi (rad);# photons'.format(z) for z in zs } hs = { z : TH2F( titles[z], titles[z], rbin, rmin, rmax, pbin, pmin, pmax ) for z in zs } psf = { z : lambda y,x: ((z-z0)/2*pi) / ( (x-x0)**2 + (y-y0)**2 + (z-z0)**2 )**1.5 for z in zs } integrate = scipy.integrate.dblquad for dat in data: x, y, z = xyz_map[dat[0]] if not z in zs: continue r = (x**2 + y**2)**0.5 phi = atan2( y, x ) n = integrate(psf[z],xm,xp, lambda x: y0 - sqrt(1024.0-(x-x0)**2), lambda x: y0 + sqrt(1024.0-(x-x0)**2) )[0] bin = hs[z].Fill(r,phi) hs[z].SetBinContent( bin, n ) canvas = TCanvas() canvas.Divide(2,2) for i,z in enumerate(zs): canvas.cd(i+1) hs[z].Draw('zcol') canvas.Modified() canvas.Update() return hs, canvas
def pystellar(self,xs,ics,integrator): """Run an integration from the central point to the outer edge.""" ys, data = integrate(self.integral,xs,ics,args=(integrator,),**self.config["System.Integrator.PyStellar"][integrator]["Arguments"]) self.log.debug("Finished %s Integration" % integrator) if self._logmode: xs = np.power(10,xs) rho = density(P=ys[:,2],T=ys[:,3],mu=self.mu) eps = dldm(T=ys[:,3],rho=rho,X=self.X,XCNO=self.XCNO,cfg=self.config["Data.Energy"]) self.opacity.kappa(T=ys[:,3],rho=rho) rgrad = radiative_gradient(T=ys[:,3],P=ys[:,2],l=ys[:,1],m=xs,rho=rho,optable=self.opacity) agrad = grad(rgrad) self.opacity.kappa(T=ys[:,3],rho=rho) kappa = self.opacity.retrieve() all_data = np.vstack(map(np.atleast_2d,(xs,ys.T,rho,eps,rgrad,agrad,kappa))).T np.savetxt(self.config["System.Outputs.Data.Integration"] % {'integrator':integrator},all_data) if self._plotting and np.isfinite(all_data).all(): self.update_dashboard(xs,ys.T,rho,agrad,kappa,eps,line=integrator+self.name,figure='split') self.dashboard.update("integration","integrationextras") elif not np.isfinite(all_data).all(): self.log.debug("Skipping integration plots due to non-finite data.") self.log.debug("Plotted %s Integration" % integrator) return ys, xs, data
def intervalErrorPlot(f, y, integrator, T=1, maxNumberOfSteps=1000, numberOfPointsOnPlot=16): """ Рисует график зависимости погрешности интегрирования на интервале от длины шага интегрирвания. Аргументы повторяют аргументы oneStepErrorPlot. """ eps = np.finfo(float).eps numberOfSteps = np.logspace(0, np.log10(maxNumberOfSteps), numberOfPointsOnPlot).astype(np.int) steps = T / numberOfSteps # шаги интегрирования y0 = y(0) # начальное значение yPrecise = y(T) # точнре значения решения на правом конце yApproximate = [ integrate(N, T / N, f, y0, integrator) for N in numberOfSteps ] # приближенные решения # print('precise:', yPrecise) # print('appr:', yApproximate) # print(steps) # plt.plot(steps, yApproximate, '-g') # c = 2 * np.arctanh(np.tan(1 / 2)) # yExact = lambda t: 2 * np.arctan(np.tanh((t + c) / 2)) # plt.plot(steps, yExact(steps), '-r') h = [np.maximum(np.max(np.abs(yPrecise - ya)), eps) for ya in yApproximate] plt.loglog(steps, h, '.-') plt.xlabel("Шаг интегрирования") plt.ylabel("Погрешность интегрования на интервале")
def theoretical_time_cdf_function_limit(S): expectation = integrate(S, 0, np.inf) # expectation of T def F(tau): return (integrate(S, 0, tau) - tau * S(tau)) / expectation return np.vectorize(F)
def marginalise(self, **kwargs): if len(kwargs) == 0: return self if len(self.factors) != 0: var, domain = kwargs.popitem() samefacs = [] for factor in self.factors: if var in factor.vars: newfac = factor.marginalise(**{var: domain}) else: samefacs.append(factor) newdist = newfac for d in samefacs: newdist = newdist * d return newdist.marginalise(**kwargs) if len(kwargs) == 1: var, domain = kwargs.popitem() subdomain = self.domain.copy() if var in subdomain.keys(): subdomain.pop(var) if isinstance(domain, Reals): f = lambda **other: log( integrate(lambda a: self.bind(**other).expcall(**{var: a}), domain.min, domain.max)[0]) elif isinstance(domain, Integers): f=lambda **other: reduce(logaddexp,map(lambda a:self.bind(**other).expcall(**{var:a}),domain))\ -log(domain.max-domain.min) return LogDistributionFunction(f, **subdomain) else: var, domain = kwargs.popitem() subspace = self.marginalise(**{var: domain}) return subspace.marginalise(**kwargs)
def optical_mag_fn_atten(hm, mag, band, z, params): """ Number density per unit observed (extincted) optical magnitude, in a given band. Uses an analytic marginalisation to reduce the number of integrals. """ mstar = np.logspace(params['mass_mstar_min'], params['mass_mstar_max'], params['nsamp_mstar']) sfr = np.logspace(params['sfr_min'], params['sfr_max'], params['nsamp_sfr']) # Calculate passive fraction and stellar mass function fpass = f_passive(mstar, z, params=params) dndlogms = stellar_mass_fn(hm, mstar, z, params=params) # Loop over magnitude values n_mag_sfms = []; n_mag_pass = [] for m in mag: # Evaluate p(mag | SFR, M*) . p(SFR | M*) n(M*) and integrate over M* n_sfms = []; n_pass = [] for _sfr in sfr: _pdf_om = pdf_optical_mag_atten(m, _sfr, mstar, band, z, params) n_sfms.append( integrate( (1. - fpass) * dndlogms * _pdf_om * pdf_sfr_sfms(_sfr, mstar, z, params), np.log(mstar) ) ) n_pass.append( integrate( fpass * dndlogms * _pdf_om * pdf_sfr_passive(_sfr, mstar, z, params), np.log(mstar) ) ) """ # Evaluate p(mag | SFR, M*) . p(SFR | M*) n(M*) and integrate over M* n_sfms = [integrate( (1. - fpass) * dndlogms * pdf_sfr_sfms(_sfr, mstar, z, params=params) * pdf_optical_mag_atten(m, _sfr, mstar, band, z, params), np.log(mstar) ) for _sfr in sfr] n_pass = [integrate( fpass * dndlogms * pdf_sfr_passive(_sfr, mstar, z, params=params) * pdf_optical_mag_atten(m, _sfr, mstar, band, z, params), np.log(mstar) ) for _sfr in sfr] """ # Integrate over SFR to get n(mag) n_mag_sfms.append( integrate(n_sfms, sfr) ) n_mag_pass.append( integrate(n_pass, sfr) ) # Return total function (dn/dmag) ~ Mpc^-3 mag^-1 return np.array(n_mag_sfms), np.array(n_mag_pass)
def theoretical_time_cdf_function_at_time(S, t): tmp = integrate(S, 0, t) def F(tau): bound = min(t, tau) return (integrate(S, 0, bound) - bound * S(tau)) / tmp return np.vectorize(F)
def fromData(cls, x, y): store = cls() mean, var, skew, kurt = [cls.nthMoment(x, y, i) for i in range(1, 5)] store['area'] = integrate(x, y) store['mean'] = mean store['var'] = var store['skew'] = skew store['kurt'] = kurt return store
def integrate(self, omega): y0 = list(self.cp.surface.base_sheets) tmp = y0[self.starting_sheet] del y0[self.starting_sheet] y0 = np.array([tmp] + y0) sp = self.cp.surface._path_factory.RiemannSurfacePath_from_complex_path( self._path, y0=y0) return sp.integrate(omega)
def integrate(f, y0, t, t0=None, method_name='zvode', f_params=None, save_func=None, **kwargs): r""" Functional interface to solvers from `scipy.integrate.ode` Provides syntax resembling `scipy.integrate.odeint` to solve the first-order differential equation: .. math:: \frac{dy}{dt} = f(t, y, \ldots) with the initial value y0 at times specified by the vector t. If y0 is a higher than 1-dimensional vector, integrate only integrates over the last axes, looping over all prior axes. Parameters ---------- f : function Funtion to integrate. Should take arguments like f(t, y, **f_params). y0 : np.ndarray Initial value at time t0. t : np.ndarray Times at which to return the state of the system. t0 : float, optional Time at which to start the integration. Defaults to t[0]. method_name : string, optional Method name to pass to scipy.integrate.ode (default 'zvode'). If method_name is not 'zvode', scipy.integrate.complex_ode is used instead. f_params : dict, optional Additional parameters to pass to `f`. save_func : function, optional Function to call on a state y to select the desired return values. By default, the entire state vector is returned. **kwargs : optional Additional arguments to pass to the set_integrator of the scipy.integrate.ode instance used to solve this ODE. Returns ------- y : np.ndarray, shape (len(t), len(save_func(y0))) 2D array containing the results of calling save_func on the state of the integrator at all given times t. See also -------- scipy.integrate.ode scipy.integrate.odeint """ if len(y0.shape) == 1: return _integrate(f, y0, t, t0, method_name, f_params, save_func, **kwargs) else: return ndarray_list((integrate(f, y0i, t, t0, method_name, f_params, save_func, **kwargs) for y0i in y0), len(y0))
def normalizeDistrib(x, y, u=None): x = x.values if isinstance(x, pd.Series) else x y = y.values if isinstance(y, pd.Series) else y # normalize the distribution to area of 1 norm = integrate(x, y) #print("CONTINs norm", norm) y /= norm if u is not None: u /= norm return x, y, u
def MarcenkoPasturIntegral(x, beta): if beta <= 0 or beta > 1: raise ValueError('beta beyond') lobnd = (1 - np.sqrt(beta))^2 hibnd = (1 + np.sqrt(beta))^2 if (x < lobnd) or (x > hibnd): raise ValueError('x beyond') dens = lambda t: np.sqrt((hibnd-t) * (t-lobnd)) / (2*pi * beta * t) I = integrate(dens, lobnd, x) printf('x={x:.3f},beta={beta:.3f},I={I:.3f}\n') return I
def integrate(self, omega): y0 = list(self.cp.surface.base_sheets) tmp = y0[self.starting_sheet] del y0[self.starting_sheet] y0 = np.array([tmp] + y0) # We modify this method to make use of the previously calculated surface path if it exists. if self.surface_path != None: sp = self.surface_path else: sp = self.cp.surface._path_factory.RiemannSurfacePath_from_complex_path(self._path, y0=y0) return sp.integrate(omega)
def return_book_index(): x = np.linspace(0, 100, 101) y = np.linspace(0, 200, 201) yy, xx = np.meshgrid(x, y) z = a * yy**3 + b * yy**2 + c * yy + d world = np.array([list(zip(x, y, z)) for x, y, z in zip(xx, yy, z)]) y = f(x) len100 = int(integrate(f, 100)[0]) len0 = int(integrate(f, 0)[0]) worldlist = [world[200, 0], world[200, 100], world[0, 0], world[0, 100]] imagelist = [ np.array([200, len0]), np.array([200, len100]), np.array([0, len0]), np.array([0, len100]) ] worldlist = np.array(worldlist, dtype=np.float32) imagelist = np.array(imagelist, dtype=np.float32) return world, worldlist, imagelist
def integrate(self, payoff_function, option_type=None): """ Integrate the payoff times numeraire. :param payoff_function: a function, typically get_payoff or get_unit_payoff :param option_type: OptionType or None, None to be exclusively used for get_unit_payoff :return: float """ assert option_type is not None or payoff_function.__name__ == 'get_unit_payoff' args = [option_type] if option_type is not None else [] result = integrate(payoff_function, *args, **self.model.integrate_quad_options_dict) return result[0]
def integrate_weno(equation: equations.Equation, times: np.ndarray = _DEFAULT_TIMES, warmup: float = 0, integrate_method: str = 'RK23', **kwargs: Any) -> xarray.Dataset: """Integrate a baseline finite difference model.""" differentiator = WENODifferentiator(equation, **kwargs) return integrate(equation, differentiator, times, warmup, integrate_method=integrate_method)
def integrate_exact( equation: equations.Equation, times: np.ndarray = _DEFAULT_TIMES, warmup: float = 0, integrate_method: str = 'RK23', filter_interval: float = None) -> xarray.Dataset: """Integrate only the exact model.""" equation = equation.to_exact() differentiator = exact_differentiator(equation) return integrate(equation, differentiator, times, warmup, integrate_method=integrate_method, filter_interval=filter_interval)
def integrate_baseline( equation: equations.Equation, times: np.ndarray = _DEFAULT_TIMES, warmup: float = 0, accuracy_order: int = 1, integrate_method: str = 'RK23', exact_filter_interval: float = None) -> xarray.Dataset: """Integrate a baseline finite difference model.""" differentiator = PolynomialDifferentiator( equation, accuracy_order=accuracy_order) return integrate(equation, differentiator, times, warmup, integrate_method=integrate_method, filter_interval=exact_filter_interval)
def integrate_spectral( equation: equations.Equation, times: np.ndarray = _DEFAULT_TIMES, warmup: float = 0, integrate_method: str = 'RK23', exact_filter_interval: float = None) -> xarray.Dataset: """Integrate a baseline finite difference model.""" if type(equation) not in equations.EQUATION_TYPES.values(): raise ValueError('invalid equation: {}'.format(equation)) differentiator = SpectralDifferentiator(equation) return integrate(equation, differentiator, times, warmup, integrate_method=integrate_method, filter_interval=exact_filter_interval)
def joint_lumfn_sfr_optical(hm, sfr, mag, band, z, params, atten=True): """ Joint luminosity function for tracers of SFR and optical magnitudes. """ mstar = np.logspace(params['mass_mstar_min'], params['mass_mstar_max'], params['nsamp_mstar']) # Calculate passive fraction and stellar mass function fpass = f_passive(mstar, z, params=params) dndlogms = stellar_mass_fn(hm, mstar, z, params=params) # Evaluate joint lum. fn. on a grid in SFR and (dust-atten.) optical mag. # The pdf for the SFR tracer is assumed to be a delta-fn., so the SFR # integral has effectively already been evaluated in this expression. n_sfms = []; n_pass = [] for _sfr in sfr: _nsfms = []; _npass = [] for _mag in mag: # Apply dust attenuation correction (or not) if atten: pdf_mag = pdf_optical_mag_atten(_mag, _sfr, mstar, band, z, params) else: pdf_mag = pdf_optical_mag(_mag, _sfr, mstar, band, z, params) # Integrate over stellar mass _nsfms.append( integrate( (1. - fpass) * dndlogms * pdf_mag * pdf_sfr_sfms(_sfr, mstar, z, params), np.log(mstar) ) ) _npass.append( integrate( fpass * dndlogms * pdf_mag * pdf_sfr_passive(_sfr, mstar, z, params), np.log(mstar) ) ) n_sfms.append(_nsfms) n_pass.append(_npass) # Return joint luminosity fns., dn(SFR, mag)/dSFR/dmag return np.array(n_sfms), np.array(n_pass)
def OuterIntegration(i,shapes,mu,data_obsDict,PrettyHugeDict,lnN_matrix,datacards_dict,processes_dict,stats,integrand,Keys,sampler2,measure=1.0,n=10,**IntVars): # Sum elements and elements squared total = 0.0 total_sq = 0.0 for x in itertools.islice(sampler2, n): num,a,b=Boundaries(i,x,shapes,Keys,lnN_keys,lnN_matrix,datacards_dict,processes_dict,PrettyHugeDict) f = integrate(x,shapes,mu,data_obsDict,PrettyHugeDict,lnN_matrix,datacards_dict,processes_dict,stats,integrand,Keys,sampler(num,a,b),measure=1.0,n=100,**IntVars)[0] total += f total_sq += (f**2) # Return answer sample_mean = total/n sample_var = (total_sq - ((total/n)**2)/n)/(n-1.0) return (measure*sample_mean, measure*math.sqrt(sample_var/n))
def pystellar(self, xs, ics, integrator): """Run an integration from the central point to the outer edge.""" ys, data = integrate(self.integral, xs, ics, args=(integrator, ), **self.config["System.Integrator.PyStellar"] [integrator]["Arguments"]) self.log.debug("Finished %s Integration" % integrator) if self._logmode: xs = np.power(10, xs) rho = density(P=ys[:, 2], T=ys[:, 3], mu=self.mu) eps = dldm(T=ys[:, 3], rho=rho, X=self.X, XCNO=self.XCNO, cfg=self.config["Data.Energy"]) self.opacity.kappa(T=ys[:, 3], rho=rho) rgrad = radiative_gradient(T=ys[:, 3], P=ys[:, 2], l=ys[:, 1], m=xs, rho=rho, optable=self.opacity) agrad = grad(rgrad) self.opacity.kappa(T=ys[:, 3], rho=rho) kappa = self.opacity.retrieve() all_data = np.vstack( map(np.atleast_2d, (xs, ys.T, rho, eps, rgrad, agrad, kappa))).T np.savetxt( self.config["System.Outputs.Data.Integration"] % {'integrator': integrator}, all_data) if self._plotting and np.isfinite(all_data).all(): self.update_dashboard(xs, ys.T, rho, agrad, kappa, eps, line=integrator + self.name, figure='split') self.dashboard.update("integration", "integrationextras") elif not np.isfinite(all_data).all(): self.log.debug( "Skipping integration plots due to non-finite data.") self.log.debug("Plotted %s Integration" % integrator) return ys, xs, data
def nquad_vec(func, ranges): initial_depth = len(ranges) - 1 def integrate(*args, depth): if depth == 0: f = functools.partial(func, *args) else: f = functools.partial(integrate, *args, depth=depth - 1) return scipy.integrate.quad_vec(f, *ranges[initial_depth - depth])[0] return integrate(depth=initial_depth)
def calculate(self,k): '''Return value of :math:`\hat{\omega}` at supplied :math:`k` Arguments --------- k: np.ndarray array of wavenumber values to calculate :math:`\omega` at ''' integrate = np.trapz integrate = scipy.integrate.simps self.value = np.zeros_like(k) B = [] dx = 0.1 x = np.arange(dx,100,dx) K,X = np.meshgrid(k,x,indexing='ij') # Precaculate factors for efficiency ZBase = (1/(np.pi*K))*X*(np.sin(K-X)/(K-X) - np.sin(K+X)/(K+X)) sinxx = np.sin(x)/x sinXX = np.sin(X)/X sinkk = np.sin(k)/k J0Base = (np.sin(x)/x - np.cos(x)) for tau in range(2,self.length): J0val = 2/np.pi * integrate((sinxx)**(tau)*J0Base,x=x) B = (1 - J0val)**(-1.0) Z = ZBase * (sinXX)**(tau) Jvals = integrate(Z,x=x,axis=1) omega_t = B * ((sinkk)**(tau) - Jvals) self.value += (self.length - tau) * (omega_t - (sinkk)**(tau)) self.value *= 2.0/self.length self.value += self.FJC.calculate(k) return self.value
def stellar_mass_fn(hm, mstar, z, params): """ Calculate the stellar mass function, dn/dlog(M*), as a function of stellar mass and redshift. """ # Halo mass function, n(M_h) = dn/dlogM Mh = np.logspace(params['mass_mhalo_min'], params['mass_mhalo_max'], params['nsamp_mhalo']) dndlogm = hm.dndlogm(Mh, z) # Integrate mass fn. over halo mass, weighted by p(M* | M_h), to get n(M*) n_mstar = [ integrate( dndlogm * pdf_mass_stellar(_mstar, Mh, z, params=params), np.log(Mh) ) for _mstar in mstar] return mstar * np.array(n_mstar) # Convert to dn/dlog(M*)
def likelihood_total(params, overwrite=True): '''[lambd, a4, b4, c1, c2, c3,..., cN]''' global toc global likelihood_min if params.size == 0 or params.shape == (1, 23): fname = "current_optimizer_" + m_nu + '_' + o_m + '_' + A_s + ".npy" params = np.load(fname) lambd = params[0] p = params[1:] print(p) _, hmf_piecewise_params = get_HMF_piecewise(p, reg_bins=19, Mpiv=Mpiv, offset=0) N_model = integrate(hmf_piecewise_params, zeroth_bin=False) print("var: ", likelihood_var(lambd, params[3:])) print("sim: ", likelihood_sim(Y_curr, N_model, C, idx)) res = likelihood_sim(Y_curr, N_model, C, idx) + \ likelihood_var(lambd, params[3:]) if overwrite and res < likelihood_min: likelihood_min = res fname = "current_optimizer_" + m_nu + '_' + o_m + '_' + A_s + ".npy" np.save(fname, params) print("Saved to ", fname) cost_overrun = 0 for c in params[2:]: if c > 0.: cost_overrun += (1000 * c)**8 if params[0] < 1: cost_overrun += (1000 * (1 - params[0]))**8 if not overwrite: print(N_model) print("overrun: ", cost_overrun) # toc = time.perf_counter() return res + cost_overrun
def _abel_sym(): """ Analytical integration of the cell near the singular value in the abel transform The resulting formula is implemented in abel.lib.direct.abel_integrate """ from sympy import symbols, simplify, integrate, sqrt from sympy.assumptions.assume import global_assumptions r, y, r0, r1, r2, z, dr, c0, c_r, c_rr, c_z, c_zz, c_rz = symbols( 'r y r0 r1 r2 z dr c0 c_r c_rr c_z c_zz c_rz', positive=True) f0, f1, f2 = symbols('f0 f1 f2') global_assumptions.add(Q.is_true(r > y)) global_assumptions.add(Q.is_true(r1 > y)) global_assumptions.add(Q.is_true(r2 > y)) global_assumptions.add(Q.is_true(r2 > r1)) P = c0 + (r - y) * c_r #+ (r-r0)**2*c_rr K_d = 1 / sqrt(r**2 - y**2) res = integrate(P * K_d, (r, y, r1)) sres = simplify(res) print(sres)
def _abel_sym(): """ Analytical integration of the cell near the singular value in the abel transform The resulting formula is implemented in abel.lib.direct.abel_integrate """ from sympy import symbols, simplify, integrate, sqrt from sympy.assumptions.assume import global_assumptions r, y,r0, r1,r2, z,dr, c0, c_r, c_rr,c_z, c_zz, c_rz = symbols( 'r y r0 r1 r2 z dr c0 c_r c_rr c_z c_zz c_rz', positive=True) f0, f1, f2 = symbols('f0 f1 f2') global_assumptions.add(Q.is_true(r>y)) global_assumptions.add(Q.is_true(r1>y)) global_assumptions.add(Q.is_true(r2>y)) global_assumptions.add(Q.is_true(r2>r1)) P = c0 + (r-y)*c_r #+ (r-r0)**2*c_rr K_d = 1/sqrt(r**2-y**2) res = integrate(P*K_d, (r,y, r1)) sres= simplify(res) print(sres)
def solve_mc_single(H, psi, T, J=None, adapt=None, time_manager=None, dp_max=1e-2, seed=0, save_jumptimes=False): if time_manager is None: time_manager = TimeStepManager() T_calculated = [T[0]] results = Trajectory([psi.copy()]) jumptimes = [] rand_gen = random.Random(seed) state = IntegrationState(T[0], psi, H, J) while True: state = time_manager(state, T, adapt, dp_max) if state.t in T[1:]: if state.t not in T_calculated: T_calculated.append(state.t) results.append(state.psi.copy()) if state.t == T[-1]: break next_t = state.next_t() rand_number = rand_gen.random()/(next_t - state.t) P = state.jump_probabilities if P is not None and rand_number < P[-1]: # Quantum Jump n = (P<rand_number).sum() state.psi = state.jumps[n] state.jumped = True if save_jumptimes: jumptimes.append((state.t, n)) else: # non hermitian time evolution if state.H_nH is None: state.H_nH = calculate_H_nH(state.H, state.J) #try: state.psi = integrate(state.H_nH, state.psi, next_t - state.t) #except: # print("Integration aborted.") # return results state.psi.renorm() state.t_last = state.t state.t = next_t #print(state.t) if save_jumptimes: return results, jumptimes return results
# hd = 0.5 plt.show() quit() print(abs(p-n)) print(abs(m-n)) quit() hist_dist_np = bin_width * 0.5 * sum(abs(p[0:99]-n[0:99])) hist_dist_nm = bin_width * 0.5 * sum(abs(m[0:99]-n[0:99])) print(hist_dist_np, hist_dist_nm) quit() integrand1 = bin_width * abs(sum(p)-sum(n)) hist_dist = 0.5 * sp.integrate(bin_width * abs(p-n)) print(hist_dist) plt.show() quit() hist_dist = 0.5 * Integral(abs()) a = integral1-integral b = integral2-integral1 hist_dist1 = 0.5 * a hist_dist2 = 0.5 * b print(hist_dist1, hist_dist2) plt.show() quit() # m,n = sns.distplot(cFPdata1_trans).get_lines()[0].get_data() # print(m)
L_2 = 6 * eta * (1 + 0.5 * eta) **2. / (1 - eta )**4. L_3 = 0.5 * eta * L_1 c_x = L_1 * phi_1 + L_2 * phi_2 + L_3 * phi_3 fourpi = 4 * np.pi I_R = np.zeros(R.shape) c_R = np.copy(I_R) g_R = np.copy(I_R) I_x = fourpi ** 2. * p * d3 * c_x * c_x / (1 - fourpi * p * c_x ) for j in range(npoints_r) : r = R[j] sin_x = np.sin( x * r / d ) f_x = x * sin_x * I_x pre = 1./(2 * np.pi**2. * r * d*d) I_R[j] = pre * integrate(f_x , x ) if r < d : c_R[j] = L_1 + L_2 * (r/d) + L_3 * (r/d)**3. else: c_R[j] = 0.0 #AX[i].plot(R,I_R) #AX[i].set_title(r'$\rho^{*}$ = %f'%p) h_R = I_R + c_R plt.plot(R,h_R) plt.title(r'$\rho^{*}$ = %f'%p) plt.savefig('1iii_rho_%.2f.png'%p) plt.clf() # write h_R to file g_R = h_R + 1. ofn = 'g_R_rho_%.2f.dat'%p
def __prepare_interpolation(self): "prepares the interpolation (private function)" q=self.input.q; x=self.input.x; f=self.input.f.copy(); # -- (A) normalisation: f -> f*w ------------------------------------------- for iq in range(f.shape[0]): for ix in range(f.shape[1]): f[iq,ix] = f[iq,ix]*self.wfunc(q[iq],x[iq,ix]); # -- (B) integration: F = Int f dx ---------------------------------------- def integrate(f,x): F=np.zeros(x.size); for i in range(x.size): # Simpson rule seems to be problematic for f(x)~0 #F[i]=scipy.integrate.simps(f[0:i+1],x[0:i+1]); # Trapezoidal rule #F[i]=scipy.integrate.trapz(f[0:i+1],x=x[0:i+1]); # we use simple summation (see FAQ 3) F[i]=np.sum(f[0:i+1])*(x[1]-x[0]); return F; F=np.zeros(f.shape); for iq in range(q.size): F[iq]=integrate(f[iq],x[iq]); # DEBUG: plot f(q,x) and F(q,x) if self.__debug: fig=plt.figure(); ax1 = fig.add_subplot(211); ax2 = fig.add_subplot(212); FamilyOfCurves(q,x,f).plot(ax=ax1, title="Debug: (B) Integration"); FamilyOfCurves(q,x,F,fdesc="F").plot(ax=ax2,legend=False); ax1.legend(loc="upper left", bbox_to_anchor=(1,1)) fig.subplots_adjust(right=0.75); # -- (C) inversion F(q,x) -> xi(q,Fi) ------------------------------------- Fi=F.flatten(); Fi.sort(); # adaptive grid for new F vals if self.num_F is not None: # reduce number of F values index=np.linspace(0,len(Fi)-1,self.num_F); Fi=Fi[map(int,np.round(index))]; Fi=np.unique(Fi); Fmin=F[:,-1].min(); Fmax=F[:,-1].max(); # last value of F should be 1 Fi=Fi[np.where(Fi<Fmin)]; # make F(q,x) surjective if (Fmax-Fmin)/(Fmax+Fmin) > 0.001: # check normalisation if self.verbosity>0: print "\n WARNING: normalisation of integrals deviates by " +\ "%4.1f%% at x=%4.1f"%(100*(Fmax-Fmin)/(Fmax+Fmin),x[0,-1]) +\ "\n check the sum-rule and eventually increase the x-range." xi=FamilyOfCurves(q,F,x, qdesc="q",xdesc="F",fdesc="x").interpolate_x(Fi,k=self.k); # interp. curves x(q,F) along # abscissa at Fi => xi(q,Fi) # -- (D) save family of curves xi(Fi,q) ----------------------------------- self.__xi_of_Fi_q = FamilyOfCurves(Fi,q,xi.swapaxes(0,1), qdesc="Fi",xdesc="q",fdesc="xi");
# numarray=[i*j for i,j in zip(fft,gf)] # number=scipy.integrate.simps(numarray, x=freq) # print l, number #print ' ' # cvv for l in lamb: fplus=array([f(l, i, beta) for i in freq]) # filetemp=open('f_vv_'+str(l), 'w') # trash=[filetemp.write('%f %f\n' %(i,j)) for i,j in zip(freq, fplus)] # filetemp.close() # integrate numarray=[i*j for i,j in zip(fft,fplus)] number=scipy.integrate.simps(numarray, x=freq) number=integrate(freq[1], fft[1:], fplus) print l/beta, number print ' ' ## force #for l in lamb: # gffplus=array([t(l, i, beta) for i in freq]) ## filetemp=open('f_ff_'+str(l), 'w') ## trash=[filetemp.write('%f %f\n' %(i,j)) for i,j in zip(freq, gffplus)] ## filetemp.close() # number=integrate(freq[1], fft, gffplus) # print l, number # #
def integrand1(z): return lognorm.pdf(z,1) def integrand2(z): return norm.pdf(z,0,1) def sampler1(num): while True: z=random.uniform(0,10) yield z def sampler2(num): while True: z=random.uniform(-4,4) yield z err1=0 err2=0 for i in xrange(0,100): err1+=integrate(integrand1,sampler1(1),measure=10.0, n=1000)[1]/integrate(integrand1,sampler1(1),measure=10.0, n=1000)[0] err2+=integrate(integrand2,sampler2(1),measure=40.0, n=1000)[1]/integrate(integrand2,sampler2(1),measure=40.0, n=1000)[0] print err1/100, err2/100 #print (int(strftime("%H", gmtime())[0:2])+2), int(strftime("%M", gmtime())[0:2]) #func1= lambda *args: function(**Assign(args,**IntVars)) #func2= lambda *args: sum(args) #print func2(1,1,1,1,1) #print integrate.nquad(func1,[[0,1],[0,1],[0,1],[0,1]])
plt.legend() plt.xlabel("$N$") plt.ylabel("Approximation - $\int_0^1 \exp(x)\,dx$") plt.ylim(simp_error.min(), simp_error.max()) ax.yaxis.set_major_formatter(FormatStrFormatter("%0.4f")) plt.tight_layout() plt.savefig("latex/approximation_errors.pdf") # evaluates $\int_a^b func(x)\,dx$ using simpson's thing # with $N, 2N, 4N, 8N,$ etc subdivisions until requested accuracy is reached # (simpson($2^{k+1} N$) - simpson($2^k N$))/simpson($2^k N$) < requested accuracy def integrate(func, a, b, N, requested_accuracy): k = 0 prev = simpson(func, a, b, N * 2**k) while True: cur = simpson(func, a, b, N * 2**(k+1)) if abs((prev - cur)/prev) < requested_accuracy: break k += 1 prev = cur return cur # some tests print ("\\int_0^1 e^x\\,dx \\approx %0.10f" % integrate(np.exp, 0, 1, 1, 0.00001)) print ("\\int_0^1 x^9\\,dx \\approx %0.10f" % integrate(lambda x: x**9, 0, 1, 1, 0.00001)) print scipy.integrate.quad(np.exp, 0, 1) print scipy.integrate.romberg(np.exp, 0, 1)
sigma=PrettyHugeDict[key.split(".")[0]+".txt"][key.split(".")[1].split("-")[1]][string][int(key.split(".")[1].split("-")[2]) - 1][1] - PrettyHugeDict[key.split(".")[0]+".txt"][key.split(".")[1].split("-")[1]][string][int(key.split(".")[1].split("-")[2]) - 1][0] sigma=abs(sigma) else: # The mean must be given by "GBC_sum" rather than mu_k! xxx=PrettyHugeDict[key.split(".")[0]+".txt"][key.split(".")[1].split("-")[1]][string][int(key.split(".")[1].split("-")[2]) - 1] mini+=min(xxx[0]-xxx[1],xxx[2]-xxx[1],0.0) maxi+=max(xxx[0]-xxx[1],xxx[2]-xxx[1],0.0) upper=mean+maxi+4*sigma lower=mean+mini-4*sigma a.append(lower) b.append(upper) #Measure*=(upper - lower) else: num+=1 upper=50 lower=0 a.append(lower) b.append(upper) #Measure*=(upper - lower) print num print len(shapes) #print P(mu,data_obsDict,PrettyHugeDict,lnN_matrix,datacards_dict,processes_dict,stats,**IntVars) #print Sum(shapes,mu,data_obsDict,PrettyHugeDict,lnN_matrix,datacards_dict,processes_dict,stats,**IntVars) print integrate(shapes,mu,data_obsDict,PrettyHugeDict,lnN_matrix,datacards_dict,processes_dict,stats,integrand,Keys,sampler(num,a,b),measure=Measure,n=100,**IntVars) print start_time print strftime("%Y-%m-%d %H:%M:%S", gmtime()) # ------------------------------------------------------------------------------
plt.ylabel("Approximation - $\int_0^1 \exp(x)\,dx$") plt.legend() plt.xlabel("$N$") plt.tight_layout() plt.savefig("latex/approximation_errors_long.pdf") # evaluates $\int_a^b func(x)\,dx$ using simpson's thing # with $N, 2N, 4N, 8N,$ etc subdivisions until requested accuracy is reached # (simpson($2^{k+1} N$) - simpson($2^k N$))/simpson($2^k N$) < requested accuracy def integrate(func, a, b, N, requested_accuracy): k = 0 prev = simpson(func, a, b, N * 2**k) while True: cur = simpson(func, a, b, N * 2**(k+1)) if abs((prev - cur)/prev) < requested_accuracy: break k += 1 prev = cur return cur # some tests print ("\\int_0^1 e^x\\,dx \\approx %0.10f, error %0.5g" % (integrate(np.exp, 0, 1, 1, 0.00001), integrate(np.exp, 0, 1, 1, 0.00001) - 1.7182818284590452354)) print ("\\int_0^1 x^9\\,dx \\approx %0.10f" % integrate(lambda x: x**9, 0, 1, 1, 0.00001)) print scipy.integrate.quad(np.exp, 0, 1) print scipy.integrate.romberg(np.exp, 0, 1) print (scipy.integrate.romberg(np.exp, 0, 1) - 1.7182818284590452354)
def cumint(fn=kroupa, bins=np.logspace(-2,2,500)): xax,integral = integrate(fn,bins) return integral.cumsum() / integral.sum()
from sympy import * import scipy.integrate as integrate import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np x = Symbol('x') f = lambdify(x,-abs(x-1/2)+1) pprint(f(3/4)) pprint(integrate(f(x),(x,0,1))) #X = np.linspace(0,1,100) #plt.plot(X,-abs(X-1/2)+1) #plt.show() """ a,b,c,x = symbols('a b c x') f = lambdify(x,a*x**2 + b*x + c) df = lambdify(x,diff(f(x),x)) pprint(solve([Eq(df(0),0),Eq(f(1),0)],[a,b,c])) phi = lambdify(x,1-x**2) #X = np.linspace(0,1,100) #plt.plot(X,phi(X)) #plt.show() RQ = integrate(diff(phi(x),x)**2+x**2*phi(x)**2, (x,0,1))/integrate(phi(x)**2,(x,0,1)) pprint(RQ.evalf(16)) """