Python bindings

import ferric gives you the same engine as the ferric CLI, as plain function calls that return result objects holding floats and numpy arrays. To install it, see Installation. The wheel is enough; you do not need a clone of the repository to run anything on this page.

If you already know PySCF, For PySCF users maps the calls you know onto ferric's and lists where the two behave differently.

Every snippet below uses an inline geometry. Run them in order, since later ones reuse water, o2, bs, bs_dz and aux from earlier ones. The snippets through "Properties and charges" were run when this page was written (2026-09-23), and any output shown is what they printed. The one-line calls in the reference tables were not run.

Molecules and basis sets

import ferric

water = ferric.Molecule.from_xyz_string("""3
water
O   0.000000   0.000000   0.117790
H   0.000000   0.755453  -0.471161
H   0.000000  -0.755453  -0.471161
""")
bs = ferric.BasisSet.bundled("sto-3g")

The string is standard XYZ: an atom count on the first line, a comment line, then one symbol x y z line per atom. The count must be the first line, so start the string with """3. Starting it with """ and a newline gives an empty first line, and parsing fails with bad atom count. Molecule.from_xyz(path) reads the same format from a file. A leading @ on a symbol (@H) makes a ghost atom, which carries basis functions but no nucleus or electrons.

Charge and spin belong to the molecule, not to the SCF call:

o2 = ferric.Molecule.from_xyz_string("""2
O2 triplet
O 0.0 0.0 0.0
O 0.0 0.0 1.208
""", charge=0, multiplicity=3)

