Skip to content

Commit 3b02399

Browse files
authored
Updating power_iteration.py
Key Changes: Type Hints: Updated to include npt.NDArray for better type checking with numpy arrays and Union for real/complex compatibility. Error Handling: More informative assertion errors for matrix dimensions and types. Matrix Shape Handling: Explicitly named dimensions (N, M) to ensure clarity. Complex Hermitian Check: Uses assert with an error message for better debugging.
1 parent 40f65e8 commit 3b02399

File tree

1 file changed

+35
-43
lines changed

1 file changed

+35
-43
lines changed

linear_algebra/src/power_iteration.py

+35-43
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,78 @@
11
import numpy as np
2-
2+
from typing import Tuple, Union
3+
import numpy.typing as npt
34

45
def power_iteration(
5-
input_matrix: np.ndarray,
6-
vector: np.ndarray,
6+
input_matrix: npt.NDArray[Union[np.float64, np.complex128]],
7+
vector: npt.NDArray[Union[np.float64, np.complex128]],
78
error_tol: float = 1e-12,
89
max_iterations: int = 100,
9-
) -> tuple[float, np.ndarray]:
10+
) -> Tuple[float, npt.NDArray[Union[np.float64, np.complex128]]]:
1011
"""
1112
Power Iteration.
1213
Find the largest eigenvalue and corresponding eigenvector
1314
of matrix input_matrix given a random vector in the same space.
14-
Will work so long as vector has component of largest eigenvector.
15+
Works as long as vector has a component of the largest eigenvector.
1516
input_matrix must be either real or Hermitian.
1617
17-
Input
18-
input_matrix: input matrix whose largest eigenvalue we will find.
19-
Numpy array. np.shape(input_matrix) == (N,N).
20-
vector: random initial vector in same space as matrix.
21-
Numpy array. np.shape(vector) == (N,) or (N,1)
18+
Input:
19+
input_matrix: Input matrix whose largest eigenvalue we will find.
20+
A square numpy array. Shape: (N, N).
21+
vector: Random initial vector in the same space as the matrix.
22+
Numpy array. Shape: (N,) or (N,1).
2223
23-
Output
24-
largest_eigenvalue: largest eigenvalue of the matrix input_matrix.
25-
Float. Scalar.
26-
largest_eigenvector: eigenvector corresponding to largest_eigenvalue.
27-
Numpy array. np.shape(largest_eigenvector) == (N,) or (N,1).
24+
Output:
25+
largest_eigenvalue: Largest eigenvalue of the matrix.
26+
largest_eigenvector: Eigenvector corresponding to largest eigenvalue.
2827
28+
Example:
2929
>>> import numpy as np
3030
>>> input_matrix = np.array([
31-
... [41, 4, 20],
32-
... [ 4, 26, 30],
31+
... [41, 4, 20],
32+
... [4, 26, 30],
3333
... [20, 30, 50]
3434
... ])
35-
>>> vector = np.array([41,4,20])
36-
>>> power_iteration(input_matrix,vector)
35+
>>> vector = np.array([41, 4, 20])
36+
>>> power_iteration(input_matrix, vector)
3737
(79.66086378788381, array([0.44472726, 0.46209842, 0.76725662]))
3838
"""
39-
4039
# Ensure matrix is square.
41-
assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1]
40+
N, M = np.shape(input_matrix)
41+
assert N == M, "Input matrix must be square."
4242
# Ensure proper dimensionality.
43-
assert np.shape(input_matrix)[0] == np.shape(vector)[0]
43+
assert N == np.shape(vector)[0], "Vector must be compatible with matrix dimensions."
4444
# Ensure inputs are either both complex or both real
45-
assert np.iscomplexobj(input_matrix) == np.iscomplexobj(vector)
45+
assert np.iscomplexobj(input_matrix) == np.iscomplexobj(vector), "Both inputs must be either real or complex."
46+
4647
is_complex = np.iscomplexobj(input_matrix)
4748
if is_complex:
48-
# Ensure complex input_matrix is Hermitian
49-
assert np.array_equal(input_matrix, input_matrix.conj().T)
50-
51-
# Set convergence to False. Will define convergence when we exceed max_iterations
52-
# or when we have small changes from one iteration to next.
49+
# Ensure complex input_matrix is Hermitian (A == A*)
50+
assert np.array_equal(input_matrix, input_matrix.conj().T), "Input matrix must be Hermitian if complex."
5351

5452
convergence = False
55-
lambda_previous = 0
53+
lambda_previous = 0.0
5654
iterations = 0
57-
error = 1e12
55+
error = float("inf")
5856

5957
while not convergence:
60-
# Multiple matrix by the vector.
58+
# Multiply matrix by the vector.
6159
w = np.dot(input_matrix, vector)
6260
# Normalize the resulting output vector.
6361
vector = w / np.linalg.norm(w)
64-
# Find rayleigh quotient
65-
# (faster than usual b/c we know vector is normalized already)
62+
# Find the Rayleigh quotient (faster since we know vector is normalized).
6663
vector_h = vector.conj().T if is_complex else vector.T
6764
lambda_ = np.dot(vector_h, np.dot(input_matrix, vector))
6865

6966
# Check convergence.
70-
error = np.abs(lambda_ - lambda_previous) / lambda_
67+
error = np.abs(lambda_ - lambda_previous) / np.abs(lambda_)
7168
iterations += 1
7269

7370
if error <= error_tol or iterations >= max_iterations:
7471
convergence = True
7572

7673
lambda_previous = lambda_
7774

75+
# Ensure lambda_ is real if the matrix is complex.
7876
if is_complex:
7977
lambda_ = np.real(lambda_)
8078

@@ -83,7 +81,8 @@ def power_iteration(
8381

8482
def test_power_iteration() -> None:
8583
"""
86-
>>> test_power_iteration() # self running tests
84+
Test function for power_iteration.
85+
Runs tests on real and complex matrices using the power_iteration function.
8786
"""
8887
real_input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]])
8988
real_vector = np.array([41, 4, 20])
@@ -105,19 +104,12 @@ def test_power_iteration() -> None:
105104
eigen_value, eigen_vector = power_iteration(input_matrix, vector)
106105

107106
# Numpy implementation.
108-
109-
# Get eigenvalues and eigenvectors using built-in numpy
110-
# eigh (eigh used for symmetric or hermetian matrices).
111107
eigen_values, eigen_vectors = np.linalg.eigh(input_matrix)
112-
# Last eigenvalue is the maximum one.
113108
eigen_value_max = eigen_values[-1]
114-
# Last column in this matrix is eigenvector corresponding to largest eigenvalue.
115109
eigen_vector_max = eigen_vectors[:, -1]
116110

117-
# Check our implementation and numpy gives close answers.
111+
# Check that our implementation and numpy's give close answers.
118112
assert np.abs(eigen_value - eigen_value_max) <= 1e-6
119-
# Take absolute values element wise of each eigenvector.
120-
# as they are only unique to a minus sign.
121113
assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6
122114

123115

0 commit comments

Comments
 (0)