Exemplo n.º 1
0
 def test_roots_discont(self):
     # Check that a discontinuity across zero is reported as root
     c = np.array([[1], [-1]]).T
     x = np.array([0, 0.5, 1])
     pp = PPoly(c, x)
     assert_array_equal(pp.roots(), [0.5])
     assert_array_equal(pp.roots(discontinuity=False), [])
Exemplo n.º 2
0
 def test_roots_discont(self):
     # Check that a discontinuity across zero is reported as root
     c = np.array([[1], [-1]]).T
     x = np.array([0, 0.5, 1])
     pp = PPoly(c, x)
     assert_array_equal(pp.roots(), [0.5])
     assert_array_equal(pp.roots(discontinuity=False), [])
Exemplo n.º 3
0
    def test_roots_random(self):
        # Check high-order polynomials with random coefficients
        np.random.seed(1234)

        num = 0

        for extrapolate in (True, False):
            for order in range(0, 20):
                x = np.unique(np.r_[0, 10 * np.random.rand(30), 10])
                c = 2 * np.random.rand(order + 1, len(x) - 1, 2, 3) - 1

                pp = PPoly(c, x)
                r = pp.roots(discontinuity=False, extrapolate=extrapolate)

                for i in range(2):
                    for j in range(3):
                        rr = r[i, j]
                        if rr.size > 0:
                            # Check that the reported roots indeed are roots
                            num += rr.size
                            val = pp(rr, extrapolate=extrapolate)[:, i, j]
                            cmpval = pp(rr, nu=1,
                                        extrapolate=extrapolate)[:, i, j]
                            assert_allclose(val / cmpval,
                                            0,
                                            atol=1e-7,
                                            err_msg="(%r) r = %s" % (
                                                extrapolate,
                                                repr(rr),
                                            ))

        # Check that we checked a number of roots
        assert_(num > 100, repr(num))
Exemplo n.º 4
0
    def test_roots_random(self):
        # Check high-order polynomials with random coefficients
        np.random.seed(1234)

        num = 0

        for extrapolate in (True, False):
            for order in range(0, 20):
                x = np.unique(np.r_[0, 10 * np.random.rand(30), 10])
                c = 2*np.random.rand(order+1, len(x)-1, 2, 3) - 1

                pp = PPoly(c, x)
                r = pp.roots(discontinuity=False, extrapolate=extrapolate)

                for i in range(2):
                    for j in range(3):
                        rr = r[i,j]
                        if rr.size > 0:
                            # Check that the reported roots indeed are roots
                            num += rr.size
                            val = pp(rr, extrapolate=extrapolate)[:,i,j]
                            cmpval = pp(rr, nu=1, extrapolate=extrapolate)[:,i,j]
                            assert_allclose(val/cmpval, 0, atol=1e-7,
                                            err_msg="(%r) r = %s" % (extrapolate,
                                                                     repr(rr),))

        # Check that we checked a number of roots
        assert_(num > 100, repr(num))
Exemplo n.º 5
0
    def test_roots_idzero(self):
        # Roots for piecewise polynomials with identically zero
        # sections.
        c = np.array([[-1, 0.25], [0, 0], [-1, 0.25]]).T
        x = np.array([0, 0.4, 0.6, 1.0])

        pp = PPoly(c, x)
        assert_array_equal(pp.roots(), [0.25, 0.4, np.nan, 0.6 + 0.25])
Exemplo n.º 6
0
    def test_roots_idzero(self):
        # Roots for piecewise polynomials with identically zero
        # sections.
        c = np.array([[-1, 0.25], [0, 0], [-1, 0.25]]).T
        x = np.array([0, 0.4, 0.6, 1.0])

        pp = PPoly(c, x)
        assert_array_equal(pp.roots(),
                           [0.25, 0.4, np.nan, 0.6 + 0.25])
Exemplo n.º 7
0
def _get_piecewise_mean_price_vs_size_from_orderbook_entry(orders):
    """ orders is just asks or just orders """
    cm = [0] + [x['cm'] for x in orders]
    # integral (price times qty) d_qty / qty
    # represent this as integral of piecewise polynomial with coeff [0, price]
    price = np.zeros((2, len(cm) - 1))
    price[1, :] = [x['price'] for x in orders]
    f = PPoly(price, cm, extrapolate=False)
    F = f.antiderivative()
    return lambda x: F(x) / x
Exemplo n.º 8
0
    def test_bp_from_pp(self):
        x = [0, 1, 3]
        c = [[3, 2], [1, 8], [4, 3]]
        pp = PPoly(c, x)
        bp = BPoly.from_power_basis(pp)
        pp1 = PPoly.from_bernstein_basis(bp)

        xp = [0.1, 1.4]
        assert_allclose(pp(xp), bp(xp))
        assert_allclose(pp(xp), pp1(xp))
Exemplo n.º 9
0
        def _make_ppoly():
            if n_waypoints == 1:
                waypoints = _extract_waypoints(0)
                pp_coeffs = np.zeros((1, 1, self.dof))
                for idof in range(self.dof):
                    pp_coeffs[0, 0, idof] = waypoints[0, idof]
                return PPoly(pp_coeffs, [0, 1])

            if self._interpolation == "quadratic":
                waypoints = _extract_waypoints(0)
                waypoints_d = _extract_waypoints(1)
                waypoints_dd = []
                for i in range(n_waypoints - 1):
                    qdd = (waypoints_d[i + 1] - waypoints_d[i]) / (
                        self.ss_waypoints[i + 1] - self.ss_waypoints[i]
                    )
                    waypoints_dd.append(qdd)
                waypoints_dd = np.array(waypoints_dd)

                # Fill the coefficient matrix for scipy.PPoly class
                pp_coeffs = np.zeros((3, n_waypoints - 1, self.dof))
                for idof in range(self.dof):
                    for iseg in range(n_waypoints - 1):
                        pp_coeffs[:, iseg, idof] = [
                            waypoints_dd[iseg, idof] / 2,
                            waypoints_d[iseg, idof],
                            waypoints[iseg, idof],
                        ]
                return PPoly(pp_coeffs, self.ss_waypoints)

            if self._interpolation == "cubic":
                waypoints = _extract_waypoints(0)
                waypoints_d = _extract_waypoints(1)
                waypoints_dd = _extract_waypoints(2)
                waypoints_ddd = []
                for i in range(n_waypoints - 1):
                    qddd = (waypoints_dd[i + 1] - waypoints_dd[i]) / (
                        self.ss_waypoints[i + 1] - self.ss_waypoints[i]
                    )
                    waypoints_ddd.append(qddd)
                waypoints_ddd = np.array(waypoints_ddd)

                # Fill the coefficient matrix for scipy.PPoly class
                pp_coeffs = np.zeros((4, n_waypoints - 1, self.dof))
                for idof in range(self.dof):
                    for iseg in range(n_waypoints - 1):
                        pp_coeffs[:, iseg, idof] = [
                            waypoints_ddd[iseg, idof] / 6,
                            waypoints_dd[iseg, idof] / 2,
                            waypoints_d[iseg, idof],
                            waypoints[iseg, idof],
                        ]
                return PPoly(pp_coeffs, self.ss_waypoints)
            raise ValueError("An error has occured. Unable to form PPoly.")
Exemplo n.º 10
0
    def test_roots_repeated(self):
        # Check roots repeated in multiple sections are reported only
        # once.

        # [(x + 1)**2 - 1, -x**2] ; x == 0 is a repeated root
        c = np.array([[1, 0, -1], [-1, 0, 0]]).T
        x = np.array([-1, 0, 1])

        pp = PPoly(c, x)
        assert_array_equal(pp.roots(), [-2, 0])
        assert_array_equal(pp.roots(extrapolate=False), [0])
Exemplo n.º 11
0
    def test_roots_repeated(self):
        # Check roots repeated in multiple sections are reported only
        # once.

        # [(x + 1)**2 - 1, -x**2] ; x == 0 is a repeated root
        c = np.array([[1, 0, -1], [-1, 0, 0]]).T
        x = np.array([-1, 0, 1])

        pp = PPoly(c, x)
        assert_array_equal(pp.roots(), [-2, 0])
        assert_array_equal(pp.roots(extrapolate=False), [0])
Exemplo n.º 12
0
    def test_bp_from_pp_random(self):
        np.random.seed(1234)
        m, k = 5, 8  # number of intervals, order
        x = np.sort(np.random.random(m))
        c = np.random.random((k, m - 1))
        pp = PPoly(c, x)
        bp = BPoly.from_power_basis(pp)
        pp1 = PPoly.from_bernstein_basis(bp)

        xp = np.linspace(x[0], x[-1], 21)
        assert_allclose(pp(xp), bp(xp))
        assert_allclose(pp(xp), pp1(xp))
Exemplo n.º 13
0
    def test_derivative_simple(self):
        np.random.seed(1234)
        c = np.array([[4, 3, 2, 1]]).T
        dc = np.array([[3*4, 2*3, 2]]).T
        ddc = np.array([[2*3*4, 1*2*3]]).T
        x = np.array([0, 1])

        pp = PPoly(c, x)
        dpp = PPoly(dc, x)
        ddpp = PPoly(ddc, x)

        assert_allclose(pp.derivative().c, dpp.c)
        assert_allclose(pp.derivative(2).c, ddpp.c)
Exemplo n.º 14
0
    def test_multi_shape(self):
        c = np.random.rand(6, 2, 1, 2, 3)
        x = np.array([0, 0.5, 1])
        p = PPoly(c, x)
        assert_equal(p.x.shape, x.shape)
        assert_equal(p.c.shape, c.shape)
        assert_equal(p(0.3).shape, c.shape[2:])

        assert_equal(p(np.random.rand(5, 6)).shape, (5, 6) + c.shape[2:])

        dp = p.derivative()
        assert_equal(dp.c.shape, (5, 2, 1, 2, 3))
        ip = p.antiderivative()
        assert_equal(ip.c.shape, (7, 2, 1, 2, 3))
Exemplo n.º 15
0
 def __init__(self, poly_coeff_set):
     self.poly_coeff_set = np.array(poly_coeff_set)
     self.shape = np.array(self.poly_coeff_set.shape)
     self.amount_segment = self.shape[1]
     self.dof = self.shape[2]
     self.degree_poly = self.shape[0]
     self.s_start = 0
     self.s_end = self.amount_segment
     self.duration = self.amount_segment
     self.s_waypoint = np.arange(0, self.duration + 1, 1)
     self.picecwise_poly = PPoly(self.poly_coeff_set, self.s_waypoint)
     self.picecwise_poly_s = self.picecwise_poly.derivative()
     self.picecwise_poly_ss = self.picecwise_poly_s.derivative()
     import ipdb
     ipdb.set_trace()
Exemplo n.º 16
0
    def test_multi_shape(self):
        c = np.random.rand(6, 2, 1, 2, 3)
        x = np.array([0, 0.5, 1])
        p = PPoly(c, x)
        assert_equal(p.x.shape, x.shape)
        assert_equal(p.c.shape, c.shape)
        assert_equal(p(0.3).shape, c.shape[2:])

        assert_equal(p(np.random.rand(5,6)).shape,
                     (5,6) + c.shape[2:])

        dp = p.derivative()
        assert_equal(dp.c.shape, (5, 2, 1, 2, 3))
        ip = p.antiderivative()
        assert_equal(ip.c.shape, (7, 2, 1, 2, 3))
Exemplo n.º 17
0
 def test_construct_fast(self):
     np.random.seed(1234)
     c = np.array([[1, 4], [2, 5], [3, 6]], dtype=float)
     x = np.array([0, 0.5, 1])
     p = PPoly.construct_fast(c, x)
     assert_allclose(p(0.3), 1 * 0.3**2 + 2 * 0.3 + 3)
     assert_allclose(p(0.7), 4 * (0.7 - 0.5)**2 + 5 * (0.7 - 0.5) + 6)
Exemplo n.º 18
0
    def test_antiderivative_vs_derivative(self):
        np.random.seed(1234)
        x = np.linspace(0, 1, 30)**2
        y = np.random.rand(len(x))
        spl = splrep(x, y, s=0, k=5)
        pp = PPoly.from_spline(spl)

        for dx in range(0, 10):
            ipp = pp.antiderivative(dx)

            # check that derivative is inverse op
            pp2 = ipp.derivative(dx)
            assert_allclose(pp.c, pp2.c)

            # check continuity
            for k in range(dx):
                pp2 = ipp.derivative(k)

                r = 1e-13
                endpoint = r * pp2.x[:-1] + (1 - r) * pp2.x[1:]

                assert_allclose(pp2(pp2.x[1:]),
                                pp2(endpoint),
                                rtol=1e-7,
                                err_msg="dx=%d k=%d" % (dx, k))
Exemplo n.º 19
0
def get_piecewise_price_vs_size_from_orderbook_entry(orders, mean=True):
    """ orders is just asks or just orders. takes maybe 300 micros though timeit reports much less """
    if not orders:
        return None
    cm = [0] + [x['cm'] for x in orders]
    # integral (price times qty) d_qty / qty
    # represent this as integral of piecewise polynomial with coeff [0, price]
    price = np.zeros((2, len(cm)-1))
    price[1,:] = [x['price'] for x in orders]
    f = PPoly(price, cm, extrapolate=False)
    F = f.antiderivative()
    if mean:
        # generally you want mean price if you took out the stack up to some size
        return lambda x: F(x) / x
    else:
        return F
Exemplo n.º 20
0
def test_size_history_R(rnd_eta):
    p = rnd_eta
    q = PPoly(x=p.t, c=[1.0 / p.Ne]).antiderivative()
    for t in np.random.rand(100) * len(p.t):
        assert abs(p.R(t) - q(t)) < 1e-4
    for t1, t2 in np.random.rand(100, 2) * len(p.t):
        assert abs((p.R(t1 + t2) - p.R(t1)) - (q(t1 + t2) - q(t1))) < 1e-4
Exemplo n.º 21
0
    def test_ppoly(self):
        b = _make_random_spline()
        t, c, k = b.tck
        pp = PPoly.from_spline((t, c, k))

        xx = np.linspace(t[k], t[-k], 100)
        assert_allclose(b(xx), pp(xx), atol=1e-14, rtol=1e-14)
Exemplo n.º 22
0
    def test_ppoly(self):
        b = _make_random_spline()
        t, c, k = b.tck
        pp = PPoly.from_spline((t, c, k))

        xx = np.linspace(t[k], t[-k], 100)
        assert_allclose(b(xx), pp(xx), atol=1e-14, rtol=1e-14)
Exemplo n.º 23
0
def cubic_interp(obs_t, cum_obs):
    """
    Construct a cubic count interpolant
    (which for monotonic counts is a quadratic rate)
    """

    # extend with null counts
    # so that it extrapolates, but conservatively
    obs_t = np.concatenate([
        [obs_t[0] - 2, obs_t[0] - 1],
        obs_t,
        [obs_t[-1] + 1, obs_t[-1] + 2]
    ])
    cum_obs = np.concatenate([
        [cum_obs[0], cum_obs[0]],
        cum_obs,
        [cum_obs[-1], cum_obs[-1]]
    ])

    big_n_hat = PPoly.from_bernstein_basis(
        PchipInterpolator(
            obs_t,
            cum_obs,
            extrapolate=True
        )
    )
    return big_n_hat
Exemplo n.º 24
0
def curve_from_controls(durations, accels, t0=0., x0=0., v0=0.):
    assert len(durations) == len(accels)
    #from numpy.polynomial import Polynomial
    #t = Polynomial.identity()
    times = [t0]
    positions = [x0]
    velocities = [v0]
    coeffs = []
    for duration, accel in zip(durations, accels):
        assert duration >= 0.
        coeff = [0.5 * accel, 1. * velocities[-1], positions[-1]]  # 0. jerk
        coeffs.append(coeff)
        times.append(times[-1] + duration)
        p_curve = np.poly1d(coeff)  # Not centered
        positions.append(p_curve(duration))
        v_curve = p_curve.deriv()  # Not centered
        velocities.append(v_curve(duration))
    # print(positions)
    # print(velocities)

    #np.piecewise
    # max_order = max(p_curve.order for p_curve in p_curves)
    # coeffs = np.zeros([max_order + 1, len(p_curves), 1])
    # for i, p_curve in enumerate(p_curves):
    #     # TODO: need to center
    #     for k, c in iterate_poly1d(p_curve):
    #         coeffs[max_order - k, i] = c
    from scipy.interpolate import PPoly
    # TODO: check continuity
    #from scipy.interpolate import CubicHermiteSpline
    return PPoly(c=np.array(coeffs).T, x=times)  # TODO: spline.extend
Exemplo n.º 25
0
 def test_construct_fast(self):
     np.random.seed(1234)
     c = np.array([[1, 4], [2, 5], [3, 6]], dtype=float)
     x = np.array([0, 0.5, 1])
     p = PPoly.construct_fast(c, x)
     assert_allclose(p(0.3), 1*0.3**2 + 2*0.3 + 3)
     assert_allclose(p(0.7), 4*(0.7-0.5)**2 + 5*(0.7-0.5) + 6)
Exemplo n.º 26
0
 def from_poly(poly):
     from scipy.interpolate import PPoly
     if isinstance(poly, MultiPPoly):
         return poly
     assert len(poly.c.shape) == 3
     d = poly.c.shape[2]
     return MultiPPoly(
         [PPoly(c=poly.c[..., k], x=poly.x) for k in range(d)])
Exemplo n.º 27
0
def add_anchor_point(x, y):
    """Auxilliary function to create stepping potential used by energy_model.peq_models.jump_spline2 module
       Find additional anchoring point (x_add, y_add), such that x[0] < x_add < x[1], and y_add = y_spline (x_add_mirror),
       where y_spline is spline between x[1] and x[2], and x_add_mirror is a mirror point of x_add w.r.t. x[1], e.g. |x_add-x[1]|=|x[1]-x_add_mirror|.
       This additional point will force the barriers to have symmetrical shape.

       Params:
           x: x - values at three right or three left boundary points, e.g. interp_x[0:3], or interp_x[-3:][::-1] (reverse order on the right boundary)
           y: corresponding y values
       Returns:
           x_add, y_add - additional point in between x[0] < x_add < x[1] that can be used for spline interpolation
    """
    # Start with the middle point
    x_add_mirror = 0.5 * (x[1] + x[2])
    not_found = True
    cpoly = PPoly(CubicSpline(np.sort(x[1:3]), np.sort(
        y[1:3]), bc_type=[(1, 0), (1, 0)]).c, np.sort([x[1], x[2]]))
    first_peak_is_maximum = True if y[0] <= y[1] else False
    while not_found:
        # Check if y-value at anchor point exceeds value at the boundary and that x-value is within an interval
        if first_peak_is_maximum:
            if cpoly(x_add_mirror) > y[0] and np.abs(x_add_mirror - x[1]) < np.abs(x[1] - x[0]):
                x_add = 2 * x[1] - x_add_mirror
                if x[1] > x[0]:
                    poly2 = PPoly(CubicSpline([x[0], x_add, x[1]], [y[0], cpoly(
                        x_add_mirror), y[1]], bc_type=[(1, 0), (1, 0)]).c, [x[0], x_add, x[1]])
                else:
                    poly2 = PPoly(CubicSpline([x[1], x_add, x[0]], [y[1], cpoly(
                        x_add_mirror), y[0]], bc_type=[(1, 0), (1, 0)]).c, [x[1], x_add, x[0]])
                x_dense = np.linspace(x[0], x[1], 100)
                if all(poly2(x_dense) <= y[1]):
                    not_found = False
        else:
            if cpoly(x_add_mirror) < y[0] and np.abs(x_add_mirror - x[1]) < np.abs(x[1] - x[0]):
                x_add = 2 * x[1] - x_add_mirror
                if x[1] > x[0]:
                    poly2 = PPoly(CubicSpline([x[0], x_add, x[1]], [y[0], cpoly(
                        x_add_mirror), y[1]], bc_type=[(1, 0), (1, 0)]).c, [x[0], x_add, x[1]])
                else:
                    poly2 = PPoly(CubicSpline([x[1], x_add, x[0]], [y[1], cpoly(
                        x_add_mirror), y[0]], bc_type=[(1, 0), (1, 0)]).c, [x[1], x_add, x[0]])
                x_dense = np.linspace(x[0], x[1], 100)
                if all(poly2(x_dense) >= y[1]):
                    not_found = False
        x_add_mirror = 0.5 * (x[1] + x_add_mirror)
    return x_add, cpoly(2 * x[1] - x_add)
Exemplo n.º 28
0
    def setup(self):
        np.random.seed(1234)
        m, k = 55, 3
        x = np.sort(np.random.random(m + 1))
        c = np.random.random((3, m))
        self.pp = PPoly(c, x)

        npts = 100
        self.xp = np.linspace(0, 1, npts)
Exemplo n.º 29
0
    def test_integrate_ppoly(self):
        # test .integrate method to be consistent with PPoly.integrate
        x = [0, 1, 2, 3, 4]
        b = make_interp_spline(x, x)
        b.extrapolate = 'periodic'
        p = PPoly.from_spline(b)

        for x0, x1 in [(-5, 0.5), (0.5, 5), (-4, 13)]:
            assert_allclose(b.integrate(x0, x1), p.integrate(x0, x1))
Exemplo n.º 30
0
    def test_roots(self):
        x = np.linspace(0, 1, 31)**2
        y = np.sin(30 * x)

        spl = splrep(x, y, s=0, k=3)
        pp = PPoly.from_spline(spl)

        r = pp.roots()
        r = r[(r >= 0) & (r <= 1)]
        assert_allclose(r, sproot(spl), atol=1e-15)
Exemplo n.º 31
0
    def test_from_spline(self):
        np.random.seed(1234)
        x = np.sort(np.r_[0, np.random.rand(11), 1])
        y = np.random.rand(len(x))

        spl = splrep(x, y, s=0)
        pp = PPoly.from_spline(spl)

        xi = np.linspace(0, 1, 200)
        assert_allclose(pp(xi), splev(xi, spl))
Exemplo n.º 32
0
 def smooth(self):
     "Return an C2 interpolant of self, suitable for optimization"
     pc = scipy.interpolate.PchipInterpolator(x=self.t[:-1],
                                              y=1.0 / self.Ne)
     # the base class of PchipInterpolator seems to have switched from a BPoly to a PPoly at some point
     assert isinstance(pc, scipy.interpolate.PPoly)
     # add a final piece at the back that is constant
     cinf = np.eye(pc.c.shape[0])[:, -1:] * pc.c[-1, -1]
     ret = PPoly(c=np.append(pc.c, cinf, axis=1), x=np.append(pc.x, np.inf))
     return ret
Exemplo n.º 33
0
    def test_from_spline(self):
        np.random.seed(1234)
        x = np.sort(np.r_[0, np.random.rand(11), 1])
        y = np.random.rand(len(x))

        spl = splrep(x, y, s=0)
        pp = PPoly.from_spline(spl)

        xi = np.linspace(0, 1, 200)
        assert_allclose(pp(xi), splev(xi, spl))
Exemplo n.º 34
0
    def test_integrate_ppoly(self):
        # test .integrate method to be consistent with PPoly.integrate
        x = [0, 1, 2, 3, 4]
        b = make_interp_spline(x, x)
        b.extrapolate = 'periodic'
        p = PPoly.from_spline(b)

        for x0, x1 in [(-5, 0.5), (0.5, 5), (-4, 13)]:
            assert_allclose(b.integrate(x0, x1),
                            p.integrate(x0, x1))
Exemplo n.º 35
0
    def test_pp_from_bp(self):
        x = [0, 1, 3]
        c = [[3, 3], [1, 1], [4, 2]]
        bp = BPoly(c, x)
        pp = PPoly.from_bernstein_basis(bp)
        bp1 = BPoly.from_power_basis(pp)

        xp = [0.1, 1.4]
        assert_allclose(bp(xp), pp(xp))
        assert_allclose(bp(xp), bp1(xp))
Exemplo n.º 36
0
    def test_roots(self):
        x = np.linspace(0, 1, 31)**2
        y = np.sin(30*x)

        spl = splrep(x, y, s=0, k=3)
        pp = PPoly.from_spline(spl)

        r = pp.roots()
        r = r[(r >= 0) & (r <= 1)]
        assert_allclose(r, sproot(spl), atol=1e-15)
Exemplo n.º 37
0
def trim_end(poly, end):
    from scipy.interpolate import PPoly
    times = poly.x
    if end >= times[-1]:
        return poly
    if end <= times[0]:
        return None
    last = find(lambda i: times[i] <= end, reversed(range(len(times))))
    times = list(times[:last + 1]) + [end]
    c = poly.c[:, :last + 1, ...]
    return PPoly(c=c, x=times)
Exemplo n.º 38
0
    def to_pp(self) -> PPoly:
        """Return a piecewise polynomial representation of this segmentation.

        Notes:
            Only represents segments heights. Identity of haplotype panel is currently ignored.
        """
        x = np.array(
            [self.segments[0].interval[0]] + [s.interval[1] for s in self.segments]
        )
        c = np.array([s.height for s in self.segments])[None]
        return PPoly(x=x, c=c)
Exemplo n.º 39
0
    def test_derivative_eval(self):
        np.random.seed(1234)
        x = np.sort(np.r_[0, np.random.rand(11), 1])
        y = np.random.rand(len(x))

        spl = splrep(x, y, s=0)
        pp = PPoly.from_spline(spl)

        xi = np.linspace(0, 1, 200)
        for dx in range(0, 3):
            assert_allclose(pp(xi, dx), splev(xi, spl, dx))
Exemplo n.º 40
0
    def test_derivative_eval(self):
        np.random.seed(1234)
        x = np.sort(np.r_[0, np.random.rand(11), 1])
        y = np.random.rand(len(x))

        spl = splrep(x, y, s=0)
        pp = PPoly.from_spline(spl)

        xi = np.linspace(0, 1, 200)
        for dx in range(0, 3):
            assert_allclose(pp(xi, dx), splev(xi, spl, dx))
