PAOFLOW.sparse.solver#

Lowest-eigenpair solver for sparse Bloch Hamiltonians.

Two per-k-point kernels behind one entry point, chosen by select_hk_solver() from (n, nev) alone. Both consume the same sparse H(k) assembled from the bond list, so the choice is only how one k-point’s matrix is diagonalized — it never changes how H(R) is stored. hk_solver='dense' does not put the run back on the dense PAOFLOW pipeline: there is no O(nk * n^2) tensor either way.

hk_solver='sparse' — ARPACK shift-invert (eigsh, shift below the spectrum via a Gershgorin bound, inverse applied with a sparse splu) whenever the requested fraction of the spectrum is small. This is the regime Lanczos is built for and the matrix is never densified.

hk_solver='dense' — scipy.linalg.eigh, driver='evr', subset_by_index, when nev approaches n. This is a deliberate, measured exception to the backend’s “strictly iterative” rule — see the memory contract in sparse/README.md. The reason is that the rule stops buying anything in this regime: scipy’s default Krylov dimension is ncv = min(n, max(2k+1, 20)), so at k = nev + guard above roughly n/2 it degenerates to ``ncv = n`` and ARPACK internally allocates a dense (n, n) Arnoldi basis plus O(n*ncv^2) reorthogonalization — the same per-k memory class as a dense eigh, at 13-66x the cost. The 'dense' kernel allocates one (n, n) scratch matrix that is discarded before the next k-point; no global O(nk*n^2) tensor is ever formed, which is the contract that actually matters.

Above dense_n_max the (n, n) scratch stops being cheap, so the mixed regime raises NotImplementedError naming both exits rather than silently swapping tens of GB. Failure stays loud everywhere: the ARPACK retry ladder ends in RuntimeError with diagnostics, and there is no silent fallback in either direction.

Driver choice for the 'dense' kernel is evr (zheevr, MRRR). evd (divide and conquer) has no subset support and always computes all n vectors; evx resolves clusters by inverse iteration with explicit reorthogonalization, whereas at N-fold cell folding multiplets of 8-64 exactly degenerate bands are the normal case and evr returns an orthonormal cluster basis by construction.

Attributes#

Functions#

gershgorin_lower(H)

Rigorous lower bound on the spectrum of a Hermitian sparse matrix.

select_hk_solver(n, nev[, guard, hk_solver, ...])

Pick the per-k kernel, 'sparse' or 'dense', for an (n, nev) solve.

describe_hk_solver(n, nev[, guard, hk_solver])

Multi-line report of the dispatch, for printing once per k-loop.

solve_lowest(H, nev[, sigma, v0, tol, guard, ...])

Lowest nev eigenpairs of a Hermitian sparse matrix.

count_in_window(H, elo, ehi[, dense_n_max])

Number of eigenvalues of H in [elo, ehi].

solve_interior(H, elo, ehi[, k0, tol, hk_solver, ...])

All eigenpairs of a Hermitian sparse H with elo <= E <= ehi.

count_below(H, ehi[, dense_n_max])

Number of eigenvalues of H at or below ehi.

Module Contents#

PAOFLOW.sparse.solver.DENSE_RATIO = 0.125[source]#
PAOFLOW.sparse.solver.DENSE_N_MAX = 4096[source]#
PAOFLOW.sparse.solver.gershgorin_lower(H)[source]#

Rigorous lower bound on the spectrum of a Hermitian sparse matrix.

Parameters:

H (scipy.sparse matrix, shape (n, n), Hermitian)

Returns:

A value guaranteed to be at or below the smallest eigenvalue.

Return type:

float

Notes

Gershgorin’s theorem places every eigenvalue of a matrix inside at least one disc centred on a diagonal entry with radius the sum of the absolute off-diagonal entries in that row. For a Hermitian matrix the eigenvalues are real, so the discs collapse to intervals and the lowest eigenvalue cannot fall below

\[\min_i \Big( \mathrm{Re}\, H_{ii} - \sum_{j \neq i} |H_{ij}| \Big).\]

The bound is cheap (one pass over the stored entries) and needs no iteration, which is what makes it usable as a shift-invert origin at every k-point: placing the shift strictly below the spectrum guarantees it never lands inside a cluster of eigenvalues, where the shifted inverse would be near-singular.

