B-splines are commonly used as basis functions to fit smoothing curves to large data sets. To do this, the abscissa axis is broken up into some number of intervals, where the endpoints of each interval are called “breakpoints”. These breakpoints are then converted to “knots” by imposing various continuity and smoothness conditions at each interface. Given a nondecreasing knot vector t = {t0, t1, ..., tn+k-1}, the n basis splines of order k are defined by
for i = 0, ..., n-1. The common case of cubic B-splines is given by k = 4. The above recurrence relation can be evaluated in a numerically stable way by the de Boor algorithm.
If we define appropriate knots on an interval [a,b] then the B-spline basis functions form a complete set on that interval. Therefore we can expand a smoothing function as
given enough data pairs. The coefficients ci can be readily obtained from a least-squares fit.
This is the class use to calculate the Basis Splines.
The following example computes a linear least squares fit to data using cubic B-spline basis functions with uniform breakpoints. The data is generated from the curve on the interval [0,15] with gaussian noise added:
-- number of point and breakpoints
n, br = 200, 10
f = |x| cos(x) * exp(-0.1 * x)
xsmp = |i| 15 * (i-1) / (n-1)
-- we calculate the simulated data
x, y = new(n, 1, |i| xsmp(i)), new(n, 1, |i| f(xsmp(i)))
-- we add a gaussian noise and calculate weights
r = rng()
w = new(n, 1)
for i=1,n do
local yi = y:get(i,1)
local sigma = 0.1 * yi
y:set(i,1, yi + rnd.gaussian(r, sigma))
w:set(i,1, 1/sigma^2)
end
-- we create a bspline object and we calculate the model matrix X
b = bspline(0, 15, br)
X = b:model(x)
-- linear least-squares fit
c, cov = mlinear(X, y, w)
-- plot
p = plot('B-splines curve approximation')
p:addline(xyline(x, mul(X, c)))
p:addline(xyline(x, y), 'blue', {{'marker', size=5}})
p:show()
And the resulting plot is: