Second Example - Comparison With/Without Constraint

This example compares a cubic spline without constraints and a cubic spline with a monotonicity constraint.

Complete Code

examples/quick_start2.py
    import numpy as np
    from BsplineQuantRegpy import SplineCubicQuant
    import matplotlib.pyplot as plt
    
    print("test_basic_fit")
    x = np.linspace(0, 1, 30)
    #y = x + 0.5*np.sin(10*np.pi*x) + 0.05*np.random.randn(30)
    y = x*(1-x) + 0.05*np.random.randn(30)

    x_eval = np.linspace(0, 1, 100)

    knots = np.quantile(x, np.linspace(0, 1, 6))
    result = SplineCubicQuant(x, y, knots, tau=0.5)
    y_eval = result(x_eval)


    print(" test_monotonicity")

    knots = np.quantile(x, np.linspace(0, 1, 6))
    result_m = SplineCubicQuant(x, y, knots, tau=0.5, monot=1)

    y_eval_m = result_m(x_eval)


    plt.plot(x,y,"*r")
    plt.plot(x_eval,y_eval,color='grey')
    plt.plot(x_eval,y_eval_m,color='black')
    plt.show()

Explanation

  1. Data: - 30 points on the interval [0, 1] - The target function is \(x(1-x)\) with added noise

  2. Two fits: - Unconstrained: Standard cubic spline (SplineCubicQuant without constraint parameter) - Constrained: Cubic spline with monot=1 (increasing)

  3. Visual comparison: - Data points in red - Unconstrained spline in gray - Constrained spline in black

Result

The graph illustrates how the monotonicity constraint forces the curve to remain increasing, unlike the unconstrained spline which may exhibit oscillations.

Possible Modification

You can test other constraints by modifying the monot parameter: - monot=-1: decreasing - convex=1: convex - convex=-1: concave