Пример #1
0
def cheb_sum(x):
    s = p0()*SP.eval_chebyt(0,x) +\
        p1()*SP.eval_chebyt(1,x) +\
        p2()*SP.eval_chebyt(2,x) +\
        p3()*SP.eval_chebyt(3,x) +\
        p4()*SP.eval_chebyt(4,x)
    return s
Пример #2
0
    def cheb_one_pressure(alpha, tlim, plim, temps, pressure):
        """ Calculates T,P-dependent rate constants [k(T,P)]s using
            a Chebyshev functional expression, at a given pressure,
            across several temperatures.
        """

        tmin, tmax = tlim
        pmin, pmax = plim
        alpha_nrows, alpha_ncols = alpha.shape

        ktps = np.zeros(len(temps))
        for i, temp in enumerate(temps):
            ctemp = ((2.0 * temp**(-1) - tmin**(-1) - tmax**(-1)) /
                     (tmax**(-1) - tmin**(-1)))
            cpress = (
                (2.0 * np.log10(pressure) - np.log10(pmin) - np.log10(pmax)) /
                (np.log10(pmax) - np.log10(pmin)))

            logktp = 0.0
            for j in range(alpha_nrows):
                for k in range(alpha_ncols):
                    logktp += (alpha[j][k] * eval_chebyt(j, ctemp) *
                               eval_chebyt(k, cpress))

            ktps[i] = 10**(logktp)

        return ktps
Пример #3
0
def cheby_band(w, w1, w2, N, ripple=1, scale=0.95):
    """
    Simple Chebyshev Type I bandpass filter function in wavelength space.

    Parameters
    ----------
    w : astropy.units.Quantity
        Wavelength
    w1 : astropy.units.Quantity
        Wavelength of short wavelength edge of bandpass
    w2 : astropy.units.Quantity
        Wavelength of long wavelength edge of bandpass
    N : int
        Order of the Chebyshev function
    ripple : float, optional
        Scaling to apply to the ripple of the Chebyshev function, default
        1.0
    scale : float, optional
        Scaling to apply to the transmission of the Chebyshev function,
        default 0.95

    Returns
    -------
    transmission : astropy.units.Quantity
        Filter transmission at wavelength `w`.
    """
    # Bandpass implemented as low pass and high pass in series
    w = ensure_unit(w, u.nm)
    g1 = 1 / np.sqrt(1 + ripple**2 * eval_chebyt(N, (w1/w).to(u.dimensionless_unscaled).value)**2)
    g2 = 1 / np.sqrt(1 + ripple**2 * eval_chebyt(N, (w/w2).to(u.dimensionless_unscaled).value)**2)
    return scale * g1 * g2
Пример #4
0
def Em_cheb_der(x):
    s = np.sign(cheb_sum(x))
    return 2.*s*np.array([\
        SP.eval_chebyt(0,x) ,\
        SP.eval_chebyt(1,x) ,\
        SP.eval_chebyt(2,x) ,\
        SP.eval_chebyt(3,x) ,\
        SP.eval_chebyt(4,x)  ])
