PAOFLOW.sparse.hamiltonian#
Bond-list representation of the PAO real-space Hamiltonian.
SparseHamiltonian stores H(R) as a flat list of “bonds”
(i, j, R, value) shared across all lattice vectors R, thresholded on
|value|. The Bloch Hamiltonian at any k is assembled as
with s = +1 matching the dense band-path convention
(spectrum.do_bands.band_loop_H) and s = -1 matching the dense
FFT mesh convention (scipy.fftpack.fftn in
hamiltonian.do_double_grid / do_gradient).
The CSR sparsity pattern (the union of bond index pairs over all R) is
built once and only the numerical values are refilled per k-point, so
per-k assembly is a vectorized phase multiply plus one
np.add.reduceat — the structure is never re-sorted.
For even R grids the folded Nyquist plane (m = -nk/2) has no
+nk/2 partner, which would make the Fourier sum slightly
non-Hermitian at k-points off the original grid. The assembly plan
therefore splits every Nyquist-plane bond into two half-weight bonds at
-nk/2 and +nk/2 — the bond-list equivalent of what
utils.zero_pad does for the dense pipeline. At original-grid
k-points the two half phases coincide, so grid values are unchanged;
off the grid, H(k) becomes exactly Hermitian, as the iterative
solver requires. The stored bond list stays on the folded grid
(doubling operates on it directly); the split lives only inside the
plan.
The gradient dH(k)/dk_l is assembled on the same pattern with the
per-bond coefficient 1j * (alat * Rcart_l + Dnm_l), replicating
hamiltonian.do_gradient (R term) plus its diagonal tight-binding
correction (Dnm term). Dnm is stored per bond, never as a dense
(nawf, nawf, 3) array.
HERMITIZE_GROWTH is the bond-count growth factor across
SparseHamiltonian.hermitize(), used for size projection only. That
operation unions the list with its mirrored conjugate, so the true factor
lies in [1, 2]: 1 when every (j,i,-R) partner is already present, 2
when none is. Thresholding drops partners asymmetrically, so it sits above
1; measured 1.19 on example01 at nx=1, rounded up here.
Attributes#
Classes#
Thresholded bond list for H(R) with fixed-pattern k-space assembly. |
Functions#
|
Pack folded lattice triples into the linear FFT-box index. |
|
Unpack linear FFT-box indices back into folded lattice triples. |
|
|
|
Pack |
|
Integer lattice triples of the FFT R grid, folded around zero. |
Module Contents#
- PAOFLOW.sparse.hamiltonian.encode_R(triples, nk_grid)[source]#
Pack folded lattice triples into the linear FFT-box index.
- Parameters:
- Returns:
One integer per triple, in
[0, nk1*nk2*nk3).- Return type:
np.ndarray, shape (m,), int64
Notes
Each triple is shifted into the non-negative box and then read as a three-digit number in mixed radix, most significant axis first. Because the shift is monotonic per axis, ascending code order is identical to the lexicographic order of
(m1, m2, m3), which is whatnp.unique(..., axis=0)produces — the property that lets the encoded path stay bit-identical to the void-view lexsort it replaces.
- PAOFLOW.sparse.hamiltonian.decode_R(codes, nk_grid)[source]#
Unpack linear FFT-box indices back into folded lattice triples.
- Parameters:
codes (np.ndarray, shape (m,)) – Codes as produced by
encode_R().nk_grid (sequence of int) – The three R-grid dimensions.
- Returns:
The folded lattice triples.
- Return type:
np.ndarray, shape (m, 3), int64
Notes
Exact inverse of
encode_R(): successive division and remainder peel off the mixed-radix digits, and the per-axis offsets are subtracted to return to folded coordinates.
- PAOFLOW.sparse.hamiltonian.unique_R(triples, nk_grid)[source]#
np.unique(triples, axis=0, return_inverse=True)in O(nnz).- Parameters:
- Returns:
(R_uniq, inverse) – The distinct triples in lexicographic order,
(nR, 3), and the index into them for each input row,(nnz,).- Return type:
tuple of np.ndarray
- Raises:
AssertionError – If any triple lies outside the folded window of the grid, which would mean the caller produced a lattice vector the R grid cannot represent.
Notes
Lattice triples take at most
nk1*nk2*nk3distinct values, a number fixed by the grid and typically far smaller than the bond count. So the generic sort-based unique —O(nnz log nnz)on a structured array — is replaced by a presence mask over the whole box plus a lookup table: every bond is touched twice, and nothing is sorted. Output is bit-identical to theaxis=0form, since the code order ofencode_R()reproduces lexicographic order.
- PAOFLOW.sparse.hamiltonian.encode_bond(rows, cols, triples, nawf, nk_grid)[source]#
Pack
(row, col, m1, m2, m3)into one int64 key.- Parameters:
rows (np.ndarray, shape (nnz,)) – Orbital indices of each bond.
cols (np.ndarray, shape (nnz,)) – Orbital indices of each bond.
triples (np.ndarray, shape (nnz, 3)) – Folded lattice triple of each bond.
nawf (int) – Number of orbitals, the radix of the row/column digits.
nk_grid (sequence of int) – The three R-grid dimensions.
- Returns:
One key per bond, unique across the whole
(orbital, orbital, R)space.- Return type:
np.ndarray, shape (nnz,), int64
- Raises:
NotImplementedError – If the key space does not fit in int64.
Notes
Row and column are the most significant digits, so ascending code order reproduces the lexicographic ordering of the 5-column key array that
np.unique(key, axis=0)returns — the bond list therefore comes out in exactly the same order as the void-view implementation, down to the floating-point summation order of the assembly plan. A single integer key also sorts an order of magnitude faster than a structured array and costs 8 bytes per bond instead of 40.
- PAOFLOW.sparse.hamiltonian.folded_R_triples(nk1, nk2, nk3)[source]#
Integer lattice triples of the FFT R grid, folded around zero.
- Parameters:
- Returns:
Row
nis the folded triple(m1, m2, m3)for linear indexn = k + j*nk3 + i*nk2*nk3.- Return type:
np.ndarray, shape (nk1*nk2*nk3, 3), int32
Notes
An FFT indexes its real-space grid from 0 to
nk-1, but the second half of that range represents negative lattice vectors: indexi >= nk/2means the cell ati - nk. Folding makes that explicit, so a lattice triple can be used directly as a displacement in the phase factor and in the bond length. This replicates the fold used byutils.get_R_grid_fft(componenti/nk >= 0.5mapped toi - nk).
- class PAOFLOW.sparse.hamiltonian.SparseHamiltonian(nawf, nspin, alat, a_vectors, nk_grid, R_int, rows, cols, ridx, vals, dnm, threshold=0.0, drop_report=None)[source]#
Thresholded bond list for H(R) with fixed-pattern k-space assembly.
- Parameters:
nawf (int) – Number of atomic orbitals in the current cell.
nspin (int) – Number of spin channels.
alat (float) – Lattice constant in Bohr.
a_vectors (array_like, shape (3, 3)) – Lattice vectors in units of
alat(rows).nk_grid (sequence of int) – The three R-grid dimensions; fixed by the original DFT k-mesh and unchanged by doubling.
R_int (array_like, shape (nR, 3)) – Distinct folded lattice triples referenced by the bonds.
rows (array_like, shape (nnz,)) – Orbital indices of each bond.
cols (array_like, shape (nnz,)) – Orbital indices of each bond.
ridx (array_like, shape (nnz,)) – Index into
R_intfor each bond.vals (array_like, shape (nnz, nspin)) – Hamiltonian matrix element of each bond, in eV.
dnm (array_like, shape (nnz, 3)) – Intra-cell orbital position difference of each bond, in Bohr.
threshold (float, optional) – Magnitude below which H(R) entries were dropped (eV).
drop_report (dict or None, optional) – Truncation statistics, carried alongside the data.
- Variables:
nspin (nawf,)
alat (float) – Lattice constant in Bohr.
a_vectors (np.ndarray, shape (3, 3)) – Current-cell lattice vectors in units of
alat(rows). Updated by doubling.R_int (np.ndarray, shape (nR, 3), int32) – Folded integer lattice triples in the current-cell basis.
cols (rows,) – Orbital indices of each bond.
ridx (np.ndarray, shape (nnz,), int32) – Index into
R_intfor each bond.dnm (np.ndarray, shape (nnz, 3), float64) – Intra-cell orbital position difference (Bohr) on the bond pattern; zero for bonds connecting different cell replicas.
threshold (float) – Magnitude below which H(R) entries were dropped (eV).
drop_report (dict) – Truncation statistics;
eig_boundis a rigorous upper bound on the eigenvalue shift caused by thresholding (max row sum of dropped magnitudes, valid at every k).
Notes
A tight-binding Hamiltonian in real space is a list of hoppings: orbital
iin the home cell couples to orbitaljin the cell displaced by lattice vectorR, with some amplitude. Almost all of those amplitudes are negligible — the interaction decays with distance — so storing the full(nawf, nawf, nR)array wastes memory that grows quadratically with the cell. Here only the surviving hoppings are stored, as parallel arrays of row, column, R index and value. Cell doubling then costs a factor of two in memory instead of four.The one operation the whole pipeline repeats is building \(H(\mathbf{k})\) from these bonds, millions of times over a k-mesh. Each bond always lands in the same matrix entry regardless of k, and only its phase factor changes, so the sparsity structure is computed once (
plan) and every k-point reuses it: multiply each bond by its phase, sum the bonds that share a matrix entry, done. No sorting, no allocation of index arrays, no dense intermediate.- classmethod from_data_controller(data_controller, threshold, rcut=None)[source]#
Threshold the dense
HRsin a DataController into a bond list.- Parameters:
data_controller (DataController) – Run state holding the dense
arrays['HRs']produced bypao_hamiltonian, plusa_vectors,alatand, when present,Dnm.threshold (float) – Magnitude in eV below which a hopping is dropped.
rcut (float or None, optional) – Additional bond-length cutoff in Bohr.
- Returns:
The thresholded bond list for the base cell.
- Return type:
Notes
This is the single sanctioned dense-to-sparse boundary of the sparse pipeline, intended for the base (pre-doubling) cell where
HRsis small. The caller is responsible for deletingarrays['HRs']afterwards. Deterministic on every rank (HRsis broadcast bypao_hamiltonian), so no MPI communication is needed.A hopping is kept if it passes the threshold in any spin channel, so both channels keep a common sparsity pattern and the assembly plan is shared between them.
Truncation shifts the eigenvalues, and by how much is bounded rather than guessed. The dropped part of the Hamiltonian is itself a Hermitian matrix at every k, and Gershgorin’s theorem bounds its spectral norm by its largest absolute row sum; a perturbation of that norm can move an eigenvalue by at most that much. Summing the dropped magnitudes per row therefore gives
eig_bound, a rigorous upper bound on the error introduced, valid at every k-point.rcutdrops bonds whose physical length|alat*R + tau_i - tau_j|exceeds it. It is applied as part of the keep mask, not as a post-filter, so the reportedeig_boundcovers both truncations. The kept set has to be closed under the Hermitian pairing(i,j,R) -> (j,i,-R)or the bond list stops being Hermitian. Off the Nyquist plane that is automatic, since-Ris a distinct grid point at the same length. On the folded Nyquist plane-Rmaps ontoRitself, so the two partners get different lengths (measured: tens of Bohr apart) and a plain mask would silently break Hermiticity there; a bond is therefore kept when either partner is inside the cutoff.rcutmust be applied here, at the base cell:doubling.double_axiszeroesdnmon cross-replica blocks (replicating the denseblock_diag(Dnm, Dnm)semantics), after which the true bond vector is no longer recoverable from the container. Note also thatrcutis a physically different truncation axis fromthreshold(bond length vs matrix-element magnitude) and the two interact; the default isNone.
- property plan: dict[str, numpy.ndarray][source]#
The k-independent assembly plan, built on first access.
Notes
Keys are
seg_starts(segment boundaries of the reduction),indicesandindptr(the CSR pattern),R_uniqandRcart(distinct lattice vectors, fractional and Cartesian in units ofalat),ridx(lattice vector of each ordered bond),vals(bond values in plan order) andrcoef(gradient coefficients in Bohr).
- invalidate_plan()[source]#
Discard the cached plan so geometry changes take effect.
Notes
Call after mutating
a_vectors: the Cartesian lattice vectors and the gradient coefficients are baked into the plan, so a stale plan would silently keep using the old cell.
- compact()[source]#
Build the assembly plan and release the raw bond arrays.
- Returns:
self, for chaining.- Return type:
- Raises:
RuntimeError – If already compacted.
Notes
The plan already carries everything per-k assembly needs (ordered values, CSR indices, gradient coefficients), so after it is built
rows/cols/dnm/valsare dead weight — roughly half the steady-state bond memory. Call this once the bond list is final, i.e. after the lastdouble_axisandhermitize.Irreversible: anything that mutates or inspects the bond list (
hermitize(),hermiticity_error(),double_axis()) raises afterwards. Assembly, and therefore every property, is unaffected.
- assemble_hk(kvec, ispin=0, sign=-1, cart=False)[source]#
Assemble
H(k)as a CSR matrix on the fixed union pattern.- Parameters:
- Returns:
The Bloch Hamiltonian at this k-point, in eV.
- Return type:
scipy.sparse.csr_matrix, shape (nawf, nawf)
Notes
Each lattice vector contributes a phase \(e^{s 2\pi i \mathbf{k} \cdot \mathbf{R}}\); every bond is multiplied by the phase of its own lattice vector, and bonds sharing a matrix entry are summed with one segmented reduction over the precomputed group boundaries. The CSR index arrays come straight from the plan, so no sorting or index construction happens per k-point.
- assemble_hk_dhk(kvec, ispin=0, sign=-1, cart=False)[source]#
Assemble
H(k)and its gradient with respect to k.- Parameters:
kvec (np.ndarray, shape (3,)) – The k-point, in the frame selected by
cart.ispin (int, optional) – Spin channel.
sign ({-1, +1}, optional) – Sign of the Fourier phase; see
assemble_hk().cart (bool, optional) – Whether
kvecis Cartesian; see_phase_arg().
- Returns:
(hk, dhk) – The Bloch Hamiltonian, and a list of its three Cartesian derivatives
[dH/dk_0, dH/dk_1, dH/dk_2], all CSR matrices of shape(nawf, nawf).- Return type:
Notes
Differentiating the Fourier sum with respect to k brings down a factor of the bond displacement, so the gradient shares the phase factors and the sparsity pattern of \(H(k)\) and costs only three more segmented reductions. Per bond the coefficient is
1j * (alat * Rcart_l + Dnm_l), replicatinghamiltonian.do_gradient: theRcartterm is the displacement between cells, and theDnmterm is the tight-binding correction for the offset between the two orbitals inside the cell. Both are precomputed in the plan asrcoef.
- hermitize()[source]#
Return the bond-level Hermitian average
(B + B^dagger)/2.- Returns:
A new bond list, exactly Hermitian at every k-point.
- Return type:
- Raises:
RuntimeError – If the bond arrays have been released by
compact().
Notes
A Hamiltonian must be Hermitian, which in real space means the hopping from orbital
jin cell-Rto orbitaliin the home cell is the complex conjugate of the hopping fromitojatR. This method enforces that by averaging the bond list with its own transposed conjugate: each bond(i, j, R, v)is paired with(j, i, -R, conj(v)), both at half weight, and bonds that then coincide are added together. The mirrored-Ris folded back into the R window (+nk/2 -> -nk/2on even axes), so the result stays in folded-grid coordinates and the assembly plan’s Nyquist split applies uniformly.Combined with that split, this is exactly equivalent to replacing
H(k)by(H(k) + H(k)^dagger)/2at every k-point — the operation the dense pipeline applies toHksp/dHkspingradient_and_momenta— done once, in real space, instead of at every k-point.It is needed because the dense doubling kernel (which sparse doubling replicates bond-for-bond) maps the base cell’s self-paired Nyquist plane asymmetrically, leaving the doubled
H(R)slightly non-Hermitian; the dense pipeline mops this up with per-k Hermitizations and one-triangleeighreads, while the sparse solver requires an exactly Hermitian operator. On an already Hermitian bond list this is an exact no-op.The merge groups bonds by a single int64 key (
encode_bond()) rather than bynp.uniqueover a(2*nnz, 5)array: same ordering, roughly 17x faster, and 8 bytes per row instead of 40 — which matters because this step is the memory high-water mark of the whole doubling stage. The position differencesdnmare a per-pair property rather than a weight, so members of a group carry identical values and are assigned rather than summed; the antisymmetryDnm_ij = -Dnm_jiis applied to the mirrored half.
- hermiticity_error()[source]#
Max
|H_ij(R) - conj(H_ji(-R))|over stored bonds.- Returns:
The largest Hermiticity violation, in eV; 0.0 for an empty list.
- Return type:
- Raises:
RuntimeError – If the bond arrays have been released by
compact().
Notes
Diagnostic counterpart of
hermitize(): it measures how far the stored list is from Hermitian without changing it. Each bond is looked up against its(j, i, -R)partner through a sorted search on the packed bond key. A bond whose partner was dropped by thresholding has nothing to cancel against, so it contributes its own magnitude to the error.Fully vectorized: usable as a production assertion at tens of millions of bonds.
- bytes_per_bond()[source]#
Bytes per bond for the three states a bond list passes through.
- Returns:
(container, plan, hermitize_peak) – All per bond of the list being described.
- Return type:
Notes
Derived from the actual allocations, so these track the implementation rather than a remembered constant:
container:rows+cols+ridx(int32) +vals(complex128 per spin) +dnm(3 float64).plan: what survivescompact()—ridx(int64),vals(complex128 per spin),rcoef(3 float64), plus the CSR pattern (seg_startsint64 +indicesint32, at most one per bond).hermitize_peak: everythinghermitize()holds at once, counted per input bond — it works on2*nnzrows, so this is the high-water mark of the whole doubling stage and the number that decides whether a run fits. Terms:triples+mirrored(24 each),rows_all/cols_all(16),triples_all(48),vals(32/spin),dnm(48),code(16),np.unique’s sorted copy and argsort (32),inv+first+uniq_code(48), the output arrays (~112), and the input container that stays alive throughout.
- project_doubling(nx, ny, nz)[source]#
Project the cost of
doubling_Hamiltonian(nx, ny, nz).- Parameters:
- Returns:
d(total doublings),N(cell multiplier2**d),nawfandnnzafter doubling,steady_bytes(the resident cost of the final plan),peak_bytes(the high-water mark during hermitization) anddense_hk_bytes(one denseH(k)at the final size, for comparison).- Return type:
- Raises:
ValueError – If any doubling count is negative.
Notes
Doubling is pure index arithmetic that replicates every bond exactly twice per step (see
PAOFLOW.sparse.doubling), so the final bond count isnnz * 2**(nx+ny+nz)— exact, not a heuristic.nawfscales the same way. The only estimated quantity is the peak, which assumeshermitizeis the high-water mark of the stage (it is: the per-stepdouble_axistransients act on lists at most half as long).nnzis the count entering hermitization, which is what the peak scales with. Hermitization then takes the union of the list with its mirrored conjugate, so the steady-state count lands betweennnz(list already Hermitian, every partner present) and2*nnz(no partner present at all); thresholding drops partners asymmetrically, so growth is the norm — measured 1.19x on example01 at nx=1.steady_bytestherefore carriesHERMITIZE_GROWTH.Running this before the doubling itself is the point: it lets a run fail immediately with a number, instead of after hours, in the out-of-memory killer.