PAOFLOW.sparse.solver.select_hk_solver(n, nev, guard=4, hk_solver='auto', dense_ratio=DENSE_RATIO, dense_n_max=DENSE_N_MAX)[source]#

Pick the per-k kernel, ‘sparse’ or ‘dense’, for an (n, nev) solve.

Parameters:
  • n (int) – Matrix dimension, i.e. the number of orbitals.

  • nev (int) – Number of lowest eigenpairs wanted.

  • guard (int, optional) – Extra pairs the sparse kernel requests on top of nev; counted here because it is what ARPACK actually has to converge.

  • hk_solver ({'auto', 'sparse', 'dense'}, optional) – 'auto' decides from the table below; the other two are honoured verbatim, for A/B validation.

  • dense_ratio (float, optional) – Fraction of the spectrum above which an iterative solve stops paying for itself.

  • dense_n_max (int, optional) – Largest n for which an (n, n) per-k scratch matrix is considered affordable.

Returns:

(hk_solver, reason) – The chosen kernel and a human-readable justification, logged once per k-loop.

Return type:

tuple of str

Raises:
  • ValueError – If hk_solver is not one of the three accepted values.

  • NotImplementedError – If the solve is past the iterative regime and too large for a dense scratch matrix. The message names both ways out.

Notes

First match wins:

condition

outcome

hk_solver is ‘sparse’ or ‘dense’

honoured verbatim

nev + guard >= n - 1

dense (no Krylov room)

nev + guard > ratio*n, small n

dense

nev + guard > ratio*n, large n

NotImplementedError

otherwise

sparse

The decision is deterministic in (n, nev, guard) only — never in the matrix values — so it can be hoisted out of a k-loop and reported once. That is a property worth preserving: a dispatch that depended on the spectrum could silently change kernel partway through a mesh and make two halves of one property incomparable.

PAOFLOW.sparse.solver.describe_hk_solver(n, nev, guard=4, hk_solver='auto', **kw)[source]#

Multi-line report of the dispatch, for printing once per k-loop.

Parameters:
  • n (int) – Matrix dimension.

  • nev (int) – Number of lowest eigenpairs wanted.

  • guard (int, optional) – Extra pairs requested by the sparse kernel.

  • hk_solver ({'auto', 'sparse', 'dense'}, optional) – Requested kernel, passed through to select_hk_solver().

  • **kw – Further keyword arguments forwarded to select_hk_solver() (dense_ratio, dense_n_max).

Returns:

Two or three lines naming the chosen kernel, its memory consequence, and the reason for the choice.

Return type:

str

Notes

The report states what the choice does and does not change: ‘dense’ names the per-k-point kernel, never the storage model, and the line says so explicitly because the word ‘dense’ in a log emitted by the sparse backend otherwise reads as “this run fell back to dense PAOFLOW”.

It also carries the nev creep warning that the nev + guard >= n - 1 hard stop used to enforce. The dense kernel removes the error, so the intent has to survive as a warning: past nev of about half the spectrum the eigenvector block alone is quadratic in n and the run has left the regime this backend exists to serve, even though it still completes.

PAOFLOW.sparse.solver.solve_lowest(H, nev, sigma=None, v0=None, tol=0.0, guard=4, hk_solver='auto', dense_ratio=DENSE_RATIO, dense_n_max=DENSE_N_MAX)[source]#

Lowest nev eigenpairs of a Hermitian sparse matrix.

Parameters:
  • H (scipy.sparse matrix, shape (n, n), Hermitian)

  • nev (int) – Number of lowest eigenpairs wanted.

  • sigma (float or None, optional) – ARPACK shift for shift-invert. Default: gershgorin_lower(H) - 1.0, strictly below the spectrum (never inside a cluster).

  • v0 (np.ndarray or None, optional) – Warm-start vector for the Lanczos iteration (e.g. the lowest eigenvector of a neighbouring k-point).

  • tol (float, optional) – ARPACK relative tolerance; 0.0 means machine precision.

  • guard (int, optional) – Extra pairs computed and discarded on the 'sparse' path, so a degenerate cluster split exactly at nev does not stall convergence.

  • hk_solver ({'auto', 'sparse', 'dense'}, optional) – Per-k kernel, see select_hk_solver(). 'sparse' and 'dense' force a kernel, for A/B validation. Neither changes how H(R) is stored.

  • dense_ratio (float, optional) – Fraction of the spectrum above which the dense kernel is chosen.

  • dense_n_max (int, optional) – Largest n for which the dense kernel’s scratch is affordable.

