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

# # QR Iteration
# 
# Copyright (C) 2023 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[6]:


import numpy as np
import numpy.linalg as la

np.set_printoptions(linewidth=120)


# Make a matrix with given eigenvalues:

# In[7]:


n = 5

np.random.seed(70)
eigvecs = np.random.randn(n, n)
eigvals = np.sort(np.random.randn(n))

A = np.dot(la.solve(eigvecs, np.diag(eigvals)), eigvecs)
print(eigvals)


# ## Unshifted QR

# In[121]:


X = A
Qall = np.eye(n)


# In[142]:


Q, R = la.qr(X)
X = R @ Q

Qall = Qall @ Q

print(X)


# In[169]:


np.tril(X, -1)


# In[170]:


la.norm(np.tril(X, -1))


# In[143]:


la.norm(A - Qall @ X @ Qall.T, 2) / la.norm(A, 2)


# ## Shifted QR

# In[145]:


X = A
Qall = np.eye(n)


# In[164]:


i = -4
sigma = X[i,i]
Q, R = la.qr(X - sigma*np.eye(n))
X = R @ Q + sigma*np.eye(n)

Qall = Qall @ Q

print(X)


# To compare convergence speed, count iterations until left-of-diagonal entries decay below $10^{-10}$.

# In[172]:


la.norm(np.tril(X, -1))


# In[173]:


la.norm(A - Qall @ X @ Qall.T, 2) / la.norm(A, 2)


# In[ ]:




