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

# # Kernel in the Source and Target Variables ("Anterpolation and Interpolation")
# 
# Copyright (C) 2026 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[52]:


import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as plt


# Some Chebyshev utilities up front:

# In[53]:


def Tk(k, x):
    return np.cos(k*np.arccos(x))

nnodes = 20
k = nnodes-1
nodes = np.cos(np.arange(k+1)/k*np.pi)

xplot = np.linspace(-1, 1, 1000)
plt.plot(xplot, Tk(k, xplot))
plt.plot(nodes, Tk(k, nodes), "x")


# Now construct an interpolation toolkit with `vdm(targets)` and `interp_to_targets(targets, nodes)`, and test it:

# In[73]:


def vdm(targets):
    return Tk(np.arange(k+1), targets[:, None])

def interp_to_targets(targets, nodes):
    return vdm(targets) @ la.inv(vdm(nodes))

print(la.norm(np.sin(5*xplot) - interp_to_targets(xplot, nodes)@np.sin(5*nodes), np.inf))


# In[74]:


N = 1000
sources = np.random.rand(N) * 2 - 1
charges = np.random.randn(N)

targets = np.random.rand(N)*2 - 1 - 4

def interaction_mat(targets, sources):
    return np.log(np.abs(targets[:, None] - sources))


# Try out target-space interpolation as a matrix identity:

# In[75]:


tgt_nodes = nodes - 4
la.norm(
    interp_to_targets(targets+4, tgt_nodes+4) @ interaction_mat(tgt_nodes, sources)
    -
    interaction_mat(targets, sources),
    2
)


# Now try out source interpolation ("anterpolation") as a matrix identity:

# In[76]:


la.norm(
    interaction_mat(targets, nodes) @ interp_to_targets(sources, nodes).T
    -
    interaction_mat(targets, sources), 
    2)


# In[ ]:




