## Pages

### B-spline Curve Fitting Example in Python

B-spline or basis spline is a curve approximation method based on given coefficients. B-spline requires the parameters such as knots, spline coefficients, and degree of a spline. The SciPy API provides BSpline class to implement the B-spline fitting for a given dataset.
In this tutorial, you'll learn how to implement B-spline interpolation by using a BSpline class in Python. The tutorial covers:

1. B-spline interpolation
2. Source code listing

` `
```from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np ```
` `

B-spline interpolation

B-spline constructs a curve for given data points and it is useful function to smooth a curve or surface data. Here, we'll see how B-spline can help us to smooth a given curve data.
We'll prepare dataset for this tutorial and visualize it in a plot. The target data contains x and y components of curve data. You may apply the same method for your target data.

```y = [0,1,3,4,3,5,7,5,2,3,4,8,9,8,7]
n = len(y)
x = range(0, n) ```
` `

Next, we'll visualize the data and linear interpolation on a graph. Linear interpolation in a graph is simply connecting data points linearly.

` `
```plt.plot(x, y, 'ro', label="original")
plt.plot(x, y, 'b', label="linear interpolation")
plt.title("Target data")
plt.grid()
plt.show() ```

To represent B-spline interpolation, we need to provide required coefficients. We can take them by using the 'splrep' function. The 'splrep' function returns t, c, k tuple containing  the vector of knots, the B-spline coefficients, and the degree of the spline.

` `
`tck = interpolate.splrep(x, y, s=0, k=3) `
` `

Next, we'll create new x data with more sample number to make smoother curve. Then build the B-splne curve on this data.

` `
```x_new = np.linspace(min(x), max(x), 100)
y_fit = interpolate.BSpline(*tck)(x_new)
```
` `

Finally, we can visualize the constructed B-spline curve on a graph.

` `
```plt.title("BSpline curve fitting")
plt.plot(x, y, 'ro', label="original")
plt.plot(x_new, y_fit, '-c', label="B-spline")
plt.grid()
plt.show() ```
` `

In this tutorial, we've briefly learned how to implement B-spline interpolation by using SciPy API's BSpline class in Python. The full source code is listed below.

Source code listing

` `
```from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np

y = [0,1,3,4,3,5,7,5,2,3,4,8,9,8,7]
n = len(y)
x = range(0, n)

plt.plot(x, y, 'ro', label="original")
plt.plot(x, y, 'b', label="linear interpolation")
plt.title("Target data")
plt.grid()
plt.show()

tck = interpolate.splrep(x, y, s=0, k=3)
x_new = np.linspace(min(x), max(x), 100)
y_fit = interpolate.BSpline(*tck)(x_new)

plt.title("BSpline curve fitting")
plt.plot(x, y, 'ro', label="original")
plt.plot(x_new, y_fit, '-c', label="B-spline")
`  `