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

# # Discrete Green's Functions and Interaction Rank
# 
# 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[3]:


import numpy as np
import scipy.linalg as la

import matplotlib.pyplot as pt


# Let's solve $u''=-30x^2$ with $u(0)=1$ and $u(1)=-1$.

# In[5]:


n = 50

mesh = np.linspace(0, 1, n)
h = mesh[1] - mesh[0]


# Set up the system matrix `A` to carry out centered finite differences
# 
# $$
# u''(x)\approx \frac{u(x+h) - 2u(x) + u(x-h)}{h^2}.
# $$
# 
# Use `np.eye(n, k=...)`. What needs to be in the first and last row?

# In[6]:


A = (np.eye(n, k=1) + -2*np.eye(n) + np.eye(n, k=-1))/h**2
A[0] = 0
A[-1] = 0
A[0,0] = 1
A[-1,-1] = 1


# Next, fix the right hand side: 

# In[7]:


b = -30*mesh**2
b[0] = 1
b[-1] = -1


# Compute a reference solution `x_true` to the linear system:

# In[8]:


x_true = la.solve(A, b)
pt.plot(mesh, x_true)


# Next, let's consider the influence of each individual RHS component:

# In[18]:


b = np.zeros_like(mesh)

# experiment with these set to zero/nonzero
b[17] = 1
b[0] = 0
b[-1] = 0


# In[19]:


x_true = la.solve(A, b)
pt.plot(mesh, x_true)


# In[20]:


pt.imshow(np.log10(1e-15+np.abs(la.inv(A))))


# In[ ]:




