Ejemplo n.º 1
0
def epsilon_experiment(N,
                       series_type,
                       Omega,
                       eps_values=[1.0, 0.1, 0.01, 0.001]):
    # x is global, symbol or array
    psi = series(x, series_type, N)
    f = 1
    for eps in eps_values:
        A = sym.zeros(N - 1, N - 1)
        b = sym.zeros(N - 1)

        for i in range(0, N - 1):
            integrand = f * psi[i]
            integrand = sym.lambdify([x], integrand, 'mpmath')
            b[i, 0] = mpmath.quad(integrand, [Omega[0], Omega[1]])
            for j in range(0, N - 1):
                integrand = eps*sym.diff(psi[i], x)*\
                  sym.diff(psi[j], x) - sym.diff(psi[i], x)*psi[j]
                integrand = sym.lambdify([x], integrand, 'mpmath')
                A[i, j] = mpmath.quad(integrand, [Omega[0], Omega[1]])

        c = A.LUsolve(b)
        u = sum(c[r, 0] * psi[r] for r in range(N - 1)) + x

        U = sym.lambdify([x], u, modules='numpy')
        x_ = numpy.arange(Omega[0], Omega[1], 1 / ((N + 1) * 100.0))
        U_ = U(x_)
        plt.plot(x_, U_)
    plt.legend(["eps=%.1e" % eps for eps in eps_values], loc="upper left")
    plt.title(series_type)
    plt.show()
Ejemplo n.º 2
0
def least_squares_orth(f, psi, Omega, symbolic=True, print_latex=False):
    """
    Given a function f(x,y) on a rectangular domain
    Omega=[[xmin,xmax],[ymin,ymax]],
    return the best approximation to f(x,y) in the space V
    spanned by the functions in the list psi.
    This function assumes that psi are orthogonal on Omega.
    """
    # Modification of least_squares function: drop the j loop,
    # set j=i, compute c on the fly in the i loop.

    N = len(psi) - 1
    # Note that A, b, c becmes (N+1)x(N+1), use 1st column
    A = sym.zeros(N + 1)
    b = sym.zeros(N + 1)
    c = sym.zeros(N + 1)
    x, y = sym.symbols('x y')
    print('...evaluating matrix...', A.shape, b.shape, c.shape)
    for i in range(N + 1):
        j = i
        print('(%d,%d)' % (i, j))

        integrand = psi[i] * psi[j]
        if symbolic:
            I = sym.integrate(integrand, (x, Omega[0][0], Omega[0][1]),
                              (y, Omega[1][0], Omega[1][1]))
        if not symbolic or isinstance(I, sym.Integral):
            # Could not integrate symbolically, use numerical int.
            print('numerical integration of', integrand)
            integrand = sym.lambdify([x, y], integrand, 'mpmath')
            I = mpmath.quad(integrand, [Omega[0][0], Omega[0][1]],
                            [Omega[1][0], Omega[1][1]])
        A[i, 0] = I

        integrand = psi[i] * f
        if symbolic:
            I = sym.integrate(integrand, (x, Omega[0][0], Omega[0][1]),
                              (y, Omega[1][0], Omega[1][1]))
        if not symbolic or isinstance(I, sym.Integral):
            # Could not integrate symbolically, use numerical int.
            print('numerical integration of', integrand)
            integrand = sym.lambdify([x, y], integrand, 'mpmath')
            I = mpmath.quad(integrand, [Omega[0][0], Omega[0][1]],
                            [Omega[1][0], Omega[1][1]])
        b[i, 0] = I
        c[i, 0] = b[i, 0] / A[i, 0]
    print()
    print('A:\n', A, '\nb:\n', b)
    c = [c[i, 0] for i in range(c.shape[0])]  # make list
    print('coeff:', c)

    # c is a sympy Matrix object, numbers are in c[i,0]
    u = sum(c[i] * psi[i] for i in range(len(psi)))
    print('approximation:', u)
    print('f:', sym.expand(f))
    if print_latex:
        print(sym.latex(A, mode='plain'))
        print(sym.latex(b, mode='plain'))
        print(sym.latex(c, mode='plain'))
    return u, c
 def test(self):
     pot = lambda x,y,z: self.m/2.*(self.wx**2*x**2+self.wy**2*y**2+self.wz**2*z**2)
     u0 = 4*pi*hbar**2*self.a0/self.m
     TF = lambda x,y,z: scipy.maximum(self.mu-pot(x,y,z)/u0,0)
     import mpmath
     print 'hi'
     print mpmath.quad(TF,[-self.Rx,self.Rx],[-self.Ry,self.Ry],[-self.Rz,self.Rz])
Ejemplo n.º 4
0
def cdf(x, p, b, loc=0, scale=1):
    """
    Cumulative distribution function of the generalized inverse Gaussian
    distribution.

    The CDF is computed by using mpmath.quad to numerically integrate the PDF.
    """
    x = mpmath.mpf(x)
    p = mpmath.mpf(p)
    b = mpmath.mpf(b)
    loc = mpmath.mpf(loc)
    scale = mpmath.mpf(scale)

    if x <= loc:
        return mpmath.mp.zero
    m = mode(p, b, loc, scale)
    # If the mode is in the integration interval, use it to do the integral
    # in two parts.  Otherwise do just one integral.
    if x <= m:
        c = mpmath.quad(lambda t: pdf(t, p, b, loc, scale), [loc, x])
    else:
        c = (mpmath.quad(lambda t: pdf(t, p, b, loc, scale), [loc, m]) +
             mpmath.quad(lambda t: pdf(t, p, b, loc, scale), [m, x]))
    c = min(c, mpmath.mp.one)
    return c
Ejemplo n.º 5
0
def least_squares_non_verbose(f, psi, Omega, symbolic=True):
    """
    Given a function f(x) on an interval Omega (2-list)
    return the best approximation to f(x) in the space V
    spanned by the functions in the list psi.
    """
    N = len(psi) - 1
    A = sym.zeros(N + 1, N + 1)
    b = sym.zeros(N + 1, 1)
    x = sym.Symbol('x')
    for i in range(N + 1):
        for j in range(i, N + 1):
            integrand = psi[i] * psi[j]
            integrand = sym.lambdify([x], integrand, 'mpmath')
            I = mpmath.quad(integrand, [Omega[0], Omega[1]])
            A[i, j] = A[j, i] = I
        integrand = psi[i] * f
        integrand = sym.lambdify([x], integrand, 'mpmath')
        I = mpmath.quad(integrand, [Omega[0], Omega[1]])
        b[i, 0] = I
    c = mpmath.lu_solve(A, b)  # numerical solve
    c = [c[i, 0] for i in range(c.rows)]

    u = sum(c[i] * psi[i] for i in range(len(psi)))
    return u, c
Ejemplo n.º 6
0
 def ila_er_lp1(self, rloc):
     alpha, beta = self.alpha, self.beta
     interval = [0, self.k * self.na]
     integrand = lambda eta: self.ila_integrand_lp1_a(eta, rloc)
     res = (alpha + 1j * beta) / 2 * mpmath.quad(integrand, interval)
     integrand = lambda eta: self.ila_integrand_lp1_b(eta, rloc)
     res += (alpha + 1j * beta) / 2 * mpmath.quad(integrand, interval)
     return res
Ejemplo n.º 7
0
def least_squares_numerical(f,
                            psi,
                            N,
                            x,
                            integration_method='scipy',
                            orthogonal_basis=False):
    """
    Given a function f(x) (Python function), a basis specified by the
    Python function psi(x, i), and a mesh x (array), return the best
    approximation to f(x) in in the space V spanned by the functions
    in the list psi. The best approximation is represented as an array
    of values corresponding to x.  All calculations are performed
    numerically. integration_method can be `scipy` or `trapezoidal`
    (the latter uses x as mesh for evaluating f).
    """
    import scipy.integrate
    A = np.zeros((N + 1, N + 1))
    b = np.zeros(N + 1)
    if not callable(f) or not callable(psi):
        raise TypeError('f and psi must be callable Python functions')
    Omega = [x[0], x[-1]]
    dx = x[1] - x[0]  # assume uniform partition

    print('...evaluating matrix...', end=' ')
    for i in range(N + 1):
        j_limit = i + 1 if orthogonal_basis else N + 1
        for j in range(i, j_limit):
            print('(%d,%d)' % (i, j))
            if integration_method == 'scipy':
                A_ij = scipy.integrate.quad(lambda x: psi(x, i) * psi(x, j),
                                            Omega[0],
                                            Omega[1],
                                            epsabs=1E-9,
                                            epsrel=1E-9)[0]
            elif integration_method == 'sympy':
                A_ij = mpmath.quad(lambda x: psi(x, i) * psi(x, j),
                                   [Omega[0], Omega[1]])
            else:
                values = psi(x, i) * psi(x, j)
                A_ij = trapezoidal(values, dx)
            A[i, j] = A[j, i] = A_ij

        if integration_method == 'scipy':
            b_i = scipy.integrate.quad(lambda x: f(x) * psi(x, i),
                                       Omega[0],
                                       Omega[1],
                                       epsabs=1E-9,
                                       epsrel=1E-9)[0]
        elif integration_method == 'sympy':
            b_i = mpmath.quad(lambda x: f(x) * psi(x, i), [Omega[0], Omega[1]])
        else:
            values = f(x) * psi(x, i)
            b_i = trapezoidal(values, dx)
        b[i] = b_i

    c = b / np.diag(A) if orthogonal_basis else np.linalg.solve(A, b)
    u = sum(c[i] * psi(x, i) for i in range(N + 1))
    return u, c
Ejemplo n.º 8
0
 def discrete_util(self, timeslice):
     lower = slice2min(timeslice) - conf.TICK / 2.0
     upper = lower + conf.TICK
     if timeslice == 0:
         ans = quad(self.marginal_util, [0.0, conf.TICK/2.0]) + \
               quad(self.marginal_util, [conf.DAY-conf.TICK/2.0, conf.DAY])
     else:
         ans = quad(self.marginal_util, [lower, upper])
     return ans
Ejemplo n.º 9
0
 def discrete_util(self, timeslice):
     lower = slice2min(timeslice) - conf.TICK/2.0
     upper = lower + conf.TICK
     if timeslice == 0:
         ans = quad(self.marginal_util, [0.0, conf.TICK/2.0]) + \
               quad(self.marginal_util, [conf.DAY-conf.TICK/2.0, conf.DAY])
     else:
         ans = quad(self.marginal_util, [lower, upper])
     return ans
def rate_cov_strate_sleeping_v3_uniform(k_matrix,alpha,rate_th1,lamda_u1,bw):
    # define the distribution of the activity
    first_int = (1/3)                                     # correspond to the integral in first term
    second_int = (1/2) - (1/3)                                            # correspond to the integral in second term
    #---------------------------- calibrated -----------------------------------------
    expected_activity = (1/2)                             # expected value of a      # this changes for optimization hance should be calibratable
    expected_strategic_function = (1/2)                           # expected value of s
    #---------------------------- calibrated -----------------------------------------
    noise_var = 1
    # preprocessing - define empty elements and get information about the inputs
    k_mat = k_matrix.copy()
    num_tiers = k_mat.shape[0]
    density_org = k_mat[:,2].copy()
    power = gb.db2pow(k_mat[:,1])
    density_update = np.array(density_org*([1]*(num_tiers-1)+[expected_strategic_function]))
    # define necessary values
    area_org = np.zeros(num_tiers,float)                      # original association probability
    area_sc_update = np.zeros(num_tiers,float)                # association probability of disconnected cell
    N_k_u1 = np.zeros(num_tiers,float)                        #number of users in tier K BS
    N_k_sc = np.zeros(num_tiers,float)                        #number of users in tier K BS
    N_k_total = np.zeros(num_tiers,float)
    threshold_u1 = np.zeros(num_tiers,float)                  #threshold for users in tier K BS
    t_func_main = np.zeros(num_tiers,float)
    t_func_sc = np.zeros(num_tiers,float)
    for i in range(num_tiers):
        area_org[i] = A_k(density_org,power,alpha,i)
        area_sc_update[i] = A_k(density_update,power,alpha,i)
    N_k_u1 = 1 + 1.28*lamda_u1*(area_org/density_org)
    N_k_sc = expected_activity*(1-expected_strategic_function)*density_org[-1]*N_k_u1[-1]*(area_sc_update/density_update)   #for binary optimization
    N_k_total = N_k_u1 + N_k_sc
    threshold_u1 = 2**((rate_th1/bw)*N_k_total) -1
    for i in range(num_tiers):
        first_exp_term = -(threshold_u1[i]*noise_var/power[i])
        z_term = 0 if (threshold_u1[i]==0) else (threshold_u1[i])**(2/alpha) *mp.quad(lambda u: 1/ (1+u**(alpha/2)),[(1/threshold_u1[i])**(2/alpha),mp.inf])
        second_exp_term = -mp.pi*z_term* sum(density_update*(power/power[i])**(2/alpha))
        third_exp_term_main = -mp.pi * sum(density_org*(power/power[i])**(2/alpha))
        third_exp_term_sc = -mp.pi * sum(density_update*(power/power[i])**(2/alpha))
        t_func_main[i] = mp.quad(lambda y: y * mp.exp(first_exp_term*y**alpha) * mp.exp(second_exp_term*y**2) * mp.exp(third_exp_term_main*y**2),[0,mp.inf])
        t_func_sc[i] = mp.quad(lambda y: y* mp.exp(first_exp_term*y**alpha) * mp.exp(second_exp_term*y**2) * mp.exp(third_exp_term_sc*y**2), [0,mp.inf])
    temp_second_sum = sum(2*mp.pi*density_update*t_func_sc)
    temp_third_sum = sum(2*mp.pi*density_org[0:-1]*t_func_main[0:-1])
    #rate_coverage = (2*mp.pi*density_org[-1]/expected_activity)*(t_func_main[-1]*first_int + temp_second_sum*second_int) + temp_third_sum
    rate_coverage = (area_org[-1]/expected_activity)*((2*mp.pi*density_org[-1]/area_org[-1])*t_func_main[-1]*first_int + temp_second_sum*second_int) + temp_third_sum
    #print((sum(2*mp.pi*density_update*t_func_sc)*second_int+t_func_main[-1]*first_int)*(2*mp.pi*density_org[-1]))
    #print(t_func_main[-1]*first_int)
    #print(temp_second_sum*second_int)
    #print((2*mp.pi*density_org[-1]/expected_activity)*(t_func_main[-1]*first_int) + temp_third_sum)
    #print(temp_second_sum)
    return (rate_coverage)
Ejemplo n.º 11
0
 def arc_length(self, start, stop, q_type = None):
     """
     Parameters:
     ---------
     q_type:  string
         'exact', 'integral', 'numeric'
     start, stop: numeric/str
         These are the limits of integration
     """
     
     start = sym.sympify(start)
     stop = sym.sympify(stop)        
     
        
     
     if q_type is None:
         q_type = self.q_type        
     
     u = self.u
     I = sym.Integral(self.ds, (u, start, stop))
     
     if q_type == 'integral':
         return I
     elif q_type == 'exact':
         return I.doit()
     else:
         f = make_func(str(self.ds), func_params=(self.ind_var), func_type='numpy')
         value = mp.quad(f, [float(start.evalf()), float(stop.evalf())])
         return value
Ejemplo n.º 12
0
def element_vector(f, phi, Omega_e, symbolic=True, numint=None):
    n = len(phi)
    b_e = sym.zeros(n, 1)
    # Make f a function of X (via f.subs to avoid real numbers from lambdify)
    X = sym.Symbol('X')
    if symbolic:
        h = sym.Symbol('h')
    else:
        h = Omega_e[1] - Omega_e[0]
    x = (Omega_e[0] + Omega_e[1]) / 2 + h / 2 * X  # mapping
    f = f.subs('x', x)
    detJ = h / 2
    if numint is None:
        for r in range(n):
            if symbolic:
                I = sym.integrate(f * phi[r] * detJ, (X, -1, 1))
            if not symbolic or isinstance(I, sym.Integral):
                # Ensure h is numerical
                h = Omega_e[1] - Omega_e[0]
                detJ = h / 2
                f_func = sym.lambdify([X], f, 'mpmath')
                phi_func = sym.lambdify([X], phi[r], 'mpmath')
                integrand = lambda X: f_func(X) * phi_func(X) * detJ
                I = mpmath.quad(integrand, [-1, 1])
            b_e[r] = I
    else:
        #phi = [sym.lambdify([X], phi[r]) for r in range(n)]
        # f contains h from the mapping, substitute X with Xj
        # instead of f = sym.lambdify([X], f)
        for r in range(n):
            for j in range(len(numint[0])):
                Xj, wj = numint[0][j], numint[1][j]
                fj = f.subs(X, Xj)
                b_e[r] += fj * phi[r](Xj) * detJ * wj
    return b_e
