Exemplo n.º 1
0
 def in_monomial_basis(self):
     res = poly.Polynomial({poly.MonomialVector({}): 1})
     for v, p in self:
         c = cheb2poly([0] * p + [1])
         basis = poly.MonomialVector.construct_basis([v], p)
         res *= poly.Polynomial(dict(zip(basis, c)))
     return res
Exemplo n.º 2
0
def chebfun_to_poly(fun, text=False):
    low, high = fun._domain
    # Reverse the coefficients, and use cheb2poly to make it in the polynomial domain
    poly_coeffs = cheb2poly(fun.coefficients())[::-1].tolist()
    if not text:
        return poly_coeffs
    s = 'coeffs = %s\n' % poly_coeffs
    delta = high - low
    delta_sum = high + low
    # Generate the expression
    s += 'horner(coeffs, %.18g*(x - %.18g))' % (2.0 / delta, 0.5 * delta_sum)
    # return the string
    return s
Exemplo n.º 3
0
def chebfun_to_poly(fun, text=False):
    from numpy.polynomial.chebyshev import cheb2poly
    low, high = fun._domain
    # Reverse the coefficients, and use cheb2poly to make it in the polynomial domain
    poly_coeffs = cheb2poly(fun.coefficients())[::-1].tolist()
    if not text:
        return poly_coeffs
    s = 'coeffs = %s\n' %poly_coeffs
    delta = high - low
    delta_sum = high + low
    # Generate the expression
    s += 'horner(coeffs, %.18g*(x - %.18g))' %(2.0/delta, 0.5*delta_sum)
    # return the string
    return s
Exemplo n.º 4
0
def chebyshev_transpose_mult_slow(v):
    """Naive multiplication P^T v where P is the matrix of coefficients of
    Chebyshev polynomials.
    Parameters:
        v: (batch_size, n)
    Return:
        P^T v: (batch_size, n)
    """
    n = v.shape[-1]
    # Construct the coefficient matrix P for Chebyshev polynomials
    P = np.zeros((n, n), dtype=np.float32)
    for i, coef in enumerate(np.eye(n)):
        P[i, :i + 1] = chebyshev.cheb2poly(coef)
    P = torch.tensor(P)
    return v @ P
Exemplo n.º 5
0
def conv_cheb(T):
    """
    Convert a chebyshev polynomial to the power basis representation.
    Args:
        T (): The chebyshev polynomial to convert.
    Returns:
        new_conv (): The chebyshev polynomial converted to the power basis representation.

    """
    conv = C.cheb2poly(T)
    if conv.size == T.size:
        return conv
    else:
        pad = T.size - conv.size
        new_conv = np.pad(conv, ((0, pad)), 'constant')
        return new_conv
Exemplo n.º 6
0
def cheb_to_poly(coeffs_or_fun, domain=None):
    '''Just call horner on the outputs!
    '''
    from fluids.numerics import horner as horner_poly

    if isinstance(coeffs_or_fun, Chebfun):
        coeffs = coeffs_or_fun.coefficients()
        domain = coeffs_or_fun._domain
    else:
        coeffs = coeffs_or_fun

    low, high = domain
    coeffs = cheb2poly(coeffs)[::-1].tolist()  # Convert to polynomial basis
    # Mix in limits to make it a normal polynomial
    my_poly = Polynomial(
        [-0.5 * (high + low) * 2.0 / (high - low), 2.0 / (high - low)])
    poly_coeffs = horner_poly(coeffs, my_poly).coef[::-1].tolist()
    return poly_coeffs
Exemplo n.º 7
0
def cheb_to_poly(coeffs_or_fun, domain=None):
    """Just call horner on the outputs!"""
    from fluids.numerics import horner as horner_poly

    if isinstance(coeffs_or_fun, Chebfun):
        coeffs = coeffs_or_fun.coefficients()
        domain = coeffs_or_fun._domain
    elif hasattr(
            coeffs_or_fun, '__class__'
    ) and coeffs_or_fun.__class__.__name__ == 'ChebyshevExpansion':
        coeffs = coeffs_or_fun.coef()
        domain = coeffs_or_fun.xmin(), coeffs_or_fun.xmax()
    else:
        coeffs = coeffs_or_fun

    low, high = domain
    coeffs = cheb2poly(coeffs)[::-1].tolist()  # Convert to polynomial basis
    # Mix in limits to make it a normal polynomial
    my_poly = Polynomial(
        [-0.5 * (high + low) * 2.0 / (high - low), 2.0 / (high - low)])
    poly_coeffs = horner_poly(coeffs, my_poly).coef[::-1].tolist()
    return poly_coeffs
    def test_chebyshev_arithmetic(self):
        print("chebdomain:\t" + str(cbs.chebdomain))
        print("chebzero:\t" + str(cbs.chebzero))
        print("chebone\t:" + str(cbs.chebone))
        print("chebx\t:" + str(cbs.chebx))

        p1 = cbs.chebval(0.2, 4)
        print("P(0.5) = " + str(p1))

        N = 100
        chebyshevMatrix = np.zeros([N, N], dtype=float)
        for zmc in np.arange(N):
            vec = np.zeros([zmc + 1], dtype=float)
            vec[zmc] = 1.
            chebyshevMatrix[zmc, 0:zmc + 1] = cbs.cheb2poly(vec)

        print("Size of Matrix:")
        print(chebyshevMatrix.shape)

        # for zmc in np.arange(chebyshevMatrix.shape[0]):
        #     print(chebyshevMatrix[zmc])
        np.save("chebyshevCoeficientsMatrix100", chebyshevMatrix)
Exemplo n.º 9
0
def conv_cheb(T):
    """
    Convert a Chebyshev polynomial to the power basis representation in one dimension.

    Parameters
    ----------
    T : array_like
        A one dimensional array_like object that represents the coeff of a
        Chebyshev polynomial.

    Returns
    -------
    ndarray
        A one dimensional array that represents the coeff of a power basis polynomial.

    """
    conv = cheb.cheb2poly(T)
    if conv.size == T.size:
        return conv
    else:
        pad = T.size - conv.size
        new_conv = np.pad(conv, ((0, pad)), 'constant')
        return new_conv
Exemplo n.º 10
0
def chebfun_to_poly(coeffs_or_fun, domain=None, text=False):
    if isinstance(coeffs_or_fun, Chebfun):
        coeffs = coeffs_or_fun.coefficients()
        domain = coeffs_or_fun._domain
    elif hasattr(
            coeffs_or_fun, '__class__'
    ) and coeffs_or_fun.__class__.__name__ == 'ChebyshevExpansion':
        coeffs = coeffs_or_fun.coef()
        domain = coeffs_or_fun.xmin(), coeffs_or_fun.xmax()
    else:
        coeffs = coeffs_or_fun

    low, high = domain
    # Reverse the coefficients, and use cheb2poly to make it in the polynomial domain
    poly_coeffs = cheb2poly(coeffs)[::-1].tolist()
    if not text:
        return poly_coeffs
    s = 'coeffs = %s\n' % poly_coeffs
    delta = high - low
    delta_sum = high + low
    # Generate the expression
    s += 'horner(coeffs, %.18g*(x - %.18g))' % (2.0 / delta, 0.5 * delta_sum)
    # return the string
    return s
Exemplo n.º 11
0
 def test_cheb2poly(self) :
     for i in range(10) :
         assert_almost_equal(cheb.cheb2poly([0]*i + [1]), Tlist[i])
Exemplo n.º 12
0
def cheb2poly(cs):
    from numpy.polynomial.chebyshev import cheb2poly
    return cheb2poly(cs)
Exemplo n.º 13
0
def fit_cheb_poly(func, low, high, n,
                  interpolation_property=None, interpolation_property_inv=None,
                  interpolation_x=lambda x: x, interpolation_x_inv=lambda x: x,
                  arg_func=None):
    r'''Fit a function of one variable to a polynomial of degree `n` using the
    Chebyshev approximation technique. Transformations of the base function
    are allowed as lambdas.

    Parameters
    ----------
    func : callable
        Function to fit, [-]
    low : float
        Low limit of fitting range, [-]
    high : float
        High limit of fitting range, [-]
    n : int
        Degree of polynomial fitting, [-]
    interpolation_property : None or callable
        When specified, this callable will transform the output of the function
        before fitting; for example a property like vapor pressure should be
        `interpolation_property=lambda x: log(x)` because it rises
        exponentially. The output of the evaluated polynomial should then have
        the reverse transform applied to it; in this case, `exp`, [-]
    interpolation_property_inv : None or callable
        When specified, this callable reverses `interpolation_property`; it
        must always be provided when `interpolation_property` is set, and it
        must perform the reverse transform, [-]
    interpolation_x : None or callable
        Callable to transform the input variable to fitting. For example,
        enthalpy of vaporization goes from a high value at low temperatures to zero at
        the critical temperature; it is normally hard for a chebyshev series
        to match this, but by setting this to lambda T: log(1. - T/Tc), this
        issue is resolved, [-]
    interpolation_x_inv : None or callable
        Inverse function of `interpolation_x_inv`; must always be provided when
        `interpolation_x` is set, and it must perform the reverse transform,
        [-]
    arg_func : None or callable
        Function which is called with the value of `x` in the original domain,
        and that returns arguments to `func`.

    Returns
    -------
    coeffs : list[float]
        Polynomial coefficients in order for evaluation by `horner`, [-]

    Notes
    -----
    This is powered by Ian Bell's ChebTools.

    '''
    global ChebTools
    if ChebTools is None:
        import ChebTools

    low_orig, high_orig = low, high
    cheb_fun = None
    low, high = interpolation_x(low_orig), interpolation_x(high_orig)
    if arg_func is not None:
        if interpolation_property is not None:
            def func_fun(T):
                arg = interpolation_x_inv(T)
                if arg > high_orig:
                    arg = high_orig
                if arg < low_orig:
                    arg = low_orig
                return interpolation_property(func(arg, *arg_func(arg)))
        else:
            def func_fun(T):
                arg = interpolation_x_inv(T)
                if arg > high_orig:
                    arg = high_orig
                if arg < low_orig:
                    arg = low_orig
                return func(arg, *arg_func(arg))
    else:
        if interpolation_property is not None:
            def func_fun(T):
                arg = interpolation_x_inv(T)
                if arg > high_orig:
                    arg = high_orig
                if arg < low_orig:
                    arg = low_orig
                return interpolation_property(func(arg))
        else:
            def func_fun(T):
                arg = interpolation_x_inv(T)
                if arg > high_orig:
                    arg = high_orig
                if arg < low_orig:
                    arg = low_orig
                return func(arg)
    func_fun = np.vectorize(func_fun)
    if n == 1:
        coeffs = [func_fun(0.5*(low + high)).tolist()]
    else:
        cheb_fun = ChebTools.generate_Chebyshev_expansion(n-1, func_fun, low, high)

        coeffs = cheb_fun.coef()
        coeffs = cheb2poly(coeffs)[::-1].tolist() # Convert to polynomial basis
    # Mix in low high limits to make it a normal polynomial
    if high != low:
        # Handle the case of no transformation, no limits
        my_poly = Polynomial([-0.5*(high + low)*2.0/(high - low), 2.0/(high - low)])
        coeffs = horner(coeffs, my_poly).coef[::-1].tolist()
    return coeffs
