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

# # LU Factorization
# 
# Copyright (C) 2021 Andreas Kloeckner
# 
# In part based on material by Edgar Solomonik
# 
# <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[54]:


import numpy as np
import numpy.linalg as la

np.set_printoptions(linewidth=150, suppress=True, precision=3)


# In[55]:


A = np.random.randn(4, 4)
A


# Initialize `L` and `U`:

# In[56]:


L = np.eye(len(A))
U = np.zeros_like(A)


# Recall the "recipe" for LU factorization:
# 
# $$\let\B=\boldsymbol \begin{array}{cc}
#      & \left[\begin{array}{cc}
#        u_{00} & \B{u}_{01}^T\\
#        & U_{11}
#      \end{array}\right]\\
#      \left[\begin{array}{cc}
#        1 & \\
#        \B{l}_{10} & L_{11}
#      \end{array}\right] & \left[\begin{array}{cc}
#        a_{00} & \B{a}_{01}\\
#        \B{a}_{10} & A_{11}
#      \end{array}\right]
#    \end{array}$$
# 
# Find $u_{00}$ and $u_{01}$. Check `A - L@U`.

# In[57]:


U[0] = A[0]
A - L@U


# Find $l_{10}$. Check `A - L@U`.

# In[58]:


L[1:,0] = A[1:,0]/U[0,0]
A - L@U


# Recall $A_{22} =\B{l}_{21} \B{u}_{12}^T + L_{22} U_{22}$. Write the next step generic in terms of `i`.
# 
# After the step, print `A-L@U` and `remaining`.

# In[59]:


i = 1
remaining = A - L@U


# In[62]:


U[i, i:] = remaining[i, i:]
L[i+1:,i] = remaining[i+1:,i]/U[i,i]
remaining[i+1:, i+1:] -= np.outer(L[i+1:,i], U[i, i+1:])

i = i + 1

print(remaining)
print(A-L@U)


# In[ ]:




