Example #1
0
    def test_symbol_basic(self):
        # default input
        p = poly.Polynomial([1, 2, 3], symbol='z')
        assert_equal(self.as_latex(p),
                     r'$z \mapsto 1.0 + 2.0\,z + 3.0\,z^{2}$')

        # translated input
        p = poly.Polynomial([1, 2, 3], domain=[-2, 0], symbol='z')
        assert_equal(
            self.as_latex(p),
            (r'$z \mapsto 1.0 + 2.0\,\left(1.0 + z\right) + 3.0\,'
             r'\left(1.0 + z\right)^{2}$'),
        )

        # scaled input
        p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5], symbol='z')
        assert_equal(
            self.as_latex(p),
            (r'$z \mapsto 1.0 + 2.0\,\left(2.0z\right) + 3.0\,'
             r'\left(2.0z\right)^{2}$'),
        )

        # affine input
        p = poly.Polynomial([1, 2, 3], domain=[-1, 0], symbol='z')
        assert_equal(
            self.as_latex(p),
            (r'$z \mapsto 1.0 + 2.0\,\left(1.0 + 2.0z\right) + 3.0\,'
             r'\left(1.0 + 2.0z\right)^{2}$'),
        )
Example #2
0
    def test_simple_polynomial(self):
        # default input
        p = poly.Polynomial([1, 2, 3])
        assert_equal(self.as_latex(p),
                     r'$x \mapsto 1.0 + 2.0\,x + 3.0\,x^{2}$')

        # translated input
        p = poly.Polynomial([1, 2, 3], domain=[-2, 0])
        assert_equal(
            self.as_latex(p),
            r'$x \mapsto 1.0 + 2.0\,\left(1.0 + x\right) + 3.0\,\left(1.0 + x\right)^{2}$'
        )

        # scaled input
        p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5])
        assert_equal(
            self.as_latex(p),
            r'$x \mapsto 1.0 + 2.0\,\left(2.0x\right) + 3.0\,\left(2.0x\right)^{2}$'
        )

        # affine input
        p = poly.Polynomial([1, 2, 3], domain=[-1, 0])
        assert_equal(
            self.as_latex(p),
            r'$x \mapsto 1.0 + 2.0\,\left(1.0 + 2.0x\right) + 3.0\,\left(1.0 + 2.0x\right)^{2}$'
        )
Example #3
0
def plot_trace_solutions(flaton_products, trace_solution_products,
                         trace_solution_products_plot):

    from storage_descriptions import (FLAT_NORMED_DESC,
                                      FLATCENTROID_SOL_JSON_DESC)

    flat_normed = flaton_products[FLAT_NORMED_DESC].data
    _d = trace_solution_products[FLATCENTROID_SOL_JSON_DESC]
    bottom_up_solutions_ = _d["bottom_up_solutions"]

    bottom_up_solutions = []
    for b, d in bottom_up_solutions_:
        import numpy.polynomial as P
        assert b[0] == "poly"
        assert d[0] == "poly"
        bp = P.Polynomial(b[1])
        dp = P.Polynomial(d[1])
        bottom_up_solutions.append((bp, dp))

    from trace_flat import plot_solutions1, plot_solutions2
    fig2 = plot_solutions1(flat_normed, bottom_up_solutions)

    _d = trace_solution_products_plot[FLATCENTROID_SOL_JSON_DESC]
    fig3 = plot_solutions2(_d["bottom_up_centroids"],
                           _d["bottom_up_solutions"])

    return fig2, fig3
Example #4
0
class TestBinaryOperatorsDifferentSymbol:
    p = poly.Polynomial([1, 2, 3], symbol='x')
    other = poly.Polynomial([4, 5, 6], symbol='y')
    ops = (p.__add__, p.__sub__, p.__mul__, p.__floordiv__, p.__mod__)

    @pytest.mark.parametrize('f', ops)
    def test_binops_fails(self, f):
        assert_raises(ValueError, f, self.other)
Example #5
0
 def create_h_vector(self):
     if not self.f_vector:
         self.create_f_vector()
     f_vector_copy = list(self.f_vector)
     f_vector_copy.reverse()
     F_pol = npp.Polynomial(f_vector_copy)
     P = npp.Polynomial([-1, 1])
     H_pol = F_pol(P)
     self.h_vector = list(H_pol)
     self.h_vector = [int(h_i) for h_i in self.h_vector]
Example #6
0
 def interpol(self):
     M = self.solveMi()
     for i in range(self.n-1):
         P1 = poly.Polynomial([(-1)*self.points[i],1])
         P2 = poly.Polynomial([self.points[i+1],-1])
         P = P2*(self.f(self.points[i])/(self.points[i+1]-self.points[i]) - (self.points[i+1] - self.points[i])*M[i]/6)
         P += P2*P2*P2*M[i]/(6*(self.points[i+1]-self.points[i]))
         P += P1*(self.f(self.points[i+1])/(self.points[i+1]-self.points[i]) - (self.points[i+1] - self.points[i])*M[i+1]/6)
         P += P1*P1*P1*M[i+1]/(6*(self.points[i+1]-self.points[i]))
         self.splines.append(P)
Example #7
0
def ermit_polynom(x, y, dy):
    z = list(chain(*((sx, ) * 2 for sx in x)))
    f1 = lambda i, j: dy[i // 2] if z[i] == z[j] else (y[i // 2 + 1] - y[
        i // 2]) / (z[j] - z[i])
    f = lambda i, j: f1(i, j) if j - i <= 1 else (f(i + 1, j) - f(i, j - 1)
                                                  ) / (z[j] - z[i])
    f = lru_cache(maxsize=None)(f)
    P = pl.Polynomial(0)
    for i in reversed(range(1, len(z))):
        P = (P + pl.Polynomial(f(0, i))) * pl.Polynomial([-z[i - 1], 1])
    P += pl.Polynomial(y[0])
    return P
def test_complex_coefficients():
    """Test both numpy and built-in complex."""
    coefs = [0 + 1j, 1 + 1j, -2 + 2j, 3 + 0j]
    # numpy complex
    p1 = poly.Polynomial(coefs)
    # Python complex
    p2 = poly.Polynomial(array(coefs, dtype=object))
    poly.set_default_printstyle("unicode")
    assert_equal(str(p1), "1j + (1+1j)·x¹ - (2-2j)·x² + (3+0j)·x³")
    assert_equal(str(p2), "1j + (1+1j)·x¹ + (-2+2j)·x² + (3+0j)·x³")
    poly.set_default_printstyle("ascii")
    assert_equal(str(p1), "1j + (1+1j) x**1 - (2-2j) x**2 + (3+0j) x**3")
    assert_equal(str(p2), "1j + (1+1j) x**1 + (-2+2j) x**2 + (3+0j) x**3")
Example #9
0
    def __init__(self, orders, bottomup_solutions):
        self.orders = orders

        self.apcoeffs = {}
        for o, (bottom, up) in zip(orders, bottomup_solutions):
            if isinstance(bottom, (list, tuple)) and bottom[0] == "poly":
                bottom = P.Polynomial(bottom[1])
            if isinstance(up, (list, tuple)) and up[0] == "poly":
                up = P.Polynomial(up[1])

            self.apcoeffs[o] = ApCoeff(bottom, up)

        self.yi = np.arange(2048)
        self.xi = np.arange(2048)
Example #10
0
 def test_single_line_one_less(self):
     # With 'ascii' style, len(str(p)) is default linewidth - 1 (i.e. 74)
     p = poly.Polynomial([123456789, 123456789, 123456789, 1234, 1])
     assert_equal(len(str(p)), 74)
     assert_equal(str(p),
                  ('123456789.0 + 123456789.0 x**1 + 123456789.0 x**2 + '
                   '1234.0 x**3 + 1.0 x**4'))
Example #11
0
 def test_linewidth_printoption(self, lw, tgt):
     p = poly.Polynomial(
         [0, 10, 200, 3000, 40000, 500000, 600000, 70000, 8000, 900])
     with printoptions(linewidth=lw):
         assert_equal(str(p), tgt)
         for line in str(p).split('\n'):
             assert_(len(line) < lw)
Example #12
0
 def test_first_linebreak_multiline_on_linewidth(self):
     # First line is one character longer than previous test
     p = poly.Polynomial(
         [12345678, 12345678, 12345678, 12345678.12, 1, 12345678])
     assert_equal(str(p),
                  ('12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
                   '12345678.12 x**3 +\n1.0 x**4 + 12345678.0 x**5'))
Example #13
0
def lagrange_polynom(x, y):
    n = len(x)
    lij = lambda i, j: pl.Polynomial((-x[j] / (x[i] - x[j]), 1 /
                                      (x[i] - x[j])))
    li = lambda i: reduce(mul, (lij(i, j) for j in range(n) if i != j))
    P = sum(y * li(i) for i, y in enumerate(y))
    return P
Example #14
0
 def test_property(self):
     """
     'symbol' attribute is read only.
     """
     p = poly.Polynomial(self.c, symbol='x')
     with pytest.raises(AttributeError):
         p.symbol = 'z'
Example #15
0
 def test_num_chars_is_linewidth(self):
     # len(str(p)) == default linewidth == 75
     p = poly.Polynomial([123456789, 123456789, 123456789, 1234, 10])
     assert_equal(len(str(p)), 75)
     assert_equal(str(p),
                  ('123456789.0 + 123456789.0 x**1 + 123456789.0 x**2 + '
                   '1234.0 x**3 +\n10.0 x**4'))
Example #16
0
def get_poly(a, b):   
    n = len(a)
    assert len(b) == n
    
    p = []
    
    p.append( 0 )
    p.append( pln.Polynomial(coef=(1,)) )
    
    x = pln.Polynomial(coef=(0,1))
    
    for i in range(n):
        p_i = (x - a[i]) * p[-1] - b[i] * p[-2]
        p.append( p_i )
        
    return p[1:]
def test_nonnumeric_object_coefficients(coefs, tgt):
    """
    Test coef fallback for object arrays of non-numeric coefficients.
    """
    p = poly.Polynomial(coefs)
    poly.set_default_printstyle("unicode")
    assert_equal(str(p), tgt)
Example #18
0
def ermit_spline(x, y, dy=None, output_d=False):
    n = len(x)
    Pk = lambda k, a, b, c, d: sum(h * pl.Polynomial([-x[k], 1])**i
                                   for h, i in zip((a, b, c, d), range(4)))
    ak = lambda k: y[k]
    bk = None
    hk = lambda k: x[k + 1] - x[k]
    fk = lambda k: (y[k + 1] - y[k]) / hk(k)
    if dy is not None:
        bk = lambda k: dy[k]
    else:
        alphak = lambda k: 1 / hk(k)
        bettak = lambda k: 2 * (1 / hk(k) + 1 / hk(k + 1))
        gammak = lambda k: 1 / hk(k + 1)
        deltak = lambda k: 3 * (fk(k + 1) / hk(k + 1) + fk(k) / hk(k))
        alpha = np.array(list(alphak(k) for k in range(1, n - 2)))
        betta = np.array(list(bettak(k) for k in range(n - 2)))
        gamma = np.array(list(gammak(k) for k in range(n - 3)))
        delta = np.array(list(deltak(k) for k in range(n - 2)))
        A = np.diag(alpha, -1) + np.diag(betta) + np.diag(gamma, 1)
        b = sweep_solve(A, delta)
        bk = lambda k: b[k - 1] if 1 <= k <= n - 2 else 0
    ck = lambda k: (3 * fk(k) - bk(k + 1) - 2 * bk(k)) / hk(k)
    dk = lambda k: (bk(k) + bk(k + 1) - 2 * fk(k)) / (hk(k)**2)

    @np.vectorize
    def P(sx):
        k = bisect(x, sx) - 1 if sx != x[-1] else len(x) - 2
        P = Pk(k, ak(k), bk(k), ck(k), dk(k))
        return P.deriv()(sx) if output_d else P(sx)

    return P
Example #19
0
    def __get_collocation_nodes(self, m, kind):
        """Computes the collocation nodes."""
        # basis coefs
        coefs = np.zeros(m + 1)
        coefs[-1] = 1

        if kind == 'polynomial':
            nodes = polynomial.Polynomial(coefs).roots()

        elif kind == 'chebyshev':
            domain = [self.a, self.b]
            nodes = polynomial.Chebyshev(coefs, domain).roots()

        elif kind == 'legendre':
            domain = [self.a, self.b]
            nodes = polynomial.Legendre(coefs, domain).roots()

        elif kind == 'laguerre':
            domain = [self.a, self.b]
            nodes = polynomial.Laguerre(coefs, domain).roots()

        elif kind == 'hermite':
            domain = [self.a, self.b]
            nodes = polynomial.Hermite(coefs, domain).roots()

        else:
            raise ValueError

        return nodes
Example #20
0
 def test_first_linebreak_multiline_one_less_than_linewidth(self):
     # Multiline str where len(first_line) + len(next_term) == lw - 1 == 74
     p = poly.Polynomial(
         [12345678, 12345678, 12345678, 12345678, 1, 12345678])
     assert_equal(len(str(p).split('\n')[0]), 74)
     assert_equal(str(p), ('12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
                           '12345678.0 x**3 + 1.0 x**4 +\n12345678.0 x**5'))
Example #21
0
def lsq_polynom(x, y, *, deg=None, w=None):
    n = len(x)
    deg = n - 1 if deg is None else deg
    w = np.ones(deg + 1) if w is None else w
    X = np.vander(x, N=deg + 1)[:, ::-1] * w
    a = lng.inv(X.T @ X) @ X.T @ y
    P = pl.Polynomial(a)
    return P
Example #22
0
 def test_non_finite(self):
     p = poly.Polynomial([nan, inf])
     assert str(p) == 'nan + inf x'
     assert p._repr_latex_() == r'$x \mapsto \text{nan} + \text{inf}\,x$'
     with printoptions(nanstr='NAN', infstr='INF'):
         assert str(p) == 'NAN + INF x'
         assert p._repr_latex_() == \
             r'$x \mapsto \text{NAN} + \text{INF}\,x$'
Example #23
0
    def test_fixed(self):
        p = poly.Polynomial([1 / 2])
        assert_equal(str(p), '0.5')

        with printoptions(floatmode='fixed'):
            assert_equal(str(p), '0.50000000')

        with printoptions(floatmode='fixed', precision=4):
            assert_equal(str(p), '0.5000')
Example #24
0
    def test_str(self):
        p = poly.Polynomial([1 / 2, 1 / 7, 1 / 7 * 10**8, 1 / 7 * 10**9])
        assert_equal(
            str(p), '0.5 + 0.14285714 x + 14285714.28571429 x**2 '
            '+ (1.42857143e+08) x**3')

        with printoptions(precision=3):
            assert_equal(
                str(p), '0.5 + 0.143 x + 14285714.286 x**2 '
                '+ (1.429e+08) x**3')
 def test_first_linebreak_multiline_on_linewidth(self):
     # First line is one character longer than previous test
     p = poly.Polynomial([123456789, 123456789, 123456789, 123, 1, 123456789])
     assert_equal(
         str(p),
         (
             "123456789.0 + 123456789.0 x**1 + 123456789.0 x**2 + "
             "123.0 x**3 +\n1.0 x**4 + 123456789.0 x**5"
         ),
     )
Example #26
0
class TestEquality:
    p = poly.Polynomial([1, 2, 3], symbol='x')

    def test_eq(self):
        other = poly.Polynomial([1, 2, 3], symbol='x')
        assert_(self.p == other)

    def test_neq(self):
        other = poly.Polynomial([1, 2, 3], symbol='y')
        assert_(not self.p == other)
Example #27
0
def convert_to_poly(p):

    if p[0].lower().startswith("poly"):
        return P.Polynomial(p[1])

    elif p[0].lower().startswith("cheb"):
        v = cheb.Chebyshev(p[1], domain=p[2], window=p[3])
        return v

    return None
Example #28
0
    def __init__(self, n):
        # Create the segmented polynomials
        if n <= 1:
            n = 2
        self.n = n
        polys = [[pn.Polynomial([0])]*(n+1) for i in range(n+1)]
        polys[1][1] = pn.Polynomial([1])
        for i in range(2,n+1):
            #for x in polys:
            #    for y in x:
            #        print y
            #    print ' '
            for j in range(n,0,-1):
                polys[i][j] = polys[i-1][j].integ()
                polys[i][j] = polys[i][j] - polys[i][j](j-1)
                new_poly = polys[i-1][j-1].integ()
                new_poly = new_poly(j-1) - new_poly(pn.Polynomial([-1, 1]))
                polys[i][j] += new_poly

        self.polys = polys
def test_set_default_printoptions():
    p = poly.Polynomial([1, 2, 3])
    c = poly.Chebyshev([1, 2, 3])
    poly.set_default_printstyle("ascii")
    assert_equal(str(p), "1.0 + 2.0 x**1 + 3.0 x**2")
    assert_equal(str(c), "1.0 + 2.0 T_1(x) + 3.0 T_2(x)")
    poly.set_default_printstyle("unicode")
    assert_equal(str(p), "1.0 + 2.0·x¹ + 3.0·x²")
    assert_equal(str(c), "1.0 + 2.0·T₁(x) + 3.0·T₂(x)")
    with pytest.raises(ValueError):
        poly.set_default_printstyle("invalid_input")
 def test_first_linebreak_multiline_one_less_than_linewidth(self):
     # Multiline str where len(first_line) + len(next_term) == lw - 1 == 74
     p = poly.Polynomial([123456789, 123456789, 123456789, 12, 1, 123456789])
     assert_equal(len(str(p).split("\n")[0]), 74)
     assert_equal(
         str(p),
         (
             "123456789.0 + 123456789.0 x**1 + 123456789.0 x**2 + "
             "12.0 x**3 + 1.0 x**4 +\n123456789.0 x**5"
         ),
     )