Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions AI-USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,11 @@ The short version, for disclosures; the log below has the detail.

- Rebased the CPSCF solver PR onto `main` after the 0.5.0 release and the TREXIO export (its changelog entry moved to the Unreleased section).
- Planned and implemented the logging layer (step 1.2 of the backend roadmap): the `prop_sapt` logger with a handler writing into Psi4's output file, about 120 `psi4.core.print_out` calls in 15 modules replaced by module loggers with messages free of blank lines, the SAPT summary table as one record, `make_cube` progress at DEBUG, the 36 `psi4.core.clean()` calls before raises removed, with tests, docs and a changelog entry; results unchanged on He–H2 (energies, properties, densities and finite field within run-to-run round-off).

### 2026-11-23

- Planned and implemented the Psi4 backend (step 1.3 of the backend roadmap), after a review of the plan against the code: the backend contract (`prop_sapt.backends.base`: `MonomerReference`, the `Backend` base class with J/K builds, orbital-Hessian products, CPSCF J/K objects, dipole integrals, timers and scratch cleaning) and `Psi4Backend`, which runs the monomer SCFs and builds the integrals in place of `helper_SAPT`, now free of Psi4; the dimer's Psi4 objects as read-only compatibility attributes, the Psi4 output handler, timers and scratch cleaning in the backend, a test that only the Psi4-facing modules import Psi4, with docs and a changelog entry; He–H2 energies, properties, densities and their intermediates bitwise equal to `main` (single-threaded runs).

### 2026-11-25

