Example #1
0
 def test_nan(self):
     # bail out early if the input data contains nans
     x = np.arange(10, dtype=float)
     y = x**3
     w = np.ones_like(x)
     # also test LSQUnivariateSpline [which needs explicit knots]
     spl = UnivariateSpline(x, y, check_finite=True)
     t = spl.get_knots()[3:4]  # interior knots w/ default k=3
     y_end = y[-1]
     for z in [np.nan, np.inf, -np.inf]:
         y[-1] = z
         assert_raises(ValueError, UnivariateSpline,
                       **dict(x=x, y=y, check_finite=True))
         assert_raises(ValueError, InterpolatedUnivariateSpline,
                       **dict(x=x, y=y, check_finite=True))
         assert_raises(ValueError, LSQUnivariateSpline,
                       **dict(x=x, y=y, t=t, check_finite=True))
         y[-1] = y_end  # check valid y but invalid w
         w[-1] = z
         assert_raises(ValueError, UnivariateSpline,
                       **dict(x=x, y=y, w=w, check_finite=True))
         assert_raises(ValueError, InterpolatedUnivariateSpline,
                       **dict(x=x, y=y, w=w, check_finite=True))
         assert_raises(ValueError, LSQUnivariateSpline,
                       **dict(x=x, y=y, t=t, w=w, check_finite=True))
Example #2
0
    def test_invalid_input_for_univariate_spline(self):

        with assert_raises(ValueError) as info:
            x_values = [1, 2, 4, 6, 8.5]
            y_values = [0.5, 0.8, 1.3, 2.5]
            UnivariateSpline(x_values, y_values)
        assert "x and y should have a same length" in str(info.value)

        with assert_raises(ValueError) as info:
            x_values = [1, 2, 4, 6, 8.5]
            y_values = [0.5, 0.8, 1.3, 2.5, 2.8]
            w_values = [-1.0, 1.0, 1.0, 1.0]
            UnivariateSpline(x_values, y_values, w=w_values)
        assert "x, y, and w should have a same length" in str(info.value)

        with assert_raises(ValueError) as info:
            bbox = (-1)
            UnivariateSpline(x_values, y_values, bbox=bbox)
        assert "bbox shape should be (2,)" in str(info.value)

        with assert_raises(ValueError) as info:
            UnivariateSpline(x_values, y_values, k=6)
        assert "k should be 1 <= k <= 5" in str(info.value)

        with assert_raises(ValueError) as info:
            UnivariateSpline(x_values, y_values, s=-1.0)
        assert "s should be s >= 0.0" in str(info.value)
Example #3
0
    def test_invalid_input_for_lsq_univariate_spline(self):

        x_values = [1, 2, 4, 6, 8.5]
        y_values = [0.5, 0.8, 1.3, 2.5, 2.8]
        spl = UnivariateSpline(x_values, y_values, check_finite=True)
        t_values = spl.get_knots()[3:4]  # interior knots w/ default k=3

        with assert_raises(ValueError) as info:
            x_values = [1, 2, 4, 6, 8.5]
            y_values = [0.5, 0.8, 1.3, 2.5]
            LSQUnivariateSpline(x_values, y_values, t_values)
        assert "x and y should have a same length" in str(info.value)

        with assert_raises(ValueError) as info:
            x_values = [1, 2, 4, 6, 8.5]
            y_values = [0.5, 0.8, 1.3, 2.5, 2.8]
            w_values = [1.0, 1.0, 1.0, 1.0]
            LSQUnivariateSpline(x_values, y_values, t_values, w=w_values)
        assert "x, y, and w should have a same length" in str(info.value)

        with assert_raises(ValueError) as info:
            bbox = (100, -100)
            LSQUnivariateSpline(x_values, y_values, t_values, bbox=bbox)
        assert "Interior knots t must satisfy Schoenberg-Whitney conditions" in str(
            info.value)

        with assert_raises(ValueError) as info:
            bbox = (-1)
            LSQUnivariateSpline(x_values, y_values, t_values, bbox=bbox)
        assert "bbox shape should be (2,)" in str(info.value)

        with assert_raises(ValueError) as info:
            LSQUnivariateSpline(x_values, y_values, t_values, k=6)
        assert "k should be 1 <= k <= 5" in str(info.value)
Example #4
0
 def test_nan(self):
     # bail out early if the input data contains nans
     x = np.arange(10, dtype=float)
     y = x**3
     w = np.ones_like(x)
     # also test LSQUnivariateSpline [which needs explicit knots]
     spl = UnivariateSpline(x, y, check_finite=True)
     t = spl.get_knots()[3:4]  # interior knots w/ default k=3
     y_end = y[-1]
     for z in [np.nan, np.inf, -np.inf]:
         y[-1] = z
         assert_raises(ValueError, UnivariateSpline,
                 **dict(x=x, y=y, check_finite=True))
         assert_raises(ValueError, InterpolatedUnivariateSpline,
                 **dict(x=x, y=y, check_finite=True))
         assert_raises(ValueError, LSQUnivariateSpline,
                 **dict(x=x, y=y, t=t, check_finite=True))
         y[-1] = y_end  # check valid y but invalid w
         w[-1] = z
         assert_raises(ValueError, UnivariateSpline,
                 **dict(x=x, y=y, w=w, check_finite=True))
         assert_raises(ValueError, InterpolatedUnivariateSpline,
                 **dict(x=x, y=y, w=w, check_finite=True))
         assert_raises(ValueError, LSQUnivariateSpline,
                 **dict(x=x, y=y, t=t, w=w, check_finite=True))
Example #5
0
 def test_integral_out_of_bounds(self):
     # Regression test for gh-7906: .integral(a, b) is wrong if both
     # a and b are out-of-bounds
     x = np.linspace(0., 1., 7)
     for ext in range(4):
         f = UnivariateSpline(x, x, s=0, ext=ext)
         for (a, b) in [(1, 1), (1, 5), (2, 5), (0, 0), (-2, 0), (-2, -1)]:
             assert_allclose(f.integral(a, b), 0, atol=1e-15)
Example #6
0
 def test_linear_1d(self):
     x = [1, 2, 3]
     y = [0, 2, 4]
     lut = UnivariateSpline(x, y, k=1)
     assert_array_almost_equal(lut.get_knots(), [1, 3])
     assert_array_almost_equal(lut.get_coeffs(), [0, 4])
     assert_almost_equal(lut.get_residual(), 0.0)
     assert_array_almost_equal(lut([1, 1.5, 2]), [0, 1, 2])
Example #7
0
 def test_linear_1d(self):
     x = [1,2,3]
     y = [0,2,4]
     lut = UnivariateSpline(x,y,k=1)
     assert_array_almost_equal(lut.get_knots(),[1,3])
     assert_array_almost_equal(lut.get_coeffs(),[0,4])
     assert_almost_equal(lut.get_residual(),0.0)
     assert_array_almost_equal(lut([1,1.5,2]),[0,1,2])
Example #8
0
    def test_derivative_extrapolation(self):
        # Regression test for gh-10195: for a const-extrapolation spline
        # its derivative evaluates to zero for extrapolation
        x_values = [1, 2, 4, 6, 8.5]
        y_values = [0.5, 0.8, 1.3, 2.5, 5]
        f = UnivariateSpline(x_values, y_values, ext='const', k=3)

        x = [-1, 0, -0.5, 9, 9.5, 10]
        assert_allclose(f.derivative()(x), 0, atol=1e-15)
Example #9
0
    def test_derivative_and_antiderivative(self):
        # Thin wrappers to splder/splantider, so light smoke test only.
        x = np.linspace(0, 1, 70) ** 3
        y = np.cos(x)

        spl = UnivariateSpline(x, y, s=0)
        spl2 = spl.antiderivative(2).derivative(2)
        assert_allclose(spl(0.3), spl2(0.3))

        spl2 = spl.antiderivative(1)
        assert_allclose(spl2(0.6) - spl2(0.2), spl.integral(0.2, 0.6))
