safiretools#
safiretools is the companion Python package of SAFIRE. It contains tools to
prepare the Hamiltonian and Wavefunction HDF5 files SAFIRE reads
read and postprocess the results of a SAFIRE calculation
visualize common inputs and outputs such as lattices and timeseries
Installation#
safiretools is installed with pip from the python directory of the SAFIRE source
tree:
$ pip install "./python[GROUPNAME]"
Optional Dependencies#
Additional functionality is enabled by optional dependency groups, installed via
$ pip install "./python[GROUPNAME]"
where GROUPNAME is one of the groups below.
Group Name |
installs |
enables |
|---|---|---|
pyscf |
pyscf>=2.4.0 |
building Hamiltonians and wavefunctions from PySCF calculations |
vis |
matplotlib |
the plotting helpers in |
testing |
pytest |
running the safiretools test suite |
docs |
sphinx and its extensions |
building this documentation |
The AutoHF Hartree-Fock solver for lattice models is a separate package, installed with
pip install sfqmc-autohf
API Reference#
The public interface of safiretools is what the top-level package exports; anything reachable only through a deeper module path is an implementation detail.
Use this documentation as a reference. For practical instructions, the Tutorials and Examples are a good starting point.
safiretools#
- class safiretools.Hamiltonian(spin_symm=SpinSymm.CLOSED)#
Bases:
ABCBase class for all SAFIRE Hamiltonians.
- Parameters:
spin_symm (SpinSymm or str or int, optional) – Spin symmetry of the Hamiltonian. Coerced through SpinSymm.from_input, so
'uhf','collinear'andSpinSymm.COLLINEARare all accepted.
Notes
__init__takes already-formed, validated in-memory data. Build a Hamiltonian from an external description with one of the classmethod factories on the concrete subclasses (from_lattice,from_hdf5, …).- property spin_symm#
Spin symmetry of this Hamiltonian, as a SpinSymm (or None).
- abstract property basis_rotation: ndarray#
The transformation from the basis this Hamiltonian was given (e.g. atomic orbitals) in to the basis the AFQMC executable computes in (e.g. molecular or Löwdin orbitals).
Its columns are the computational orbitals expanded in the input basis, so a one-body operator transforms as \(h' = R^\dagger h R\).
- abstractmethod to_hdf5(path)#
Write this Hamiltonian to the HDF5 file path, in the format the AFQMC executable reads for this Hamiltonian’s domain.
- Return type:
None
- classmethod from_hdf5(path)#
Read a Hamiltonian from the HDF5 file path.
Called on Hamiltonian itself, the concrete subclass is chosen from the format stored in the file. Called on a concrete subclass, the file must hold a format that subclass reads.
- Parameters:
path (str or pathlib.Path) – HDF5 file to read.
- Returns:
An instance of the concrete subclass for the stored format.
- Return type:
- Raises:
ValueError – If the file holds no recognized Hamiltonian, holds one that the subclass this was called on does not read, or was written in another format version.
- class safiretools.HamiltonianBuilder(lattice, nbands=1, spin_symm=SpinSymm.COLLINEAR)#
Bases:
objectBuilds a LatticeHamiltonian on a Lattice, one term at a time.
- Parameters:
- Raises:
ValueError – When a build step is given an amplitude it can’t build from, or when no Hubbard-Stratonovich type can be unambiguously inferred.
Notes
See the User Documentation for the definition and input conventions of each Hamiltonian term.
- get_hamiltonian()#
The LatticeHamiltonian being built.
- Return type:
- classmethod from_input(lattice, *, nbands=1, spin_symm=None, t=1.0, epsilon=None, rashba_lambda=None, custom_one_body=None, U=None, U1=None, U2=None, J=None, J_heisenberg=None, V=None, pinning=None, hst_types=None)#
Construct and fully build a HamiltonianBuilder from keyword input.
Runs the build step of every given term and finalizes. Use get_hamiltonian on the result. Nearest-neighbor hopping is included by default; every other term must be requested explicitly. The build-step methods document finer control and the full input conventions.
- Parameters:
lattice (
Lattice) – Lattice describing the geometry.nbands (
int) – Number of bands. Default 1.spin_symm (SpinSymm or str or int, optional) – Spin symmetry the Hamiltonian is expressed in. By default SpinSymm.NONCOLLINEAR if rashba_lambda or a (2*nbasis, 2*nbasis) custom_one_body is given, otherwise SpinSymm.COLLINEAR.
t (float or array_like, optional) –
nth-order neighbor hopping (nth_neighbor_hopping). Default 1.0;
Nonemeans no hopping.a scalar gives nearest-neighbor hopping with strength t, within each band
a 1-dimensional list
[t1, t2, ..., tn]gives up to nth-order hoppinga 2-dimensional array with shape (nbands, nbands) gives band-resolved nearest-neighbor hopping: \(t_{mn}\) hops between band m on one site and band n on its neighbor
a list of (nbands, nbands) arrays gives band-resolved hopping up to nth order, the ith array for (i+1)th-order neighbors
Hopping only connects distinct sites; on-site inter-band terms go in epsilon.
epsilon (float or array_like, optional) – On-site one-body term (onebody_onsite), applied uniformly to all sites. A scalar is an on-site energy for every band; an (nbands, nbands) matrix gives band energies on the diagonal and on-site inter-band hopping off it.
rashba_lambda (float, optional) – Rashba spin-orbit coupling strength (rashba_soc), multiplying the hopping t of every neighbor order. Implies NONCOLLINEAR spin_symm; requires a scalar or 1-dimensional t.
custom_one_body (array_like, optional) – One-body matrix added as is (custom_one_body).
U (float or array_like, optional) –
Onsite Hubbard interaction (onsite_hubbard).
a scalar applies to all sites and bands
a 1-dimensional list of length nbands gives U_i on band i, uniformly across sites
a 1-dimensional list of length nsites gives U_i on site i, uniformly across bands
U1 (float or array_like, optional) – Hubbard density-density interaction (hubbard_U1_density_density). A scalar applies to all sites, uniformly across bands; an (nbands, nbands) matrix is an intrasite density-density interaction, applied uniformly across sites.
U2 (float or array_like, optional) – Hubbard spin-spin interaction (hubbard_U2_spin_spin), with the same conventions as U1.
J (float or array_like, optional) – Hund’s coupling (hubbard_Jij), with the same conventions as U1.
J_heisenberg (float or array_like, optional) – Heisenberg exchange (heisenberg_J).
V (float or array_like, optional) – Inter-site Hubbard interaction (nth_order_hubbard_Vij). A list gives up to nth-order neighbors.
pinning (sequence of two PinningField or None, optional) – Edge pinning fields per lattice axis (pinning).
hst_types (
dict) – Hubbard-Stratonovich type overrides, keyed by the interaction keyword ('U','U1', …). Inferred from the sign of the interaction by default.
- Return type:
Examples
>>> lattice = Lattice.from_type('square', (4, 4), ... boundaries=('periodic', 'periodic'), ... twists=(0.0, 0.0)) >>> builder = HamiltonianBuilder.from_input(lattice, t=1.0, U=4.0) >>> hamiltonian = builder.get_hamiltonian()
- nth_neighbor_hopping(t=1.0, nth_neighbor=1, spin_symm=None, opposite_twists=False)#
adds an nth-order neighbor hopping term to the Hamiltonian
\[\sum_{\langle ij\rangle^n} (-t) \hat{c}^\dagger_i \hat{c}_j\]- Parameters:
t (float | numpy.ndarray, default: 1.0) – the hopping strength. By convention a minus sign (-) is applied to the hopping. i.e. \(\sum_{<ij>} (-t) \hat{c}^\dagger_i \hat{c}_j\) If t is a float, it hops between the same band on neighboring sites. If t is a numpy.ndarray of shape (nbands, nbands), \(t_{mn}\) hops from band n on one neighboring site to band m on the other; it never couples bands on the same site (see onebody_onsite for that). A 1-dimensional list of floats, or a list of (nbands, nbands) matrices, gives one entry per neighbor order and is iterated over, see nth_neighbor.
nth_neighbor (
int) – the order of neighbor to use for hopping. nth_neighbor equal to 1 is nearest-neighbors. If t is a list, it is ignored: entry i of t is used for nth_neighbor=i+1.spin_symm (SpinSymm, optional) – an override for the default spin symmetry enumerated type for the hopping matrix. If not given, the spin symmetry of the Hamiltonian will be used.
opposite_twists (bool, optional, default: False) – if True, the hopping matrix is constructed using opposite twists, for the up and down spins (i.e. twist_down = -twist_up ). If False, the hopping matrix is constructed using the same twist for both spins.
- Raises:
ValueError – when the hopping matrix can’t be constructed for the combination of t and nth_neighbor, or when a band-dependent t is not Hermitian
Examples
adds default hopping (nearest-neighbor with t=1.0)
>>> builder.nth_neighbor_hopping()
add nearest-, and next-nearest-neighbor hopping
>>> builder.nth_neighbor_hopping(t=[1.0,0.5])
- custom_one_body(in_mat, spin_symm=None)#
add a custom one-body term to the Hamiltonian
- Parameters:
in_mat (
ndarray) – the one-body term to add to the Hamiltonianspin_symm (SpinSymm, optional) – an override for the default spin symmetry enumerated type for the hopping matrix. If not given, the spin symmetry of the Hamiltonian will be used.
Notes
The in_mat must have a valid shape for the Hamiltonian and spin symmetry. For CLOSED spin symmetry that is (nbasis,nbasis); for COLLINEAR also the stacked up/down sectors (2*nbasis,nbasis); for NONCOLLINEAR also the full spinor matrix (2*nbasis,2*nbasis). A single (nbasis,nbasis) matrix is used for both spin sectors.
Examples
>>> import numpy as np >>> from safiretools import HamiltonianBuilder, Lattice >>> lattice = Lattice.from_type('square', (3, 2), ... boundaries=('periodic', 'periodic'), ... twists=(0.0, 0.0)) >>> builder = HamiltonianBuilder(lattice=lattice) >>> nbasis = lattice.N_sites >>> one_body_matrix = 0.0001*np.random.rand(nbasis, nbasis) >>> one_body_matrix = 0.5*(one_body_matrix + one_body_matrix.T) >>> builder.custom_one_body(one_body_matrix) >>> builder.finalize()
- onebody_onsite(epsilon, spin_symm=None)#
- Adds an onsite one-body term to the Hamiltonian (for example, a chemical potential,
band energies, interband hopping, etc.)
\[\hat{H}_{onsite} = \sum_i \sum_{m m'} \epsilon_{m m'} \hat{c}^\dagger_{i,m} \hat{c}_{i,m'}\]where \(\hat{c}^\dagger_{i,m}\)/\(\hat{c}_{i,m}\) are the creation / annihilation operator for site i and band m.
- Parameters:
epsilon (float | numpy.ndarray) – the onsite energy. If epsilon is a float, it is interpreted as a band-independent onsite energy. If epsilon is a numpy.ndarray, it must have shape (nbands,nbands) and is interpreted as a band-dependent onsite energy. In all cases, epsilon is applied uniformly to all sites.
spin_symm (SpinSymm, optional) – an override for the default spin symmetry of the term.
- Raises:
ValueError – when a band-dependent epsilon is not Hermitian
- rashba_soc(rashba_lambda=1.0, t=1.0, n=1, spin_symm=None)#
Builds a Rashba spin-orbit coupling term of the form:
\[\hat{H}_{rashba SOC} = i \lambda_{rashba} \sum_{ij,\sigma\sigma'} t_{ij} (\vec{\sigma} \times \hat{r}_{ij})^{\sigma\sigma'}_z \hat{c}^\dagger_{i\sigma} \hat{c}_{j\sigma'}\]where \(\vec{\sigma}\) is the vector of Pauli matrices, and \(\vec{r}_{ij}\) is the relative position between sites i and j.
- pinning(pinning, spin_symm=None)#
Adds edge pinning fields to the Hamiltonian
Builds the one-body term \(\sum_{i \sigma} v_{i\sigma} \hat{n}_{i\sigma}\) on the edge sites, lattice coordinate 0 or L-1, of each pinned axis.
- Parameters:
pinning (sequence of two PinningField or None) – The field on the edges at the ends of axis 0 and of axis 1.
Noneleaves that axis unpinned. A site on the edges of both axes gets the sum of the two fields.spin_symm (SpinSymm, optional) – an override for the default spin symmetry enumerate type for the pinning matrix. If not given, the spin symmetry of the Hamiltonian will be used.
- Raises:
ValueError – if pinning does not have one entry per lattice axis
- onsite_hubbard(U, hst_type=None)#
adds onsite Hubbard U to the Hamiltonian with possibly band-dependent amplitude U. See Notes for conventions.
- Parameters:
U (float | iterable | numpy.ndarray) – the amplitude of the onsite Hubbard interaction. See Notes for the conventions on how U is interpreted.
hst_type (str, optional) – the type of Hubbard-Stratonovich transformation (HST) to use in AFQMC. If not specified, an appropriate HST type will be inferred based on U.
Notes
conventions:
a single number given for U implies the same U for all sites
a 1-Dimensional array with length nbands gives a different U for each band, but U is independent of site index.
a 1-Dimensional array with length nsites gives a different U for each site, uniform across bands.
Advanced Notes:
in case of an array of U values, the U values are separated into positive and negative values. Up to two terms may be generated (i.e. one positive and one negative) to allow different Hubbard-Stratonovich Transformations to be used for each case.
- hubbard_U1_density_density(U1, hst_type=None, nth_neighbor=0)#
Adds a density-density Hubbard U1 term to the Hamiltonian.
\[H_{U_1} = \sum_{ij} U^1_{ij} (n_{i\uparrow} n_{j\downarrow} + n_{i\downarrow} n_{j\uparrow})\]- Parameters:
U1 (float | numpy.ndarray) – the amplitude of the Hubbard U1 term. See Notes for conventions.
hst_type (str, optional) – the type of Hubbard-Stratonovich transformation (HST) to use in AFQMC. If not specified, an appropriate HST type will be inferred based on U1.
nth_neighbor (int, optional) – the order of neighbor to use for the interaction term. If not given, the interaction is assumed to be on-site.
Notes
conventions:
a single number given for U1 implies the same U1 for all sites, and is uniform across bands
- hubbard_U2_spin_spin(U2, hst_type=None, nth_neighbor=0)#
Adds a spin-spin Hubbard U2 term to the Hamiltonian.
\[H_{U_2} = \sum_{ij} U^2_{ij} (n_{i\uparrow} n_{j\uparrow} + n_{i\downarrow} n_{j\downarrow})\]- Parameters:
U2 (float | numpy.ndarray) – the amplitude of the Hubbard U2 term. See Notes for conventions.
hst_type (str, optional) – the type of Hubbard-Stratonovich transformation (HST) to use in AFQMC. If not specified, an appropriate HST type will be inferred based on U2.
nth_neighbor (int, optional) – the order of neighbor to use for the interaction term. If not given, the interaction is assumed to be on-site.
Notes
conventions:
a single number given for U2 implies the same U2 for all sites, and is uniform across bands
- hubbard_Jij(J, hst_type=None, nth_neighbor=0)#
Adds a Hund’s J term to the Hamiltonian.
The general form of the Hund’s J term is:
\[\sum_{i<j} J_{ij} ( \hat{c}^\dagger_{i\uparrow}\hat{c}^\dagger_{j\downarrow}\hat{c}_{i\downarrow}\hat{c}_{j\uparrow} +\hat{c}^\dagger_{i\uparrow}\hat{c}^\dagger_{i\downarrow}\hat{c}_{j\downarrow}\hat{c}_{j\uparrow} +\hat{c}^\dagger_{j\uparrow}\hat{c}^\dagger_{i\downarrow}\hat{c}_{j\downarrow}\hat{c}_{i\uparrow} +\hat{c}^\dagger_{j\uparrow}\hat{c}^\dagger_{j\downarrow}\hat{c}_{i\downarrow}\hat{c}_{i\uparrow} ),\]where i,j are combined site and band indices.
Here, we generate the \(J_{ij}\) matrix which will be interpreted as above.
- heisenberg_J(J, hst_type=None, nth_neighbor=1)#
Adds an isotropic Heisenberg spin-term.
The isotropic Heisenberg Hamiltonian can be expressed in terms of the Hubbard-Kanamori terms as:
\[H_{Heisenberg}[J] = H_{U_1}[-J/2] + H_{U_2}[J/2] - J \sum_{i < j}( C^\dagger_{i \uparrow}C^\dagger_{j \downarrow} C_{i \downarrow}C_{j \uparrow} + C^\dagger_{i \downarrow}C^\dagger_{j \uparrow} C_{i \uparrow}C_{j \downarrow} )\]The last two terms are two of the four terms of the Hund’s J.
- nth_order_hubbard_Vij(V, hst_type=None, nth_neighbor=1)#
Builds an extended Hubbard model V term and adds it to the Hamiltonian.
The conventions used are, if \(i = (\mu, m)\) is a combined lattice and band index,
\[H_V = \sum_{\langle(i<j)\rangle} \sum_{\sigma \sigma'} V_{n m} ( \hat{n}_{i \sigma \sigma'} \hat{n}_{j \sigma \sigma'} )\]which is equivalent to \(H_V = H_{U_1}(U_1=V) + H_{U_2}(U_2=V)\).
- log_components(verbose=False)#
Log each current Hamiltonian component, and its matrix if verbose.
- Return type:
None
- finalize(verbose=False)#
Combine Hamiltonian terms wherever possible, keeping terms with different hst_type separate, and settle the Hamiltonian’s spin symmetry.
- Parameters:
verbose (bool) – Log each component’s matrix before and after combining.
- Return type:
None
- class safiretools.Lattice(lattice_vectors, basis, Ls, *, boundaries, twists=(0.0, 0.0), build=True)#
Bases:
objectA two-dimensional lattice: a unit cell repeated
Ls[0] x Ls[1]times.- Parameters:
lattice_vectors (array_like, shape (2, 2)) – The lattice vectors
a1anda2, one per row.basis (array_like, shape (nb, 2)) – Positions of the sites within the unit cell, in fractional coordinates of the lattice vectors: site
bof cell(n1, n2)sits atA @ ((n1, n2) + basis[b]).Ls (iterable(int)) – 2-element lattice size, in units of the unit cell.
boundaries (iterable(str)) – Boundary condition along each lattice vector:
'open'or'periodic'('pbc'is accepted as an alias).twists (iterable, optional) – Twist angle in radians along each lattice vector, picked up when crossing a periodic boundary. Elements are numbers or strings such as
'1/2 pi'. Default is no twist,(0.0, 0.0).build (bool, optional) – Build the lattice sites immediately. Default is True.
Notes
Aandbasisare read-only properties, and the arrays they return are themselves immutable, so the geometry cannot be replaced or edited in place after construction.build() raises ValueError for a basis the neighbor search cannot handle: two basis vectors differing by a lattice translation, or an offset reaching a full supercell. See _validate_basis.
Examples
A Lieb lattice, a square lattice with a three-site basis:
>>> lattice = Lattice([[1, 0], [0, 1]], [[0, 0], [0.5, 0], [0, 0.5]], (4, 4), ... boundaries=('periodic', 'periodic'))
- classmethod from_type(type, Ls, *, cyl_mode=None, **kwargs)#
A lattice with the unit cell of a built-in lattice type.
- Parameters:
type (
str) – ‘square’, ‘triangular’, ‘honeycomb’ or ‘kagome’.Ls (iterable(int)) – 2-element lattice size, in units of the unit cell.
cyl_mode ({None, 'XC', 'YC'}, optional) – Reshape the triangular unit cell into a rectangular one of twice the size,
a2 -> -a1 + 2*a2. ‘XC’ halvesLs[1]. ‘YC’ halvesLs[0]and swaps the x and y components of the cell, so the lattice is(Ls[1], Ls[0] // 2)cells. Only for ‘triangular’.**kwargs – Forwarded to the Lattice constructor:
boundaries,twistsandbuild.
- Return type:
Examples
A honeycomb lattice with a twist, open along the second axis:
>>> lattice = Lattice.from_type('honeycomb', (6, 6), ... boundaries=('periodic', 'open'), ... twists=('1/2 pi', 0.0))
- property A#
The lattice vectors
a1anda2as the columns of a 2x2 matrix, so sitebof cell(n1, n2)sits atA @ ((n1, n2) + basis[b]). Read-only; see Lattice.
- property basis#
Basis vectors within the unit cell, in fractional coordinates of the lattice vectors. Read-only; see Lattice. The list and its arrays are both immutable.
- property nb#
Number of sites in the unit cell (basis size).
- property num_sublattice#
Number of sublattices; alias of nb.
- add_site(coord)#
Interface for external Builder
- get_nth_neighbors(n=1)#
High-Level interface to get all nth-nearest neighbors
- get_nth_direct_neighbors(n=1)#
get nth-order direct neighbors within the home cell only
- get_positions(sublattice_index=None)#
Get the positions of all sites in the lattice.
- Parameters:
sublattice_index (int, optional) – index of the sublattice to get positions for. If None, returns positions for all sites in the lattice. Default is None.
- Returns:
array of positions of all sites in the lattice
- Return type:
np.ndarray
- get_kvecs()#
get b1,b2 the Bravais lattice vectors
- get_planewaves(returnKVecs=False)#
return unitary exp(ik*r) for each site, corresponding to the unit cell r. Currently fixed to periodic/periodic only
- build()#
Populate the lattice sites.
Building twice is an error: the site list does not change once a lattice is built.
- is_image(r)#
True if r, in lattice coordinates, lies outside the lattice.
- Return type:
bool
- get_directed_pairs(directions=None, nbands=1)#
The DirectedPairs the
PairCorrelatorestimator reads — see get_directed_pairs.
- class safiretools.LatticeHamiltonian(nsites, nbands=1, spin_symm=SpinSymm.CLOSED, lattice_metadata=None)#
Bases:
HamiltonianA lattice-model Hamiltonian: a dictionary of sparse terms keyed by the names the AFQMC executable uses.
An example of the internal structure:
terms = { 'tij' : [tij_component_1, tij_component_2, ...], 'Uij' : [U_component], 'Jij' : [Jij_component], }
Each key maps to a list of HamiltonianComponent. Keeping terms separate is what makes different Hubbard-Stratonovich transformations possible within one Hamiltonian; HamiltonianBuilder.finalize collapses the ones that can be combined.
- Parameters:
nsites (
int) – Number of lattice sites.nbands (
int) – Number of bands per site. Default 1.spin_symm (SpinSymm or str or int, optional) – Spin symmetry of the Hamiltonian. Default SpinSymm.CLOSED.
lattice_metadata (dict, optional) – Shape of the lattice this Hamiltonian was built on — see lattice_metadata_from. Recorded on disk; not used for any computation.
Notes
This class is a container only. It holds no reference to a Lattice, and terms are built by HamiltonianBuilder.
- add_term(key, component)#
Append component to the list of terms stored under key.
- Return type:
None
- pop_term(key)#
Remove and return every component stored under key.
Warning
Destructive. HamiltonianBuilder.finalize uses this to move terms out before writing combined ones back.
- property num_components: int#
Total number of components across all terms.
- property real_valued: bool#
True when every component has real matrix elements.
The AFQMC executable requires all components of a file to be either real or complex, so this decides the on-disk dtype for the whole Hamiltonian.
- property nbasis: int#
Single-particle basis size,
nsites * nbands.
- property basis_rotation: ndarray#
a lattice model is computed in the basis it is given in.
- Type:
The identity
- get_one_body()#
The one-body part of the Hamiltonian summed into a single scipy.sparse.csr_array, or None if there is no one-body term.
- get_U()#
The Hubbard interaction (U, U1 and U2 together) as a single scipy.sparse.csr_array.
U and U1 share a shape and are summed; U2 occupies the lower half of a
(2*nbasis, nbasis)matrix, so the two families are placed separately rather than summed directly.
- get_J()#
The Hund’s J part of the Hamiltonian as a single sparse matrix.
- get_heisenberg()#
The Heisenberg part of the Hamiltonian as a single sparse matrix.
- classmethod from_lattice(lattice, **kwargs)#
Build a fully finalized LatticeHamiltonian on lattice.
This is the common-case wrapper around HamiltonianBuilder: it runs the build steps the keyword arguments name, and finalizes. Use HamiltonianBuilder directly to compose terms that no keyword covers.
- Parameters:
lattice (Lattice) – Lattice to build on.
**kwargs – Hamiltonian parameters, as documented in HamiltonianBuilder.from_input.
- Return type:
Examples
>>> lattice = Lattice.from_type('square', (4, 4), ... boundaries=('periodic', 'periodic'), ... twists=(0.0, 0.0)) >>> hamiltonian = LatticeHamiltonian.from_lattice(lattice, t=1.0, U=4.0)
- property lattice_params: dict#
The recorded lattice as Lattice constructor arguments, or
{}if no lattice metadata was recorded.Examples
The same lattice with a twist:
>>> lattice = Lattice(**dict(hamiltonian.lattice_params, twists=(0.1, 0.2)))
- to_hdf5(path)#
Write this Hamiltonian in the sparse component format the AFQMC executable’s
ModelHamOpsGeneratorreads.- Parameters:
path (str or pathlib.Path) – HDF5 file to write into. Created if it does not exist. A Hamiltonian already in the file is replaced; everything else — notably a
Wavefunction— is left alone, so a Hamiltonian and a wavefunction can share one file in either order.- Return type:
None
Notes
Set spin_symm on the instance before calling; it is recorded in the file. No electron count is recorded: the AFQMC executable takes it from the wavefunction.
- class safiretools.MolecularHamiltonian(hcore, chol, enuc=0.0, spin_symm=SpinSymm.CLOSED, basis_rotation=None)#
Bases:
HamiltonianA dense, Cholesky-factorized molecular Hamiltonian.
- Parameters:
hcore (numpy.ndarray) – One-body Hamiltonian in the working basis,
(nspin, npol, nmo, npol, nmo). A single matrix(npol*nmo, npol*nmo)or one per spin sector(nspin, npol*nmo, npol*nmo)is accepted too and reshaped into that — see spin_blocked_hcore.chol (numpy.ndarray) – Cholesky vectors \(L^\gamma_{ij}\),
(nspin, npol, nmo, npol, nmo, nchol). The flat Cholesky matrix(nmo*nmo, nchol)or(npol*nmo*npol*nmo, nchol)— pair index first — is accepted too and reshaped into that; see spin_blocked_chol.enuc (float, optional) – Constant (nuclear repulsion) energy. Default 0.0.
spin_symm (SpinSymm or str or int, optional) – Spin symmetry. Default SpinSymm.CLOSED.
basis_rotation (numpy.ndarray, optional) – Transformation from the input (AO) basis to the working basis,
(npol*nao, npol*nmo): the spinor matrix, spin-up block first, for a noncollinear Hamiltonian; see Hamiltonian.basis_rotation. Written asHamiltonian/BasisRotationwhen given. Omitted, the integrals are taken to be in the working basis already.
- Raises:
ValueError – If basis_rotation does not span
npolpolarizations ofnmoorbitals in its columns and of some input basis in its rows.
- property basis_rotation: ndarray#
The stored
(npol*nao, npol*nmo)transformation, or the identity when the Hamiltonian was given in its working basis.
- property nspin: int#
Number of independent spin sectors; see SpinSymm.nspin.
- property npol: int#
2 for a spin-orbital basis; see SpinSymm.npol.
- property nmo: int#
Number of orbitals, i.e. spatial orbitals unless noncollinear.
- property nchol: int#
Number of Cholesky vectors.
- property complex_chol: bool#
Whether the Cholesky matrix is written as complex. Decided by the data: complex exactly when some element has a nonzero imaginary part.
Note
The AFQMC executable’s
RealDenseHamiltonianreadsDenseFactorized/Linto a real array, so it cannot consume a complex-Cholesky file.
- classmethod from_integrals(hcore, chol=None, eri=None, enuc=0.0, spin_symm=SpinSymm.CLOSED, cholesky_tol=1e-06, verbose=False)#
Build a Hamiltonian from integrals supplied directly.
- Parameters:
hcore (numpy.ndarray) – One-body Hamiltonian, in any of the layouts spin_blocked_hcore accepts — usually
(npol*nmo, npol*nmo).chol (numpy.ndarray, optional) – Cholesky vectors \(L_{\gamma,(ij)}\), shape
(nchol, nmo**2). Exactly one of chol and eri is required.eri (numpy.ndarray, optional) – Coulomb repulsion tensor in chemists’ notation,
(ij|kl), shape(nmo, nmo, nmo, nmo). Decomposed here if given.enuc (float, optional) – Constant energy contribution. Default 0.0.
spin_symm (SpinSymm or str or int, optional) – Spin symmetry. Default SpinSymm.CLOSED.
cholesky_tol (float, optional) – Tolerance for decomposing eri. Default 1e-6.
verbose (bool, optional) – Log the decomposition’s convergence.
- Return type:
- Raises:
ValueError – If neither or both of chol and eri are given, or if either has the wrong shape.
- classmethod from_pyscf(mf, basis=None, active_space=None, df=False, chol_cut=1e-05, verbose=False)#
Build a Hamiltonian from a PySCF molecular SCF object.
- Parameters:
mf – The source of the physics:
mf.get_hcore()is the one-body Hamiltonian, andmf.molsupplies the two-electron integrals and the nuclear repulsion. The relativistic treatment is whatever mf was set up with —mol.RHF().sfx2c1e(),mol.GHF().x2c1e(), or a GHF object withwith_soc = Truefor the spin-orbit ECP term. mf need not be converged unless it also supplies the basis.basis (None or 'ortho_ao' or object or numpy.ndarray, optional) – The orbitals the Hamiltonian is expressed in.
Noneuses mf’s own orbitals,'ortho_ao'the canonically orthogonalized AO basis, an object itsmo_coeff(an ROHF or CASSCF solution, say), and an array is taken as the(nao, nmo)transformation itself. UHF and GHF orbitals cannot serve as a basis. Pass the same basis to safiretools.Wavefunction.from_pyscf.active_space (tuple(int, int), optional) –
(nelecas, ncas)active space; core orbitals are frozen into the one-body term and the constant.ncas == -1takes every orbital above the frozen core. Incompatible withbasis='ortho_ao'.df (bool, optional) – Use mf’s density-fitting vectors instead of decomposing the two-electron integrals, which needs a density-fitted mf.
chol_cut (float, optional) – Cholesky decomposition accuracy. Default 1e-5.
verbose (bool, optional) – Log timing and convergence progress.
- Returns:
Noncollinear when
mf.get_hcore()is a spinor matrix, closed otherwise: a spin-independent one-body operator gains nothing from two identical spin sectors.- Return type:
- Raises:
ValueError – If basis is an unknown string, UHF/GHF orbitals, does not span mf’s AO basis, or is
'ortho_ao'together with active_space; or if df is set and mf is not density fitted.
- classmethod from_fcidump(path, symmetry=None, cholesky_tol=1e-06, spin_symm=None, verbose=False)#
Build a Hamiltonian from a plain-text FCIDUMP file.
FCIDUMP stores the two-electron integrals in full rather than factorized, so they are Cholesky-decomposed here, as from_integrals does for an eri tensor.
The file’s
MS2header field decides the spin symmetry, and the integrals are reoriented from FCIDUMP’s \((ik|jl)\) to the \(\{(ik), (lj)\}\) pair order the decomposition needs.- Parameters:
path (str or pathlib.Path) – FCIDUMP file to read.
symmetry (int, optional) – Permutational symmetry of the two-electron integrals, 1, 4 or 8. Read from the file’s header when omitted, since some codes misreport it there.
cholesky_tol (float, optional) – Tolerance for decomposing the two-electron integrals. Default 1e-6.
spin_symm (SpinSymm or str or int, optional) – Spin symmetry. Defaults to SpinSymm.CLOSED when the header’s
MS2is zero and SpinSymm.COLLINEAR otherwise. Pass SpinSymm.NONCOLLINEAR for a FCIDUMP already written in a spinor basis, which the file itself does not record.verbose (bool, optional) – Log what was read and the decomposition’s convergence.
- Return type:
- Raises:
ValueError – If the header has no end marker, or names a permutational symmetry other than 1, 4 or 8.
- to_hdf5(path)#
Write this Hamiltonian in the dense format
RealDenseHamiltonianreads.- Parameters:
path (str or pathlib.Path) – HDF5 file to write into. Created if it does not exist. A Hamiltonian already in the file is replaced; everything else — notably a
Wavefunction— is left alone, so a Hamiltonian and a wavefunction can share one file in either order.- Return type:
None
- to_fcidump(path, nelec=(0, 0), tol=1e-08, ctol=1e-12, sym=1, cplx=True, paren=False, use_spinor=False)#
Write this Hamiltonian as a plain-text FCIDUMP file.
The two-electron integrals are reconstructed from the Cholesky matrix and written out in full, so the file is much larger than the HDF5 to_hdf5 writes and this is only practical for small basis sets.
- Parameters:
path (str or pathlib.Path) – FCIDUMP file to write. Overwritten if it exists.
nelec (tuple(int, int), optional) –
(nup, ndown)for theNELEC/MS2header fields. The Hamiltonian itself does not carry an electron count, so it is supplied here. Default(0, 0).tol (float, optional) – Only write integrals above this magnitude. Default 1e-8.
ctol (float, optional) – Largest imaginary part tolerated when cplx is False. Default 1e-12.
sym (int, optional) – Write only the symmetry-inequivalent integrals of this permutational symmetry, 1, 4 or 8. Default 1, i.e. everything.
cplx (bool, optional) – Write in the complex format. Default True.
paren (bool, optional) – Write complex values parenthesized as
(real,imag)rather than in two columns. Which one a reader wants depends on the code.use_spinor (bool, optional) – Convert the spatial-orbital integrals to a spinor basis, doubling the orbital count, before writing.
- Raises:
ValueError – If the Hamiltonian is collinear, if the Cholesky matrix is in the spatial-orbital basis while
hcoreis in the spin-orbital one, if use_spinor is asked of a Hamiltonian that is already in a spin-orbital basis, or if cplx is False and the integrals have imaginary parts above ctol.- Return type:
None
- class safiretools.NOMSDWavefunction(coeffs, dets)#
Bases:
WavefunctionA non-orthogonal multi-Slater-determinant wavefunction.
- Parameters:
coeffs (array_like) – Determinant coefficients \(c_i\),
(ndets,).dets (numpy.ndarray or tuple of numpy.ndarray) –
The occupied orbitals of every determinant, as columns. The layout decides the spin symmetry, and the shape the electron counts and the number of orbitals:
closed shell: an array
(ndets, nmo, nup), shared by both spins;collinear: a tuple of arrays
(ndets, nmo, nup)and(ndets, nmo, ndown);noncollinear: an array
(ndets, 2, nmo, nelec)of spinor orbitals, spin-up components first. nelec is then(nelec, 0), as the file format records it.
- Raises:
TypeError – If dets is none of the layouts.
ValueError – If dets holds a different number of determinants than coeffs.
Examples
>>> wavefunction = NOMSDWavefunction.from_free_electron(hamiltonian, ... nelec=(8, 8)) >>> wavefunction.to_hdf5('afqmc.h5')
- property dets#
Every determinant, in the layout the constructor takes.
- determinant(idet=0)#
Determinant idet, in the layout Wavefunction.from_single_determinant takes.
- orthonormalize(tol=1e-10)#
Return a copy whose determinants have orthonormal columns. See Wavefunction.orthonormalize.
- Return type:
- class safiretools.PHMSDWavefunction(coeffs, occa, occb, nmo, nelec=None, orbitals=None, spin_symm=SpinSymm.COLLINEAR)#
Bases:
WavefunctionA particle-hole multi-Slater-determinant wavefunction.
- Parameters:
coeffs (array_like) – Determinant coefficients,
(ndets,).occa (array_like) – Occupied-orbital indices per determinant, one array per independent spin channel:
(ndets, nup)and(ndets, ndown)when collinear, and occb of zero width otherwise, since the two polarizations then share a single channel. They index0tonpol*nmo - 1: spatial orbitals, except when noncollinear, where they are spinors and already carry the beta offset. A collinear occb does not — that offset is applied on write.occb (array_like) – Occupied-orbital indices per determinant, one array per independent spin channel:
(ndets, nup)and(ndets, ndown)when collinear, and occb of zero width otherwise, since the two polarizations then share a single channel. They index0tonpol*nmo - 1: spatial orbitals, except when noncollinear, where they are spinors and already carry the beta offset. A collinear occb does not — that offset is applied on write.nmo (
int) – Number of orbitals the occupation numbers index, spatial unless noncollinear.nelec (tuple(int, int), optional) – Physical electron counts. Taken from occa and occb’s widths when omitted, and checked against them when given.
orbitals (numpy.ndarray or tuple of numpy.ndarray, optional) – The orbital reference the occupation numbers index, its orbitals as columns. One reference shared by both spins is an array
(nmo, norb), or(2, nmo, norb)of spinor orbitals when noncollinear. A spin-resolved reference, collinear only, is a tuple of two(nmo, norb)arrays. Omitted, the occupation numbers index the Hamiltonian’s own basis.spin_symm (SpinSymm or str or int, optional) – Spin symmetry.
- Raises:
TypeError – If orbitals is none of the layouts.
ValueError – If occa/occb disagree with nelec, if an orbital index falls outside the basis, or if orbitals does not fit the spin symmetry or the basis.
- property orbitals#
The orbital references, in the layout the constructor takes, or None.
- property nreferences: int#
Number of explicit orbital references, written as
PsiT_0,PsiT_1: 0 when the occupation numbers index the Hamiltonian’s basis directly.
- orthonormalize(tol=1e-10)#
Return a copy whose orbital references have orthonormal columns. See Wavefunction.orthonormalize.
- Return type:
- class safiretools.PeriodicHamiltonian(hcore, chol, kpts, qk_to_k2, minus_k, enuc=0.0, madelung_constant=0.0, basis_rotation=None)#
Bases:
HamiltonianA k-point-factorized Hamiltonian for a periodic system.
- Parameters:
hcore (numpy.ndarray) – One-body Hamiltonian,
(nkpts, nmo, nmo): every k-point has to carry the same number of orbitals.chol (dict) – Cholesky data as
{Q: L_Q}, withL_Qof shape(nkpts, nmo**2 * nchol_Q). Only momentum transfers withQ <= minus_k[Q]are stored; the rest follow by symmetry.kpts (numpy.ndarray) – k-points, shape
(nkpts, 3).qk_to_k2 (numpy.ndarray) –
qk_to_k2[Q, k1] = k2, the momentum-transfer map.minus_k (numpy.ndarray) –
minus_k[Q]is the index of \(-Q\).enuc (float, optional) – Nuclear repulsion of every cell. Default 0.0.
madelung_constant (float, optional) – Electron self-interaction per electron: the executable subtracts it times the trial wavefunction’s electron count. Default 0.0.
basis_rotation (numpy.ndarray, optional) – Transformation from the input (Bloch AO) basis to the working basis at each k-point,
(nkpts, nao, nmo); see Hamiltonian.basis_rotation. Written asHamiltonian/BasisRotationwhen given. Omitted, the integrals are taken to be in the working basis already.
- Raises:
ValueError – If any array does not match the k-point count or the orbital count.
Notes
A supercell Hamiltonian is this same class with
nkpts == 1— the Γ point of the supercell — so there is no separate representation to branch on.The format holds only spin-independent Hamiltonians, so spin_symm is always SpinSymm.CLOSED.
- property nkpts: int#
Number of k-points. 1 for a supercell (Γ-point) Hamiltonian.
- property nmo: int#
Number of orbitals at each k-point.
- property basis_rotation: ndarray#
The stored
(nkpts, nao, nmo)transformation, or the identity at every k-point when the Hamiltonian was given in its working basis.A supercell Hamiltonian’s one k-point carries the block-diagonal rotation from the Bloch AOs of every original k-point, k-major, to the combined basis.
- classmethod from_pyscf(kmf, basis=None, kpoint_symmetry=True, chol_cut=1e-05, maxvecs=20, verbose=False)#
Generate a periodic Hamiltonian from a PySCF
pbcSCF object.- Parameters:
kmf – A converged
pbc.scfobject, at one k-point or on a mesh; itsget_hcore()is the one-body Hamiltonian.basis (None or 'ortho_ao', optional) – The working basis: the solution’s own orbitals (closed shell only), or the orthogonalized AO basis. Pass the same basis to safiretools.NOMSDWavefunction.from_pbc_scf.
kpoint_symmetry (bool, optional) – Factorize per momentum transfer (True) rather than as one supercell (False). Default True. A supercell result comes back as a Γ-point Hamiltonian, i.e. with
nkpts == 1.chol_cut (float, optional) – Cholesky convergence threshold. Default 1e-5.
maxvecs (int, optional) – Cholesky-vector bound multiplier. Default 20.
verbose (bool, optional) – Log per-iteration Cholesky progress.
- Return type:
- Raises:
ValueError – If
kmf.exxdivis neither'ewald'norNone: the Cholesky vectors use the plain Coulomb kernel, not a truncated one. Also if kpoint_symmetry is set and the k-points carry different orbital counts, e.g. after linear dependencies were removed per k-point; the supercell factorization takes those.
Notes
The whole factorization is built in memory and written by to_hdf5, serially. CoQuí is the supported route for production-sized solids.
- to_hdf5(path)#
Write this Hamiltonian in the
Hamiltonian/KPFactorizedformat.- Parameters:
path (str or pathlib.Path) – HDF5 file to write into. Created if it does not exist. A Hamiltonian already in the file is replaced; everything else — notably a
Wavefunction— is left alone, so a Hamiltonian and a wavefunction can share one file in either order.- Return type:
None
- to_fcidump(path, nelec=(0, 0), tol=1e-08, ctol=1e-12, sym=1, cplx=True, paren=False, use_spinor=False)#
Write this Hamiltonian as a plain-text FCIDUMP file, over the combined basis of every k-point.
The two-electron integrals are reconstructed from the Cholesky vectors and written out in full, so the file is far larger than the HDF5 to_hdf5 writes and this is only practical for small cells and meshes.
- Parameters:
path (str or pathlib.Path) – FCIDUMP file to write. Overwritten if it exists.
nelec (tuple(int, int), optional) –
(nup, ndown)over the whole supercell, for theNELEC/MS2header fields and the Madelung correction folded into the constant energy. The Hamiltonian itself does not carry an electron count, so it is supplied here. Default(0, 0).tol (float, optional) – Only write integrals above this magnitude. Default 1e-8.
ctol (float, optional) – Largest imaginary part tolerated when cplx is False. Default 1e-12.
sym (int, optional) – Write only the symmetry-inequivalent integrals of this permutational symmetry, 1, 4 or 8. Default 1, i.e. everything.
cplx (bool, optional) – Write in the complex format. Default True, and what a k-point factorization normally needs.
paren (bool, optional) – Write complex values parenthesized as
(real,imag)rather than in two columns.use_spinor (bool, optional) – Not implemented for a k-point Hamiltonian; see below.
- Raises:
ValueError – If there is a Madelung constant but no electron count, or if cplx is False and the integrals have imaginary parts above ctol.
NotImplementedError – If use_spinor is set.
Notes
- Return type:
None
The orbital index of the FCIDUMP is the combined
k * nmo + i.
- class safiretools.PinningField(func)#
Bases:
objectA pinning field on the two edges at the ends of one lattice axis.
- Parameters:
func (
Callable) – On-site potential of each spin at the edge site with coordinate n along the edge, on edge 0 (lattice coordinate 0) or edge 1 (coordinate L-1) of the pinned axis. Applied to every band of the site.
Examples
An AFM field of strength 0.5 with the same sign pattern on both edges, written out by hand. It equals
PinningField.afm(0.5, staggered=False):>>> field = PinningField(lambda n, edge: (0.25 * (-1)**n, -0.25 * (-1)**n))
- classmethod afm(h, *, staggered)#
Antiferromagnetic field \(\pm h/2\) alternating along the edge.
If staggered, the two edges have opposite signs.
- Return type:
- classmethod fm(h, *, staggered)#
Ferromagnetic field \(\pm h/2\), constant along the edge.
If staggered, the two edges have opposite signs.
- Return type:
- classmethod charge(h, *, staggered)#
Charge field \(\pm h/2\) on both spins, constant along the edge.
If staggered, the two edges have opposite signs.
- Return type:
- class safiretools.SpinSymm(*values)#
Bases:
IntEnumSpin symmetry of a Hamiltonian, Wavefunction, or Walker ordered by increasing generality. Values match WALKER_TYPES in src/AFQMC/config.h exactly.
- classmethod from_input(value)#
Coerce user/on-disk input to a SpinSymm.
Accepts a SpinSymm, its integer value, or one of the recognized spelling aliases (
'closed'/'rhf','collinear'/'uhf','noncollinear'/'ghf', …), case-insensitively. Another enumeration whose value is one of those is unwrapped, so code carrying its own spin-symmetry enum can hand it over directly.- Raises:
ValueError – If value names no known spin symmetry.
- Return type:
- property label: str#
The lowercase name used for this spin symmetry on disk and in AFQMC input files (
'closed','collinear','noncollinear').
- property nspin: int#
2 when collinear, else 1.
- Type:
Number of independent spin channels
- property npol: int#
2 when noncollinear, else 1.
- Type:
Spin polarizations per orbital
- nelec_per_spin(nelec)#
The electron count in each independent spin channel, of length nspin:
(nup, ndown)when collinear,(nup,)when closed (the beta channel repeats it), and the total when noncollinear (both polarizations share one channel).- Return type:
tuple
- class safiretools.Wavefunction(coeffs, nelec, nmo, spin_symm)#
Bases:
ABCBase class for all SAFIRE trial wavefunctions.
- Parameters:
coeffs (array_like) – Determinant coefficients,
(ndets,). Stored ascomplex128.nelec (tuple(int, int)) – Physical electron counts
(nup, ndown).nmo (
int) – Number of spatial orbitals, even when noncollinear.spin_symm (SpinSymm or str or int) – Spin symmetry, coerced through SpinSymm.from_input.
- Raises:
ValueError – If the electron counts contradict spin_symm.
Notes
__init__takes already-formed, validated in-memory data. Build a wavefunction from an external source with one of the classmethod factories on the concrete subclasses (from_free_electron,from_pyscf,from_pbc_scf,from_dice,from_hdf5, …).- property nspin: int#
Number of independent spin channels; see SpinSymm.nspin.
- property npol: int#
Spin polarizations per orbital; see SpinSymm.npol.
- property nelec_per_spin: tuple#
Electron count in each independent spin channel; see SpinSymm.nelec_per_spin.
- property nrows: int#
Rows of an orbital matrix,
npol * nmo.
- property ndets: int#
Number of determinants in the expansion.
- abstractmethod orthonormalize(tol=1e-10)#
Return a copy whose Slater matrices have orthonormal columns.
Each block goes through safiretools.wavefunction.slater.orthonormalize, so one already orthonormal to within tol is left exactly as it is. The instance this is called on is never modified.
- Return type:
- to_hdf5(path)#
Write this wavefunction in the format the AFQMC executable reads.
- Parameters:
path (str or pathlib.Path) – HDF5 file to write into. Created if it does not exist. A wavefunction already in the file is replaced; everything else — notably a
Hamiltonian— is left alone, so a Hamiltonian and a wavefunction can share one file in either order.- Return type:
None
Notes
The header (
spin_type,ci_coeffs) is the same for every representation and is written here; the subclass adds only its own payload.No initial walker is written: the AFQMC input chooses the wavefunction a walker set starts from (
walker_set.from), and the executable derives the initial determinant from it.Nothing is repaired on the way out. Every Slater matrix that reaches disk has its overlap’s condition number checked, and an ill-conditioned one is warned about — see safiretools.wavefunction.io.warn_if_ill_conditioned.
- classmethod from_hdf5(path)#
Read a wavefunction from the HDF5 file path.
Called on Wavefunction itself, the concrete subclass is chosen from the representation stored in the file. Called on a concrete subclass, the file must hold that representation.
- Parameters:
path (str or pathlib.Path) – HDF5 file to read.
- Returns:
An instance of the concrete subclass for the stored representation.
- Return type:
- Raises:
ValueError – If the file holds no wavefunction, or holds a representation that the subclass this was called on does not read.
- classmethod from_single_determinant(det)#
Build a single-determinant trial wavefunction from its occupied orbitals. Always a safiretools.NOMSDWavefunction.
The layout of det decides the spin symmetry, and its shape the electron counts and the number of orbitals, so nothing else is needed.
- Parameters:
det (numpy.ndarray or tuple of numpy.ndarray) –
The occupied orbitals, as columns:
closed shell: an array
(nmo, nup), shared by both spins;collinear: a tuple of arrays
(nmo, nup)and(nmo, ndown);noncollinear: an array
(2, nmo, nelec)of spinor orbitals, spin-up components first.
- Returns:
A one-determinant expansion with coefficient 1. A noncollinear one reports
nelec == (nelec, 0), as the file format does.- Return type:
- Raises:
TypeError – If det is none of the three layouts — including a list, which is not read as collinear.
ValueError – If the two collinear channels span different numbers of orbitals, or this is called on a subclass other than NOMSDWavefunction.
Notes
A collinear determinant must be a tuple. An array holding both spin channels — such as PySCF’s UHF
mo_coeff[:, :, :nocc]— has the noncollinear shape(2, nmo, n)and is read as a noncollinear determinant; passtuple(...)of it instead.Examples
A closed-shell determinant occupying the lowest two of four orbitals:
>>> import numpy as np >>> wavefunction = Wavefunction.from_single_determinant(np.eye(4)[:, :2]) >>> wavefunction.spin_symm.label, wavefunction.nelec ('closed', (2, 2))
The collinear determinant with one more spin-up electron:
>>> orbitals = np.eye(4) >>> wavefunction = Wavefunction.from_single_determinant( ... (orbitals[:, :3], orbitals[:, :2])) >>> wavefunction.nelec (3, 2)
- classmethod from_free_electron(source, nelec, spin_symm=None, filling_strategy='aufbau', shell_tol=None)#
Build a free-electron trial wavefunction from a safiretools.LatticeHamiltonian. Always a safiretools.NOMSDWavefunction.
See safiretools.wavefunction.free_electron.from_free_electron for the full parameter documentation. shell_tol defaults to that module’s SHELL_TOL rather than being restated here, so the two cannot drift.
- Return type:
- classmethod from_pyscf(mf, basis=None, active_space=None)#
Build a single-determinant trial wavefunction from a molecular PySCF SCF object. Always a safiretools.NOMSDWavefunction.
See safiretools.wavefunction.pyscf.from_pyscf for the full parameter documentation.
- Return type:
- classmethod from_pyscf_cas(mc, tol=0.0001, max_det=None)#
Read a CASSCF/CASCI expansion from a PySCF
mcscfobject. Always a safiretools.PHMSDWavefunction.See safiretools.wavefunction.pyscf.from_pyscf_cas for the full parameter documentation.
- Return type:
- classmethod from_dice(path, ndets, state=0)#
Read a selected-CI expansion from Dice’s output. Always a safiretools.PHMSDWavefunction.
See safiretools.wavefunction.dice.from_dice for the full parameter documentation.
- Return type:
- classmethod from_pbc_scf(kmf, basis=None, low=0.1, high=0.95)#
Build a single-determinant trial wavefunction from a periodic PySCF SCF object. Always a safiretools.NOMSDWavefunction.
See safiretools.wavefunction.pbc.from_pbc_scf for the full parameter documentation.
- Return type:
- class safiretools.Results(filename, stage=None)#
Bases:
objectThe observables of one stage of a results.h5.
One execute block of the input writes its observables below a
Stage<N>group of its own, and a Results reads one such stage. The file is opened for each read rather than held open, so a run still writing to it is picked up on the next call.- Parameters:
filename (
str|Path) – Path to the results.h5 an AFQMC run wrote.stage (
int|str|None) – Stage to read, either by index or by group name, so0and"Stage0"both select the first one. Defaults to the last stage in the file. Pass""to read every stage at once, which puts the stage name on the front of each observable path —"Stage0/Energy"rather than"Energy".
- Raises:
ValueError – If the file was written in another format version, if it has no
Measurementsgroup, if there is noStage<N>group below it, or if the file has no stage by the requested name.
Examples
>>> results = Results("afqmc.results.h5") >>> results.observable_names() ['BackPropEstimator/Steps=40/OneRDM', 'Energy']
mean and error of one observable, dropping the first 20 bins as equilibration
>>> energy, error = results.average("Energy", skip=20)
a quantity built from several observables, whose correlations the error accounts for
>>> ratio, error = results.evaluate( ... lambda energy, rdm: energy.real / rdm[0].trace().real, ... ["Energy", "BackPropEstimator/Steps=40/OneRDM"], ... skip=20, ... )
- observable_names()#
Every observable this stage measured, or every stage’s when stage is
"".- Returns:
The ‘/’-separated path of each observable below the stage group, sorted. A back-propagated observable keeps the estimator and the back-propagation length in its path, as in
BackPropEstimator/Steps=40/OneRDM; reading every stage puts the stage on the front as well.- Return type:
list[str]
- timeseries(observable_name)#
Read the bins of one observable.
- Parameters:
observable_name (
str) – Path of the observable below the stage group, as Results.observable_names lists it.- Returns:
The bins, the leading axis running over them and the remaining axes carrying the shape of the observable. A complex observable comes back complex.
- Return type:
ndarray- Raises:
KeyError – If this stage measured no observable by that name.
- average(observable_name, skip=0, rebinsize=None)#
Mean and stochastic error of one observable.
The bins are rebinned before averaging, so that the error accounts for successive bins being correlated. Every component is averaged on its own: the components correlate with each other, but that does not enter their individual error bars, only correlation along the series does.
- Parameters:
observable_name (
str) – Path of the observable below the stage group, as Results.observable_names lists it.skip (
int) – Leading bins to drop as equilibration, default 0.rebinsize (
int|None) – Bins to average into one before taking the error. Defaults to the size optimal_rebinsize chooses for the bins left after skip.
- Return type:
tuple[ndarray,ndarray]- Returns:
mean (numpy.ndarray) – The observable averaged over its bins.
error (numpy.ndarray) – Standard error of mean, component by component. For a complex observable the real and imaginary parts of error are the errors of the real and imaginary parts of mean rather than one combined magnitude.
- Warns:
RebinningWarning – If a scalar observable drifts after skip, in which case mean is biased.
- evaluate(func, observable_names, skip=0, rebinsize=None)#
Mean and error of a quantity computed from the averages of several observables.
If func is nonlinear, naive evaluation of func(averages) has a bias and getting its error would require knowledge of the correlation matrix. This function uses the jackknife method instead to correct the bias and calculate the errorbar.
The jackknife requires that func is smooth in its arguments.
- Parameters:
func (
Callable[...,ndarray|complex]) – Called asfunc(*averages), one argument per name in observable_names and in that order, each of them that observable averaged over its bins. It may return a scalar or an array.observable_names (
Sequence[str]) – Paths of the observables below the stage group, as Results.observable_names lists them. They all have to have the same number of bins so the jackknife lines up correctly.skip (
int) – Leading bins to drop as equilibration, default 0.rebinsize (
int|None) – Bins to average into one before the jackknife, the same for every observable. Defaults to the largest of the sizes optimal_rebinsize chooses for them, so that the slowest observable is rebinned far enough.
- Return type:
tuple[ndarray|complex,ndarray|complex]- Returns:
value (numpy.ndarray or scalar) – func evaluated on the averages of the observables, with the bias of applying a nonlinear func to averages taken out. The correction is identically zero for a linear func.
error (numpy.ndarray or scalar) – Jackknife error of value. For a complex value the real and imaginary parts of error are the errors of the real and imaginary parts of value.
- Raises:
ValueError – If the observables do not all have the same number of bins, or if fewer than two bins are left to resample.
- Warns:
RebinningWarning – If a scalar observable among them drifts after skip, in which case value is biased.
- safiretools.write_jobfile(filename, parameters)#
Write the SAFIRE input file filename from parameters.
- Parameters:
filename (str or pathlib.Path) – JSON file to write. Its directory must exist.
parameters (dict) – The input parameters, in the format of the SAFIRE afqmc.json input file, except that a Hamiltonian or Wavefunction object may stand in for the
filenameof ahamiltonianorwavefunctionblock, inline or in thehamiltonians/wavefunctionslist, or for the whole block, which is then{'filename': obj}. Every such object is written to<filename without suffix>_<name>.h5next to the input file, and itsfilenamebecomes the name of that file.<name>is the"name"of the block, or elsehamiltonian<i>/wavefunction<i>, counting the unnamed objects of that kind in order of appearance. An object in several unnamed blocks is written once.
- Raises:
ValueError – If two blocks of the same name hold different Hamiltonians, or different wavefunctions.
Examples
- Return type:
None
>>> write_jobfile(run_dir / 'afqmc.json', { ... 'execute': { ... 'wavefunction': {'name': 'uhf', 'filename': uhf, 'ndets_to_read': 10}, ... 'walker_set': {'from': {'wavefunction': rohf}}, ... 'hamiltonian': ham, ... 'timestep': 0.01, ... 'steps': 10000, ... 'num_walkers': 200, ... }, ... })
writes
afqmc_uhf.h5,afqmc_wavefunction0.h5andafqmc_hamiltonian0.h5.
safiretools.vis#
Plotting helpers, used as from safiretools import vis.
This is the only module that imports matplotlib, and safiretools/__init__.py
does not import it, so import safiretools alone never loads matplotlib.
Every helper draws into the ax it is given, creating a figure only when
none is, and returns the axes. Showing or saving the figure is left to the
caller.
- safiretools.vis.plot_lattice(lattice, *, ax=None, density=None, density_label='Density', cmap='RdBu_r', vmin=None, vmax=None, norm_type='linear', nth_neighbor=1, show_direct_nearest=True, show_image_nearest=True, show_labels=True, show_lattice_vecs=True, title=None, fig_scale=2)#
Plot the sites of a lattice and the bonds to their nth-nearest neighbors.
Bonds within the home cell are drawn solid, bonds to periodic images dotted.
- Parameters:
lattice (Lattice) – A built lattice.
ax (matplotlib.axes.Axes, optional) – Axes to draw into. By default a new figure is created, sized to the lattice.
density (array_like, optional) – One value per site, used to color it. Either flat in site order or shaped
(L1, L2, nb);(L1, L2)works whennb == 1.density_label (str, optional) – Colorbar label. Default “Density”.
cmap (str or matplotlib.colors.Colormap, optional) – Colormap for density. Default ‘RdBu_r’.
vmin (float, optional) – Color scale limits. Default the extremes of density.
vmax (float, optional) – Color scale limits. Default the extremes of density.
norm_type ({'linear', 'log'}, optional) – Color scale. Default ‘linear’.
nth_neighbor (int, optional) – Which neighbor shell to draw bonds for. Default 1.
show_direct_nearest (bool, optional) – Draw the home-cell and image bonds. Default True.
show_image_nearest (bool, optional) – Draw the home-cell and image bonds. Default True.
show_labels (bool, optional) – Label every site with its index and cell coordinate. Default True.
show_lattice_vecs (bool, optional) – Draw
a1anda2, unless the lattice is one cell wide. Default True.title (str, optional) – Axes title. Default the lattice size.
fig_scale (float, optional) – Figure inches per unit length, when a figure is created. Default 2.
- Return type:
matplotlib.axes.Axes
- safiretools.vis.plot_timeseries(results, *, ax=None, obs='Energy', skip=0)#
Plot the Monte Carlo time series of a scalar observable with its average.
The real part of each bin is plotted against the projection time, with the mean and its error band over the bins after skip, and a dashed line where they start. A secondary axis on top shows the bin index. The mean and error are also printed, rounded to two significant digits of the error.
- Parameters:
results (Results) – The results of a run.
ax (matplotlib.axes.Axes, optional) – Axes to draw into. Default the current axes.
obs (str, optional) – Name of a scalar observable. Default “Energy”.
skip (int, optional) – Leading bins to drop as equilibration from the average. Default 0.
- Return type:
matplotlib.axes.Axes