Example #1
0
def CalculateCH4ForcingEquivalent(llcp_time_series):
    ch4fe_time_series = llcp_time_series.copy()

    # Create the output DataFrame and add Columns for CO2fe(t) and CO2we(t) emissions and R(t) and S(t) intermediaries.
    ch4fe_time_series = llcp_time_series
    BlankEmissions = np.zeros(len(llcp_time_series))
    FourColumnBlankEmissions = pd.DataFrame(
        np.array([BlankEmissions, BlankEmissions, BlankEmissions, BlankEmissions]).transpose())

    #   Make Data-frames for R and S
    R = pd.concat([llcp_time_series[{'Year', 'SLCP'}], pd.DataFrame(FourColumnBlankEmissions)], axis=1)
    R['Total'] = BlankEmissions
    S = pd.concat([llcp_time_series[{'Year', 'SLCP'}], pd.DataFrame(FourColumnBlankEmissions)], axis=1)
    S['Total'] = BlankEmissions

    #   Compute the CH4fe values for each year
    for i in ch4fe_time_series.index:

        for k in Constants.DECAY_CONSTANTS.index:
            #           Compute S(i) and enter that value for the current i (Year)
            S.loc[i, k] = mp.nsum(lambda j: ch4fe_time_series.loc[int(j), 'SLCP'] * Dco2(k, i - j), [0, i])

            #           Compute R(i) given S(i) and existing values of R(i)
            R.loc[i, k] = mp.nsum(lambda j: (S.loc[int(j), 'Total'] - R.loc[int(j), 'Total']) * Dch4(k, i - j),
                                  [0, i - 1])

        S.loc[i, 'Total'] = mp.nsum(lambda k: S.loc[i, k], [0, len(Constants.DECAY_CONSTANTS.index) - 1])
        R.loc[i, 'Total'] = mp.nsum(lambda k: R.loc[i, k], [0, len(Constants.DECAY_CONSTANTS.index) - 1])

        #       Compute CO2fe(i) from these values of S(i) and R(i)
        ch4fe_time_series.loc[i, 'CH4fe'] = (S.loc[i, 'Total'] - R.loc[i, 'Total'])

    return ch4fe_time_series
def compound_interest_fnc_mpmath_with_infinite_series_definition_of_e(
        initial_investment, percent1, percent2, percent3, percent4, percent5,
        compounding_frequency):
    #converting the float values to numbers that have 100 decimal places
    initial_investment = mpmath.mpmathify(initial_investment)
    percent1 = mpmath.mpmathify(percent1)
    percent2 = mpmath.mpmathify(percent2)
    percent3 = mpmath.mpmathify(percent3)
    percent4 = mpmath.mpmathify(percent4)
    percent5 = mpmath.mpmathify(percent5)

    #   infinite series definition:  e^x = inf(x^k/K!) taken from wikipedia
    principal = initial_investment
    x = percent1 * compounding_frequency
    principal = mpmath.nsum(lambda n: principal * ((x**n) / mpmath.fac(n)),
                            [0, mpmath.inf])
    x = percent2 * compounding_frequency
    principal = mpmath.nsum(lambda n: principal * ((x**n) / mpmath.fac(n)),
                            [0, mpmath.inf])
    x = percent3 * compounding_frequency
    principal = mpmath.nsum(lambda n: principal * ((x**n) / mpmath.fac(n)),
                            [0, mpmath.inf])
    x = percent4 * compounding_frequency
    principal = mpmath.nsum(lambda n: principal * ((x**n) / mpmath.fac(n)),
                            [0, mpmath.inf])
    x = percent5 * compounding_frequency
    principal = mpmath.nsum(lambda n: principal * ((x**n) / mpmath.fac(n)),
                            [0, mpmath.inf])
    return principal
def CalculateCO2ForcingEquivalent(slcpTimeSeries):
    CO2feTimeSeries = slcpTimeSeries.copy()

    # Create the output DataFrame and add Columns for CO2fe(t) and CO2we(t) emissions and R(t) and S(t) intermediaries.
    CO2feTimeSeries = slcpTimeSeries
    BlankEmissions = np.zeros(len(slcpTimeSeries))
    FourColumnBlankEmissions = pd.DataFrame(
        np.array(
            [BlankEmissions, BlankEmissions, BlankEmissions,
             BlankEmissions]).transpose())

    #   Make Data-frames for R and S
    R = pd.concat([
        slcpTimeSeries[{'Year', 'SLCP'}],
        pd.DataFrame(FourColumnBlankEmissions)
    ],
                  axis=1)
    R['Total'] = BlankEmissions
    S = pd.concat([
        slcpTimeSeries[{'Year', 'SLCP'}],
        pd.DataFrame(FourColumnBlankEmissions)
    ],
                  axis=1)
    S['Total'] = BlankEmissions

    #   Compute the CO2fe values for each year
    for i in CO2feTimeSeries.index:

        for k in Constants.DECAY_CONSTANTS.index:
            #           Compute S(i) and enter that value for the current i (Year)
            S.loc[i, k] = mp.nsum(
                lambda j: CO2feTimeSeries.loc[int(j), 'SLCP'] * Dch4(k, i - j),
                [0, i])

            #           Compute R(i) given S(i) and existing values of R(i)
            R.loc[i, k] = mp.nsum(
                lambda j:
                (S.loc[int(j), 'Total'] - R.loc[int(j), 'Total']) * Dco2(
                    k, i - j), [0, i - 1])

        S.loc[i, 'Total'] = mp.nsum(
            lambda k: S.loc[i, k],
            [0, len(Constants.DECAY_CONSTANTS.index) - 1])
        R.loc[i, 'Total'] = mp.nsum(
            lambda k: R.loc[i, k],
            [0, len(Constants.DECAY_CONSTANTS.index) - 1])

        #       Compute CO2fe(i) from these values of S(i) and R(i)
        CO2feTimeSeries.loc[i,
                            'CO2fe'] = (S.loc[i, 'Total'] - R.loc[i, 'Total'])

        # #       Compute CO2we
        # Et = CO2feTimeSeries.loc[i, 'SLCP']
        # EtMinusdt = 0
        # if i > 19:
        #     EtMinusdt = CO2feTimeSeries.loc[int(i - 20), 'SLCP']
        # CO2feTimeSeries.loc[i, 'CO2we'] = GWPH * ((r * H) / dt * (Et - EtMinusdt) + s * Et)

    return CO2feTimeSeries
Example #4
0
def _Q(n,i,k,s):
    """
    Procedure Name: _Q
    Purpose: Computes the single probability Pk(n,i) for an M/M/s
                queue recursively.
    Arguments:  1. n: The total number of customers in the system
                2. i: An integer value
                3. k: The number of customers in the system at time 0
                4. s: The number of parallel servers
    Output:     1. Pk: A single probability for an M/M/s queue
    """
    rho=Symbol('rho')
    if k>=1 and i==k+n:
        if k>=s:
            p=(rho/(rho+1))**n
        elif k+n<=s:
            p=(rho**n)/(nprod(lambda j: rho+(k+j-1)/s,[1,n]))
        elif k<s and s<k+n:
            p=(rho**n)/((rho+1)**(n-s+k)*
                        (nprod(lambda j: rho+(k+j-1)/s,[1,s-k])))
    if k==0 and i==n:
        if n<=s:
            p=(rho**n)/nprod(lambda j: rho+(j-1)/s,[1,n])
        elif n>s:
            p=(rho**n)/((rho+1)**(n-s)*
                        nprod(lambda j: rho+(j-1)/s,[1,s]))
    if i==1:
        p=1-nsum(lambda j: _Q(n,j,k,s),[2,n+k])
    if k>=1 and i>=2 and i<=k and n==1:
        if k<=s:
            p=rho/(rho+(i-1)/s)*nprod(lambda j:
                                      1-rho/(rho+(k-j+1)/s),[1,k-i+1])
        elif k>s and i>s:
            p=rho/(rho+1)**(k-i+2)
        elif i<=s and s<k:
            p=rho/((rho+1)**(k-s+1)*(rho+(i-1/s))*
                   nprod(lambda j: 1-rho/(rho(s-j)/s),[1,s-i]))
    if n>=2 and i>=2 and i<=k+n-1:
        if i>s:
            p=rho/(rho+1)*nsum(lambda j:
                               (1/(rho+1)**(j-i+1)*_Q(n-1,j,k,s)),
                               [i-1,k+n-1])
        elif i<=s:
            p=rho/(rho+(i-1)/s)*(
                nsum(lambda j:
                     nprod(lambda h: 1-rho/(rho+(j-h+1)/s),[1,j-i+1])*
                           _Q(n-1,j,k,s),[i-1,s-1]) +
                nprod(lambda h: 1-rho/(rho+(s-h)/s),[1,s-i]) *
                nsum(lambda j: (1/(rho+1))**(j-s+1)*_Q(n-1,j,k,s),[s,k+n-1]))
    return simplify(p)
Example #5
0
    def evalAllF2(x):

        if spn.config["families"][f2] == "poisson":
            return nsum(lambda f2val: evspn(x, f2val), [0, inf],
                        verbose=False,
                        method="d")

        if spn.config["families"][f2] == "isotonic":
            return sum(map(lambda f2val: evspn(x, f2val), f2range))

        global inner
        if spn.config["featureTypes"][f2] == "continuous":
            minv = numpy.min(f2domains)
            maxv = numpy.max(f2domains)
            integral = integrate.quad(lambda f2val: evspn(x, f2val),
                                      minv,
                                      maxv,
                                      limit=30,
                                      maxp1=30,
                                      limlst=30)
            print(outer, inner, x, integral)
            inner += 1
            return integral[0]
            #return nsum(lambda f2val: evspn(x,f2val), [minv, maxv], verbose=False, method="d", tol=10 ** (-10))
        else:
            return sum(map(lambda f2val: evspn(x, f2val), f2domains))
Example #6
0
def pdf(x, df, nc):
    """
    Probability density function of the noncentral t distribution.

    The infinite series is estimated with `mpmath.nsum`.
    """
    with mpmath.extradps(5):
        x = mpmath.mpf(x)
        df = mpmath.mpf(df)
        nc = mpmath.mpf(nc)

        if x == 0:
            logp = (-nc**2 / 2 - mpmath.log(mpmath.pi) / 2 -
                    mpmath.log(df) / 2 + mpmath.loggamma(
                        (df + 1) / 2) - mpmath.loggamma(df / 2))
            p = mpmath.exp(logp)
        else:
            logc = (df * mpmath.log(df) / 2 - nc**2 / 2 -
                    mpmath.loggamma(df / 2) - mpmath.log(mpmath.pi) / 2 -
                    (df + 1) / 2 * mpmath.log(df + x**2))
            c = mpmath.exp(logc)

            def _pdf_term(i):
                logterm = (mpmath.loggamma(
                    (df + i + 1) / 2) + i * mpmath.log(x * nc) +
                           i * mpmath.log(2 / (df + x**2)) / 2 -
                           mpmath.loggamma(i + 1))
                return mpmath.exp(logterm).real

            s = mpmath.nsum(_pdf_term, [0, mpmath.inf])
            p = c * s
        return p
Example #7
0
 def _calculate_constant(self):
     """
         Calculates the normalization constant.
     :rtype:
     """
     return power(nsum(lambda n: self._internal_function(n) * power(n, -self._alpha), [1, inf],
                       method=self._summation_method), -1)
Example #8
0
def computeMI2(spn, f1, f2, verbose=False):

    Pxy = spn.marginalizeToEquation([f1, f2])
    Px = spn.marginalizeToEquation([f1])
    Py = spn.marginalizeToEquation([f2])

    sumIxy = "{Pxy} * (log({Pxy})/log(2) - (log({Px})/log(2) + log({Py})/log(2)))".format(
        **{
            'Pxy': Pxy,
            'Px': Px,
            'Py': Py
        })
    # evl = lambda x, y: eval(sumIxy, None, {"x_%s_" % f1:x, "x_%s_" % f2: y, "poissonpmf":poissonpmf})
    evl = compileEq(sumIxy, {
        "x_%s_" % f1: "x",
        "x_%s_" % f2: "y"
    },
                    compileC=False)

    Ixy = nsum(lambda x, y: evl(int(x), int(y)), [0, inf], [0, inf],
               verbose=False,
               method="d",
               tol=10**(-10))

    if verbose:
        print("I(%s,%s)=%s" % (f1, f2, Ixy))

    return Ixy
Example #9
0
    def computeIxy():
        if spn.config["families"][f1] == "poisson":
            return nsum(lambda f1val: evalAllF2(f1val), [0, inf],
                        verbose=False,
                        method="d")

        if spn.config["families"][f1] == "isotonic":
            #print(list(range(minv, maxv)))
            return sum(map(lambda f1val: evalAllF2(f1val), f1range))

        global outer
        global inner
        if spn.config["featureTypes"][f1] == "continuous":
            minv = numpy.min(f1domains)
            maxv = numpy.max(f1domains)
            inner = 0
            integral = integrate.quad(lambda f1val: evalAllF2(f1val),
                                      minv,
                                      maxv,
                                      limit=30,
                                      maxp1=30,
                                      limlst=30)
            print(outer, inner, integral)
            outer += 1
            return integral[0]
            #return nsum(lambda f1val: evalAllF2(f1val), [minv, maxv], verbose=False, method="d", tol=10 ** (-10))
        else:
            return sum(map(lambda f1val: evalAllF2(f1val), f1domains))
Example #10
0
def U(u, v, n):
    """
  Two-variables Lommel function "U" of order "n".
  """
    def seq(s):
        return (-1)**s * (u / v)**(n + 2 * s) * mp.besselj(n + 2 * s, v)

    return mp.nsum(seq, [0, mp.inf])
Example #11
0
def pi_mpmath(n):
    """Calculate PI to the Nth digit.

    I figured using mpmath would work well, but this is not very
    efficient. With n = 1000, it took over a minute on my laptop.
    """
    mp.dps = n
    return str(nsum(lambda k: (4/(8*k+1) - 2/(8*k+4) - 1/(8*k+5) - 1/(8*k+6)) / 16**k, (0, inf)))
Example #12
0
def bell_approx(n): # Dobinski's formula - nth moment of poisson distribution with E[x]=1
    '''
    :param n: natural number
    :return: nth Bell number
    '''

    mpmath.mp.dps = 50
    return int(round((1/math.e) * mpmath.nsum(lambda x: math.pow(x,n)/math.factorial(x), [0, mpmath.inf])))
Example #13
0
def chi(v, z):
    '''
    :param v:
    :param z:
    :return: Legendre chi function
    '''

    return mpmath.nsum(lambda k: pow(z, 2 * k + 1) / pow(2 * k + 1, v),
                       [0, mpmath.inf])
Example #14
0
def dtheta_t3_func(k_v, R_v, alpha_v, theta_v):
    '''
    '''
    version_with_freen = dtheta_t3_oneterm.subs({'k': k_v,
                                                 'R': R_v,
                                                 'alpha': alpha_v,
                                                 'theta': theta_v})
    freen_func = lambdify([n], version_with_freen, 'mpmath')
    return mpmath.nsum(freen_func, [2, mpmath.inf])
def a1(S):
    def sum_item(i):
        z = (4 * i + 1)**2 / (16 * S)
        val1 = gamma(i + 0.5) * sqrt(4 * i + 1) / (gamma(0.5) * gamma(i + 1)) * exp(-z)
        val2 = I(-0.25, z) - I(0.25, z)
        return val1 * val2
    ITER_MAX = 5
    result = float(nsum(sum_item, [0, ITER_MAX])) / sqrt(2 * S)
    return result 
def pi_compute(n):
    """
    >>> pi_compute(50)
    '3.1415926535897932384626433832795028841971693993751'
    """
    mp.dps = n  # accuracy
    return str(
        nsum(
            lambda k: (4 / (8 * k + 1) - 2 / (8 * k + 4) - 1 /
                       (8 * k + 5) - 1 / (8 * k + 6)) / 16**k, (0, inf)))
Example #17
0
def getNthMenageNumber( n ):
    if n < 0:
        raise ValueError( '\'menage\' requires a non-negative argument' )
    elif n in [ 1, 2 ]:
        return 0
    elif n in [ 0, 3 ]:
        return 1
    else:
        return nsum( lambda k: fdiv( fprod( [ power( -1, k ), fmul( 2, n ), binomial( fsub( fmul( 2, n ), k ), k ),
                                            fac( fsub( n, k ) ) ] ), fsub( fmul( 2, n ), k ) ), [ 0, n ] )
def bessel_function(L, x):

    # this expression is the python implementation of the expression for the bessel function of the first kind from the following link:
    # https://keisan.casio.com/exec/system/1180573472

    val = nsum(
        lambda k: ((-1)**k) / (math.factorial(k) * math.gamma(L + k + 1)) *
        ((x / 2)**(L + 2 * k)), [0, inf])

    return val
Example #19
0
def canonical_ensemble(V):
    """Calculate the cononical ensemble of the system

    Z = sum [ exp( - E_i * beta ) ]

    Args
    ----
    V (float) : Volume of the system, 
    """
    return float(mp.nsum(lambda x: mp.exp(-beta*Ei(x, V)), [0,mp.inf], method='s+r'))
Example #20
0
def pi_mpmath(n):
    """Calculate PI to the Nth digit.
    I figured using mpmath would work well, but this is not very
    efficient. With n = 1000, it took over a minute on my laptop.
    """
    mp.dps = n
    return str(
        nsum(
            lambda k: (4 / (8 * k + 1) - 2 / (8 * k + 4) - 1 /
                       (8 * k + 5) - 1 / (8 * k + 6)) / 16**k, (0, inf)))
def kolmogorov_test(x, m, alpha):
    n = len(x)
    sort_x = sorted(x)
    # Масимальнуая разность между накопленными частотами
    D = calc_D(sort_x, m)
    n = len(sort_x)
    # Расчёт значения статистики критерия хи-квадрат
    S = (n * D + 1) / sqrt(n)
    S_alpha = 1 - nsum(lambda k: (-1)**k * exp(-2 * k**2 * S**2), [-inf,  inf])
    passed = alpha < S_alpha
    return n, m, D, S, S_alpha, passed
Example #22
0
def DedekindEta(tau):
    ''' Compute the Dedekind Eta function for imaginary argument tau. 
        See: http://mathworld.wolfram.com/DedekindEtaFunction.html. '''
    try:
        import mpmath as mp
        mpmath_loaded = True
    except ImportError:
        mpmath_loaded = False 
    qbar = mp.exp(-2.0*mp.pi*tau)

    return mp.nsum(lambda n: ((-1)**n)*(qbar**((6*n-1)*(6.0*n-1)/24)),[-mp.inf,mp.inf])
Example #23
0
def moment_i0(a, j):
    '''
    Calculates the j-th moment of phi_0

    Wavelet Analysis: The Scalable Structure of Information (2002)
    Howard L. Resnikoff, Raymond O.Jr. Wells
    page 262
    '''
    N = a.size

    if j == 0:
        return 1

    s = mpmath.nsum(lambda k: binomial(j,k)*moment_i0(a, k)*
            mpmath.nsum(lambda i: a[int(i)]*mpmath.power(i, j-k),
                        [0, N-1]),
            [0, j-1])

    _2 = mp.mpmathify(2)
    return s/(_2*(mpmath.power(_2, j)-1))
Example #24
0
def mp_wright_bessel(a, b, x, dps=50, maxterms=2000):
    """Compute Wright's generalized Bessel function as Series with mpmath.
    """
    with mp.workdps(dps):
        a, b, x = mp.mpf(a), mp.mpf(b), mp.mpf(x)
        res = mp.nsum(
            lambda k: x**k / mp.fac(k) * rgamma_cached(a * k + b, dps=dps),
            [0, mp.inf],
            tol=dps,
            method='s',
            steps=[maxterms])
        return mpf2float(res)
Example #25
0
def computeExpectation(spn, f1, verbose=False):
    
    Px = spn.marginalizeToEquation([f1])
    
    sumEx = "x * {Px}".format(**{'Px': Px})

    evl = compileEq(sumEx, {"x_%s_" % f1: "x"})
    
    Ex = nsum(lambda x: evl(int(x)), [0, inf], verbose=False, method="d", tol=10 ** (-10))

    if verbose:
        print("E(%s)=%s" % (f1, Ex))

    return Ex
Example #26
0
def computeExpectation2(spn, f1, f2, verbose=False):
    
    Pxy = spn.marginalizeToEquation([f1, f2]).replace("x_%s_" % f1, "x").replace("x_%s_" % f2, "y")
    
    sumExy = "(x * y) * {Pxy}".format(**{'Pxy': Pxy})
    
    evl = compileEq(sumExy, {"x_%s_" % f1: "x", "x_%s_" % f2: "y"})
    
    Exy = nsum(lambda x, y: evl(int(x), int(y)), [0, inf], [0, inf], verbose=False, method="d", tol=10 ** (-10))

    if verbose:
        print("E(%s, %s)=%s" % (f1, f2, Exy))

    return Exy
Example #27
0
def computeEntropy2(spn, f1, f2, verbose=False):
    
    Pxy = spn.marginalizeToEquation([f1, f2])
    
    sumHxy = "{Pxy} * log({Pxy})/log(2)".format(**{'Pxy': Pxy})
    
    evl = compileEq(sumHxy, {"x_%s_" % f1: "x", "x_%s_" % f2: "y"})
    # evl = lambda x, y: eval(sumHxy, None, {"x_%s_" % f1:x, "x_%s_" % f2: y, "poissonpmf": poissonpmf})
        
    Hxy = -nsum(lambda x, y: evl(int(x), int(y)), [0, inf], [0, inf], verbose=False, methomethod="d", tol=10 ** (-10))    
    if verbose:
        print("H(%s,%s)=%s" % (f1, f2, Hxy))

    return Hxy
Example #28
0
    def nRCS(self, n='richardson+shanks', kind='isotropic gaussian', db=False):
        """Normalized Radar cross-section"""
        def _nRCS(self, pp, n, kind):
            n = float(n)
            return self.wk**2 * exp(-2*(self.sh*self.wk_z)**2) /2 * \
                   ( self.sh**(2*n) * abs( self.I(n)[pp] )**2 * \
                     roughness.spectrum(self.wk, self.sh, self.cl, self.th, \
                     n=n, kind=kind) / factorial(n) )

        if type(n) is not str:
            vv = nsum(lambda x: _nRCS(self, 'vv', x, kind), [1, n])
            hh = nsum(lambda x: _nRCS(self, 'hh', x, kind), [1, n])

        if type(n) is str:
            vv = nsum(lambda x: _nRCS(self, 'vv', x, kind), [1, inf], method=n)
            hh = nsum(lambda x: _nRCS(self, 'hh', x, kind), [1, inf], method=n)

        vv, hh = float64(vv), float64(hh)

        if db:
            vv, hh = 10 * log10(vv), 10 * log10(hh)

        return {'vv': vv, 'hh': hh}
