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

# # Reusing Decompressors
# 
# 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[15]:


import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as pt
import scipy.linalg.interpolative as sli


# In[28]:


sources = np.random.rand(2, 800)
targets = np.random.rand(2, 800) + 3

all_distvecs = sources.reshape(2, 1, -1) - targets.reshape(2, -1, 1)
dists = np.sqrt(np.sum(all_distvecs**2, axis=0))
A = 1/dists


# In[31]:


k = 40
U, sigma, VT = la.svd(A)
pt.semilogy(sigma[:k])


# In[55]:


Q = U[:, :k]
Q.shape


# In[36]:


la.norm(Q@Q.T@A - A, 2)


# In[49]:


def interp_decomp(A, k):
    idx, proj = sli.interp_decomp(A, k)
    P = np.hstack([np.eye(k), proj])[:,np.argsort(idx)]
    return P, idx[:k]


# In[53]:


P, J = interp_decomp(Q.T, k)
print(P.T.shape)


# In[62]:


la.norm(Q.T[:, J]@P - Q.T, 2)


# Recast this as $\tilde P Q_J \approx Q$.

# In[66]:


la.norm(P.T@Q[J] - Q, 2)


# Now try the same thing on $A$:

# In[65]:


la.norm(P.T@A[J] - A, 2)


# In[ ]:




