MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / lanczos_iteration

Function lanczos_iteration

graphs/lanczos_eigenvectors.py:71–130  ·  view source on GitHub ↗

Constructs the tridiagonal matrix and orthonormal basis vectors using the Lanczos method. Args: graph: The graph represented as a list of adjacency lists. num_eigenvectors: The number of largest eigenvalues and eigenvectors to approximate. Retu

(
    graph: list[list[int | None]], num_eigenvectors: int
)

Source from the content-addressed store, hash-verified

69
70
71def lanczos_iteration(
72 graph: list[list[int | None]], num_eigenvectors: int
73) -> tuple[np.ndarray, np.ndarray]:
74 """Constructs the tridiagonal matrix and orthonormal basis vectors using the
75 Lanczos method.
76
77 Args:
78 graph: The graph represented as a list of adjacency lists.
79 num_eigenvectors: The number of largest eigenvalues and eigenvectors
80 to approximate.
81
82 Returns:
83 A tuple containing:
84 - tridiagonal_matrix: A (num_eigenvectors x num_eigenvectors) symmetric
85 matrix.
86 - orthonormal_basis: A (num_nodes x num_eigenvectors) matrix of orthonormal
87 basis vectors.
88
89 Raises:
90 ValueError: If num_eigenvectors is less than 1 or greater than the number of
91 nodes.
92
93 >>> graph = [[1, 2], [0, 2], [0, 1]]
94 >>> T, Q = lanczos_iteration(graph, 2)
95 >>> T.shape == (2, 2) and Q.shape == (3, 2)
96 True
97 """
98 num_nodes: int = len(graph)
99 if not (1 <= num_eigenvectors <= num_nodes):
100 raise ValueError(
101 "Number of eigenvectors must be between 1 and the number of "
102 "nodes in the graph."
103 )
104
105 orthonormal_basis: np.ndarray = np.zeros((num_nodes, num_eigenvectors))
106 tridiagonal_matrix: np.ndarray = np.zeros((num_eigenvectors, num_eigenvectors))
107
108 rng = np.random.default_rng()
109 initial_vector: np.ndarray = rng.random(num_nodes)
110 initial_vector /= np.sqrt(np.dot(initial_vector, initial_vector))
111 orthonormal_basis[:, 0] = initial_vector
112
113 prev_beta: float = 0.0
114 for iter_index in range(num_eigenvectors):
115 result_vector: np.ndarray = multiply_matrix_vector(
116 graph, orthonormal_basis[:, iter_index]
117 )
118 if iter_index > 0:
119 result_vector -= prev_beta * orthonormal_basis[:, iter_index - 1]
120 alpha_value: float = np.dot(orthonormal_basis[:, iter_index], result_vector)
121 result_vector -= alpha_value * orthonormal_basis[:, iter_index]
122
123 prev_beta = np.sqrt(np.dot(result_vector, result_vector))
124 if iter_index < num_eigenvectors - 1 and prev_beta > 1e-10:
125 orthonormal_basis[:, iter_index + 1] = result_vector / prev_beta
126 tridiagonal_matrix[iter_index, iter_index] = alpha_value
127 if iter_index < num_eigenvectors - 1:
128 tridiagonal_matrix[iter_index, iter_index + 1] = prev_beta

Callers 1

Calls 1

multiply_matrix_vectorFunction · 0.85

Tested by

no test coverage detected