Example #10
0
    def test_derivative_and_antiderivative(self):
        # Thin wrappers to splder/splantider, so light smoke test only.
        x = np.linspace(0, 1, 70)**3
        y = np.cos(x)

        spl = UnivariateSpline(x, y, s=0)
        spl2 = spl.antiderivative(2).derivative(2)
        assert_allclose(spl(0.3), spl2(0.3))

        spl2 = spl.antiderivative(1)
        assert_allclose(spl2(0.6) - spl2(0.2), spl.integral(0.2, 0.6))
Example #11
0
    def test_array_like_input(self):
        x_values = np.array([1, 2, 4, 6, 8.5])
        y_values = np.array([0.5, 0.8, 1.3, 2.5, 2.8])
        w_values = np.array([1.0, 1.0, 1.0, 1.0, 1.0])
        bbox = np.array([-100, 100])
        # np.array input
        spl1 = UnivariateSpline(x=x_values, y=y_values, w=w_values,
                                bbox=bbox)
        # list input
        spl2 = UnivariateSpline(x=x_values.tolist(), y=y_values.tolist(),
                                w=w_values.tolist(), bbox=bbox.tolist())

        assert_allclose(spl1([0.1, 0.5, 0.9, 0.99]),
                        spl2([0.1, 0.5, 0.9, 0.99]))
Example #12
0
 def test_strictly_increasing_x(self):
     # Test the x is not required to be strictly increasing, see ticket #8535
     xx = np.arange(10, dtype=float)
     yy = xx**3
     x = np.arange(10, dtype=float)
     x[1] = x[0]
     y = x**3
     w = np.ones_like(x)
     # also test LSQUnivariateSpline [which needs explicit knots]
     spl = UnivariateSpline(xx, yy, check_finite=True)
     t = spl.get_knots()[3:4]  # interior knots w/ default k=3
     spl2 = UnivariateSpline(x=x, y=y, w=w, check_finite=True)
     spl3 = InterpolatedUnivariateSpline(x=x, y=y, check_finite=True)
     spl4 = LSQUnivariateSpline(x=x, y=y, t=t, w=w, check_finite=True)
Example #13
0
 def test_increasing_x(self):
     xx = np.arange(10, dtype=float)
     yy = xx**3
     x = np.arange(10, dtype=float)
     x[1] = x[0]
     y = x**3
     w = np.ones_like(x)
     # also test LSQUnivariateSpline [which needs explicit knots]
     spl = UnivariateSpline(xx, yy, check_finite=True)
     t = spl.get_knots()[3:4]  # interior knots w/ default k=3
     assert_raises(ValueError, UnivariateSpline,
             **dict(x=x, y=y, check_finite=True))
     assert_raises(ValueError, InterpolatedUnivariateSpline,
             **dict(x=x, y=y, check_finite=True))
     assert_raises(ValueError, LSQUnivariateSpline,
             **dict(x=x, y=y, t=t, w=w, check_finite=True))