multiplicity is 2S+1, so a triplet is 3. (PySCF's spin is 2S, so the same triplet there is spin=2.) Both constructors default to charge=0, multiplicity=1. run_uhf and run_rohf take no spin argument; they read it from the molecule. The geometry-changing drivers (run_frequencies, run_saddle, run_irc) also accept a multiplicity= keyword.

Units

QuantityUnit
XYZ input to from_xyz / from_xyz_stringÅngström
Molecule.coords()Ångström
Molecule.coords_bohr()Bohr (ferric stores Bohr internally)
point_charges= / smeared_charges= on run_rhf, run_uhf, run_rohf, run_dft, …Bohr, charges in e
external_field=Hartree atomic units
esp_at_points(..., points)points in Bohr; potential in atomic units
omega on run_attenuated_rimp2, run_rs_mp2_rpaÅ⁻¹ (default 0.420)
r0 on the terfc driversÅ
omega / r0 on compute_eri3_mo, compute_metric_2cBohr⁻¹ / Bohr (raw, unlike the run_* drivers)
QmmmSystem(..., coords_angstrom)Ångström
QmmmSystem.point_charges()Bohr
EnergiesHartree
GradientsHartree/Bohr
print(water.coords()[0])        # (0.0, 0.0, 0.11779)            Ångström
print(water.coords_bohr()[0])   # (0.0, 0.0, 0.22259084021251865) Bohr

The Sharp bits page has the full units table, including the QM/MM accessors.

Bundled basis sets

BasisSet.bundled(name) loads a basis compiled into the library. Names are case-insensitive. An unknown name raises ValueError listing the known ones; BasisSet.bundled_names() returns them, and bs.elements() gives the atomic numbers a set covers. These 64 sets are available:

KindNames
Poplesto-3g, 6-31g, 6-31g*, 6-31g**, 6-31+g*, 6-31+g**, 6-31++g**, 6-311g**, 6-311++g**
Dunningcc-pvdz, cc-pvtz, cc-pvqz, aug-cc-pvdz, aug-cc-pvtz, aug-cc-pvqz
Dunning with ECP (Z >= 29; lighter elements are the all-electron set)cc-pvdz-pp, cc-pvtz-pp, cc-pvqz-pp, aug-cc-pvdz-pp, aug-cc-pvtz-pp, aug-cc-pvqz-pp
Karlsruhe (ECP inline for Z >= 37)def2-svp, def2-svpd, def2-tzvp, def2-tzvpp, def2-tzvpd, def2-tzvppd, def2-qzvp, def2-qzvpp, def2-qzvppd
Jensenpcseg-0, pcseg-1, pcseg-2, aug-pcseg-1, aug-pcseg-2
Explicitly correlated (F12)cc-pvdz-f12 (orbital), cc-pvdz-f12-optri (OptRI auxiliary)
RI (MP2/RPA/CC fitting)cc-pvdz-rifit, cc-pvtz-rifit, cc-pvqz-rifit, aug-cc-pvdz-rifit, aug-cc-pvtz-rifit, aug-cc-pvqz-rifit, the six <set>-pp-rifit partners of the ECP sets, and def2-<x>-rifit for each of the nine def2 sets
JK (SCF fitting)def2-universal-jkfit, cc-pvtz-jkfit, cc-pvqz-jkfit, aug-cc-pvdz-jkfit, aug-cc-pvtz-jkfit, aug-cc-pvqz-jkfit

Aliases: the Pople stars also load as 6-31g(d), 6-31g(d,p), 6-31+g(d), and so on; every RIFIT set also loads as <orbital>-ri and ORCA's <orbital>/c (so cc-pvdz-ri is cc-pvdz-rifit); the JKFIT sets as <orbital>/jk; and def2-universal-jkfit as def2/jk or PySCF's def2-<x>-jkfit.

The aug-cc-pv{d,t,q}z-jkfit sets (Weigend, PCCP 4, 4285 (2002)) are the one exception to "from the Basis Set Exchange": BSE does not carry them. They come from Molpro's weigend_jkfit.libmol via Psi4's library (commit pinned in provenance.json), checked bit-identical to PySCF's copy. Two caveats from that source: their Ne, Ar and Kr functions are extrapolated, not published, and aug-cc-pvdz-jkfit was never published at all; it is aug-cc-pvtz-jkfit with the highest angular momentum dropped. For the S66-type noncovalent work they exist for, aug-cc-pvtz-jkfit is the set to use with aug-cc-pVTZ.

Each set covers what its source covers, and an element it lacks is an error at basis setup that names the element and the covered range (for example cc-pvtz has H-Ar and Ca-Kr, with no K; cc-pvtz-jkfit and cc-pvqz-jkfit have only H, B-F, Al-Cl and Ga-Br; the -pp-rifit sets cover H-Ar (the aug ones without Li and Na), Sc-Ni at TZ and QZ only, Y-Pd and Hf-Pt). It is never patched silently. The Pople sets follow Gaussian's d convention: the 6-31G family has Cartesian d (6D), and the 6-311G family has spherical d (5D) on every element, including Na-Ar, which the Basis Set Exchange marks Cartesian. Everything else is spherical, as the Basis Set Exchange types it. See For PySCF users for matching PySCF. crates/ferric-core/src/basis/provenance.json records the source, version and element list of every set. BasisSet.from_bse_json(path) loads any other Basis Set Exchange JSON file.

Validation: every set is checked against PySCF fed the same basis (crates/ferric-mp2/tests/basis_coverage_vs_pyscf.rs, at most 1e-8 Ha). Orbital sets are checked by an RHF energy, RI sets by an RI-MP2 correlation energy, and JK sets also by a density-fitted (RI-J + RI-K) RHF energy. For the BSE sets, PySCF fetches the basis from BSE by name, so the comparison covers both the shipped digits and ferric's parsing and normalisation. For the three aug-JKFIT sets, PySCF uses its own copy of the data. The digits are covered instead by the import's Psi4-vs-PySCF comparison, and the energy comparison covers parsing and normalisation.

Most drivers take a BasisSet object. The drivers that move atoms (run_optimize, run_frequencies, run_saddle, run_irc, run_qmmm, run_optimize_qmmm) take the basis name as a string instead, because they rebuild the basis at every geometry.

Ground state

rhf = ferric.run_rhf(water, bs)
print(rhf)
print(f"RHF: {rhf.energy:.10f} Ha, converged={rhf.converged}")
RHF Energy: -74.9631468000 Ha (converged: true, 5 iterations)
RHF: -74.9631468000 Ha, converged=True

run_rhf builds J and K from four-centre integrals. Before that SCF it converges a density-fitted one on def2-universal-jkfit and starts from its density (df_guess=None, the default; Psi4's DF_SCF_GUESS): a fitted iteration costs a few percent of an exact one, so the exact stage needs fewer, at the same energy (benzene/def2-TZVP: 6 exact builds instead of 11, 15.6 s instead of 26.5 s on 4 threads). rhf.iterations counts the exact stage only, and rhf.df_guess says whether the pre-stage ran and, if not, why. It is skipped when the call brings its own start (dm0, guess_basis, guess="hcore", MOM), with symmetry=True or a fock_hook, and when nothing is four-centre; with_gradient=True differentiates the converged exact stage, so it runs there too. df_guess=False turns it off, and df_guess=True raises where it cannot run. run_dft takes the same keyword; its default fitted J/K leaves it off. The correlated drivers that solve their own closed-shell reference (run_rimp2, run_ccsd, run_drpa, run_tddft and the others) take the same rule as scf_df_guess, named like their other reference-SCF options (scf_max_iter, scf_jk, ...): unset, a reference with exact J/K starts from the pre-stage, the route run_rhf takes by default, with_gradient=True included; False turns it off; True raises where it cannot run (an open-shell or unrestricted reference, fitted J/K).

Open shell, using the triplet o2 built above:

bs_dz = ferric.BasisSet.bundled("cc-pvdz")
uhf  = ferric.run_uhf(o2, bs_dz)
rohf = ferric.run_rohf(o2, bs_dz)
print(f"UHF  {uhf.energy:.10f}  converged={uhf.converged}")
print(f"ROHF {rohf.energy:.10f}  converged={rohf.converged}")
UHF  -149.6276689907  converged=True
ROHF -149.6079865946  converged=True

PySCF 2.12 on the same geometry and basis gives −149.6276689907 (UHF) and −149.6079865946 (ROHF). run_rohf returns a UhfResult: it has α and β densities and orbital energies, which coincide for the spatial orbitals.

Kohn–Sham DFT:

dft = ferric.run_dft(water, bs_dz, functional="b3lyp")
print(f"B3LYP {dft.total_energy:.10f}")

run_dft is closed-shell only, and its default functional is LDA. It uses density fitting by default (def2-universal-jkfit); run_rhf does not. Every functional gets RI-J; a global hybrid also gets RI-K, and a range-separated one two RI-K fitters (short- and long-range); a pure functional builds no RI-K. Pass df_j_aux="exact" for conventional four-centre Coulomb when you compare against an exact-Coulomb code. run_uks, run_roks, run_optimize and run_frequencies with xc= take the same default for RKS, UKS and ROKS alike, so a geometry run and a single point of the same input use the same J/K. The RI-J tensor is stored as f32 by default (half the memory; about 1e-7 Ha per atom of energy shift, see RI-J tensor precision); ri_j_precision="f64" restores the f64 tensor bit for bit, any other value than "f32"/"f64" raises ValueError, and dft.ri_j_precision says which was used. Drivers with more than one iterative stage (run_frequencies, run_cdft, the MP2 family, GW, TDDFT, ...) spell it scf_ri_j_precision. The geometry and frequency drivers (run_optimize, run_optimize_uhf, run_optimize_qmmm, run_frequencies, run_saddle, run_irc) default to the f64 tensor instead, because the f32 energy surface jitters between nearby geometries; scf_ri_j_precision="f32" there is still honoured, and the certificate's ri-j entry says which was requested and why. The RI-K tensor (hybrids, HF with df_k_aux) is a second three-index tensor beside RI-J's. df_j_aux and df_k_aux are independent, so each tensor is sized by its own auxiliary basis: RI-K's has naux_K * nbf * (nbf + 1) / 2 elements (naux_K * nbf**2 in a [gpu] mode that may build K on the device), RI-J's at most naux_J * nbf * (nbf + 1) / 2 (Schwarz pair screening can drop AO pairs). BasisSet.n_functions(mol) gives nbf and each naux. For a global hybrid, df_k_aux="" selects exact four-centre K and builds no RI-K tensor. While RI-K is active k_builder is ignored with a warning: k_builder="direct" needs df_k_aux="", and "link" needs df_j_aux="" as well, since RI-J replaces the four-centre pass LinK builds J and K in. The RI-K tensor is held as its packed symmetric half; ri_k_precision="f32" (opt-in; scf_ri_k_precision on run_cdft and run_frequencies) stores it in f32 for another factor of two, at a cost described in RI-K tensor storage; dft.ri_k_precision says which was used. dispersion="d3bj" adds Grimme D3(BJ); the result then carries e_scf, e_dispersion and their sum in total_energy. with_gradient=True also returns the analytic nuclear gradient from dft.gradient(). run_dft refuses a molecule with multiplicity > 1; the open-shell entry points are run_uks(mol, bs, "pbe") (unrestricted) and run_roks(mol, bs, "pbe") (restricted open-shell). Both take the functional as a required argument, return the UhfResult of run_uhf (α and β densities, orbital energies, MOs and occupations, certificate) and accept with_gradient=True for the analytic gradient. Their SCF settings are run_dft's (RI-J/RI-K through def2-universal-jkfit, the production grid, dm0=(D_a, D_b)); dispersion, COSX, symmetry and fock_hook are not offered. Energy and certificate equal the CLI (kind = "ksdft" on an open-shell molecule, kind = "rohf" with [dft] functional) bit for bit. Unrestricted Kohn–Sham is also reachable inside other drivers: run_frequencies(reference="uhf", xc=...), run_u_gw(xc=...), run_qmmm(method="uks") and run_cdft(functional=...).

run_rhf also takes implicit solvent (solvent=78.4 or solvent="water", IEF-PCM), point charges and a uniform field. run_optimize and run_optimize_uhf take the same solvent and pcm_lebedev_order and follow the analytic IEF-PCM gradient; there is no Python COSMO option, and COSMO has no gradient. See its docstring (help(ferric.run_rhf)) for the full SCF knob set, which matches the CLI [scf] section.

Naming the convergence keywords

A bare max_iter, energy_conv or density_conv belongs to a driver whose method is the SCF itself (run_rhf, run_uhf, run_rohf, run_dft, run_ksdft, run_qmmm). Every other driver solves a reference SCF as one stage among others (MP2, CC, RPA, GW, TDDFT, orbital optimization, constrained DFT, frequencies, geometry optimizers, saddle and IRC searches), so its SCF knobs are scf_max_iter, scf_energy_conv and scf_density_conv, with the meaning and defaults of run_rhf's. Another stage's iteration knob is stage-named (oo_max_iter, max_outer, max_steps, eigensolver_*). The bare spellings that older releases accepted on run_cdft, run_frequencies and run_oo_rimp2 (max_iter there) still work, warn with a DeprecationWarning, and raise if combined with the prefixed one. The CLI keeps each key in its own section ([scf], [optimize], [gw], [rpa], [mp2] oo_*).

Check .converged, and know what it means

run_rhf, run_uhf, run_rohf and run_qmmm return a result whether or not the SCF converged. A non-converged result has converged = False, and its energy is a plausible, wrong number. run_dft, run_ksdft and the correlated drivers (MP2, CC, RPA, GW, TDDFT) behave differently: they raise if their reference SCF does not converge.

converged = True means the SCF reached a stationary point. It does not mean the lowest one. The O2 triplet above with sto-3g instead of cc-pvdz shows this. run_uhf with the default MINAO guess converges to −147.63397 Ha, which is a saddle of the orbital Hessian 1.33 mHa above the UHF minimum at −147.635296 Ha (PySCF's default guess lands on the same saddle). Without stability_descent nothing in the result flags it. run_uhf(o2, bs, stability_descent=True) (CLI: [scf] stability_descent = true on kind = "uhf") follows the downhill eigenvector and reaches the minimum. guess="hcore" converges (converged=True) to a much higher stationary point, −147.3789 Ha, which lies above ferric's own ROHF (−147.63219 Ha). A UHF energy above the ROHF energy for the same molecule cannot be a ground state, so comparing the two is a cheap check for open-shell work.

Correlation

Correlated drivers run their own reference SCF internally, so they take the molecule and basis rather than an SCF result. They also take an explicit auxiliary (RI) basis. There is no automatic choice.

aux = ferric.BasisSet.bundled("cc-pvdz-ri")

rhf = ferric.run_rhf(water, bs_dz)
mp2 = ferric.run_rimp2(water, bs_dz, aux)
cc  = ferric.run_ccsd_t(water, bs_dz, aux)

print(f"RHF      {rhf.energy:.10f}")
print(f"RI-MP2   {mp2.total_energy:.10f}  (corr {mp2.mp2_corr:.10f})")
print(f"CCSD(T)  {rhf.energy + cc.correlation_energy + cc.t_correction:.10f}  total")
print(f"         {cc.correlation_energy:.10f}  CCSD correlation")
print(f"         {cc.t_correction:.10f}  (T)")
closed-shell CCSD converged in 10 iterations. E_corr = -0.2135061893
RHF      -76.0267679974
RI-MP2   -76.2308014541  (corr -0.2040334567)
CCSD(T)  -76.2433412449  total
         -0.2135061893  CCSD correlation
         -0.0030670582  (T)

The first line is progress output that the CCSD solver prints to stdout.

CcResult holds only correlation_energy and t_correction (which is None for run_ccd and run_ccsd). It carries no reference energy, so the total above adds run_rhf(...).energy by hand. The MP2-family results all carry a total_energy, and most also carry the reference energy.

Other members of the family use the same call shape:

att   = ferric.run_attenuated_rimp2(water, bs_dz, aux, omega=0.420)  # Å⁻¹
scs   = ferric.run_scs_mp2(water, bs_dz, aux)
sos   = ferric.run_laplace_sos_mp2(water, bs_dz, aux)
oo    = ferric.run_oo_rimp2(water, bs_dz, aux)
mp3   = ferric.run_mp3(water, bs_dz, aux)

frozen_core= is accepted by every correlated driver. run_terfc_rimp2 has no CLI method.kind of its own (the CLI reaches it through att-rimp2 with att_operator = "terfc"); the reference table below marks the CLI kind of every driver. run_rimp2, run_drpa and run_linlccd compute their method exactly unless local="amplitude-threshold" and eps= are passed (see Exact and local correlation).

Response and excited states

rpa   = ferric.run_pdep_rpa(water, bs_dz, aux)            # RPA correlation
gw    = ferric.run_gw(water, bs_dz, aux)                  # G0W0@HF by default
tddft = ferric.run_tddft(water, bs_dz, aux, n_roots=3, method="tda")

print(rpa.total_energy, rpa.eigensolver_converged)
print(gw.mo_indices, gw.eps_qp)          # quasiparticle energies, Hartree
print(tddft.excitation_energies)         # Hartree

run_gw runs method="g0w0" on an HF reference unless you pass xc= (for example xc="pbe"); by default it corrects HOMO−2 through LUMO+2. Check gw.outer_converged and gw.qp_converged before using the numbers. run_u_gw is the open-shell version.

run_tddft runs on an RHF/RKS reference for a closed-shell molecule and on a UHF/UKS reference for an open-shell one (reference="auto", the default; "restricted" or "unrestricted" force it). An unrestricted run returns spin-conserving roots with result.spin = None, result.s2 (<S^2> per root) and result.s2_reference; spin="triplet" there is a ValueError. solver="dense" builds the full A and B matrices, "davidson" is matrix-free (an unconverged root raises), and "auto" (default) is dense up to nocc * nvir = 200 and Davidson above; result.solver and result.residuals report what ran. With functional=... it includes the (ia|f_xc|jb) exchange-correlation kernel; VV10 functionals are refused because their kernel is not built. A τ-only meta-GGA (SCAN, r2SCAN, TPSS, and hybrids such as TPSSh and M06-2X) defaults to a 150 × 434 grid; result.grid reports the grid the reference SCF and the kernel shared, and result.certificate lists it as response-grid. With no functional, it is CIS (method="tda") or TDHF (method="casida"). Both methods match PySCF TDA/TDDFT to 1e-3 eV on the systems listed in Capabilities and validation.

Properties and charges

The property functions take the molecule, the basis and a converged RhfResult or DftResult. They work on closed-shell results.

import numpy as np

rhf = ferric.run_rhf(water, bs)                      # water / STO-3G

q_lowdin = ferric.lowdin_charges(water, bs, rhf)
q_resp   = ferric.resp_charges(water, bs, rhf)
print(np.round(q_lowdin, 4), np.round(q_resp, 4))

# ESP 3 Bohr above each atom. Points are an (N, 3) array in Bohr.
pts = np.array(water.coords_bohr()) + np.array([0.0, 0.0, 3.0])
print(np.round(ferric.esp_at_points(water, bs, rhf, pts), 6))
[-0.2525  0.1263  0.1263] [-0.6176  0.3088  0.3088]
[-0.064684 -0.067154 -0.067154]

The charge family is mulliken_charges, lowdin_charges, hirshfeld_charges, chelpg_charges and resp_charges, all returning one charge per atom in units of e. hirshfeld_charges builds its proatoms from free-atom SCF densities in the molecule's basis, as the CLI does; proatom="slater" selects the single-exponential Slater proatom instead, which is 0.23–0.72 e away on H2O, CO and CH3OH. resp_charges is a single-stage restrained fit, not the multi-stage, multi-conformer RESP procedure. esp_at_atoms gives the potential at each nucleus. hirshfeld_polarizability returns per-atom 3×3 polarizability tensors (Bohr³) and needs an RI basis.

PDEP-RPA properties and the NPZ bundle

run_pdep_rpa(..., properties=True) also computes the property bundle that the CLI writes under [rpa], with the TOML key names and defaults: every compute_* switch is on except compute_esp_surface, c6_source is "ts" and an unset c6_partition is the source's default (Hirshfeld for "pdep", Becke for "ts" and "mbd"). export_npz="bundle.npz" writes the CLI's NPZ and implies properties=True; export_eigpot_prefix="p" writes the leading export_eigpot_count eigenpotential densities as p_eigpot_NNN.cube (cube_spacing, cube_margin, in Bohr).

r = ferric.run_pdep_rpa(
    water, bs, aux,                       # closed shell only
    properties=True,
    c6_source="pdep",                     # "ts" (default), "pdep" or "mbd"
    c6_partition="becke",                 # unset: the source's default
    df_j_aux="def2-universal-jkfit",      # the CLI's reference SCF is RI-JK
    df_k_aux="def2-universal-jkfit",
)
r.alpha_tensor          # (3, 3) molecular static polarizability
r.alpha_atomic          # (N, 3, 3) per-atom intrinsic Becke polarizability
r.alpha_ct              # (3, 3) charge-transfer remainder
r.alpha_atomic_dynamic  # (N, nfreq, 3, 3), with c6_freqs and c6_weights
r.c6_molecular_iso      # molecular C6, a.u.

The arrays carry their NPZ names: esp_atoms, electric_field, dipole, lowdin_charges, hirshfeld_charges, mulliken_charges, chelpg_charges, resp_charges, alpha_tensor, alpha_atomic, alpha_ct, alpha_atomic_dynamic, alpha_ct_dynamic (c6_source="pdep" only), c6_iso, c6_aniso, c6_freqs, c6_weights, c6_molecular_iso, c6_partition, c6_source, esp_surface and esp_points, plus density_matrix, mo_coeffs, orbital_energies, orbital_centers, orbital_spreads and density_second_moment. An array that was not requested is None. alpha_atomic is the charge-transfer-free intrinsic polarizability, so alpha_atomic.sum(0) differs from alpha_tensor by alpha_ct; c6_iso and c6_aniso are per-atom-pair tensors that depend on the partition, and the partition-independent molecular value is c6_molecular_iso.

For the same settings the arrays are bitwise the CLI's NPZ arrays, because both call one library function. "Same settings" includes the reference SCF: the CLI's pdep-rpa reference uses RI-JK on def2-universal-jkfit and a DF-guess pre-stage, while run_pdep_rpa uses exact J/K and no pre-stage unless df_j_aux= / df_k_aux= are passed, so a default Python run and a default CLI run differ at the SCF convergence level (about 5e-14 with tight thresholds).

A property that fails is None, listed in r.property_gaps, and raised as a RuntimeWarning (the same text the CLI prints, e.g. a skipped TS C6). With export_npz= the file is written first, then the call raises RuntimeError unless allow_partial_npz=True, the Python form of the CLI's nonzero exit. An unknown c6_source or c6_partition raises ValueError before the SCF, and so does a compute_* or c6_* key passed without properties=True or export_npz=.

Orbitals, density and cube files

eval_ao_on_points, eval_density_on_points and eval_mo_on_points evaluate basis functions, the total electron density and restricted MOs at an (N, 3) array of points. Points and cube grids are in Bohr, like esp_at_points. eval_ao_on_points returns an (N, nbasis) array (PySCF eval_gto layout); eval_mo_on_points takes 0-based mo_indices into mo_coefficients and returns (N, len(mo_indices)). Orbital signs are the SCF's arbitrary phase. write_cube writes the density (e/Bohr³) or one MO (what="mo", mo_index=) on an axis-aligned grid, from the atoms' bounding box plus padding unless origin and shape are given, and returns the (origin, shape) used.

import numpy as np

rhf = ferric.run_rhf(water, bs)
pts = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]])    # Bohr
print(np.round(ferric.eval_density_on_points(water, bs, rhf, pts), 4))

