Skip to content

Instantly share code, notes, and snippets.

@jgillis
Last active February 28, 2020 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgillis/aef7659069df4fed8249f803ee7003c8 to your computer and use it in GitHub Desktop.
Save jgillis/aef7659069df4fed8249f803ee7003c8 to your computer and use it in GitHub Desktop.
Going from piecewise polynomials to CasADi BSplines
close all
% casadi.interpolant creates 'knots' and 'coefficients' out of data and passes it on to casadi.Function.bspline
% Here, we supply knots and coefficients directly to casadi.Function.bspline
%% Example 1: discontinuous example, just to make clear the interpretation
% of the pp = piecewise polynomial form clear
% 4 intervals: 0-1, 1-2, 2-4, 4-6
breaks = [0,1,2,4,6];
coeffs = [1 0 0 ... % on interval 1: x^2 (local coordinates)
0 1 0 ... % on interval 2: x (local coordinates)
0 0 1 ... % on interval 3: 1 (local coordinates)
1 2 -1]; % on interval 4: x^2+x*x-1 (local coordinates)
pp = ppmak(breaks,coeffs);
x = linspace(0,6,1000);
plot(x,fnval(pp,x));
hold on
sp = fn2fm(pp,'B-');
spline = casadi.Function.bspline('spline',{sp.knots},sp.coefs,[sp.order-1]);
% Note not really meant for discontinuities/knots with multiplicity>1 inside the interval
plot(x,full(spline(x)),'x')
legend('Matlab pp','CasADi spline')
%% Example 2: now a spline that is smooth
breaks = [0,1,2,4,6];
coeffs = [-2 2 1 ... % on interval 1: -2*x^2+2*x+1 (local coordinates)
2 -2 1 ... % on interval 2: x^2-2*x+1 (local coordinates)
-3/8 2 1 ...
-7/8 0.5 3.5];
pp = ppmak(breaks,coeffs);
figure()
x = linspace(0,6,100);
plot(x,fnval(pp,x));
hold on
sp = fn2fm(pp,'B-');
spline = casadi.Function.bspline('spline',{sp.knots},sp.coefs,[sp.order-1]);
plot(x,full(spline(x)),'x')
legend('Matlab pp','CasADi spline')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment