qrunch.chemistry.qrackle.matrix_modules.matrix_module_protocols

Protocols for matrices, vectors and matrix modules.

These protocols describe the data containers (matrices and vectors) and the operations that can be performed on them. The data containers themselves expose only metadata and (de)serialization to/from a raw numpy array; every non-trivial numerical operation is performed by the matrix module, which is the natural place to keep track of e.g. device placement (CPU/GPU), MPI distribution or block-sparse structure.

The module protocol is generic over the concrete matrix/vector types it operates on, so a concrete backend such as NumpyMatrixModule is typed against its own concrete NumpyMatrix / NumpyVector classes rather than the general protocols. This makes it impossible to mix matrices originating from different backends.

Classes

EigenvalueSolution

Solution of a standard symmetric eigenvalue problem \(A v = \\lambda v\).

MatrixModuleProtocol

Protocol for a backend that creates and manipulates matrices and vectors.

MatrixProtocol

Protocol for a two-dimensional (possibly non-square) matrix container.

VectorProtocol

Protocol for a one-dimensional vector container.

class EigenvalueSolution

Bases: Generic[TMatrix, TVector]

Solution of a standard symmetric eigenvalue problem \(A v = \\lambda v\).

Parameters:
  • eigenvalues – Vector of eigenvalues, sorted in ascending order.

  • eigenvectors – Matrix whose columns are the corresponding eigenvectors.

__init__(*, eigenvalues: TVector, eigenvectors: TMatrix) → None
Parameters:
  • eigenvalues (TVector)

  • eigenvectors (TMatrix)

Return type:

None

eigenvalues: TVector
eigenvectors: TMatrix
class MatrixModuleProtocol

Bases: Protocol, Generic[TMatrix, TVector]

Protocol for a backend that creates and manipulates matrices and vectors.

A matrix module owns the construction of matrices and vectors and provides all algebraic operations. Different backends (dense numpy, GPU/CUDA, MPI/ScaLAPACK distributed, block-sparse, …) are expected to implement this protocol with their own concrete matrix and vector types.

__init__(*args, **kwargs)
add(left: TMatrix, right: TMatrix) → TMatrix

Calculate the element-wise sum \(L + R\).

Parameters:
  • left (TMatrix) – First summand.

  • right (TMatrix) – Second summand of identical shape.

Return type:

TMatrix

allocation_report() → str

Get a human-readable, multi-line summary of all live allocations.

Backends are expected to include at least the number of live matrices and vectors and the total memory currently in use; richer backends may additionally include per-object shape, byte count and the call-site where the allocation happened.

Return type:

str

antisymmetrize(matrix: TMatrix) → TMatrix

Calculate the antisymmetric projection \(\tfrac{1}{2}(M - M^{T})\).

Parameters:

matrix (TMatrix) – Square matrix to be antisymmetrized.

Return type:

TMatrix

commutator(left: TMatrix, right: TMatrix) → TMatrix

Calculate the commutator \([L, R] = L R - R L\).

The DIIS error vector for closed-shell Hartree-Fock can be written as \(F P S - S P F\) in the non-orthogonal AO basis, or simply \(F P - P F\) in an orthonormal basis.

Parameters:
  • left (TMatrix) – Left operand.

  • right (TMatrix) – Right operand of compatible shape.

Return type:

TMatrix

copy_matrix(matrix: TMatrix) → TMatrix

Create an independent copy of matrix.

Parameters:

matrix (TMatrix) – Matrix to be copied.

Return type:

TMatrix

diagonalize(matrix: TMatrix) → EigenvalueSolution[TMatrix, TVector]

Solve the symmetric eigenvalue problem \(A v = \\lambda v\).

Parameters:

matrix (TMatrix) – Symmetric square matrix.

Return type:

EigenvalueSolution[TMatrix, TVector]

free_matrix(matrix: TMatrix) → None

Release any backend-specific resources associated with matrix.

For CPU/numpy backends this is mostly a bookkeeping operation; for GPU or distributed backends it is the explicit signal to release the device buffer or distributed handle. After this call the matrix must not be used as input to any other method of the module.

Parameters:

matrix (TMatrix) – Matrix whose backing storage should be released.

Return type:

None

free_vector(vector: TVector) → None

Release any backend-specific resources associated with vector.

See free_matrix() for the semantics. After this call the vector must not be used as input to any other method of the module.

Parameters:

vector (TVector) – Vector whose backing storage should be released.

Return type:

None

frobenius_inner_product(left: TMatrix, right: TMatrix) → float

Calculate the Frobenius inner product \(\sum_{i,j} L_{i,j} R_{i,j}\).

Used in DIIS to assemble the \(B\)-matrix of error-vector overlaps.

Parameters:
  • left (TMatrix) – First matrix.

  • right (TMatrix) – Second matrix of identical shape.

Return type:

float

frobenius_norm(matrix: TMatrix) → float

Calculate the Frobenius norm \(\| M \|_{F} = \sqrt{\sum_{i,j} M_{i,j}^{2}}\).

Parameters:

matrix (TMatrix) – Matrix whose Frobenius norm is requested.

Return type:

float

generalized_eigenvalue_solver(a_matrix: TMatrix, b_matrix: TMatrix) → EigenvalueSolution[TMatrix, TVector]

Solve the generalized symmetric eigenvalue problem \(A v = \\lambda B v\).

Parameters:
  • a_matrix (TMatrix) – Symmetric square matrix \(A\).

  • b_matrix (TMatrix) – Symmetric positive-definite square matrix \(B\) of identical shape (typically the AO overlap matrix in HF/DFT).

Return type:

EigenvalueSolution[TMatrix, TVector]

identity(dimension: int) → TMatrix

Get the square identity matrix of the given dimension.

Parameters:

dimension (int) – Number of rows and columns of the identity matrix.

Return type:

TMatrix

init_matrix(shape: tuple[int, int], *, zeroes: bool) → TMatrix

Allocate a new matrix of the given shape.

Parameters:
  • shape (tuple[int, int]) – Desired (number_of_rows, number_of_columns).

  • zeroes (bool) – If True the matrix is initialized to zero, otherwise its contents are unspecified.

Return type:

TMatrix

init_vector(length: int, *, zeroes: bool) → TVector

Allocate a new vector of the given length.

Parameters:
  • length (int) – Desired number of elements.

  • zeroes (bool) – If True the vector is initialized to zero, otherwise its contents are unspecified.

Return type:

TVector

inverse(matrix: TMatrix) → TMatrix

Calculate the inverse \(M^{-1}\).

Parameters:

matrix (TMatrix) – Square non-singular matrix.

Return type:

TMatrix

linear_combination(coefficients: list[float], matrices: list[TMatrix]) → TMatrix

Calculate the linear combination \(\sum_i c_i M_i\).

Used in DIIS to form the extrapolated Fock matrix from a history of Fock matrices.

Parameters:
  • coefficients (list[float]) – Real coefficients \(c_i\).

  • matrices (list[TMatrix]) – Matrices \(M_i\) of identical shape; must be of the same length as coefficients and non-empty.

Return type:

TMatrix

lowdin_orthogonalizer(overlap: TMatrix, threshold: float = 1e-09) → TMatrix

Construct the symmetric (Lowdin) orthogonalizer \(X = S^{-1/2}\).

Eigenvectors whose overlap eigenvalue is below threshold are dropped from the construction, projecting out near-linear-dependent directions. The returned matrix \(X\) satisfies \(X^T S X = I\) on the well-conditioned subspace.

Parameters:
  • overlap (TMatrix) – Symmetric positive-definite overlap matrix \(S\).

  • threshold (float) – Eigenvalue cutoff for near-linear-dependence removal.

Return type:

TMatrix

matrix_exponential(matrix: TMatrix) → TMatrix

Calculate the matrix exponential \(\exp(M)\), not the element-wise exponential.

The input is unchanged and the result owns independent storage.

Parameters:

matrix (TMatrix) – Square matrix.

Return type:

TMatrix

matrix_multiply(left: TMatrix, right: TMatrix) → TMatrix

Calculate the matrix product \(L R\).

Parameters:
  • left (TMatrix) – Left factor of shape (m, k).

  • right (TMatrix) – Right factor of shape (k, n).

Return type:

TMatrix

metadata_hash(matrix: TMatrix) → str

Calculate a stable metadata hash for a matrix.

Parameters:

matrix (TMatrix) – Matrix whose contents should be hashed.

Return type:

str

new_matrix(array: NDArray[float64]) → TMatrix

Allocate an independently owned matrix containing a copy of the input array.

Parameters:

array (NDArray[float64]) – Two-dimensional numpy array whose shape and contents are copied.

Return type:

TMatrix

property number_of_live_allocations: int

Number of matrices and vectors currently held by the module.

resized_copy(matrix: TMatrix, *, shape: tuple[int, int]) → TMatrix

Create a new matrix of the given shape holding the overlapping top-left block of matrix.

Entries outside matrix are zero, so this pads, crops, or both.

Parameters:
  • matrix (TMatrix) – Source matrix.

  • shape (tuple[int, int]) – Shape of the result as (rows, columns).

Return type:

TMatrix

scale(matrix: TMatrix, scalar: float) → TMatrix

Scale the matrix by a scalar \(cM\).

Parameters:
  • matrix (TMatrix) – Matrix to be scaled.

  • scalar (float) – Real scaling factor.

Return type:

TMatrix

shifted_floored_divide(numerator: TMatrix, denominator: TMatrix, *, shift: float, denominator_floor: float) → TMatrix

Divide elementwise by shifted denominators, preserving their signs when flooring.

Each denominator is first shifted by subtracting shift. Magnitudes below denominator_floor are replaced by that floor with the same sign, including signed zero. Neither input is modified.

Parameters:
  • numerator (TMatrix) – Numerator matrix.

  • denominator (TMatrix) – Denominator matrix of identical shape.

  • shift (float) – Finite scalar subtracted from every denominator.

  • denominator_floor (float) – Finite positive minimum denominator magnitude.

Return type:

TMatrix

slice_columns(matrix: TMatrix, start_column: int, end_column: int) → TMatrix

Create a new matrix containing columns start_column to end_column (exclusive).

The returned matrix has shape (number_of_rows, end_column - start_column).

Parameters:
  • matrix (TMatrix) – Source matrix.

  • start_column (int) – First column index (inclusive).

  • end_column (int) – Last column index (exclusive).

Return type:

TMatrix

solve_linear_system(lhs_matrix: TMatrix, rhs_matrix: TMatrix) → TMatrix

Solve \(A X = B\) for \(X\).

Parameters:
  • lhs_matrix (TMatrix) – Square non-singular matrix \(A\).

  • rhs_matrix (TMatrix) – Right-hand-side matrix \(B\).

Return type:

TMatrix

subtract(left: TMatrix, right: TMatrix) → TMatrix

Calculate the element-wise difference \(L - R\).

Parameters:
  • left (TMatrix) – Minuend.

  • right (TMatrix) – Subtrahend of identical shape.

Return type:

TMatrix

symmetrize(matrix: TMatrix) → TMatrix

Calculate the symmetric projection \(\tfrac{1}{2}(M + M^{T})\).

Parameters:

matrix (TMatrix) – Square matrix to be symmetrized.

Return type:

TMatrix

property total_allocated_bytes: int

Total memory in bytes used by the currently live matrices and vectors.

trace(matrix: TMatrix) → float

Calculate the trace \(\mathrm{Tr}(M) = \sum_{i} M_{i,i}\).

Parameters:

matrix (TMatrix) – Square matrix.

Return type:

float

trace_of_product(left: TMatrix, right: TMatrix) → float

Calculate the trace \(\mathrm{Tr}(L R) = \sum_{i,k} L_{i,k} R_{k,i}\).

Computed without forming the full product matrix.

Parameters:
  • left (TMatrix) – Left factor of shape (m, n).

  • right (TMatrix) – Right factor of shape (n, m).

Return type:

float

transpose(matrix: TMatrix) → TMatrix

Calculate the transpose \(M^{T}\).

Parameters:

matrix (TMatrix) – Matrix to be transposed.

Return type:

TMatrix

vector_outer_difference(left: TVector, right: TVector) → TMatrix

Create the matrix with elements \(L_i - R_j\).

Parameters:
  • left (TVector) – Vector determining the rows.

  • right (TVector) – Vector determining the columns.

Return type:

TMatrix

class MatrixProtocol

Bases: Protocol

Protocol for a two-dimensional (possibly non-square) matrix container.

Only metadata and conversion to and from a raw numpy array is exposed; all algebraic operations are performed by the owning matrix module.

__init__(*args, **kwargs)
fill_from_raw_numpy_array(array: NDArray[float64]) → None

Fill the matrix with data from a raw numpy array.

Parameters:

array (NDArray[float64]) – Two-dimensional numpy array with the same shape as self.

Return type:

None

property shape: tuple[int, int]

Shape of the matrix as (number_of_rows, number_of_columns).

to_raw_numpy_array() → NDArray[float64]

Contents of the matrix as a dense raw numpy array.

Return type:

NDArray[float64]

class VectorProtocol

Bases: Protocol

Protocol for a one-dimensional vector container.

__init__(*args, **kwargs)
fill_from_raw_numpy_array(array: NDArray[float64]) → None

Fill the vector with data from a raw numpy array.

Parameters:

array (NDArray[float64]) – One-dimensional numpy array with length elements.

Return type:

None

property length: int

Number of elements of the vector.

to_raw_numpy_array() → NDArray[float64]

Contents of the vector as a raw numpy array.

Return type:

NDArray[float64]