origin, shape = ferric.write_cube("homo.cube", water, bs, rhf,
                                  what="mo", mo_index=4, spacing=0.3)
print(shape)
[10.2392  0.8103]
[28, 38, 32]

ferric.molden.write(path, mol, bs, result) writes the orbitals of an RHF, KS, UHF or ROHF result as a Molden file for Avogadro, Jmol, Multiwfn and other viewers; see Export.

For NPZ export of ML-ready features (MO coefficients, PDEP eigenvectors, ESP, charges, polarizabilities, C6 coefficients) in one run, use the CLI's [rpa] export_npz section; see Input file (TOML).

What comes back

Results are Python objects with plain attributes for scalars and methods for arrays:

D = rhf.density()             # numpy.ndarray, (n_bf, n_bf), AO basis
e = rhf.orbital_energies()    # numpy.ndarray, ascending, Hartree
C = rhf.mo_coefficients()     # numpy.ndarray, (n_bf, n_mo)

Matrices and tensors come back as numpy.ndarray. Per-atom lists (charges, ESP values) come back as Python lists; wrap them in np.asarray if you need arrays. run_drpa, run_linlccd and tune_omega return plain dicts, and run_drpa_scan returns a list of them.

Most results carry a .certificate: the grade of the method, the build, the approximations in effect and warnings. It holds a measured error only for a run inside the settings the validation test ran; see Certificates.

AO-basis matrices follow libint2's basis-function conventions, which are not PySCF's. Measured on CO/cc-pVDZ: total and orbital energies agree with PySCF to 3e-12 and 8e-9 Ha, and the two AO density matrices differ element by element by up to 1.5. Compare invariant quantities, not raw AO matrices.

Building blocks

ferric.AoIntegrals(mol, basis_set) exposes the integrals and J/K builds the drivers use, as numpy arrays, so a method can be written in numpy the way it is on top of PySCF's get_hcore / get_jk / ao2mo. Bohr and Hartree throughout; AOs are in ferric's shell order (shell_offsets()).

BlockReturns
overlap(), kinetic(), nuclear(), ecp(), hcore(), dipole(origin)(nao, nao); hcore() includes the ECP; dipole is (3, nao, nao)
jk(D)(J, K) of the TOTAL density, direct and Schwarz-screened: the RHF Fock matrix is hcore() + J - 0.5 * K
jk(D, hermi=0), jk(Ds)J/K of a non-symmetric D (hermi=0: J of (D + Dᵀ)/2, K general, e.g. a transition density C_v X C_oᵀ; hermi=2: antisymmetric D, J = 0); a (k, nao, nao) stack takes one integral pass. Default hermi=1 refuses an asymmetric D. DfJk.jk takes the same
df_jk(aux)a DfJk holding the RI-J/RI-K fit, reused for every .jk(D)
eri()dense (μν|λσ), chemists' order, refused above max_gb (default 2 GiB)
eri3(aux), eri2(aux)raw (P|μν) as (naux, nao, nao) and the metric (P|Q)
df_mo(aux, C1, C2)fitted B^P_pq, (naux, k1, k2), with (pq|rs) ≈ Σ_P B^P_pq B^P_rs (the RI-MP2 fit)
ao2mo(C1, C2, C3, C4)exact (pq|rs), integral-direct, never holding the nao⁴ AO tensor
grad_*, hess_*, cphf, xc_functionalnuclear-derivative, response and XC pieces
ferric.einsum(spec, a, b, ..., scale=1.0, out=None, beta=0.0)the contraction engine of ferric's correlation codes (grammar); out/beta write scale * result + beta * out into your buffer inside the GEMM

Every two-electron method takes operator="coulomb" | "erf" | "erfc" with omega in Bohr⁻¹. Orbitals come from the result objects (mo_coefficients(), orbital_energies(), density()) or from a numpy SCF on the blocks.

ints = ferric.AoIntegrals(water, bs)
J, K = ints.jk(D)
F = ints.hcore() + J - 0.5 * K
E = 0.5 * np.sum(D * (ints.hcore() + F)) + ints.nuclear_repulsion()
print(abs(E - rhf.energy) < 1e-8)
B = ints.df_mo(aux, C[:, :5], C[:, 5:])    # (naux, nocc, nvir)
print(B.shape)
True
(84, 5, 2)

Three methods written this way are in examples/python/ and are tested against the Rust drivers: rhf_from_blocks.py (DIIS RHF from hcore() and jk(), equal to run_rhf and PySCF to 1e-8 Ha), rimp2_from_blocks.py (RI-MP2 from df_mo, equal to run_rimp2 and PySCF DFMP2 to 1e-8 Ha) and cis_from_blocks.py (singlet CIS from df_mo or ao2mo, equal to run_tddft(method="tda") and PySCF TDA).

Spin-free X2C core Hamiltonian

ints.hcore_x2c(c=None) is the spin-free X2C-1e core Hamiltonian, the matrix that replaces T + V. It is built in the uncontracted basis (one shell per unique exponent and angular momentum) and contracted back, with the settings of PySCF scf.RHF(mol).sfx2c1e() (approx='1e', xuncontract=True); c defaults to PySCF's 137.03599967994. Only the core Hamiltonian is transformed: the two-electron interaction and property operators stay nonrelativistic. A basis with an ECP atom raises ValueError, since the ECP already carries the core's scalar relativity.

A scalar-relativistic SCF is relativistic="x2c1e" on run_rhf, run_uhf, run_rohf, run_dft/run_ksdft, run_uks and run_roks: the driver uses this matrix as its core Hamiltonian, records x2c1e among the certificate's approximations and grades the run Ungraded. It is for energies only: with_gradient=True, and scf_relativistic= on run_optimize and run_frequencies, raise ValueError, and post-SCF methods that rebuild the nonrelativistic core Hamiltonian (orbital-optimized MP2) refuse an X2C reference. run_rimp2, run_scs_mp2, run_ccsd and run_ccsd_t take the same relativistic="x2c1e": their reference SCF uses the X2C core Hamiltonian and the correlation energy is evaluated on its orbitals (the kinds the CLI's [scf] relativistic runs). The same SCF runs from the block through a constant Fock hook, which must return Tr[D dH] as its energy (not half of it):

neon = ferric.Molecule.from_xyz_string("1\n\nNe 0 0 0\n")
dz = ferric.BasisSet.bundled("cc-pvdz")
ints_ne = ferric.AoIntegrals(neon, dz)
dh = ints_ne.hcore_x2c() - ints_ne.hcore()
nr = ferric.run_rhf(neon, dz)
rel = ferric.run_rhf(neon, dz, fock_hook=lambda d: (float(np.sum(d * dh)), dh))
drv = ferric.run_rhf(neon, dz, relativistic="x2c1e")
print(f"{rel.energy - nr.energy:.5f} {drv.energy - nr.energy:.5f}")
-0.12694 -0.12694

PySCF gives −0.1269416 Ha for the same shift. Validation is in the Python entry points table.

Fock hooks and starting densities

fock_hook=hook on run_rhf and run_dft adds one density-dependent term: hook(D) receives the total density every iteration and returns (E, V). run_uhf and run_rohf take hook(D_a, D_b) -> (E, V_a, V_b).

RuleDetail
Symmetry of Vmax |V - Vᵀ| at most 4 n ε ‖V‖_F (n = nao), the round-off of a product chain of up to four GEMMs; the driver uses ½ (V + Vᵀ). A larger asymmetry raises ValueError.
run_dft ladderEvery convergence-ladder rung runs with the hook. Rungs that switch on SOSCF run without it, keeping their level shift, ADIIS and smearing: the SOSCF orbital Hessian does not include the hook.
Energy noise floorRound-off in the hook term adds ε Σ|D_ij V_ij| to the noise floor of dE (summed over spins for an open-shell hook), with D and V from the hook's last call. A user-set energy_conv below the floor including this term emits a RuntimeWarning after the SCF; the warning before the SCF cannot include it. MEASURED 2026-11-11, HF-in-PBE projection embedding of water/cc-pVDZ (O as subsystem A, run_rhf, exact J/K, three starting guesses): the RMS of dE over iterations 31 to 60 is 1.8e-11 to 2.2e-11 Ha at μ = 1e5, 1.6e-10 to 2.1e-10 at μ = 1e6 and 1.3e-9 to 2.3e-9 at μ = 1e7, against a term of 8.7e-11, 8.7e-10 and 8.7e-9 Ha. The final |ΔE| after 200 iterations is 4.6e-10 Ha at μ = 1e7 and 4.1e-9 Ha at μ = 1e8, so energy_conv=1e-11 does not converge there.