Exemplo n.º 41
0
    def test_extrapolate_attr(self):
        # [ 1 - x**2 ]
        c = np.array([[-1, 0, 1]]).T
        x = np.array([0, 1])

        for extrapolate in [True, False, None]:
            pp = PPoly(c, x, extrapolate=extrapolate)
            pp_d = pp.derivative()
            pp_i = pp.antiderivative()

            if extrapolate is False:
                assert_(np.isnan(pp([-0.1, 1.1])).all())
                assert_(np.isnan(pp_i([-0.1, 1.1])).all())
                assert_(np.isnan(pp_d([-0.1, 1.1])).all())
                assert_equal(pp.roots(), [1])
            else:
                assert_allclose(pp([-0.1, 1.1]), [1-0.1**2, 1-1.1**2])
                assert_(not np.isnan(pp_i([-0.1, 1.1])).any())
                assert_(not np.isnan(pp_d([-0.1, 1.1])).any())
                assert_allclose(pp.roots(), [1, -1])
Exemplo n.º 42
0
    def test_derivative(self):
        np.random.seed(1234)
        x = np.sort(np.r_[0, np.random.rand(11), 1])
        y = np.random.rand(len(x))

        spl = splrep(x, y, s=0, k=5)
        pp = PPoly.from_spline(spl)

        xi = np.linspace(0, 1, 200)
        for dx in range(0, 10):
            assert_allclose(pp(xi, dx), pp.derivative(dx)(xi),
                            err_msg="dx=%d" % (dx,))
Exemplo n.º 43
0
    def test_bp_from_pp_random(self):
        np.random.seed(1234)
        m, k = 5, 8   # number of intervals, order
        x = np.sort(np.random.random(m))
        c = np.random.random((k, m-1))
        pp = PPoly(c, x)
        bp = BPoly.from_power_basis(pp)
        pp1 = PPoly.from_bernstein_basis(bp)

        xp = np.linspace(x[0], x[-1], 21)
        assert_allclose(pp(xp), bp(xp))
        assert_allclose(pp(xp), pp1(xp))
Exemplo n.º 44
0
    def test_vs_alternative_implementations(self):
        np.random.seed(1234)
        c = np.random.rand(3, 12, 22)
        x = np.sort(np.r_[0, np.random.rand(11), 1])

        p = PPoly(c, x)

        xp = np.r_[0.3, 0.5, 0.33, 0.6]
        expected = _ppoly_eval_1(c, x, xp)
        assert_allclose(p(xp), expected)

        expected = _ppoly_eval_2(c[:, :, 0], x, xp)
        assert_allclose(p(xp)[:, 0], expected)
Exemplo n.º 45
0
    def test_derivative(self):
        np.random.seed(1234)
        x = np.sort(np.r_[0, np.random.rand(11), 1])
        y = np.random.rand(len(x))

        spl = splrep(x, y, s=0, k=5)
        pp = PPoly.from_spline(spl)

        xi = np.linspace(0, 1, 200)
        for dx in range(0, 10):
            assert_allclose(pp(xi, dx),
                            pp.derivative(dx)(xi),
                            err_msg="dx=%d" % (dx, ))
Exemplo n.º 46
0
    def test_antiderivative_simple(self):
        np.random.seed(1234)
        # [ p1(x) = 3*x**2 + 2*x + 1,
        #   p2(x) = 1.6875]
        c = np.array([[3, 2, 1], [0, 0, 1.6875]]).T
        # [ pp1(x) = x**3 + x**2 + x,
        #   pp2(x) = 1.6875*(x - 0.25) + pp1(0.25)]
        ic = np.array([[1, 1, 1, 0], [0, 0, 1.6875, 0.328125]]).T
        # [ ppp1(x) = (1/4)*x**4 + (1/3)*x**3 + (1/2)*x**2,
        #   ppp2(x) = (1.6875/2)*(x - 0.25)**2 + pp1(0.25)*x + ppp1(0.25)]
        iic = np.array([[1/4, 1/3, 1/2, 0, 0],
                        [0, 0, 1.6875/2, 0.328125, 0.037434895833333336]]).T
        x = np.array([0, 0.25, 1])

        pp = PPoly(c, x)
        ipp = pp.antiderivative()
        iipp = pp.antiderivative(2)
        iipp2 = ipp.antiderivative()

        assert_allclose(ipp.x, x)
        assert_allclose(ipp.c.T, ic.T)
        assert_allclose(iipp.c.T, iic.T)
        assert_allclose(iipp2.c.T, iic.T)
Exemplo n.º 47
0
    def test_derivative_ppoly(self):
        # make sure it's consistent w/ power basis
        np.random.seed(1234)
        m, k = 5, 8   # number of intervals, order
        x = np.sort(np.random.random(m))
        c = np.random.random((k, m-1))
        bp = BPoly(c, x)
        pp = PPoly.from_bernstein_basis(bp)

        for d in range(k):
            bp = bp.derivative()
            pp = pp.derivative()
            xp = np.linspace(x[0], x[-1], 21)
            assert_allclose(bp(xp), pp(xp))
Exemplo n.º 48
0
    def test_derivative_ppoly(self):
        # make sure it's consistent w/ power basis
        np.random.seed(1234)
        m, k = 5, 8  # number of intervals, order
        x = np.sort(np.random.random(m))
        c = np.random.random((k, m - 1))
        bp = BPoly(c, x)
        pp = PPoly.from_bernstein_basis(bp)

        for d in range(k):
            bp = bp.derivative()
            pp = pp.derivative()
            xp = np.linspace(x[0], x[-1], 21)
            assert_allclose(bp(xp), pp(xp))
Exemplo n.º 49
0
    def test_antiderivative_vs_spline(self):
        np.random.seed(1234)
        x = np.sort(np.r_[0, np.random.rand(11), 1])
        y = np.random.rand(len(x))

        spl = splrep(x, y, s=0, k=5)
        pp = PPoly.from_spline(spl)

        for dx in range(0, 10):
            pp2 = pp.antiderivative(dx)
            spl2 = splantider(spl, dx)

            xi = np.linspace(0, 1, 200)
            assert_allclose(pp2(xi), splev(xi, spl2),
                            rtol=1e-7)
Exemplo n.º 50
0
    def test_integrate(self):
        np.random.seed(1234)
        x = np.sort(np.r_[0, np.random.rand(11), 1])
        y = np.random.rand(len(x))

        spl = splrep(x, y, s=0, k=5)
        pp = PPoly.from_spline(spl)

        a, b = 0.3, 0.9
        ig = pp.integrate(a, b)

        ipp = pp.antiderivative()
        assert_allclose(ig, ipp(b) - ipp(a))
        assert_allclose(ig, splint(a, b, spl))

        a, b = -0.3, 0.9
        ig = pp.integrate(a, b, extrapolate=True)
        assert_allclose(ig, ipp(b) - ipp(a))

        assert_(np.isnan(pp.integrate(a, b, extrapolate=False)).all())
Exemplo n.º 51
0
    def test_antiderivative_vs_derivative(self):
        np.random.seed(1234)
        x = np.linspace(0, 1, 30)**2
        y = np.random.rand(len(x))
        spl = splrep(x, y, s=0, k=5)
        pp = PPoly.from_spline(spl)

        for dx in range(0, 10):
            ipp = pp.antiderivative(dx)

            # check that derivative is inverse op
            pp2 = ipp.derivative(dx)
            assert_allclose(pp.c, pp2.c)

            # check continuity
            for k in range(dx):
                pp2 = ipp.derivative(k)

                r = 1e-13
                endpoint = r*pp2.x[:-1] + (1 - r)*pp2.x[1:]

                assert_allclose(pp2(pp2.x[1:]), pp2(endpoint),
                                rtol=1e-7, err_msg="dx=%d k=%d" % (dx, k))
Exemplo n.º 52
0
from scipy.interpolate import PPoly
from scipy.interpolate import splev, splrep

W = np.array([-2.0, -2.5, -3.7538003, -5.00760061, -5.50760061])

tvec = np.linspace(0, 1, W.shape[0])

W = np.hstack((W[0], W[0], W[:], W[-1] - 0.1, W[-1] - 0.2))
tvec = np.hstack((-0.1, -0.05, tvec, 1.05, 1.1))

tck = splrep(tvec, W, s=0, k=3)

x2 = np.linspace(0, 1, 100)
# x2 = np.linspace(tvec[0], tvec[-1], 100)
y2 = splev(x2, tck)

print splev(0, tck)
print splev(0, tck, der=1)
print splev(1, tck, der=1)

poly = PPoly.from_spline(tck)
dpoly = poly.derivative(1)
ddpoly = poly.derivative(2)

[B, idx] = np.unique(poly.x, return_index=True)
coeff = poly.c[:, idx]


plt.plot(tvec, W, "o", x2, y2)
plt.show()