Exemplo n.º 14
0
    def test_chebint(self) :
        # check exceptions
        assert_raises(ValueError, cheb.chebint, [0], .5)
        assert_raises(ValueError, cheb.chebint, [0], -1)
        assert_raises(ValueError, cheb.chebint, [0], 1, [0,0])

        # test integration of zero polynomial
        for i in range(2, 5):
            k = [0]*(i - 2) + [1]
            res = cheb.chebint([0], m=i, k=k)
            assert_almost_equal(res, [0, 1])

        # check single integration with integration constant
        for i in range(5) :
            scl = i + 1
            pol = [0]*i + [1]
            tgt = [i] + [0]*i + [1/scl]
            chebpol = cheb.poly2cheb(pol)
            chebint = cheb.chebint(chebpol, m=1, k=[i])
            res = cheb.cheb2poly(chebint)
            assert_almost_equal(trim(res), trim(tgt))

        # check single integration with integration constant and lbnd
        for i in range(5) :
            scl = i + 1
            pol = [0]*i + [1]
            chebpol = cheb.poly2cheb(pol)
            chebint = cheb.chebint(chebpol, m=1, k=[i], lbnd=-1)
            assert_almost_equal(cheb.chebval(-1, chebint), i)

        # check single integration with integration constant and scaling
        for i in range(5) :
            scl = i + 1
            pol = [0]*i + [1]
            tgt = [i] + [0]*i + [2/scl]
            chebpol = cheb.poly2cheb(pol)
            chebint = cheb.chebint(chebpol, m=1, k=[i], scl=2)
            res = cheb.cheb2poly(chebint)
            assert_almost_equal(trim(res), trim(tgt))

        # check multiple integrations with default k
        for i in range(5) :
            for j in range(2,5) :
                pol = [0]*i + [1]
                tgt = pol[:]
                for k in range(j) :
                    tgt = cheb.chebint(tgt, m=1)
                res = cheb.chebint(pol, m=j)
                assert_almost_equal(trim(res), trim(tgt))

        # check multiple integrations with defined k
        for i in range(5) :
            for j in range(2,5) :
                pol = [0]*i + [1]
                tgt = pol[:]
                for k in range(j) :
                    tgt = cheb.chebint(tgt, m=1, k=[k])
                res = cheb.chebint(pol, m=j, k=list(range(j)))
                assert_almost_equal(trim(res), trim(tgt))

        # check multiple integrations with lbnd
        for i in range(5) :
            for j in range(2,5) :
                pol = [0]*i + [1]
                tgt = pol[:]
                for k in range(j) :
                    tgt = cheb.chebint(tgt, m=1, k=[k], lbnd=-1)
                res = cheb.chebint(pol, m=j, k=list(range(j)), lbnd=-1)
                assert_almost_equal(trim(res), trim(tgt))

        # check multiple integrations with scaling
        for i in range(5) :
            for j in range(2,5) :
                pol = [0]*i + [1]
                tgt = pol[:]
                for k in range(j) :
                    tgt = cheb.chebint(tgt, m=1, k=[k], scl=2)
                res = cheb.chebint(pol, m=j, k=list(range(j)), scl=2)
                assert_almost_equal(trim(res), trim(tgt))