dm0=D on run_rhf and run_dft starts the SCF from a total closed-shell AO density (nao, nao), such as a previous run's density(); the first Fock matrix is built from it. D must be finite, symmetric within the bound above and hold the system's electron count, |tr(D S) − N| ≤ n² ε Σ|D_ij S_ij|, the round-off of the trace. A density of another charge state raises ValueError. A converged density of an identical run restarts in at most two iterations. dm0 with guess= or guess_basis= raises ValueError.

dm0=(D_a, D_b) on run_uhf and run_rohf starts from per-spin AO densities, such as a previous run's (density_alpha(), density_beta()). Each D_s passes the checks above with the spin's electron count N_s. The start is the natural orbitals of each density (for ROHF, the doubly occupied orbitals from D_b and the singly occupied ones from D_a in the rest of the space), so a converged open-shell pair is reproduced on the first iteration and restarts in at most two. A closed-shell density D is passed as (D / 2, D / 2) and gives run_rhf(dm0=D)'s energy. A closed shell has its β HOMO and LUMO turned by 0.1 rad, as from any UHF start.

Gradients of a hooked SCF

with_gradient=True with a fock_hook needs fock_hook_grad=grad, the hook's explicit nuclear derivative: grad(D, mol) (run_rhf, run_dft) or grad(D_a, D_b, mol) (run_uhf, run_rohf) returns ∂E_hook/∂R at fixed AO density, shape (natoms, 3) in Hartree/Bohr, for the converged densities and the Molecule being differentiated. result.gradient() is the analytic gradient of the hooked SCF plus this term. Without fock_hook_grad the gradient raises ValueError.

What grad must and must not contain:

TermIn grad?Why
Integrals over AOs centred on atoms, operator centres on atoms, classical terms of E_hookYesOnly the hook knows how E_hook depends on the atom positions at fixed D.
The Pulay term of V, −Tr[W_V ∂S/∂R]NoThe energy-weighted density comes from the hooked orbitals and eigenvalues (for ROHF, the hooked spin Fock matrices), so it is already included.
The change of D with geometryNoThe SCF is stationary in the orbitals; the Lagrangian handles it.

A hook that depends on D only (for example E = λ Σ D_ij²) has grad = 0. A hook built from a geometry-dependent AO matrix has a nonzero one: for V = λ h, E = λ Tr[D h], grad is λ Tr[D ∂h/∂R]:

ints = ferric.AoIntegrals(water, bs)
lam, h = 0.1, ints.hcore()
r = ferric.run_rhf(
    water, bs, with_gradient=True,
    fock_hook=lambda d: (lam * float(np.sum(d * h)), lam * h),
    fock_hook_grad=lambda d, mol: lam * ints.grad_hcore(d),
)

E = λ Tr[D S] is the check that both halves are right: its explicit term λ Tr[D ∂S/∂R] and its Pulay term −λ Tr[D ∂S/∂R] cancel, as they must for the constant λN, so the hooked gradient equals the plain one. run_optimize(method="scf", fock_hook=, fock_hook_grad=) optimizes the hooked surface; because the geometry moves, both callables there receive the step's Molecule as their last argument (hook(D, mol), grad(D, mol)), and each step's SCF starts from the default guess. The derivation is in book/src/07-hartree-fock/06-fock-hooks.md#fock-hooks-equations; the checks (finite differences of the hooked energy for RHF, UHF, ROHF and LDA, and a point charge entered as a hook against point_charges) are in crates/ferric-python/tests/test_fock_hook_gradient.py and crates/ferric-scf/tests/fock_hook_gradient.rs.

Not exposed: the Rust-side structs (PreparedBasis, Engine, screening bounds), method intermediates (CC amplitudes, GW self-energies, PDEP eigenpairs) and periodic (PBC) integrals. Those stay behind the drivers.

Trajectory, finite-difference and PDB helpers

Three pure-Python modules, none imported by import ferric:

  • ferric.correlation: velocity_autocorrelation, mean_squared_displacement, diffusion_coefficient (Green-Kubo, from velocities) and diffusion_from_msd (Einstein, from unwrapped positions) on (n_frames, n_atoms, 3) arrays such as MdResult.velocities and MdResult.positions_angstrom. No units are converted: those inputs give a diffusion coefficient in Ų/fs.
  • ferric.finite_difference: finite_difference_gradient(energy, coords, h) is the central difference of a callable over an (N, 3) array, and gradient_check(analytic, numerical, atol) returns the largest difference and raises AssertionError above atol. Pass Molecule.coords_bohr() to compare with ferric's gradients, which are in Hartree/Bohr.
  • ferric.pdb: to_pdb(mol) / write_pdb(path, mol) write one HETATM record per atom (Å, no connectivity; ghost atoms are left out). Atom names are the element plus a per-element counter (H1, H2).

Memory, threads and MPI

Most drivers accept memory_budget_gb (GiB). It sets the same per-allocation limits as the CLI's [memory] budget_gb: an allocation that does not fit is spilled to disk, recomputed on demand (the DFT grid AO cache) or refused with an error naming it (for example run_rimp2 and run_ccsd). Unlike the CLI, Python installs no shared ledger, so each check compares its own allocation with the whole budget rather than with what other live allocations have left. Two checks instead subtract the process's current resident memory (RSS) first and allow 90% of the remainder: the KS-DFT decision to store or recompute the grid AO cache, and the UKS Newton/TRAH fxc kernel's second grid cache. Because RSS includes everything already resident, those two see less than the full budget. It does not cap total process memory; see Sharp bits.

mp2 = ferric.run_rimp2(water, bs_dz, aux, memory_budget_gb=8.0)

import ferric runs OpenBLAS at one thread inside ferric's parallel regions unless OPENBLAS_NUM_THREADS is already set; ferric parallelizes with rayon (RAYON_NUM_THREADS). Serial sections such as the per-iteration Fock diagonalization use ferric.blas_threads() OpenBLAS threads, by default the rayon thread count; ferric.set_blas_threads(1) makes results bit-identical across thread counts. The OpenBLAS thread count is process-wide, so when you run several jobs at once from Python threads, call ferric.set_blas_threads(1) first: otherwise one job's serial section raises the count under the other jobs' parallel regions, which oversubscribes the machine and makes their results vary at the last bit from run to run. run_rhf, run_uhf, run_rohf, run_dft, run_rimp2, run_ccsd, run_ccsd_t, run_gw and run_tddft release the GIL, so independent jobs submitted from a ThreadPoolExecutor run in parallel. The other drivers hold it. For throughput across many molecules, prefer many single-threaded processes.

A Python script runs under mpirun only when it is written for it: without ferric.parallel every rank runs the whole script and prints and writes it N times. Whole calculations go through the CLI built with MPI (see Installation); scripts built from the blocks use ferric.parallel.

Full reference

The module registers 61 public functions and 39 classes. That count excludes _cli_main, the entry point behind the ferric console command. It also exports two constants: DEFAULT_TEMPERATURE_K (298.15) and BOLTZMANN_HARTREE_PER_K. The list below was taken from the registration block of #[pymodule] fn ferric in crates/ferric-python/src/lib.rs, and each purpose line is condensed from that item's doc comment, or from its code where it has none. help(ferric.<name>) shows the full docstring and signature. The installed package also carries its type stubs (ferric/ferric.pyi beside a py.typed marker), so editors and type checkers see every signature.

"CLI" gives the matching method.kind, task or TOML section, or "—" when the capability is Python-only. How well each one is validated is on Capabilities and validation.

Molecules and basis sets

NamePurposeCLI
MoleculeGeometry, charge and multiplicity. from_xyz, from_xyz_string, from_arrays (symbols or atomic numbers, coordinates in units="angstrom" or "bohr", optional ghost= flags), coords, coords_bohr, symbols, atomic_numbers, is_ghost, natoms, nelec, nuclear_repulsion, to_xyz_string.[molecule]
BasisSetA Gaussian basis set, orbital or auxiliary. BasisSet.bundled(name).[basis]

SCF and DFT

NamePurposeCLI
run_rhfClosed-shell RHF with the full SCF knob set, point charges, field and IEF-PCM solvent; with_gradient=True adds the analytic gradient (an unset ri_j_precision is then "f64").rhf
run_uhfUnrestricted HF; α/β counts come from the molecule's charge and multiplicity. with_gradient=True as for run_rhf.uhf
run_rohfRestricted open-shell HF (Guest–Saunders coupling); returns a UhfResult. with_gradient=True as for run_rhf.rohf
run_dftClosed-shell Kohn–Sham DFT (LDA/GGA/hybrid/RSH/meta-GGA, pure or hybrid, by name), optional dispersion (dispersion="d3bj" or "mbd", added to the energy and, with with_gradient=True, to the gradient) and analytic gradient.ksdft
run_ksdftAlias of run_dft.ksdft
run_uksUnrestricted Kohn–Sham for an open-shell molecule (functional required); returns a UhfResult; with_gradient=True gives the analytic UKS gradient.ksdft (multiplicity > 1)
run_roksRestricted open-shell Kohn–Sham (functional required); returns a UhfResult; with_gradient=True gives the analytic ROKS gradient.rohf + [dft] functional
d3bj_energyGrimme D3(BJ) dispersion energy for a molecule and functional, in Hartree; s9=1.0 adds the ATM three-body term (default 0, off).[dft] dispersion
mbd_rsscs_energyMBD@rsSCS dispersion energy (Hartree) from per-atom Hirshfeld volume ratios and β (or a functional with a published β); returns MbdRsscsResult with the screened α₀, C6, R_vdW and ω.—
tune_omegaIP-based (Baer/Kronik) tuning of an RSH functional's ω (Bohr⁻¹); closed-shell neutral plus doublet cation. continuation=True seeds each evaluation from the nearest already-evaluated ω, which keeps the cation on one branch across an out-of-order golden-section search; branch_tol flags an evaluation whose cation spin-population asymmetry jumps. check_cation_stability (default True) runs the UKS internal-stability analysis on every cation: each eval dict carries cation_lambda_min and cation_stability, and a tuned ω whose cation is an internal saddle raises RuntimeError naming ω and λ_min. Functionals without an orbital-Hessian kernel (VV10 such as ωB97X-V, meta-GGA) are reported not_analysed with a stability_warning, never as stable.—
dft_grid_point_countNumber of points in the main KS grid run_dft would build for the molecule with the same grid_* kwargs, without running an SCF (shows what pruning saves).—
SymmetricRhfResultResult of run_rhf(symmetry=True) (point-group-blocked RHF): energy (of the symmetrized geometry), point_group, orbital_irreps, max_symmetrization_shift, irrep_occupations(), orbital_energies(), symmetrized_coords(), frame_transform(). density(), mo_coefficients() and gradient() raise: the AO matrices live in the rotated frame.
RhfResultResult of run_rhf: energy, converged, iterations, density(), orbital_energies(), mo_coefficients(), gradient() (None unless with_gradient=True), one_step_energy_drop and stationarity_tol (the converged exit is stationary when the drop is above -stationarity_tol; both None for a non-aufbau or unconverged exit).
UhfResultResult of run_uhf/run_rohf/run_uks/run_roks: α and β densities and orbital energies, gradient(), one_step_energy_drop, stationarity_tol.
DftResultResult of run_dft: total_energy (= e_scf + e_dispersion), e_scf, e_dispersion (None when not requested), dispersion_model ("D3(BJ)", "MBD@rsSCS" or None), volume_ratios (MBD@rsSCS only), converged, exit_reason(), one_step_energy_drop, stationarity_tol, density(), gradient().