Example #14
0
    def test_out_of_range_regression(self):
        # Test different extrapolation modes. See ticket 3557
        x = np.arange(5, dtype=np.float)
        y = x**3

        xp = linspace(-8, 13, 100)
        xp_zeros = xp.copy()
        xp_zeros[np.logical_or(xp_zeros < 0., xp_zeros > 4.)] = 0

        for cls in [UnivariateSpline, InterpolatedUnivariateSpline]:
            spl = cls(x=x, y=y)
            for ext in [0, 'extrapolate']:
                assert_allclose(spl(xp, ext=ext), xp**3, atol=1e-16)
                assert_allclose(cls(x, y, ext=ext)(xp), xp**3, atol=1e-16)
            for ext in [1, 'zeros']:
                assert_allclose(spl(xp, ext=ext), xp_zeros**3, atol=1e-16)
                assert_allclose(cls(x, y, ext=ext)(xp),
                                xp_zeros**3,
                                atol=1e-16)
            for ext in [2, 'raise']:
                assert_raises(ValueError, spl, xp, **dict(ext=ext))

        # also test LSQUnivariateSpline [which needs explicit knots]
        t = spl.get_knots()[3:4]  # interior knots w/ default k=3
        spl = LSQUnivariateSpline(x, y, t)
        assert_allclose(spl(xp, ext=0), xp**3, atol=1e-16)
        assert_allclose(spl(xp, ext=1), xp_zeros**3, atol=1e-16)
        assert_raises(ValueError, spl, xp, **dict(ext=2))

        # also make sure that unknown values for `ext` are caught early
        for ext in [-1, 'unknown']:
            spl = UnivariateSpline(x, y)
            assert_raises(ValueError, spl, xp, **dict(ext=ext))
            assert_raises(ValueError, UnivariateSpline,
                          **dict(x=x, y=y, ext=ext))
Example #15
0
    def make_splines(self, err_tol_factor=1e-2):
        """Generate a spline of a ws dependent curve (power/ct)

        Parameters
        ----------
        func : function
            curve function (power/ct)
        err_tol_factor : float, default is 0.01
            the number of data points used by the spline is increased until the relative
            sum of errors is less than err_tol_factor.
        """
        # make curve tabular
        ws = np.arange(0, 100, .001)
        power, ct = [self.np_interp(ws, run_only=i) for i in [0, 1]]

        # smoothen curve to avoid spline oscillations around steps (especially around cut out)
        n, e = 99, 3
        lp_filter = ((np.cos(np.linspace(-np.pi, np.pi, n)) + 1) / 2)**e
        lp_filter /= lp_filter.sum()
        power = np.convolve(power, lp_filter, 'same')
        ct = np.convolve(ct, lp_filter, 'same')

        # make spline
        self.power_spline, self.ct_spline = [
            UnivariateSpline(ws, curve, s=(curve.max() * err_tol_factor)**2)
            for curve in [power, ct]
        ]
        self.power_ct_spline_derivative = self.power_spline.derivative(
        ), self.ct_spline.derivative()
Example #16
0
        def get_spline(func, err_tol_factor=1e-2):
            """Generate a spline of a ws dependent curve (power/ct)

            Parameters
            ----------
            func : function
                curve function (power/ct)
            err_tol_factor : float, default is 0.01
                the number of data points used by the spline is increased until the relative
                sum of errors is less than err_tol_factor.
            """
            # make curve tabular
            ws = np.arange(0, 100, .001)
            curve = func(ws, yaw=0)

            # smoothen curve to avoid spline oscillations around steps (especially around cut out)
            n, e = 99, 3
            lp_filter = ((np.cos(np.linspace(-np.pi, np.pi, n)) + 1) / 2)**e
            lp_filter /= lp_filter.sum()
            curve = np.convolve(curve, lp_filter, 'same')

            # make spline
            return UnivariateSpline(ws,
                                    curve,
                                    s=(curve.max() * err_tol_factor)**2)
Example #17
0
 def test_increasing_x(self):
     xx = np.arange(10, dtype=float)
     yy = xx**3
     x = np.arange(10, dtype=float)
     x[1] = x[0]
     y = x**3
     w = np.ones_like(x)
     # also test LSQUnivariateSpline [which needs explicit knots]
     spl = UnivariateSpline(xx, yy, check_finite=True)
     t = spl.get_knots()[3:4]  # interior knots w/ default k=3
     assert_raises(ValueError, UnivariateSpline,
                   **dict(x=x, y=y, check_finite=True))
     assert_raises(ValueError, InterpolatedUnivariateSpline,
                   **dict(x=x, y=y, check_finite=True))
     assert_raises(ValueError, LSQUnivariateSpline,
                   **dict(x=x, y=y, t=t, w=w, check_finite=True))
