diff --git a/AI-USAGE.md b/AI-USAGE.md index 0cdb3b9..8c57201 100644 --- a/AI-USAGE.md +++ b/AI-USAGE.md @@ -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. diff --git a/CHANGELOG.md b/CHANGELOG.md index 5927dc3..6c999ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/api.rst b/docs/api.rst index 305d69a..446dab4 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -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 ---------- diff --git a/docs/usage.rst b/docs/usage.rst index dbcf640..b960408 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -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 diff --git a/prop_sapt/backends/__init__.py b/prop_sapt/backends/__init__.py new file mode 100644 index 0000000..90f7d99 --- /dev/null +++ b/prop_sapt/backends/__init__.py @@ -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"] diff --git a/prop_sapt/backends/base.py b/prop_sapt/backends/base.py new file mode 100644 index 0000000..946965a --- /dev/null +++ b/prop_sapt/backends/base.py @@ -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 diff --git a/prop_sapt/backends/psi4_backend.py b/prop_sapt/backends/psi4_backend.py new file mode 100644 index 0000000..13431d6 --- /dev/null +++ b/prop_sapt/backends/psi4_backend.py @@ -0,0 +1,508 @@ +"""Psi4 as the backend of propSAPT. + +`Psi4Backend` runs the monomer SCFs of a dimer in the dimer-centred basis set and builds +the integrals propSAPT needs, as Psi4's own SAPT does. It keeps the Psi4 objects it made +(wavefunctions, `MintsHelper`, JK object), which a `Dimer` also exposes as compatibility +attributes (`wfnA`, `wfnB`, `mints`, ...). The Psi4 options in place when it is built +decide the calculation: `BASIS`, `DF_BASIS_SAPT`, `DF_BASIS_SCF`, `SCF_TYPE`, the +convergence thresholds, and Psi4's memory (`psi4.set_memory`). + +`Psi4OutputHandler` writes the records of the `prop_sapt` logger into Psi4's output +file, see `prop_sapt.log`. +""" + +import logging +import time +from collections.abc import Sequence +from contextlib import contextmanager +from functools import wraps +from typing import Iterator, Literal, overload + +import numpy as np +import opt_einsum as oe +import psi4 +from psi4.driver.p4util import message_box, OptionsState, OptionsStateCM + +from ..fragments import DimerFragments +from .base import MONOMERS, Backend, MonomerReference, check_reference + +logger = logging.getLogger(__name__) + + +@overload +def psi4_energy(name: str, return_wfn: Literal[False] = False, **kwargs) -> float: ... + + +@overload +def psi4_energy( + name: str, return_wfn: Literal[True], **kwargs +) -> tuple[float, psi4.core.Wavefunction]: ... + + +@wraps(psi4.energy) +def psi4_energy( + name: str, return_wfn: bool = False, **kwargs +) -> float | tuple[float, psi4.core.Wavefunction]: + # SAVE_JK keeps the JK object on the wavefunction, which CPSCF (`cphf_Hx`) needs; + # the user's setting is restored afterwards, as Psi4's own SAPT does + optstash = OptionsState(["SAVE_JK"], ["SCF", "SAVE_JK"]) + try: + psi4.core.set_global_option("SAVE_JK", True) + psi4.core.set_local_option("SCF", "SAVE_JK", True) + return psi4.energy(name, return_wfn=return_wfn, **kwargs) + finally: + optstash.restore() + + +def jk_memory_doubles(memory: float | None = None) -> int: + """Memory of the JK object `Psi4Backend` builds, in doubles, the unit of + `JK.set_memory`. + + Args: + memory (float | None, optional): Memory in GB, from the deprecated + `Dimer(memory=...)`. None, the default, takes Psi4's memory + (`psi4.set_memory`) times `SCF_MEM_SAFETY_FACTOR`, as Psi4's SCF does for + its own JK object. + + Returns: + int: Memory in doubles (8 bytes each). + """ + + if memory is None: + safety_factor = psi4.core.get_global_option("SCF_MEM_SAFETY_FACTOR") + memory_bytes = psi4.get_memory() * safety_factor + else: + memory_bytes = memory * 1e9 + + return int(memory_bytes / 8) + + +def changed_psi4_options() -> dict | None: + """The Psi4 options changed from their defaults, None if Psi4 cannot list them.""" + + try: + from psi4.driver.p4util import prepare_options_for_set_options + except ImportError: + return None + + return prepare_options_for_set_options() + + +class Psi4OutputFormatter(logging.Formatter): + """The message alone, after its level ("Warning: ...") for warnings and errors.""" + + def format(self, record: logging.LogRecord) -> str: + text = super().format(record) + if record.levelno >= logging.WARNING: + return f"{record.levelname.capitalize()}: {text}" + + return text + + +class Psi4OutputHandler(logging.Handler): + """Writes each log record into Psi4's output file, ended by a newline. `prop_sapt.log` + gives it the records of the `prop_sapt` logger.""" + + # marks the handler of this module across reloads, which create a new class + _prop_sapt_psi4_output = True + + def __init__(self, level: int = logging.NOTSET): + super().__init__(level) + self.setFormatter(Psi4OutputFormatter()) + + def emit(self, record: logging.LogRecord): + try: + psi4.core.print_out(self.format(record) + "\n") + except Exception: + self.handleError(record) + + +class Psi4Backend(Backend): + """ + Psi4's reference calculation of a dimer: the SCFs of monomers A and B in the + dimer-centred basis set, the integrals of the dimer and Psi4's J/K objects. + + Building it runs the calculation: the geometry becomes Psi4's active molecule, and + the SCFs follow the Psi4 options in place. The dimer is kept in its input frame (no + reorientation, symmetry c1). + + Attributes: + molecule (psi4.core.Molecule): The dimer. + wavefunctions (dict[str, psi4.core.Wavefunction]): Monomer SCF wavefunctions by + monomer, "A" and "B". + dimer_wfn (psi4.core.Wavefunction): Wavefunction of the dimer basis set, without + an SCF. + mints (psi4.core.MintsHelper): Integrals of the dimer basis set. + jk (psi4.core.JK): J/K object of the dimer basis set (density fitted in + `DF_BASIS_SCF` or exact, as `SCF_TYPE` says). + jk_memory (int): Memory of the J/K objects, in doubles. + memory (float): The same in GB. + psi4_options (dict | None): The Psi4 options changed from their defaults when + the dimer was built, before the SCFs changed any. + fitting_bases (dict[str, str]): The fitting basis sets as built + (``basis.blend()``), by option: "DF_BASIS_SAPT" and "DF_BASIS_SCF". + + Args: + geometry (str): Dimer geometry in Psi4 format, with monomers A and B as its + first two fragments; any further fragments are ghost atoms. + reference (str, optional): "RHF" or "RKS". Defaults to "RHF". + functional (str | None, optional): Functional of an RKS reference, required for + it. Defaults to None. + grac_A (float | None, optional): GRAC shift of monomer A (Psi4's + `dft_grac_shift`). Defaults to no shift. + grac_B (float | None, optional): GRAC shift of monomer B. Defaults to no shift. + memory (float | None, optional): Memory of the J/K objects in GB, see + `jk_memory_doubles`. Defaults to Psi4's memory. + + Raises: + ValueError: If frozen core is set, the reference is not supported or is RKS + without a functional, the geometry has fewer than two fragments, or a + monomer is not a singlet; all before any SCF is run. + """ + + def __init__( + self, + geometry: str, + reference: str = "RHF", + *, + functional: str | None = None, + grac_A: float | None = None, + grac_B: float | None = None, + memory: float | None = None, + ): + + tstart_backend = time.time() + + # create Psi4 Molecule object + dimer = psi4.geometry(geometry) + dimer.print_out_in_angstrom() + self.molecule = dimer + + # the Psi4 options the dimer is built with, before the monomer SCFs change any + self.psi4_options = changed_psi4_options() + + # propSAPT is all-electron: reject frozen core instead of ignoring it + if psi4.core.get_global_option("FREEZE_CORE") not in ("FALSE", "0"): + raise ValueError( + "propSAPT does not support frozen core; set FREEZE_CORE to false." + ) + + check_reference(reference) + if reference == "RKS" and functional is None: + raise ValueError("An RKS reference needs a functional.") + + dimer.reset_point_group("c1") + dimer.fix_orientation(True) + dimer.fix_com(True) + dimer.update_geometry() + nfrags = dimer.nfragments() + + if nfrags < 2: + raise ValueError(f"Found {nfrags:d} fragments, must be at least 2.") + elif nfrags > 2: + logger.info( + f"Found {nfrags:d} fragments, using first 2 as monomers, " + "and the rest as extra basis functions (ghosts)." + ) + + # Grab monomers in DCBS + monomerA = dimer.extract_subsets(1, [i for i in range(2, nfrags + 1)]) + monomerA.set_name("monomerA") + monomerB = dimer.extract_subsets(2, [1] + [i for i in range(3, nfrags + 1)]) + monomerB.set_name("monomerB") + monomer_molecules = {"A": monomerA, "B": monomerB} + + # closed-shell references only, fail before any SCF is run + for label in MONOMERS: + mult = monomer_molecules[label].multiplicity() + if mult != 1: + raise ValueError( + f"Monomer {label} has multiplicity {mult}, " + f"{reference} reference requires singlet monomers." + ) + + # Compute monomer properties + grac = {"A": grac_A, "B": grac_B} + energies = {} + potentials = {} + self.wavefunctions = {} + for label in MONOMERS: + logger.info(message_box(f"Monomer {label} {reference}").strip("\n")) + tstart = time.time() + if reference == "RHF": + energies[label], self.wavefunctions[label] = psi4_energy( + "SCF", return_wfn=True, molecule=monomer_molecules[label] + ) + elif reference == "RKS": + with OptionsStateCM(["dft_grac_shift"]): + if grac[label]: + psi4.set_options({"dft_grac_shift": grac[label]}) + else: + logger.warning( + f"GRAC shift for monomer {label} not specified; " + "running without GRAC." + ) + energies[label], self.wavefunctions[label] = psi4_energy( + functional, return_wfn=True, molecule=monomer_molecules[label] + ) + potentials[label] = np.asarray( + psi4.core.MintsHelper( + self.wavefunctions[label].basisset() + ).ao_potential() + ) + logger.info( + f"{reference} for monomer {label} finished in " + f"{time.time() - tstart:.2f} seconds." + ) + + # Setup a few variables + self.jk_memory = jk_memory_doubles(memory) # in doubles + self.memory = self.jk_memory * 8 / 1e9 # the same in GB + + monomers = {} + for label in MONOMERS: + wfn = self.wavefunctions[label] + monomers[label] = MonomerReference( + C=np.asarray(wfn.Ca()), + eps=np.asarray(wfn.epsilon_a()), + ndocc=wfn.doccpi()[0], + V=potentials[label], + energy=energies[label], + nuclear_repulsion=monomer_molecules[label].nuclear_repulsion_energy(), + ) + + ### Compute DF ERIs for dimer basis + tstart = time.time() + logger.info("Compute DF integrals for dimer-centered basis...") + + self.dimer_wfn = psi4.core.Wavefunction.build( + dimer, psi4.core.get_global_option("BASIS") + ) + self.mints = psi4.core.MintsHelper(self.dimer_wfn.basisset()) + + # DF integrals in AO + aux_basis = psi4.core.BasisSet.build( + self.dimer_wfn.molecule(), + target=psi4.core.get_global_option("DF_BASIS_SAPT"), + other=psi4.core.get_global_option("DF_BASIS_SAPT"), + fitrole="RIFIT", + ) + aux_basis.print_out() + # the fitting bases as built, not the options naming them + self.fitting_bases = {"DF_BASIS_SAPT": aux_basis.blend()} + zero_basis = psi4.core.BasisSet.zero_ao_basis_set() + metric = self.mints.ao_eri(aux_basis, zero_basis, aux_basis, zero_basis) + metric.power(-0.5, 1.0e-14) + metric = np.squeeze(metric) + Ppq = self.mints.ao_eri( + aux_basis, + zero_basis, + self.dimer_wfn.basisset(), + self.dimer_wfn.basisset(), + ) + Ppq = np.squeeze(Ppq) + Qpq = np.array(oe.contract("QP,Ppq->Qpq", metric, Ppq)) + + logger.info(f"... DF integrals finished in {time.time() - tstart:.2f} seconds.") + + # JK object + logger.info("Initialize JK objects...") + tstart = time.time() + aux_basis = psi4.core.BasisSet.build( + self.dimer_wfn.molecule(), + "DF_BASIS_SCF", + psi4.core.get_option("SCF", "DF_BASIS_SCF"), + "JKFIT", + psi4.core.get_global_option("BASIS"), + puream=self.dimer_wfn.basisset().has_puream(), + ) + self.fitting_bases["DF_BASIS_SCF"] = aux_basis.blend() + # also the default fitting basis of the "DF" CPSCF, see `build_cpscf_jk` + self._df_basis_scf = aux_basis + + self.jk = psi4.core.JK.build(self.dimer_wfn.basisset(), aux_basis) + self.jk.set_memory(self.jk_memory) + self.jk.initialize() + logger.info(f"...initialized JK objects in {time.time() - tstart:.2f} seconds.") + + # Overlap matrix in AO + S = np.asarray(self.mints.ao_overlap()) + + super().__init__( + reference=reference, + monomers=monomers, + S=S, + Qpq=Qpq, + nuclear_repulsion=dimer.nuclear_repulsion_energy(), + fragments=DimerFragments.from_molecule(dimer), + functional=functional, + grac_A=grac_A, + grac_B=grac_B, + ) + + logger.info( + f"...finished the Psi4 calculations in " + f"{time.time() - tstart_backend:5.2f} seconds." + ) + + @property + def basisset(self) -> psi4.core.BasisSet: + """The dimer basis set, the one the backend was built with.""" + + return self.dimer_wfn.basisset() + + 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 pairs (C_left, C_right), with the J/K object `jk`, see + `Backend.compute_jk`.""" + + # the J/K object keeps its inputs until cleared: a failed build must not leave + # them for the next one, which would return their J and K matrices too + try: + for Cl, Cr in zip(lefts, rights): + self.jk.C_left_add(psi4.core.Matrix.from_array(Cl)) + self.jk.C_right_add(psi4.core.Matrix.from_array(Cr)) + + self.jk.compute() + + J_list = [np.array(J) for J in self.jk.J()] + K_list = [np.array(K) for K in self.jk.K()] + finally: + self.jk.C_clear() + + return J_list, K_list + + def orbital_hessian_product( + self, + monomer: str, + vectors: Sequence[np.ndarray], + cpscf_jk: psi4.core.JK | None = None, + ) -> list[np.ndarray]: + """Products of the orbital Hessian of `monomer` with (ov) `vectors`, see + `Backend.orbital_hessian_product`. Psi4's `cphf_Hx` gives them, with the + opposite sign, taking the J and K matrices from the monomer wavefunction's J/K + object; `cpscf_jk` takes its place for the call.""" + + wfn = self.wavefunctions[monomer] + matrices = [ + psi4.core.Matrix.from_array(np.ascontiguousarray(x)) for x in vectors + ] + + # `cphf_Hx` takes the J and K matrices from the wavefunction's J/K object + swap_jk = cpscf_jk is not None + if swap_jk: + scf_jk = wfn.jk() + wfn.set_jk(cpscf_jk) + + try: + products = wfn.cphf_Hx(matrices) + finally: + if swap_jk: + wfn.set_jk(scf_jk) + + return [-np.asarray(product) for product in products] + + def build_cpscf_jk( + self, cpscf_type: str, df_basis: str | None = None + ) -> psi4.core.JK | None: + """ + J/K object for CPSCF solves of type `cpscf_type`, shared by both monomers, see + `Backend.build_cpscf_jk`. + + It is set up as Psi4's SCF sets up its own (`initialize_jk`), with the memory of + the backend's J/K object, `jk_memory`. The "DF" one is MemDFJK if it fits in + that memory and DiskDFJK otherwise, as for Psi4's `SCF_TYPE` "DF". + + Args: + cpscf_type (str): "DIRECT" or "DF". + df_basis (str | None, optional): Fitting basis of "DF". Defaults to the + dimer's `DF_BASIS_SCF` fitting basis (see `fitting_bases`): the one of + Psi4's `DF_BASIS_SCF` when the dimer was built, or else the JKFIT basis + of its orbital basis. + + Returns: + psi4.core.JK | None: The J/K object, or None if the monomer SCF's J/K + objects are of this type already ("DF" only without `df_basis`). + """ + + scf_jk_names = {wfn.jk().name() for wfn in self.wavefunctions.values()} + if cpscf_type == "DIRECT" and scf_jk_names == {"DirectJK"}: + return None + if ( + cpscf_type == "DF" + and df_basis is None + and scf_jk_names <= {"MemDFJK", "DiskDFJK"} + ): + return None + + # the monomers share the dimer basis set (ghost atoms), as in Psi4's SAPT + wfn = self.wavefunctions["A"] + aux = None + if cpscf_type == "DF" and df_basis is None: + aux = self._df_basis_scf + elif cpscf_type == "DF": + # a named fitting basis covers every atom; Psi4 only needs a valid orbital + # basis name next to it, the dimer's, not the options at this solve + aux = psi4.core.BasisSet.build( + wfn.molecule(), + "DF_BASIS_SCF", + df_basis, + "JKFIT", + wfn.basisset().name(), + puream=wfn.basisset().has_puream(), + ) + + tstart = time.time() + logger.info(f"Initialize the {cpscf_type} J/K object of CPSCF...") + jk = psi4.core.JK.build( + wfn.basisset(), + aux=aux, + jk_type=cpscf_type, + do_wK=wfn.functional().is_x_lrc(), + memory=self.jk_memory, + ) + + # `initialize_jk` also puts the J/K object on the wavefunction + scf_jk = wfn.jk() + try: + wfn.initialize_jk(self.jk_memory, jk=jk) + finally: + wfn.set_jk(scf_jk) + + fitting = f", fitting basis {aux.name()} ({aux.nbf()} functions)" if aux else "" + logger.info( + f"...initialized {jk.name()}{fitting} in {time.time() - tstart:.2f} seconds." + ) + + return jk + + def dipole_integrals(self) -> list[np.ndarray]: + """AO dipole integrals (`MintsHelper.ao_dipole`), see + `Backend.dipole_integrals`.""" + + return [np.asarray(component) for component in self.mints.ao_dipole()] + + def nuclear_dipole(self) -> np.ndarray: + """Nuclear dipole moment (`Molecule.nuclear_dipole`), see + `Backend.nuclear_dipole`.""" + + dipole = self.molecule.nuclear_dipole() + return np.array([dipole[0], dipole[1], dipole[2]]) + + @staticmethod + def clean_scratch() -> None: + """Remove Psi4's scratch files (`psi4.core.clean`).""" + + psi4.core.clean() + + @staticmethod + @contextmanager + def timer() -> Iterator[None]: + """Context between Psi4's `tstart` and `tstop`, which write the time it took into + Psi4's output file. Psi4 has one such timer: a nested context restarts it.""" + + psi4.core.tstart() + # no tstop for a calculation that raised, as before propSAPT had backends + yield + psi4.core.tstop() diff --git a/prop_sapt/config.py b/prop_sapt/config.py index 9f515ad..1e338b9 100644 --- a/prop_sapt/config.py +++ b/prop_sapt/config.py @@ -74,7 +74,7 @@ class ConfigError(ValueError): """Raised when a run configuration cannot be read or is invalid.""" -# References the propSAPT code can run (see `helper_SAPT.__init__`). +# References the propSAPT code can run (see `prop_sapt.backends.check_reference`). SUPPORTED_REFERENCES = ("RHF", "RKS") # Psi4 options the runner sets itself, from `basis`, `df_basis` and the `save_jk` requirement. diff --git a/prop_sapt/fragments.py b/prop_sapt/fragments.py index 2172d5b..028f84c 100644 --- a/prop_sapt/fragments.py +++ b/prop_sapt/fragments.py @@ -368,7 +368,7 @@ def parse_fragments(geometry: str | os.PathLike) -> DimerFragments: molecule = psi4.core.Molecule.from_string(geometry) - # the frame of `helper_SAPT.__init__`: input orientation (centered by Psi4 unless + # the frame of `Psi4Backend`: input orientation (centered by Psi4 unless # `no_com`), symmetry not imposed molecule.reset_point_group("c1") molecule.fix_orientation(True) diff --git a/prop_sapt/helper_SAPT_DF.py b/prop_sapt/helper_SAPT_DF.py index 32fd7c1..d2518e0 100644 --- a/prop_sapt/helper_SAPT_DF.py +++ b/prop_sapt/helper_SAPT_DF.py @@ -52,87 +52,30 @@ import logging import time from typing import overload, Literal, Any -from functools import wraps import numpy as np import opt_einsum as oe -import psi4 -from psi4.driver.p4util import message_box, OptionsState, OptionsStateCM +from .backends.base import Backend from .cpscf_solver import conjugate_gradient from .options import PROPSAPT_OPTIONS, check_cpscf_type, check_df_basis_cpscf logger = logging.getLogger(__name__) -@overload -def psi4_energy(name: str, return_wfn: Literal[False] = False, **kwargs) -> float: ... - - -@overload -def psi4_energy( - name: str, return_wfn: Literal[True], **kwargs -) -> tuple[float, psi4.core.Wavefunction]: ... - - -@wraps(psi4.energy) -def psi4_energy( - name: str, return_wfn: bool = False, **kwargs -) -> float | tuple[float, psi4.core.Wavefunction]: - # SAVE_JK keeps the JK object on the wavefunction, which CPSCF (`cphf_Hx`) needs; - # the user's setting is restored afterwards, as Psi4's own SAPT does - optstash = OptionsState(["SAVE_JK"], ["SCF", "SAVE_JK"]) - try: - psi4.core.set_global_option("SAVE_JK", True) - psi4.core.set_local_option("SCF", "SAVE_JK", True) - return psi4.energy(name, return_wfn=return_wfn, **kwargs) - finally: - optstash.restore() - - -def jk_memory_doubles(memory: float | None = None) -> int: - """Memory of the JK object `helper_SAPT` builds, in doubles, the unit of - `JK.set_memory`. +class helper_SAPT(object): + """ + The arrays of a dimer that the SAPT contractions use, from a reference calculation + of the dimer by a backend (see `prop_sapt.backends`): orbitals, orbital energies, + potentials and overlaps of the monomers, and density-fitted integrals. The J/K builds + and CPSCF solves also go through the backend. Args: - memory (float | None, optional): Memory in GB, from the deprecated - `Dimer(memory=...)`. None, the default, takes Psi4's memory - (`psi4.set_memory`) times `SCF_MEM_SAFETY_FACTOR`, as Psi4's SCF does for - its own JK object. - - Returns: - int: Memory in doubles (8 bytes each). + backend (Backend): The reference calculation, kept as `backend`. """ - if memory is None: - safety_factor = psi4.core.get_global_option("SCF_MEM_SAFETY_FACTOR") - memory_bytes = psi4.get_memory() * safety_factor - else: - memory_bytes = memory * 1e9 + def __init__(self, backend: Backend): - return int(memory_bytes / 8) - - -class helper_SAPT(object): - def __init__(self, dimer, reference="RHF", memory=None, **kwargs): - - # propSAPT is all-electron: reject frozen core instead of ignoring it - if psi4.core.get_global_option("FREEZE_CORE") not in ("FALSE", "0"): - raise ValueError( - "propSAPT does not support frozen core; set FREEZE_CORE to false." - ) - - # Verify 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.") - - # Check if the functional is specified for DFT - dft_functional = kwargs.get( - "functional", PROPSAPT_OPTIONS["default_functional"] - ) + reference = backend.reference # Initialize time tinit_start = time.time() @@ -146,105 +89,42 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): logger.info(f"Selected reference is {reference}") # Set a few crucial attributes - self.reference = reference.upper() + self.backend = backend + self.reference = reference # DFT settings, recorded in the output artifacts - self.functional = dft_functional if self.reference == "RKS" else None - self.grac_A = kwargs.get("grac_A") - self.grac_B = kwargs.get("grac_B") - dimer.reset_point_group("c1") - dimer.fix_orientation(True) - dimer.fix_com(True) - dimer.update_geometry() - nfrags = dimer.nfragments() - - if nfrags < 2: - raise ValueError(f"Found {nfrags:d} fragments, must be at least 2.") - elif nfrags > 2: - logger.info( - f"Found {nfrags:d} fragments, using first 2 as monomers, " - "and the rest as extra basis functions (ghosts)." - ) + self.functional = backend.functional + self.grac_A = backend.grac_A + self.grac_B = backend.grac_B - # Grab monomers in DCBS - monomerA = dimer.extract_subsets(1, [i for i in range(2, nfrags + 1)]) - monomerA.set_name("monomerA") - monomerB = dimer.extract_subsets(2, [1] + [i for i in range(3, nfrags + 1)]) - monomerB.set_name("monomerB") - self.mult_A = monomerA.multiplicity() - self.mult_B = monomerB.multiplicity() - - # closed-shell references only, fail before any SCF is run - for label, mult in (("A", self.mult_A), ("B", self.mult_B)): - if mult != 1: - raise ValueError( - f"Monomer {label} has multiplicity {mult}, " - f"{reference} reference requires singlet monomers." - ) - - # Compute monomer properties - logger.info(message_box(f"Monomer A {reference}").strip("\n")) - tstart = time.time() - if reference == "RHF": - self.rhfA, self.wfnA = psi4_energy( - "SCF", return_wfn=True, molecule=monomerA - ) - elif reference == "RKS": - with OptionsStateCM(["dft_grac_shift"]): - if kwargs.get("grac_A"): - psi4.set_options({"dft_grac_shift": kwargs["grac_A"]}) - else: - logger.warning( - "GRAC shift for monomer A not specified; running without GRAC." - ) - self.dftA, self.wfnA = psi4_energy( - dft_functional, return_wfn=True, molecule=monomerA - ) - self.V_A = np.asarray( - psi4.core.MintsHelper(self.wfnA.basisset()).ao_potential() - ) - logger.info( - f"{reference} for monomer A finished in {time.time() - tstart:.2f} seconds." - ) + self.fragments = backend.fragments + self.mult_A = backend.fragments.A.multiplicity + self.mult_B = backend.fragments.B.multiplicity + + monomer_A = backend.monomers["A"] + monomer_B = backend.monomers["B"] - logger.info(message_box(f"Monomer B {reference}").strip("\n")) - tstart = time.time() + # SCF energies of the monomers if reference == "RHF": - self.rhfB, self.wfnB = psi4_energy( - "SCF", return_wfn=True, molecule=monomerB - ) + self.rhfA, self.rhfB = monomer_A.energy, monomer_B.energy elif reference == "RKS": - with OptionsStateCM(["dft_grac_shift"]): - if kwargs.get("grac_B"): - psi4.set_options({"dft_grac_shift": kwargs["grac_B"]}) - else: - logger.warning( - "GRAC shift for monomer B not specified; running without GRAC." - ) - self.dftB, self.wfnB = psi4_energy( - dft_functional, return_wfn=True, molecule=monomerB - ) - self.V_B = np.asarray( - psi4.core.MintsHelper(self.wfnB.basisset()).ao_potential() - ) - logger.info( - f"{reference} for monomer B finished in {time.time() - tstart:.2f} seconds." - ) + self.dftA, self.dftB = monomer_A.energy, monomer_B.energy + + self.V_A = monomer_A.V + self.V_B = monomer_B.V # Setup a few variables - self.jk_memory = jk_memory_doubles(memory) # in doubles - self.memory = self.jk_memory * 8 / 1e9 # the same in GB - self.nmo = self.wfnA.nmo() - self.nbf = self.wfnA.basisset().nbf() + self.nmo = monomer_A.nmo + self.nbf = backend.nbf # Monomer A - self.nuc_rep_A = monomerA.nuclear_repulsion_energy() - self.ndocc_A = self.wfnA.doccpi()[0] + self.nuc_rep_A = monomer_A.nuclear_repulsion + self.ndocc_A = monomer_A.ndocc self.nvirt_A = self.nmo - self.ndocc_A if reference == "ROHF": self.idx_A = ["i", "a", "r"] - self.nsocc_A = self.wfnA.soccpi()[0] + self.nsocc_A = monomer_A.nsocc occA = self.ndocc_A + self.nsocc_A elif reference == "UHF" or reference == "UKS": @@ -258,20 +138,20 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): else: raise ValueError(f"Unknown reference type: {reference}.") - self.C_A = np.asarray(self.wfnA.Ca()) + self.C_A = monomer_A.C self.Co_A = self.C_A[:, : self.ndocc_A] self.Ca_A = self.C_A[:, self.ndocc_A : occA] self.Cv_A = self.C_A[:, occA:] - self.eps_A = np.asarray(self.wfnA.epsilon_a()) + self.eps_A = monomer_A.eps # Monomer B - self.nuc_rep_B = monomerB.nuclear_repulsion_energy() - self.ndocc_B = self.wfnB.doccpi()[0] - self.nvirt_B = self.nmo - self.ndocc_B + self.nuc_rep_B = monomer_B.nuclear_repulsion + self.ndocc_B = monomer_B.ndocc + self.nvirt_B = monomer_B.nmo - self.ndocc_B if reference == "ROHF": self.idx_B = ["j", "b", "s"] - self.nsocc_B = self.wfnB.soccpi()[0] + self.nsocc_B = monomer_B.nsocc occB = self.ndocc_B + self.nsocc_B elif reference == "UHF" or reference == "UKS": @@ -285,16 +165,14 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): else: raise ValueError(f"Unknown reference type: {reference}.") - self.C_B = np.asarray(self.wfnB.Ca()) + self.C_B = monomer_B.C self.Co_B = self.C_B[:, : self.ndocc_B] self.Ca_B = self.C_B[:, self.ndocc_B : occB] self.Cv_B = self.C_B[:, occB:] - self.eps_B = np.asarray(self.wfnB.epsilon_a()) + self.eps_B = monomer_B.eps # Dimer - self.nuc_rep = ( - dimer.nuclear_repulsion_energy() - self.nuc_rep_A - self.nuc_rep_B - ) + self.nuc_rep = backend.nuclear_repulsion - self.nuc_rep_A - self.nuc_rep_B self.vt_nuc_rep = self.nuc_rep / ( (2 * self.ndocc_A + self.nsocc_A) * (2 * self.ndocc_B + self.nsocc_B) ) @@ -358,61 +236,11 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): f"Number of molecular orbitals per type:\n{rule}\n{labels}\n{rule}\n{counts}" ) - ### Compute DF ERIs for dimer basis - tstart = time.time() - logger.info("Compute DF integrals for dimer-centered basis...") - - self.dimer_wfn = psi4.core.Wavefunction.build( - dimer, psi4.core.get_global_option("BASIS") - ) - mints = psi4.core.MintsHelper(self.dimer_wfn.basisset()) - self.mints = mints - - # DF integrals in AO - aux_basis = psi4.core.BasisSet.build( - self.dimer_wfn.molecule(), - target=psi4.core.get_global_option("DF_BASIS_SAPT"), - other=psi4.core.get_global_option("DF_BASIS_SAPT"), - fitrole="RIFIT", - ) - aux_basis.print_out() - self.nao_aux = aux_basis.nao() - # the fitting bases as built, not the options naming them - self.fitting_bases = {"DF_BASIS_SAPT": aux_basis.blend()} - zero_basis = psi4.core.BasisSet.zero_ao_basis_set() - metric = self.mints.ao_eri(aux_basis, zero_basis, aux_basis, zero_basis) - metric.power(-0.5, 1.0e-14) - metric = np.squeeze(metric) - Ppq = self.mints.ao_eri( - aux_basis, - zero_basis, - self.dimer_wfn.basisset(), - self.dimer_wfn.basisset(), - ) - Ppq = np.squeeze(Ppq) - self.Qpq = np.array(oe.contract("QP,Ppq->Qpq", metric, Ppq)) - - logger.info(f"... DF integrals finished in {time.time() - tstart:.2f} seconds.") - - # JK object - logger.info("Initialize JK objects...") - tstart = time.time() - aux_basis = psi4.core.BasisSet.build( - self.dimer_wfn.molecule(), - "DF_BASIS_SCF", - psi4.core.get_option("SCF", "DF_BASIS_SCF"), - "JKFIT", - psi4.core.get_global_option("BASIS"), - puream=self.dimer_wfn.basisset().has_puream(), - ) - self.fitting_bases["DF_BASIS_SCF"] = aux_basis.blend() - # also the default fitting basis of the "DF" CPSCF, see `build_cpscf_jk` - self._df_basis_scf = aux_basis - - self.jk = psi4.core.JK.build(self.dimer_wfn.basisset(), aux_basis) - self.jk.set_memory(self.jk_memory) - self.jk.initialize() - logger.info(f"...initialized JK objects in {time.time() - tstart:.2f} seconds.") + ### DF ERIs and the overlap of the dimer basis + self.Qpq = backend.Qpq + # number of functions of the SAPT fitting basis (spherical ones if it is) + self.naux = self.Qpq.shape[0] + self.S = backend.S self.J_A, self.K_A = self.compute_jk(self.Co_A, self.Co_A) self.J_B, self.K_B = self.compute_jk(self.Co_B, self.Co_B) @@ -420,9 +248,6 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): # J/K object of the CPSCF solves, see `build_cpscf_jk`; None uses the monomer SCF's self.cpscf_jk = None - # Overlap matrix in AO - self.S = np.asarray(self.mints.ao_overlap()) - # Save additional rank 2 tensors self.V_A_BB = oe.contract("ui,vj,uv->ij", self.C_B, self.C_B, self.V_A) self.V_A_AB = oe.contract("ui,vj,uv->ij", self.C_A, self.C_B, self.V_A) @@ -620,9 +445,9 @@ def orbital_hessian_product( 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 the exchange-correlation kernel too. Its J and K matrices come from - the J/K object of the monomer SCF, or from `cpscf_jk` if it is set (see - `build_cpscf_jk`). Psi4's `cphf_Hx` gives the products, with the opposite sign. + and for RKS the exchange-correlation kernel too. The backend builds the + products (`Backend.orbital_hessian_product`), with the J/K of the monomer SCF, + or of `cpscf_jk` if it is set (see `build_cpscf_jk`). Args: monomer (str): "A" or "B". @@ -637,47 +462,26 @@ def orbital_hessian_product( if len(vectors) == 0: return [] - wfn = self.wfnA if monomer == "A" else self.wfnB - matrices = [ - psi4.core.Matrix.from_array(np.ascontiguousarray(x)) for x in vectors - ] - - # `cphf_Hx` takes the J and K matrices from the wavefunction's J/K object - swap_jk = self.cpscf_jk is not None - if swap_jk: - scf_jk = wfn.jk() - wfn.set_jk(self.cpscf_jk) - - try: - products = wfn.cphf_Hx(matrices) - finally: - if swap_jk: - wfn.set_jk(scf_jk) - - return [-np.asarray(product) for product in products] + return self.backend.orbital_hessian_product(monomer, vectors, self.cpscf_jk) def build_cpscf_jk( self, cpscf_type: str | None, df_basis: str | None = None - ) -> psi4.core.JK | None: + ) -> object: """ - J/K object for CPSCF solves of type `cpscf_type`, shared by both monomers. - - It is set up as Psi4's SCF sets up its own (`initialize_jk`), with the memory of - propSAPT's J/K object, `jk_memory`. `cpscf_batch` uses it in place of the - monomer SCF's J/K object while it is `cpscf_jk`. The "DF" one is MemDFJK if it - fits in that memory and DiskDFJK otherwise, as for Psi4's `SCF_TYPE` "DF". + J/K object for CPSCF solves of type `cpscf_type`, shared by both monomers, from + the backend (`Backend.build_cpscf_jk`). `cpscf_batch` uses it in place of the + monomer SCF's J/K while it is `cpscf_jk`. Args: cpscf_type (str | None): "DIRECT" or "DF", case-insensitive, see the `cpscf_type` option; None stands for the monomer SCF's J/K objects. df_basis (str | None, optional): Fitting basis of "DF". Defaults to the - dimer's `DF_BASIS_SCF` fitting basis (see `fitting_bases`): the one of - Psi4's `DF_BASIS_SCF` when the dimer was built, or else the JKFIT basis - of its orbital basis. + backend's default, for Psi4 the dimer's `DF_BASIS_SCF` fitting basis + (see `fitting_bases`). Returns: - psi4.core.JK | None: The J/K object, or None if the monomer SCF's J/K - objects are of this type already ("DF" only without `df_basis`). + object: The J/K object, or None if the monomer SCF's J/K objects are of + this type already ("DF" only without `df_basis`). """ cpscf_type = check_cpscf_type(cpscf_type) @@ -686,56 +490,7 @@ def build_cpscf_jk( if cpscf_type is None: return None - scf_jk_names = {self.wfnA.jk().name(), self.wfnB.jk().name()} - if cpscf_type == "DIRECT" and scf_jk_names == {"DirectJK"}: - return None - if ( - cpscf_type == "DF" - and df_basis is None - and scf_jk_names <= {"MemDFJK", "DiskDFJK"} - ): - return None - - # the monomers share the dimer basis set (ghost atoms), as in Psi4's SAPT - wfn = self.wfnA - aux = None - if cpscf_type == "DF" and df_basis is None: - aux = self._df_basis_scf - elif cpscf_type == "DF": - # a named fitting basis covers every atom; Psi4 only needs a valid orbital - # basis name next to it, the dimer's, not the options at this solve - aux = psi4.core.BasisSet.build( - wfn.molecule(), - "DF_BASIS_SCF", - df_basis, - "JKFIT", - wfn.basisset().name(), - puream=wfn.basisset().has_puream(), - ) - - tstart = time.time() - logger.info(f"Initialize the {cpscf_type} J/K object of CPSCF...") - jk = psi4.core.JK.build( - wfn.basisset(), - aux=aux, - jk_type=cpscf_type, - do_wK=wfn.functional().is_x_lrc(), - memory=self.jk_memory, - ) - - # `initialize_jk` also puts the J/K object on the wavefunction - scf_jk = wfn.jk() - try: - wfn.initialize_jk(self.jk_memory, jk=jk) - finally: - wfn.set_jk(scf_jk) - - fitting = f", fitting basis {aux.name()} ({aux.nbf()} functions)" if aux else "" - logger.info( - f"...initialized {jk.name()}{fitting} in {time.time() - tstart:.2f} seconds." - ) - - return jk + return self.backend.build_cpscf_jk(cpscf_type, df_basis) def _check_cpscf(self, monomer): """Raises ValueError unless CPSCF is implemented for this reference and `monomer`.""" @@ -768,6 +523,25 @@ def transform_ao_to_mo(self, x, string): return self.orbitals[string[0]].T.dot(x).dot(self.orbitals[string[1]]) def compute_jk(self, Cleft, Cright, tensor=None): + """ + J and K matrices of generalized densities D = C_left C_right^T, or + D = C_left M C_right^T with M given as `tensor`, from the backend + (`Backend.compute_jk`). + + M is folded into the side with fewer columns. A pair with no columns on a side + gets zero matrices without reaching the backend. + + Args: + Cleft (np.ndarray | list[np.ndarray]): C_left matrix, (nbf, k), or a list. + Cright (np.ndarray | list[np.ndarray]): C_right matrix, (nbf, l), or a list + as long as `Cleft`. + tensor (np.ndarray | list[np.ndarray] | None, optional): M matrix, (k, l), + or a list of them, one per pair. Defaults to None, no M. + + Returns: + tuple: J and K: AO matrices if single matrices are given, lists of them + otherwise. + """ if self.reference == "ROHF": raise NotImplementedError( @@ -789,7 +563,8 @@ def compute_jk(self, Cleft, Cright, tensor=None): raise ValueError("Cleft list is not the same length as Cright list") zero_append = [] - num_compute = 0 + lefts = [] + rights = [] for num, (Cl, Cr) in enumerate(zip(Cleft, Cright)): if (Cr.shape[1] == 0) or (Cl.shape[1] == 0): @@ -810,22 +585,14 @@ def compute_jk(self, Cleft, Cright, tensor=None): else: Cr = np.dot(Cr, tensor[num].T) - Cl = psi4.core.Matrix.from_array(Cl) - Cr = psi4.core.Matrix.from_array(Cr) - - self.jk.C_left_add(Cl) - self.jk.C_right_add(Cr) - num_compute += 1 - - self.jk.compute() + lefts.append(Cl) + rights.append(Cr) J_list = [] K_list = [] - for num in range(num_compute): - J_list.append(np.array(self.jk.J()[num])) - K_list.append(np.array(self.jk.K()[num])) - - self.jk.C_clear() + if lefts: + J_list, K_list = self.backend.compute_jk(lefts, rights) + J_list, K_list = list(J_list), list(K_list) z = np.zeros((self.nbf, self.nbf)) for num in zero_append: diff --git a/prop_sapt/log.py b/prop_sapt/log.py index 9f02e49..8984ed2 100644 --- a/prop_sapt/log.py +++ b/prop_sapt/log.py @@ -1,49 +1,20 @@ -"""The `prop_sapt` logger and the handler that writes its records into Psi4's output -file. +"""The `prop_sapt` logger, and where its records go. Every module of the package logs through `logging.getLogger(__name__)`, a child of the -`prop_sapt` logger, and this module is the only one that writes to Psi4's output. By -default the records go to Psi4's output file, like propSAPT's output always has. The -standard `logging` calls quiet or redirect them, e.g. +`prop_sapt` logger. By default the records go to Psi4's output file, like propSAPT's +output always has, through the Psi4 backend's handler +(`prop_sapt.backends.psi4_backend.Psi4OutputHandler`). The standard `logging` calls quiet or redirect them, e.g. `logging.getLogger("prop_sapt").setLevel(logging.WARNING)` keeps only the warnings, and `logging.getLogger("prop_sapt.cpscf_solver")` is the logger of the CPSCF iterations. """ import logging -import psi4 +from .backends.psi4_backend import Psi4OutputFormatter, Psi4OutputHandler logger = logging.getLogger("prop_sapt") -class Psi4OutputFormatter(logging.Formatter): - """The message alone, after its level ("Warning: ...") for warnings and errors.""" - - def format(self, record: logging.LogRecord) -> str: - text = super().format(record) - if record.levelno >= logging.WARNING: - return f"{record.levelname.capitalize()}: {text}" - - return text - - -class Psi4OutputHandler(logging.Handler): - """Writes each log record into Psi4's output file, ended by a newline.""" - - # marks the handler of this module across reloads, which create a new class - _prop_sapt_psi4_output = True - - def __init__(self, level: int = logging.NOTSET): - super().__init__(level) - self.setFormatter(Psi4OutputFormatter()) - - def emit(self, record: logging.LogRecord): - try: - psi4.core.print_out(self.format(record) + "\n") - except Exception: - self.handleError(record) - - def _install_psi4_output(): """Sends the `prop_sapt` records to Psi4's output file, once, and logs INFO and above unless the logger's level was set before the package was imported.""" diff --git a/prop_sapt/molecule.py b/prop_sapt/molecule.py index 51486f1..78ee4cd 100644 --- a/prop_sapt/molecule.py +++ b/prop_sapt/molecule.py @@ -13,9 +13,9 @@ import psi4 from .sinfinity import sinfinity from .cubes import Cube, make_cube -from .fragments import DimerFragments from .evaluate import evaluate_density, evaluate_esp, evaluate_orbital -from .options import check_cpscf_type, check_df_basis_cpscf +from .backends.psi4_backend import Psi4Backend +from .options import PROPSAPT_OPTIONS, check_cpscf_type, check_df_basis_cpscf from .partition import ( FragmentOperators, QuadratureGrid, @@ -23,11 +23,44 @@ hirshfeld_fragment_weights, molecular_grid, ) -from .utils import changed_psi4_options logger = logging.getLogger(__name__) +class _Psi4Attribute: + """A read-only attribute of a `Dimer`, kept for compatibility, that gives attribute + `name` of its Psi4 backend, or item `key` of that attribute.""" + + def __init__(self, name: str, key: str | None = None, doc: str | None = None): + self.name = name + self.key = key + self.__doc__ = doc + + def __set_name__(self, owner, attribute: str): + self.attribute = attribute + + def __get__(self, dimer, owner=None): + if dimer is None: + return self + + backend = dimer.backend + try: + value = getattr(backend, self.name) + except AttributeError: + raise AttributeError( + f"`{self.attribute}` belongs to the Psi4 backend, but this dimer's " + f"backend is {type(backend).__name__}." + ) from None + + return value if self.key is None else value[self.key] + + def __set__(self, dimer, value): + raise AttributeError( + f"`{self.attribute}` is read-only: it belongs to the Psi4 backend, " + "see `Dimer.backend`." + ) + + class Dimer(sinfinity): """ Core dimer (molecule-like) class. @@ -47,6 +80,13 @@ class Dimer(sinfinity): Memory comes from Psi4's setting (`psi4.set_memory`), as for any Psi4 calculation. + Psi4 runs the monomer SCFs and builds the integrals, through + `prop_sapt.backends.psi4_backend.Psi4Backend`, which the dimer keeps as `backend`. + Its Psi4 objects are also read-only attributes of the dimer: `dimer` (the + molecule), `wfnA` and `wfnB` (the monomer wavefunctions), `dimer_wfn`, `mints` and + `jk`, and so are its settings: `jk_memory` and `memory` (of the J/K objects), + `psi4_options` and `fitting_bases`. + Args: geometry (str): Dimer geometry in Psi4 format, with monomers A and B as its first two fragments; any further fragments are ghost atoms. @@ -76,42 +116,70 @@ def __init__(self, geometry, reference="RHF", memory=None, **kwargs): t_start = time() logger.info("*" * 80) logger.info("Initializing Dimer object...") - psi4.core.tstart() - - # create Psi4 Molecule object - self.geometry = geometry - self.dimer = psi4.geometry(geometry) - self.dimer.print_out_in_angstrom() - # the Psi4 options the dimer is built with, before the monomer SCFs change any - self.psi4_options = changed_psi4_options() - - # initialize parent class - super().__init__(self.dimer, reference, memory, **kwargs) + # in Psi4's timer, around the whole construction (each Psi4 SCF restarts it) + with Psi4Backend.timer(): + self.geometry = geometry + + # the monomer SCFs and the integrals + backend = Psi4Backend( + geometry, + reference, + functional=kwargs.get( + "functional", PROPSAPT_OPTIONS["default_functional"] + ), + grac_A=kwargs.get("grac_A"), + grac_B=kwargs.get("grac_B"), + memory=memory, + ) - self.fragments = DimerFragments.from_molecule(self.dimer) + # initialize parent class + super().__init__(backend) - # induction amplitudes with the monomer SCF's J/K objects, as in IND2,r - self.cpscf_ra = None - self.cpscf_sb = None + # induction amplitudes with the monomer SCF's J/K objects, as in IND2,r + self.cpscf_ra = None + self.cpscf_sb = None - # the CPSCF type in use, see `use_cpscf_type`; None is the monomer SCF's J/K - self._cpscf_key: tuple[str, str | None] | None = None - # induction amplitudes of the other CPSCF types, keyed (monomer, type) - self._other_cpscf_amplitudes: dict[tuple, np.ndarray] = {} + # the CPSCF type in use, see `use_cpscf_type`; None is the monomer SCF's J/K + self._cpscf_key: tuple[str, str | None] | None = None + # induction amplitudes of the other CPSCF types, keyed (monomer, type) + self._other_cpscf_amplitudes: dict[tuple, np.ndarray] = {} - # theta amplitudes of the exchange density matrices, see `get_theta_amplitudes` - self.theta_amplitudes: dict[str, np.ndarray | tuple[np.ndarray, ...]] = {} - # the CPSCF type they were calculated with - self._theta_cpscf_key: tuple[str, str | None] | None = None + # theta amplitudes of the exchange density matrices, + # see `get_theta_amplitudes` + self.theta_amplitudes: dict[str, np.ndarray | tuple[np.ndarray, ...]] = {} + # the CPSCF type they were calculated with + self._theta_cpscf_key: tuple[str, str | None] | None = None - # print time - logger.info( - f"...finished initializing Dimer object in {(time() - t_start):5.2f} seconds." - ) - psi4.core.tstop() + # print time + logger.info( + "...finished initializing Dimer object in " + f"{(time() - t_start):5.2f} seconds." + ) logger.info("*" * 80) + # the Psi4 backend's objects, for compatibility + dimer = _Psi4Attribute("molecule", doc="The dimer's `psi4.core.Molecule`.") + wfnA = _Psi4Attribute("wavefunctions", "A", doc="Monomer A's SCF wavefunction.") + wfnB = _Psi4Attribute("wavefunctions", "B", doc="Monomer B's SCF wavefunction.") + dimer_wfn = _Psi4Attribute( + "dimer_wfn", doc="Wavefunction of the dimer basis set, without an SCF." + ) + mints = _Psi4Attribute( + "mints", doc="`psi4.core.MintsHelper` of the dimer basis set." + ) + jk = _Psi4Attribute("jk", doc="J/K object of the dimer basis set.") + jk_memory = _Psi4Attribute( + "jk_memory", doc="Memory of the J/K objects, in doubles." + ) + memory = _Psi4Attribute("memory", doc="Memory of the J/K objects, in GB.") + psi4_options = _Psi4Attribute( + "psi4_options", doc="The Psi4 options changed from their defaults." + ) + fitting_bases = _Psi4Attribute( + "fitting_bases", doc="The fitting basis sets as built, by option." + ) + def get_cpscf_ra(self) -> np.ndarray: """ Grab CPSCF response amplitudes for monomer A or calculate them if they haven't been @@ -284,6 +352,7 @@ def get_psi4_molecule(self) -> psi4.core.Molecule: psi4.core.Molecule: Psi4 molecule object of the dimer. """ + # through the attribute, which says so if the backend is not Psi4's return self.dimer def get_psi4_wavefunction(self) -> psi4.core.Wavefunction: @@ -308,6 +377,7 @@ def get_psi4_basisset(self) -> psi4.core.BasisSet: psi4.core.BasisSet: Psi4 basis set object of the dimer. """ + # through the attribute, which says so if the backend is not Psi4's return self.dimer_wfn.basisset() def make_cube( diff --git a/prop_sapt/properties.py b/prop_sapt/properties.py index 65dfb12..217c869 100644 --- a/prop_sapt/properties.py +++ b/prop_sapt/properties.py @@ -4,7 +4,6 @@ from collections.abc import Generator -import psi4 import numpy as np import pandas as pd import opt_einsum as oe @@ -688,12 +687,10 @@ def calc_induced_dipole(dimer: Dimer, response: bool | str = True) -> pd.DataFra _check_response(response) # grab nuclear dipole moment - nuc_dipole = dimer.dimer.nuclear_dipole() - nuc_dipole = np.array([nuc_dipole[0], nuc_dipole[1], nuc_dipole[2]]) + nuc_dipole = dimer.backend.nuclear_dipole() # grab AO dipole moment matrices - d_vec = dimer.mints.ao_dipole() - d_vec = [np.asarray(elem) for elem in d_vec] + d_vec = dimer.backend.dipole_integrals() # the CPSCF equations of the three axes are solved together, see `solve_batched` names = {axis: f"Property calculation along {axis}" for axis in "XYZ"} @@ -779,6 +776,6 @@ def calc_property( ### Results saving to file results.to_csv(results_fname) - psi4.core.clean() + dimer.backend.clean_scratch() return results diff --git a/prop_sapt/runner.py b/prop_sapt/runner.py index 45408a7..cd753cf 100644 --- a/prop_sapt/runner.py +++ b/prop_sapt/runner.py @@ -19,6 +19,7 @@ import psi4 from ._version import __version__ +from .backends.psi4_backend import Psi4Backend from .basis_overrides import apply_basis_overrides from .config import RunConfig, load_config, resolve_config from .densities import calc_densities @@ -280,6 +281,7 @@ def run( handle.write("\n") finally: - psi4.core.clean() + # on the class: the dimer, and so its backend, may not have been built + Psi4Backend.clean_scratch() return results diff --git a/prop_sapt/sapt_driver.py b/prop_sapt/sapt_driver.py index c7408d6..f451860 100644 --- a/prop_sapt/sapt_driver.py +++ b/prop_sapt/sapt_driver.py @@ -5,7 +5,6 @@ import logging -import psi4 import pandas as pd from .molecule import Dimer @@ -111,9 +110,8 @@ def calc_sapt_energy(dimer: Dimer, **kwargs) -> pd.Series: " | Second-Quantized SAPT | \n" " |-------------------------------------| " ) - psi4.core.tstart() - with CalcTimer("SAPT energy calculations"): + with dimer.backend.timer(), CalcTimer("SAPT energy calculations"): pd_results_series = pd.Series(dtype=float) @@ -186,6 +184,6 @@ def calc_sapt_energy(dimer: Dimer, **kwargs) -> pd.Series: if results_fname: pd_results_series.to_csv(results_fname) - psi4.core.clean() + dimer.backend.clean_scratch() return pd_results_series diff --git a/prop_sapt/sinfinity.py b/prop_sapt/sinfinity.py index e94326a..0c2b148 100644 --- a/prop_sapt/sinfinity.py +++ b/prop_sapt/sinfinity.py @@ -39,8 +39,8 @@ def get_B_aa(s_ba, s_ab): class sinfinity(helper_SAPT): - def __init__(self, dimer, reference="RHF", memory=None, **kwargs): - super().__init__(dimer, reference, memory, **kwargs) + def __init__(self, backend): + super().__init__(backend) ### Starting initialisation logger.info("Initializing Sinfinity object...") diff --git a/prop_sapt/utils.py b/prop_sapt/utils.py index 316e5da..9fe36ae 100644 --- a/prop_sapt/utils.py +++ b/prop_sapt/utils.py @@ -51,17 +51,6 @@ def package_version(name: str) -> str: return "unknown" -def changed_psi4_options() -> dict | None: - """The Psi4 options changed from their defaults, None if Psi4 cannot list them.""" - - try: - from psi4.driver.p4util import prepare_options_for_set_options - except ImportError: - return None - - return prepare_options_for_set_options() - - def prepare_path(file_path: str) -> str: """ Create directories (and subdirectories) from `file_path` if they don't exist. diff --git a/tests/test_artifacts.py b/tests/test_artifacts.py index 81c0465..8cfe1a1 100644 --- a/tests/test_artifacts.py +++ b/tests/test_artifacts.py @@ -414,7 +414,7 @@ def cached_mo_components(monkeypatch, prepare_dimer, component_matrices): MO basis of their monomer: C^T S rho S C, the inverse of C rho C^T as C^T S C = 1. """ - overlap = np.asarray(prepare_dimer.mints.ao_overlap()) + overlap = prepare_dimer.S coefficients = {"A": prepare_dimer.C_A, "B": prepare_dimer.C_B} mo_components = { monomer: { diff --git a/tests/test_backends.py b/tests/test_backends.py new file mode 100644 index 0000000..722f91c --- /dev/null +++ b/tests/test_backends.py @@ -0,0 +1,159 @@ +"""The backend contract, `prop_sapt.backends.base`, on arrays alone.""" + +import numpy as np +import pytest + +from prop_sapt.backends import Backend, MonomerReference, check_reference + +NBF, NAUX = 6, 9 + + +class ArrayBackend(Backend): + """A backend of given arrays, with operations that do nothing.""" + + def compute_jk(self, lefts, rights): + return [], [] + + def orbital_hessian_product(self, monomer, vectors, cpscf_jk=None): + return [] + + def dipole_integrals(self): + return [np.zeros((NBF, NBF))] * 3 + + def nuclear_dipole(self): + return np.zeros(3) + + +def monomer(ndocc=2, nmo=NBF, nbf=NBF, **changes): + rng = np.random.default_rng(7) + data = { + "C": rng.standard_normal((nbf, nmo)), + "eps": np.sort(rng.standard_normal(nmo)), + "ndocc": ndocc, + "V": -np.eye(nbf), + "energy": -1.0, + "nuclear_repulsion": 0.5, + } + data.update(changes) + return MonomerReference(**data) + + +def backend_data(**changes): + data = { + "reference": "RHF", + "monomers": {"A": monomer(1), "B": monomer(2)}, + "S": np.eye(NBF), + "Qpq": np.zeros((NAUX, NBF, NBF)), + "nuclear_repulsion": 2.0, + "fragments": None, + } + data.update(changes) + return data + + +@pytest.mark.parametrize("reference", ["RHF", "RKS"]) +def test_supported_references(reference): + assert check_reference(reference) == reference + + +@pytest.mark.parametrize("reference", ["ROHF", "UHF", "UKS"]) +def test_open_shell_references_not_implemented(reference): + with pytest.raises(ValueError, match=f"Reference '{reference}' not implemented"): + check_reference(reference) + + +@pytest.mark.parametrize("reference", ["MP2", "rhf"]) +def test_unknown_reference(reference): + with pytest.raises(ValueError, match=f"Unsupported reference type '{reference}'"): + check_reference(reference) + + +def test_monomer_sizes(): + reference = monomer(ndocc=2, nmo=5) + + assert (reference.nbf, reference.nmo) == (NBF, 5) + assert reference.nsocc == 0 + + +@pytest.mark.parametrize( + "changes, message", + [ + ({"eps": np.zeros(NBF - 1)}, "Orbital energies should have shape"), + ({"V": np.zeros((NBF - 1, NBF - 1))}, "V should have shape"), + ({"C": np.zeros(NBF)}, "C should be a 2-dimensional array"), + ({"ndocc": NBF + 1}, "do not fit"), + ({"ndocc": -1}, "do not fit"), + ({"nsocc": NBF}, "do not fit"), + ], +) +def test_inconsistent_monomer(changes, message): + with pytest.raises(ValueError, match=message): + monomer(**changes) + + +def test_backend_keeps_its_arrays(): + """The backend keeps the arrays it is given, without copies.""" + + data = backend_data() + backend = ArrayBackend(**data) + + assert backend.nbf == NBF + assert backend.S is data["S"] + assert backend.Qpq is data["Qpq"] + assert backend.monomers["A"] is data["monomers"]["A"] + assert backend.nuclear_repulsion == 2.0 + + +def test_functional_only_for_rks(): + rhf = ArrayBackend(**backend_data(functional="PBE0")) + rks = ArrayBackend(**backend_data(reference="RKS", functional="PBE0")) + + assert rhf.functional is None + assert rks.functional == "PBE0" + + +@pytest.mark.parametrize( + "changes, message", + [ + ({"reference": "UHF"}, "not implemented"), + ({"monomers": {"A": monomer()}}, "The monomers should be"), + ({"monomers": {"A": monomer(), "B": None}}, "should be a MonomerReference"), + ({"S": np.zeros((NBF, NBF + 1))}, "S should be square"), + ({"Qpq": np.zeros((NAUX, NBF, NBF + 1))}, "Qpq should have shape"), + ({"Qpq": np.zeros((NBF, NBF))}, "Qpq should be a 3-dimensional array"), + ( + {"monomers": {"A": monomer(), "B": monomer(nbf=NBF - 1, nmo=NBF - 1)}}, + "Monomer B has 5 basis functions", + ), + ( + {"monomers": {"A": monomer(), "B": monomer(nmo=NBF - 1)}}, + "Monomer A has 6 orbitals and monomer B 5", + ), + ], +) +def test_inconsistent_backend(changes, message): + with pytest.raises(ValueError, match=message): + ArrayBackend(**backend_data(**changes)) + + +def test_default_hooks_do_nothing(): + backend = ArrayBackend(**backend_data()) + + assert backend.clean_scratch() is None + with backend.timer(): + pass + + +def test_backend_needs_the_operations(): + class NoOperations(Backend): + pass + + with pytest.raises(TypeError, match="abstract"): + NoOperations(**backend_data()) + + +def test_no_cpscf_jk_types_by_default(): + backend = ArrayBackend(**backend_data()) + + with pytest.raises(NotImplementedError, match="ArrayBackend has no CPSCF"): + backend.build_cpscf_jk("DF") diff --git a/tests/test_basis_fetch.py b/tests/test_basis_fetch.py index 7dc8ade..16bfcd8 100644 --- a/tests/test_basis_fetch.py +++ b/tests/test_basis_fetch.py @@ -86,7 +86,7 @@ def he_h2_molecule() -> psi4.core.Molecule: def jkfit_size(molecule, target: str) -> int: - """Size of a JKFIT basis, built the way helper_SAPT_DF builds DF_BASIS_SCF.""" + """Size of a JKFIT basis, built the way Psi4Backend builds DF_BASIS_SCF.""" return psi4.core.BasisSet.build( molecule, "DF_BASIS_SCF", target, "JKFIT", "aug-cc-pvtz" diff --git a/tests/test_calc_density_matrix.py b/tests/test_calc_density_matrix.py index a99894d..629a9ff 100644 --- a/tests/test_calc_density_matrix.py +++ b/tests/test_calc_density_matrix.py @@ -28,9 +28,7 @@ def prepare_dipole_along_x(prepare_dimer): """Prepare dipole moment AO matrix along X axis.""" - d_vec = prepare_dimer.mints.ao_dipole() - d_vec = [np.asarray(elem) for elem in d_vec] - d_X = d_vec[0] + d_X = prepare_dimer.backend.dipole_integrals()[0] return d_X diff --git a/tests/test_calc_property.py b/tests/test_calc_property.py index dcad249..c48c2ab 100644 --- a/tests/test_calc_property.py +++ b/tests/test_calc_property.py @@ -170,7 +170,7 @@ def test_calc_property_from_matrix(prepare_dimer, tmp_path, monkeypatch): one row of floats. The property components return floats, as the energy ones do.""" threshold = 1.0e-8 - d_X = np.asarray(prepare_dimer.mints.ao_dipole()[0]) + d_X = prepare_dimer.backend.dipole_integrals()[0] returned = {} for name in PROPERTY_COMPONENTS: @@ -205,7 +205,7 @@ def test_uncoupled_property(prepare_dimer, tmp_path, monkeypatch): """ threshold = 1.0e-8 - d_X = np.asarray(prepare_dimer.mints.ao_dipole()[0]) + d_X = prepare_dimer.backend.dipole_integrals()[0] def no_cpscf_amplitudes(): raise AssertionError("response=False asked for the CPSCF induction amplitudes") @@ -283,9 +283,9 @@ def test_batched_dipole_matches_single_axes(prepare_dimer): """Every term of every axis is what the axis alone gives.""" batched = calc_induced_dipole(prepare_dimer, response="both") - for axis, d_i in zip("XYZ", prepare_dimer.mints.ao_dipole()): + for axis, d_i in zip("XYZ", prepare_dimer.backend.dipole_integrals()): single = perform_property_contractions( - prepare_dimer, np.asarray(d_i), response="both" + prepare_dimer, d_i, response="both" ).iloc[0] for key, value in single.items(): assert batched.loc[axis, key] == pytest.approx(value, rel=0, abs=1e-12), ( diff --git a/tests/test_cpscf_type.py b/tests/test_cpscf_type.py index c16ba4c..b4555a6 100644 --- a/tests/test_cpscf_type.py +++ b/tests/test_cpscf_type.py @@ -174,36 +174,24 @@ def solve(df_basis): np.testing.assert_allclose(value, reference, rtol=0, atol=1e-10 * scale) -class FailingHx: - """Wraps a monomer wavefunction whose Hessian products fail, recording the name of - its J/K object at the failure.""" +def test_state_restored_after_failed_solve(prepare_dimer, monkeypatch): + """A Hessian product that fails on the CPSCF J/K object leaves the dimer on the + monomer SCF's J/K objects.""" - def __init__(self, wfn): - self.wfn = wfn - self.jk_names = [] - - def __getattr__(self, name): - return getattr(self.wfn, name) + mol = prepare_dimer + jk_names = [] - def cphf_Hx(self, x_vec): - self.jk_names.append(self.wfn.jk().name()) + def failing(monomer, vectors, cpscf_jk=None): + jk_names.append(cpscf_jk.name()) raise RuntimeError("Hessian product failed") - -def test_scf_jk_restored_after_failed_solve(prepare_dimer, monkeypatch): - """A Hessian product that fails on the CPSCF J/K object leaves the monomer SCF's - J/K object on the wavefunction.""" - - mol = prepare_dimer - failing = FailingHx(mol.wfnA) - monkeypatch.setattr(mol, "wfnA", failing) + monkeypatch.setattr(mol.backend, "orbital_hessian_product", failing) with pytest.raises(RuntimeError, match="Hessian product failed"): with mol.use_cpscf_type("DF", DF_BASIS): mol.cpscf_batch("A", [np.ones((mol.sizes["a"], mol.sizes["r"]))]) - assert failing.jk_names == ["MemDFJK"] - assert mol.wfnA.jk().name() == "DirectJK" + assert jk_names == ["MemDFJK"] assert mol.cpscf_jk is None assert mol._cpscf_key is None @@ -310,7 +298,7 @@ def test_properties_use_cpscf_type(prepare_dimer, df_options, monkeypatch): DIRECT ones to the fitting error.""" mol = prepare_dimer - d_X = np.asarray(mol.mints.ao_dipole()[0]) + d_X = mol.backend.dipole_integrals()[0] reset_propsapt_options("cpscf_type") reference = perform_property_contractions(mol, d_X) diff --git a/tests/test_density_property_identity.py b/tests/test_density_property_identity.py index 1c46181..8953075 100644 --- a/tests/test_density_property_identity.py +++ b/tests/test_density_property_identity.py @@ -59,7 +59,7 @@ def operator(water_dimer): """A random symmetric AO matrix. The property terms are linear in the operator, so this probes every element of the density matrices at once.""" - nbf = np.asarray(water_dimer.mints.ao_overlap()).shape[0] + nbf = water_dimer.nbf matrix = np.random.default_rng(2026).standard_normal((nbf, nbf)) return matrix + matrix.T diff --git a/tests/test_dimer.py b/tests/test_dimer.py index 2d9a3a2..4a3a3d6 100644 --- a/tests/test_dimer.py +++ b/tests/test_dimer.py @@ -4,7 +4,7 @@ from .he_h2 import HE_H2 from prop_sapt import Dimer, get_propsapt_options -from prop_sapt.helper_SAPT_DF import jk_memory_doubles +from prop_sapt.backends.psi4_backend import jk_memory_doubles HE_H = """ symmetry c1 @@ -127,16 +127,17 @@ def test_overlap_of_empty_block(prepare_dimer, monkeypatch, string): assert mol.s(string).shape == expected -class CountedHx: - """Wraps a monomer wavefunction, recording how many vectors each `cphf_Hx` call gets.""" +class CountedProducts: + """Wraps the orbital-Hessian products of a backend, recording how many vectors each + call gets.""" - def __init__(self, wfn): - self.wfn = wfn + def __init__(self, product): + self.product = product self.calls = [] - def cphf_Hx(self, x_vec): - self.calls.append(len(x_vec)) - return self.wfn.cphf_Hx(x_vec) + def __call__(self, monomer, vectors, cpscf_jk=None): + self.calls.append(len(vectors)) + return self.product(monomer, vectors, cpscf_jk) def random_perturbations(mol, monomer, count): @@ -166,9 +167,9 @@ def test_cpscf_batch_builds_products_together(prepare_dimer, monkeypatch, monome vectors: as many calls as its slowest vector alone, the first with every vector.""" perturbations = random_perturbations(prepare_dimer, monomer, 3) - attribute = "wfnA" if monomer == "A" else "wfnB" - counted = CountedHx(getattr(prepare_dimer, attribute)) - monkeypatch.setattr(prepare_dimer, attribute, counted) + backend = prepare_dimer.backend + counted = CountedProducts(backend.orbital_hessian_product) + monkeypatch.setattr(backend, "orbital_hessian_product", counted) single_calls = [] for p in perturbations: @@ -227,6 +228,71 @@ def test_orbital_hessian_product_of_nothing(prepare_dimer): assert prepare_dimer.orbital_hessian_product("A", []) == [] +class RecordedJK: + """Wraps the J/K builds of a backend, recording the pairs of each call.""" + + def __init__(self, compute_jk): + self.compute_jk = compute_jk + self.calls = [] + + def __call__(self, lefts, rights): + self.calls.append([(Cl.shape[1], Cr.shape[1]) for Cl, Cr in zip(lefts, rights)]) + return self.compute_jk(lefts, rights) + + +def test_compute_jk_fills_in_empty_pairs(prepare_dimer, monkeypatch): + """A pair with no columns on a side gets zero matrices without reaching the backend; + the other pairs keep their places.""" + + mol = prepare_dimer + recorded = RecordedJK(mol.backend.compute_jk) + monkeypatch.setattr(mol.backend, "compute_jk", recorded) + empty = mol.Co_A[:, :0] + + J, K = mol.compute_jk([mol.Co_A, empty, mol.Co_B], [mol.Co_A, mol.Co_B, mol.Co_B]) + + assert recorded.calls == [[(mol.ndocc_A, mol.ndocc_A), (mol.ndocc_B, mol.ndocc_B)]] + np.testing.assert_allclose(J[0], mol.J_A, rtol=0, atol=1e-12) + np.testing.assert_allclose(K[2], mol.K_B, rtol=0, atol=1e-12) + assert not J[1].any() and not K[1].any() + assert J[1].shape == (mol.nbf, mol.nbf) + + +def test_compute_jk_of_empty_pairs_only(prepare_dimer, monkeypatch): + mol = prepare_dimer + recorded = RecordedJK(mol.backend.compute_jk) + monkeypatch.setattr(mol.backend, "compute_jk", recorded) + empty = mol.Co_A[:, :0] + + J, K = mol.compute_jk(empty, mol.Co_B) + + assert recorded.calls == [] + assert J.shape == K.shape == (mol.nbf, mol.nbf) + assert not J.any() and not K.any() + + +@pytest.mark.parametrize("side", ["left", "right"]) +def test_compute_jk_folds_in_the_tensor(prepare_dimer, side): + """D = C_left M C_right^T, whichever side M is folded into (the one with fewer + columns): J and K are those of D itself, given to the backend as D I^T.""" + + mol = prepare_dimer + M = np.random.default_rng(5).standard_normal((mol.ndocc_A, mol.nvirt_A)) + if side == "left": + Cl, Cr = mol.Co_A, mol.Cv_A + else: + Cl, Cr, M = mol.Cv_A, mol.Co_A, M.T + assert (Cl.shape[1] < Cr.shape[1]) == (side == "left") + + J, K = mol.compute_jk(Cl, Cr, tensor=M) + (J_ref,), (K_ref,) = mol.backend.compute_jk([Cl @ M @ Cr.T], [np.eye(mol.nbf)]) + + np.testing.assert_allclose(J, J_ref, rtol=0, atol=1e-12) + np.testing.assert_allclose(K, K_ref, rtol=0, atol=1e-12) + # K tells D from its transpose + assert np.abs(K - K.T).max() > 1e-3 + + def test_cpscf_rejects_wrong_shape(prepare_dimer): with pytest.raises(ValueError, match="right-hand side of shape"): prepare_dimer.cpscf_batch("A", [np.ones((2, 2))]) diff --git a/tests/test_fragments.py b/tests/test_fragments.py index 71f0c7c..d072dc4 100644 --- a/tests/test_fragments.py +++ b/tests/test_fragments.py @@ -51,7 +51,7 @@ def test_parse_from_file(tmp_path): def test_parse_keeps_dimer_frame_with_extra_fragment(): - """Angstrom input off the origin gets the frame of `helper_SAPT.__init__`.""" + """Angstrom input off the origin gets the frame of `Psi4Backend`.""" fragments = parse_fragments(LI_WATER_MIDBOND) diff --git a/tests/test_imports.py b/tests/test_imports.py index c975d36..8cd66cc 100644 --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -1,5 +1,6 @@ """Static checks of how the package imports itself.""" +import ast import re from pathlib import Path @@ -7,6 +8,28 @@ ABSOLUTE_IMPORT = re.compile(r"^\s*(?:from|import)\s+prop_sapt\b", re.MULTILINE) +#: The modules that may import Psi4: its backend, and those not yet working through the +#: backend contract (the analysis modules, bundles, runner, configuration and finite +#: field). The SAPT core is not among them. +PSI4_MODULES = { + "artifacts.py", + "backends/psi4_backend.py", + "basis_fetch.py", + "basis_overrides.py", + "checks.py", + "cli.py", + "cubes.py", + "evaluate.py", + "finite_field/core.py", + "finite_field/utils.py", + "forces.py", + "fragments.py", + "molecule.py", + "partition.py", + "runner.py", + "trexio_export.py", +} + def test_package_imports_itself_relatively(): """Modules import the package relatively (`from ..molecule import Dimer`). An @@ -39,3 +62,40 @@ def test_term_packages_export_their_functions(): continue for name in re.findall(r"^def (\w+)\(", module.read_text(), re.MULTILINE): assert f'"{name}"' in init, f"{package.name} does not export {name}" + + +def _imports_psi4(path: Path) -> bool: + """Whether a module imports Psi4 anywhere, functions included.""" + + for node in ast.walk(ast.parse(path.read_text())): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + names = [node.module] + else: + continue + if any(name.split(".")[0] == "psi4" for name in names): + return True + + return False + + +def test_only_psi4_facing_modules_import_psi4(): + """The SAPT core (`helper_SAPT`, the contractions, the energy, property and density + drivers, CPSCF) does not import Psi4: its calculations reach Psi4 through the + backend, so another backend can take its place. The list of Psi4 modules is exact: + it shrinks as modules move onto the backend contract. + + Only imports are checked. The density driver still uses Psi4 objects of the dimer + for some of its output: the cube files (`Dimer.make_cube`) and the monomer + wavefunctions of the deprecated ``matrix_format="npy"`` (`wfnA.to_file`).""" + + root = Path(prop_sapt.__file__).parent + importing = { + path.relative_to(root).as_posix() + for path in sorted(root.rglob("*.py")) + if _imports_psi4(path) + } + + assert sorted(importing - PSI4_MODULES) == [] + assert sorted(PSI4_MODULES - importing) == [] diff --git a/tests/test_log.py b/tests/test_log.py index 18f4bdb..87127ff 100644 --- a/tests/test_log.py +++ b/tests/test_log.py @@ -8,6 +8,7 @@ import pytest import prop_sapt.log +from prop_sapt.backends.psi4_backend import Psi4OutputHandler from .test_cpscf_solver import DenseHessian, right_hand_sides, solve @@ -130,16 +131,25 @@ def _calls(pattern: str) -> list[str]: return found -def test_only_the_log_module_writes_to_psi4_output(): - """The modules log, and only `prop_sapt.log` writes into Psi4's output file, so a - backend other than Psi4 needs only another handler.""" +def test_only_the_psi4_backend_writes_to_psi4_output(): + """The modules log instead of calling `psi4.core.print_out`, which only the Psi4 + backend's handler calls, so a backend other than Psi4 needs only another handler. + The `print_out` methods of Psi4 objects (in `cubes` and `forces`) are not counted. + """ calls = _calls("psi4.core.print_out(") - assert [call.split(":")[0] for call in calls] == ["log.py"] + assert [call.split(":")[0] for call in calls] == ["backends/psi4_backend.py"] -def test_psi4_scratch_cleaned_only_at_the_end_of_jobs(): - """Psi4's scratch files are cleaned between jobs, not before raising an error.""" +def test_log_module_installs_the_psi4_backends_handler(): + assert prop_sapt.log.Psi4OutputHandler is Psi4OutputHandler + assert any(isinstance(handler, Psi4OutputHandler) for handler in _handlers()) + + +def test_psi4_scratch_cleaned_only_by_the_backend(): + """Psi4's scratch files are cleaned by the Psi4 backend, at the end of jobs + (`clean_scratch`), not before raising an error.""" files = [call.split(":")[0] for call in _calls("psi4.core.clean()")] - assert files == ["properties.py", "runner.py", "sapt_driver.py"] + assert files == ["backends/psi4_backend.py"] + assert len(_calls(".clean_scratch()")) == 3 diff --git a/tests/test_psi4_backend.py b/tests/test_psi4_backend.py new file mode 100644 index 0000000..4261a18 --- /dev/null +++ b/tests/test_psi4_backend.py @@ -0,0 +1,239 @@ +"""The Psi4 backend: the data it gives the dimer, and the dimer's Psi4 attributes.""" + +from types import SimpleNamespace + +import numpy as np +import psi4 +import pytest + +from prop_sapt import Dimer +from prop_sapt.backends import MonomerReference +from prop_sapt.backends.psi4_backend import Psi4Backend +from prop_sapt.sinfinity import sinfinity + +from .he_h2 import OPTIONS +from .test_cpscf_type import DF_BASIS +from .test_dimer import HE_H + + +def test_backend_of_the_dimer(prepare_dimer): + backend = prepare_dimer.backend + + assert isinstance(backend, Psi4Backend) + assert backend.reference == prepare_dimer.reference == "RHF" + assert backend.nbf == backend.basisset.nbf() + + +@pytest.mark.parametrize("monomer", ["A", "B"]) +def test_monomer_data(prepare_dimer, monomer): + """Orthonormal orbitals in the dimer basis set, in order of their energies, and a + symmetric attractive potential.""" + + backend = prepare_dimer.backend + reference = backend.monomers[monomer] + wfn = backend.wavefunctions[monomer] + + assert isinstance(reference, MonomerReference) + assert reference.C.shape == (backend.nbf, wfn.nmo()) + assert reference.ndocc == wfn.doccpi()[0] + assert reference.energy == wfn.energy() + np.testing.assert_allclose( + reference.C.T @ backend.S @ reference.C, np.eye(wfn.nmo()), atol=1e-10 + ) + assert np.all(np.diff(reference.eps) >= 0) + np.testing.assert_allclose(reference.V, reference.V.T, atol=1e-12) + assert np.trace(reference.V @ backend.S) < 0 + + +def test_dimer_data(prepare_dimer): + backend = prepare_dimer.backend + + np.testing.assert_allclose(backend.S, backend.S.T, atol=1e-14) + np.testing.assert_allclose(backend.Qpq, backend.Qpq.transpose(0, 2, 1), atol=1e-12) + assert backend.nuclear_repulsion == backend.molecule.nuclear_repulsion_energy() + assert backend.fragments.A.atoms == (0,) + assert backend.fragments.B.atoms == (1, 2) + + +def test_naux_counts_the_fitting_functions(prepare_dimer): + """`naux` is the number of functions of the SAPT fitting basis, the rows of `Qpq`: + spherical ones for a spherical basis, fewer than its Cartesian ones.""" + + mol = prepare_dimer + fitting_basis = OPTIONS["DF_BASIS_SAPT"] + aux = psi4.core.BasisSet.build( + mol.dimer, target=fitting_basis, other=fitting_basis, fitrole="RIFIT" + ) + + assert aux.has_puream() + assert mol.naux == mol.Qpq.shape[0] == aux.nbf() < aux.nao() + + +def test_dipole_integrals(prepare_dimer): + """The electronic integrals are Psi4's, with the electron charge included; the + nuclear dipole is sum Z R over the real atoms.""" + + backend = prepare_dimer.backend + dipoles = backend.dipole_integrals() + + assert len(dipoles) == 3 + for component, psi4_component in zip(dipoles, backend.mints.ao_dipole()): + np.testing.assert_array_equal(component, np.asarray(psi4_component)) + fragments = backend.fragments + charges = np.where(fragments.real, fragments.atomic_numbers, 0) + np.testing.assert_allclose( + backend.nuclear_dipole(), charges @ fragments.coordinates, rtol=0, atol=1e-12 + ) + + +def test_dimer_takes_the_backend_arrays(prepare_dimer): + """The dimer's arrays are the backend's, not copies.""" + + mol = prepare_dimer + backend = mol.backend + + assert mol.S is backend.S + assert mol.Qpq is backend.Qpq + assert mol.C_A is backend.monomers["A"].C + assert mol.eps_B is backend.monomers["B"].eps + assert mol.V_A is backend.monomers["A"].V + assert mol.fragments is backend.fragments + assert mol.rhfA == backend.monomers["A"].energy + + +def test_psi4_attributes_are_the_backends(prepare_dimer): + mol = prepare_dimer + backend = mol.backend + + assert mol.dimer is backend.molecule + assert mol.get_psi4_molecule() is backend.molecule + assert mol.wfnA is backend.wavefunctions["A"] + assert mol.wfnB is backend.wavefunctions["B"] + assert mol.dimer_wfn is backend.dimer_wfn + assert mol.mints is backend.mints + assert mol.jk is backend.jk + assert mol.jk_memory == backend.jk_memory + assert mol.memory == backend.memory + assert mol.psi4_options is backend.psi4_options + assert mol.fitting_bases is backend.fitting_bases + + +@pytest.mark.parametrize("attribute", ["wfnA", "mints", "dimer"]) +def test_psi4_attributes_are_read_only(prepare_dimer, attribute): + """Replacing a Psi4 object of the dimer would not reach the backend, which does the + calculations, so it raises.""" + + with pytest.raises(AttributeError, match="read-only"): + setattr(prepare_dimer, attribute, None) + + +@pytest.mark.parametrize( + "get", + [ + lambda dimer: dimer.wfnA, + lambda dimer: dimer.get_psi4_molecule(), + lambda dimer: dimer.get_psi4_basisset(), + lambda dimer: dimer.get_psi4_wavefunction(), + ], + ids=["wfnA", "get_psi4_molecule", "get_psi4_basisset", "get_psi4_wavefunction"], +) +def test_psi4_attributes_of_another_backend(get): + """A dimer whose backend is not Psi4's says so when asked for a Psi4 object.""" + + dimer = Dimer.__new__(Dimer) + dimer.backend = SimpleNamespace() + + with pytest.raises( + AttributeError, + match="belongs to the Psi4 backend, but this dimer's backend is SimpleNamespace", + ): + get(dimer) + + +def test_rks_needs_a_functional(): + """Checked before any SCF is run.""" + + with pytest.raises(ValueError, match="RKS reference needs a functional"): + Psi4Backend( + HE_H.format(atom_A="He", mult_A=1, atom_B="He", mult_B=1), + "RKS", + functional=None, + ) + + +def test_helper_from_the_backend_alone(prepare_dimer): + """The SAPT arrays are built from the backend alone: a new object on the dimer's + backend reproduces them.""" + + mol = prepare_dimer + rebuilt = sinfinity(mol.backend) + + for name in ["J_A", "K_B", "omegaA_bs", "omega_exchB_ar", "Qar", "t_rsab"]: + np.testing.assert_allclose( + getattr(rebuilt, name), getattr(mol, name), rtol=0, atol=1e-12 + ) + assert rebuilt.nuc_rep == mol.nuc_rep + + +def test_compute_jk_of_the_occupied_orbitals(prepare_dimer): + mol = prepare_dimer + + (J_A, J_B), (K_A, K_B) = mol.backend.compute_jk( + [mol.Co_A, mol.Co_B], [mol.Co_A, mol.Co_B] + ) + + np.testing.assert_allclose(J_A, mol.J_A, rtol=0, atol=1e-12) + np.testing.assert_allclose(K_B, mol.K_B, rtol=0, atol=1e-12) + + +def test_failed_compute_jk_leaves_no_inputs(prepare_dimer): + """A J/K build that fails part way clears the pairs it had added, so the next build + returns the J and K matrices of its own pairs only.""" + + mol = prepare_dimer + backend = mol.backend + + # a 3-dimensional array is not a matrix + with pytest.raises(ValueError): + backend.compute_jk([mol.Co_A, np.zeros((2, 2, 2))], [mol.Co_A, mol.Co_B]) + + J, K = backend.compute_jk([mol.Co_B], [mol.Co_B]) + + assert len(J) == len(K) == 1 + np.testing.assert_allclose(J[0], mol.J_B, rtol=0, atol=1e-12) + np.testing.assert_allclose(K[0], mol.K_B, rtol=0, atol=1e-12) + + +class FailingHx: + """Wraps a monomer wavefunction whose Hessian products fail, recording the name of + its J/K object at the failure.""" + + def __init__(self, wfn): + self.wfn = wfn + self.jk_names = [] + + def __getattr__(self, name): + return getattr(self.wfn, name) + + def cphf_Hx(self, x_vec): + self.jk_names.append(self.wfn.jk().name()) + raise RuntimeError("Hessian product failed") + + +def test_scf_jk_restored_after_failed_product(prepare_dimer, monkeypatch): + """A Hessian product that fails on a CPSCF J/K object leaves the monomer SCF's J/K + object on the wavefunction.""" + + mol = prepare_dimer + backend = mol.backend + failing = FailingHx(backend.wavefunctions["A"]) + monkeypatch.setitem(backend.wavefunctions, "A", failing) + cpscf_jk = backend.build_cpscf_jk("DF", DF_BASIS) + + with pytest.raises(RuntimeError, match="Hessian product failed"): + backend.orbital_hessian_product( + "A", [np.ones((mol.sizes["a"], mol.sizes["r"]))], cpscf_jk + ) + + assert failing.jk_names == ["MemDFJK"] + assert backend.wavefunctions["A"].jk().name() == "DirectJK" diff --git a/tests/test_runner.py b/tests/test_runner.py index 4c3ddee..d902d0c 100644 --- a/tests/test_runner.py +++ b/tests/test_runner.py @@ -226,7 +226,7 @@ def ri_basis_size(mol, target): hydrogen, "aug-cc-pvqz-ri" ) - # the way helper_SAPT_DF builds the DF_BASIS_SAPT basis + # the way Psi4Backend builds the DF_BASIS_SAPT basis target = psi4.core.get_global_option("DF_BASIS_SAPT") assert ri_basis_size(molecule, target) == expected assert expected < ri_basis_size(molecule, "aug-cc-pvqz-ri") @@ -262,7 +262,7 @@ def jkfit_basis_size(target): molecule, "DF_BASIS_SCF", target, "JKFIT", "aug-cc-pvtz" ).nbf() - # the way helper_SAPT_DF builds the DF_BASIS_SCF basis + # the way Psi4Backend builds the DF_BASIS_SCF basis target = psi4.core.get_option("SCF", "DF_BASIS_SCF") assert target == "PROPSAPT-TEST-JKFIT" assert jkfit_basis_size(target) == jkfit_basis_size("def2-universal-jkfit") @@ -324,7 +324,7 @@ def energies_with_overrides(basis_overrides) -> np.ndarray: dimer = runner.build_dimer(config, HE_H2) return np.array( - [calc_elst1_energy(dimer), calc_disp2_energy(dimer)["DISP2"], dimer.nao_aux] + [calc_elst1_energy(dimer), calc_disp2_energy(dimer)["DISP2"], dimer.naux] ) diff --git a/tests/test_sapt_driver.py b/tests/test_sapt_driver.py index 9227eb7..d97a60e 100644 --- a/tests/test_sapt_driver.py +++ b/tests/test_sapt_driver.py @@ -1,5 +1,8 @@ """Saving of the `calc_sapt_energy` results, with the energy terms stubbed out.""" +from contextlib import nullcontext +from types import SimpleNamespace + import pandas as pd import pytest @@ -23,12 +26,17 @@ def stub_terms(monkeypatch, tmp_path): monkeypatch.setattr(sapt_driver, "print_sapt_summary", lambda results, **kw: None) monkeypatch.chdir(tmp_path) + # a dimer whose backend has no timers and no scratch files + return SimpleNamespace( + backend=SimpleNamespace(timer=nullcontext, clean_scratch=lambda: None) + ) + def test_results_saved_to_sapt_results_csv_by_default(stub_terms, tmp_path): """Like the other entry points, it saves its results unless told not to, under a name no other default uses (`calc_property` writes results.csv).""" - results = sapt_driver.calc_sapt_energy(None) + results = sapt_driver.calc_sapt_energy(stub_terms) saved = pd.read_csv(tmp_path / "sapt_results.csv", index_col=0).iloc[:, 0] assert results["TOTAL"] == 6.0 @@ -36,24 +44,24 @@ def test_results_saved_to_sapt_results_csv_by_default(stub_terms, tmp_path): def test_results_true_saves_to_the_default_file(stub_terms, tmp_path): - sapt_driver.calc_sapt_energy(None, results=True) + sapt_driver.calc_sapt_energy(stub_terms, results=True) assert [path.name for path in tmp_path.glob("*.csv")] == ["sapt_results.csv"] def test_results_path(stub_terms, tmp_path): - sapt_driver.calc_sapt_energy(None, results=str(tmp_path / "energies.csv")) + sapt_driver.calc_sapt_energy(stub_terms, results=str(tmp_path / "energies.csv")) assert [path.name for path in tmp_path.glob("*.csv")] == ["energies.csv"] @pytest.mark.parametrize("results", [False, None]) def test_results_false_saves_nothing(stub_terms, tmp_path, results): - sapt_driver.calc_sapt_energy(None, results=results) + sapt_driver.calc_sapt_energy(stub_terms, results=results) assert list(tmp_path.glob("*.csv")) == [] def test_invalid_response_names_every_choice(stub_terms): with pytest.raises(ValueError, match="True, False or 'both'"): - sapt_driver.calc_sapt_energy(None, response="coupled") + sapt_driver.calc_sapt_energy(stub_terms, response="coupled")