Constrained DFT

NamePurposeCLI
run_cdftConstrained UHF, or UKS when functional names a libxc functional other than "HF" (None and "HF", any case, give UHF): minimize the energy subject to fragment population constraints (Wu–Van Voorhis nested λ loop). Raises if the λ loop does not converge.—
CdftConstraintOne fragment constraint: atoms (0-based), target (a Becke electron population, not a net charge), kind = "charge" (Nα + Nβ) or "spin" (Nα − Nβ).—
cdft_couplingWu–Van Voorhis coupling H_ab between two converged single-"charge"-constraint states solved with the same geometry, basis, occupations and Hamiltonian.—
CdftResultenergy (without the constraint term), converged, scf_converged, lambdas, populations, targets, density_alpha(), density_beta(), weight_matrix(i).
CdftCouplingResulth_ab (sign is a phase convention), s_ab, e_a, e_b.

See Constrained DFT for a worked example.

Geometry, vibrations and reaction paths

NamePurposeCLI
run_optimizeGeometry optimization (basis by name). method="scf" (default): RHF/UHF/ROHF, RKS/UKS/ROKS with xc= (reference=, unset: by multiplicity), dispersion= as in run_dft, df_j_aux / df_k_aux as in run_frequencies; method="rimp2" (auxbasis=, scf_jk="exact"/"rijk"), method="scs-mp2" (as "rimp2", plus c_os= / c_ss=, defaults 6/5 and 1/3), method="oo-rimp2" (auxbasis=, scf_jk="exact"/"rijk", oo_max_iter, oo_grad_conv), method="att-rimp2" (as "rimp2", plus omega= in Å⁻¹, erfc; or att_operator="terfc" with r0= in Å), method="scs-mp2-2terfc" (as "rimp2", plus r0_bonded= / r0_nonbonded= in Å, defaults 0.75 / 1.05, and c_os= / c_ss=, defaults 1.27 / 4.05) and method="pdep-rpa" (auxbasis=, rpa_gradient=, n_quad=), closed shell; "rimp2", "att-rimp2" and "scs-mp2-2terfc" also on a UHF open shell (ROHF raises). A kwarg the method does not read raises. run_optimize_uhf is reference="uhf". solvent / pcm_lebedev_order optimize on the IEF-PCM surface (method="scf"); scf_warm_start=False re-guesses every geometry's SCF instead of starting from the previous geometry's orbitals ([optimize] scf_warm_start); coordinates="cartesian" (default) or "internal" (redundant internal coordinates) sets the step coordinates for every method ([optimize] coordinates), and anything else raises ValueError; coordinates="internal" together with point_charges= or external_field= also raises ValueError, because fixed charges and a field exert a net force and torque that internal steps cannot follow (use "cartesian"; solvent= is fine); initial_hessian="lindh" (default) or "simple" and trust_update="ratio" (default) or "fixed" set the BFGS start and the trust-radius rule ([optimize] initial_hessian, trust_update).task = "optimize"
run_frequenciesHarmonic frequencies from the analytic Hessian (RHF, UHF, ROHF with exact J/K, or RI-J / RI-K) or finite differences of the analytic gradient; RHF/UHF/ROHF or their KS variants. Closed-shell KS and UKS (reference="uhf") (LDA/GGA, pure or global hybrid) use the analytic moving-grid Hessian under the default hessian="auto" (explicitly: hessian="analytic-moving-grid"); other KS references use finite differences. method="pdep-rpa", "att-rimp2", "rimp2", "scs-mp2", "scs-mp2-2terfc" and "oo-rimp2" (auxbasis= required) difference the analytic gradient of that method centrally, as the CLI's task = "frequencies" does for those kinds; att-rimp2 reads omega= (inverse Angstrom), att_operator= and r0= (Å), scf_jk=, jk_auxbasis= and frozen_core=; rimp2 (UHF reference and unrestricted gradient when the molecule's multiplicity is above 1), scs-mp2 (c_os=, c_ss=), scs-mp2-2terfc (r0_bonded=, r0_nonbonded=, c_os=, c_ss=; UHF when the multiplicity is above 1) and oo-rimp2 (oo_max_iter=, oo_grad_conv=, frozen_core 0) read the same reference kwargs, with scs-mp2 and oo-rimp2 closed shell only; pdep-rpa reads rpa_gradient=, n_quad=, quadrature= and trunc_thresh=; neither gives IR intensities. scf_warm_start=True (opt-in) starts every displaced SCF of a finite-difference Hessian from the reference geometry's orbitals ([frequencies] scf_warm_start); pair it with a tighter scf_density_conv.task = "frequencies"
run_xtb_energy_gradientGFN1/GFN2/GFN-FF energy and gradient (Hartree, Hartree/Bohr). Present in every build; raises RuntimeError unless the extension was built with the xtb cargo feature (libxtb on the loader path).no CLI kind
run_xtb_optimizeGeometry optimization on a GFN-xTB surface with the run_optimize BFGS driver; max_steps bounds geometry steps, scc_max_iter the SCC at each geometry, and an unconverged SCC raises. Certificate is not graded.no CLI kind
run_xtb_frequenciesHarmonic frequencies on a GFN-xTB surface: central differences of the xTB gradient (6N evaluations), shared mass-weighting and translation/rotation projection.no CLI kind
run_saddleFirst-order saddle-point (transition-state) search by P-RFO; closed-shell. hessian="fd" (default) / "analytic" / "auto"; .hessian_source reports which ran. scf_warm_start=False re-guesses every step's SCF instead of warm-starting it (the FD Hessians are always cold).—
run_ircIntrinsic reaction coordinate in both directions from a saddle; closed-shell. scf_warm_start=False re-guesses every point's SCF.—
OptimizeResultenergy, converged, steps, energy_trace, mol().
FrequencyResultFrequencies in cm⁻¹ (negative = imaginary), normal modes, cartesian_hessian, asymmetry diagnostic, hessian_source, molecule (the geometry).
SaddleResultOutcome of a P-RFO search: geometry (Å), n_imaginary, imaginary_mode, is_transition_state().
IrcResultBoth directions of an IRC, plus the saddle they came from.
IrcBranchOne direction of an IRC walk.

Molecular dynamics

NamePurposeCLI
run_aimdBorn-Oppenheimer MD on the SCF surface: RHF/UHF/ROHF, or RKS/UKS/ROKS with xc= (reference=, unset: by multiplicity), dispersion= and df_j_aux / df_k_aux as in run_optimize. thermostat="nve" (velocity Verlet), "berendsen" (tau_fs=, equilibration only) or "langevin" (BAOAB, friction_per_ps=); temperature_k, init_temperature_k, seed, stride, scf_warm_start, masses_amu; trajectory_path= / energies_path= write XYZ and CSV. A thermostat parameter of another thermostat raises ValueError.task = "md"
run_ffmdMD on the force field of an MmTopology, atoms given by symbols and coords_angstrom; cutoff_angstrom= for the non-periodic reaction-field cutoff. The MD kwargs of run_aimd.—
MdResultPer-frame times_fs, potential_energies, kinetic_energies, total_energies, conserved, temperatures; positions_angstrom, velocities (Å/fs); n_dof, max_conserved_drift, scf_iterations, certificate (ungraded), mol().

See Molecular dynamics.

QM/MM

NamePurposeCLI
QmmmSystemA QM/MM partition with link atoms and boundary-charge schemes (coordinates in Å).[qmmm]
MmTopologyExplicit-parameter AMBER-form MM force field; assigns no parameters itself.—
run_qmmmEmbedded SCF energy plus QM gradient, MM forces and full gradient.[qmmm] (energy)
run_optimize_qmmmOptimize a QmmmSystem; QM atoms always move, MM atoms per move_mm; initial_hessian= and trust_update= as on run_optimize.—
QmmmResultenergy, qm_gradient(), mm_forces() (forces, not gradients), full_gradient().
QmmmOptimizeResultThe relaxed partition and its energy trajectory.

See QM/MM for a worked example.

MP2 family

NamePurposeCLI
run_rimp2RI-MP2 on an RHF reference; UHF + unrestricted RI-MP2 when multiplicity > 1 (reference says which). Exact by default; local=/eps= for the local approximation. with_gradient=True adds the analytic gradient (closed-shell exact RI-MP2 on an exact-J/K RHF).rimp2
run_oo_rimp2Orbital-optimized RI-MP2 (level-shifted Newton + DIIS + Cayley rotation). Closed shell only; open-shell OO-RI-MP2 is CLI-only. with_gradient=True adds the analytic gradient (frozen_core=0, converged loop).oo-rimp2
run_mp3MP3 on an RHF reference, with RI integrals.mp3
run_attenuated_rimp2RI-MP2 with the erfc-attenuated operator; ω in Å⁻¹, default 0.420.att-rimp2
run_terfc_rimp2RI-MP2 with the exact tempered-erfc operator at one cutoff r0 (Å); needs the terfc tables.—
run_scs_mp2Spin-component-scaled MP2 (defaults c_OS = 6/5, c_SS = 1/3). relativistic="x2c1e" for an X2C reference.scs-mp2
run_scs_mp2_2terfcDual-attenuated SCS-MP2(2terfc); needs the terfc tables.scs-mp2-2terfc
run_mp2_vMP2-V: attenuated MP2 plus damped VV10 nonlocal correlation.mp2-v
run_double_hybridB2PLYP or DSD-PBEP86 double hybrid; UKS reference for multiplicity > 1 or unrestricted=True; dispersion="d3bj" selects the kind's D3(BJ) set; the result carries a certificate (Proven). kind="wb97x-l-v" runs ωB97X-L-V (closed-shell; lambda_ / omega override the published 0.6 and 0.1 Bohr⁻¹; dispersion= raises).b2plyp, dsd-pbep86, wb97x-l-v
run_laplace_mp2Laplace-transform RI-MP2 (default 7 quadrature points).laplace-mp2
run_laplace_sos_mp2Laplace-transform SOS-MP2, E = c_os · E_OS; MO, AO or AO-sparse formulations.laplace-sos-mp2
RiMp2ResultResult of run_rimp2 and run_terfc_rimp2: total_energy, rhf_energy (the reference SCF energy, RHF or UHF), mp2_corr, reference, local (None for the exact method, else the local model dict) and gradient().
OoRiMp2ResultResult of run_oo_rimp2, with converged, grad_norm and gradient().
Mp3Resulte_hf, e_mp2, e_mp3, e_corr, e_total.
AttenuatedMp2ResultAttenuated MP2 total, correlation and spin components.
ScsMp2ResultResult of run_scs_mp2/run_scs_mp2_2terfc, with e_os/e_ss.
Mp2VResultMP2-V total, attenuated MP2 part and VV10 part.
LaplaceMp2ResultLaplace MP2 total, correlation and spin components.
SosMp2ResultScaled and unscaled OS energy, c_os, n_quad and formulation echoed back.
DoubleHybridResultResult of run_double_hybrid: total_energy, e_ks, e_corr_scaled, e_os, e_ss, c_os, c_ss, certificate. For kind="wb97x-l-v", e_os is the unscaled short-range LinLCCD energy, c_os is λ and e_ss = c_ss = 0.