Exemplo n.º 15
0
    def test_chebint(self):
        # check exceptions
        assert_raises(ValueError, cheb.chebint, [0], .5)
        assert_raises(ValueError, cheb.chebint, [0], -1)
        assert_raises(ValueError, cheb.chebint, [0], 1, [0, 0])

        # test integration of zero polynomial
        for i in range(2, 5):
            k = [0]*(i - 2) + [1]
            res = cheb.chebint([0], m=i, k=k)
            assert_almost_equal(res, [0, 1])

        # check single integration with integration constant
        for i in range(5):
            scl = i + 1
            pol = [0]*i + [1]
            tgt = [i] + [0]*i + [1/scl]
            chebpol = cheb.poly2cheb(pol)
            chebint = cheb.chebint(chebpol, m=1, k=[i])
            res = cheb.cheb2poly(chebint)
            assert_almost_equal(trim(res), trim(tgt))

        # check single integration with integration constant and lbnd
        for i in range(5):
            scl = i + 1
            pol = [0]*i + [1]
            chebpol = cheb.poly2cheb(pol)
            chebint = cheb.chebint(chebpol, m=1, k=[i], lbnd=-1)
            assert_almost_equal(cheb.chebval(-1, chebint), i)

        # check single integration with integration constant and scaling
        for i in range(5):
            scl = i + 1
            pol = [0]*i + [1]
            tgt = [i] + [0]*i + [2/scl]
            chebpol = cheb.poly2cheb(pol)
            chebint = cheb.chebint(chebpol, m=1, k=[i], scl=2)
            res = cheb.cheb2poly(chebint)
            assert_almost_equal(trim(res), trim(tgt))

        # check multiple integrations with default k
        for i in range(5):
            for j in range(2, 5):
                pol = [0]*i + [1]
                tgt = pol[:]
                for k in range(j):
                    tgt = cheb.chebint(tgt, m=1)
                res = cheb.chebint(pol, m=j)
                assert_almost_equal(trim(res), trim(tgt))

        # check multiple integrations with defined k
        for i in range(5):
            for j in range(2, 5):
                pol = [0]*i + [1]
                tgt = pol[:]
                for k in range(j):
                    tgt = cheb.chebint(tgt, m=1, k=[k])
                res = cheb.chebint(pol, m=j, k=list(range(j)))
                assert_almost_equal(trim(res), trim(tgt))

        # check multiple integrations with lbnd
        for i in range(5):
            for j in range(2, 5):
                pol = [0]*i + [1]
                tgt = pol[:]
                for k in range(j):
                    tgt = cheb.chebint(tgt, m=1, k=[k], lbnd=-1)
                res = cheb.chebint(pol, m=j, k=list(range(j)), lbnd=-1)
                assert_almost_equal(trim(res), trim(tgt))

        # check multiple integrations with scaling
        for i in range(5):
            for j in range(2, 5):
                pol = [0]*i + [1]
                tgt = pol[:]
                for k in range(j):
                    tgt = cheb.chebint(tgt, m=1, k=[k], scl=2)
                res = cheb.chebint(pol, m=j, k=list(range(j)), scl=2)
                assert_almost_equal(trim(res), trim(tgt))
Exemplo n.º 16
0
 def test_cheb2poly(self):
     for i in range(10):
         assert_almost_equal(cheb.cheb2poly([0]*i + [1]), Tlist[i])
Exemplo n.º 17
0
Arquivo: foldd.py Projeto: lujig/dfpsr
    coeff = np.float64(coeff)
    t0 = np.float64(t0 - stt_date) * 86400.0
    t1 = np.float64(t1 - stt_date) * 86400.0
    dt = (np.array([0, nbin0]) * tsamp + stt_sec - t0) / (t1 - t0) * 2 - 1
    coeff1 = coeff.sum(1)
    phase = nc.chebval(dt, coeff1) + dispc / freq_end**2
    phase0 = np.ceil(phase[0])
    nperiod = int(
        np.floor(phase[-1] - phase0 + dispc / freq_start**2 -
                 dispc / freq_end**2))
    coeff[0, 0] -= phase0
    coeff1 = coeff.sum(1)
    roots = nc.chebroots(coeff1)
    roots = np.real(roots[np.isreal(roots)])
    root = roots[np.argmin(np.abs(roots - dt[0]))]
    period = 1. / np.polyval(np.polyder(nc.cheb2poly(coeff1)[::-1]),
                             root) / 2.0 * (t1 - t0)
    stt_sec = (root + 1) / 2.0 * (t1 - t0) + t0
    stt_date = stt_date + stt_sec // 86400
    stt_sec = stt_sec % 86400
    info['phase0'] = int(phase0) + tmp
    phase -= phase0
#
info['nperiod'] = nperiod
info['period'] = period
#
nbin_max = (nbin0 - 1) / (np.max(phase) - np.min(phase))
if args.nbin:
    nbin = args.nbin
    if nbin > nbin_max:
        temp_multi = 1
Exemplo n.º 18
0
def cheb2poly(cs) :
    from numpy.polynomial.chebyshev import cheb2poly
    return cheb2poly(cs)
Exemplo n.º 19
0

def normalized_dct(Y):
    Z = dct(Y)
    # print(Z)
    Z = Z / len(Z)
    # print(Z)
    Z[0] = Z[0] / 2
    # print(Z)
    return Z


C = normalized_dct(Y)
# print('C:', C)

#### Compute the coefficients of the Chebyshev expansion in the canonical basis.

P = cheb2poly(C)
# print('P:', P)

#### Plot f and its chebyshev interpolation approximation

nb_plot_points = 100
X_plot = [a + i * (b - a) / nb_plot_points for i in range(nb_plot_points + 1)]
Y_f_plot = [f(x) for x in X_plot]
Y_P_plot = [polyval(inverse_affine_transformation(x), P) for x in X_plot]
# plt.plot(X_plot, Y_f_plot, label='f')
# plt.plot(X_plot, Y_P_plot, label = 'P')
# plt.legend()
# plt.show()
Exemplo n.º 20
0
import matplotlib.pyplot as plt
import numpy as np
from numpy.polynomial.chebyshev import Chebyshev, cheb2poly

mindeg, maxdeg = 0, 5

cmap = plt.get_cmap('rainbow')
colors = cmap(np.linspace(0, 1, maxdeg - mindeg + 1))
print(colors)

l = list(np.zeros(mindeg, int)) + [1]
xx = np.linspace(-1, 1, 100)
tx = 0.2
for i, col in zip(range(mindeg, maxdeg + 1), colors):
    c = Chebyshev(l)
    print('T({}) = {}'.format(i, cheb2poly(c.coef)))
    yy = [c(x) for x in xx]
    #col = colors.pop()
    plt.gcf().text(tx, 0.9, 'T({})'.format(i), color=col)
    tx += 0.1
    plt.plot(xx, yy, color=col)
    l.insert(0, 0)  # increment the degree
plt.grid(True)
plt.show()
Exemplo n.º 21
0
	tmp=int(coeff[0,0])
	coeff[0,0]-=tmp
	coeff=np.float64(coeff)
	time0=file_time[0]
	t0=np.float64(t0-time0[-1])*86400.0
	t1=np.float64(t1-time0[-1])*86400.0
	dt=(np.array([0,nbin0])*tsamp+time0[:-1].sum()-delay-t0)/(t1-t0)*2-1
	coeff1=coeff.sum(1)
	phase=nc.chebval(dt,coeff1)+dispc/freq_end**2
	phase0=np.ceil(phase[0])
	nperiod=int(np.floor(phase[-1]-phase0+dispc/freq_start**2-dispc/freq_end**2))
	coeff[0,0]-=phase0
	roots=nc.chebroots(coeff1)
	roots=np.real(roots[np.isreal(roots)])
	root=roots[np.argmin(np.abs(roots-dt[0]))]
	period=1./np.polyval(np.polyder(nc.cheb2poly(coeff1)[::-1]),root)/2.0*(t1-t0)
	stt_sec=(root+1)/2.0*(t1-t0)+t0
	stt_date=time0[-1]+stt_sec//86400
	stt_sec=stt_sec%86400
	info['phase0']=int(phase0)+tmp
	phase-=phase0
	print(coeff)
#
info['stt_sec']=stt_sec
info['stt_date']=stt_date
info['stt_time']=stt_date+stt_sec/86400.0
#
info['nperiod']=nperiod
info['period']=period
#
nbin_max=(nbin0-1)/(np.max(phase)-np.min(phase))