Skip to content

Commit

Permalink
complete Lanzco's method
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenhky committed Sep 1, 2022
1 parent 4758842 commit 9798fc5
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions mogu/spectral/lanzcos.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# implementing Lanzco's algorithm

import numpy as np
from scipy.linalg import eigh_tridiagonal


def lanzcos(M, k):
Expand All @@ -12,18 +13,20 @@ def lanzcos(M, k):

a = np.zeros(k+1)
b = np.zeros(k)
v = np.zeros((d, k+1))

v0 = np.random.uniform(size=d)
v0 /= np.linalg.norm(v0)
v[:, 0] = np.random.uniform(size=d)
v[:, 0] /= np.linalg.norm(v[:, 0])

a[0] = v0.T @ M @ v0
v1 = M @ v0 - a[0]*v0
v1 /= np.linalg.norm(v1)
a[0] = v[:, 0].T @ M @ v[:, 0]
v[:, 1] = M @ v[:, 0] - a[0] * v[:, 0]
v[:, 1] /= np.linalg.norm(v[:, 1])

for i in range(1, k+1):
a[i] = v1.T @ M @ v1
b[i-1] = v0.T @ M @ v1
v2 = M @ v1 - a[i]*v1 - b[i-1]*v0
v2 /= np.linalg.norm(v2)
for i in range(1, k):
a[i] = v[:, i].T @ M @ v[:, i]
b[i-1] = v[:, i-1].T @ M @ v[:, i]
v[:, i+1] = M @ v[:, i] - a[i] * v[:, i] - b[i-1] * v[:, i-1]
v[:, i+1] /= np.linalg.norm(v[:, i+1])

v0, v1 = v1, v2
eigvals, eigvecs = eigh_tridiagonal(a, b)
return eigvals, v @ eigvecs

0 comments on commit 9798fc5

Please sign in to comment.