Пример #5
0
def test_chebyshev():
    allTrue = True
    for order in range(ORDER_MAX):
        x = np.random.rand(1).item()
        valuePy = sp.eval_chebyt(order, x)
        valueCpp = NumCpp.chebyshev_t_Scaler(order, x)
        if np.round(valuePy, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    assert allTrue

    allTrue = True
    for order in range(ORDER_MAX):
        shapeInput = np.random.randint(10, 100, [
            2,
        ], dtype=np.uint32)
        shape = NumCpp.Shape(*shapeInput)
        cArray = NumCpp.NdArray(shape)
        x = np.random.rand(*shapeInput)
        cArray.setArray(x)
        valuePy = sp.eval_chebyt(order, x)
        valueCpp = NumCpp.chebyshev_t_Array(order, cArray)
        if not np.array_equal(np.round(valuePy, DECIMALS_ROUND),
                              np.round(valueCpp, DECIMALS_ROUND)):
            allTrue = False

    assert allTrue

    allTrue = True
    for order in range(ORDER_MAX):
        x = np.random.rand(1).item()
        valuePy = sp.eval_chebyu(order, x)
        valueCpp = NumCpp.chebyshev_u_Scaler(order, x)
        if np.round(valuePy, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    assert allTrue

    allTrue = True
    for order in range(ORDER_MAX):
        shapeInput = np.random.randint(10, 100, [
            2,
        ], dtype=np.uint32)
        shape = NumCpp.Shape(*shapeInput)
        cArray = NumCpp.NdArray(shape)
        x = np.random.rand(*shapeInput)
        cArray.setArray(x)
        valuePy = sp.eval_chebyu(order, x)
        valueCpp = NumCpp.chebyshev_u_Array(order, cArray)
        if not np.array_equal(np.round(valuePy, DECIMALS_ROUND),
                              np.round(valueCpp, DECIMALS_ROUND)):
            allTrue = False

    assert allTrue
Пример #6
0
def cheby_band(w, w1, w2, N, ripple=1, peak=0.95):
    """
    Simple Chebyshev Type I bandpass filter function in wavelength space
    To be more realistic this should definitely include cone angle effect 
    but at f/5.34 (Space Eye focal ratio) that is pretty insignficant    
    """
    # Bandpass implemented as low pass and high pass in series
    g1 = 1 / np.sqrt(1 + ripple**2 * eval_chebyt(N, (
        w1 / w).to(u.dimensionless_unscaled).value)**2)
    g2 = 1 / np.sqrt(1 + ripple**2 * eval_chebyt(N, (
        w / w2).to(u.dimensionless_unscaled).value)**2)
    return peak * g1 * g2
Пример #7
0
def chebyshev_one_pressure(alpha, tmin, tmax, pmin, pmax, temps, pressure):
    """ Calculates T,P-dependent rate constants [k(T,P)]s using
        a Chebyshev functional expression, at a given pressure,
        across several temperatures.

        :param alpha: Chebyshev coefficient matrix
        :type alpha: numpy.ndarray
        :param tmin: minimum temperature Chebyshev model is defined
        :type tmin: float
        :param tmax: maximum temperature Chebyshev model is defined
        :type tmax: float
        :param pmin: minimum pressure Chebyshev model is defined
        :type pmin: float
        :param pmax: maximum pressure Chebyshev model is defined
        :type pmax: float
        :param temps: Temps used to calculate high- and low-k(T)s
        :type temps: numpy.ndarray
        :param pressure: Pressure used to calculate k(T,P)s
        :type pressure: float
        :return ktps: Set of k(T,P)s at given pressure
        :rtype numpy.ndarray
    """

    alpha_nrows, alpha_ncols = alpha.shape

    ktps = np.zeros(len(temps))
    for i, temp in enumerate(temps):
        ctemp = (
            (2.0 * 1/temp - 1/tmin - 1/tmax) /
            (1/tmax - 1/tmin)
        )
        cpress = (
            (2.0 * np.log10(pressure) - np.log10(pmin) - np.log10(pmax)) /
            (np.log10(pmax) - np.log10(pmin))
        )

        logktp = 0.0
        for j in range(alpha_nrows):
            for k in range(alpha_ncols):
                logktp += (
                    alpha[j][k] *
                    eval_chebyt(j, ctemp) *
                    eval_chebyt(k, cpress)
                )

        ktps[i] = 10**(logktp)

    return ktps
Пример #8
0
 def evaluate_basis(self, x, i=0, output_array=None):
     x = np.atleast_1d(x)
     if output_array is None:
         output_array = np.zeros(x.shape)
     #output_array[:] = np.cos(i*np.arccos(x))
     output_array[:] = eval_chebyt(i, x)
     return output_array
Пример #9
0
 def test_chebyshev_matrices(self):
     # test that it works on matrices too
     key = jax.random.PRNGKey(0)
     xx = jax.random.normal(key, shape=(5, 10))
     for i in range(10):
         poly0 = chebyshev.eval_chebyt(i, xx)
         poly1 = special.eval_chebyt(i, xx)
         np.testing.assert_allclose(poly0, poly1, rtol=1E-4)
Пример #10
0
def test_chebyshev():
    if NumCpp.NO_USE_BOOST:
        return

    for order in range(ORDER_MAX):
        x = np.random.rand(1).item()
        valuePy = sp.eval_chebyt(order, x)
        valueCpp = NumCpp.chebyshev_t_Scaler(order, x)
        assert np.round(valuePy,
                        DECIMALS_ROUND) == np.round(valueCpp, DECIMALS_ROUND)

    for order in range(ORDER_MAX):
        shapeInput = np.random.randint(10, 100, [
            2,
        ], dtype=np.uint32)
        shape = NumCpp.Shape(*shapeInput)
        cArray = NumCpp.NdArray(shape)
        x = np.random.rand(*shapeInput)
        cArray.setArray(x)
        valuePy = sp.eval_chebyt(order, x)
        valueCpp = NumCpp.chebyshev_t_Array(order, cArray)
        assert np.array_equal(np.round(valuePy, DECIMALS_ROUND),
                              np.round(valueCpp, DECIMALS_ROUND))

    for order in range(ORDER_MAX):
        x = np.random.rand(1).item()
        valuePy = sp.eval_chebyu(order, x)
        valueCpp = NumCpp.chebyshev_u_Scaler(order, x)
        assert np.round(valuePy,
                        DECIMALS_ROUND) == np.round(valueCpp, DECIMALS_ROUND)

    for order in range(ORDER_MAX):
        shapeInput = np.random.randint(10, 100, [
            2,
        ], dtype=np.uint32)
        shape = NumCpp.Shape(*shapeInput)
        cArray = NumCpp.NdArray(shape)
        x = np.random.rand(*shapeInput)
        cArray.setArray(x)
        valuePy = sp.eval_chebyu(order, x)
        valueCpp = NumCpp.chebyshev_u_Array(order, cArray)
        assert np.array_equal(np.round(valuePy, DECIMALS_ROUND),
                              np.round(valueCpp, DECIMALS_ROUND))
Пример #11
0
def evaluate(cheby1d, x):
    """ チェビシェフ辞書にxの値を代入した結果を評価する.

    引数:
        cheby1d 評価対象のチェビシェフ辞書.
        x       xの値.floatを想定(多分sympy値でも動く).

    返り値:
        floatまたはsympy値型の評価結果.
    """
    return sum(eval_chebyt(i, x) * v for i, v in cheby1d.items())
 def approx_weights(self):
     """
     Returns the weights of the Chebyshev regression using Chebyshev
     polynomials up to 'order'.  Number of approximation nodes = gridsize.
     Returns an array of order + 1 floats.
     """
     theta = np.zeros(self.order + 1)
     theta[0] = np.mean(self.func_vals)
     for j in range(1, self.order + 1):
         tj = eval_chebyt(j, self.roots)
         theta[j] = (2.0 / self.gridsize) * np.sum(tj * self.func_vals)
     return theta
Пример #13
0
def chebyshev_basis_2D(x, y, n):
    a = np.array([])
    b = np.array([])

    for i in range(n + 1):
        for j in range(n + 1):
            if (i + j) < (n + 1):
                a = np.append(a, i)
                b = np.append(b, j)

    A = np.zeros((len(x), len(a)))
    xx = x.copy() - x.min()
    xx /= xx.max() / 2
    xx -= 1
    yy = y.copy() - y.min()
    yy /= yy.max() / 2
    yy -= 1

    for i in range(len(a)):
        A[:, i] = special.eval_chebyt(a[i], xx) * special.eval_chebyt(b[i], yy)

    return A
 def __call__(self, eval_grid):
     """
     Evaluate the approximation at the points in array eval_grid.
     Returns an array of floats.
     """
     z_vec = self.to_regular(eval_grid)
     j = np.array(range(self.order + 1), dtype=int)
     K = len(z_vec)
     vals = np.empty(K)
     for k in range(K):
         y = np.sum(self.theta * eval_chebyt(j, z_vec[k]))
         vals[k] = y
     return np.array(vals)
Пример #15
0
def chebyshev_rate_constants(temps, pressure, alpha, tmin, tmax, pmin, pmax):
    """ computes the rate constants using the chebyshev polynomials
    """
    alpha_nrows, alpha_ncols = alpha.shape

    ktps = np.zeros(len(temps))
    for i, temp in enumerate(temps):
        ctemp = ((2.0 * temp**(-1) - tmin**(-1) - tmax**(-1)) /
                 (tmax**(-1) - tmin**(-1)))
        cpress = (
            (2.0 * np.log10(pressure) - np.log10(pmin) - np.log10(pmax)) /
            (np.log10(pmax) - np.log10(pmin)))

        logktp = 0.0
        for j in range(alpha_nrows):
            for k in range(alpha_ncols):
                logktp += (alpha[j][k] * eval_chebyt(j, ctemp) *
                           eval_chebyt(k, cpress))

        ktps[i] = 10**(logktp)

    return ktps
Пример #16
0
def value_at_a_point(x, An):
    """Evaluates a spectral function at a given spectral point given
    the value of the Spectral Coordinate and the set of Spectral Coefficients of the Function."""

    # Estimating the Number of Spectral Coefficients/Collocation Points:
    N = An.size - 1

    # Initializing the value
    value_at_point = 0.0

    # Adding the contribution of each Spectral Mode:
    for ns in range(0, N + 1):
        # Value of the n-th Chebyshev Polynomial at the given spectral coordinate:
        T_nn_x = special.eval_chebyt(ns, x)
        value_at_point += An[ns] * T_nn_x

    return value_at_point
Пример #17
0
    def _eval_numpy_(self, n, x):
        """
        Evaluate ``self`` using numpy.

        EXAMPLES::

            sage: import numpy
            sage: z = numpy.array([1,2])
            sage: z2 = numpy.array([[1,2],[1,2]])
            sage: z3 = numpy.array([1,2,3.])
            sage: chebyshev_T(1,z)
            array([ 1.,  2.])
            sage: chebyshev_T(1,z2)
            array([[ 1.,  2.],
                   [ 1.,  2.]])
            sage: chebyshev_T(1,z3)
            array([ 1.,  2.,  3.])
            sage: chebyshev_T(z,0.1)
            array([ 0.1 , -0.98])
        """
        from scipy.special import eval_chebyt
        return eval_chebyt(n, x)
Пример #18
0
    def _eval_numpy_(self, n, x):
        """
        Evaluate ``self`` using numpy.

        EXAMPLES::

            sage: import numpy
            sage: z = numpy.array([1,2])
            sage: z2 = numpy.array([[1,2],[1,2]])
            sage: z3 = numpy.array([1,2,3.])
            sage: chebyshev_T(1,z)
            array([ 1.,  2.])
            sage: chebyshev_T(1,z2)
            array([[ 1.,  2.],
                   [ 1.,  2.]])
            sage: chebyshev_T(1,z3)
            array([ 1.,  2.,  3.])
            sage: chebyshev_T(z,0.1)
            array([ 0.1 , -0.98])
        """
        from scipy.special import eval_chebyt
        return eval_chebyt(n, x)
Пример #19
0
 def eval_basis(ind, x):
     result = 1
     for i in range(self.dim):
         coord = (x[i] - self.center[i]) / (self.h / 2)
         result *= eval_chebyt(ind[i], coord)
     return result
Пример #20
0
 def ceb2(x):
     return spec.eval_chebyt(p, x / 95)
Пример #21
0
 def approx_integral(i):
     """
     Approximates the integral by taking the mean value
     of n sample points
     """
     return sum(eval_chebyt(i, 2. * xj - 1.) for xj in x) / n
def T(j,u,N,x1,x2):
    m = get_slope_intercept(x1,x2)[0]
    b = get_slope_intercept(x1,x2)[1]
    return eval_chebyt(j,m*u+b)
Пример #23
0
            q1 = q2
            q2 = q3
        moments = np.mean(G, axis=0)
        inputs = np.insert(moments, 0, 1)
        pickle.dump(inputs, open('chebyshevmoments' + str(K), "wb"))

        #% compute Chebyshev polynomial
        x = np.linspace(gmin, gmax, gridlength)

        v = np.diff(x)
        v = np.append(v, 0)
        n = len(inputs)

        chebarray = np.zeros((n, int(gridlength)))
        for i1 in range(0, n):
            q = (special.eval_chebyt(i1, x, out=None))
            chebarray[i1, :] = q

        typec = 'chebyshev'

        #% MaxEnt Algorithm
        entr = []
        momnum = []
        sharpness = (1e-3)

        #% store datas
        #Y = np.zeros((m,int(gridlength)))
        MaxEntdistri = np.zeros((m, int(gridlength)))
        MaxEntCoefficient = []
        Xbound = np.zeros(m)
        Prediction = np.zeros(m)
Пример #24
0
 def cons(alpha):
     j = 1 + np.dot(alpha, chebarray[:-(n - m)])
     q = np.exp(-j)
     u = sum(q * ((special.eval_chebyt(alpha, x, out=None))) * v)
     return u
Пример #25
0
 def eval_basis(ind, x):
     result = 1
     for i in range(self.dim):
         coord = (x[i] - self.center[i])/(self.h/2)
         result *= eval_chebyt(ind[i], coord)
     return result
Пример #26
0
# -*- coding: utf-8 -*-

import os
import scipy
from scipy.special import airy, jn, eval_chebyt, eval_legendre

subplot(2, 2, 3)
x = linspace(-1, 1)
for i in range(6):
    plot(x, eval_chebyt(i, x))
title("Chebyshev polynomials of the first kind")

os.system("pause")
Пример #27
0
 def test_chebyt_int(self):
     assert_mpmath_equal(lambda n, x: sc.eval_chebyt(int(n), x),
                         _exception_to_nan(lambda n, x: mpmath.chebyt(n, x, **HYPERKW)),
                         [IntArg(), Arg()],
                         n=2000)
Пример #28
0
 def mesanaceb(x, y):
     return spec.eval_chebyt(p1, x / 200) * spec.eval_chebyt(p2, y / 200)
Пример #29
0
def kfit(temps, ktp_dct, tdeg=6, pdeg=4, a_conv_factor=1):
    """ Fits T,P-dependent rate constants [k(T,P)]s to a
        a Chebyshev functional expression.

        :param alpha: Chebyshev coefficient matrix
        :type alpha: np.ndarray
        :param tdeg: degree of the temp component of Chebyshev polynomial
        :type tdeg: int
        :param pdeg: degree of the pressure component of Chebyshev polynomial
        :type pdeg: int
        :param temps: Temps used to calculate high- and low-k(T)s
        :type temps: np.ndarray
        :param pressure: Pressure used to calculate k(T,P)s
        :type pressure: float
        :return alpha: alpha fitting coefficients
        :rtype np.ndarray
    """

    # Get the pressures from the ktp_dct
    pressures = tuple(pressure for pressure in ktp_dct.keys()
                      if pressure != 'high')

    # Determine the number and range of temperatures and pressures
    tnum, pnum = len(temps), len(pressures)
    tmin, tmax = min(temps), max(temps)
    pmin, pmax = min(pressures), max(pressures)

    # Calculate the reduced temperatures and pressures
    tred = []
    for temp in temps:
        tred.append(
            (2.0 * temp**(-1) - tmin**(-1) - tmax**(-1)) /
            (tmax**(-1) - tmin**(-1))
        )

    pred = []
    for pressure in pressures:
        pred.append(
            (2.0 * np.log10(pressure) - np.log10(pmin) - np.log10(pmax)) /
            (np.log10(pmax) - np.log10(pmin))
        )

    # Build a numpy array for the fits
    ktps = conv_dct_to_array(ktp_dct, temps, a_conv_factor=a_conv_factor)

    # Create matrices for fits
    A = np.zeros((tnum * pnum, tdeg * pdeg), np.float64)
    b = np.zeros((tnum * pnum), np.float64)
    nzero = 0
    for t1, T in enumerate(tred):
        for p1, P in enumerate(pred):
            for t2 in range(tdeg):
                for p2 in range(pdeg):
                    idx1, idx2 = (p1 * tnum + t1), (p2 * tdeg + t2)
                    A[idx1, idx2] = eval_chebyt(t2, T) * eval_chebyt(p2, P)
            if ktps[t1, p1] is not None:
                b[idx1] = np.log10(ktps[t1, p1])
            else:
                b[idx1] = None
                nzero += 1

    nnonzero = tnum * pnum - nzero
    idxp = -1
    Ap = np.zeros((nnonzero, tdeg * pdeg), np.float64)
    bp = np.zeros((nnonzero), np.float64)
    for idx in range(tnum*pnum):
        if not np.isnan(b[idx]):
            idxp += 1
            bp[idxp] = b[idx]
            for idx2 in range(tdeg*pdeg):
                Ap[idxp,idx2] = A[idx,idx2]

        
    # Perform least-squares fit to get alpha coefficients
    theta = np.linalg.lstsq(Ap, bp, rcond=RCOND)[0]

    alpha = np.zeros((tdeg, pdeg), np.float64)
    for t2 in range(tdeg):
        for p2 in range(pdeg):
            alpha[t2, p2] = theta[p2 * tdeg + t2]

    return alpha, (tmin, tmax), (pmin, pmax)
Пример #30
0
 def test_chebyt_int(self):
     assert_mpmath_equal(
         lambda n, x: sc.eval_chebyt(int(n), x),
         _exception_to_nan(lambda n, x: mpmath.chebyt(n, x, **HYPERKW)),
         [IntArg(), Arg()],
         n=2000)
Пример #31
0
 def test_chebyshev(self):
     xx = jnp.linspace(-5, 5)
     for i in range(10):
         poly0 = chebyshev.eval_chebyt(i, xx)
         poly1 = special.eval_chebyt(i, xx)
         np.testing.assert_allclose(poly0, poly1, rtol=1E-5)
Пример #32
0
 def ceb(x):
     return spec.eval_chebyt(p, x / 200)
Пример #33
0
    svdo[i] = np.array([(tov[i]) * 0.0010000] * nlat)
    svd[i] = np.array([(sv.speed[i]) * 0.0010000] * nlat)
svpo = [svdo[0]]
svp = [svd[0]]
for i in range(1, ndep):
    svpo = np.append(svpo, [svdo[i]], axis=0)
    svp = np.append(svp, [svd[i]], axis=0)
o0 = np.array([svpo] * nlon)
a0 = np.array([svp] * nlon)
########## com model
svp = [[] for s in range(nlon)]
chet = np.arange(o_chet + 1, dtype=float)
for s in range(nlon):
    achet = 0
    for c in range(o_chet + 1):
        chet[c] = eval_chebyt(c, (s - slon) / slon)
        achet = c_chet[c] * chet[c] + achet
    achet = achet / d_chet
    svc = [[] for i in range(ndep)]
    for i in range(0, m_s_dp[0]):
        svc[i] = np.array([m_s_km[0] * 0.001 * 0.1 * 0.5 * achet] * nlat)
#    svc[i] = np.array([m_s_km[0]*0.001*0.1*(1./float(2*slon))*float(s-slon)] * nlat)
    for i in range(m_s_dp[0], m_s_dp[1]):
        svc[i] = np.array([m_s_km[1] * 0.001 * 0.1 * 0.5 * achet] * nlat)
#    svc[i] = np.array([m_s_km[1]*0.001*0.1*(1./float(2*slon))*float(s-slon)] * nlat)
    for i in range(m_s_dp[1], ndep):
        svc[i] = np.array([m_s_km[2] * 0.001 * 0.1 * 0.5 * achet] * nlat)
#    svc[i] = np.array([m_s_km[2]*0.001*0.1*(1./float(2*slon))*float(s-slon)] * nlat)
    svp[s] = [svc[0]]
    for i in range(1, ndep):
        svp[s] = np.append(svp[s], [svc[i]], axis=0)
Пример #34
0
def testFunctions():
    print(colored('Testing Polynomial functions', 'magenta'))
    ORDER_MAX = 5
    DECIMALS_ROUND = 7

    print(colored('Testing chebyshev_t_Scaler', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        x = np.random.rand(1).item()
        valuePy = sp.eval_chebyt(order, x)
        valueCpp = NumCpp.chebyshev_t_Scaler(order, x)
        if np.round(valuePy, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))
        print(f'valuePy = {valuePy}, valueCpp = {valueCpp}')

    print(colored('Testing chebyshev_t_Array', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        shapeInput = np.random.randint(10, 100, [
            2,
        ], dtype=np.uint32)
        shape = NumCpp.Shape(*shapeInput)
        cArray = NumCpp.NdArray(shape)
        x = np.random.rand(*shapeInput)
        cArray.setArray(x)
        valuePy = sp.eval_chebyt(order, x)
        valueCpp = NumCpp.chebyshev_t_Array(order, cArray)
        if not np.array_equal(np.round(valuePy, DECIMALS_ROUND),
                              np.round(valueCpp, DECIMALS_ROUND)):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))

    print(colored('Testing chebyshev_u_Scaler', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        x = np.random.rand(1).item()
        valuePy = sp.eval_chebyu(order, x)
        valueCpp = NumCpp.chebyshev_u_Scaler(order, x)
        if np.round(valuePy, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))
        print(f'valuePy = {valuePy}, valueCpp = {valueCpp}')

    print(colored('Testing chebyshev_u_Array', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        shapeInput = np.random.randint(10, 100, [
            2,
        ], dtype=np.uint32)
        shape = NumCpp.Shape(*shapeInput)
        cArray = NumCpp.NdArray(shape)
        x = np.random.rand(*shapeInput)
        cArray.setArray(x)
        valuePy = sp.eval_chebyu(order, x)
        valueCpp = NumCpp.chebyshev_u_Array(order, cArray)
        if not np.array_equal(np.round(valuePy, DECIMALS_ROUND),
                              np.round(valueCpp, DECIMALS_ROUND)):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))

    print(colored('Testing hermite_Scaler', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        x = np.random.rand(1).item()
        valuePy = sp.eval_hermite(order, x)
        valueCpp = NumCpp.hermite_Scaler(order, x)
        if np.round(valuePy, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))
        print(f'valuePy = {valuePy}, valueCpp = {valueCpp}')

    print(colored('Testing hermite_Array', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        shapeInput = np.random.randint(10, 100, [
            2,
        ], dtype=np.uint32)
        shape = NumCpp.Shape(*shapeInput)
        cArray = NumCpp.NdArray(shape)
        x = np.random.rand(*shapeInput)
        cArray.setArray(x)
        valuePy = sp.eval_hermite(order, x)
        valueCpp = NumCpp.hermite_Array(order, cArray)
        if not np.array_equal(np.round(valuePy, DECIMALS_ROUND),
                              np.round(valueCpp, DECIMALS_ROUND)):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))

    print(colored('Testing laguerre_Scaler1', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        x = np.random.rand(1).item()
        valuePy = sp.eval_laguerre(order, x)
        valueCpp = NumCpp.laguerre_Scaler1(order, x)
        if np.round(valuePy, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))
        print(f'valuePy = {valuePy}, valueCpp = {valueCpp}')

    print(colored('Testing laguerre_Array1', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        shapeInput = np.random.randint(10, 100, [
            2,
        ], dtype=np.uint32)
        shape = NumCpp.Shape(*shapeInput)
        cArray = NumCpp.NdArray(shape)
        x = np.random.rand(*shapeInput)
        cArray.setArray(x)
        valuePy = sp.eval_laguerre(order, x)
        valueCpp = NumCpp.laguerre_Array1(order, cArray)
        if not np.array_equal(np.round(valuePy, DECIMALS_ROUND),
                              np.round(valueCpp, DECIMALS_ROUND)):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))

    print(colored('Testing laguerre_Scaler2', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        degree = np.random.randint(0, 10, [
            1,
        ]).item()
        x = np.random.rand(1).item()
        valuePy = sp.eval_genlaguerre(degree, order, x)
        valueCpp = NumCpp.laguerre_Scaler2(order, degree, x)
        if np.round(valuePy, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))
        print(f'valuePy = {valuePy}, valueCpp = {valueCpp}')

    print(colored('Testing laguerre_Array2', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        degree = np.random.randint(0, 10, [
            1,
        ]).item()
        shapeInput = np.random.randint(10, 100, [
            2,
        ], dtype=np.uint32)
        shape = NumCpp.Shape(*shapeInput)
        cArray = NumCpp.NdArray(shape)
        x = np.random.rand(*shapeInput)
        cArray.setArray(x)
        valuePy = sp.eval_genlaguerre(degree, order, x)
        valueCpp = NumCpp.laguerre_Array2(order, degree, cArray)
        if not np.array_equal(np.round(valuePy, DECIMALS_ROUND),
                              np.round(valueCpp, DECIMALS_ROUND)):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))

    print(colored('Testing legendre_p_Scaler1', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        x = np.random.rand(1).item()
        valuePy = sp.eval_legendre(order, x)
        valueCpp = NumCpp.legendre_p_Scaler1(order, x)
        if np.round(valuePy, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))
        print(f'valuePy = {valuePy}, valueCpp = {valueCpp}')

    print(colored('Testing legendre_p_Array1', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        shapeInput = np.random.randint(10, 100, [
            2,
        ], dtype=np.uint32)
        shape = NumCpp.Shape(*shapeInput)
        cArray = NumCpp.NdArray(shape)
        x = np.random.rand(*shapeInput)
        cArray.setArray(x)
        valuePy = sp.eval_legendre(order, x)
        valueCpp = NumCpp.legendre_p_Array1(order, cArray)
        if not np.array_equal(np.round(valuePy, DECIMALS_ROUND),
                              np.round(valueCpp, DECIMALS_ROUND)):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))

    print(colored('Testing legendre_p_Scaler2', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        x = np.random.rand(1).item()
        degree = np.random.randint(order, ORDER_MAX)
        valuePy = sp.lpmn(order, degree, x)[0][order, degree]
        valueCpp = NumCpp.legendre_p_Scaler2(order, degree, x)
        if np.round(valuePy, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))
        print(f'valuePy = {valuePy}, valueCpp = {valueCpp}')

    print(colored('Testing legendre_q_Scaler', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        x = np.random.rand(1).item()
        valuePy = sp.lqn(order, x)[0][order]
        valueCpp = NumCpp.legendre_q_Scaler(order, x)
        if np.round(valuePy, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))
        print(f'valuePy = {valuePy}, valueCpp = {valueCpp}')

    print(colored('Testing spherical_harmonic', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        degree = np.random.randint(order, ORDER_MAX)
        theta = np.random.rand(1).item() * np.pi * 2
        phi = np.random.rand(1).item() * np.pi
        valuePy = sp.sph_harm(order, degree, theta, phi)
        valueCpp = NumCpp.spherical_harmonic(order, degree, theta, phi)
        if (np.round(valuePy.real, DECIMALS_ROUND) != np.round(
                valueCpp[0], DECIMALS_ROUND)
                or np.round(valuePy.imag, DECIMALS_ROUND) != np.round(
                    valueCpp[1], DECIMALS_ROUND)):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))
        print(f'valuePy = {valuePy}, valueCpp = {valueCpp}')

    print(colored('Testing spherical_harmonic_r', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        degree = np.random.randint(order, ORDER_MAX)
        theta = np.random.rand(1).item() * np.pi * 2
        phi = np.random.rand(1).item() * np.pi
        valuePy = sp.sph_harm(order, degree, theta, phi)
        valueCpp = NumCpp.spherical_harmonic_r(order, degree, theta, phi)
        if np.round(valuePy.real, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))
        print(f'valuePy = {valuePy}, valueCpp = {valueCpp}')

    print(colored('Testing spherical_harmonic_i', 'cyan'))
    allTrue = True
    for order in range(ORDER_MAX):
        degree = np.random.randint(order, ORDER_MAX)
        theta = np.random.rand(1).item() * np.pi * 2
        phi = np.random.rand(1).item() * np.pi
        valuePy = sp.sph_harm(order, degree, theta, phi)
        valueCpp = NumCpp.spherical_harmonic_i(order, degree, theta, phi)
        if np.round(valuePy.imag, DECIMALS_ROUND) != np.round(
                valueCpp, DECIMALS_ROUND):
            allTrue = False

    if allTrue:
        print(colored('\tPASS', 'green'))
    else:
        print(colored('\tFAIL', 'red'))
        print(f'valuePy = {valuePy}, valueCpp = {valueCpp}')
Пример #35
0
def reaction(ktp_dct, temps, tdeg=6, pdeg=4, a_conv_factor=1.0):
    """ Fits T,P-dependent rate constants [k(T,P)]s to a
        a Chebyshev functional expression.

        :param ktp_dct: k(T,P)s
        :type ktp_dct: k(T,P) dictionary
        :param temps: Temps used to calculate high- and low-k(T)s
        :type temps: np.ndarray
        :param tdeg: degree of the temp component of Chebyshev polynomial
        :type tdeg: int
        :param pdeg: degree of the pressure component of Chebyshev polynomial
        :type pdeg: int
        :rtype: (np.ndarray, tuple(float), tuple(float))
    """

    # Get the pressures from the ktp_dct
    pressures = tuple(pressure for pressure in ktp_dct.keys()
                      if pressure != 'high')

    # Determine the number and range of temperatures and pressures
    tnum, pnum = len(temps), len(pressures)
    tmin, tmax = min(temps), max(temps)
    pmin, pmax = min(pressures), max(pressures)

    # Calculate the reduced temperatures and pressures
    tred = []
    for temp in temps:
        tred.append(
            (2.0 * temp**(-1) - tmin**(-1) - tmax**(-1)) /
            (tmax**(-1) - tmin**(-1))
        )

    pred = []
    for pressure in pressures:
        pred.append(
            (2.0 * np.log10(pressure) - np.log10(pmin) - np.log10(pmax)) /
            (np.log10(pmax) - np.log10(pmin))
        )

    # Build a numpy array for the fits
    ktps = conv_dct_to_array(ktp_dct, temps, a_conv_factor=a_conv_factor)

    # Create matrices for fits
    amat = np.zeros((tnum * pnum, tdeg * pdeg), np.float64)
    bvec = np.zeros((tnum * pnum), np.float64)
    nzero = 0
    for tidx1, temp in enumerate(tred):
        for pidx1, press in enumerate(pred):
            for tidx2 in range(tdeg):
                for pidx2 in range(pdeg):
                    idx1 = (pidx1 * tnum + tidx1)
                    idx2 = (pidx2 * tdeg + tidx2)
                    amat[idx1, idx2] = (
                        eval_chebyt(tidx2, temp) * eval_chebyt(pidx2, press)
                    )
            if ktps[tidx1, pidx1] is not None:
                bvec[idx1] = np.log10(ktps[tidx1, pidx1])
            else:
                bvec[idx1] = None
                nzero += 1

    nnonzero = tnum * pnum - nzero
    idxp = -1
    amatp = np.zeros((nnonzero, tdeg * pdeg), np.float64)
    bvecp = np.zeros((nnonzero), np.float64)
    for idx in range(tnum*pnum):
        if not np.isnan(bvec[idx]):
            idxp += 1
            bvecp[idxp] = bvec[idx]
            for idx2 in range(tdeg*pdeg):
                amatp[idxp, idx2] = amat[idx, idx2]

    # Perform least-squares fit to get alpha coefficients
    theta = np.linalg.lstsq(amatp, bvecp, rcond=RCOND)[0]

    alpha = np.zeros((tdeg, pdeg), np.float64)
    for tidx2 in range(tdeg):
        for pidx2 in range(pdeg):
            alpha[tidx2, pidx2] = theta[pidx2 * tdeg + tidx2]

    return alpha, (tmin, tmax), (pmin, pmax)
Пример #36
0
def Tn(n, x):
    return np.where(np.asarray(n) >= 0, eval_chebyt(n, x), 0)
Пример #37
0
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import eval_chebyt

fig = plt.figure()

xvalues = np.linspace(-1, 1, 300)
nmax = 5
for n in range(nmax+1):
    yvalues = eval_chebyt(n, xvalues)
    plt.plot(xvalues, yvalues)
plt.title('Chebyshev polynomials $T_n(x)$ for $n=0,\\ldots,{}$'.format(nmax))
plt.axhline(0, color='gray')
plt.axvline(0, color='gray')
plt.xlabel('$x$')
plt.ylabel('$T_n(x)$')

print('Displaying graph')

plt.show()