Ejemplo n.º 13
0
    def calculate(self):
        """
        Example:
        >>> calc = CrossSectionCalcBed(1.4e8, atom = AtomFactory.get_h2())
        >>> calc.calculate()*2.
        """
        integrated_cross_sec_subshells = np.zeros(len(self.w_max))
        for n_shell in range(len(self.w_max)):
            u = self.u[n_shell]
            S = self.S[n_shell]

            factor = S / (self.t[n_shell] + u + 1.0)

            sub_factor1_1 = 2.0 - (self.atom.Ni[n_shell] /
                                   self.atom.N[n_shell])
            sub_factor1_2 = (self.t[n_shell] - 1.0) / self.t[n_shell] - np.log(
                self.t[n_shell]) / (self.t[n_shell] + 1.)
            summand1 = sub_factor1_1 * sub_factor1_2
            integrated_cross_sec_subshells[n_shell] = mp.quad(
                lambda w: self.calculate_modified_oscillator_strength(
                    w, n_shell), [0., self.w_max[n_shell]])

            factor2 = np.log(self.t[n_shell]) / self.atom.N[n_shell]
            integrated_cross_sec_subshells[n_shell] *= factor2
            integrated_cross_sec_subshells[n_shell] += summand1
            integrated_cross_sec_subshells[n_shell] *= factor

        total_cross_section_bed = np.sum(integrated_cross_sec_subshells)

        return (total_cross_section_bed) * 1.e4
Ejemplo n.º 14
0
def logistic_gaussian_deriv2(m, v):
    if m.is_infinite or v.is_infinite:
        return Float('0.0')
    mpmath.mp.dps = 500
    mmpf = m._to_mpmath(500)
    vmpf = v._to_mpmath(500)
    # The integration routine below is obtained by substituting x = atanh(t)
    # into the definition of logistic_gaussian''
    #
    # def f(x):
    #     expx = mpmath.exp(x)
    #     one_plus_expx = 1 + expx
    #     return mpmath.exp(-(x - mmpf) * (x - mmpf) / (2 * vmpf)) * (1 - expx) / ((1 + mpmath.exp(-x)) * one_plus_expx * one_plus_expx)
    # coef = 1 / mpmath.sqrt(2 * mpmath.pi * vmpf)
    # int = mpmath.quad(f, [-mpmath.inf, mpmath.inf])
    # result = coef * int
    #
    # Such substitution makes mpmath.quad call much faster.
    def f(t):
        one_minus_t = 1 - t
        one_minus_t_squared = 1 - t * t
        sqrt_one_minus_t_squared = mpmath.sqrt(one_minus_t_squared)
        return mpmath.exp(-(mpmath.atanh(t) - mmpf) ** 2 / (2 * vmpf)) * (one_minus_t - sqrt_one_minus_t_squared) / ((one_minus_t_squared + sqrt_one_minus_t_squared) * (one_minus_t + sqrt_one_minus_t_squared))
    coef = mpmath.mpf('0.5') / mpmath.sqrt(2 * mpmath.pi * vmpf)
    int, err = mpmath.quad(f, [-1, 1], error=True)
    result = coef * int
    if mpmath.mpf('1e50') * abs(err) > abs(int):
        print(f"Suspiciously big error when evaluating an integral for logistic_gaussian''({m}, {v}).")
        print(f"Integral: {int}")
        print(f"integral error estimate: {err}")
        print(f"Coefficient: {coef}")
        print(f"Result (Coefficient * Integral): {result}")
    return Float(result)
Ejemplo n.º 15
0
def logistic_gaussian(m, v):
    if m == oo:
        if v == oo:
            return oo
        return Float('1.0')
    if v == oo:
        return Float('0.5')
    mpmath.mp.dps = 500
    mmpf = m._to_mpmath(500)
    vmpf = v._to_mpmath(500)
    # The integration routine below is obtained by substituting x = atanh(t)
    # into the definition of logistic_gaussian
    #
    # f = lambda x: mpmath.exp(-(x - mmpf) * (x - mmpf) / (2 * vmpf)) / (1 + mpmath.exp(-x))
    # result = 1 / mpmath.sqrt(2 * mpmath.pi * vmpf) * mpmath.quad(f, [-mpmath.inf, mpmath.inf])
    #
    # Such substitution makes mpmath.quad call much faster.
    tanhm = mpmath.tanh(mmpf)
    # Not really a precise threshold, but fine for our data
    if tanhm == mpmath.mpf('1.0'):
        return Float('1.0')
    f = lambda t: mpmath.exp(-(mpmath.atanh(t) - mmpf) ** 2 / (2 * vmpf)) / ((1 - t) * (1 + t + mpmath.sqrt(1 - t * t)))
    coef = 1 / mpmath.sqrt(2 * mpmath.pi * vmpf)
    int, err = mpmath.quad(f, [-1, 1], error=True)
    result = coef * int
    if mpmath.mpf('1e50') * abs(err) > abs(int):
        print(f"Suspiciously big error when evaluating an integral for logistic_gaussian({m}, {v}).")
        print(f"Integral: {int}")
        print(f"integral error estimate: {err}")
        print(f"Coefficient: {coef}")
        print(f"Result (Coefficient * Integral): {result}")
    return Float(result)
Ejemplo n.º 16
0
 def __compute_surprise_weighted_by_quadrature(self, mi, pi, m, p):
     f = lambda i: mpmath.binomial(
         self.pi, i) * mpmath.binomial(self.p - self.pi, self.m - i) / \
         mpmath.binomial(self.p, self.m)
     # +- 0.5 is because of the continuity correction
     return float(
         -mpmath.log10(mpmath.quad(f, [self.mi - 0.5, self.m + 0.5])))
Ejemplo n.º 17
0
    def nPDF(self, x):

        p = np.zeros(x.size)
        for i, xx in enumerate(x):

            gil_pelaez = lambda t: mp.re(
                self.char_fn(t) * mp.exp(-1j * t * xx))

            cutoff = self.find_cutoff(1e-30)
            # Instead of finding roots, break up quadrature into degrees proportional to the
            # expected number of oscillations of e^(i xx t) within t = [0, cutoff]
            nosc = cutoff / (1 / max(10, np.abs(xx - self.mean())))
            #            roots = self.find_roots(gil_pelaez, cutoff)
            #            if np.abs(xx - self.mean()) < 3 * np.sqrt(self.variance()):

            I = mp.quad(gil_pelaez, np.linspace(0, cutoff, nosc), maxdegree=10)
            #            I = mp.quadosc(gil_pelaez, (0, cutoff), zeros=roots)

            #            else:
            # For now, do not trust any results out greater than 3sigma

            #                I = 0

            # if np.abs(xx - self.mean()) >= 2 * np.sqrt(self.variance()):

            #            I = self.asymptotic_expansion(xx)

            p[i] = 1 / np.pi * float(I)
            print(i)
        return p
def Z_abc(a, b, c):
    if (a != 0):
        return (mp.quad(lambda u:
                        (1 / (1 + u**(b / 2))), [((c / a)**(2 / b)), mp.inf]) *
                (a**(2 / b)))
    else:
        return (0)