Returns:

(E, V) – Eigenvalues (nev,) ascending and eigenvectors (n, nev).

Return type:

tuple of np.ndarray

Raises:
  • NotImplementedError – If hk_solver='sparse' is forced at a size that leaves ARPACK no Krylov room.

  • RuntimeError – If every attempt in the retry ladder failed to converge. The message lists what was tried.

Notes

Lanczos-type methods converge fastest on the outermost eigenvalues of a matrix, and the states wanted here are at the bottom of the spectrum, interior to nothing but also not extremal in magnitude. Shift-invert fixes that: the solver is handed the operator \((H - \sigma)^{-1}\) with \(\sigma\) placed just below the whole spectrum, which maps the lowest eigenvalues of \(H\) to the largest of the transformed operator, where the iteration converges quickly. The inverse is never formed — it is applied as a sparse LU solve. The shift comes from a Gershgorin bound (gershgorin_lower()) minus one, so it is guaranteed to sit outside the spectrum and never inside a cluster, where the shifted matrix would be near-singular.

A few extra pairs beyond nev are requested (guard). Degenerate multiplets are common in folded cells, and asking for a count that cuts a multiplet in half makes convergence markedly harder; the surplus is discarded after sorting.

Non-convergence is answered with a retry ladder rather than a fallback: the Krylov subspace and iteration limit are grown a few times, then one attempt is made without shift-invert (targeting the algebraically smallest eigenvalues directly, slower to converge but not dependent on the LU factorization), and if all of that fails the call raises with the full history. There is no silent degradation of the answer.

sigma, v0, tol and guard are ARPACK-only and are ignored on the 'dense' kernel: evr returns exactly the requested index range with an orthonormal basis on each degenerate cluster, so it needs neither a guard nor the sort-and-orthonormalize fixup. The two branches agree to ~1e-9 eV but are not bit-identical (Householder tridiagonalization vs an splu solve chain), and their eigenvector gauges differ inside degenerate subspaces — compare gauge-invariant quantities, never eigenvectors elementwise.

PAOFLOW.sparse.solver.INTERIOR_DENSE_N = 512[source]#
PAOFLOW.sparse.solver.INTERIOR_K0 = 16[source]#
PAOFLOW.sparse.solver.INTERIOR_GROWTH = 2.0[source]#
PAOFLOW.sparse.solver.INTERIOR_MAX_ATTEMPTS = 6[source]#
PAOFLOW.sparse.solver.count_in_window(H, elo, ehi, dense_n_max=DENSE_N_MAX)[source]#

Number of eigenvalues of H in [elo, ehi].

Parameters:
  • H (scipy.sparse matrix, shape (n, n), Hermitian)

  • elo (float) – Window bounds in eV, both inclusive.

  • ehi (float) – Window bounds in eV, both inclusive.

  • dense_n_max (int, optional) – Largest n for which the (n, n) scratch is affordable.

Returns:

The number of states in the window.

Return type:

int

Raises:

NotImplementedError – If n exceeds dense_n_max. The message names the way out.

Notes

Companion to count_below() for sizing an interior window, and the reference the sparse path is validated against. Counting states in an interval needs no eigenvectors, so this is one tridiagonal reduction followed by a value-subset eigenvalue query — cheap in time, but it densifies, so it carries the same size guard as the dense kernel.

PAOFLOW.sparse.solver.solve_interior(H, elo, ehi, k0=None, tol=0.0, hk_solver='auto', dense_n_max=DENSE_N_MAX, interior_dense_n=INTERIOR_DENSE_N, max_attempts=INTERIOR_MAX_ATTEMPTS)[source]#

All eigenpairs of a Hermitian sparse H with elo <= E <= ehi.