def univariate_spline(df: DataFrame, var=45):

    sample_header_names = [
        h.name for h in process_header_data(df, HeaderType.SAMPLE)
    ]
    depth = 'depth (m abs)'

    x = df[depth]
    xs = np.linspace(min(x), max(x), var)
    xs_dict = {depth: pandas.Series(xs)}

    for sample_header_name in sample_header_names:
        y = df[sample_header_name]
        spl = UnivariateSpline(x, y)
        new_spl = pandas.Series(spl(xs))
        spline_xs = {sample_header_name: new_spl}
        xs_dict.update(spline_xs)
    spline_df = pandas.concat(xs_dict, axis=1)

    colnames = spline_df.columns.tolist()

    colnames = colnames[-1:] + colnames[:-1]

    spline_df = spline_df[colnames]
    return spline_df
Example #19
0
 def test_preserve_shape(self):
     x = [1, 2, 3]
     y = [0, 2, 4]
     lut = UnivariateSpline(x, y, k=1)
     arg = 2
     assert_equal(shape(arg), shape(lut(arg)))
     assert_equal(shape(arg), shape(lut(arg, nu=1)))
     arg = [1.5, 2, 2.5]
     assert_equal(shape(arg), shape(lut(arg)))
     assert_equal(shape(arg), shape(lut(arg, nu=1)))
Example #20
0
 def test_strictly_increasing_x(self):
     # Test the x is required to be strictly increasing for
     # UnivariateSpline if s=0 and for InterpolatedUnivariateSpline,
     # but merely increasing for UnivariateSpline if s>0
     # and for LSQUnivariateSpline; see gh-8535
     xx = np.arange(10, dtype=float)
     yy = xx**3
     x = np.arange(10, dtype=float)
     x[1] = x[0]
     y = x**3
     w = np.ones_like(x)
     # also test LSQUnivariateSpline [which needs explicit knots]
     spl = UnivariateSpline(xx, yy, check_finite=True)
     t = spl.get_knots()[3:4]  # interior knots w/ default k=3
     UnivariateSpline(x=x, y=y, w=w, s=1, check_finite=True)
     LSQUnivariateSpline(x=x, y=y, t=t, w=w, check_finite=True)
     assert_raises(ValueError, UnivariateSpline,
                   **dict(x=x, y=y, s=0, check_finite=True))
     assert_raises(ValueError, InterpolatedUnivariateSpline,
                   **dict(x=x, y=y, check_finite=True))
Example #21
0
 def test_resize_regression(self):
     """Regression test for #1375."""
     x = [-1., -0.65016502, -0.58856235, -0.26903553, -0.17370892,
          -0.10011001, 0., 0.10011001, 0.17370892, 0.26903553, 0.58856235,
          0.65016502, 1.]
     y = [1.,0.62928599, 0.5797223, 0.39965815, 0.36322694, 0.3508061,
          0.35214793, 0.3508061, 0.36322694, 0.39965815, 0.5797223,
          0.62928599, 1.]
     w = [1.00000000e+12, 6.88875973e+02, 4.89314737e+02, 4.26864807e+02,
          6.07746770e+02, 4.51341444e+02, 3.17480210e+02, 4.51341444e+02,
          6.07746770e+02, 4.26864807e+02, 4.89314737e+02, 6.88875973e+02,
          1.00000000e+12]
     spl = UnivariateSpline(x=x, y=y, w=w, s=None)
     desired = array([0.35100374, 0.51715855, 0.87789547, 0.98719344])
     assert_allclose(spl([0.1, 0.5, 0.9, 0.99]), desired, atol=5e-4)
Example #22
0
 def test_empty_input(self):
     # Test whether empty input returns an empty output. Ticket 1014
     x = [1, 3, 5, 7, 9]
     y = [0, 4, 9, 12, 21]
     spl = UnivariateSpline(x, y, k=3)
     assert_array_equal(spl([]), array([]))