run_rimp2, run_oo_rimp2, run_attenuated_rimp2, run_terfc_rimp2, run_scs_mp2, run_scs_mp2_2terfc, run_mp2_v, run_laplace_mp2, run_laplace_sos_mp2 and run_rs_mp2_rpa take scf_jk="exact"|"rijk"|"rijcosx" and jk_auxbasis= to choose how the reference SCF builds J and K, and their results echo scf_jk and jk_auxbasis. The default is "exact", except for run_rs_mp2_rpa, whose default is "rijk". run_oo_rimp2 and run_optimize(method="oo-rimp2") accept "exact" and "rijk" (the orbital steps rebuild J/K on the reference's route) and raise on "rijcosx". See The MP2 family.

Exact and local correlation

run_rimp2, run_drpa and run_linlccd name a method and compute it exactly by default. The local approximation is asked for with keywords that mirror the CLI's [local] section, under the same rules, raised as ValueError before any SCF:

  • local= is None (exact; "none" is the same) or "amplitude-threshold"; any other value is an error.
  • eps= is required with local="amplitude-threshold": the threshold is part of the model and has no default. eps=0 reproduces the exact method. eps= without local= is an error, not ignored.
  • compute_reference=True (local only) also computes the exact method and reports it: local["e_corr_canonical_ri"] (MP2), e_corr_plasmon_canonical (dRPA), local["e_corr_exact"] (LinLCCD). Off, the key is present and None. It is a full exact calculation, so it removes any cost saving.
  • run_rimp2(integral_direct=True, ...) selects the integral-direct local MP2, with its locality maps aux_radius, virt_radius (Bohr), ao_tail, schwarz_skip, eri3_pass ("aux-major", the default, or "batches"), batch_merge (only with eri3_pass="batches", default 4 there), gate_cal, virt_schwarz_kappa and pair_skip ("auto", "on", "off", "audit"), with the CLI names and defaults. They are errors without integral_direct=True. fock_screen (default True, the Fock-propagated mask screen; False keeps the plain integral mask) applies to the local MP2 on both paths, in core and integral-direct. kappa is an error on the local MP2.

Every result says which model it is: RiMp2Result.local and the dicts' "local" key are None for the exact method, else a dict with scheme, eps, keep_fraction and integral_direct plus solver counters. All local paths are closed shell.

NamePurposeCLI
run_drpadRPA@HF by the drCCD Riccati solve. Exact by default (equals the plasmon formula); MemoryError before the SCF when the exact solve cannot fit (use run_pdep_rpa(..., trunc_thresh=0)). diis= (default 8); eps_rtol_factor= (local only). The CLI's exact drpa takes the frequency route instead (no static eigensolve, 48 Gauss–Legendre points); the two agree to the quadrature and rounding error (4.3e-11 Ha on n-hexane / cc-pVDZ).drpa ([local] for the local scheme)
run_drpa_scanThe local dRPA over a list of eps values, sharing one SCF and localization; each dict carries "local".drpa + [local] eps_sweep
run_linlccdLinearized ladder CCD, variant = "hh" (default), "drivers-only", "full". Exact by default.linlccd

Coupled cluster

All use RI integrals from the auxbasis argument and a closed-shell RHF reference.

NamePurposeCLI
run_ccdCCD correlation energy.ccd
run_ccsdSpin-adapted closed-shell CCSD. relativistic="x2c1e" for an X2C reference.ccsd
run_ccsd_tCCSD plus the spin-adapted (T) correction. relativistic="x2c1e" for an X2C reference.ccsd(t)
CcResultcorrelation_energy and t_correction (None without triples). No reference energy.
run_eom_ccsdEE-EOM-CCSD singlet excitation energies on the spin-adapted CCSD.eom-ccsd
EomCcsdResultexcitation_energies, residuals, singles_weight, r1(k) / r2(k) (right eigenvectors), rhf_energy, ccsd_correlation_energy, certificate.

Multireference

All start from the canonical exact-J/K RHF orbitals of a closed-shell molecule. casscf_optimizer is "ah" (default, augmented-Hessian step) or "bfgs"; casscf_integrals is "auto" (default), "dense" or "direct". See CAS-CI and CASSCF.

NamePurposeCLI
run_casciCAS-CI, lowest root of the (n_alpha, n_beta) sector; compute_rdms=True returns the RDMs.library only
run_casscfTwo-step CASSCF; casscf_grad_tol, casscf_energy_tol, casscf_max_iter, casscf_max_step, casscf_optimizer, casscf_integrals, casscf_integral_thresh, canonicalize. Returns a CasScfResult with a certificate.casscf
run_nevpt2Strongly contracted NEVPT2 on a CASSCF (reference="casscf") or CAS-CI ("casci") reference, closed-shell active space (n_alpha = n_beta). Returns a Nevpt2Result with the eight class energies.nevpt2

RPA, GW and excited states

NamePurposeCLI
run_pdep_rpaDirect RPA correlation energy by PDEP (projective dielectric eigenpotentials); accepts point charges, field and solvent. properties=True / export_npz= add the CLI's [rpa] property bundle (polarizabilities, per-atom and charge-transfer α, C6, charges, ESP, field, NPZ); export_eigpot_prefix= writes eigenpotential cubes. Closed shell only; open-shell U-PDEP-RPA is CLI-only. with_gradient=True adds the analytic nuclear gradient of the total energy (result.gradient(), (natoms, 3) Hartree/Bohr, as run_rimp2): full-rank dense Coulomb RPA on an exact RHF reference, so an unset trunc_thresh is 0 and an unset scf_density_conv is 1e-9; a nonzero trunc_thresh, chi0_sparsity, k_builder="cosx", df_j_aux / df_k_aux, point charges, field, solvent, the property keys, run_diagnostics and an open shell raise ValueError before the SCF.pdep-rpa
run_rs_mp2_rpaRange-separated SR-MP2 + LR-RPA (formulation = "delta-lr" or "coupled-rings"; ω in Å⁻¹; a list for omega or formulation returns a list of results from one SCF).rs-mp2-rpa
run_gwClosed-shell G0W0 / COHSEX / evGW0 / evGW on an RHF or RKS reference.gw
run_u_gwOpen-shell GW variants on a UHF/UKS or ROHF reference.gw with multiplicity > 1
run_bse_tdaBSE-TDA singlet excitation energies on a closed-shell RHF reference.bse-tda
run_tdhf_static_polarizabilityRPAx@KS static (ω = 0) polarizability on a closed-shell KS reference.tdhf-static-polarizability
run_tddftTDA or Casida excitations on an HF (CIS/TDHF) or KS reference, restricted or unrestricted, with the f_xc kernel and <S^2> per root.tda, tddft
PdepRpaResulttotal_energy, e_rpa, eigensolver_converged, eigenvalues and quadrature grid, route, eigenpotentials, dressed_eigenvectors, and inv_dielectric_freq (with with_inv_dielectric_freq=True).
RsMp2RpaResultSR-MP2, LR-MP2 and dRPA pieces; which fields are set depends on formulation.
GwResulteps_qp, eps_mf, sigma_x, sigma_c, z_factor, outer_converged, qp_converged.
UGwResultα and β versions of the GwResult fields.
BseResultExcitation energies and oscillator strengths.
TdhfStaticPolarizabilityResultPolarizability tensor and its isotropic value iso.
TddftResultexcitation_energies, oscillator_strengths, method, grid, certificate.

Properties and charges

Each takes (mol, basis_set, result) with a converged closed-shell RhfResult or DftResult; esp_at_points also takes the points and hirshfeld_polarizability an RI basis.

NamePurposeCLI
esp_at_atomsElectrostatic potential at each nucleus, in atomic units.[rpa] compute_esp
esp_at_pointsElectrostatic potential at arbitrary points given in Bohr.[rpa] compute_esp_surface (vdW-surface points only)
mulliken_chargesMulliken population charges.[rpa] compute_mulliken_charges
lowdin_chargesLöwdin (symmetric-orthogonalization) charges.[rpa] compute_lowdin_charges
hirshfeld_chargesHirshfeld charges. The default proatom="scf" uses free-atom SCF densities in the molecule's basis, solved with the result's own SCF settings, as the CLI does; proatom="slater" uses a single-exponential Slater proatom.[rpa] compute_hirshfeld_charges
chelpg_chargesCHELPG charges fitted to the ESP on a grid.[rpa] compute_chelpg_charges
resp_chargesSingle-stage RESP (restrained ESP-fit) charges.[rpa] compute_resp_charges
hirshfeld_polarizabilityPer-atom Hirshfeld-partitioned static polarizability tensors (Bohr³) from PDEP-RPA.—
orbital_momentsPer-orbital centroids and spatial spreads (Bohr) of the restricted MOs.—
density_second_moment3×3 second-moment tensor of the electron density (Bohr²).—
eval_ao_on_pointsAO values at (N, 3) points in Bohr, shape (N, nbasis).—
eval_density_on_pointsTotal electron density (e/Bohr³) at points in Bohr.—
eval_mo_on_pointsRestricted MO values at points in Bohr, for chosen 0-based MO indices.—
write_cubeGaussian cube file of the density or one restricted MO; all lengths in Bohr.—

The [rpa] compute_* keys write into the CLI's NPZ export.

Integrals and orbitals (prototyping)

These take omega/r0 in raw Bohr units, unlike the run_* drivers.

NamePurposeCLI
AoIntegralsOne-electron matrices, ERIs (dense, 3- and 2-index, MO-transformed), J/K, gradient/Hessian/response/XC pieces for one molecule and basis; see Building blocks.—
DfJkFrom AoIntegrals.df_jk(aux): RI-J/RI-K j(D), k(D), jk(D) over a fit built once.—
XcFunctionalFrom AoIntegrals.xc_functional(name): E_xc, V_xc, f_xc response and XC gradient/Hessian on run_dft's grid.—
Cphf, UcphfFrom AoIntegrals.cphf(...) / ucphf(...): orbital-Hessian matvec, CPHF/CPKS solve, response density.—
einsumContraction of two or more operands under ferric's einsum spec grammar; three or more run as a fixed left-to-right chain of binary contractions with no order search.—
compute_eri3Raw 3-centre Coulomb integrals (P|μν), shape (naux, n_bf, n_bf).—
compute_eri3_moMO-basis 3-centre integrals (P|pq) for any two coefficient matrices, built blockwise under a memory budget.—
compute_metric_2c2-centre metric (P|w|Q) over the auxiliary basis, Coulomb by default.—
shell_infoShell centres (Bohr), first-function offsets and sizes, for building fitting domains.—
boys_localizeFoster–Boys localization of given orbitals; returns a BoysResult.—
BoysResultResult of boys_localize: c_loc(), centers(), converged, iterations.

Conformer ensembles

NamePurposeCLI
ConformerEnsembleConformers of one species sharing atom order, composition, charge and multiplicity.—
BoltzmannWeightsBoltzmann populations of an ensemble at one temperature.—
EnsembleDiagnosticsPopulation-structure readout: effective number of conformers, dominance verdict.—
WeightedStatsA weighted mean with its spread (mean, std_dev, min, max).—
boltzmann_weightsBoltzmann weights from a list of energies (Hartree) at a temperature (default 298.15 K).—
weighted_statsWeighted mean and standard deviation of a scalar property.—
weighted_stats_vectorThe same, component-wise, for a vector property.—
weighted_stats_tensorThe same, element-wise, for a rank-2 tensor property.—

Porting published methods

Three published methods run on the building blocks with no change to ferric's Rust. The only ferric calls are AoIntegrals, XcFunctional, Molecule.from_xyz(charge=) and the fock_hook argument of run_rhf / run_dft. Each port is a script in examples/python/ with under 100 lines of method code, an exactness anchor against an independent ferric construction, and a comparison with PySCF numbers written by scripts/gen_pyscf_block_ports_refs.py to testdata/reference/block_ports_pyscf.json. The checks are in crates/ferric-python/tests/test_block_ports.py.

ScriptMethodBlocks usedMethod lines
drpa_from_blocks.pyRI direct RPA by imaginary-frequency quadrature (Eshuis, Yarkony, Furche, JCP 132, 234114 (2010))df_mo22
adc2_from_blocks.pysinglet ADC(2) excitation energies (Schirmer, PRA 26, 2395 (1982)), spin orbitalsao2mo72
embedding_from_blocks.pyprojection-based HF-in-DFT and DFT-in-DFT embedding (Manby, Stella, Goodpaster, Miller, JCTC 8, 2564 (2012)), SPADE partitionveff, xc_functional, hcore, overlap, ao_atoms, fock_hook59

Measured agreement, water and NH3, all electrons (2026-11-11, Hartree):

PortAnchorAnchor residualPySCF referenceDifference
dRPA, cc-pVDZ / cc-pVDZ-RIrun_drpa (Riccati, no quadrature), 80 nodes<= 4e-12gw.rpa.RPA, same 40 nodes<= 1e-12
ADC(2), 6-31GADC(1) equals cis_from_blocks<= 4e-15adc.RADC, "adc(2)", "ee", 3 roots<= 2.7e-9
Embedding, PBE, cc-pVDZ, heavy atom as APBE-in-PBE equals full PBE, extrapolated from mu = 1e5 and 1e6<= 1.2e-9the same algorithm on PySCF's RKS, flat 99 x 590 grid3.5e-8 (water), 1.8e-9 (NH3)

The embedding comparison is limited by the XC grids: PySCF's HF-in-PBE energy moves 2.3e-7 (water) and 2.7e-7 (NH3) between its 99 x 590 and 150 x 974 grids, and the test's bar is the sum of both codes' grid changes and their full-KS difference.

Notes for writing a port:

  • fock_hook refuses a V that is not symmetric to round-off. A level-shift projector mu S C C^T S with mu = 1e6 is asymmetric by 2e-10, so symmetrize it before returning it.
  • At finite mu the subsystem density leaks into B's space and the embedding energy is low by c / mu, with c = 6.96 Ha (water) and 5.44 Ha (NH3): 7e-6 Ha at mu = 1e6. PySCF's reference has the same c to 4e-5 relative. Extrapolate in 1/mu rather than raising mu: at mu = 1e7 run_dft(fock_hook=) does not converge in 200 iterations from its own guess. dm0= supplies a starting density to every driver, but a better start does not remove the energy noise floor of the hook term (see "Energy noise floor" above), which sets the limit on energy_conv at large mu.
  • A subsystem SCF with N_A electrons is a Molecule with all nuclei and charge Q_total + N_B, where N_B is the number of electrons assigned to B; the hook adds v_emb, so no ghost atoms or new integrals are needed.
  • ao2mo returns the full (pq|rs) block, so the spin-orbital ADC(2) port holds (2 nmo)^4 arrays and is for small bases; it builds the singles-doubles coupling one occupied pair at a time. A density-fitted ADC(2) would build the same intermediates from df_mo.

Second set: dm0, open-shell hooks, cphf and einsum

Three more ports cover the blocks the first set does not use: run_uhf's dm0 and mom_reference, veff_polarized, dipole, cphf and ferric.einsum, on the RhfResult, UhfResult and DftResult accessors. The references are PySCF's own implementations, written by scripts/gen_pyscf_block_ports_set2_refs.py to testdata/reference/block_ports_set2_pyscf.json; the checks are in crates/ferric-python/tests/test_block_ports_set2.py.

ScriptMethodBlocks usedMethod lines
delta_scf_from_blocks.pycore-hole ΔSCF (Bagus, Phys. Rev. 139, A619 (1965)) held by initial maximum overlap (Barca, Gilbert, Gill, JCTC 14, 1501 (2018))run_uhf(dm0=, mom_reference="initial"), veff_polarized, hcore, overlap29
cphf_polarizability_from_blocks.pyCPHF / CPKS static polarizability (Pople, Krishnan, Schlegel, Binkley, IJQC S13, 225 (1979))dipole, cphf, xc_functional14
fno_mp2_from_blocks.pyDF-MP2 frozen natural orbitals (Taube, Bartlett, Collect. Czech. Chem. Commun. 70, 837 (2005))df_mo, ferric.einsum21

Measured agreement, water and NH3, cc-pVDZ, all electrons (2026-11-13, Hartree and atomic units):

PortAnchorAnchor residualPySCF referenceDifference
ΔSCF, O / N 1s binding energy (19.9003 / 14.9760 Ha)a numpy MOM-UHF on veff_polarized from the same start, previous-iteration reference<= 5.7e-14scf.addons.mom_occ UHF minus RHF<= 5.7e-14
CPHF polarizabilityfinite field on run_rhf(external_field=), Richardson in the step2.7e-7 (HF), 3.0e-7 (PBE0, water)the CPHF equations on PySCF's response function, solved densely1.9e-9 (water), 1.6e-9 (NH3)
FNO-MP2, cc-pVDZ-RIevery virtual kept equals run_rimp2<= 1.9e-16DFMP2.make_fno: occupations, and E_corr with 1/4, 1/2 and all virtuals<= 3.4e-12 (occupations), <= 5.6e-12 (energies)

Mutations seen to fail (each applied to the port, the named test run, the port restored):

PortMutationFailing test, measured shift
ΔSCFmom_reference="initial" dropped from run_uhfboth ΔSCF comparisons (water): the cation falls to the valence hole, the binding energy moves by 19.5 Ha
CPHFr[j] for r[i] in alpha_ijPySCF comparison (water): off-diagonal elements become alpha_jj, up to 6.9 a.u.
FNOthe exchange term dropped from D_abPySCF comparison (water): occupations move by 1.3e-2; the all-virtual anchor still passes, since E_corr does not depend on the virtual rotation
FNO(ia|jb) for (ib|ja) in the energyall-virtual anchor (water): E_corr moves by 5.2e-2 Ha

Notes from these ports:

  • run_uhf(mom_after_iter=k) arms MOM after iteration k >= 1 (k = 0 is off), so it cannot hold the occupation of a dm0 start: the first iterations' aufbau refills the core hole, and from the water core-hole start mom_after_iter=1 converges to the valence-hole cation (-75.632 Ha instead of -56.126 Ha). mom_reference="initial" takes the start's occupied orbitals as the reference, fixed, from the first iteration, as PySCF's mom_occ does; it converges the core-hole cation in 15 iterations at the default diis_size=8 (water, cc-pVDZ, energy_conv 1e-11, density_conv 1e-9).
  • PySCF's scf.cphf.solve (the solver of prop.polarizability.rhf) stops up to 2.5e-7 a.u. short of the dense solution of its own equations, at tol 1e-11 and 1e-13 alike, so the comparison is made against the dense solve.
  • ferric.einsum takes explicit -> specs with no repeated index within a term; the semicanonical orbital energies of the FNO port (a three-operand diagonal) use numpy.einsum.

Third set: solvers, contract, ferric.mo and streamed integrals

Four pieces take the boilerplate out of the ports above:

ModuleWhat it gives
ferric.solversdavidson(matvec, diag, nroots) (block Davidson; symmetric=False for right eigenvectors), davidson_rpa(apb, amb, diag, nroots) (full TDHF/RPA in the Stratmann–Scuseria–Frisch reduced form, X and Y normalized as XᵀX − YᵀY = 1), Diis(max_vecs=8) (.update(x, err) on arrays or tuples of arrays) and solve_linear(matvec, rhs) (block preconditioned CG). Matvecs take an (n, k) block so a J/K build or contraction serves k vectors at once. An unconverged solve raises ConvergenceError with the last iterate in err.result; a non-positive-definite operator raises NumericalError.
ferric.tensorcontract(spec, *operands, optimize="greedy", out=None, accumulate=False): any numpy.einsum spec (implicit output, ..., diagonals, traces) on the engine behind ferric.einsum, with a pairwise order search ("greedy", "optimal", False for written order). contract_path(spec, *shapes) reports the chosen order, its FLOPs and largest intermediate against the written order. When the last step runs on the engine and out is C-contiguous, shares no memory with an operand and needs no transposition, out=/accumulate=True is written by that step itself (ferric.einsum(..., out=, beta=): no result allocation, no extra pass). Batched, element-wise and batched-dot steps run on the engine's own kernels (rayon over the batch); numpy keeps broadcast products and batched dots whose batch indices come in different orders.
AoIntegrals.df_mo_batches(aux, C1, C2, max_gb=)df_mo as an iterator of (i0, i1, B) occupied batches whose size comes from max_gb (default 2 GiB), which bounds the batch and raw aux block sizes, so the full (naux, k1, k2) and AO (P|μν) tensors are held only when they fit it; .path says whether (P|μq) was kept ("half-transformed") or rebuilt per batch ("recompute").
ferric.moThe orbital-space objects a method script otherwise re-derives. Reference(mo_coeff, mo_energy, nocc) (or Reference.from_result(rhf, ints), closed shell; the occupied count is the AoIntegrals' ECP-aware nelec // 2): occupied/virtual slices, excitation_gaps() (the Davidson diagonal), denominators("ijab"), and the integral-direct response maps transition_densities(x) (D_k = C_v X_kᵀ C_oᵀ, for jk(D, hermi=0)), ov_part(M) and vo_part(M): with J and K of D, ov_part(J) is (ia|jb) x_jb, ov_part(K) is (ib|ja) x_jb and vo_part(K) is (ij|ab) x_jb. ThreeIndex.density_fitted(ints, aux, ref) / ThreeIndex.exact(ints, ref): the oo, ov and vv blocks of a three-index factor. stream_ov(ints, aux, ref, path, max_gb=): the ov block from df_mo_batches into a disk-backed memmap. Checks: tests/test_mo.py.

The new ports use them, with the checks in crates/ferric-python/tests/test_python_method_ports.py and PySCF references written by scripts/gen_pyscf_{ccd,tdhf}_from_blocks_refs.py:

ScriptMethodBuilt onMethod lines
ccd_from_blocks.pyclosed-shell CCD, LCCD (CEPA(0)), LinLCCD (Carter-Fenk, JPCA 129, 7251 (2025)) and MP3 from one amplitude equation, on a DF (df_mo) or exact (ao2mo) three-index factorferric.mo, contract, Diis61
tdhf_from_blocks.pyfull TDHF singlets and triplets, A and B never formed; on a three-index factor or integral-directferric.mo, davidson_rpa, jk(hermi=0)47
streamed_mp2_from_blocks.pySCS-MP2 (Grimme, JCP 118, 9095 (2003)) and SOS-MP2, B streamed once to a disk-backed memmap and summed over pairs of occupied batchesferric.mo.stream_ov, contract32

Measured agreement (2026-11-29, Hartree; cc-pVDZ / cc-pVDZ-RI against the drivers, 6-31G exact integrals against PySCF):

PortReferenceDifference (water)
CCDrun_ccd / PySCF pyscf.cc.ccd.CCD (exact)5.2e-12 / 3.2e-11
MP3 (E3)run_mp31.2e-16
LinLCCDrun_linlccd(variant="full")6.7e-11
TDHF, 5 singlets / 5 tripletsrun_tddft(method="rpa")9.5e-14 / 3.5e-13
TDHF, exactPySCF tdscf.TDHF8.2e-11 / 8.5e-11
SCS- and SOS-MP2run_scs_mp22.5e-16 (benzene, 3 batches at 0.01 GiB: 3.7e-15)

LCCD with its ring terms has no ferric driver and no PySCF reference; it is anchored through its parts (its linear operator gives MP3 exactly, the ladders alone give LinLCCD, adding the quadratic terms gives CCD).

Notes from these ports:

  • A TDA or A − B product needs K of a non-symmetric transition density. jk(D, hermi=0) takes one (and a (k, nao, nao) stack in one pass over the integrals), so tdhf_from_blocks.tdhf_direct runs exact TDHF with no MO integral tensor at all: one jk call per Davidson block, shared by A + B and A − B. Its roots equal PySCF's TDHF to 8.5e-11 Ha (water, NH3, 6-31G).
  • contract keeps the written order when that is cheapest: for water's particle-particle ladder Pac,Pbd,ijcd->ijab it forms (ac|bd) (19 virtuals), and contract_path shows when a larger virtual space makes it contract a B factor into the amplitudes first.
  • df_mo_batches plans memory from the tensors it holds; libint's per-thread three-centre engines (about 20 MiB each) come on top. Benzene/cc-pVTZ with all orbitals, 4 threads: df_mo peaks at 1181 MiB above baseline, the stream at 734 MiB with max_gb=0.6 (half-transformed, 1.6 s against 2.0 to 2.5 s) and 310 MiB with max_gb=0.1 (recompute, 11 batches, 12.7 s).

Compiled contractions: ferric.tensor_program

ferric.tensor_program runs several contractions in ONE call into Rust, for code that issues many small ones:

NameWhat it does
compile(spec, *shapes)a Plan: contract's pairwise plan executed natively in one call, plan(*operands, out=, scale=, accumulate=)
Program.trace(fn, *shapes)records fn on placeholders (contract, +, -, * and / by a scalar or tensor, .T / .transpose, .reshape; anything else raises ProgramError) and replays the whole graph per call with independent steps in parallel. The recorded floating-point order is kept; reassociate=True opts in to folding scalars into the GEMMs and merging sums, which changes results at round-off
Program.map(items), contract_many(spec, operand_tuples)many independent evaluations in one call, rayon across items
Program.to_rust(name)Rust source of the recorded program on the einsum! macro (the same spec grammar), to move a prototype into a crate

The ports import contract from here; on arrays it is ferric.tensor.contract, so their functions run eagerly as written and can also be traced (tests/test_tensor_program.py traces the CCD residual and the TDHF contractions and checks them against the eager result).

What it buys, measured (4 shared cores, under load, so approximate): a program of 11 small contractions (24 x 24 operands) took 1.6 ms through contract and 49 us as one program call. GEMM-bound work gains nothing: the CCD and MP3 ports spend their time in a few large contractions, and compiling them did not change their wall time, so the ports stay eager. The TDHF factor route's speedup came from reusing the last block's contractions for A+B and A-B (factor_terms caches it, as direct_terms does), not from compiling.

Distributed memory (MPI)

ferric.parallel lets a method-development script run SPMD, one Python process per rank:

mpirun -np 4 python examples/python/ccd_from_blocks.py

It needs the MPI build (the ferric-mpi wheel, or maturin develop --features mpi); the default wheel links no MPI. There ferric.parallel.world() is rank 0 of size 1 and every collective is a no-op, so the same script runs serially and prints the same bytes. For a whole calculation prefer the CLI (mpirun -np N ferric input.toml, Installation), which handles output and errors for you; this section is for scripts built from the blocks.

The model. Every rank runs the whole script. Only the auxiliary index P of the density-fitted factor BPpq is distributed: rank r holds the contiguous band world.aux_band(naux) = (p0, p1) of rows (the first naux % size ranks take one extra), so (pq|rs) = ΣP BPpq BPrs is a sum of per-rank partial sums. Everything else is replicated: orbitals and orbital energies (rank 0's, broadcast, so every rank holds the same bits), amplitudes, DIIS and Davidson subspaces. Every contraction over P yields a partial result, which is summed over the ranks with world.allreduce_sum. A contraction that does not run over P (the quadratic CCD terms, the Davidson algebra) is computed redundantly on every rank: it costs no communication and no more wall time than one rank's share. Only rank 0 prints or writes (if world.is_root).

import ferric, ferric.parallel
from ferric.mo import Reference, ThreeIndex

world = ferric.parallel.world()          # rank, size, is_root
ref = Reference.from_result(scf, ints).replicated(world)
f = ThreeIndex.density_fitted(ints, aux, ref, world)   # this rank's band of P
g = f.ovov(world)                        # (ia|jb): partial sums, all-reduced

API.

world.rank, .size, .is_root, .mpi_enabledthis process in MPI_COMM_WORLD; 0, 1, True without MPI
world.allreduce_sum(a, identical=False)sum a C-contiguous float64 array over the ranks, in place, on the array's own buffer (no copy). identical=True then broadcasts rank 0's result so every rank holds the same bits: use it for anything that steers control flow
world.bcast(a), world.barrier(), world.all_true(flag)rank 0's array to all; synchronize; AND of a flag over the ranks
world.aux_band(naux)this rank's (p0, p1)
AoIntegrals.n_aux(aux)naux, without building integrals
AoIntegrals.df_mo(aux, c1, c2, aux_range=(p0, p1)), df_mo_batches(..., aux_range=)rows [p0, p1) of the fitted B, equal to df_mo(...)[p0:p1]
ThreeIndex.density_fitted(..., world=), ThreeIndex.exact(..., world=), stream_ov(..., world=), Reference.replicated(world), ferric.mo.reduce / replicatethe banded factor (ThreeIndex.band), the banded stream (one .rank<r> memmap per rank) and the helpers the ports use

Collectives are called by every rank, in the same order; a rank that skips one leaves the others waiting. An all-reduce may round differently on different ranks (the sum order is the library's); the ports use identical=True for the residuals and subspaces they iterate on, so every rank takes the same branches.

Why the fitted rows need all of P. The fit is B = V−1/2(Q|μν)C C with V the (P|Q) metric, which mixes every auxiliary function, so a rank cannot fit its own band from its own raw rows. df_mo(aux_range=) forms V−1/2 (naux², on every rank), streams the raw (Q|μν) in blocks over all Q, MO-transforms each block and multiplies it by the band's rows of V−1/2 into the band. Per rank, memory is naux² for the metric plus the band, (p1 − p0)·k1·k2, plus one raw block of about 512 MiB (less when nao is large): the band is 1/size of the factor, the metric factor is not reduced. The raw three-index integrals and their transformation are computed by every rank in full; distributing that work would need a message exchange between ranks and is not done. What scales with the rank count is the storage of B and every later contraction over P.

Per port (o occupied, v virtual, k Davidson block width; each "all-reduce" is followed by the broadcast of identical=True, so counts are of allreduce plus bcast of the same size):

PortPer rankCommunication
ccd_from_blocks (CCD, LCCD, LinLCCD, MP3)band of oo, ov, vv; replicated t (o²v²), g = (ia|jb), DIIS historyone all-reduce of o²v² for g at the start; one all-reduce of o²v² for L(t) each iteration (all of L's terms, ladders and rings, are P-sums); the quadratic terms and DIIS are local
tdhf_from_blocks, factor routeband of oo, ov, vv; replicated Davidson subspaceone all-reduce of 3·o·v·k per product block (the three integral terms stacked); A+B and A−B each need one
tdhf_from_blocks, integral-direct routeno B at alljk(hermi=0) is a collective inside ferric: the exact quartets are striped over the ranks (the DirectJK reduction, correct at np ≥ 2 since the carry-over fix) and each rank gets the whole J, K; then rank 0's three o·v·k terms are broadcast
streamed_mp2_from_blocksband of the ov block on disk, (p1 − p0)·o·v per rank, two batches in memoryone all-reduce of a (bI, v, bJ, v) block per pair of occupied batches (the energy is quadratic in (ia|jb), so the P-sum comes before the square); o²v² in total

The SCF that produces the orbitals is not part of this: every rank runs it, its J/K are distributed inside ferric (the exact path and the DF path both, see the mpi feature comment in crates/ferric-python/Cargo.toml), and rank 0's orbitals are broadcast.

Interop with mpi4py. There is one MPI per process, initialized once. If you use mpi4py too, import ferric.parallel and call world() before mpi4py.MPI: ferric then initializes MPI and mpi4py finds it initialized and shares the same COMM_WORLD. Importing mpi4py first makes it initialize MPI; ferric then sees MPI started behind its back, reports a one-rank world, and world() raises rather than let every rank compute alone. Both must link the same MPI library.

Exit. ferric finalizes MPI at interpreter exit. A rank that dies with an uncaught exception skips the finalize, so mpirun tears the job down instead of leaving the other ranks in a collective. Set RAYON_NUM_THREADS per rank: import ferric creates the rayon pool before any rank count is known, so np ranks on one node each take every core unless told otherwise.

Not supported. Only the auxiliary index is distributed: no distributed occupied or virtual indices, so amplitudes and the (ia|jb) tensor are replicated and bound a single node's memory. The raw three-index integral work is replicated (above). Only float64 C-contiguous arrays go through the collectives; there are no point-to-point calls, communicators other than the world, or non-blocking collectives. ThreeIndex.exact(world=) keeps a band of an already-replicated factor and exists to test; it saves no memory. The other run_* drivers are unchanged: those that build J/K through ferric's own SCF paths are distributed as the mpi feature comment in crates/ferric-python/Cargo.toml describes, and the rest run replicated and print on every rank.