#!/usr/bin/env python
# coding: utf-8

# In[1]:


#example points to interpolate
from numpy import array
x = array([1, 2, 3, 4])
y = array([3, 4, 6, 7])


# In[5]:


#linear spline
from numpy import interp, linspace
xi = linspace(1, 4)
yil = interp(xi, x, y)


# In[6]:


from matplotlib.pyplot import plot
plot(x, y, 's', xi, yil)


# In[7]:


#interpolating polynomial
from numpy import polyfit, polyval
p = polyfit(x, y, 3)
yip = polyval(p, xi)


# In[8]:


plot(x, y, 's', xi, yip)


# In[10]:


#Lagrange form of interpolating polynomial
n = 4
yipl = 0
for i in range(n):
    term = 1
    for j in range(n):
        if j != i:
            term = term * (xi - x[j])/(x[i] - x[j])
    term = term * y[i]
    yipl = yipl + term


# In[12]:


plot(x, y, 's', xi, yipl, '-', xi, yip)


# In[13]:


plot(xi, yipl - yip)


# In[14]:


#cubic spline interpolation
from scipy.interpolate import CubicSpline
s1 =  CubicSpline(x, y, bc_type='not-a-knot')


# In[18]:


s2 =  CubicSpline(x, y, bc_type='natural')


# In[27]:


from scipy.interpolate import PchipInterpolator
#piecewise cubic Hermite interpolation (shape-preserving)
pchip = PchipInterpolator(x, y)


# In[26]:


yis1 = s1(xi)
yis2 = s2(xi)
yipchip = pchip(xi)


# In[28]:


from matplotlib.pyplot import legend
plot(x, y, 's', xi, yis1, '-', xi, yis2, '-', xi, yipchip)
legend(['points', 'not-a-knot cubic spline', 'natural cubic spline', 'PCHIP'])


# In[32]:


s2.c


# In[29]:


s1.c #coefficients of all the cubic spline pieces (4 for each piece)


# In[30]:


s1.solve(5) #find at what point the piecewise polynomial is equal to 5


# In[31]:


s1(2.5)


# In[ ]:




