Example #1
0
    def _initialize_pp_gm(self):
        pp_gm_cent_array = numpy.zeros_like(self._ln_k_array)

        for idx in xrange(self._ln_k_array.size):
            pp_gm_cent = integrate.romberg(
                self._pp_gm_integrand, numpy.log(self.mass.nu_min),
                numpy.log(self.mass.nu_max), vec_func=True,
                tol=defaults.default_precision["halo_precision"],
                args=(self._ln_k_array[idx], "central_first_moment"))
            pp_gm_cent_array[idx] = pp_gm_cent/self.n_bar

        self._pp_gm_cent_spline = InterpolatedUnivariateSpline(
            self._ln_k_array, pp_gm_cent_array)

        pp_gm_sat_array = numpy.zeros_like(self._ln_k_array)

        for idx in xrange(self._ln_k_array.size):
            pp_gm_sat = integrate.romberg(
                self._pp_gm_integrand, numpy.log(self.mass.nu_min),
                numpy.log(self.mass.nu_max), vec_func=True,
                tol=defaults.default_precision["halo_precision"],
                args=(self._ln_k_array[idx], "satellite_first_moment"))
            pp_gm_sat_array[idx] = pp_gm_sat/self.n_bar

        self._pp_gm_sat_spline = InterpolatedUnivariateSpline(
            self._ln_k_array, pp_gm_sat_array)

        self._initialized_pp_gm = True
def dirichlet_integrate(alpha):
    normalizer = exp(sum(gammaln(alpha)) - gammaln(sum(alpha)))

    def f_recur(x, idx, upper, vals):
        if idx == 1:
            # base case.
            # set values for last two components
            vals[1] = x
            vals[0] = 1.0 - sum(vals[1:])
            # compute Dirichlet value
            print(vals.T, prod(vals ** (alpha - 1)) , normalizer, alpha)
            return prod(vals.T ** (alpha - 1)) / normalizer
        else:
            vals[idx] = x
            split = alpha[idx-1] / sum(alpha)
            if (split < upper - x):
                return romberg(f_recur, 0, split, args=(idx - 1, upper - x, vals), vec_func=False) + \
                    romberg(f_recur, split, upper - x, args=(idx - 1, upper - x, vals), vec_func=False)
            else:
                return romberg(f_recur, 0, upper - x, args=(idx - 1, upper - x, vals), vec_func=False)

    split = alpha[-1] / sum(alpha)
    print(alpha / sum(alpha))
    return romberg(f_recur, 0, split, args=(len(alpha) - 1, 1.0, zeros((len(alpha), 1), float64)), vec_func=False) + \
        romberg(f_recur, split, 1, args=(len(alpha) - 1, 1.0, zeros((len(alpha), 1), float64)), vec_func=False) 
Example #3
0
    def _normalize(self):
        self.f_norm = 1.0
        norm = integrate.romberg(
            self.f_nu, self.nu_min, self.nu_max, vec_func=True,
            tol=defaults.default_precision["global_precision"],
            rtol=defaults.default_precision["mass_precision"],
            divmax=defaults.default_precision["divmax"])
        self.f_norm = 1.0/norm

        self.bias_norm = 1.0
        norm = integrate.romberg(
            lambda x: self.f_nu(x)*self.bias_nu(x),
            self.nu_min, self.nu_max, vec_func=True,
            tol=defaults.default_precision["global_precision"],
            rtol=defaults.default_precision["mass_precision"],
            divmax=defaults.default_precision["divmax"])
        self.bias_norm = 1.0/norm
        
        self.bias_2_norm = 0.0
        norm = integrate.romberg(
            lambda x: self.f_nu(x)*self.bias_2_nu(x),
            self.nu_min, self.nu_max, vec_func=True,
            tol=defaults.default_precision["global_precision"],
            rtol=defaults.default_precision["mass_precision"],
            divmax=defaults.default_precision["divmax"])
        self.bias_2_norm = -norm
def dirichlet_integrate(alpha):
    normalizer = exp(sum(gammaln(alpha)) - gammaln(sum(alpha)))

    def f_recur(x, idx, upper, vals):
        if idx == 1:
            # base case.
            # set values for last two components
            vals[1] = x
            vals[0] = 1.0 - sum(vals[1:])
            # compute Dirichlet value
            print vals.T, prod(vals**(alpha - 1)), normalizer, alpha
            return prod(vals.T**(alpha - 1)) / normalizer
        else:
            vals[idx] = x
            split = alpha[idx - 1] / sum(alpha)
            if (split < upper - x):
                return romberg(f_recur, 0, split, args=(idx - 1, upper - x, vals), vec_func=False) + \
                    romberg(f_recur, split, upper - x, args=(idx - 1, upper - x, vals), vec_func=False)
            else:
                return romberg(f_recur,
                               0,
                               upper - x,
                               args=(idx - 1, upper - x, vals),
                               vec_func=False)

    split = alpha[-1] / sum(alpha)
    print alpha / sum(alpha)
    return romberg(f_recur, 0, split, args=(len(alpha) - 1, 1.0, zeros((len(alpha), 1), float64)), vec_func=False) + \
        romberg(f_recur, split, 1, args=(len(alpha) - 1, 1.0, zeros((len(alpha), 1), float64)), vec_func=False)
Example #5
0
    def raw_correlation(self, r):
        """
        Compute the value of the correlation at array values r

        Args:
            r: float array of position values in Mpc/h
        """
        try:
            xi_out = numpy.empty(len(r))
            for idx, value in enumerate(r):
                xi_out[idx] = integrate.romberg(
                    self._correlation_integrand,
                    self._ln_k_min, self._ln_k_max, args=(value,),
                    vec_func=True,
                    tol=defaults.default_precision["global_precision"],
                    rtol=defaults.default_precision["corr_precision"],
                    divmax=defaults.default_precision["divmax"])
        except TypeError:
            xi_out = integrate.romberg(
                    self._correlation_integrand,
                    self._ln_k_min, self._ln_k_max, args=(r,), vec_func=True,
                    tol=defaults.default_precision["global_precision"],
                    rtol=defaults.default_precision["corr_precision"],
                    divmax=defaults.default_precision["divmax"])
        return xi_out
Example #6
0
 def adj_term(self, N_bins, method):
     # Area of ideal histogram bins.
     A = 1. / N_bins
     cum_areas = np.arange(N_bins) * A
     ideal_bins = erfinv(
         cum_areas)  # Ideally the Nth bin has height 0 and infinite width
     real_bins = np.append(ideal_bins, self.cutoff_val)
     bin_widths = np.diff(real_bins)
     # Heights of the ideal bins
     id_bin_hs = A / bin_widths
     #id_bin_hs[-1] = 0
     # Calulate the adjustment to the error
     if method == "sq":
         adj_error = np.sqrt(2 / np.pi) - id_bin_hs.sum() * A
     elif method == "abs":
         adj_error = romberg(lambda z: np.square(id_bin_hs[np.digitize(
             z, real_bins) - 1] - 2 / np.sqrt(np.pi) * np.exp(-z**2)),
                             0.,
                             self.cutoff_val * .999,
                             divmax=100,
                             tol=1.e-6,
                             vec_func=True)
     elif method == "abs_sqrtM":
         adj_error = np.sqrt(N_bins) * romberg(
             lambda z: np.square(id_bin_hs[np.digitize(z, real_bins) - 1] -
                                 2 / np.sqrt(np.pi) * np.exp(-z**2)),
             0.,
             self.cutoff_val * .999,
             divmax=100,
             tol=1.e-6,
             vec_func=True)
     return adj_error, real_bins, id_bin_hs
Example #7
0
    def raw_window_function(self, chi):
        a = 1.0 / (1.0 + self.cosmo.redshift(chi))

        try:
            g_chi = numpy.empty(len(chi))
            for idx, value in enumerate(chi):
                chi_bound = value
                if chi_bound < self._g_chi_min: chi_bound = self._g_chi_min

                g_chi[idx] = integrate.romberg(
                    self._lensing_integrand,
                    chi_bound,
                    self.chi_max,
                    args=(value, ),
                    vec_func=True,
                    tol=defaults.default_precision["window_precision"])
        except TypeError:
            chi_bound = chi
            if chi_bound < self._g_chi_min: chi_bound = self._g_chi_min

            g_chi = integrate.romberg(
                self._lensing_integrand,
                chi_bound,
                self.chi_max,
                args=(chi, ),
                vec_func=True,
                tol=defaults.default_precision["window_precision"])

        g_chi *= self.cosmo.H0 * self.cosmo.H0 * chi

        return 3.0 / 2.0 * self.cosmo._omega_m0 * g_chi / a
def cont_est_logistic(ind, division, xs, coefs_p):

    ncols = xs.shape[1]
    #nrows=xs.shape[0]

    x = np.zeros((ncols, 3))
    x[:, 1] = xs.iloc[ind, :].values
    x[:, 2] = (x[:, 1] - x[:, 0]) / division
    y = np.zeros((division, ncols))

    temp = np.zeros((ncols, 2))
    for j in range(temp.shape[0]):
        temp[j, 0] = x[j, 0]
        temp[j, 1] = x[j, 0] + x[j, 2]

        def f(x):
            return pd_logistic(x, j, temp, coefs_p)

        y[0, j] = sci.romberg(f, 0, 1)

    for i in range(1, y.shape[0]):
        for j in range(temp.shape[0]):
            temp[j, 0] = temp[j, 1]
            temp[j, 1] = temp[j, 0] + x[j, 2]

            def f(x):
                return pd_logistic(x, j, temp, coefs_p)

            y[i, j] = sci.romberg(f, 0, 1)

    return y.sum(axis=0)
Example #9
0
    def correlation(self, l):
        """
        Compute the value of the correlation at array values theta

        Args:
            theta: float array of angular values in radians to compute the
                correlation
        """
        try:
            power = numpy.empty(len(l))
            for idx, value in enumerate(l):
                power[idx] = integrate.romberg(
                    self._correlation_integrand,
                    self.kernel.chi_min,
                    self.kernel.chi_max,
                    args=(value, ),
                    vec_func=True,
                    tol=defaults.default_precision["global_precision"],
                    rtol=defaults.default_precision["corr_precision"],
                    divmax=defaults.default_precision["divmax"])
        except TypeError:
            power = integrate.romberg(
                self._correlation_integrand,
                self.kernel.chi_min,
                self.kernel.chi_max,
                args=(l, ),
                vec_func=True,
                tol=defaults.default_precision["global_precision"],
                rtol=defaults.default_precision["corr_precision"],
                divmax=defaults.default_precision["divmax"])
        return power
Example #10
0
    def raw_correlation(self, r):
        """
        Compute the value of the correlation at array values r

        Args:
            r: float array of position values in Mpc/h
        """
        try:
            xi_out = numpy.empty(len(r))
            for idx, value in enumerate(r):
                xi_out[idx] = integrate.romberg(
                    self._correlation_integrand,
                    self._ln_k_min,
                    self._ln_k_max,
                    args=(value, ),
                    vec_func=True,
                    tol=defaults.default_precision["global_precision"],
                    rtol=defaults.default_precision["corr_precision"],
                    divmax=defaults.default_precision["divmax"])
        except TypeError:
            xi_out = integrate.romberg(
                self._correlation_integrand,
                self._ln_k_min,
                self._ln_k_max,
                args=(r, ),
                vec_func=True,
                tol=defaults.default_precision["global_precision"],
                rtol=defaults.default_precision["corr_precision"],
                divmax=defaults.default_precision["divmax"])
        return xi_out
Example #11
0
def complex_quad(func, a, b, **kwargs):
    real = lambda x: np.real(func(x))
    imag = lambda x: np.imag(func(x))

    real_i = integrate.romberg(real, a, b, **kwargs)
    imag_i = integrate.romberg(imag, a, b, **kwargs)
    return real_i + 1j * imag_i
Example #12
0
def complex_integral(func,a,b,args,intype='stupid'):
    real_func = lambda z: np.real(func(z,*args))
    imag_func = lambda z: np.imag(func(z,*args))
    if intype == 'quad':
        real_int = integ.quad(real_func,a,b)
        imag_int = integ.quad(imag_func,a,b)
#        print(real_int)
#        print(imag_int)
        return real_int[0] + 1j * imag_int[0]
    elif intype == 'quadrature':
        real_int = integ.quadrature(real_func,a,b)
        imag_int = integ.quadrature(imag_func,a,b)
#        print(real_int)
#        print(imag_int)
        return real_int[0] + 1j * imag_int[0]
    elif intype == 'romberg':
        real_int = integ.romberg(real_func,a,b)
        imag_int = integ.romberg(imag_func,a,b)
#        print(real_int)
#        print(imag_int)
        return real_int + 1j * imag_int
    elif intype == 'stupid':
        Npoints = 500
        z,dz = np.linspace(a,b,Npoints,retstep=True)
        real_int = np.sum(real_func(z))*dz
        imag_int = np.sum(imag_func(z))*dz
#        print(real_int)
#        print(imag_int)
        return real_int + 1j*imag_int
Example #13
0
def funct(A, r1, r2, r3, hcc, theor, bc0, cl0, k2, b1, b2, b3, b4):
    ca = (pi *
          (r1**2 * romberg(c, bc0, b1, args=(cl0, A, k2)) +
           romberg(cpyra, b1, b2, args=(r1, hcc, b1, cl0, A, k2)) + r2**2 *
           (romberg(c, b2, b3, args=(cl0, A, k2))) + r3**2 *
           (romberg(c, b3, b4, args=(cl0, A, k2)))) - theor) * 100. / theor
    return ca
Example #14
0
    def synphot (self, wlen, flam):
        """`wlen` and `flam` give a tabulated model spectrum in wavelength and f_λ
        units. We interpolate linearly over both the model and the bandpass
        since they're both discretely sampled.

        Note that quadratic interpolation is both much slower and can blow up
        fatally in some cases. The latter issue might have to do with really large
        X values that aren't zero-centered, maybe?

        I used to use the quadrature integrator, but Romberg doesn't issue
        complaints the way quadrature did. I should probably acquire some idea
        about what's going on under the hood.

        """
        from scipy.interpolate import interp1d
        from scipy.integrate import romberg

        d = self._ensure_data ()

        mflam = interp1d (wlen, flam,
                          kind='linear',
                          bounds_error=False, fill_value=0)

        mresp = interp1d (d.wlen, d.resp,
                          kind='linear',
                          bounds_error=False, fill_value=0)

        bmin = d.wlen.min ()
        bmax = d.wlen.max ()

        numer = romberg (lambda x: mresp (x) * mflam (x),
                         bmin, bmax, divmax=20)
        denom = romberg (lambda x: mresp (x),
                         bmin, bmax, divmax=20)
        return numer / denom
Example #15
0
    def raw_window_function(self, chi):
        a = 1.0/(1.0 + self.cosmo.redshift(chi))

        try:
            g_chi = numpy.empty(len(chi))
            for idx,value in enumerate(chi):
                chi_bound = value
                if chi_bound < self._g_chi_min: chi_bound = self._g_chi_min

                g_chi[idx] = integrate.romberg(
                    self._lensing_integrand, chi_bound,
                    self.chi_max, args=(value,), vec_func=True,
                    tol=defaults.default_precision["window_precision"])
        except TypeError:
            chi_bound = chi
            if chi_bound < self._g_chi_min: chi_bound = self._g_chi_min

            g_chi = integrate.romberg(
                self._lensing_integrand, chi_bound,
                self.chi_max, args=(chi,), vec_func=True,
                tol=defaults.default_precision["window_precision"])

        g_chi *= self.cosmo.H0*self.cosmo.H0*chi

        return 3.0/2.0*self.cosmo._omega_m0*g_chi/a
Example #16
0
	def pok(self):

		self.msfcbias()
		self.NFWpro()

		bias_interp = scipy.interpolate.interp1d(mass_arr, self.bias)
		nlnm_interp = scipy.interpolate.interp1d(mass_arr, self.ndlnm)
		pk_dat = np.loadtxt(self.name['pok_file'])
		pk_interp = scipy.interpolate.interp1d(pk_dat[:, 0], pk_dat[:, 1])
		plk_arr = pk_interp(self.karr)     
		
		p1h_arr = np.zeros(CP['num_k'])
		pok_arr = np.zeros(CP['num_k'])
		Ii_arr = np.zeros(CP['num_k'])
		m_min = 1.000001 * min(mass_arr)
		m_max = 0.999999 * max(mass_arr)

		for i in range(CP['num_k']):
		        rho_interp = scipy.interpolate.interp1d(mass_arr, self.NFW[i, :])
		        p1h_arr[i] = romberg(pf,np.log(m_min),np.log(m_max),args=(nlnm_interp,rho_interp))
		        Ii_arr[i] = romberg(Itm,np.log(m_min),np.log(m_max),args=(nlnm_interp,bias_interp,rho_interp))
		        pok_arr[i] = plk_arr[i]*Ii_arr[i]**2.0 + p1h_arr[i]

		pkk_arr = np.zeros([CP['num_k'], 5])
		pkk_arr[:, 0] = self.karr
		pkk_arr[:, 1] = p1h_arr
		pkk_arr[:, 2] = Ii_arr
		pkk_arr[:, 3] = plk_arr
		pkk_arr[:, 4] = plk_arr * (Ii_arr/max(Ii_arr))**2.0 + p1h_arr

		return pkk_arr
Example #17
0
    def _initialize_defaults(self):
        if self._w0 != -1.0 or self._wa != 0.0:
            a_array = numpy.logspace(
                -16, 0,
                defaults.default_precision["cosmo_npoints"])
            self._de_presure_array = self._de_presure(1/a_array - 1.0)
            self._de_presure_spline = InterpolatedUnivariateSpline(
                numpy.log(a_array), self._de_presure_array)

        self._chi = integrate.romberg(
            self.E, 0.0, self._redshift, vec_func=True,
            tol=defaults.default_precision["cosmo_precision"])

        self.growth_norm = integrate.romberg(
            self._growth_integrand, 1e-16, 1.0, vec_func=True,
            tol=defaults.default_precision["cosmo_precision"])
        self.growth_norm *= 2.5*self._omega_m0*numpy.sqrt(self.E0(0.0))

        a = 1.0/(1.0 + self._redshift)
        growth = integrate.romberg(
            self._growth_integrand, 1e-16, a, vec_func=True,
            tol=defaults.default_precision["cosmo_precision"])
        growth *= 2.5*self._omega_m0*numpy.sqrt(self.E0(self._redshift))
        self._growth = growth/self.growth_norm

        self._sigma_norm = 1.0
        self._sigma_norm = self._sigma_8*self._growth/self.sigma_r(8.0)
Example #18
0
    def correlation(self, l):
        """
        Compute the value of the correlation at array values theta

        Args:
            theta: float array of angular values in radians to compute the
                correlation
        """
        try:
            power = numpy.empty(len(l))
            for idx, value in enumerate(l):
                power[idx] = integrate.romberg(
                    self._correlation_integrand, 
                    self.kernel.chi_min, self.kernel.chi_max, args=(value,), 
                    vec_func=True,
                    tol=defaults.default_precision["global_precision"],
                    rtol=defaults.default_precision["corr_precision"],
                    divmax=defaults.default_precision["divmax"])
        except TypeError:
            power = integrate.romberg(
                self._correlation_integrand, 
                self.kernel.chi_min, self.kernel.chi_max, args=(l,), vec_func=True,
                tol=defaults.default_precision["global_precision"],
                rtol=defaults.default_precision["corr_precision"],
                divmax=defaults.default_precision["divmax"])
        return power
Example #19
0
	def __call__(self,Phi_Mz,p_Mz,par):
		#
		integrand = lambda M,z: Phi_Mz(M,z,par) * p_Mz(M,z) * self.dVdzdO(z)
		inner = lambda z: romberg(integrand,*self.Mrange,args=(z,),
		                          **self.int_kwargs)
		outer = romberg(inner,*self.zrange,**self.int_kwargs)
		return outer
Example #20
0
 def ri(u):
     ''' Epälineaarisen osan integrointi Gaussin kaavalla '''
     J = h/2 # Jakobiaani
     I = lambda k: N(k)*np.cos(np.sum(N(k)*u))*J # Integrandi
     I0 = lambda k: I(k)[0]
     I1 = lambda k: I(k)[1]
     #return 2.0*I(0.0)
     #return quad(I,-1,1)[0]
     return np.array([romberg(I0,-1,1),romberg(I1,-1,1)])
Example #21
0
 def pin(self,alpha, lmd):
     # p(act -> inact)#
     a = -lmd - alpha
     b = lmd - alpha
     c = -lmd + alpha
     d = lmd + alpha
     p1 = sci.romberg(self.f, a, b)
     p2 = sci.romberg(self.f, c, d)
     p = 0.5 * p1 + 0.5 * p2
     return p
Example #22
0
def P_2_numerical(a):
    from scipy.integrate import romberg
    from numpy import cos, sin, pi, exp

    def num(beta):
        return (1.5 * cos(beta)**2 - 0.5) * exp(a * cos(beta)**2) * sin(beta)

    def denom(beta):
        return exp(a * cos(beta)**2) * sin(beta)

    return romberg(num, 0, pi / 2) / romberg(denom, 0, pi / 2)
Example #23
0
def dcom(z, Om0, OmL, ninter=20):
    """
    function computing comoving distance Dc for a given redshift and mean matter and vacuum energies Om0 and OmL
    """
    Omk = 1. - Om0 - OmL
    kwargs = {"Om0": Om0, "OmL": OmL, "Omk": Omk}
    a = 1. / (1.0 + z)

    nz = np.size(z)
    if nz == 1:
        if np.abs(a - 1.0) < 1.e-10:
            dc = 0.
        else:
            dc = romberg(d_func,
                         a,
                         1.,
                         rtol=1.e-10,
                         mmax=16,
                         verbose=False,
                         **kwargs)[0]
    elif nz > 1:
        dc = np.zeros(nz)
        if nz <= ninter:
            for i, ad in enumerate(a):
                if np.abs(ad - 1.0) < 1.e-10:
                    dc[i] = 0.
                else:
                    dc[i] = romberg(d_func,
                                    ad,
                                    1.,
                                    rtol=1.e-10,
                                    mmax=16,
                                    verbose=False,
                                    **kwargs)[0]
        else:
            zmin = np.min(z)
            zmax = np.max(z)
            zi = np.linspace(zmin, zmax, num=ninter)
            fi = np.zeros(ninter)
            for i, zid in enumerate(zi):
                aid = 1.0 / (1 + zid)
                if np.abs(aid - 1.0) < 1.e-10:
                    fi[i] = 0.
                else:
                    fi[i] = romberg(d_func,
                                    aid,
                                    1.,
                                    rtol=1.e-10,
                                    mmax=16,
                                    verbose=False,
                                    **kwargs)[0]
            dsp = UnivariateSpline(zi, fi, s=0.)
            dc = dsp(z)
    return dc
Example #24
0
def romberg_slit_1d(q, width, height, form, pars):
    """
    Romberg integration for slit resolution.

    This is an adaptive integration technique.  It is called with settings
    that make it slow to evaluate but give it good accuracy.
    """
    from scipy.integrate import romberg, dblquad

    if any(k not in form.info['defaults'] for k in pars.keys()):
        keys = set(form.info['defaults'].keys())
        extra = set(pars.keys()) - keys
        raise ValueError("bad parameters: [%s] not in [%s]"%
                         (", ".join(sorted(extra)), ", ".join(sorted(keys))))

    if np.isscalar(width):
        width = [width]*len(q)
    if np.isscalar(height):
        height = [height]*len(q)
    _int_w = lambda w, qi: eval_form(sqrt(qi**2 + w**2), form, pars)
    _int_h = lambda h, qi: eval_form(abs(qi+h), form, pars)
    # If both width and height are defined, then it is too slow to use dblquad.
    # Instead use trapz on a fixed grid, interpolated into the I(Q) for
    # the extended Q range.
    #_int_wh = lambda w, h, qi: eval_form(sqrt((qi+h)**2 + w**2), form, pars)
    q_calc = slit_extend_q(q, np.asarray(width), np.asarray(height))
    Iq = eval_form(q_calc, form, pars)
    result = np.empty(len(q))
    for i, (qi, w, h) in enumerate(zip(q, width, height)):
        if h == 0.:
            r = romberg(_int_w, 0, w, args=(qi,),
                        divmax=100, vec_func=True, tol=0, rtol=1e-8)
            result[i] = r/w
        elif w == 0.:
            r = romberg(_int_h, -h, h, args=(qi,),
                        divmax=100, vec_func=True, tol=0, rtol=1e-8)
            result[i] = r/(2*h)
        else:
            w_grid = np.linspace(0, w, 21)[None,:]
            h_grid = np.linspace(-h, h, 23)[:,None]
            u = sqrt((qi+h_grid)**2 + w_grid**2)
            Iu = np.interp(u, q_calc, Iq)
            #print np.trapz(Iu, w_grid, axis=1)
            Is = np.trapz(np.trapz(Iu, w_grid, axis=1), h_grid[:,0])
            result[i] = Is / (2*h*w)
            """
            r, err = dblquad(_int_wh, -h, h, lambda h: 0., lambda h: w,
                             args=(qi,))
            result[i] = r/(w*2*h)
            """

    # r should be [float, ...], but it is [array([float]), array([float]),...]
    return result
Example #25
0
def romberg_slit_1d(q, width, height, form, pars):
    """
    Romberg integration for slit resolution.

    This is an adaptive integration technique.  It is called with settings
    that make it slow to evaluate but give it good accuracy.
    """
    from scipy.integrate import romberg  # type: ignore

    par_set = set([p.name for p in form.info.parameters.call_parameters])
    if any(k not in par_set for k in pars.keys()):
        extra = set(pars.keys()) - par_set
        raise ValueError("bad parameters: [%s] not in [%s]"
                         % (", ".join(sorted(extra)),
                            ", ".join(sorted(pars.keys()))))

    if np.isscalar(width):
        width = [width]*len(q)
    if np.isscalar(height):
        height = [height]*len(q)
    _int_w = lambda w, qi: eval_form(sqrt(qi**2 + w**2), form, pars)
    _int_h = lambda h, qi: eval_form(abs(qi+h), form, pars)
    # If both width and height are defined, then it is too slow to use dblquad.
    # Instead use trapz on a fixed grid, interpolated into the I(Q) for
    # the extended Q range.
    #_int_wh = lambda w, h, qi: eval_form(sqrt((qi+h)**2 + w**2), form, pars)
    q_calc = slit_extend_q(q, np.asarray(width), np.asarray(height))
    Iq = eval_form(q_calc, form, pars)
    result = np.empty(len(q))
    for i, (qi, w, h) in enumerate(zip(q, width, height)):
        if h == 0.:
            total = romberg(_int_w, 0, w, args=(qi,),
                            divmax=100, vec_func=True, tol=0, rtol=1e-8)
            result[i] = total/w
        elif w == 0.:
            total = romberg(_int_h, -h, h, args=(qi,),
                            divmax=100, vec_func=True, tol=0, rtol=1e-8)
            result[i] = total/(2*h)
        else:
            w_grid = np.linspace(0, w, 21)[None, :]
            h_grid = np.linspace(-h, h, 23)[:, None]
            u_sub = sqrt((qi+h_grid)**2 + w_grid**2)
            f_at_u = np.interp(u_sub, q_calc, Iq)
            #print(np.trapz(Iu, w_grid, axis=1))
            total = np.trapz(np.trapz(f_at_u, w_grid, axis=1), h_grid[:, 0])
            result[i] = total / (2*h*w)
            # from scipy.integrate import dblquad
            # r, err = dblquad(_int_wh, -h, h, lambda h: 0., lambda h: w,
            #                  args=(qi,))
            # result[i] = r/(w*2*h)

    # r should be [float, ...], but it is [array([float]), array([float]),...]
    return result
Example #26
0
    def _smith_parameters(self, a, **kwargs):
        r""" Computes the non linear scale, effective spectral index
        and spectral curvature"""
        a = atleast_1d(a)
        R_nl = zeros_like(a)
        n = zeros_like(a)
        C = zeros_like(a)

        ksamp = logspace(log10(self._kmin), log10(self._kmax), 1024)
        pklog = interp1d(
            log(ksamp),
            ksamp**3 * self.pk_lin(ksamp, **kwargs) / (2.0 * pi**2))
        g = self.G(a)

        def int_sigma(logk, r, _g):
            y = exp(logk) * r
            return pklog(logk) * _g**2 * exp(-y**2)

        def int_neff(logk, r, _g):
            y = exp(logk) * r
            return pklog(logk) * _g**2 * y**2 * exp(-y**2)

        def int_C(logk, r, _g):
            y = exp(logk) * r
            return pklog(logk) * _g**2 * (y**2 - y**4) * exp(-y**2)

        for i in range(R_nl.size):
            sigm = lambda r: romberg(int_sigma,
                                     log(self._kmin),
                                     log(self._kmax),
                                     args=(exp(r), g[i]),
                                     rtol=1e-4,
                                     vec_func=True,
                                     divmax=100) - 1
            R_nl[i] = exp(brentq(sigm, -5, 1.5, rtol=1e-4))

            n[i] = 2.0 * romberg(int_neff,
                                 log(self._kmin),
                                 log(self._kmax),
                                 args=(R_nl[i], g[i]),
                                 rtol=1e-4,
                                 vec_func=True,
                                 divmax=100) - 3

            C[i] = (3 + n[i])**2 + 4 * romberg(int_C,
                                               log(self._kmin),
                                               log(self._kmax),
                                               args=(R_nl[i], g[i]),
                                               rtol=1e-4,
                                               vec_func=True,
                                               divmax=100)
        k_nl = 1.0 / R_nl
        return k_nl, n, C
Example #27
0
def dL2(z,h):
    c=3.e5
    H0=100.*h
    if type(z) == ndarray:
	n=len(z)
	DL=zeros(n,'d')
	for i in range(n):
	    s=romberg(func,0.,z[i])#,tol=1.e-6)
	    DL[i]=c/H0*(1+z[i])*s #(Mpc/h)
    else:
	s=romberg(func,0.,z)#,tol=1.e-6)
	DL=c/H0*(1+z)*s #(Mpc/h)
    return DL
Example #28
0
def dL2(z, h):
    c = 3.e5
    H0 = 100. * h
    if type(z) == ndarray:
        n = len(z)
        DL = zeros(n, 'd')
        for i in range(n):
            s = romberg(func, 0., z[i])  #,tol=1.e-6)
            DL[i] = c / H0 * (1 + z[i]) * s  #(Mpc/h)
    else:
        s = romberg(func, 0., z)  #,tol=1.e-6)
        DL = c / H0 * (1 + z) * s  #(Mpc/h)
    return DL
    def __massEjected(self, m_min):
        """
        Return the mass integration of the mass ejected by the collapse of the
        star
        """
        if(self.imfType == "S"):
            return self.__massEjectedSalpeter(m_min)

        else:
            mEject = (romberg(self.__mPhi, m_min, self.__amsup1, tol=1.48e-04)
                 - romberg(self.__mrPhi, m_min, self.__amsup1, tol=1.48e-04)
                      )
        return mEject
Example #30
0
def dL(z,h):
    c=3.e5
    H0=100.*h

    try:#multiple objects
	n=len(z)
	DL=zeros(n,'d')
	for i in range(n):
	    s=romberg(func,0.,z[i])#,tol=1.e-6)
	    DL[i]=c/H0*(1+z[i])*s #(Mpc/h)
    except TypeError:
	s=romberg(func,0.,z)#,tol=1.e-6)
	DL=c/H0*(1+z)*s #(Mpc/h)
    return DL
Example #31
0
def dL(z, h):
    c = 3.e5
    H0 = 100. * h

    try:  #multiple objects
        n = len(z)
        DL = zeros(n, 'd')
        for i in range(n):
            s = romberg(func, 0., z[i])  #,tol=1.e-6)
            DL[i] = c / H0 * (1 + z[i]) * s  #(Mpc/h)
    except TypeError:
        s = romberg(func, 0., z)  #,tol=1.e-6)
        DL = c / H0 * (1 + z) * s  #(Mpc/h)
    return DL
Example #32
0
def Lookback(z1,
             z2,
             Omega_m0,
             Hz=H_LamCDM,
             H0=H0_def):  ### calculating the lookback time between z1 and z2
    def h(z):
        return 1 / ((1.0 + z) * Hz(Omega_m0, z, H0))

    if z1 >= z2:
        q = romberg(h, z2, z1) * H0
    else:
        q = romberg(h, z1, z2) * H0
    time = q * (100 / H0) * 9.78  ### age is in Gyr
    return time
Example #33
0
    def _de_presure(self, redshift):
        dpresuredz = lambda z: (1 + self.w(z))/(1 + z)

        try:
            presure = numpy.empty(len(redshift))
            for idx, z in enumerate(redshift):
                presure[idx] = 3.0*integrate.romberg(
                    dpresuredz, 0, z, vec_func=True,
                    tol=defaults.default_precision["cosmo_precision"])
        except TypeError:
            presure = 3.0*integrate.romberg(
                dpresuredz, 0, redshift, vec_func=True,
                tol=defaults.default_precision["cosmo_precision"])
        return presure
Example #34
0
def _test_one(name, p, w, tol):
    import scipy.integrate as sum
    # Check that the pdf approximately matchs the numerical integral
    # Check that integral(-inf,0) of pdf sums to 0.5
    err = abs(sum.romberg(p.pdf, -20 * w, 0, tol=1e-15) - 0.5)
    assert err < tol, "%s cdf(0) == 0.5 yields %g" % (name, err)

    # Check that integral(-inf,x) of pdf sums to cdf when x != 0
    err = abs(sum.romberg(p.pdf, -20 * w, w / 6, tol=1e-15) - p.cdf(w / 6))
    assert err < tol, "%s cdf(w/6) == w/6 yields %g" % (name, err)

    # Check that P = cdf(ppf(P))
    P = 0.002
    err = abs(p.cdf(p.ppf(P)) - P)
    assert err < tol, "%s p(lo) = P yields %g" % (name, err)
Example #35
0
def _test_one(name, p, w, tol):
    import scipy.integrate as sum
    # Check that the pdf approximately matchs the numerical integral
    # Check that integral(-inf, 0) of pdf sums to 0.5
    err = abs(sum.romberg(p.pdf, -20*w, 0, tol=1e-15) - 0.5)
    assert err < tol, "%s cdf(0) == 0.5 yields %g"%(name, err)

    # Check that integral(-inf, x) of pdf sums to cdf when x != 0
    err = abs(sum.romberg(p.pdf, -20*w, w/6, tol=1e-15) - p.cdf(w/6))
    assert err < tol, "%s cdf(w/6) == w/6 yields %g"%(name, err)

    # Check that P = cdf(ppf(P))
    P = 0.002
    err = abs(p.cdf(p.ppf(P)) - P)
    assert err < tol, "%s p(lo) = P yields %g"%(name, err)
Example #36
0
def dL(z,
       k,
       Omega_m0,
       H0=H0_def,
       Hz=H_LamCDM):  ### calculate luminosity distance in Mpc
    def h(x):
        return 1.0 / Hz(Omega_m0, x, H0)

    p = H0 * sqrt(abs(Omega_k0(k, H0))) * romberg(h, 0, z)
    if k:
        q = (1.0 + z) * (c / H0) * (1.0 / sqrt(abs(Omega_k0(k, H0)))) * FF(
            p, k)
    else:
        q = (1.0 + z) * (c / H0) * H0 * romberg(h, 0, z)
    return q
Example #37
0
def RhoCoul(r1,r2,theta,tau,xkappa,z,kmax,lmax,nmax,D):
    uklim = sqrt(float(kmax)/(tau*xkappa))
    rhocoul = 0.
    if D == 2:
        rhocoul = integrate.romberg(CGrand2D, 0., 2.*uklim, args=(r1,r2,theta,tau,xkappa,z,lmax))
    elif D == 3:
        rhocoul = integrate.romberg(CGrand3D, 0., 2.*uklim, args=(r1,r2,theta,tau,xkappa,z,lmax))
    if (z > 0.):
        return rhocoul
    else:
        if D == 2:
            rhocoul += Bound2D(r1,r2,theta,tau,xkappa,z,nmax)
        elif D == 3:
            rhocoul += Bound3D(r1,r2,theta,tau,xkappa,z,nmax)
    return rhocoul
Example #38
0
def yieldcode(tmin, tmax, time, RBsol, fracinterp, polynomial, c, IMF):
    """
    The yieldcode module will use the step solution from the rombergquad
    module to calculate the yield in any time period, by calculating and
    excess outside the step ranges.
    """

    if tmin < time[-1]:
        tmin = time[-1]
        
    if tmax > time[0]:
        tmax = time[0]

    deriv = polynomial.deriv()    

    lowerindex = np.where(time<=tmax)[0][0]
    upperindex = np.where(time>=tmin)[0][-1]
   

    if lowerindex >= upperindex: # this is to avoid counting romberg intervals when the times don't actually cover any interval.
        m = lambda t: np.exp(polynomial(np.log(t)))
        y = lambda t: IMF(m(t))*c*deriv(np.log(t))*fracinterp(t)/t*m(t)    
        intsum = romberg(y, tmax, tmin)
        
    else:
        intervals = RBsol[lowerindex:upperindex] 
    
        intsum = np.sum(intervals)
    
        
        # Finding the excess integrals
        m = lambda t: np.exp(polynomial(np.log(t)))
        y = lambda t: IMF(m(t))*c*deriv(np.log(t))*fracinterp(t)/t*m(t) 
       
        t1 = time[lowerindex]   # corrected time is a decreasing vector
        t2 = tmax

        sol = romberg(y, t2, t1)
        intsum += sol
        
        
        t1 = tmin   
        t2 = time[upperindex]

        sol = romberg(y, t2, t1)
        intsum += sol
        
    return intsum
Example #39
0
 def correl_swsw(self, angle, nz1, nz2, h1, h2, method='quad'):
     """Correlation coeficients between two spherical waves."""
     alpha = angle * 4.85*1.e-6
     R = self.pupil_diameter / 2.
     R1 = (h1-self.h_profile) / h1 * R
     R2 = (h2-self.h_profile) / h2 * R
     zeta = alpha  * self.h_profile / R1
     w = R2 / R1
     Lam = 2. * np.pi * R1 / self.large_scale
     n1, m1 = zernike.noll2zern(nz1)
     n2, m2 = zernike.noll2zern(nz2)
     k1, k2 = _kvalues(n1, n2, m1, m2, nz1, nz2)
     results = np.zeros(len(self.h_profile))
     for idx in np.arange(len(self.h_profile)):
         if method == 'quad':
             result_quad = quad(_chassat_integral, 0, np.inf, args=(zeta[idx], Lam[idx], w[idx],  k1, k2, n1, n2, m1, m2))
             results[idx] = result_quad[0] * self.cn2[idx] * R1[idx]**(5./3.)
         elif method == 'romberg':
             result_quad = romberg(_modified_chassat, 1.e-26,np.pi/2., args=(zeta[idx], Lam[idx], w[idx], k1, k2, n1, n2, m1, m2), vec_func = False)
             results[idx] = result_quad * self.cn2[idx] * R1[idx]**(5./3.)
     if len(results) < 2:
         final_integral = results / (self.cn2 * R1**(5./3.))
     else:
         final_integral = trapz(results, x=self.h_profile) / trapz(self.cn2 * R1**(5./3.), x=self.h_profile)
     final_integral = 3.895 * (-1.)**((n1+n2-m1-m2)/2.) * np.sqrt((n1+1.)*(n2+1.)) * self.dr0**(5./3.) * final_integral    
     return final_integral
Example #40
0
def romberg_pinhole_1d(q, q_width, form, pars, nsigma=5):
    """
    Romberg integration for pinhole resolution.

    This is an adaptive integration technique.  It is called with settings
    that make it slow to evaluate but give it good accuracy.
    """
    from scipy.integrate import romberg

    if any(k not in form.info['defaults'] for k in pars.keys()):
        keys = set(form.info['defaults'].keys())
        extra = set(pars.keys()) - keys
        raise ValueError("bad parameters: [%s] not in [%s]" %
                         (", ".join(sorted(extra)), ", ".join(sorted(keys))))

    _fn = lambda q, q0, dq: eval_form(q, form, pars) * gaussian(q, q0, dq)
    r = [
        romberg(_fn,
                max(qi - nsigma * dqi, 1e-10 * q[0]),
                qi + nsigma * dqi,
                args=(qi, dqi),
                divmax=100,
                vec_func=True,
                tol=0,
                rtol=1e-8) for qi, dqi in zip(q, q_width)
    ]
    return np.asarray(r).flatten()
Example #41
0
    def Dplus(self):
        M, L = self.M, self.L
        logx = numpy.linspace(logamin, 0, Np)
        x = numpy.exp(logx)

        def kernel(loga):
            a = numpy.exp(loga)
            return (a * self.Ea(a))**-3 * a  # da = a * d loga

        y = self.Ea(x) * numpy.array([
            romberg(kernel, logx.min(), loga, vec_func=True) for loga in logx
        ])

        def func(x,
                 nu=0,
                 intp=interp1d(logx,
                               y,
                               bounds_error=False,
                               fill_value=numpy.nan,
                               kind=5)):
            return intp(numpy.log(x), nu=nu)
        func.__doc__ =  \
        """evaluates D+(a) There is no 2.5 factor neither.
       (dimensionless, not multiplied by H0)
       for OmegaM = %g, OmegaL = %g
    """ % (M, L)
        return func
Example #42
0
 def test_romberg_rtol(self):
     # Typical function with two extra arguments:
     def myfunc(x, n, z):       # Bessel function integrand
         return 1e19*cos(n*x-z*sin(x))/pi
     val = romberg(myfunc, 0, pi, args=(2, 1.8), rtol=1e-10)
     table_val = 1e19*0.30614353532540296487
     assert_allclose(val, table_val, rtol=1e-10)
Example #43
0
 def test_romberg(self):
     # Typical function with two extra arguments:
     def myfunc(x, n, z):       # Bessel function integrand
         return cos(n*x-z*sin(x))/pi
     val = romberg(myfunc, 0, pi, args=(2, 1.8))
     table_val = 0.30614353532540296487
     assert_almost_equal(val, table_val, decimal=7)
Example #44
0
def DA(z,h):#uses numerical integration technique gaussian quadrature
    c=3.e5
    H0=100.*h
    s=romberg(func,0.,z) 
    DA=c/H0/(1+z)*s     #(Mpc/radian)
    DA=DA*1000./206264  #(kpc/arcsec)    
    return DA
Example #45
0
    def match_abundance(self,
                        halomass,
                        bs,
                        mfunc='Mice',
                        aa=1,
                        Mmin=10.**11.,
                        Mmax=None):
        '''Returns new halomasses by matching abundance to given mass function'''
        if Mmax is None:
            Mmax = halomass[0] * 1.01
        marray = numpy.exp(numpy.arange(numpy.log(Mmin), numpy.log(Mmax),
                                        0.01))
        abund = []
        l = marray.shape[0]
        # f = lambda x:temp_mice(x, a)
        f = lambda x: self.DnDlnm(numpy.exp(x), mfunc=mfunc, aa=aa)
        for foo in range(0, marray.shape[0]):
            abund.append(
                romberg(f,
                        numpy.log(marray)[l - foo - 1],
                        numpy.log(marray)[-1]))

        abund = numpy.array(abund)
        nexpect = abund * bs**3
        newmass = interpolate(nexpect, marray[::-1])
        halomassnew = newmass(
            numpy.linspace(1, len(halomass), num=len(halomass), endpoint=True))
        return halomassnew
Example #46
0
 def _initialize_i_2_2(self):
     _i_2_2_array = numpy.empty((len(self._ln_k_array),
                           len(self._ln_k_array)))
     
     for idx1 in xrange(len(self._ln_k_array)):
         for idx2 in xrange(idx1, len(self._ln_k_array)):
             ln_k1 = self._ln_k_array[idx1]
             ln_k2 = self._ln_k_array[idx2]
             norm = 1.0/self._i_2_2_integrand(0.0, ln_k1, ln_k2, 1.0)
             i_2_2 = integrate.romberg(
                 self._i_2_2_integrand, numpy.log(self.mass.nu_min),
                 numpy.log(self.mass.nu_max), vec_func=True,
                 args=(ln_k2, ln_k2, norm),
                 rtol=defaults.default_precision["halo_precision"],
                 tol=defaults.default_precision["global_precision"],
                 divmax=defaults.default_precision["divmax"])/(self.rho_bar)
             if idx1 == idx2:
                 _i_2_2_array[idx1, idx2] = i_2_2/norm
             else:
                 _i_2_2_array[idx1, idx2] = i_2_2/norm
                 _i_2_2_array[idx2, idx1] = i_2_2/norm
     
     self._i_2_2_spline = RectBivariateSpline(self._ln_k_array,
                                              self._ln_k_array,
                                              _i_2_2_array)
     print "Initialized::I_2_2"
     self._initialized_i_2_2 = True
Example #47
0
    def _initialize_defaults(self):
        self._initialized_growth_spline = False

        if self._w0 != -1.0 or self._wa != 0.0:
            # a_array = numpy.logspace(-4, 0,
            #     defaults.default_precision["cosmo_npoints"])
            a_array = numpy.logspace(
                numpy.log10(defaults.default_precision['cosmo_precision']),
                0, defaults.default_precision["cosmo_npoints"])
            self._de_pressure_array = self._de_pressure(1/a_array - 1.0)
            self._de_pressure_spline = InterpolatedUnivariateSpline(
                numpy.log(a_array), self._de_pressure_array)

        self._chi = integrate.romberg(
            self.E, 0.0, self._redshift, vec_func=True,
            tol=defaults.default_precision["global_precision"],
            rtol=defaults.default_precision["cosmo_precision"],
            divmax=defaults.default_precision["divmax"])

        self.growth_norm = self.growth_factor_eval(1.0)

        a = 1.0 / (1.0 + self._redshift)
        growth = self.growth_factor_eval(a)
        self._growth = growth / self.growth_norm

        self._sigma_norm = 1.0
        self._sigma_norm = self._sigma_8*self._growth/self.sigma_r(8.0)
Example #48
0
    def _initialize_splines(self):
        for idx in xrange(self._z_array.size):
            dist = integrate.romberg(
                self.epoch0.E, 0.0, self._z_array[idx], vec_func=True,
                tol=defaults.default_precision["global_precision"],
                rtol=defaults.default_precision["cosmo_precision"],
                divmax=defaults.default_precision["divmax"])
            self._chi_array[idx] = dist
        self._chi_spline = InterpolatedUnivariateSpline(
            self._z_array, self._chi_array)
        self._z_spline = InterpolatedUnivariateSpline(
            self._chi_array, self._z_array)

        self.growth_norm = self.epoch0.growth_norm

        # for idx in xrange(self._z_array.size):
        #     a = 1.0/(1.0 + self._z_array[idx])
        #     growth = integrate.romberg(
        #         self.epoch0._growth_integrand, 1e-16, a, vec_func=True,
        #         tol=defaults.default_precision["global_precision"],
        #         rtol=defaults.default_precision["cosmo_precision"],
        #         divmax=defaults.default_precision["divmax"])
        #     growth *= 2.5*self._omega_m0*numpy.sqrt(
        #         self.epoch0.E0(self._z_array[idx]))
        #     self._growth_array[idx] = growth/self.growth_norm

        a = 1. / (1. + self._z_array)
        self._growth_array = self.epoch0.growth_factor_eval(a)/self.growth_norm

        self._growth_spline = InterpolatedUnivariateSpline(
            self._z_array, self._growth_array)
Example #49
0
    def _growth_integrand_dynde(G, a, cosmo):
        """
        Derivatives of normalized linear growth function G := D/a and dG/da.
        For dynamical dark energy models, there is no closed integral
        expression for the growth function and the defining differential
        equation must be solved numerically.

        This function is intended as input to scipy.integrate.odeint.
        
        Args:
            G: vector of the state variables (G,G')
            a: scale factor
            cosmo: Instance of cosmology.SingleEpoch

        References:
            Linder E. V., Jenkins A., 2003, MNRAS, 346, 573. (eq. 11)
        """
        z = 1. / a - 1.
        g1, g2 = G
        Xde = lambda x: cosmo.w(1. / x - 1.) / x
        X = numpy.exp(-3. * integrate.romberg(Xde, a, 1., vec_func=True,
                    tol=defaults.default_precision["global_precision"],
                    rtol=defaults.default_precision["cosmo_precision"],
                    divmax=defaults.default_precision["divmax"]))
        X *= cosmo._omega_m0 / (1.0 - cosmo._omega_m0)
        w = cosmo.w(z)
        # create f = (x1', x2')
        f = [(-(3.5 - 1.5 * w / (1. + X)) * g1 / a -
              1.5 * ((1. - w) / (1. + X)) * g2 / a ** 2),
             g1]
        return f
def Beta_J_disk_BR(rdisks, mcold, mstar_disk, Jcold_molecular, vdisk_gas):
    """Calculate the angular momentum loading factor for the galaxy disk using the 
    empirical Blitz & Rosolowsky (2006) star formation law, assuming a flat rotation 
    profile for the disk.

    Inputs:
           rdisks = [gas, stellar] disk half mass radius in kpc
           mcold = total gas mass in the disk in Msun
           mstar_disk = total stellar mass in the disk in Msun
           mgas_mol = total molecular gas mass in Msun Gyr^-1
    Outputs:
           Beta_J_disk = dJ_star/dt = rate of change of angular momentum for the stellar component of the disk in Msun kpc kms^-1 Gyr^-1"""

    # Set integration limits so that 99.95% of the total gas mass is enclosed
    rmin = 0.0
    rmax = 10.0 * np.array(rdisks).max() / Constant.RDISK_HALF_SCALE

    # Calculate the integral of r multiplied by the mass loading factor in annuli, weighted by molecular gas surface density in the disk
    Sigma_Molecular_Weighted_Beta = integrate.romberg(Beta_J_integrand1, rmin, rmax, args = (rdisks, mcold, mstar_disk), tol=0.05,rtol=0.05) # Msun kpc
    
    Norm = Jcold_molecular / vdisk_gas

    # Renormalise to calculate the average mass loading factor of the entire disk
    Beta_J_disk = Sigma_Molecular_Weighted_Beta / Norm

    return Beta_J_disk
Example #51
0
 def test_romberg(self):
     # Typical function with two extra arguments:
     def myfunc(x, n, z):       # Bessel function integrand
         return cos(n*x-z*sin(x))/pi
     val = romberg(myfunc, 0, pi, args=(2, 1.8))
     table_val = 0.30614353532540296487
     assert_almost_equal(val, table_val, decimal=7)
Example #52
0
 def _initialize_PT_averaged(self):
     
     _pt_ave_array = numpy.empty((len(self._ln_k_array),
                                  len(self._ln_k_array)))
     _pt_norm_array = numpy.empty((len(self._ln_k_array),
                                   len(self._ln_k_array)))
     
     for idx1 in xrange(len(self._ln_k_array)):
         for idx2 in xrange(idx1, len(self._ln_k_array)):
             ln_k1 = self._ln_k_array[idx1]
             ln_k2 = self._ln_k_array[idx2]
             pt_ave_norm = 1.0/self._pt_ave_integrand(numpy.pi/2.0,
                                                      ln_k1, ln_k2, 1.0)
             print "Norm", ln_k1, ln_k2, pt_ave_norm
             pt = 1.0/numpy.pi*integrate.romberg(
                 self._pt_ave_integrand, 0.0, numpy.pi,
                 args=(ln_k1, ln_k2, pt_ave_norm), vec_func=True,
                 tol=defaults.default_precision["global_precision"],
                 rtol=defaults.default_precision["halo_precision"],
                 divmax=defaults.default_precision["divmax"])
             if idx1 == idx2:
                 _pt_ave_array[idx1, idx2] = pt/pt_ave_norm
             else:
                 _pt_ave_array[idx1, idx2] = pt/pt_ave_norm
                 _pt_ave_array[idx2, idx1] = pt/pt_ave_norm
                 
     self._min_pt_ave = numpy.min(_pt_ave_array)
     self._t_PT_ave_spline = RectBivariateSpline(
         self._ln_k_array, self._ln_k_array,
         numpy.log(_pt_ave_array - self._min_pt_ave + 1.0))
     
     self._initialzied_PT_averaged = True
Example #53
0
 def test_romberg_rtol(self):
     # Typical function with two extra arguments:
     def myfunc(x, n, z):       # Bessel function integrand
         return 1e19*cos(n*x-z*sin(x))/pi
     val = romberg(myfunc, 0, pi, args=(2, 1.8), rtol=1e-10)
     table_val = 1e19*0.30614353532540296487
     assert_allclose(val, table_val, rtol=1e-10)
Example #54
0
    def test_non_dtype(self):
        # Check that we work fine with functions returning float
        import math

        valmath = romberg(math.sin, 0, 1)
        expected_val = 0.45969769413185085
        assert_almost_equal(valmath, expected_val, decimal=7)