sci_solvers.eigen_problem¶
Projected-Hamiltonian problem and eigenpair container for a CI subspace.
These two objects are backend-agnostic and useful beyond the energy solvers:
- :class:
EigenProblemowns the Hamiltonian representation for one sampledalpha x betaCI subspace. It exposes a matrix-freematvec(viatorch_sci_solver's batched kernel), a lazily assembled sparse matrix, the diagonal (for preconditioning), and a scipyLinearOperatorview. Anything that needs to diagonalize a projected CI Hamiltonian can consume it without pulling in the SQD pipeline or a specific eigensolver. - :class:
EigenResultis the plain(energies, vectors)container adapters return, with an energy-ascending :meth:~EigenResult.sortedhelper. - :class:
SymmetrizedEigenProblemis a same-interface view over anEigenProblemfor closed-shell subspaces: it block-diagonalizesHby the alpha<->beta swap symmetry and exposes one+/-1parity sector on a packed, roughly half-size basis, so an adapter solves the smaller block unchanged.
The matrix-free matvec reuses torch_sci_solver's batched Hamiltonian
kernel (already a hard dependency). PySCF's contract_2e builds the same
operator but is orders of magnitude slower at large active spaces (seconds per
matvec at norb ~ 36 vs sub-millisecond for the torch kernel), which would
dominate every ARPACK/LOBPCG/PRIMME iteration.
The torch kernel stores amplitudes in interleaved-Wick parity, which differs
from PySCF's spin-block convention by a per-(ia, ib) sign sigma. We wrap
that sign into matvec (H_block = sigma . H_inter . sigma) so the operator,
its eigenvectors, and the amplitudes handed back are all in the spin-block
convention the rest of the ecosystem (PySCF, qiskit-addon-sqd) expects.
Conventions¶
eriis the full 4-index array in chemists' notation(pq|rs), matching :class:~sci_solvers.hamiltonian.HamiltonianData.nelec = (n_alpha, n_beta).
EigenProblem
[source]
¶
EigenProblem(strs_a: ndarray, strs_b: ndarray, hcore: ndarray, eri: ndarray, norb: int, nelec: Tuple[int, int], *, device: 'str | torch.device' = 'cpu', dtype: dtype = float64, chunk_size: int = 2000000, matvec_impl: str = 'torch')
Projected Hamiltonian on span{|a>|b>}, flat index ia * Nb + ib.
The subspace is the Cartesian product of the alpha and beta CI strings.
matvec and hdiag are backed by torch_sci_solver's batched kernel
(fast at large norb); sigma bridges its interleaved-Wick parity to
the spin-block convention so the operator and eigenvectors match PySCF. All
representations are cached on first use.
Build a projected-Hamiltonian problem for one subspace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strs_a
|
ndarray
|
Alpha CI strings (int64 bitmask array). |
required |
strs_b
|
ndarray
|
Beta CI strings (int64 bitmask array). |
required |
hcore
|
ndarray
|
One-electron integrals, shape |
required |
eri
|
ndarray
|
Two-electron integrals, full 4-index chemists' notation. |
required |
norb
|
int
|
Number of spatial orbitals. |
required |
nelec
|
Tuple[int, int]
|
|
required |
device
|
'str | torch.device'
|
Torch device for the matvec kernel ( |
'cpu'
|
dtype
|
dtype
|
Torch float dtype (float64 recommended for stability). |
float64
|
chunk_size
|
int
|
Matvec batch size for the torch kernel. |
2000000
|
matvec_impl
|
str
|
|
'torch'
|
matvec
¶
matvec(x: ndarray) -> ndarray
Apply H (spin-block convention) to x of shape (dim,) or (dim, k).
A 2-D x is applied as one batched (vmap) call rather than column
by column; the sigma similarity is applied on both sides to return
the operator in spin-block convention.
This is the numpy entry point: it accepts and returns np.ndarray,
moving data to/from self.device each call. SciPy solvers
(ARPACK/LOBPCG/PRIMME) need it. Torch-native drivers (the torch_sci
adapter) should call :meth:matvec_torch instead to stay on-device — on
CUDA the numpy round-trip is a hard host sync on the hot path.
matvec_torch
¶
matvec_torch(x: Tensor) -> Tensor
Apply H (spin-block convention) fully on-device: Tensor -> Tensor.
Same operator as :meth:matvec but with no numpy conversion — the input
stays on self.device and the result is returned as a torch Tensor on
the same device. This is what a torch driver (e.g. the torch_sci
Davidson adapter) should call so the whole iteration avoids the per-apply
device<->host sync that :meth:matvec incurs. Accepts (dim,) (single
vector, applied via the scalar kernel) or (dim, k) (block, applied via
one batched vmap call); the sigma similarity is folded in on both
sides to return the operator in the spin-block convention.
linear_operator
¶
linear_operator() -> LinearOperator
Return a symmetric scipy LinearOperator view of H.
matmat maps :meth:matvec over a block's columns in one batched
torch.vmap call, so block solvers (LOBPCG/PRIMME) get a single
batched apply per macro-iteration instead of k sequential ones.
hdiag
¶
hdiag() -> ndarray
Return the Hamiltonian diagonal (used for preconditioning).
The diagonal is invariant under the sigma similarity (sigma**2 = 1),
so the torch kernel's diagonal is already the spin-block diagonal.
hdiag_torch
¶
hdiag_torch() -> Tensor
Return the Hamiltonian diagonal as a (dim,) Tensor on self.device.
The torch-native counterpart of :meth:hdiag, so a torch driver can seed
its preconditioner without a device->host copy. As with :meth:hdiag, the
diagonal is invariant under the sigma similarity (sigma**2 = 1), so
the kernel diagonal is already the spin-block diagonal.
sparse
¶
sparse() -> csr_matrix
Materialize P H P as a scipy CSR matrix (cached).
Assembled by applying :meth:matvec to the identity, so it builds a
dense (dim, dim) intermediate before compressing to CSR — O(dim^2)
memory (~800 MB at dim = 1e4). Only use for adapters that need an
explicit matrix and for modest dim; prefer the matrix-free
:meth:matvec / :meth:linear_operator path for large subspaces (the
default ARPACK/SLEPc/PRIMME configurations already do).
EigenResult
[source]
dataclass
¶
EigenResult(energies: ndarray, vectors: ndarray, converged: ndarray | None = None)
Eigenpairs returned by an adapter.
Attributes:
| Name | Type | Description |
|---|---|---|
energies |
ndarray
|
Shape |
vectors |
ndarray
|
Shape |
converged |
ndarray | None
|
Optional per-root convergence flags, shape |
sorted
¶
sorted() -> 'EigenResult'
Return a copy with roots sorted by ascending energy.
Sorting is on the real part of the energies. For a real symmetric
operator the energies are already real and this is a plain ascending
sort (behavior unchanged). For a complex Hermitian operator the
eigenvalues are real in exact arithmetic but a backend may return them
with a negligible imaginary part; sorting on .real keeps the ordering
well-defined without discarding the (tiny) imaginary residual.
converged (if set) is reordered along with the other two.
SymmetrizedEigenProblem
[source]
¶
SymmetrizedEigenProblem(base: EigenProblem, sector: int = +1)
Packed-sector view of an :class:EigenProblem for a closed-shell subspace.
When the alpha and beta CI-string pools are identical (strs_a == strs_b,
Na == Nb == D — the closed-shell open_shell=False case), the CI
coefficient matrix C (shape (D, D)) commutes with the alpha<->beta
swap P: C -> C.T. Since [H, P] = 0, H is block-diagonal in the
+/-1 eigenspaces of P:
sector=+1(C = +C.T): even total spinS = 0, 2, 4, ..., dimensionD(D+1)/2.sector=-1(C = -C.T): odd total spinS = 1, 3, 5, ..., dimensionD(D-1)/2.
This view exposes the same operator interface an adapter consumes
(:attr:dim, :meth:matvec, :meth:linear_operator, :meth:hdiag,
:meth:sparse) but on the packed sector, so an adapter diagonalizes the
smaller block without knowing symmetrization happened. The physical
attributes (strs_a, strs_b, norb, nelec, hcore, eri,
Na, Nb) are delegated to the wrapped full-space problem so downstream
RDM building is unchanged; :meth:unpack_eigenvectors maps packed
eigenvectors back to the full (D*D,) product-space layout first.
The packed basis is orthonormal: off-diagonal packed components carry a
1/sqrt(2) weight so the embedding S (packed -> full) is an isometry
and S^T H S stays symmetric. Equivalently, for a symmetric full operator
H, :meth:matvec computes S^T H S in the packed basis.
Wrap base as a single-parity-sector view.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
EigenProblem
|
The full-space problem. Its alpha/beta pools must be identical
(closed shell), else a :class: |
required |
sector
|
int
|
|
+1
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
dtype
property
¶
dtype: dtype
Numpy operator dtype of the packed block (complex iff the base is).
Exposed so the adapters' complex-detection (_is_complex_problem,
which reads problem.dtype) engages the complex-Hermitian code paths
for a packed complex sector — the diagonal alone is real and cannot serve
as the signal.
matvec
¶
matvec(x: ndarray) -> ndarray
Apply S^T H S to a packed (dim,) vector or (dim, k) block.
A 2-D x expands all columns into one full (D*D, k) block and
applies the base matvec once (it batches columns internally), then
compresses each column back — preserving the batched-kernel speedup for
block solvers (LOBPCG/PRIMME).
.. note::
Packing reduces vector storage and Krylov dimension. Each product
still expands to the full space, applies ``base.matvec``, and
compresses the result.
matvec_torch
¶
matvec_torch(x: Tensor) -> Tensor
Apply S^T H S fully on-device: packed Tensor -> packed Tensor.
The torch-native counterpart of :meth:matvec: it expands each packed
column to the full space, calls :meth:EigenProblem.matvec_torch (which
never leaves the device), and compresses back — all in torch, so a torch
driver on a packed sector view keeps the same on-device iteration the full
problem gets. Accepts (dim,) or (dim, k). Same per-apply FLOPs as
:meth:matvec (see that method's note); the win is avoiding the host
sync, not fewer FLOPs.
hdiag_torch
¶
hdiag_torch() -> Tensor
Packed approximate diagonal as a device Tensor (see :meth:hdiag).
linear_operator
¶
linear_operator() -> LinearOperator
Return a symmetric scipy LinearOperator view of the packed block.
hdiag
¶
hdiag() -> ndarray
Return an approximate packed diagonal (Jacobi preconditioner).
Used only to build a diagonal preconditioner (LOBPCG M / PRIMME
OPinv) and to seed LOBPCG's initial guess, so an approximation is
both sufficient and standard. The exact packed diagonal of
S^T H S for an off-diagonal packed entry (i < j) is
H[ij, ij] + sector * H[ij, ji], but the coupling term H[ij, ji]
is an off-diagonal element of the full H that base.hdiag() does
not expose. We therefore drop it and return the full-space diagonal
restricted to the packed indices, H[ij, ij] (with diagonal packed
entries (i, i) exact at H[ii, ii]) — the dominant, preconditioner-
relevant part. This is intentionally not diag(sparse()).
sparse
¶
sparse() -> csr_matrix
Materialize the packed block S^T H S as a scipy CSR matrix (cached).
Assembled by applying :meth:matvec to the identity (dense
(dim, dim) intermediate) — same cost note as
:meth:EigenProblem.sparse, but on the smaller packed dimension.
unpack_eigenvectors
¶
unpack_eigenvectors(vectors: ndarray) -> ndarray
Map packed eigenvectors (dim, k) to full product space (D*D, k).
Each column is embedded via :meth:_expand; because S is an isometry
the full vectors inherit the packed columns' normalization. k == 0
(e.g. an eigensolver that converged zero roots) returns an empty
(D*D, 0) array rather than crashing np.column_stack on an
empty list.
HermitianOperator
[source]
¶
HermitianOperator(matrix, *, check_hermitian: bool = True, atol: float = 1e-08, rtol: float = 1e-05)
General Hermitian operator built from an explicit matrix or a matvec.
This is a separate entry point from :class:EigenProblem. Where
EigenProblem represents a real symmetric CI Hamiltonian assembled from
chemistry integrals (and is hardwired to float64), HermitianOperator
wraps an arbitrary Hermitian operator A (complex or real) supplied
directly, so complex-valued Hermitian matrices with real eigenvalues can be
diagonalized without touching the chemistry path.
It exposes the same duck-typed operator interface the adapters consume
(:attr:dim, :meth:matvec, :meth:hdiag, :meth:sparse,
:meth:linear_operator), so the complex-capable adapters (dense fallback,
SciPy ARPACK/LOBPCG, in-house Davidson) work on it unchanged. The operator
dtype is preserved end to end: a real input yields a float64 problem that
behaves exactly like the real path, while a complex input yields a
complex128 problem whose :meth:linear_operator uses a genuine conjugate
transpose for rmatvec (A^H, not A^T).
Construct with either a matrix (HermitianOperator(A)) or a matrix-free
operator (HermitianOperator.from_matvec(matvec, hdiag, dim, dtype=...)).
Build a problem from an explicit dense or sparse Hermitian matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
A square |
required | |
check_hermitian
|
bool
|
If |
True
|
atol
|
float
|
Absolute tolerance for the Hermiticity check. |
1e-08
|
rtol
|
float
|
Relative tolerance for the Hermiticity check. |
1e-05
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
from_matvec
classmethod
¶
from_matvec(matvec: Callable[[ndarray], ndarray], hdiag: ndarray, dim: int, *, dtype=complex128) -> 'HermitianOperator'
Build a matrix-free problem from a Hermitian matvec and diagonal.
The caller guarantees matvec applies a Hermitian operator (no check
is possible without materializing the matrix). hdiag is the operator
diagonal, used only for preconditioning/guesses (its real part is used).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matvec
|
Callable[[ndarray], ndarray]
|
Applies |
required |
hdiag
|
ndarray
|
Operator diagonal, shape |
required |
dim
|
int
|
Operator dimension |
required |
dtype
|
Result dtype ( |
complex128
|
Returns:
| Type | Description |
|---|---|
'HermitianOperator'
|
A matrix-free :class: |
rmatvec
¶
rmatvec(x: ndarray) -> ndarray
Apply A^H (the adjoint) to x.
For a Hermitian operator A^H == A, so this equals :meth:matvec; it
exists so :meth:linear_operator can advertise a correct adjoint (a
conjugate transpose, not a plain transpose) to SciPy.
linear_operator
¶
linear_operator() -> LinearOperator
Return a scipy LinearOperator view of A with the true adjoint.
rmatvec is the conjugate transpose A^H (equal to matvec for a
Hermitian operator), and the operator dtype matches the input, so SciPy's
complex-Hermitian code paths (eigsh/lobpcg) engage for complex
input while real input behaves exactly as before.
sparse
¶
sparse() -> csr_matrix
Materialize A as a scipy CSR matrix (cached).
Returns the stored matrix directly when built from one; for a matrix-free
problem it assembles A by applying :meth:matvec to the identity
(dense (dim, dim) intermediate — same cost note as
:meth:EigenProblem.sparse).
PairCIProblem
[source]
¶
PairCIProblem(strs_a: ndarray, strs_b: ndarray, hcore: ndarray, eri: ndarray, norb: int, nelec: Tuple[int, int], *, device: 'str | torch.device' = 'cpu', dtype: dtype = float64, chunk_size: int = 2000000)
Projected Hamiltonian on an explicit (alpha_i, beta_i) determinant-pair list.
Where :class:EigenProblem spans the Cartesian product of the alpha and
beta CI strings (flat index ia * Nb + ib), this problem spans an explicit
parallel list of (alpha_i, beta_i) pairs — the "GDB" / general-determinant
basis contract used by SBDSolver and torch_sci_solver. The dimension is
the number of pairs, not the product Na * Nb.
It is backed directly by torch_sci_solver's vendored pair engine
(pairs/mult_pairs/rdm_pairs/pair_helpers), which applies the
full-determinant Slater--Condon rules to a pair basis. That kernel carries no
per-spin parity factorization and no sigma fold — the amplitudes are
in interleaved-Wick signs, the convention the pair RDM builders expect, so the
operator is sigma . H . sigma of the spin-block one (sigma from
_inter_to_block_signs_pair) and, unlike :class:EigenProblem, there is no
interleaved-Wick similarity to wrap around
matvec. Real integrals go through to_torch_integrals; complex Hermitian
integrals go through :func:~sci_solvers.complex_ci_problem._complex_torch_integrals,
yielding a genuinely Hermitian complex operator.
Exposes the same duck-typed operator interface the adapters consume
(:attr:dim, :meth:matvec, :meth:matvec_torch, :meth:hdiag,
:meth:hdiag_torch, :meth:linear_operator, :meth:sparse) plus the fields
result-packing needs (:attr:pair_basis, :attr:pair_helpers, the deduped +
lex-sorted :attr:strs_a/:attr:strs_b, :attr:norb, :attr:nelec,
:attr:hcore, :attr:eri). It deliberately has no Na/Nb attributes,
so nothing can accidentally reshape it back into a product.
Note pair_basis_from_arrays dedups and lex-sorts the pair list, so the pair
order generally differs from the input order — always read :attr:strs_a /
:attr:strs_b back from the basis when aligning amplitudes.
Build a projected-Hamiltonian problem for one determinant-pair list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strs_a
|
ndarray
|
Alpha CI strings (int64 bitmask array), parallel to |
required |
strs_b
|
ndarray
|
Beta CI strings (int64 bitmask array), parallel to |
required |
hcore
|
ndarray
|
One-electron integrals, shape |
required |
eri
|
ndarray
|
Two-electron integrals, full 4-index chemists' notation (may be complex Hermitian). |
required |
norb
|
int
|
Number of spatial orbitals. |
required |
nelec
|
Tuple[int, int]
|
|
required |
device
|
'str | torch.device'
|
Torch device for the matvec kernel ( |
'cpu'
|
dtype
|
dtype
|
Torch float/complex dtype. Overridden to |
float64
|
chunk_size
|
int
|
Matvec/RDM batch size for the pair kernels. |
2000000
|
matvec
¶
matvec(x: ndarray) -> ndarray
Apply H to x of shape (dim,) or (dim, k).
The numpy entry point SciPy solvers (ARPACK/LOBPCG/PRIMME) need: it
accepts and returns np.ndarray, moving data to/from self.device
each call. Torch-native drivers should call :meth:matvec_torch instead.
matvec_torch
¶
matvec_torch(x: Tensor) -> Tensor
Apply H fully on-device: Tensor -> Tensor.
Accepts (dim,) (single vector) or (dim, k) (block). The pair
kernel's scatter uses complex index_add_, which torch.vmap does not
compose with, so a block is applied column by column rather than via a
batched vmap (the same caveat the complex product path documents).
linear_operator
¶
linear_operator() -> LinearOperator
Return a scipy LinearOperator view of H with the true adjoint.
rmatvec is :meth:matvec — H is Hermitian (H^H == H) — and the
operator dtype matches the integrals, so SciPy's complex-Hermitian code
paths engage for complex integrals while real integrals behave as before.
hdiag_torch
¶
hdiag_torch() -> Tensor
Return the Hamiltonian diagonal as a (dim,) Tensor on self.device.
sparse
¶
sparse() -> csr_matrix
Materialize H as a scipy CSR matrix (cached).
Assembled by applying :meth:matvec to the identity (dense (dim, dim)
intermediate — same cost note as :meth:EigenProblem.sparse). Only for
adapters that need an explicit matrix and for modest dim.