Parameters:
  • H (scipy.sparse matrix, shape (n, n), Hermitian)

  • elo (float) – Window bounds in eV, ehi > elo. Both are inclusive.

  • ehi (float) – Window bounds in eV, ehi > elo. Both are inclusive.

  • k0 (int or None, optional) – Starting Krylov request. ARPACK is asked for the k0 eigenvalues nearest the window centre; if that set does not straddle both edges of the window, k grows and the solve repeats. A good k0 (say the count from a neighbouring k-point) removes the retries; a bad one only costs time, never correctness — a failed attempt measures the local level density, so the next k is extrapolated rather than merely doubled.

  • tol (float, optional) – ARPACK relative tolerance; 0.0 means machine precision.

  • hk_solver ({'auto', 'sparse', 'dense'}, optional) – 'dense' uses subset_by_value directly; 'sparse' forces shift-invert; 'auto' takes dense below interior_dense_n, where the splu factorization costs more than a direct subset solve, and also falls back to dense if the window turns out to hold so much of the spectrum that the Krylov request approaches n. Under 'sparse' that situation raises instead — no silent fallback.

  • dense_n_max (int, optional) – Largest n for which an (n, n) scratch is affordable when the dense branch is reached by fallback rather than by request.

  • interior_dense_n (int, optional) – Below this n, 'auto' goes straight to the dense branch.

  • max_attempts (int, optional) – How many Krylov sizes to try before giving up.

Returns:

(E, V) – Eigenvalues (m,) ascending and eigenvectors (n, m), where m is the number of states in the window. m is not known in advance and is legitimately 0 when the window lies in a gap; both arrays come back correctly shaped in that case.

Return type:

tuple of np.ndarray

Raises:
  • ValueError – If the window is empty or inverted, or hk_solver is unknown.

  • NotImplementedError – If the dense branch is needed at an n past dense_n_max.

  • RuntimeError – If the Krylov ladder ran out of attempts, or if a forced sparse solve met a window holding nearly the whole spectrum.

Notes

solve_lowest() answers “the nev lowest states”, which forces every property to carry the whole valence manifold even when its physics only needs a few \(k_BT\) around \(E_F\) — Boltzmann transport, Fermi-surface quantities, flat bands in a moire cell. This function answers “every state in [elo, ehi]” instead, so the cost tracks the number of states in the window rather than the number below it.

The mechanism is again shift-invert, but with the shift placed at the centre of the window: the transformed operator’s largest eigenvalues are then those of \(H\) closest to the window centre, which is exactly the set wanted. Two properties make this the regime ARPACK was built for. The count in a narrow interior window is typically a fraction of a percent of the spectrum, and — unlike the from-the-bottom case — that fraction is set by the material’s basis richness rather than by where \(E_F\) sits. Under N-fold folding both the count and n scale by N, so the fraction is scale-invariant here too: a supercell neither helps nor hurts.

The number of states in the window is not known in advance, so the solver asks for k states nearest the centre and then checks whether that set reaches past both edges. If it does, every in-window state is inside the returned set and the rest are discarded; if it does not, states may lie beyond the last one converged and k must grow. The growth is an extrapolation rather than a blind doubling: the k values just returned span some energy range, so k divided by that span estimates the local level density, and multiplying by the window width estimates the k needed to bracket it. Blind doubling would need log2(m/k0) rounds to reach a window holding m states, exhausting the attempt budget on a problem that is not actually hard.

The returned count is k-dependent by construction (a band crossing the window edge is in at one k-point and out at the next). Callers that need rectangular arrays must pad; that is deliberately not done here, so this function stays a pure eigensolver.

Degenerate groups are re-orthonormalized exactly as in solve_lowest() — required here, since a folded supercell or a moire flat-band manifold puts multiplets inside the window by design.

PAOFLOW.sparse.solver.count_below(H, ehi, dense_n_max=DENSE_N_MAX)[source]#

Number of eigenvalues of H at or below ehi.

Parameters:
  • H (scipy.sparse matrix, shape (n, n), Hermitian)

  • ehi (float) – Upper bound in eV, inclusive.

  • dense_n_max (int, optional) – Largest n for which the (n, n) scratch is affordable.

Returns:

The number of states at or below ehi.

Return type:

int

Raises:

NotImplementedError – If n exceeds dense_n_max. The message names the two ways out.

Notes

This is the probe used to size an energy window: it answers how many bands a from-the-bottom solve must compute to reach a given energy at a given k-point. One tridiagonal reduction with zheevr’s subset_by_value and no eigenvectors — cheap, but it densifies, so it carries the same size guard as the 'dense' kernel.