AutoHF API Reference
Top-level API
- class autohf.AutoHFHamiltonian(source=None, settings=None, **kwargs)
Bases:
objectContainer class to hold Hamiltonian terms for AutoHF in internal format.
Hamiltonian terms are stored as
(vals, sites)pairs, wherevalsis a list of unique non-zero coupling values andsitesis a list of the corresponding site-index arrays at which each value appears.- Parameters:
source (AutoHFHamiltonian or afqmctools.Hamiltonian, optional) – If
sourceis anAutoHFHamiltonian, performs a deep-copy (copy constructor). Ifsourceis an afqmctoolsHamiltonian, readsT,U,U1,U2,J, and Heisenberg terms from it. IfNone(default), builds from keyword arguments.settings (dict, optional) –
Convenience dict for lattice geometry. Takes precedence over the
Nx,Ny, andNbandskeyword arguments. Expected keys:"L"–(Nx, Ny)tuple of lattice dimensions (required)."Nbands"– number of orbitals per site (default 1).
**kwargs –
Hamiltonian terms and lattice metadata passed directly. See the Notes section below for the accepted term keywords and array formats. Additional keys:
N– total number of orbitals (sites timesNbands; inferred fromTorsettingsif omitted).Nx,Ny– lattice dimensions (used for metadata only).Nbands– number of orbitals per site (default 1).
Notes
Supported Hamiltonian terms. Supply each term as a keyword argument, with input arrays in the formats below.
Tarray-like, shape(nspin, N, N)One-body hopping matrix. Implements \(\sum_{ij,\sigma} T_{ij} c_{i\sigma}^\dagger c_{j\sigma}\).
Must be a list/tuple/ndarray with one
NxNmatrix per spin sector:(T_up, T_dn)for collinear (UHF) or[T_total]for non-collinear (GHF).Uscalar, 1-D array of lengthN, orNxNmatrixOn-site Hubbard interaction. Implements \(\sum_i U_i n_{i\uparrow} n_{i\downarrow}\).
Accepted forms:
scalar – expanded to
np.ones(N) * Uthen diagonalized.1-D array of length
N– treated as diagonal of the coupling matrix.NxNmatrix – all non-zero entries are used as per-orbital strengths (row indices are stored; off-diagonal entries contribute their row index, which is the intended behavior for orbital-dependentU).
U1NxNarrayInter-orbital mixed-spin density-density coupling. Implements \(\sum_{i<j,\sigma} U1_{ij}\, n_{i\sigma} n_{j\bar\sigma}\).
Stored as
_terms["U1"] = (U1vals, U1Sites), whereU1Sites[k]is a tuple(i_array, j_array)of pairs withi < jand coupling valueU1vals[k]. Only the upper-triangular part of the matrix is used.U2NxNarrayInter-orbital same-spin density-density coupling (Wick-contracted with the exchange correction). Implements \(\sum_{i<j,\sigma} U2_{ij}\, n_{i\sigma} n_{j\sigma}\).
Uses the same format as
U1, stored under_terms["U2"]. Only the upper-triangular part of the matrix is used.JNxNarrayHund’s coupling (HK-model form). Encodes pair-hopping and spin-flip processes between orbitals
iandj. Implements \(\sum_{i<j} J_{ij} (c_{i\uparrow}^\dagger c_{j\uparrow} c_{j\downarrow}^\dagger c_{i\downarrow} + \mathrm{h.c.})\).Uses the same format as
U1, stored under_terms["J"]. Only the upper-triangular part of the matrix is used.Jheis,JheisenbergNxNarrayHeisenberg spin-spin coupling. Implements \(\sum_{i<j} J_{ij}\, \vec{S}_i \cdot \vec{S}_j\).
Uses the same format as
U1, stored under_terms["J_heisenberg"].Jheisenbergis an alias forJheis.
A general second quantized interaction of shape
\[\hat{H}^\text{Int}_V = \sum_{ijkl} V_{ijkl} \hat{c}^\dagger_{i} \hat{c}^\dagger_{j} \hat{c}_{k} \hat{c}_l = \frac 12 \sum_{ijkl} \left( \sum_{n=1}^{N_\text{chol}} v^n_{il} v^n_{kj} \right) \hat{c}^\dagger_{i} \hat{c}^\dagger_{j} \hat{c}_{k} \hat{c}_l\]is supported via the functions
autohf.terms.cholesky.hf_onebody()andautohf.terms.cholesky.hf_cholesky()and a custom energy term. See the Molecules example for more details.- add_terms(**kwargs)
Add one or more Hamiltonian terms.
- Parameters:
**kwargs – Hamiltonian terms and lattice metadata passed directly. See
Supported Hamiltonian Termsin the docstring of AutoHFHamiltonian for the accepted term keywords and array formats.
- get(key, default=None)
- get_one_body()
- keys()
- set(key, value)
- autohf.solve_hf(hamiltonian, settings=None, initial_guess=None, start_from=None, inputfile=None, custom_energy_term=None, verbosity=1, **kwargs)
Run Hartree-Fock on lattice model Hamiltonians.
Minimizes the Hartree-Fock energy of
hamiltonianover the chosen variational ansatz, optionally starting from a supplied initial guess or a previously saved state.- Parameters:
hamiltonian (AutoHFHamiltonian) – The Hamiltonian to solve. Required.
settings (dict, optional) – Dictionary of solver options. If
None, the settings are read frominputfile. The dictionary must also providenelec(the number of electrons). See the Settings table below for the recognized keys.initial_guess (array-like, optional) – Initial Slater-determinant orbitals to start the optimization from. If
None, a free-electron (or random) guess is constructed.start_from (str, optional) – Path to a previously saved state to restart the optimization from. Takes precedence over
initial_guess.inputfile (str, optional) – Path to an input file from which to read
settingswhensettingsisNone.custom_energy_term (callable, optional) – Additional energy term added to the Hartree-Fock energy during optimization.
verbosity (int, default 1) – Console output level:
0minimal (no banner),1usual,2extra detail.**kwargs – Additional keyword arguments forwarded to the energy construction and optimizer (e.g.
optimizer,averageSpins).
- Returns:
output_data (dict) – Results of the run (orbitals, energies, settings, …), as produced by the saving routines.
data_functions (dict) – Helper callables that cannot be pickled, with keys
"makeRDMs","state2Orbitals","energy_func","loss", and"loss_v".
Notes
Settings. The
settingsdictionary (or input file) accepts the following keys:approx_expmdefaultFalseIf
True, use a fast, but approximate, matrix exponentiation.dump_batchdefaultFalseOnly applies when
outputis set. Dump the orbitals from all trials to the output file, as opposed to only those of the best HF solution.etadefault0.1The step size for gradient descent. Has no effect for the
"lbfgs"or"basin"optimization methods.force_complexdefaultFalseIf
True, forces the HF orbitals to be complex-valued.outputdefaultNoneName of the file to save results to. The format and the data saved are determined from the file name.
"*.npy"saves the orbitals to the NumPy binary format."*.h5"saves, in an HDF5 file, \(\alpha\) for the best HF solution and for all trials, the energies for the best HF solution and for all trials, the orbitals of the best variational state, the AutoHF settings, the reference Slater determinant, and the number of electrons used."*.pkl"or"*.pickle"saves the same information as the HDF5 format, but as a Python pickle file. HDF5 is recommended over pickle files for security reasons [1].riemanniandefaultFalseIf
True, use the constraint-dissolving approach to impose optimization on a Stiefel manifold. Only applicable to theSDorSDCansätze.state0_scaledefault0.01Controls the amount of random noise introduced to the initial \(\alpha\). The details of how the noise is applied depend on the specific ansatz used.
verbosedefaultFalseIf
True, turns on verbose debug printing. This will significantly slow down calculations.jaxoptargsdefaultNoneA dictionary of keyword settings to pass along to the jaxopt LBFGS optimizer. See the jaxopt documentation for more.
[1]Only use Python pickle files that you trust. Arbitrary code can be encoded and then executed when loading a pickle file.
Subpackages
Modules
input/output (io)
- autohf.io.loadStates(input_, args, nelec)
Loads saved pkl from saveStates Supports using the same ansatz or any ansatz -> SD/SDC
- autohf.io.read_input_params(infile)
Read parameters from a human-readable input file in TOML format. Returns a Dictionary containing the parameters.
- autohf.io.saveStates(states, orbFunc, energies, phi0, args, nelec, fname, dump_batch)
Save all the trial states in an extra file Will automatically save based on npy/pkl/pickle file extension Does nothing if fname is empty/None
options
- class autohf.options.RepOptions(*values)
Bases:
Enum- CUSTOM = 7
- DIAG = 6
- NONE = 1
- SLATERDET = 2
- SLATERDETC = 3
- SLATERDET_ROT = 4
- SLATERDET_ROTC = 5
- class autohf.options.SlaterType(*values)
Bases:
Enum- CLOSED = 2
- COLLINEAR = 3
- GHF = 4
- NONCOLLINEAR = 4
- NONE = 1
- RHF = 2
- UHF = 3
- autohf.options.get_ansatz(ansatz)
Given a string, return the correct RepOptions, or representation options enum
- Return type:
- autohf.options.process_args(args_dict=None, display=True)
Processes autoHF arguments into a single namespace using default values if not specified. Accepts arguments from either a namespace args, a dictionary args_dict, or a combination. If both are provided and set the same values, the dictionary takes priority. If neither are provided, then a namespace containing default settings is returned.
Will ignore any arguments provided which do not correspond to valid keyword arguments.
- Parameters:
args (Namespace) – a Namespace instance containing arguments (i.e. similar to the output of argparse)
args_dict (dict) – a dict containing arguments. If both args and args_dict set the same argument, the value in args_dict takes precendence.
- Return type:
SimpleNamespace
tools
- autohf.tools.create_polarized_func(phi0, f)
Wrap a function so it receives spin-polarized, occupation-sliced orbitals.
Builds a closure that slices an input state down to the occupied orbitals implied by the collinear reference
phi0before passing it tof. This is used to apply a function defined on the occupied subspace to a larger state array.- Parameters:
phi0 (sequence of array-like) – Collinear reference orbitals
(phi_up, phi_dn). The shapes(N, Nup)and(_, Ndn)determine the slice applied to each input state.f (callable) – Function to call with the sliced
(up, dn)orbital tuple.
- Returns:
rdm_func – Function that takes a state
(state_up, state_dn), slices it to the occupied blocksstate[0][:N, :Nup]andstate[1][:N, :Ndn], and returnsfevaluated on the result.- Return type:
callable
- autohf.tools.sd_to_rdm(sds)
Build the one-body reduced density matrix from collinear orbitals.
Computes the spin-resolved one-body reduced density matrix \(\langle\psi| c_i^\dagger c_j |\psi\rangle / \langle\psi|\psi\rangle\) for a collinear (UHF) Slater determinant.
- Parameters:
sds (array-like, shape
(2, N, Ne)) – The occupied orbitals of the up and down spin sectors.Nis the number of orbitals andNethe number of electrons in each sector (the two sectors may have different occupations).- Returns:
rdm_up (jax.numpy.ndarray, shape
(N, N)) – One-body reduced density matrix of the up-spin sector.rdm_dn (jax.numpy.ndarray, shape
(N, N)) – One-body reduced density matrix of the down-spin sector.
- autohf.tools.sd_to_rdm_noncollinear(sds)
Build the one-body reduced density matrix from noncollinear orbitals.
Computes the one-body reduced density matrix \(\langle\psi| c_i^\dagger c_j |\psi\rangle / \langle\psi|\psi\rangle\) for a noncollinear (GHF) Slater determinant, where the two spin sectors are combined into a single spinor block.
- Parameters:
sds (array-like, shape
(1, N, Ne_total)) – The occupied spinor orbitals.Nis the number of orbitals andNe_totalthe total number of electrons.- Returns:
rdm – The one-body reduced density matrix.
- Return type:
jax.numpy.ndarray, shape
(N, N)
Notes
Unlike
sd_to_rdm(), this returns a single array rather than a tuple, since the collinear spin decomposition does not apply.
- autohf.tools.uhf_to_ghf(x)
Convert collinear (UHF) orbitals to block-diagonal noncollinear (GHF) form.
Embeds the up- and down-spin blocks of a UHF input \([o_\uparrow, o_\downarrow]\) into a single block-diagonal GHF matrix:
\[\begin{split}\begin{bmatrix} o_\uparrow & 0 \\ 0 & o_\downarrow \end{bmatrix}\end{split}\]- Parameters:
x (numpy.ndarray or jax.numpy.ndarray) – A length-2 sequence
[o_up, o_dn]of the up- and down-spin blocks. A NumPy input produces a NumPy result; otherwise a JAX array is returned.- Returns:
The block-diagonal GHF matrix, of the same array type as the input.
- Return type:
numpy.ndarray or jax.numpy.ndarray