# ## MIT License

# 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.
#

# In[1]:
import numpy as np
import numpy.linalg as la
# In[2]:
np.random.seed(15)
n = 5
A = np.random.randn(n, n)
# Now compute the eigenvalues and eigenvectors of $A^TA$ as `eigvals` and `eigvecs` using `la.eig` or `la.eigh` (symmetric):
# In[3]:
eigvals, eigvecs = la.eigh(A.T @ A)
# In[4]:
eigvals
# Eigenvalues are real and non-negative. Coincidence?
# In[5]:
eigvecs.shape
# Check that those are in fact eigenvectors and eigenvalues:
# In[6]:
B = A.T @ A
B - eigvecs @ np.diag(eigvals) @ la.inv(eigvecs)
# `eigvecs` are orthonormal! (Why?)
#
# Check:
# In[7]:
la.norm(eigvecs.T @ eigvecs - np.eye(n))
# Now piece together the SVD:
# In[8]:
Sigma = np.diag(np.sqrt(eigvals))
# In[9]:
V = eigvecs
# In[10]:
U = A @ V @ la.inv(Sigma)
# Check orthogonality of `U`:
# In[11]:
U @ U.T - np.eye(n)
# In[ ]: