I am interpolating an array and there is the possibility, that I might not have enough knots for the interpolation. In this case, I will need to adjust the degree of the smoothing spline. In the minimal working example given below, this would be the case if N = 3
.
from scipy.interpolate import InterpolatedUnivariateSpline
import numpy as np
N = 10 # is working fine
# N = 3 # produces error
x = np.linspace(-3, 3, N)
y = np.exp(-x**2) + 0.1 * np.random.randn(N)
spline = InterpolatedUnivariateSpline(x, y, bbox=[x[0],x[-1]], k=3, ext=0)
x_full = np.linspace(-3,3,10*N)
yspline = spline(x_full)
The error, if N=3
is
error: (m>k) failed for hidden m: fpcurf0:m=3
.
The same error as described here and here. I know what this error means and know why it appears, this is not the issue.
I would like to write a try/except to catch this case and handle it appropriately.
What <ErrorType>
would this be?
try:
spline = InterpolatedUnivariateSpline(x, y, bbox=[x[0],x[-1]], k=3, ext=0)
yspline = spline(x_full)
except <ErrorType>:
print('something')
(I know I could instead write an if/else
statement checking the length of x
and y
. I will keep this in mind as an alternative. But for know, it would be better to use the try/except
statement.)
except Exception
. While generally considered bad form (for a reason!), it'll work here.