Example #29
0
def computeEntropy(spn, f1, verbose=False):
        
    Px = spn.marginalizeToEquation([f1])
    
    sumHxy = "{Px} * log({Px})/log(2)".format(**{'Px': Px})
    
    evl = compileEq(sumHxy, {"x_%s_" % f1: "x"})
    
    Hx = -nsum(lambda x: evl(int(x)), [0, inf], verbose=False, method="d", tol=10 ** (-10))
    
    if verbose:
        print("H(%s)=%s" % (f1, Hx))

    return Hx
Example #30
0
    def nRCS(self, n='richardson+shanks', kind='isotropic gaussian', db=False):
        """Normalized Radar cross-section"""

        def _nRCS(self, pp, n, kind):
            n = float(n)
            return self.wk**2 * exp(-2*(self.sh*self.wk_z)**2) /2 * \
                   ( self.sh**(2*n) * abs( self.I(n)[pp] )**2 * \
                     roughness.spectrum(self.wk, self.sh, self.cl, self.th, \
                     n=n, kind=kind) / factorial(n) )

        if type(n) is not str:
            vv = nsum(lambda x: _nRCS(self, 'vv', x, kind), [1,n] )
            hh = nsum(lambda x: _nRCS(self, 'hh', x, kind), [1,n] )

        if type(n) is str:
            vv = nsum(lambda x: _nRCS(self, 'vv', x, kind), [1,inf], method=n)
            hh = nsum(lambda x: _nRCS(self, 'hh', x, kind), [1,inf], method=n)

        vv, hh = float64(vv), float64(hh)

        if db :
            vv, hh = 10*log10(vv), 10*log10(hh)

        return {'vv':vv, 'hh':hh}
Example #31
0
def cramerVonMises(x, y):

    try:
        x = sorted(x)
        y = sorted(y)

        pool = x + y

        ps, pr = _sortRank(pool)

        rx = array([pr[ind] for ind in [ps.index(element) for element in x]])
        ry = array([pr[ind] for ind in [ps.index(element) for element in y]])

        n = len(x)
        m = len(y)

        i = array(range(1, n + 1))
        j = array(range(1, m + 1))

        u = n * sum(power((rx - i), 2)) + m * sum(power((ry - j), 2))

        t = u / (n * m * (n + m)) - (4 * n * m - 1) / (6 * (n + m))
        Tmu = 1 / 6 + 1 / (6 * (n + m))
        Tvar = 1 / 45 * ((m + n + 1) / power(
            (m + n), 2)) * (4 * m * n * (m + n) - 3 *
                            (power(m, 2) + power(n, 2)) - 2 * m * n) / (4 * m *
                                                                        n)
        t = (t - Tmu) / power(45 * Tvar, 0.5) + 1 / 6

        if t < 0:
            return -1
        elif t <= 12:
            a = 1 - mp.nsum(
                lambda x:
                (mp.gamma(x + 0.5) /
                 (mp.gamma(0.5) * mp.fac(x))) * mp.power(4 * x + 1, 0.5) * mp.
                exp(-mp.power(4 * x + 1, 2) /
                    (16 * t)) * mp.besselk(0.25,
                                           mp.power(4 * x + 1, 2) / (16 * t)),
                [0, 100]) / (mp.pi * mp.sqrt(t))
            return float(mp.nstr(a, 3))
        else:
            return 0
    except Exception as e:
        print e
        return -1
Example #32
0
def cdf(x, dfn, dfd, nc):
    """
    CDF of the noncentral F distribution.
    """
    if x < 0:
        return _mp.mp.zero

    def _cdfk(k):
        return _cdf_term(k, x, dfn, dfd, nc)

    with _mp.extradps(5):
        x = _mp.mpf(x)
        dfn = _mp.mpf(dfn)
        dfd = _mp.mpf(dfd)
        nc = _mp.mpf(nc)
        p = _mp.nsum(_cdfk, [0, _mp.inf])
        return p
Example #33
0
def internal_energy(V):
    """Average internal energy of the system

    E = E(V)  Internal energy states of the SHO change depending on volume

    Calculates: 
    <E> = sum [ E_i exp( - E_i * beta ) ]/ Z

    w/ Z = Z(V) = cononical enbsemble

    Args
    ---
    V (float) : Volume of the system, 

    """
    return float(mp.nsum(
        lambda x: Ei(x, V) * mp.exp(-beta*Ei(x, V)), [0,mp.inf], method='s+r') 
        / canonical_ensemble(V) )
Example #34
0
    def test_cf(dist, support_lower_limit, support_upper_limit):
        pdf = density(dist)
        t = S('t')
        x = S('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.nsum(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
Example #35
0
def moment(a, i, j):
    '''
    Calculates the j-th moment of phi_i

    Wavelet Analysis: The Scalable Structure of Information (2002)
    Howard L. Resnikoff, Raymond O.Jr. Wells
    page 262
    '''
    N = a.size

    assert j > -1

    if j == 0:
        return 1 if i == 0 else 0

    if i == 0:
        return moment_i0(a, j)

    return mpmath.nsum(lambda k: binomial(j,k)*mpmath.power(i, (j-k))*moment_i0(a, k), [0, j])
Example #36
0
def getNthMenageNumber(n):
    '''https://oeis.org/A000179'''
    if n == 1:
        return -1

    if n == 2:
        return 0

    if n in [0, 3]:
        return 1

    return nsum(
        lambda k: fdiv(
            fprod([
                power(-1, k),
                fmul(2, n),
                binomial(fsub(fmul(2, n), k), k),
                fac(fsub(n, k))
            ]), fsub(fmul(2, n), k)), [0, n])
Example #37
0
def hypsum(expr, n, start, prec):
    """
    Sum a rapidly convergent infinite hypergeometric series with
    given general term, e.g. e = hypsum(1/factorial(n), n). The
    quotient between successive terms must be a quotient of integer
    polynomials.
    """
    from sympy import Float, hypersimp, lambdify

    if prec == float('inf'):
        raise NotImplementedError('does not support inf prec')

    if start:
        expr = expr.subs(n, n + start)
    hs = hypersimp(expr, n)
    if hs is None:
        raise NotImplementedError("a hypergeometric series is required")
    num, den = hs.as_numer_denom()

    func1 = lambdify(n, num)
    func2 = lambdify(n, den)

    h, g, p = check_convergence(num, den, n)

    if h < 0:
        raise ValueError("Sum diverges like (n!)^%i" % (-h))

    term = expr.subs(n, 0)
    if not term.is_Rational:
        raise NotImplementedError("Non rational term functionality is not implemented.")

    # Direct summation if geometric or faster
    if h > 0 or (h == 0 and abs(g) > 1):
        term = (MPZ(term.p) << prec) // term.q
        s = term
        k = 1
        while abs(term) > 5:
            term *= MPZ(func1(k - 1))
            term //= MPZ(func2(k - 1))
            s += term
            k += 1
        return from_man_exp(s, -prec)
    else:
        alt = g < 0
        if abs(g) < 1:
            raise ValueError("Sum diverges like (%i)^n" % abs(1/g))
        if p < 1 or (p == 1 and not alt):
            raise ValueError("Sum diverges like n^%i" % (-p))
        # We have polynomial convergence: use Richardson extrapolation
        vold = None
        ndig = prec_to_dps(prec)
        while True:
            # Need to use at least quad precision because a lot of cancellation
            # might occur in the extrapolation process; we check the answer to
            # make sure that the desired precision has been reached, too.
            prec2 = 4*prec
            term0 = (MPZ(term.p) << prec2) // term.q

            def summand(k, _term=[term0]):
                if k:
                    k = int(k)
                    _term[0] *= MPZ(func1(k - 1))
                    _term[0] //= MPZ(func2(k - 1))
                return make_mpf(from_man_exp(_term[0], -prec2))

            with workprec(prec):
                v = nsum(summand, [0, mpmath_inf], method='richardson')
            vf = Float(v, ndig)
            if vold is not None and vold == vf:
                break
            prec += prec  # double precision each time
            vold = vf

        return v._mpf_