- Worked through a code review of the Psi4 backend pull request: J/K inputs cleared after a failed build, monomers with different numbers of orbitals rejected, `nao_aux` renamed `naux` (it now counts spherical fitting functions), Psi4's timer around the whole dimer construction again, clear errors from the Psi4 getters with another backend, the tensor folding of `compute_jk` tested on both sides, with docs and changelog notes for the API changes.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ requests of the private repository propSAPT was developed in before it was publi
`logging` calls now quiet or redirect it, in whole or per module. The progress of
`make_cube` over the grid is logged at the DEBUG level. See the
[usage guide](https://btyrcha.github.io/propSAPT/usage.html#output-and-logging).
- Psi4 runs as the dimer's backend, `dimer.backend`, which holds the monomer SCFs and the
integrals propSAPT works from; the results are the same. The dimer's Psi4 objects and
settings (`wfnA`, `wfnB`, `mints`, `dimer_wfn`, `jk`, `memory`, `psi4_options`,
`fitting_bases`, ...) are still there, now read-only. `dimer.nao_aux` is now
`dimer.naux`, the number of functions of the SAPT fitting basis: `nao_aux` counted
Cartesian functions even for a spherical basis. `changed_psi4_options` moved
from `prop_sapt.utils` to `prop_sapt.backends.psi4_backend`.

### Fixed

Expand Down
11 changes: 11 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ Dimer Class
:undoc-members:
:show-inheritance:

Backends
--------

.. automodule:: prop_sapt.backends.base
:members:
:show-inheritance:

.. automodule:: prop_sapt.backends.psi4_backend
:members:
:show-inheritance:

Properties
----------

Expand Down
7 changes: 7 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,13 @@ itself: the Psi4 option ``save_jk`` is not needed.
If your geometry string will include more fragments, they will be treated as ghost atoms.
You can specify midbonds and farbonds in this way.

Psi4 runs as the dimer's backend, ``dimer.backend``
(:class:`~prop_sapt.backends.psi4_backend.Psi4Backend`), which holds the results of the
monomer SCFs and the integrals that propSAPT works from. Its Psi4 objects are also on the
dimer, as ``dimer.wfnA`` and ``dimer.wfnB`` (the monomer wavefunctions), ``dimer.mints``
and ``dimer.dimer_wfn``, and through ``get_psi4_molecule()`` and ``get_psi4_basisset()``.
These attributes are read-only, since replacing one would not change the calculations.

The fragment structure is kept on the dimer as ``dimer.fragments``
(:class:`~prop_sapt.fragments.DimerFragments`): the atoms of monomers A and B and of any
extra fragments, their charges and multiplicities, the ghost atoms, and the coordinates in
Expand Down
7 changes: 7 additions & 0 deletions prop_sapt/backends/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""Backends: the quantum-chemistry codes that run the reference calculations of a dimer
for propSAPT, see `prop_sapt.backends.base` for the contract. Psi4
(`prop_sapt.backends.psi4_backend.Psi4Backend`) is the only one so far."""

from .base import MONOMERS, Backend, MonomerReference, check_reference

__all__ = ["MONOMERS", "Backend", "MonomerReference", "check_reference"]
307 changes: 307 additions & 0 deletions prop_sapt/backends/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,307 @@
"""The backend contract: what a quantum-chemistry code supplies to propSAPT.

A backend is a finished reference calculation of a dimer: the SCFs of both monomers in
the dimer-centred basis set (DCBS) and the integrals of the dimer, as NumPy arrays, with
the operations propSAPT calls while it calculates. `helper_SAPT` reads only these, so
the SAPT contractions work with any code that supplies them.

Conventions every backend follows, where the arrays enter or leave propSAPT:

- AO arrays are in the dimer basis set, monomer ghosts and extra fragments included,
in the backend's own AO order; the contractions work in the MO basis, so the order
cancels inside propSAPT and only matters for AO matrices passed in or handed out.
- Orbitals are the columns of the MO coefficients `C`, occupied first.
- `V` of a monomer is the attraction of an electron by that monomer's nuclei, -Z/r
summed over its atoms.
- `Qpq` is a factor of the density-fitted two-electron integrals in the fitting basis
of the SAPT terms (Psi4's `DF_BASIS_SAPT`): ``sum_Q Q_pq Q_rs = (pq|rs)``. Any
factor works, e.g. ``J^(-1/2) (P|pq)`` or a Cholesky one.
"""

from abc import ABC, abstractmethod
from collections.abc import Mapping, Sequence
from contextlib import AbstractContextManager, nullcontext
from dataclasses import dataclass
from typing import TYPE_CHECKING

import numpy as np

if TYPE_CHECKING:
from ..fragments import DimerFragments

#: Monomer labels of a dimer.
MONOMERS = ("A", "B")


def check_reference(reference: str) -> str:
"""
Check that propSAPT supports a reference.

Args:
reference (str): "RHF" or "RKS"; "ROHF", "UHF" and "UKS" are not implemented yet.

Raises:
ValueError: If the reference is unknown or not implemented yet.

Returns:
str: The reference.
"""

if reference not in ["RHF", "ROHF", "UHF", "RKS", "UKS"]:
raise ValueError(f"Unsupported reference type '{reference}'.")

if reference in ["ROHF", "UHF", "UKS"]:
# NOTE: Future upgrades
raise ValueError(f"Reference '{reference}' not implemented yet.")

return reference


@dataclass(frozen=True, eq=False)
class MonomerReference:
"""
The SCF of one monomer in the dimer-centred basis set.
"""

#: MO coefficients, (nbf, nmo): doubly occupied, singly occupied, virtual orbitals.
C: np.ndarray
#: Orbital energies, (nmo,).
eps: np.ndarray
#: Number of doubly occupied orbitals.
ndocc: int
#: Attraction of an electron by the monomer's nuclei in the AO basis, (nbf, nbf).
V: np.ndarray
#: SCF energy.
energy: float
#: Repulsion of the monomer's nuclei.
nuclear_repulsion: float
#: Number of singly occupied orbitals, 0 for closed-shell references.
nsocc: int = 0

def __post_init__(self):
nbf, nmo = _shape(self.C, 2, "C")
if _shape(self.eps, 1, "eps") != (nmo,):
raise ValueError(
f"Orbital energies should have shape ({nmo},), not {self.eps.shape}!"
)
if _shape(self.V, 2, "V") != (nbf, nbf):
raise ValueError(
f"V should have shape ({nbf}, {nbf}) to match the AOs of C, "
f"not {self.V.shape}!"
)
if not 0 <= self.ndocc + self.nsocc <= nmo or min(self.ndocc, self.nsocc) < 0:
raise ValueError(
f"{self.ndocc} doubly and {self.nsocc} singly occupied orbitals do not "
f"fit in {nmo} orbitals!"
)

@property
def nbf(self) -> int:
"""Number of basis functions."""
return self.C.shape[0]

@property
def nmo(self) -> int:
"""Number of molecular orbitals."""
return self.C.shape[1]


class Backend(ABC):
"""
A reference calculation of a dimer by a quantum-chemistry code, with the operations
propSAPT needs from that code. Subclasses run the calculation and pass its results
to this constructor, which checks them.

Args:
reference (str): "RHF" or "RKS", see `check_reference`.
monomers (Mapping[str, MonomerReference]): SCFs of monomers "A" and "B".
S (np.ndarray): AO overlap matrix, (nbf, nbf).
Qpq (np.ndarray): Density-fitting factor of the two-electron integrals,
(naux, nbf, nbf), see the module conventions.
nuclear_repulsion (float): Repulsion of all nuclei of the dimer.
fragments (DimerFragments): Atoms and fragments of the dimer, in the frame of
the calculation.
functional (str | None, optional): Functional of an RKS reference, ignored for
other references. Defaults to None.
grac_A (float | None, optional): GRAC shift of monomer A. Defaults to None.
grac_B (float | None, optional): GRAC shift of monomer B. Defaults to None.

Raises:
ValueError: If the reference is not supported, or the arrays are inconsistent.
"""

def __init__(
self,
*,
reference: str,
monomers: Mapping[str, MonomerReference],
S: np.ndarray,
Qpq: np.ndarray,
nuclear_repulsion: float,
fragments: "DimerFragments",
functional: str | None = None,
grac_A: float | None = None,
grac_B: float | None = None,
):

self.reference = check_reference(reference)
self.functional = functional if reference == "RKS" else None
self.grac_A = grac_A
self.grac_B = grac_B

if set(monomers) != set(MONOMERS):
raise ValueError(
f"The monomers should be {list(MONOMERS)}, not {sorted(monomers)}!"
)
for label in MONOMERS:
if not isinstance(monomers[label], MonomerReference):
raise ValueError(
f"Monomer {label} should be a MonomerReference, "
f"not {type(monomers[label]).__name__}!"
)

nbf = _shape(S, 2, "S")[0]
if S.shape != (nbf, nbf):
raise ValueError(f"S should be square, but has shape {S.shape}!")
if _shape(Qpq, 3, "Qpq")[1:] != (nbf, nbf):
raise ValueError(
f"Qpq should have shape (naux, {nbf}, {nbf}) to match S, not {Qpq.shape}!"
)
for label in MONOMERS:
if monomers[label].nbf != nbf:
raise ValueError(
f"Monomer {label} has {monomers[label].nbf} basis functions, but "
f"the dimer has {nbf}: the monomers should use the dimer basis set!"
)
nmo_A, nmo_B = monomers["A"].nmo, monomers["B"].nmo
if nmo_A != nmo_B:
raise ValueError(
f"Monomer A has {nmo_A} orbitals and monomer B {nmo_B}, but they should "
"have the same number: both use the dimer basis set!"
)

self.monomers = dict(monomers)
self.S = S
self.Qpq = Qpq
self.nuclear_repulsion = nuclear_repulsion
self.fragments = fragments

@property
def nbf(self) -> int:
"""Number of basis functions of the dimer basis set."""
return self.S.shape[0]

@abstractmethod
def compute_jk(
self, lefts: Sequence[np.ndarray], rights: Sequence[np.ndarray]
) -> tuple[list[np.ndarray], list[np.ndarray]]:
"""
J and K matrices of the generalized densities ``D = C_left C_right^T``, in the
AO basis: ``J_mn = (mn|ls) D_ls`` and ``K_mn = (ml|ns) D_ls``. propSAPT passes
only pairs with at least one column on each side.

Args:
lefts (Sequence[np.ndarray]): C_left matrices, (nbf, k) each.
rights (Sequence[np.ndarray]): C_right matrices, one per C_left and with as
many columns, (nbf, k) each.

Returns:
tuple[list[np.ndarray], list[np.ndarray]]: The J and the K matrices, in the
order of the pairs.
"""

@abstractmethod
def orbital_hessian_product(
self, monomer: str, vectors: Sequence[np.ndarray], cpscf_jk: object = None
) -> list[np.ndarray]:
"""
Products of the orbital Hessian of a monomer with (ov) vectors, the left-hand
side of its CPSCF equations.

The Hessian is the symmetric positive definite one of a real singlet
perturbation, for RHF ::

H_{ar,a'r'} = (eps_r - eps_a) delta_{aa'} delta_{rr'}
+ 4 (ar|a'r') - (ar'|a'r) - (aa'|rr')

and for RKS with the exchange-correlation kernel too.

Args:
monomer (str): "A" or "B".
vectors (Sequence[np.ndarray]): (ov) vectors, (ndocc, nvirt) each.
cpscf_jk (object, optional): J/K object of `build_cpscf_jk` to build the
products with; None, the default, uses the J/K of the monomer SCF.

Returns:
list[np.ndarray]: The (ov) products, in the order of `vectors`.
"""

@abstractmethod
def dipole_integrals(self) -> list[np.ndarray]:
"""
Integrals of the electronic dipole operator, -r, in the AO basis, about the
origin of the dimer's frame, with the electron charge included, as in Psi4's
`ao_dipole`.

Returns:
list[np.ndarray]: The x, y and z components, (nbf, nbf) each.
"""

@abstractmethod
def nuclear_dipole(self) -> np.ndarray:
"""
Dipole moment of the dimer's nuclei, sum_A Z_A R_A, about the origin of the
dimer's frame. Ghost atoms carry no charge.

Returns:
np.ndarray: The x, y and z components, (3,).
"""

def build_cpscf_jk(self, cpscf_type: str, df_basis: str | None = None) -> object:
"""
J/K object for CPSCF solves of type `cpscf_type` (see the `cpscf_type` option),
to pass to `orbital_hessian_product`.

Args:
cpscf_type (str): "DIRECT" or "DF".
df_basis (str | None, optional): Fitting basis of "DF"; None, the default,
is the backend's default fitting basis.

Returns:
object: The J/K object, or None if the monomer SCF's J/K is of this type
already.

Raises:
NotImplementedError: If the backend has no CPSCF J/K types, as by default.
"""

raise NotImplementedError(
f"{type(self).__name__} has no CPSCF J/K types; "
"leave the `cpscf_type` option at None."
)

def clean_scratch(self) -> None:
"""Remove the files the backend keeps on disk between calculations, at the end
of a job such as `calc_sapt_energy`. Does nothing by default."""

def timer(self) -> AbstractContextManager[None]:
"""A context timed by the backend's own timers, if it has any; propSAPT logs its
own timings either way. By default, a context that does nothing."""

return nullcontext()


def _shape(array: np.ndarray, ndim: int, name: str) -> tuple[int, ...]:
"""Shape of `array`, checked to have `ndim` dimensions."""

if not isinstance(array, np.ndarray):
raise ValueError(
f"{name} should be a {ndim}-dimensional array, "
f"not a {type(array).__name__}!"
)
if array.ndim != ndim:
raise ValueError(
f"{name} should be a {ndim}-dimensional array, but has shape {array.shape}!"
)

return array.shape
Loading