def clarray(aps, lmax, zarray, zromb=3, zwidth=None): """Calculate an array of C_l(z, z'). Parameters ---------- aps : function The angular power spectrum to calculate. lmax : integer Maximum l to calculate up to. zarray : array_like Array of z's to calculate at. zromb : integer The Romberg order for integrating over frequency samples. zwidth : scalar, optional Width of frequency channel to integrate over. If None (default), calculate from the separation of the first two bins. Returns ------- aps : np.ndarray[lmax+1, len(zarray), len(zarray)] Array of the C_l(z,z') values. """ if zromb == 0: return aps( np.arange(lmax + 1)[:, np.newaxis, np.newaxis], zarray[np.newaxis, :, np.newaxis], zarray[np.newaxis, np.newaxis, :], ) else: zsort = np.sort(zarray) zhalf = np.abs(zsort[1] - zsort[0]) / 2.0 if zwidth is None else zwidth / 2.0 zlen = zarray.size zint = 2 ** zromb + 1 zspace = 2.0 * zhalf / 2 ** zromb za = ( zarray[:, np.newaxis] + np.linspace(-zhalf, zhalf, zint)[np.newaxis, :] ).flatten() lsections = np.array_split(np.arange(lmax + 1), lmax // 5) cla = np.zeros((lmax + 1, zlen, zlen), dtype=np.float64) for lsec in lsections: clt = aps( lsec[:, np.newaxis, np.newaxis], za[np.newaxis, :, np.newaxis], za[np.newaxis, np.newaxis, :], ) clt = clt.reshape(-1, zlen, zint, zlen, zint) clt = si.romb(clt, dx=zspace, axis=4) clt = si.romb(clt, dx=zspace, axis=2) cla[lsec] = clt / (2 * zhalf) ** 2 # Normalise return cla
def internalInductance1(self, npoints=300): """Calculates li1 plasma internal inductance """ # Produce array of Bpol^2 in (R,Z) B_polvals_2 = self.Bz(self.R, self.Z)**2 + self.Br(R, Z)**2 R = self.R Z = self.Z dR = R[1, 0] - R[0, 0] dZ = Z[0, 1] - Z[0, 0] dV = 2. * np.pi * R * dR * dZ if self.mask is not None: # Only include points in the core dV *= self.mask Ip = self.plasmaCurrent() R_geo = self.Rgeometric(npoints=npoints) elon = self.geometricElongation(npoints=npoints) effective_elon = self.effectiveElongation(npoints=npoints) integral = romb(romb(B_polvals_2 * dV)) return ((2 * integral) / ((mu0 * Ip)**2 * R_geo)) * ((1 + elon * elon) / (2. * effective_elon))
def coupled_entropy(dist, kappa, alpha, d, root, integration): # x, xmin, xmax): if root == False: dist_temp = coupled_probability(dist, kappa, alpha, d, integration) coupled_logarithm_values = [] for i in dist: coupled_logarithm_values.append(coupled_logarithm(i**(-alpha), kappa, d)) pre_integration = [x*y*(-1/alpha) for x,y in zip(dist_temp, coupled_logarithm_values)] # looks like this next line is replaced by the if statement and can be removed final_integration = -1*np.trapz(pre_integration) if integration == 'trapz': final_integration = -1*np.trapz(pre_integration) elif integration == 'simpsons': final_integration = -1*integrate.simps(pre_integration) #elif integration == 'quad': #final_integration, error = -1*integrate.quad(pre_integration[x], 0, len(new_dist_temp)) elif integration == 'romberg': final_integration = -1*integrate.romb(pre_integration) else: dist_temp = coupled_probability(dist, kappa, alpha, d, integration) coupled_logarithm_values = [] for i in dist: coupled_logarithm_values.append(coupled_logarithm(i**(-alpha), kappa, d)**(1/alpha)) pre_integration = [x * y for x, y in zip(dist_temp, coupled_logarithm_values)] if integration == 'trapz': final_integration = np.trapz(pre_integration) elif integration == 'simpsons': final_integration = integrate.simps(pre_integration) #elif integration == 'quad': #final_integration, error = integrate.quad(pre_integration, 0, len(new_dist_temp)) elif integration == 'romberg': final_integration = integrate.romb(pre_integration) return final_integration
def toroidalBeta(self): """Calculate plasma toroidal beta by integrating the thermal pressure and toroidal magnetic field pressure over the plasma volume. """ R = self.R Z = self.Z # Produce array of Btor in (R,Z) B_torvals_2 = self.Btor(R, Z)**2 dR = R[1, 0] - R[0, 0] dZ = Z[0, 1] - Z[0, 0] dV = 2. * np.pi * R * dR * dZ # Normalised psi psi_norm = (self.psi() - self.psi_axis) / (self.psi_bndry - self.psi_axis) # Plasma pressure pressure = self.pressure(psi_norm) if self.mask is not None: # Only include points in the core dV *= self.mask pressure_integral = romb(romb(pressure * dV)) # Correct for errors in Btor and core masking np.nan_to_num(B_torvals_2, copy=False) field_integral_tor = romb(romb(B_torvals_2 * dV)) return 2 * mu0 * pressure_integral / field_integral_tor
def computeFluxes(self, filterWavelength, filterTransmission): """ computeFluxes: Compute the AB and Vega fluxes for specified tranmission curve. USAGE: fluxAB,fluxVega = Vega().computeFluxes(wavelength,transmission) INPUT wavelength -- Wavelengths for filter transmission curve. transmission -- Transmission for filter transmission curve. OUTPUT fluxAB -- AB flux for this filter transmission. fluxVega -- Vega flux for this filter transmission. """ # Interpolate spectrum and transmission data TRANSMISSION = interp1d(filterWavelength,filterTransmission,\ bounds_error=False,fill_value="extrapolate") kRomberg = 8 wavelength = np.linspace(filterWavelength.min(), filterWavelength.max(), 2**kRomberg + 1) deltaWavelength = wavelength[1] - wavelength[0] FLUX = interp1d(self.spectrum.wavelength,self.spectrum.flux,\ bounds_error=False,fill_value="extrapolate") # Get AB spectrum spectrumAB = 1.0 / wavelength**2 # Get the filtered spectrum filteredSpectrum = TRANSMISSION(wavelength) * FLUX(wavelength) filteredSpectrumAB = TRANSMISSION(wavelength) * spectrumAB # Compute the integrated flux. fluxVega = romb(filteredSpectrum, dx=deltaWavelength) fluxAB = romb(filteredSpectrumAB, dx=deltaWavelength) return fluxAB, fluxVega
def poloidalBeta2(self): """Calculate plasma poloidal beta by integrating the thermal pressure and poloidal magnetic field pressure over the plasma volume. """ R = self.R Z = self.Z # Produce array of Bpol in (R,Z) B_polvals_2 = self.Br(R, Z)**2 + self.Bz(R, Z)**2 dR = R[1, 0] - R[0, 0] dZ = Z[0, 1] - Z[0, 0] dV = 2. * np.pi * R * dR * dZ # Normalised psi psi_norm = (self.psi() - self.psi_axis) / (self.psi_bndry - self.psi_axis) # Plasma pressure pressure = self.pressure(psi_norm) if self.mask is not None: # Only include points in the core dV *= self.mask pressure_integral = romb(romb(pressure * dV)) field_integral_pol = romb(romb(B_polvals_2 * dV)) return 2 * mu0 * pressure_integral / field_integral_pol return poloidal_beta
def total_variation_distance(samples1, samples2, dt): """ Romberg integration using samples of the density functions. Ensure that exactly 2 ** k + 1 evenly spaced samples are created.""" assert samples1.shape == samples2.shape, 'different sample lengths' result = 0.5 * integrate.romb(np.abs(samples1 - samples2), dt) while type(result) == np.ndarray: result = integrate.romb(result, dt) return result
def solve(self, profiles, Jtor=None, psi=None, psi_bndry=None): """ Calculate the plasma equilibrium given new profiles replacing the current equilibrium. This performs the linear Grad-Shafranov solve profiles - An object describing the plasma profiles. At minimum this must have methods: .Jtor(R, Z, psi) -> [nx, ny] .pprime(psinorm) .ffprime(psinorm) .pressure(psinorm) .fpol(psinorm) Jtor : 2D array If supplied, specifies the toroidal current at each (R,Z) point If not supplied, Jtor is calculated from profiles by finding O,X-points psi_bndry - Poloidal flux to use as the separatrix (plasma boundary) If not given then X-point locations are used. """ self._profiles = profiles if Jtor is None: # Calculate toroidal current density if psi is None: psi = self.psi() Jtor = profiles.Jtor(self.R, self.Z, psi, psi_bndry=psi_bndry) # Set plasma boundary # Note that the Equilibrium is passed to the boundary function # since the boundary may need to run the G-S solver (von Hagenow's method) self._applyBoundary(self, Jtor, self.plasma_psi) # Right hand side of G-S equation rhs = -mu0 * self.R * Jtor # Copy boundary conditions rhs[0, :] = self.plasma_psi[0, :] rhs[:, 0] = self.plasma_psi[:, 0] rhs[-1, :] = self.plasma_psi[-1, :] rhs[:, -1] = self.plasma_psi[:, -1] # Call elliptic solver plasma_psi = self._solver(self.plasma_psi, rhs) self._updatePlasmaPsi(plasma_psi) # Update plasma current dR = self.R[1, 0] - self.R[0, 0] dZ = self.Z[0, 1] - self.Z[0, 0] self._current = romb(romb(Jtor)) * dR * dZ
def clarray(aps, lmax, zarray, zromb=3, zwidth=None): """Calculate an array of C_l(z, z'). Parameters ---------- aps : function The angular power spectrum to calculate. lmax : integer Maximum l to calculate up to. zarray : array_like Array of z's to calculate at. zromb : integer The Romberg order for integrating over frequency samples. zwidth : scalar, optional Width of frequency channel to integrate over. If None (default), calculate from the separation of the first two bins. Returns ------- aps : np.ndarray[lmax+1, len(zarray), len(zarray)] Array of the C_l(z,z') values. """ if zromb == 0: return aps(np.arange(lmax+1)[:, np.newaxis, np.newaxis], zarray[np.newaxis, :, np.newaxis], zarray[np.newaxis, np.newaxis, :]) else: zsort = np.sort(zarray) zhalf = np.abs(zsort[1] - zsort[0]) / 2.0 if zwidth is None else zwidth / 2.0 zlen = zarray.size zint = 2**zromb + 1 zspace = 2.0*zhalf / 2**zromb za = (zarray[:, np.newaxis] + np.linspace(-zhalf, zhalf, zint)[np.newaxis, :]).flatten() lsections = np.array_split(np.arange(lmax+1), lmax / 50) cla = np.zeros((lmax+1, zlen, zlen), dtype=np.float64) for lsec in lsections: clt = aps(lsec[:, np.newaxis, np.newaxis], za[np.newaxis, :, np.newaxis], za[np.newaxis, np.newaxis, :]) clt = clt.reshape(-1, zlen, zint, zlen, zint) clt = si.romb(clt, dx=zspace, axis=4) clt = si.romb(clt, dx=zspace, axis=2) cla[lsec] = clt / (2*zhalf)**2 # Normalise return cla
def lnlike(H0, z, zerr, pb_gal, distmu, diststd, distnorm, H0_min, H0_max, z_min, z_max, zerr_use, cosmo_use, omegam=0.3): if ((zerr_use == False) & (cosmo_use == False)): distgal = (c / 1000.) * z / H0 like_gals = pb_gal * norm(distmu, diststd).pdf(distgal) elif ((zerr_use == False) & (cosmo_use == True)): cosmo = FlatLambdaCDM(H0=H0, Om0=omegam, Tcmb0=2.725) distgal = cosmo.luminosity_distance(z) #in Mpc like_gals = pb_gal * norm(distmu, diststd).pdf(distgal.value) elif ((zerr_use == True) & (cosmo_use == False)): ngals = z.shape[0] like_gals = np.zeros(ngals) z_s = np.arange(z_min, z_max, step=0.02) const = (c / 1000.) / H0 normalization = H0**3 for i in range(ngals): # Multiply the 2 Gaussians (redshift pdf and GW likelihood) with a change of variables into one Gaussian with mean Mu_new and std sigma_new #mu_new = (z[i]*diststd[i]*diststd[i]/(const*const)+ distmu[i]/const*zerr[i])/(diststd[i]*diststd[i]/(const*const)+zerr[i]*zerr[i]) #sigma_new = (diststd[i]*diststd[i]*zerr[i]*zerr[i]/(const*const)/(diststd[i]*diststd[i]/(const*const)+ zerr[i]*zerr[i]))**0.5 #like_gals[i]= pb_gal[i] * distnorm[i] * romb(gauss(mu_new, sigma_new, z_s) * z[i]*z[i], dx=0.02) like_gals[i] = pb_gal[i] * romb(gauss(z[i], zerr[i], z_s) * gauss( distmu[i], diststd[i], const * z_s), dx=0.02) else: ngals = z.shape[0] cosmo = FlatLambdaCDM(H0=H0, Om0=omegam) like_gals = np.zeros(ngals) z_s = np.arange(z_min, z_max, step=0.02) normalization = 1. for i in range(ngals): like_gals[i] = pb_gal[i] * romb(gauss(z[i], zerr[i], z_s) * gauss( distmu[i], diststd[i], cosmo.luminosity_distance(z[i]).value), dx=0.02) #normalization = H0**3 #lnlike_sum = np.log(np.sum(like_gals)/normalization) lnlike_sum = np.log(np.sum(like_gals)) return lnlike_sum
def calc_ip_numint(f, g, rs, method=0): """ f : continuum wave function g : L2 function which is not normalized """ fgs = np.array([f(r) * g(r) for r in rs]) ggs = np.array([g(r) * g(r) for r in rs]) if method == 0: int_fgs = integrate.simps(fgs, rs) int_ggs = integrate.simps(ggs, rs) else: int_fgs = integrate.romb(fgs, rs[1] - rs[0]) int_ggs = integrate.romb(ggs, rs[1] - rs[0]) return int_fgs / np.sqrt(int_ggs)
def freeBoundary(eq, Jtor, psi): """ Apply a free boundary condition using Green's functions Note: This method is inefficient because it requires an integral over the area of the domain for each point on the boundary. Inputs ------ eq Equilibrium object (not used) Jtor 2D array of toroidal current (not used) psi 2D array of psi values (modified by call) Returns ------- None """ # Get the (R,Z) coordinates from the Equilibrium object R = eq.R Z = eq.Z nx, ny = psi.shape dR = R[1, 0] - R[0, 0] dZ = Z[0, 1] - Z[0, 0] # List of indices on the boundary bndry_indices = concatenate( [ [(x, 0) for x in range(nx)], [(x, ny - 1) for x in range(nx)], [(0, y) for y in range(ny)], [(nx - 1, y) for y in range(ny)], ] ) for x, y in bndry_indices: # Calculate the response of the boundary point # to each cell in the plasma domain greenfunc = Greens(R, Z, R[x, y], Z[x, y]) # Prevent infinity/nan by removing (x,y) point greenfunc[x, y] = 0.0 # Integrate over the domain psi[x, y] = romb(romb(greenfunc * Jtor)) * dR * dZ
def calc_ip_numint(f, g, rs, method=0): """ f : continuum wave function g : L2 function which is not normalized """ fgs = np.array([f(r) * g(r) for r in rs]) ggs = np.array([g(r) * g(r) for r in rs]) if method == 0: int_fgs = integrate.simps(fgs, rs) int_ggs = integrate.simps(ggs, rs) else: int_fgs = integrate.romb(fgs, rs[1]-rs[0]) int_ggs = integrate.romb(ggs, rs[1]-rs[0]) return int_fgs / np.sqrt(int_ggs)
def plasmaVolume(self): """Calculate the volume of the plasma in m^3""" dR = self.R[1, 0] - self.R[0, 0] dZ = self.Z[0, 1] - self.Z[0, 0] # Volume element dV = 2. * pi * self.R * dR * dZ if self.mask is not None: # Only include points in the core dV *= self.mask # Integrate volume in 2D return romb(romb(dV))
def ricker_int_1d(p, u): """Equação a diferenças do tipo Ricker com difusão espacial: v[t+1] (x) = a * \int K(y-x) * v[t](y) * exp(-g * v[t](y)) dy Com K(y-x) := exp(-(y-x)^2 / s^2) v representa uma população de larvas. """ n = len(u) - 1 uu = np.zeros(u.size) for i in range(1, u.size): uu[i] = p['a'] * romb(u * np.exp(- p['g'] * u) * p['K'][n-i:-i], p['dx']) uu[0] = p['a'] * romb(u * np.exp(- p['g'] * u) * p['K'][n:], p['dx']) return [uu]
def integrate_f_jnjn(f, n, mean, delta, x_max): """Doesn't work for n=0, because we set f=0 for the first point. """ if n == 0: raise NotImplementedError() x_max = float(x_max) mean = float(mean) delta = float(delta) # Reduce x_max if envelope is significant. if delta == 0: envelop_width = 1000 * x_max else: envelop_width = 5 * (2 * np.pi / delta) x_max = min(x_max, 5 * envelop_width) x, ntuple, delta_tuple = sample_jnjn(n, mean, delta, x_max) # Envelope of a Gaussian with width of several oscillations. This # controls the oscillations out to high k. envelope = np.exp(-0.5*(x - n / mean)**2 / envelop_width**2) f_eval = np.empty_like(x) f_eval[0] = 0 f_eval[1:] = f(x[1:]) lower = np.s_[:ntuple[0] + 1] jnjn_lower = np.empty_like(x[lower]) jnjn_lower[0] = 0 jnjn_lower[1:] = jnjn(n, mean, delta, x[lower][1:]) integral = integrate.romb(f_eval[lower] * jnjn_lower, dx=delta_tuple[0]) if ntuple[1]: upper = np.s_[ntuple[0]:] jnjn_upper = approx_jnjn(n, mean, delta, x[upper]) integral += integrate.romb(f_eval[upper] * jnjn_upper * envelope[upper], dx=delta_tuple[1]) # XXX #print "n points:", ntuple #plt.plot(x[lower], jnjn_lower * f_eval[lower]) #plt.plot(x[upper], jnjn_upper * f_eval[upper]) #plt.plot(x[lower], jnjn_lower * f_eval[lower] * envelope[lower]) #plt.plot(x[upper], jnjn_upper * f_eval[upper] * envelope[upper]) #plt.show() return integral
def gt_fouriertrans(g_tau, tau, w_n): r"""Performs a forward fourier transform for the interacting Green function in which only the interval :math:`[0,\beta]` is required and output given into positive fermionic matsubara frequencies up to the given cutoff. Array sizes need not match between frequencies and times .. math:: G(i\omega_n) = \int_0^\beta G(\tau) e^{i\omega_n \tau} d\tau Parameters ---------- g_tau : real float array Imaginary time interacting Green function tau : real float array Imaginary time points w_n : real float array fermionic matsubara frequencies. Only use the positive ones beta : float Inverse temperature of the system Returns ------- out : complex ndarray Interacting Greens function in matsubara frequencies """ beta = tau[-1] power = np.exp(1j * dger(1, w_n, tau)) g_shape = g_tau.shape g_tau = g_tau.reshape(-1, 1, g_shape[-1]) * power return np.squeeze(romb(g_tau, dx=beta / (tau.size - 1)))
def diff_off_diag(p, u, v): """Equação a diferenças tipo logística com difusão espacial: u[t+1] (x) = a1 * v[t] * (1 - g1 * v[t]) v[t+1] (x) = a2 * \int K(y-x) * u[t](y) dy Com K(y-x) := exp(-(y-x)^2 / s^2) u representa uma população de moscas e v a quantidade de larvas. """ n = len(u) - 1 uu = p['a1'] * v * (1 - p['g1'] * v) vv = np.zeros(v.size) for i in range(1, v.size): vv[i] = p['a2'] * romb(u * p['K'][n-i:-i], p['dx']) vv[0] = p['a2'] * romb(u * p['K'][n:], p['dx']) return [uu, vv]
def _legacy_romberg_by_convotulion(self, leadfield, src, k=4): from _fast_reciprocal_reconstructor import ckESI_convolver r = max(src._nodes) n = 2**k + 1 X = np.linspace(src.x - r, src.x + r, n) Y = np.linspace(src.y - r, src.y + r, n) Z = np.linspace(src.z - r, src.z + r, n) convolver = ckESI_convolver([X, Y, Z], [X, Y, Z]) model_src = common.SphericalSplineSourceKCSD(0, 0, 0, src._nodes, src._coefficients, src.conductivity) LEADFIELD = np.full([n, n, n], np.nan) for i, x in enumerate(X): for j, y in enumerate(Y): for k, z in enumerate(Z): LEADFIELD[i, j, k] = leadfield(x, y, z) weights = si.romb(np.identity(n), dx=r / (n // 2)) POT_CORR = convolver.leadfield_to_base_potentials( LEADFIELD, model_src.csd, (weights, ) * 3) return POT_CORR[n // 2, n // 2, n // 2]
def kernel_fi(x_list, opt_h): kernel = _get_uni_kde(x_list, opt_h) low, high = _get_array_bounds(kernel, 0.0001, 0.9999) x = linspace(low, high, 2**11 + 1) probs = kernel.pdf(x) p_prime2 = gradient(probs, x)**2 return romb(p_prime2 / probs)
def gf_fourier(interface, ps, qs, energies, sampling_factor=None, return_ncalls=False): """Fourier-transformed energy-dependent GF.""" if sampling_factor is None: sampling_factor = 1 energies = np.array(energies) omega_middle = .5 * (min(energies.real) + max(energies.real)) de = (energies[1] - energies[0]).real ntimes = int(2 ** np.ceil(np.log2(sampling_factor * len(energies)))) + 1 times = np.linspace(0, sampling_factor / de, ntimes) # Enforce img part positive energies = energies.real + 1.j * abs(energies.imag) weights = np.exp(1.j * times[:, np.newaxis] * (energies + omega_middle)[np.newaxis, :]) if return_ncalls: tdgf, ncalls = gf_time(interface, ps, qs, times, energy_shift=omega_middle, return_ncalls=True) else: tdgf = gf_time(interface, ps, qs, times, energy_shift=omega_middle, return_ncalls=False) integrand = tdgf[..., np.newaxis] * weights[(np.newaxis,) * (tdgf.ndim-1) + (slice(None), slice(None))] result = integrate.romb( integrand, dx=times[1] - times[0], axis=-2, ) if return_ncalls: return result, ncalls else: return result
def calc_rate_eps(eps, xs, gamma, field, z=0, cdf=False): """ Calculate the interaction rate for given tabulated cross sections against an isotropic photon background. The tabulated cross sections need to be of length n = 2^i + 1 and the tabulation points log-linearly spaced. eps : tabulated photon energies [J] in nucleus rest frame xs : tabulated cross sections [m^2] gamma : (array of) nucleus Lorentz factors field : photon background, see photonField.py z : redshift cdf : calculate cumulative differential rate Returns : interaction rate 1/lambda(gamma) [1/Mpc] or cumulative differential rate d(1/lambda)/d(s_kin) [1/Mpc/J^2] """ F = cumtrapz(x=eps, y=eps * xs, initial=0) n = field.getDensity(np.outer(1. / (2 * gamma), eps), z) if cdf: y = n * F / eps**2 return cumtrapz(x=eps, y=y, initial=0) / np.expand_dims(gamma, -1) * Mpc else: y = n * F / eps dx = mean_log_spacing(eps) return romb(y, dx=dx) / gamma * Mpc
def integrator_linspace(y, dx=1, method="simps", axis=-1): """ Integrate y using samples along the given axis with spacing dx. method is in ['simps', 'trapz', 'romb']. Note that romb requires len(y) = 2**k + 1. Example: >>> nx = 2**8+1 >>> x = np.linspace(0, np.pi, nx) >>> dx = np.pi/(nx-1) >>> y = np.sin(x) >>> for method in ["simps", "trapz", "romb"]: print(integrator_linspace(y, dx=dx, method=method)) 2.00000000025 1.99997490024 2.0 """ from scipy.integrate import simps, trapz, romb if method == "simps": return simps(y, x=None, dx=dx, axis=axis, even='avg') elif method == "trapz": return trapz(y, x=None, dx=dx, axis=axis) elif method == "romb": return romb(y, dx=dx, axis=axis, show=False) else: raise ValueError("Wrong method: %s" % method)
def verification_total_mass(m,x,y): ############################################################ # # This function performs the surface integral of the density # profile. Inputs are: the total dust mass (the constraint) in # solar masses, the array of distances (in AU) and the array # with the surface density profile (in g/cm^2). The # output is the error between the total dust mass generated # by the density profile and the actual value. Therefore, # if the density profile reproduces exactly the value of # the constraint, the returned value will be zero. # # IMPORTANT: the number of points of the density profile array # (N) can not be arbitrary. It should respect the rule: N=2^k+1 # with k integer. Also, the values of the independent variable # i.e. the radial distance, must be equally spaced. # ############################################################ x_integrate=x*cte.au.value*100 y_integrate=x_integrate*y dx=x_integrate[1]-x_integrate[0] dust_mass_integrated=2*np.pi*romb(y_integrate,dx)/(cte.M_sun.value*1000) #dust_mass_integrated=romb(y_integrate,dx)/(cte.M_sun.value*1000) error=abs(m-dust_mass_integrated) return error
def MassVariance(self, M): """ Finds the Mass Variance of R using the top-hat window function. Input: R: the radius of the top-hat function (single number). Output: sigma_squared: the mass variance. """ # Calculate the integrand of the function. Note that the power spectrum and k values must be #'un-logged' before use, and we multiply by k because our steps are in logk. integrand = np.exp(self.k_extended)**3 * np.exp( self.power_spectrum) * self.TopHat_WindowFunction(M) # Perform the integration using romberg integration, and multiply be the pre-factors. sigma_squared = (0.5 / np.pi**2) * intg.romb(integrand, dx=self.steps) # Multiply by the growth factor for the redshifts involved. dist = Distances(camb_config.omega_lambda, camb_config.omega_baryon + camb_config.omega_cdm, 0.0, H_0=camb_config.hubble) growth = dist.GrowthFactor(self.z)**2 sigma_squared = sigma_squared * growth return sigma_squared
def Dplus(self, redshifts): """ Finds the factor D+(a), from Lukic et. al. 2007, eq. 8. Uses romberg integration with a suitable step-size. Input: z: redshift. Output: dplus: the factor. """ if type(redshifts) is type(0.4): redshifts = [redshifts] dplus = np.zeros_like(redshifts) for i, z in enumerate(redshifts): step_size = self.StepSize(0.0000001, self.ScaleFactor(z)) a_vector = np.arange(0.0000001, self.ScaleFactor(z), step_size) integrand = 1.0 / (a_vector * self.HubbleFunction(self.zofa(a_vector)))**3 integral = intg.romb(integrand, dx=step_size) dplus[i] = 5.0 * self.omega_mass * self.HubbleFunction( z) * integral / 2.0 return dplus
def dlnsdlnM(self, M): """ Uses a top-hat window function to calculate |dlnsigma/dlnM| at a given radius. Input: R: the radius of the top-hat function. Output: integral: the derivatiave of log sigma with respect to log Mass. """ R = self.Radius(M) # define the vector g = kR g = np.exp(self.k_extended) * R # Find the mass variance. sigma = np.sqrt(self.MassVariance(M)) # Define the derivative of the window function squared. window = (np.sin(g) - g * np.cos(g)) * (np.sin(g) * (1 - 3.0 / (g**2)) + 3.0 * np.cos(g) / g) # Compile into the integrand. integrand = (np.exp(self.power_spectrum) / np.exp(self.k_extended)) * window # Integrate using romberg integration and multiply by pre-factors. integral = (3.0 / (2.0 * sigma**2 * np.pi**2 * R**4)) * intg.romb( integrand, dx=self.steps) return integral
def dlnsdlnM(self,M): """ Uses a top-hat window function to calculate |dlnsigma/dlnM| at a given radius. Input: R: the radius of the top-hat function. Output: integral: the derivatiave of log sigma with respect to log Mass. """ R = self.Radius(M) # define the vector g = kR g = np.exp(self.k_extended)*R # Find the mass variance. sigma = np.sqrt(self.MassVariance(M)) # Define the derivative of the window function squared. window = (np.sin(g)-g*np.cos(g))*(np.sin(g)*(1-3.0/(g**2))+3.0*np.cos(g)/g) # Compile into the integrand. integrand = (np.exp(self.power_spectrum)/np.exp(self.k_extended))*window # Integrate using romberg integration and multiply by pre-factors. integral =(3.0/(2.0*sigma**2*np.pi**2*R**4))*intg.romb(integrand,dx=self.steps) return integral
def residuals( knotvals: np.ndarray, unfolded_cameras: List[Dataset], ) -> np.ndarray: symmetric_emissivity, asymmetry_parameter = knotvals_to_xarray(knotvals) estimate = EmissivityProfile( symmetric_emissivity, asymmetry_parameter, flux_coords ) start = 0 resid = np.empty(sum(c.attrs["nlos"] for c in unfolded_cameras)) self.integral = [] for c in unfolded_cameras: end = start + c.attrs["nlos"] rho, R = c.indica.convert_coords(rho_maj_rad) rho_min, x2 = c.indica.convert_coords(c.attrs["impact_parameters"]) emissivity_vals = estimate.evaluate(rho, R, R_0=c.coords["R_0"]) axis = emissivity_vals.dims.index(c.attrs["transform"].x2_name) integral = romb(emissivity_vals, c.attrs["dl"], axis) resid[start:end] = ((c.camera - integral) / c.weights)[ c["has_data"] ].data start = end x1_name = c.attrs["transform"].x1_name self.integral.append( DataArray(integral, coords=[(x1_name, c.coords[x1_name])]) ) assert np.all(np.isfinite(resid)) return resid
def _bhattacharyya_cont(df_1, df_2, var_list, continuous_integration_points): """ Utility functino for calculating the Bhattacharyya distance between continuous columns in two DataFrames :param df_1: First DataFrame :param df_2: Second DataFrame :param var_list: list - continuous variables to be included in the calculation, all variables must match a column in each DataFrame :return: Pandas Series with the distance as values and column names as indices """ assert (all([issubdtype(t, number) for t in df_1[var_list].dtypes]) and all([issubdtype(t, number) for t in df_2[var_list].dtypes])),\ 'All continuous variables must be numerical' assert (log2(continuous_integration_points-1) % 1 == 0),\ 'The number of integration points must be 2**n+1 where n is a non-negative integer' # Compute the Gaussian KDEs for all continuous columns in both DataFrames kernels_1 = [gaussian_kde(df_1[v].get_values()) for v in var_list] kernels_2 = [gaussian_kde(df_2[v].get_values()) for v in var_list] # Define low and high points for each integration range, i.e. the end points of the two distributions low_points = [min(df_1[v].min(), df_2[v].min()) for v in var_list] high_points = [max(df_1[v].max(), df_2[v].max()) for v in var_list] # Calculate integration points positions = [mgrid[lp:hp:complex(0, continuous_integration_points)] for lp, hp in zip(low_points, high_points)] # Calculate the KDE values at each integration point kdes_1 = [k(p) for k, p in zip(kernels_1, positions)] kdes_2 = [k(p) for k, p in zip(kernels_2, positions)] # Return a pandas Series with the computed distances return Series([-log(romb(sqrt(k1*k2), dx=(p[1:]-p[:-1]).mean())) for k1, k2, p in zip(kdes_1, kdes_2, positions)], index=var_list)
def spectralWeight(self, limits=None): """Calculates the spectral weight of the model. If an energy window is give, a partial spectral weight is returned. Parameter: limits -- A tuple indicating beginning and end where to calculate the partial spectral weight of the model. Returns: The calculated dielectric function. """ _sw = 0.0 if not limits: for oscillator in self.__oscillators: _sw += oscillator.spectralWeight else: # Using Romberg: See http://young.physics.ucsc.edu/242/romberg.pdf interval = limits[1]-limits[0] # Finding minimal k for a smaller than 0.02 integration step k = ceil(log(interval/0.02-1)/log(2)) # Determining final step size dx = interval/(2.0**k) # Create a 2**k+1 equally spaced sample x = np.linspace(limits[0], limits[1], 2**k+1) _sw = romb(np.imag(self.dielectricFunction(x)), dx) return _sw
def romberg(self, leadfield, src, k=4): r = max(src._nodes) n = 2**k + 1 dxyz = r**3 / 2**(3 * k - 3) X = np.linspace(src.x - r, src.x + r, n) Y = np.linspace(src.y - r, src.y + r, n) Z = np.linspace(src.z - r, src.z + r, n) CSD = src.csd(X.reshape(-1, 1, 1), Y.reshape(1, -1, 1), Z.reshape(1, 1, -1)) return dxyz * si.romb([ si.romb([ si.romb([leadfield(xx, yy, zz) for zz in Z] * CSD_XY) for yy, CSD_XY in zip(Y, CSD_X) ]) for xx, CSD_X in zip(X, CSD) ])
def computeSigma8(self, h0=1.0, verbose=False): dk = self.k[1] - self.k[0] values = self.pk( self.k) * (self.getFourierWindow(8.0, h0=h0) * self.k)**2 sigma8 = romb(values, dx=dk, show=verbose) / dk sigma8 /= 2.0 * (Pi**2) return np.sqrt(sigma8)
def calc_rate_s(s_kin, xs, E, field, z=0, cdf=False): """ Calculate the interaction rate for given tabulated cross sections against an isotropic photon background. The tabulated cross sections need to be of length n = 2^i + 1 and the tabulation points log-linearly spaced. s_kin : tabulated (s - m**2) for cross sections [J^2] xs : tabulated cross sections [m^2] E : (array of) cosmic ray energies [J] field : photon background, see photonField.py z : redshift cdf : calculate cumulative differential rate Returns : interaction rate 1/lambda(gamma) [1/Mpc] or cumulative differential rate d(1/lambda)/d(s_kin) [1/Mpc/J^2] """ F = cumtrapz(x=s_kin, y=s_kin * xs, initial=0) n = field.getDensity(np.outer(1. / (4 * E), s_kin), z) if cdf: y = n * F / s_kin**2 return cumtrapz(x=s_kin, y=y, initial=0) / 2 / np.expand_dims(E, -1) * Mpc else: y = n * F / s_kin ds = mean_log_spacing(s_kin) return romb(y, dx=ds) / 2 / E * Mpc
def integral_grid_d_3_xi(self, FUN, element=1, component=None): if element == 'stress': element = self.ELEMENT_stress[:, :, :, component[0] - 1, component[1] - 1] if FUN.ndim == 3: return 8*romb(romb(romb(FUN*element, \ dx = self.dx, axis = 0), dx = self.dy, axis = 0), dx = self.dz, axis = 0) elif FUN.ndim == 4: return 8*romb(romb(romb(FUN*element[:,:,:,None], \ dx = self.dx, axis = 0), dx = self.dy, axis = 0), dx = self.dz, axis = 0) elif FUN.ndim == 5: return 8*romb(romb(romb(FUN*element[:,:,:,None,None], \ dx = self.dx, axis = 0), dx = self.dy, axis = 0), dx = self.dz, axis = 0)
def _integration_weights(cls, X): # Regular `X` assumed dx = cls._d(X) n = len(X) if 2**int(np.log2(n - 1)) == n - 1: return romb(np.eye(n), dx=dx) return np.full(n, dx)
def kernel_fi(x_list, eps): opt_h = find_opt_h(x_list, eps) kernel = get_uni_kde(x_list, opt_h) low, high = get_array_bounds(kernel, 0.0001, 0.9999) x = np.linspace(low, high, 2 ** 11 + 1) probs = kernel.pdf(x) p_prime2 = np.gradient(probs, x) ** 2 return romb(p_prime2 / probs)
def _compute_std_romberg(self, psi, p_sep, xmin, xmax): ''' Compute the variance of the distribution function psi from xmin to xmax along the contours p_sep using numerical integration methods. ''' x_arr = np.linspace(xmin, xmax, 257) dx = x_arr[1] - x_arr[0] Q, V = 0, 0 for x in x_arr: y = np.linspace(0, p_sep(x), 257) dy = y[1] - y[0] z = psi(x, y) Q += romb(z, dy) z = x**2 * psi(x, y) V += romb(z, dy) Q *= dx V *= dx return np.sqrt(V/Q)
def test_romb_gh_3731(self): # Check that romb makes maximal use of data points x = np.arange(2**4+1) y = np.cos(0.2*x) val = romb(y) val2, err = quad(lambda x: np.cos(0.2*x), x.min(), x.max()) assert_allclose(val, val2, rtol=1e-8, atol=0) # should be equal to romb with 2**k+1 samples with suppress_warnings() as sup: sup.filter(AccuracyWarning, "divmax .4. exceeded") val3 = romberg(lambda x: np.cos(0.2*x), x.min(), x.max(), divmax=4) assert_allclose(val, val3, rtol=1e-12, atol=0)
def test_romb_gh_3731(self): # Check that romb makes maximal use of data points x = np.arange(2 ** 4 + 1) y = np.cos(0.2 * x) val = romb(y) val2, err = quad(lambda x: np.cos(0.2 * x), x.min(), x.max()) assert_allclose(val, val2, rtol=1e-8, atol=0) # should be equal to romb with 2**k+1 samples with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=AccuracyWarning) val3 = romberg(lambda x: np.cos(0.2 * x), x.min(), x.max(), divmax=4) assert_allclose(val, val3, rtol=1e-12, atol=0)
def Cmp_XC_Energy(Nc,MM,LL,mumesh,Ximesh,in12,index,R0,FX=1.0,FC=1.0): "Computes XC energy within LDA" code1=""" #line 117 "LDA.py" double rho=0.0; for (int i=0; i<an12.extent(0); i++){ int i1 = andex(an12(i,0)); int i2 = andex(an12(i,1)); rho += MM(i1,ix)*LL(i1,ir)*Nc(i)*MM(i2,ix)*LL(i2,ir); } return_val = rho/(2*M_PI*R0*R0*R0/8); """ exc = ExchangeCorrelation() Exc = zeros((len(mumesh),len(Ximesh)),dtype=float) an12 = array(in12) andex = array(index) for ix,eta in enumerate(mumesh): for ir,xi in enumerate(Ximesh): rho = weave.inline(code1, ['ir', 'ix', 'Nc','an12','andex','MM','LL','R0'], type_converters=weave.converters.blitz, compiler = 'gcc') if rho<0.0: print 'WARNING: rho<0 for ', eta, xi, 'rho=', rho #print 'Nc=', Nc #dsum=0.0 #for i,(i1,i2) in enumerate(in12): # print i1, i2, MM[i1,ix]*LL[i1,ir]*Nc[i]*MM[i2,ix]*LL[i2,ir], dsum # dsum += MM[i1,ix]*LL[i1,ir]*Nc[i]*MM[i2,ix]*LL[i2,ir] rho=1e-300 rs = pow(3/(4*pi*rho),1/3.) Exc[ix,ir] = (2*exc.Ex(rs)*rho*FX + 2*exc.Ec(rs)*rho*FC)*(xi**2-eta**2)*(2*pi*R0**3/8) Ene = zeros(len(mumesh),dtype=float) for ix,eta in enumerate(mumesh): Ene[ix] = integrate.romb(Exc[ix,:]*(Ximesh-1.),dhXi) return integrate.romb(Ene,mumesh[1]-mumesh[0])
def kpc2pix(H, Om, z0): ''' Converts physical distances in kiloparsec to Chandra pixels at redshift z0 H = Hubble constant in km/sec/Mpc Om = total matter density ''' N = 64 # Number of evaluation points c = 3e5 # speed of light in km/s z = linspace(0, z0, N+1) E = sqrt( Om*(1+z)**3 + 1-Om ) dC = 1e3 * c/H * romb(1/E, 1.*z0/N) # Comoving distance in Mpc dA = dC / (1+z0) # Angular diameter distance rad2arcsec = 180*3600/pi px2arcsec = 0.492 return 1/dA * rad2arcsec / px2arcsec #kpc2px
def cmp_MPM(Ny, maxm,maxl, ist, ak, Modd): Xx = linspace(-1,1,Ny) MPM = zeros((len(ist),maxl+1),dtype=float) MPxM = zeros((len(ist),maxl+1),dtype=float) for i,(i1,i2) in enumerate(ist): (R1,Ene1,m1,p1,A1) = Sol[i1] (R2,Ene2,m2,p2,A2) = Sol[i2] print 'i1=', i1, 'i2=', i2, 'm1=', m1, 'm2=', m2 #, MPM,MPxM m = abs(m1-m2) Plm_all = array([special.lpmn(maxm,maxl,x)[0] for x in Xx]) MM = array([Mm(x,m1,p1,ak[i1]) * Mm(x,m2,p2,ak[i2]) for x in Xx]) Plm = transpose(Plm_all[:,m]) for il in range(m,maxl+1): odd = (Modd[i1]+Modd[i2]+il+m)%2 if not odd: # If the function is odd, we do not calculate! MMP = MM*Plm[il,:] MMPx = MMP * Xx**2 MPM [i,il] = integrate.romb(MMP, Xx[1]-Xx[0]) MPxM[i,il] = integrate.romb(MMPx,Xx[1]-Xx[0]) return (MPM,MPxM)
def test_marginalization(): # Integrating out one of the variables of a 2D Gaussian should # yield a 1D Gaussian mean = np.array([2.5, 3.5]) cov = np.array([[.5, 0.2], [0.2, .6]]) n = 2 ** 8 + 1 # Number of samples delta = 6 / (n - 1) # Grid spacing v = np.linspace(0, 6, n) xv, yv = np.meshgrid(v, v) pos = np.empty((n, n, 2)) pos[:, :, 0] = xv pos[:, :, 1] = yv pdf = multivariate_normal.pdf(pos, mean, cov) # Marginalize over x and y axis margin_x = romb(pdf, delta, axis=0) margin_y = romb(pdf, delta, axis=1) # Compare with standard normal distribution gauss_x = norm.pdf(v, loc=mean[0], scale=cov[0, 0] ** 0.5) gauss_y = norm.pdf(v, loc=mean[1], scale=cov[1, 1] ** 0.5) assert_allclose(margin_x, gauss_x, rtol=1e-2, atol=1e-2) assert_allclose(margin_y, gauss_y, rtol=1e-2, atol=1e-2)
def calc_rate_eps(eps, xs, gamma, field, z=0): """ Calculate the interaction rate for given tabulated cross sections against an isotropic photon background. The tabulated cross sections need to be of length n = 2^i + 1 and the tabulation points log-linearly spaced. eps : tabulated photon energies [J] in nucleus rest frame xs : tabulated cross sections [m^2] gamma : (array of) nucleus Lorentz factors field : photon background, see photonField.py Returns : inverse mean free path [1/Mpc] """ F = integrate.cumtrapz(x=eps, y=eps*xs, initial=0) n = field.getDensity(np.outer(1./(2*gamma), eps), z) dx = np.mean(np.diff(np.log(eps))) # value of log-spacing return integrate.romb(n * F / eps, dx=dx) / gamma * Mpc
def local_term(ells, chi, delta, flat=False): out = [] chi = float(chi) delta = float(delta) for ell in ells: ell = int(ell) p_k_interp = matter_power.p_k_interp(chi) if flat: if (ell/chi) > matter_power.K_MAX: out.append(0.) continue # Maximum k_par. k_max = np.sqrt(max(matter_power.K_MAX**2 - (ell/chi)**2, 0)) # Reduce x_max if envelope is significant. if delta == 0: envelop_width = 1000 * k_max else: envelop_width = 5 * (2 * np.pi / delta) k_max = min(k_max, 5 * envelop_width) nk = sph_bessel.pow_2_gt(k_max * delta * 5) + 1 k = np.linspace(0, k_max, nk, endpoint=True) delta_k = k_max / (nk - 1) # Envelope of a Gaussian with width of several oscillations. This # controls the oscillations out to high k. envelope = np.exp(-0.5*k**2 / envelop_width**2) p_k_local = p_k_interp(np.sqrt((ell/chi)**2 + k**2)) p_k_local *= envelope # Fourier factor. p_k_local *= np.cos(k * delta) I1 = integrate.romb(p_k_local, dx=delta_k) I1 /= np.pi * chi**2 else: p_k = lambda k: k**2 * p_k_interp(k) I1 = sph_bessel.integrate_f_jnjn(p_k, ell, chi, delta, matter_power.K_MAX) * (2 / np.pi) out.append(I1) return out
def normalize(E, V, interval): """ Use the Romberg method of integration from the SciPy module to normalize the wave function. """ min,max,steps = interval k = np.ceil(np.log2(steps - 1)) int_interval = (min,max,np.exp2(k)+1) xpoints,ypoints = ode.solve(f_eq = schrod_eq, dep_i = (0,1), interval = int_interval, order = 4, return_points = True, V = V, E = E ) ypoints = np.power(ypoints[0,:],2) # strip out phi values and square dx = (max-min)/(np.exp2(k)) A2 = integrate.romb(ypoints,dx) return 1/np.sqrt(A2)
def d_plus(z, omegam, omegak, omegav): """ Finds the factor D+(a), from Lukic et. al. 2007, eq. 8. Uses romberg integration with a suitable step-size. Input: z: redshift. Output: dplus: the factor. """ stepsize = step_size(0.0000001, a_from_z(z)) a_vector = np.arange(0.0000001, a_from_z(z), stepsize) integrand = 1.0 / (a_vector * hubble_z(z_from_a(a_vector), omegam, omegak, omegav)) ** 3 integral = intg.romb(integrand, dx=stepsize) dplus = 5.0 * omegam * hubble_z(z, omegam, omegak, omegav) * integral / 2.0 return dplus
def invMFP_fast(eps, xs, gamma, field): """ Calculate the inverse mean free path for given tabulated cross sections against an isotropic photon background: Fully vectorized version using Romberg integration. The tabulated cross sections need to be of length n = 2^i + 1 and the tabulation points log-linearly spaced eps : photon energies [J] in nucleus rest frame xs : cross sections [m^2] gamma : (array of) nucleus Lorentz factors field : photon background, see photonField.py Returns : inverse mean free path [1/Mpc] """ F = integrate.cumtrapz(x=eps, y=eps*xs, initial=0) / eps n = field.getDensity( np.outer(1 / (2 * gamma), eps) ) dx = np.mean(np.diff(np.log(eps))) # average log-spacing return integrate.romb(n * F, dx=dx) * Mpc / gamma
def rate(s_kin, xs, E,field): """ Calculate interaction rate against an isotropic photon background for given tabulated cross sections. 1/lambda = 1/(2E) * \int n((smax-m^2)/(4E)) / (smax-m^2) F(smax-m^2) dln(smax-m^2) F(smax-m^2) = \int_{smin-m^2}^{smax-m^2} sigma(s) (s - m^2) d(s-m^2) s = 2E eps (1 - cos(theta)) + m^2 smax = 4E*eps + m^2 smin = m^2 field : n(eps) photon background, see photonField.py s_kin : tabulated (s - m**2) for cross sections [J^2], size n=2^i+1, log-spaced xs : tabulated cross sections [m^2] E : (array of) cosmic ray energies [J] Returns : interaction rate [1/Mpc] """ F = integrate.cumtrapz(x=s_kin, y=(s_kin)*xs, initial=0) n = field.getDensity(np.outer(1./(4*E), s_kin)) ds = np.mean(np.diff(np.log(s_kin))) # value of log-spacing return integrate.romb(n * F / (s_kin), dx=ds) / 2 / E * Mpc
def integrate_f_jnjn_brute(f, n, mean, delta, x_max): x_max = float(x_max) mean = float(mean) delta = float(delta) x_min = n / mean / 2 npoints = 4 * mean * (x_max - x_min) npoints = pow_2_gt(npoints) delta_x = (x_max - x_min) / npoints x = np.arange(npoints + 1, dtype=float) * delta_x + x_min integrand = np.empty_like(x) integrand[0] = 0 integrand[0:] = f(x[0:]) integrand *= jnjn(n, mean, delta, x) # XXX #print "brute n points:", npoints #plt.plot(x, integrand) return integrate.romb(integrand, dx=delta_x)
def calc_rate_s(s_kin, xs, E, field): """ Calculate the interaction rate for given tabulated cross sections against an isotropic photon background. The tabulated cross sections need to be of length n = 2^i + 1 and the tabulation points log-linearly spaced. 1/lambda = 1/(2E) * \int n((smax-m^2)/(4E)) / (smax-m^2) F(smax-m^2) dln(smax-m^2) F(smax-m^2) = \int_{smin-m^2}^{smax-m^2} sigma(s) (s - m^2) d(s-m^2) s = 2E eps (1 - cos(theta)) + m^2 smax = 4*E*eps + m^2 smin = m^2 s_kin : tabulated (s - m**2) for cross sections [J^2] xs : tabulated cross sections [m^2] E : (array of) cosmic ray energies [J] field : photon background, see photonField.py Returns : interaction rate [1/Mpc] """ F = integrate.cumtrapz(x=s_kin, y=s_kin*xs, initial=0) n = field.getDensity(np.outer(1./(4*E), s_kin)) ds = np.mean(np.diff(np.log(s_kin))) # value of log-spacing return integrate.romb(n * F / s_kin, dx=ds) / 2 / E * Mpc
def MassVariance(self,M): """ Finds the Mass Variance of R using the top-hat window function. Input: R: the radius of the top-hat function (single number). Output: sigma_squared: the mass variance. """ # Calculate the integrand of the function. Note that the power spectrum and k values must be #'un-logged' before use, and we multiply by k because our steps are in logk. integrand = np.exp(self.k_extended)**3*np.exp(self.power_spectrum)*self.TopHat_WindowFunction(M) # Perform the integration using romberg integration, and multiply be the pre-factors. sigma_squared = (0.5/np.pi**2)*intg.romb(integrand,dx = self.steps) # Multiply by the growth factor for the redshifts involved. dist = Distances(camb_config.omega_lambda, camb_config.omega_baryon+camb_config.omega_cdm,0.0,H_0 = camb_config.hubble) growth = dist.GrowthFactor(self.z)**2 sigma_squared = sigma_squared*growth return sigma_squared
def Dplus(self,redshifts): """ Finds the factor D+(a), from Lukic et. al. 2007, eq. 8. Uses romberg integration with a suitable step-size. Input: z: redshift. Output: dplus: the factor. """ if type(redshifts) is type (0.4): redshifts = [redshifts] dplus = np.zeros_like(redshifts) for i,z in enumerate(redshifts): step_size = self.StepSize(0.0000001,self.ScaleFactor(z)) a_vector = np.arange(0.0000001,self.ScaleFactor(z),step_size) integrand = 1.0/(a_vector*self.HubbleFunction(self.zofa(a_vector)))**3 integral = intg.romb(integrand,dx=step_size) dplus[i] = 5.0*self.omega_mass*self.HubbleFunction(z)*integral/2.0 return dplus
def _cvar(self,upper=0.05,samples=64,lower=0.00001): interval = (upper - lower) / float(samples) ppfs = self.dist.ppf(numpy.arange(lower, upper+interval, interval)) result = integrate.romb(ppfs, dx=interval) return result
A2 = np.zeros(shape = (len(Ls),len(ns))) G = np.zeros(shape = (len(Ls),len(thetas))) Tau = np.zeros(shape = (len(Ls),len(thetas))) a = Aiz(eiz_x,eiz_z,eiz_w) delta_par = Delta_par(eiz_z,eiz_w) delta_prp = Delta_prp(eiz_x,eiz_w) # Integrand, A0(n=0) and A2(n=0) terms f0_term0 = U*U*U * np.exp(-2.* U)\ *2.*(1.+3.*a[0])*(1.+3.*a[0]) #*((eiz_z[0]-eiz_w[0])/(eiz_z[0]-eiz_w[0]))\ f2_term0 = U*U*U * np.exp(-2.* U)\ *(1.-a[0])*(1.-a[0]) #*((eiz_z[0]-eiz_w[0])/(eiz_z[0]-eiz_w[0]))\ Ft0_term0 = romb(f0_term0) #Ft0_term0 = np.sum(f0_term0) Ft2_term0 = romb(f2_term0) #Ft2_term0 = np.sum(f2_term0) # Calculate 1 \geq n \leq 500 terms for i,L in enumerate(Ls): print 'Computing A for separation number %3.0f of %3.0f'%(i, len(Ls)) for j,n in enumerate(ns): p[i,j] = Pn(eiz_w[j],zs[j],L) # Integrand A0 f0 = T*np.exp(-2.*p[i,j]*np.sqrt(T*T+1.))/(T*T+1.)\ *2.*((delta_par[j]+6.*delta_prp[j])*(delta_par[j]+6.*delta_prp[j])*T*T*T*T\ +2.*(delta_par[j]*delta_par[j]+4.*delta_prp[j]*delta_par[j]+4.*delta_prp[j]*delta_par[j]+12.*delta_prp[j]*delta_prp[j])*T*T \ + 2.*(delta_par[j]+2.*delta_prp[j])*(delta_par[j]+2.*delta_prp[j])) #*((eiz_z[j]-eiz_w[j])/(eiz_z[j]-eiz_w[j]))\
def RSDband_covariance_PP(self, l1, l2, logscale = False): """ Calculate power spectrum covariance matrix C_{l1,l2} = < P_l1 P_l2 > - < P_l1 >< P_l2 > Parameter --------- l1,l2: mode 0,2,4 """ from scipy.integrate import quad,simps from numpy import zeros, sqrt, pi, exp import cmath I = cmath.sqrt(-1) klist = self.klist kcenter = self.kcenter skcenter = self.skcenter mulist = self.mulist dk = self.kmax - self.kmin #dlnk = self.dlnk #sdlnk = self.sdlnk sdk = self.skmax - self.skmin matterpower = self.RealPowerBand s = self.s b = self.b f = self.f Vs = self.Vs nn = self.nn dmu = self.dmu # FirstTerm + SecondTerm matrix1, matrix2 = np.mgrid[0:len(mulist),0:self.subN] mumatrix = self.mulist[matrix1] Le_matrix1 = Ll(l1,mumatrix) Le_matrix2 = Ll(l2,mumatrix) #Vi = 4 * pi * kcenter**2 * dk + 1./3 * pi * (dk)**3 Vi = 4./3 * pi * ( self.kmax**3 - self.kmin**3 ) Const_alpha = (2*l1 + 1.) * (2*l2 + 1.) * (2*pi)**3 /Vs resultlist1 = [] resultlist2 = [] for i in range(len(kcenter)): k = skcenter[i*self.subN : i*self.subN+self.subN] Pm = matterpower[i*self.subN : i*self.subN+self.subN] kmatrix = k[matrix2] Dmatrix = np.exp(- kmatrix**2 * mumatrix**2 * self.s**2) #FOG matrix R = (self.b + self.f * mumatrix**2)**2 * Dmatrix Rintegral3 = romb( R**2 * Le_matrix1 * Le_matrix2, dx = dmu, axis=0 ) Rintegral2 = romb( R * Le_matrix1 * Le_matrix2, dx = dmu, axis=0 ) result1 = romb( 4 * pi * k**2* Pm**2 * Rintegral3, dx = self.sdk) result2 = romb( 4 * pi * k**2 * Pm * Rintegral2, dx = self.sdk) resultlist1.append(result1) resultlist2.append(result2) FirstTerm = Const_alpha * np.array(resultlist1) /Vi**2 SecondTerm = Const_alpha * 2./nn * np.array(resultlist2) /Vi**2 # LastTerm if l1 == l2: LastTerm = (2*l1 + 1.) * 2. * (2 * pi)**3/Vs/nn**2 /Vi else: LastTerm = 0. Total = FirstTerm + SecondTerm + LastTerm covariance_mutipole_PP = np.zeros((len(kcenter),len(kcenter))) np.fill_diagonal(covariance_mutipole_PP,Total) #print 'covariance_PP {:>1.0f}{:>1.0f} is finished'.format(l1,l2) sys.stdout.write('.') return covariance_mutipole_PP
def test_romb(self): assert_equal(romb(np.arange(17)), 128)
def Pn(e,zn,l): return np.sqrt(e)*zn*l*(1./c) a = Aiz(eiz_x,eiz_z,eiz_w) delta = Delta(eiz_z,eiz_w) # Calculate N=0 term # Integrand f_term0 = (1./(Y0*np.sqrt(1.0 - (1./Y0)))) *U*U*U*U\ *np.exp(-2.* Y0 *U)\ *((eiz_z[0]-eiz_w[0])/(eiz_z[0]-eiz_w[0]))\ *(2.*(1. + 3.*a[0])*(1. + 3.*a[0])\ +(1.-a[0])*(1.-a[0])) # Double Integral Ft_term0 = romb(f_term0, axis = 1) Fty_term0 = romb(Ft_term0, axis = 0) # Calculate 1 < N < 500 terms for i,L in enumerate(Ls): print 'Computing A for separation number %3.0f of %3.0f'%(i, len(Ls)) for j,n in enumerate(ns): p[i,j] = Pn(eiz_w[j],zs[j],L) # Integrand f = (1./(Y*np.sqrt(1.0 - (1./Y))))\ * np.exp(-2.*Y*p[i,j]*np.sqrt(T*T+1.))\ * (T / np.sqrt(T*T + 1.))\ *((eiz_z[j]-eiz_w[j])/(eiz_z[j]-eiz_w[j]))\ * (2. * (1. + 3.*a[j]) * (1. + 3.*a[j]) * T*T*T*T\ + 4. * (1. + 2.*a[j] + 2.*a[j] + 3.*a[j] * a[j]) *T*T\ + 4.*(1.+a[j])*(1.+a[j])\