Search code examples
pythonscipy

Python: interpolate.UnivariateSpline package 'error: (xb<=x[0]) failed for 2nd keyword xb: fpcurf0:xb=3.78832'


I have been attempting to plot a line, along with a spline fitting. The following is a generalized version of my code. 'wavelength' and 'absorbance' are lists containing lists of float values. Generalized version of my code:

import matplotlib.pyplot as plt
import csv
from scipy.interpolate import UnivariateSpline
s = UnivariateSpline(wavelength, absorbance,bbox=[p[0][0],b[0][0]],s = 5)
n1 = len(wavelength)
xs = np.linspace(wavelength[0], wavelength[-1], n1*100)
ys = s(xs)
s.set_smoothing_factor(0.8)

plt.plot(wavelength, absorbance, 'o')
plt.plot(xs, ys,lw=3)
plt.show()

I now obtain an error message:

Cell In[125], line 1
----> 1 plot3(r'C:\\Users\\meng.zu\\Desktop\\convert 
data\\D1_17.1.SSC.txt',None,None,None)

Cell In[124], line 57, in plot3(path, c, y, k)
 50             b.append([i,j])
 51             break
 ---> 57 s = UnivariateSpline(wavelength, absorbance,bbox=[p[0] 
 [0],b[0][0]],s = 5)
 58 n1 = len(wavelength)
 59 xs = np.linspace(wavelength[0], wavelength[-1], n1*100)

 File D:\Anaconda\Lib\site-packages\scipy\interpolate\_fitpack2.py:221, in UnivariateSpline.__init__(self, x, y, w, bbox, k, s, ext, check_finite)
217 x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, s, ext,
218                                               check_finite)
220 # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
--> 221 data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0],
222                         xe=bbox[1], s=s)
223 if data[-1] == 1:
224     # nest too small, setting to maximum bound
225     data = self._reset_nest(data)

error: (xb<=x[0]) failed for 2nd keyword xb: fpcurf0:xb=3.78832

where p[0][0] and b[0][0] are two float numbers, and p[0][0] < b[0][0]

If I do it without setting the bbox range, it looks something like this: fit line without setting bbox range However, I want it to fit the peak curve region, so I set the interval around the peak to fit it. This is where the error occurs.

Here are values for p[0][0], b[0][0] and x[0]:

 (3.7883158772582326, 4.035764192724556, 2.859500138756903).

I have tried to look up all possible resources, but cannot find related issue like this.

Any suggestion or comment would be greatly appreciated!


Solution

  • My guess would be that this is an explicit error being thrown by a library that you're using. It's not a failure of your code, per se, but a problem with your data.

    (xb<=x[0]) seems to be causing the failure. Your value for xb is 3.78832. I don't know what the value of x[0] is but my guess is that xb needs to be smaller than it.

    Appears to be something to do with bounding boxes.