Ejemplo n.º 19
0
    def log_likelihood_marginalised_mean_flux(
            self,
            params,
            include_emu=True,
            integration_bounds='default',
            integration_options='gauss-legendre',
            verbose=True,
            integration_method='Quadrature'):  #marginalised_axes=(0, 1)
        """Evaluate (Gaussian) likelihood marginalised over mean flux parameter axes: (dtau0, tau0)"""
        #assert len(marginalised_axes) == 2
        assert self.mf_slope
        if integration_bounds == 'default':
            integration_bounds = [
                list(self.param_limits[0]),
                list(self.param_limits[1])
            ]

        likelihood_function = lambda dtau0, tau0: mmh.exp(
            self.likelihood(np.concatenate(([dtau0, tau0], params)),
                            include_emu=include_emu))
        if integration_method == 'Quadrature':
            integration_output = mmh.quad(likelihood_function,
                                          integration_bounds[0],
                                          integration_bounds[1],
                                          method=integration_options,
                                          error=True,
                                          verbose=verbose)
        elif integration_method == 'Monte-Carlo':
            integration_output = (self._do_Monte_Carlo_marginalisation(
                likelihood_function, n_samples=integration_options), )
        print(integration_output)
        return float(mmh.log(integration_output[0]))
Ejemplo n.º 20
0
	def mini(r):
		nonlocal txi, tv
		xi = [r]
		y = f(r)
		v = r*f(r) + mpmath.quad(f, [r, mpmath.inf])
		if verbose:
			print('Trying r={0} (v={1})'.format(r, v), file=sys.stderr)
		for i in itertools.count():
			xm1 = xi[i]
			h = v / xm1
			y += h
			if y >= maximum or mpmath.almosteq(y, maximum, abs_eps=mpmath.mp.eps * 2**10):
				break
			# We solve for x via secant method instead of using f's inverse.
			x = mpmath.findroot(lambda x: f(x) - y, xm1)
			xi.append(x)
		xi.append(mpmath.mpf())
		if len(xi) == nseg:
			if mpmath.almosteq(y, maximum, abs_eps=mpmath.mp.eps * 2**10):
				txi, tv = xi[::-1], v
				return 0
			# If y > maximum, then v is too large, which means r is too far
			# left, so we want to return a negative value. The opposite holds
			# true when y < maximum.
			return maximum - y
		return len(xi) - nseg + h*mpmath.sign(len(xi) - nseg)
Ejemplo n.º 21
0
def _noncentral_chi_cdf(x, df, nc, dps=None):
    if dps is None:
        dps = mpmath.mp.dps
    x, df, nc = mpmath.mpf(x), mpmath.mpf(df), mpmath.mpf(nc)
    with mpmath.workdps(dps):
        res = mpmath.quad(lambda t: _noncentral_chi_pdf(t, df, nc), [0, x])
        return res
Ejemplo n.º 22
0
def obj1(fn_param, m, b, x0, x1):
    lin_y0 = mp.mp.mpf(m) * x0 + b
    lin_y1 = mp.mp.mpf(m) * x1 + b
    lin_area = (lin_y0 + lin_y1) / 2 * (x1 - x0)
    fn_area = mp.quad(fn_param, [x0, x1])

    return abs(lin_area - fn_area)
Ejemplo n.º 23
0
def _noncentral_chi_cdf(x, df, nc, dps=None):
    if dps is None:
        dps = mpmath.mp.dps
    x, df, nc = mpmath.mpf(x), mpmath.mpf(df), mpmath.mpf(nc)
    with mpmath.workdps(dps):
        res = mpmath.quad(lambda t: _noncentral_chi_pdf(t, df, nc), [0, x])
        return res
Ejemplo n.º 24
0
def test(f_test, a, b):
    result = mpmath.quad(f_test, (a, b))
    print('Test Integrate = %.16f' % result)
    print('Composite Trapezoid method:')
    print_info(CTrapezoid, f_test, a, b, M, result)
    print('Composite Gauss method:')
    print_info(CGauss, f_test, a, b, M, result)
Ejemplo n.º 25
0
def least_squares(f, psi, Omega, symbolic=True):
    """
    Given a function f(x) on an interval Omega (2-list)
    return the best approximation to f(x) in the space V
    spanned by the functions in the list psi.
    """
    N = len(psi) - 1
    A = sym.zeros(N + 1, N + 1)
    b = sym.zeros(N + 1, 1)
    x = sym.Symbol('x')
    print('...evaluating matrix...', end=' ')
    for i in range(N + 1):
        for j in range(i, N + 1):
            print('(%d,%d)' % (i, j))

            integrand = psi[i] * psi[j]
            if symbolic:
                I = sym.integrate(integrand, (x, Omega[0], Omega[1]))
            if not symbolic or isinstance(I, sym.Integral):
                # Could not integrate symbolically, use numerical int.
                print('numerical integration of', integrand)
                integrand = sym.lambdify([x], integrand, 'mpmath')
                I = mpmath.quad(integrand, [Omega[0], Omega[1]])
            A[i, j] = A[j, i] = I
        integrand = psi[i] * f
        if symbolic:
            I = sym.integrate(integrand, (x, Omega[0], Omega[1]))
        if not symbolic or isinstance(I, sym.Integral):
            # Could not integrate symbolically, use numerical int.
            print('numerical integration of', integrand)
            integrand = sym.lambdify([x], integrand, 'mpmath')
            I = mpmath.quad(integrand, [Omega[0], Omega[1]])
        b[i, 0] = I
    print()
    print('A:\n', A, '\nb:\n', b)
    if symbolic:
        c = A.LUsolve(b)  # symbolic solve
        # c is a sympy Matrix object, numbers are in c[i,0]
        c = [sym.simplify(c[i, 0]) for i in range(c.shape[0])]
    else:
        c = mpmath.lu_solve(A, b)  # numerical solve
        c = [c[i, 0] for i in range(c.rows)]
    print('coeff:', c)

    u = sum(c[i] * psi[i] for i in range(len(psi)))
    print('approximation:', u)
    return u, c
Ejemplo n.º 26
0
def solve(f, x0=None, nseg=128, verbose=False):
	"""Find r, v, and the x coordinates for f."""
	r = x0
	if r is None:
		if verbose:
			print('Calculating initial guess... ', end='', file=sys.stderr)
		# The area we seek is nseg equal-area rectangles surrounding f(x), not
		# f(x) itself, but we can get a good approximation from it.
		v = mpmath.quad(f, [0, mpmath.inf]) / nseg
		r = mpmath.findroot(lambda x: x*f(x) + mpmath.quad(f, [x, mpmath.inf]) - v, x0=1, x1=100, maxsteps=100)
		if verbose:
			print(r, file=sys.stderr)
	# We know that f(0) is the maximum because f must decrease monotonically.
	maximum = f(0)
	txi = []
	tv = mpmath.mpf()
	def mini(r):
		nonlocal txi, tv
		xi = [r]
		y = f(r)
		v = r*f(r) + mpmath.quad(f, [r, mpmath.inf])
		if verbose:
			print('Trying r={0} (v={1})'.format(r, v), file=sys.stderr)
		for i in itertools.count():
			xm1 = xi[i]
			h = v / xm1
			y += h
			if y >= maximum or mpmath.almosteq(y, maximum, abs_eps=mpmath.mp.eps * 2**10):
				break
			# We solve for x via secant method instead of using f's inverse.
			x = mpmath.findroot(lambda x: f(x) - y, xm1)
			xi.append(x)
		xi.append(mpmath.mpf())
		if len(xi) == nseg:
			if mpmath.almosteq(y, maximum, abs_eps=mpmath.mp.eps * 2**10):
				txi, tv = xi[::-1], v
				return 0
			# If y > maximum, then v is too large, which means r is too far
			# left, so we want to return a negative value. The opposite holds
			# true when y < maximum.
			return maximum - y
		return len(xi) - nseg + h*mpmath.sign(len(xi) - nseg)
	r = mpmath.findroot(mini, r)
	assert len(txi) == nseg
	if verbose:
		print('Done calculating r, v, x[i].', file=sys.stderr)
	return r, tv, txi
def rate_cov_random_switching_v2(k_matrix, alpha, rate_th, lamda_user, q_on,
                                 bw):
    k_mat = k_matrix.copy()
    num_tiers = k_mat.shape[0]
    #density = k_mat[:,2]
    #density[-1] = q_on
    density = np.array(
        k_mat[:, 2] *
        ([1] * (num_tiers - 1) +
         [q_on]))  #hence last row always corresponds to small cells
    #print(density)
    power = gb.db2pow(k_mat[:, 1])
    small_cell_idx = num_tiers - 1  #indicates the index of the small cell
    #density[small_cell_idx] = q_on
    # initialize the integration result matrix
    tier_integ_result = np.zeros(num_tiers,
                                 float)  #integration results of each tier
    area_tiers = np.zeros(num_tiers, float)  #area of the tiers
    threshold_tier = np.zeros(num_tiers, float)  #threshold of the tiers
    N_k = np.zeros(num_tiers, float)  #number of users in each tier
    first_exp_term = np.zeros(num_tiers,
                              float)  #first exponential term in integral
    second_exp_term = np.zeros(num_tiers,
                               float)  #second exponential term in integral
    third_exp_term = np.zeros(num_tiers,
                              float)  #third exponential term in integral
    for i in range(num_tiers):
        area_tiers[i] = A_k(density, power, alpha, i)
        #N_k[i] = 0 if density[i]==0 else  1.28*lamda_user*area_tiers[i]/density[i]
        N_k[i] = 0 if density[
            i] == 0 else 1 + 1.28 * lamda_user * area_tiers[i] / density[i]
        threshold_tier[i] = mp.inf if (
            bw == 0) else 2**(rate_th * N_k[i] / bw) - 1
        first_exp_term[i] = threshold_tier[i] * 1 / power[i]
        third_exp_term[i] = mp.pi * sum(density *
                                        (power / power[i])**(2 / alpha))
        Z_term = 0 if (threshold_tier[i] == 0) else threshold_tier[i]**(
            2 / alpha) * mp.quad(lambda u: 1 / (1 + u**(alpha / 2)),
                                 [(threshold_tier[i])**(-2 / alpha), mp.inf])
        second_exp_term[i] = third_exp_term[i] * Z_term
    for k in range(num_tiers):
        tier_integ_result[k] = mp.quad(
            lambda y: y * mp.exp(-first_exp_term[k] * y**alpha) * mp.exp(
                -second_exp_term[k] * y**2) * mp.exp(-third_exp_term[k] * y**2
                                                     ), [0, mp.inf])
    rate_cov_prob = 2 * mp.pi * sum(density * tier_integ_result)
    return (rate_cov_prob)
Ejemplo n.º 28
0
    def getIntegratedFisher(self, K, FisherPerMode, kmin, kmax, V, apply_filter = False, scipy_mode = True, interp_mode = 'cubic'):
        """Integrate per-mode Fisher matrix element in k, to get full Fisher matrix element.

        Given arrays of k values and corresponding Fisher matrix elements F(k), compute
            \frac{V}{(2\pi)^2} \int_{kmin}^{kmax} dk k^2 F(k) ,
        where V is the survey volume. The function actually first interpolates over
        the discrete supplied values of FisherPerMode, and then integrates the
        interpolating function between kmin and kmax using scipy.integrate.quad.

        Parameters
        ----------
        K : ndarray
            Array of k values.
        FisherPerMode : array
            Array of Fisher element values corresponding to K.
        kmin : float
            Lower limit of k integral.
        kmax : float
            Upper limit of k integral.
        V : float
            Survey volume.

        Returns
        -------
        result : float
            Result of integral.
        """
        if (kmin<np.min(K)) or (kmax>np.max(K)):
            print('Kmin(Kmax) should be higher(lower) than the minimum(maximum) of the K avaliable!')
            print('\tMin, max K available: %f %f' % (np.min(K),np.max(K)))
            print('\tInput Kmin, Kmax: %f %f' % (kmin,kmax))
            return 0
        else:

            if apply_filter:
                lenK = len(K)
                window_length = 7 #2*int(lenK/10)+1 #make sure it is an odd number
                FisherPerMode = savgol_filter(FisherPerMode, window_length, 3) #, mode = 'nearest')

            mus = np.linspace(-1, 1, len(K))

            function = scipy.interpolate.interp2d(K, mus, FisherPerMode, interp_mode, fill_value = 0., bounds_error = 0.)
        
            f = lambda x1,x2 : x1**2.*(si.dfitpack.bispeu(function.tck[0], function.tck[1], function.tck[2], function.tck[3], function.tck[4], x1, x2)[0])[0]

            if scipy_mode:
                result = scipy.integrate.dblquad(lambda y, x: function(x, y)*x**2., kmin, kmax, lambda x: -1., lambda x: 1., epsrel = 1e-15)
            else:
                ## A bit slow but it is worth it for numerical precision
                #def f(x, y):
                #    x, y = float(x), float(y)
                #    z = function(x, y)*x**2.
                #    z = z[0]
                #    return mpmath.mpf(1)*z
                resultmp = mpmath.quad(f, [kmin, kmax], [-1, 1])
                result = [resultmp]

            result = result[0]*(V)/(2.*np.pi)**2.
            return result
Ejemplo n.º 29
0
def compute_log_moment(sample_ration, variance, iterataions, order):
    mu0 = lambda y: pdf_gauss_mp(y, sigma=variance, mean=mp.mpf(0))
    mu1 = lambda y: pdf_gauss_mp(y, sigma=variance, mean=mp.mpf(1))
    mu = lambda y: (1 - sample_ration) * mu0(y) + sample_ration * mu1(y)
    a_lambda_fn = lambda z: mu(z) * (mu(z) / mu0(z)) ** order
    integral, _ = mp.quad(a_lambda_fn, [-mp.inf, mp.inf], error=True)
    moment = _to_np_float64(integral)
    return np.log(moment)*iterataions
Ejemplo n.º 30
0
    def norm_vawe_function(self, ind_layer_energy):

        C_norm = (mp.sqrt(
            mp.quad(
                lambda t:
                (self.vawe_function(t, self.roots[ind_layer_energy]))**2,
                [min(self.structure_width_vector), self.x_max])).real)
        #print(C_norm)
        return self.vawe_layer(ind_layer_energy) / C_norm
Ejemplo n.º 31
0
def Imn_func(mv,nv,kv,Rv,alphav):
    '''
    eqn. 12.106
    The 'gauss-legendre' quadrature method is used here as it provides 
    more accurate output, even with increasing m&n indices. 
    '''
    return mpmath.quad(lambda thetav: Imn_term_func(mv,nv,kv,Rv,alphav, thetav),
                       (0,alphav),
                       method='gauss-legendre')   
Ejemplo n.º 32
0
def electronOccupationState(eigenvalues, fermiEnergy):
    """
    return electron occupation state for each subband meaning just number of suband value sets
    """
    nk = []
    for eigenvalue in eigenvalues:
        result = temp1*mpmath.quad(lambda x: 1/(1 + mpmath.exp((x-fermiEnergy)/temp2)), [eigenvalue, 2*eigenvalue + fermiEnergy])
        nk.append(result)
    nk = np.array(nk)
    return nk
Ejemplo n.º 33
0
    def getIntegratedFisher(self, K, FisherPerMode, kmin, kmax, V, apply_filter = False, scipy_mode = False, interp_mode = 'cubic'):
        """Integrate per-mode Fisher matrix element in k, to get full Fisher matrix element.

        Given arrays of k values and corresponding Fisher matrix elements F(k), compute
            \frac{V}{(2\pi)^2} \int_{kmin}^{kmax} dk k^2 F(k) ,
        where V is the survey volume. The function actually first interpolates over
        the discrete supplied values of FisherPerMode, and then integrates the
        interpolating function between kmin and kmax using scipy.integrate.quad.

        Parameters
        ----------
        K : ndarray
            Array of k values.
        FisherPerMode : array
            Array of Fisher element values corresponding to K.
        kmin : float
            Lower limit of k integral.
        kmax : float
            Upper limit of k integral.
        V : float
            Survey volume.

        Returns
        -------
        result : float
            Result of integral.
        """
        if (kmin<np.min(K)) or (kmax>np.max(K)):
            print('Kmin(Kmax) should be higher(lower) than the minimum(maximum) of the K avaliable!')
            print('\tMin, max K available: %f %f' % (np.min(K),np.max(K)))
            print('\tInput Kmin, Kmax: %f %f' % (kmin,kmax))
            return 0
        else:

            if apply_filter:
                lenK = len(K)
                window_length = 7 #2*int(lenK/10)+1 #make sure it is an odd number
                FisherPerMode = savgol_filter(FisherPerMode, window_length, 3) #, mode = 'nearest')

            function = scipy.interpolate.interp1d(K, FisherPerMode, interp_mode)

            if scipy_mode:
                result = scipy.integrate.quad(lambda x: function(x)*x**2., kmin, kmax, epsrel = 1e-15)
            else:
                ## A bit slow but it is worth it for numerical precision
                def f(x):
                    x = float(x)
                    y = function(x)*x**2.
                    return mpmath.mpf(1)*y

                resultmp = mpmath.quad(f, [kmin, kmax])
                result = [resultmp]

            result = result[0]*V/(4.*np.pi**2.)
            return result
Ejemplo n.º 34
0
def E_C_pareto_k_c_approx(l, a, d, k, c, w_cancel=True):
  q = 0 if d <= l else 1 - (l/d)**a
  def tail(x):
    if x <= l: return 1
    else: return (l/x)**a
  def tail_delayed(x):
    return (d/(x+d) )**a
  def proxy(x): return tail(x)*tail(x+d)/tail(d)
  def proxy_u(x): return tail(x)**2
  def proxy_l(x): return tail(x+d)**2/tail(d)**2
  if c == 1:
    if d <= l:
      E_X__X_leq_d = 0
      # E_Y = (a*l + d)/2/(a-1)
      # E_Y = l-d + l**a*(l**(1-a) - (l+d)**(1-a) )/(a-1) \
      #       + l**(2*a) * (l*(l+d))**(a-1/2) / (2*a-1)
      
      # E_Y = l-d + l**a*mpmath.quad(lambda x: (x+d)**(-a), [l-d, l] ) \
      #       + l**(2*a)*mpmath.quad(lambda x: x**(-a) * (x+d)**(-a), [l, mpmath.inf] )
      # E_Y = l-d + l**a*mpmath.quad(lambda x: (x+d)**(-a), [l-d, l] ) \
      #       + (l**(2*a)*mpmath.quad(lambda x: x**(-a) * x**(-a), [l, mpmath.inf] ) \
      #         + l**(2*a)*mpmath.quad(lambda x: (x+d)**(-a) * (x+d)**(-a), [l, mpmath.inf] ) )/2
      
      # E_Y = (mpmath.quad(proxy_u, [0, mpmath.inf] ) + mpmath.quad(proxy_l, [0, mpmath.inf] ) )/2
      E_Y = mpmath.quad(tail_delayed, [0, mpmath.inf] )
      
      return k*(q*E_X__X_leq_d + (1-q)*(2*E_Y + d) )
    else:
      E_X__X_leq_d = l*a/(a-1)*(1 - (l/d)**(a-1) )/(1 - (l/d)**a)
      # E_Y = (a*l + d)/2/(a-1)
      # E_Y = mpmath.quad(proxy, [0, mpmath.inf] )
      
      # E_Y = d**a*mpmath.quad(lambda x: (x+d)**(-a), [0, l] ) \
      #       + (l*d)**a*mpmath.quad(lambda x: x**(-a) * (x+d)**(-a), [l, mpmath.inf] )
      # E_Y = d**a*mpmath.quad(lambda x: (x+d)**(-a), [0, l] ) \
      #       + ((l*d)**a*mpmath.quad(lambda x: x**(-a) * x**(-a), [l, mpmath.inf] )
      #         + (l*d)**a*mpmath.quad(lambda x: (x+d)**(-a) * (x+d)**(-a), [l, mpmath.inf] ) )/2
      
      # E_Y = (mpmath.quad(proxy_u, [0, mpmath.inf] ) + mpmath.quad(proxy_l, [0, mpmath.inf] ) )/2
      E_Y = mpmath.quad(tail, [0, mpmath.inf] )
      
      return k*(q*E_X__X_leq_d + (1-q)*(2*E_Y + d) )
Ejemplo n.º 35
0
def E_C_pareto_k_c_approx(l, a, d, k, c, w_cancel=True):
  q = 0 if d <= l else 1 - (l/d)**a
  def tail(x):
    if x <= l: return 1
    else: return (l/x)**a
  def tail_delayed(x):
    return (d/(x+d) )**a
  def proxy(x): return tail(x)*tail(x+d)/tail(d)
  def proxy_u(x): return tail(x)**2
  def proxy_l(x): return tail(x+d)**2/tail(d)**2
  if c == 1:
    if d <= l:
      E_X__X_leq_d = 0
      # E_Y = (a*l + d)/2/(a-1)
      # E_Y = l-d + l**a*(l**(1-a) - (l+d)**(1-a) )/(a-1) \
      #       + l**(2*a) * (l*(l+d))**(a-1/2) / (2*a-1)
      
      # E_Y = l-d + l**a*mpmath.quad(lambda x: (x+d)**(-a), [l-d, l] ) \
      #       + l**(2*a)*mpmath.quad(lambda x: x**(-a) * (x+d)**(-a), [l, mpmath.inf] )
      # E_Y = l-d + l**a*mpmath.quad(lambda x: (x+d)**(-a), [l-d, l] ) \
      #       + (l**(2*a)*mpmath.quad(lambda x: x**(-a) * x**(-a), [l, mpmath.inf] ) \
      #         + l**(2*a)*mpmath.quad(lambda x: (x+d)**(-a) * (x+d)**(-a), [l, mpmath.inf] ) )/2
      
      # E_Y = (mpmath.quad(proxy_u, [0, mpmath.inf] ) + mpmath.quad(proxy_l, [0, mpmath.inf] ) )/2
      E_Y = mpmath.quad(tail_delayed, [0, mpmath.inf] )
      
      return k*(q*E_X__X_leq_d + (1-q)*(2*E_Y + d) )
    else:
      E_X__X_leq_d = l*a/(a-1)*(1 - (l/d)**(a-1) )/(1 - (l/d)**a)
      # E_Y = (a*l + d)/2/(a-1)
      # E_Y = mpmath.quad(proxy, [0, mpmath.inf] )
      
      # E_Y = d**a*mpmath.quad(lambda x: (x+d)**(-a), [0, l] ) \
      #       + (l*d)**a*mpmath.quad(lambda x: x**(-a) * (x+d)**(-a), [l, mpmath.inf] )
      # E_Y = d**a*mpmath.quad(lambda x: (x+d)**(-a), [0, l] ) \
      #       + ((l*d)**a*mpmath.quad(lambda x: x**(-a) * x**(-a), [l, mpmath.inf] )
      #         + (l*d)**a*mpmath.quad(lambda x: (x+d)**(-a) * (x+d)**(-a), [l, mpmath.inf] ) )/2
      
      # E_Y = (mpmath.quad(proxy_u, [0, mpmath.inf] ) + mpmath.quad(proxy_l, [0, mpmath.inf] ) )/2
      E_Y = mpmath.quad(tail, [0, mpmath.inf] )
      
      return k*(q*E_X__X_leq_d + (1-q)*(2*E_Y + d) )
Ejemplo n.º 36
0
    def za_l(self, wc, l, n, t, tc):
        """
        Longitudinal impedance in unit of Ohms.
        wc: w/w_pc, where w_pc is core electron plasma frequency.
        tc: core electron temperature.

        """
        limits = self.long_interval(wc, n, t)
        #print(limits)
        result = mp.quad(lambda z: self.za_l_integrand(z, wc, l, n, t), limits)
        return result * self.z_unit * mp.mpc(0, 1)/ mp.sqrt(tc)
def electronOccupationState(eigenvalues, fermiEnergy):
 print 'Finding n_k...'
 nk = []
 for i in range(0,len(eigenvalues)):
  ek = float(eigenvalues[i])	
  #result = nk_factor *( limit(x-ln(1+exp(x-fermiEnergy)/pc.k/300),x,oo) - (ek - ln(1+exp(ek-fermiEnergy)/pc.k/300)))
  result = mpmath.quad(lambda x: nk_factor/(1+mpmath.exp((x-fermiEnergy)/T/K)), [ek, 2*ek + fermiEnergy])
  print float(result)
  nk.append(float(result))

 return nk
Ejemplo n.º 38
0
 def za(self, wrel, lc, n, t, k, Tc):
     """
     antenna impedance
     
     """
     wc = wrel * mp.sqrt(1+n)
     coeff = 4*mp.mpc(0,1) / mp.pi**2 / permittivity
     coeff *= mp.sqrt(emass/2/boltzmann/Tc)
     int_range = MaxKappa.int_interval(wrel, n, t, k)
     integral = mp.quad(lambda zc: self.za_integrand(zc, wc, lc, n, t, k), int_range, method='tanh-sinh')
     return coeff * integral
Ejemplo n.º 39
0
def E_T_exp_k_n(mu, d, k, n):
  if d == 0:
    return 1/mu*(H(n) - H(n-k) )
  q = 1 - math.exp(-mu*d)
  
  E_H_n_r = 0
  for r in range(k+1):
    E_H_n_r += H(n-r) * binom(k,r) * q**r * (1-q)**(k-r)
  
  return d - mpmath.quad(lambda x: (1-math.exp(-mu*x) )**k, [0, d] ) + \
         1/mu*(E_H_n_r - H(n-k) )
Ejemplo n.º 40
0
def E_T_exp_k_n(mu, d, k, n):
  if d == 0:
    return 1/mu*(H(n) - H(n-k) )
  q = 1 - math.exp(-mu*d)
  
  E_H_n_r = 0
  for r in range(k+1):
    E_H_n_r += H(n-r) * binom(k,r) * q**r * (1-q)**(k-r)
  
  return d - mpmath.quad(lambda x: (1-math.exp(-mu*x) )**k, [0, d] ) + \
         1/mu*(E_H_n_r - H(n-k) )
Ejemplo n.º 41
0
    def unsigned_area(self) -> mp.mpf:
        """Calculate the geometric area bounded by x_range.

        Returns
        -------
        unsigned_area : mp.mpf
            The unsigned area of the analyzed function relative to the
            x-axis.

        """
        return mp.quad(lambda x_val: abs(self.func_real(x_val)), self.x_range)
Ejemplo n.º 42
0
 def bimax(self, wrel, l, n, t, tc):
     """
     electron noise.
     w: f/f_p, where f_p is the total plasma frequency.
     
     """
     wc = wrel * mp.sqrt(1+n)
     limits = self.long_interval(wc, n, t)
     #print(limits)
     result = mp.quad(lambda z: self.bimax_integrand(z, wc, l, n, t), limits)
     return result * self.v_unit * mp.sqrt(tc)
Ejemplo n.º 43
0
 def maxkappa(wrel, lc, n, t, k, Tc):
     """
     integral in electron noise calculation.
     wrel:= w/w_ptot, where w_ptot is the total electron plasma frequency
     Tc:= core electron temperature
     
     """
     wc = wrel * mp.sqrt(1+n)
     int_range = MaxKappa.int_interval(wrel, n, t, k)
     coeff = 16 * emass/mp.pi**(3/2) /permittivity /wc**2 * mp.sqrt(2*boltzmann*Tc/emass)
     integral = mp.quad(lambda z: MaxKappa.maxkappa_integrand(z, wc, lc, n, t, k), int_range)
     return coeff * integral 
Ejemplo n.º 44
0
def E_C_pareto_k_c(loc, a, d, k, c, w_cancel=True):
  if w_cancel and d == 0:
    # log(WARNING, "loc= {}, a= {}, d= {}, k= {}, c= {}".format(loc, a, d, k, c) )
    return k*(c+1) * a*(c+1)*loc/(a*(c+1)-1)
  
  q = 0 if d <= loc else 1 - (loc/d)**a
  if not w_cancel:
    return (c*(1-q)+1)*(a*loc/(a-1) )
  else:
    def tail(x):
      if x <= loc: return 1
      else: return (loc/x)**a
    def proxy(x): return tail(x)*tail(x+d)/tail(d)
    if c == 1:
      if d <= loc:
        E_X__X_leq_d = 0
        E_Y = mpmath.quad(proxy, [0, mpmath.inf] )
        return k*(q*E_X__X_leq_d + (1-q)*(2*E_Y + d) )
      else:
        E_X__X_leq_d = loc*a/(a-1)*(1 - (loc/d)**(a-1) )/(1 - (loc/d)**a)
        E_Y = mpmath.quad(proxy, [0, mpmath.inf] )
        return k*(q*E_X__X_leq_d + (1-q)*(2*E_Y + d) )
Ejemplo n.º 45
0
def d_E_T_shiftedexp_k_n_dk(D, mu, d, k, n):
  q_ = 1 - math.exp(-mu*(d+D/k) )
  # return D/k**2 * (-2 + q_**k - k*(1-q_)/(n-k*q_) )
  
  # Beta_q_k_0 = mpmath.quad(lambda x: x**(k-1) * 1/(1-x), [0, q_] )
  # rhs = mu*D/k**2 * q_**k - k*Beta_q_k_0 + (mu*D/k*(1-q_) - q_)/(n-k*q_) + 1/(n-k)
  # return -2*D/k**2 + 1/mu*rhs
  
  Beta_q_ = mpmath.quad(lambda x: x**k * 1/(1-x), [0, q_] )
  rhs = (mu*D*(k+1)/k**2 * (1-q_)/q_ - math.log(q_) )*Beta_q_ + (mu*D/k*(1-q_) - q_)/(n-k*q_) + 1/(n-k)
  r = -2*D/k**2 + 1/mu*rhs
  print("k= {}, r= {}".format(k, r) )
  return r
Ejemplo n.º 46
0
def rescale_profile_by_mass(profile, param, mass, radius):
    """
    Rescale a density profile by a total mass
    within some radius.

    Parameters
    ----------
    profile : Formula1D
        Formula that is a radial density profile.
    param : string
        The density-valued parameter that needs to be rescaled.
    mass : YTQuantity
        The mass of the object.
    radius : YTQuantity
        The radius that the *mass* corresponds to.

    Examples
    --------
    >>> import yt.units as u
    >>> import numpy as np
    >>> gas_density = AM06_density_profile()
    >>> a = 600.0*u.kpc
    >>> a_c = 60.0*u.kpc
    >>> c = 0.17
    >>> alpha = -2.0
    >>> beta = -3.0
    >>> M0 = 1.0e14*u.Msun
    >>> # Don't set the density parameter rho_0!
    >>> gas_density.set_param_values(a=a, a_c=a_c, c=c, 
    ...                              alpha=alpha, beta=beta)
    >>> rescale_profile_by_mass(gas_density, "rho_0", M0, np.inf*u.kpc)
    """
    R = float(in_cgs(radius).value)
    M = float(in_cgs(mass).value)
    rho = profile.copy()
    values = {}
    for n, p in profile.param_values.items():
        if n == param:
            # Set the density parameter to change to unity
            values[n] = 1.0
        elif isinstance(p, float):
            values[n] = p
        else:
            values[n] = float(in_cgs(p).value)
    rho.set_param_values(**values)
    mass_int = lambda r: rho(r)*r*r
    scale = float(M/(4.*np.pi*quad(mass_int, [0, R])))
    u = get_units(mass/radius**3)
    quan = check_type(mass)(scale, "g/cm**3")
    profile.param_values[param] = in_units(quan, u)
Ejemplo n.º 47
0
def calc_term_noonan(p, nudist, n, dps=None):
    if dps:
        mp.dps = dps

    coeffs = nudist[::-1].tolist()

    def calc_term(z, nudist, p, n):
        ans = mp.polyval(coeffs, z)
        ans = z - p * ans
        ans = (1.0 - p) / ans
        return mp.power(ans, n)

    ans2 = mp.quad(lambda z: calc_term(z, nudist, p, n), [1, mp.j, -1, -mp.j, 1])
    ans2 /= 2 * mp.pi * n
    return ans2.imag
Ejemplo n.º 48
0
def E_C_G_1red(task_t_rv, d, k, w_cancel=True):
  mu = task_t_rv.mean()
  if w_cancel:
    def Pr_T_g_t(t):
      t_ = max(d, t)
      return (t <= d)*(task_t_rv.cdf(d)**k - task_t_rv.cdf(t)**k) \
              + 1 - task_t_rv.cdf(t_)**(k-1) * (k*task_t_rv.cdf(t-d)*(1 - task_t_rv.cdf(t_) ) + task_t_rv.cdf(t_) )
    
    def E_X_k__k_minus_1(k_):
      return k_*mu - mpmath.quad(lambda x: x * k_*task_t_rv.cdf(x)**(k_-1)*task_t_rv.pdf(x), [0, mpmath.inf] )
    
    # E_X_k_k = mpmath.quad(lambda x: x * k*task_t_rv.cdf(x)**(k-1)*task_t_rv.pdf(x), [0, mpmath.inf] )
    E_T = E_T_G_1red(task_t_rv, d, k)
    # return k*mu + 2*E_T_G_1red(task_t_rv, d, k) - E_X_k_k - mpmath.quad(Pr_T_g_t, [0, d] )
    
    Pr_X_k_k__l__d_plus_X = mpmath.quad(lambda x: task_t_rv.cdf(d+x)**k*task_t_rv.pdf(x), [0, mpmath.inf] )
    Pr_X_k_k_m_1__l__d_plus_X = mpmath.quad(lambda x: (k*task_t_rv.cdf(d+x)**(k-1)*(1-task_t_rv.cdf(d+x)) + task_t_rv.cdf(d+x)**k)*task_t_rv.pdf(x), [0, mpmath.inf] )
    
    Pr_T_g_d = 1 - task_t_rv.cdf(d)**k
    sum_ = E_X_k__k_minus_1(k) + E_T \
           + mpmath.quad(Pr_T_g_t, [d, mpmath.inf] ) # - max(E_T-d-mu, 0)*(1-Pr_X_k_k__l__d_plus_X)
    return min(sum_, E_X_k__k_minus_1(k+1) + E_T_G_1red(task_t_rv, 0, k) )
  else:
    return k*mu + mu*(1 - task_t_rv.cdf(d)**k)
Ejemplo n.º 49
0
def main():
    func = lambda x: mpmath.exp(mpmath.power(x, 2))
    precision = sys.argv[1].split('**')
    precision = math.pow(int(precision[0]), int(precision[1]))
    x = mpmath.mpf(float(sys.argv[2]))

    print "expected value = %f" % mpmath.quad(func, [0, x])
    print "precision = %f" % precision
    print "x = %f" % x
    print "max Taylor degree to try = %s" % sys.argv[3]
    print ""

    upperbound = int(sys.argv[3])
    lowerbound = 0
    lowestn = 0

    # find the degree logarithmically, this is usually faster than trying 0..n
    while lowerbound < upperbound:
        n = (lowerbound + upperbound) / 2

        # estimate the remainder
        diff = mpmath.diff(func, x, n)
        rn = diff / mpmath.factorial(n + 1)
        rn = rn * mpmath.power(x, n + 1)

        # is it good enough?
        if rn < precision:
            upperbound = n
            lowestn = n
        else:
            lowerbound = n + 1

    if lowestn:
        print "lowest Taylor degree needed = %d" % lowestn
        coefficients = []

        # find the coefficients of our Taylor polynomial
        for k in reversed(range(lowestn + 1)):
            if k > 0:
                coefficients.append(mpmath.diff(func, 0, k - 1) / mpmath.factorial(k))

        # compute the value of the polynomial (add 0 for the free variable, the value of the indefinite integral at 0)
        p = mpmath.polyval(coefficients + [0], x)
        print "computed value = %f" % p
    else:
        print "max n is too low"
Ejemplo n.º 50
0
    def test_cf(dist, support_lower_limit, support_upper_limit):
        pdf = density(dist)
        t = Symbol('t')
        x = Symbol('x')

        # first function is the hardcoded CF of the distribution
        cf1 = lambdify([t], characteristic_function(dist)(t), 'mpmath')

        # second function is the Fourier transform of the density function
        f = lambdify([x, t], pdf(x)*exp(I*x*t), 'mpmath')
        cf2 = lambda t: mpmath.quad(lambda x: f(x, t), [support_lower_limit, support_upper_limit], maxdegree=10)

        # compare the two functions at various points
        for test_point in [2, 5, 8, 11]:
            n1 = cf1(test_point)
            n2 = cf2(test_point)

            assert abs(re(n1) - re(n2)) < 1e-12
            assert abs(im(n1) - im(n2)) < 1e-12
def cdf_of_gamma_difference(z, alpha_1, beta_1, alpha_2, beta_2):
    '''
    The cumulative distribution function of Gamma_1 - Gamma_2 
    using mpmath.quad integrating pdf directly.
    
    Args:
        z: A float. x1 - x2.
        alpha_1: An int. Alpha of Gamma1.
        beta_1: An int. Beta of Gamma1.
        alpha_2: An int. Alpha of Gamma2.
        beta_2: An int. Beta of Gamma2.
        
    Returns:
        The cumulative probability of Gamma1- Gamma2 at z.
    '''
    center = float(alpha_1 ) / float(beta_1) - float(alpha_2) / float(beta_2) 
    standard_err = (float(alpha_1 ) / beta_1 ** 2 + float(alpha_2 ) / beta_2 ** 2 ) ** 0.5
    if z > center + 30 * standard_err:
        z = center + 30 * standard_err
    return mpmath.quad(lambda x: pdf_of_gamma_difference(x, alpha_1, beta_1, alpha_2, beta_2), [center - 200 * standard_err, z])
Ejemplo n.º 52
0
 def arc_length(self, start, stop, q_type = None):
     """
     Parameters:
     ---------
     q_type:  string
         'exact', 'integral', 'numeric'
     start, stop: numeric/str
         These are the limits of integration
     """
     u = self.u
     
     if q_type is None:
         q_type = self.q_type
     
     if q_type == 'integral':
         return sym.Integral(self.ds, (u, start, stop))
     elif q_type == 'exact':
         return self.Ids.subs(u, stop) - self.Ids.subs(u, start)
     else:
         f = make_func(str(self.ds), func_params=(self.ind_var), func_type='numpy')
         value = mp.quad(f, [start, stop])
         return value
Ejemplo n.º 53
0
from __future__ import print_function
import mpmath as mp
from math import *

def func( t, r ):
    return exp( -r**2 * t **2)

r = 10.0

f = lambda t : func(t, r)

res1 = mp.quad( f, (0,mp.inf) ) * 2.0 / sqrt(pi)
print('res1 = %f' % res1)
Ejemplo n.º 54
0
def calc_F_v1( t, ibf1, ibf2 ):
    f = lambda x: exp(-t**2*( x - xgrid[ibf1] )**2) * eval_bfs(x, ibf2, xgrid)
    #print('mpmath v1 = %18.10f' % mp.quad( eval_F, [-mp.inf,mp.inf] ) )
    print('mpmath v2 = %18.10f' % mp.quad( f, [-mp.inf,mp.inf] ) )
Ejemplo n.º 55
0
def calc_F_v2( t, ibf1, ibf2 ):
    # integrand
    beta = pi/(h*t)
    xbar = xgrid[ibf1] - xgrid[ibf2]
    f = lambda x : exp(-x**2) * sin(beta*(x + t*xbar))/(x + t*xbar) * sqrt(h)/pi
    print('mpmath v3 = %18.10f' % mp.quad( f, [-mp.inf,mp.inf] ) )
Ejemplo n.º 56
0
 def _integral_inf_mp(self, fn):
   integral, _ = mp.quad(
       fn, [-mp.inf, mp.inf], error=True,
       maxdegree=7)  # maxdegree = 6 is not enough
   return integral
Ejemplo n.º 57
0
 def E(self):
     def mom_1(x):
         return x * self.pdf(x)
     return float(mpmath.quad(mom_1, [self.a, self.b]))
Ejemplo n.º 58
0
 def cdf(self, x, n):
     def pdf_n(x):
         return self.pdf(x, n)
     cdf = mpmath.quad(pdf_n, [1, x])
     return float(cdf) 
Ejemplo n.º 59
0
 def _integral_bounded_mp(self, fn, lb, ub):
   integral, _ = mp.quad(fn, [lb, ub], error=True)
   return integral