AutoHF API Reference

Top-level API

class autohf.AutoHFHamiltonian(source=None, settings=None, **kwargs)

Bases: object

Container class to hold Hamiltonian terms for AutoHF in internal format.

Hamiltonian terms are stored as (vals, sites) pairs, where vals is a list of unique non-zero coupling values and sites is a list of the corresponding site-index arrays at which each value appears.

Parameters:
  • source (AutoHFHamiltonian or afqmctools.Hamiltonian, optional) – If source is an AutoHFHamiltonian, performs a deep-copy (copy constructor). If source is an afqmctools Hamiltonian, reads T, U, U1, U2, J, and Heisenberg terms from it. If None (default), builds from keyword arguments.

  • settings (dict, optional) –

    Convenience dict for lattice geometry. Takes precedence over the Nx, Ny, and Nbands keyword 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 times Nbands; inferred from T or settings if 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 N x N matrix per spin sector: (T_up, T_dn) for collinear (UHF) or [T_total] for non-collinear (GHF).

Uscalar, 1-D array of length N, or N x N matrix

On-site Hubbard interaction. Implements \(\sum_i U_i n_{i\uparrow} n_{i\downarrow}\).

Accepted forms:

  • scalar – expanded to np.ones(N) * U then diagonalized.

  • 1-D array of length N – treated as diagonal of the coupling matrix.

  • N x N matrix – 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-dependent U).

U1N x N array

Inter-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), where U1Sites[k] is a tuple (i_array, j_array) of pairs with i < j and coupling value U1vals[k]. Only the upper-triangular part of the matrix is used.

U2N x N array

Inter-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.

JN x N array

Hund’s coupling (HK-model form). Encodes pair-hopping and spin-flip processes between orbitals i and j. 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, JheisenbergN x N array

Heisenberg 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"]. Jheisenberg is an alias for Jheis.

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() and autohf.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 Terms in 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 hamiltonian over 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 from inputfile. The dictionary must also provide nelec (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 settings when settings is None.

  • custom_energy_term (callable, optional) – Additional energy term added to the Hartree-Fock energy during optimization.

  • verbosity (int, default 1) – Console output level: 0 minimal (no banner), 1 usual, 2 extra 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 settings dictionary (or input file) accepts the following keys:

approx_expmdefault False

If True, use a fast, but approximate, matrix exponentiation.

dump_batchdefault False

Only applies when output is set. Dump the orbitals from all trials to the output file, as opposed to only those of the best HF solution.

etadefault 0.1

The step size for gradient descent. Has no effect for the "lbfgs" or "basin" optimization methods.

force_complexdefault False

If True, forces the HF orbitals to be complex-valued.

outputdefault None

Name 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].

riemanniandefault False

If True, use the constraint-dissolving approach to impose optimization on a Stiefel manifold. Only applicable to the SD or SDC ansätze.

state0_scaledefault 0.01

Controls the amount of random noise introduced to the initial \(\alpha\). The details of how the noise is applied depend on the specific ansatz used.

verbosedefault False

If True, turns on verbose debug printing. This will significantly slow down calculations.

jaxoptargsdefault None

A 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:

RepOptions

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 phi0 before passing it to f. 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 blocks state[0][:N, :Nup] and state[1][:N, :Ndn], and returns f evaluated 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. N is the number of orbitals and Ne the 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. N is the number of orbitals and Ne_total the 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