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

# # Playing with Barycentric Interpolation
# 
# Copyright (C) 2020 Andreas Kloeckner
# 
# <details>
# <summary>MIT License</summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# </details>

# In[29]:


import numpy as np
import matplotlib.pyplot as plt


# In[49]:


x = np.linspace(-1, 1, 5)
xx = np.linspace(-1, 1, 100)

def f(x):
    return np.sin(5/(1.6-x))


# In[50]:


plt.plot(xx, f(xx))
plt.plot(x, f(x), "o")


# In[80]:


dmat = x.reshape(-1, 1) - x
np.fill_diagonal(dmat, 1)
dmat[0, 2], x[0]-x[2]


# In[128]:


w = 1/dmat.prod(axis=1)
w


# In[119]:


def bary_first_form(z, f):
    z = z[:, np.newaxis]
    ell = (z-x).prod(axis=-1)
    return ell * (w / (z - x) * f(x)).sum(axis=-1)


# In[129]:


plt.plot(xx, bary_first_form(xx, f))
plt.plot(xx, f(xx))


# In[134]:


def bary_second_form(z, f, weights=None):
    if weights is None:
        weights = w
    z = z[:, np.newaxis]
    num = (weights / (z - x) * f(x)).sum(axis=-1)
    denom = (weights / (z - x)).sum(axis=-1)
    return num/denom


# In[140]:


wr = w.copy()
wr[:] = np.random.randn(len(x))

plt.plot(xx, bary_second_form(xx, f))
plt.plot(xx, bary_second_form(xx, f, weights=wr))
plt.plot(xx, f(xx))
plt.plot(x, f(x), "o")
plt.ylim([-2, 2])


# In[ ]:




