diff --git a/CHANGELOG.md b/CHANGELOG.md index 905dc51..403e61b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,9 @@ requests of the private repository propSAPT was developed in before it was publi usually carry most of a change, in the spirit of NOCV. - `Dimer.from_backend`: a dimer of a backend calculation that has run already, such as a `Psi4Backend` built beforehand. +- `Dimer.basis`: the dimer's basis set for the functions of `evaluate`, `partition`, + `cubes` and `forces`, which still take Psi4 basis sets. `make_cube`, + `calc_force_at_nuc` and `calc_force_nuc_nuc` take it in place of the Psi4 molecule. ### Changed @@ -41,9 +44,18 @@ requests of the private repository propSAPT was developed in before it was publi `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`. +- `make_cube` and `calc_force_at_nuc` write one line on the basis set into the output, where + Psi4 printed it. Psi4's timings are around `Dimer.make_cube` and no longer come with + `prop_sapt.cubes.make_cube`. +- `Dimer` warns about a basis set with effective core potentials (ECPs), which propSAPT + does not support. See the + [usage guide](https://btyrcha.github.io/propSAPT/usage.html#known-limitations). ### Fixed +- `make_cube` and `calc_force_at_nuc` raise a `TypeError` for a `basisset` that is not a + basis set. They ignored it and used one built from the `BASIS` option, whose functions + the matrices may not be in. - The cube and `.npy` files of the `Ind` and `Disp` densities are now named `delta_dm_ind-total*` and `delta_dm_disp-total*`. Their old names differ from those of `ind` and `disp` only in case, so on a case-insensitive file system (macOS and Windows by diff --git a/docs/api.rst b/docs/api.rst index 446dab4..8fd3736 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -22,6 +22,14 @@ Backends :members: :show-inheritance: +.. automodule:: prop_sapt.backends.ao_basis + :members: + :show-inheritance: + +.. automodule:: prop_sapt.backends.psi4_basis + :members: + :show-inheritance: + Properties ---------- diff --git a/docs/usage.rst b/docs/usage.rst index 9e94dfb..4b5d80e 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -70,6 +70,10 @@ These attributes are read-only, since replacing one would not change the calcula :meth:`Dimer.from_backend ` makes a dimer of a backend that has run already, such as a ``Psi4Backend`` built beforehand. +``dimer.basis`` is the dimer's basis set as the analysis functions below take it (an +:class:`~prop_sapt.backends.base.AOBasis`): point evaluation, fragment operators, cubes and +forces. They take Psi4 basis sets too. + 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 @@ -613,25 +617,22 @@ To compute Hellmann-Feynman forces on nuclei from one-particle AO density matric from prop_sapt.forces import calc_force_at_nuc, calc_force_nuc_nuc - mol = dimer.get_psi4_molecule() - basisset = dimer.get_psi4_basisset() - # Force on nucleus 0 from the interaction-induced density of monomer A - force = calc_force_at_nuc(mol, 2 * rho_A, atidx=0, basisset=basisset, add_nuclear=False) + force = calc_force_at_nuc(dimer.basis, 2 * rho_A, atidx=0, add_nuclear=False) # Pass multiple density matrices — integrals are computed only once forces = calc_force_at_nuc( - mol, [2 * rho_A_elst, 2 * rho_A_exch], atidx=0, basisset=basisset, add_nuclear=False + dimer.basis, [2 * rho_A_elst, 2 * rho_A_exch], atidx=0, add_nuclear=False ) # Nuclear-nuclear repulsion only (no electron density needed) - force_nuc = calc_force_nuc_nuc(mol, atidx=0) + force_nuc = calc_force_nuc_nuc(dimer.basis, atidx=0) All forces are in atomic units (Hartree/Bohr). The nuclear-nuclear repulsion contribution is added by default; pass ``add_nuclear=False`` to obtain the electronic part only, as for -interaction-induced densities above. The matrices must be in the AO basis of ``basisset``; -without it, a basis set is built for ``mol`` from the current ``BASIS`` option, so pass the -dimer's for its density matrices. As elsewhere, no spin factor is applied: pass +interaction-induced densities above. A Psi4 molecule in place of ``dimer.basis`` needs the +basis set the matrices are in as ``basisset=``, since without it one is built from the +current ``BASIS`` option. As elsewhere, no spin factor is applied: pass ``2 * rho`` for the matrices of :func:`~prop_sapt.densities.calc_densities`. Evaluating at Arbitrary Points @@ -647,7 +648,7 @@ points without the last axis. import numpy as np from prop_sapt.evaluate import evaluate_density, evaluate_orbital, evaluate_esp - basisset = dimer.get_psi4_basisset() + basisset = dimer.basis # or a Psi4 basis set # density along the x axis line = np.zeros((200, 3)) @@ -661,14 +662,14 @@ points without the last axis. C = dimer.wfnA.Ca().np psi = evaluate_orbital(C[:, :3], line, basisset) # shape (3, 200) - # ESP of the electrons; nuclei=True adds the nuclei of the basis set's molecule + # ESP of the electrons; nuclei=True adds the nuclei of the basis set's atoms esp = evaluate_esp(rho_A, line, basisset) The same functions are :class:`~prop_sapt.molecule.Dimer` methods that use the dimer basis set: ``dimer.evaluate_density(rho, points)``, ``dimer.evaluate_orbital(C, points)`` and ``dimer.evaluate_esp(rho, points)``. -* Matrices must be in the AO basis of ``basisset``, in Psi4 AO order. +* Matrices must be in the AO basis of ``basisset``, in its AO order (Psi4's). * No spin factor is applied. The density matrices returned by :func:`~prop_sapt.densities.calc_densities` follow the ``Da`` convention, so pass ``2 * rho`` for the total (RHF) density, as the density cubes do. @@ -727,7 +728,7 @@ and the electrons any density matrix :math:`D` puts on :math:`X` are the trace Fragment weights from any other partitioning (e.g. LISA or MBIS weights from horton_part) work as well: give them at the points of the grid they were computed on, with that grid's quadrature weights. Only these arrays are needed; the basis functions -are evaluated by Psi4 in the given basis set: +are those of the given basis set: .. code-block:: python @@ -735,7 +736,7 @@ are evaluated by Psi4 in the given basis set: # points (n, 3) in bohr, quadrature weights (n,), fragment weights w_A, w_B (n,) ops = FragmentOperators.from_grid( - points, weights, {"A": w_A, "B": w_B}, dimer.get_psi4_basisset() + points, weights, {"A": w_A, "B": w_B}, dimer.basis ) q_A = ops.charge("A", 2 * rho_pol) @@ -790,8 +791,8 @@ It supports three matrix types: cube = dimer.make_cube(2 * rho_B, grid_step=0.1) :func:`prop_sapt.cubes.make_cube` does the same for any Psi4 molecule; pass the basis set -the matrices are in as ``basisset=``, e.g. ``dimer.get_psi4_basisset()``, since without it -a basis set is built from the current ``BASIS`` option. A grid from +the matrices are in as ``basisset=``, e.g. ``dimer.basis``, since without it a basis set is +built from the current ``BASIS`` option. A grid from :func:`prop_sapt.cubes.prepare_grid` can be reused across calls with ``grid=``. Working with cubes @@ -869,6 +870,8 @@ Known limitations * **Closed-shell references only.** The monomers must be closed-shell singlets with an ``RHF`` or ``RKS`` reference; unrestricted references are not implemented. * **All-electron only.** Frozen core is not supported, and :class:`~prop_sapt.molecule.Dimer` - rejects the ``FREEZE_CORE`` option. + rejects the ``FREEZE_CORE`` option. It warns about a basis set with effective core + potentials (ECPs): the SCFs use them, but the potentials in the SAPT terms do not, so the + electrostatic energies are wrong and the other results less accurate. * **Finite-field files.** :func:`~prop_sapt.finite_field.finite_field_sapt` writes the SAPT energies of every field into the working directory, :file:`results--.csv`. diff --git a/prop_sapt/backends/__init__.py b/prop_sapt/backends/__init__.py index 90f7d99..0176f77 100644 --- a/prop_sapt/backends/__init__.py +++ b/prop_sapt/backends/__init__.py @@ -2,6 +2,6 @@ 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 +from .base import MONOMERS, AOBasis, Backend, MonomerReference, check_reference -__all__ = ["MONOMERS", "Backend", "MonomerReference", "check_reference"] +__all__ = ["MONOMERS", "AOBasis", "Backend", "MonomerReference", "check_reference"] diff --git a/prop_sapt/backends/ao_basis.py b/prop_sapt/backends/ao_basis.py new file mode 100644 index 0000000..ba31a22 --- /dev/null +++ b/prop_sapt/backends/ao_basis.py @@ -0,0 +1,111 @@ +"""The `mol` and `basisset` arguments of propSAPT's analysis functions +(`prop_sapt.evaluate`, `prop_sapt.partition`, `prop_sapt.cubes`, `prop_sapt.forces`): an +AO basis of any code, or a Psi4 molecule or basis set. Psi4 is imported only for the +latter, so the analysis modules load without it. +""" + +import sys +from typing import TYPE_CHECKING, Union + +import numpy as np + +from .base import AOBasis + +if TYPE_CHECKING: + import psi4 + +#: The basis set an analysis function takes, see `as_ao_basis`. +BasisLike = Union[AOBasis, "psi4.core.BasisSet"] +#: The atoms an analysis function takes, see `atoms_of`. +AtomsLike = Union[AOBasis, "psi4.core.Molecule"] + + +def as_ao_basis(basisset: BasisLike) -> AOBasis: + """ + The AO basis of an analysis function's `basisset` argument: an `AOBasis` as it is, a + Psi4 basis set as a `Psi4Basis`. + + Raises: + TypeError: If `basisset` is neither. + """ + + if isinstance(basisset, AOBasis): + return basisset + + if _is_psi4(basisset, "BasisSet"): + from .psi4_basis import Psi4Basis + + return Psi4Basis(basisset) + + raise TypeError( + "`basisset` should be of type `psi4.core.BasisSet` or " + f"`prop_sapt.backends.AOBasis` was `{type(basisset)}`!" + ) + + +def atoms_of(mol: AtomsLike) -> tuple[np.ndarray, np.ndarray]: + """ + The atoms of an analysis function's `mol` argument: a Psi4 molecule, whose geometry + is updated first (`Molecule.update_geometry`), or an AO basis. + + Raises: + TypeError: If `mol` is neither. + + Returns: + tuple[np.ndarray, np.ndarray]: Coordinates in bohr, (natom, 3), and charges, + (natom,), 0 for ghost atoms. + """ + + if isinstance(mol, AOBasis): + return mol.coordinates, mol.charges + + if _is_psi4(mol, "Molecule"): + from .psi4_basis import molecule_arrays + + mol.update_geometry() + return molecule_arrays(mol) + + raise TypeError( + "`mol` should be of type `psi4.core.Molecule` or " + f"`prop_sapt.backends.AOBasis` was `{type(mol)}`!" + ) + + +def atoms_and_basis( + mol: AtomsLike, basisset: BasisLike | None +) -> tuple[np.ndarray, np.ndarray, AOBasis]: + """ + The atoms and the AO basis of an analysis function's `mol` and `basisset` arguments. + + Args: + mol (AOBasis | psi4.core.Molecule): The atoms, see `atoms_of`. + basisset (AOBasis | psi4.core.BasisSet | None): The basis set. None is `mol` + itself if that is an AO basis, and otherwise the basis set of the current + `BASIS` option, built for the molecule. + + Raises: + TypeError: If `mol` or `basisset` is of another type. + + Returns: + tuple[np.ndarray, np.ndarray, AOBasis]: Coordinates in bohr, (natom, 3), and + charges, (natom,), of the atoms, and the AO basis. + """ + + coordinates, charges = atoms_of(mol) + if basisset is None: + if isinstance(mol, AOBasis): + return coordinates, charges, mol + from .psi4_basis import option_basis + + return coordinates, charges, option_basis(mol) + + return coordinates, charges, as_ao_basis(basisset) + + +def _is_psi4(argument: object, name: str) -> bool: + """Whether `argument` is of the class `name` of `psi4.core`. Nothing is where Psi4 + has not been imported.""" + + psi4 = sys.modules.get("psi4") + + return psi4 is not None and isinstance(argument, getattr(psi4.core, name)) diff --git a/prop_sapt/backends/base.py b/prop_sapt/backends/base.py index 946965a..f768e42 100644 --- a/prop_sapt/backends/base.py +++ b/prop_sapt/backends/base.py @@ -5,6 +5,10 @@ the operations propSAPT calls while it calculates. `helper_SAPT` reads only these, so the SAPT contractions work with any code that supplies them. +The analysis of AO matrices (`prop_sapt.evaluate`, `prop_sapt.partition`, +`prop_sapt.cubes`, `prop_sapt.forces`) needs no calculation, only a basis set on its +atoms: an `AOBasis`, which a backend gives as its `basis`. + 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, @@ -19,7 +23,7 @@ """ from abc import ABC, abstractmethod -from collections.abc import Mapping, Sequence +from collections.abc import Iterator, Mapping, Sequence from contextlib import AbstractContextManager, nullcontext from dataclasses import dataclass from typing import TYPE_CHECKING @@ -106,6 +110,131 @@ def nmo(self) -> int: return self.C.shape[1] +class AOBasis(ABC): + """ + The AOs of a quantum-chemistry code on their atoms, with the values and integrals + propSAPT needs to analyse AO matrices. + + The AOs are in the code's own order, the one of the matrices its backend hands out + (`Backend.S`, the MO coefficients, the density matrices of `calc_densities`). + Matrices of one code with the basis of another give wrong numbers without an error + whenever the sizes match. + """ + + @property + @abstractmethod + def nbf(self) -> int: + """Number of basis functions.""" + + @property + @abstractmethod + def coordinates(self) -> np.ndarray: + """Coordinates of the atoms in bohr, (natom, 3), ghost atoms included. Those of + a backend's `basis` are its `fragments.coordinates`, in their order.""" + + @property + @abstractmethod + def charges(self) -> np.ndarray: + """Nuclear charges of the atoms, (natom,), 0 for ghost atoms.""" + + @abstractmethod + def values(self, points: np.ndarray) -> np.ndarray: + """ + Values of the AOs at points, all computed at once: propSAPT passes large sets of + points in blocks. No distant AO is screened out. + + Args: + points (np.ndarray): Points in bohr, (n, 3). + + Returns: + np.ndarray: The values, (n, nbf). + """ + + def value_blocks( + self, points: np.ndarray, block_size: int + ) -> Iterator[tuple[slice, np.ndarray]]: + """ + `values` at consecutive blocks of `points`, at most `block_size` points at a + time, as propSAPT computes them. By default, one `values` call per block; a code + may keep what it needs between the blocks of one loop, but not after it. + + Args: + points (np.ndarray): Points in bohr, (n, 3). + block_size (int): Largest number of points in a block, >= 1. + + Yields: + tuple[slice, np.ndarray]: Slice of `points` in the block, and the values + there, (n_block, nbf). + """ + + for start in range(0, len(points), block_size): + block = points[start : start + block_size] + + yield slice(start, start + len(block)), self.values(block) + + @abstractmethod + def overlap(self) -> np.ndarray: + """ + Overlap matrix of the AOs. + + Returns: + np.ndarray: The matrix, (nbf, nbf). + """ + + @abstractmethod + def potential(self, dms: np.ndarray, points: np.ndarray) -> np.ndarray: + """ + Electrostatic potential of the electrons of AO density matrices at points, from + analytic integrals: ``-sum_mn D_mn ``, negative for a positive + density. The nuclei are not included, nor any spin factor. + + Args: + dms (np.ndarray): AO density matrices, (M, nbf, nbf). + points (np.ndarray): Points R in bohr, (n, 3). + + Returns: + np.ndarray: The potential, (M, n). + """ + + @abstractmethod + def field_integrals(self, origin: np.ndarray) -> list[np.ndarray]: + """ + Integrals of the electric field operator, ````. + + Args: + origin (np.ndarray): The point R in bohr, (3,). + + Returns: + list[np.ndarray]: The x, y and z components, (nbf, nbf) each. + """ + + def molecular_grid( + self, + radial_points: int, + spherical_points: int, + nuclear_scheme: str, + bs_radius_alpha: float, + ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + The code's molecular quadrature grid around the atoms, ghost atoms included: an + unpruned Treutler radial grid times a Lebedev spherical grid at every atom, with + space divided between the atoms. The arguments are those of + `prop_sapt.partition.molecular_grid`, checked and with their defaults filled in. + + Returns: + tuple[np.ndarray, np.ndarray, np.ndarray]: Points in bohr, (n, 3), weights, + (n,), and the index of the atom each point belongs to, (n,). + + Raises: + NotImplementedError: If the code has no such grid, as by default. + """ + + raise NotImplementedError( + f"{type(self).__name__} has no molecular quadrature grid; " + "give the points and weights of another grid." + ) + + class Backend(ABC): """ A reference calculation of a dimer by a quantum-chemistry code, with the operations @@ -191,6 +320,17 @@ def nbf(self) -> int: """Number of basis functions of the dimer basis set.""" return self.S.shape[0] + @property + def basis(self) -> AOBasis: + """The dimer basis set on the dimer's atoms, in the order of `fragments` and the + AO order of `S`, to analyse AO matrices with. Not needed for energies, properties and density matrices; + raises `NotImplementedError` if the backend has none, as by default.""" + + raise NotImplementedError( + f"{type(self).__name__} has no `basis`, which the analysis of AO matrices " + "(cubes, values at points, fragment operators) needs." + ) + @abstractmethod def compute_jk( self, lefts: Sequence[np.ndarray], rights: Sequence[np.ndarray] diff --git a/prop_sapt/backends/psi4_backend.py b/prop_sapt/backends/psi4_backend.py index 13431d6..03c245d 100644 --- a/prop_sapt/backends/psi4_backend.py +++ b/prop_sapt/backends/psi4_backend.py @@ -13,9 +13,10 @@ import logging import time +import warnings from collections.abc import Sequence from contextlib import contextmanager -from functools import wraps +from functools import cached_property, wraps from typing import Iterator, Literal, overload import numpy as np @@ -25,6 +26,7 @@ from ..fragments import DimerFragments from .base import MONOMERS, Backend, MonomerReference, check_reference +from .psi4_basis import Psi4Basis logger = logging.getLogger(__name__) @@ -88,6 +90,38 @@ def changed_psi4_options() -> dict | None: return prepare_options_for_set_options() +def warn_of_ecps(basisset: psi4.core.BasisSet, stacklevel: int = 2): + """ + Warn if a basis set has effective core potentials (ECPs), and log the same message. + propSAPT is all-electron: the potentials of the monomers (`MonomerReference.V`) are + those of their nuclei, without the ECP operators, and Psi4 sets the nuclear charges + of the dimer back to the full ones when the fitting basis sets are built. + + Args: + basisset (psi4.core.BasisSet): The basis set, on the atoms of its molecule. + stacklevel (int, optional): Stack level of the warning, as in `warnings.warn`. + Defaults to the caller of this function. + """ + + if not basisset.has_ECP(): + return + + molecule = basisset.molecule() + elements = { + molecule.symbol(atom).capitalize() + for atom in range(molecule.natom()) + if basisset.n_ecp_core(molecule.label(atom)) > 0 + } + message = ( + "The basis set has effective core potentials (ECPs), on " + f"{', '.join(sorted(elements))}. propSAPT is all-electron and may not perform " + "well with them: the electrostatic energy takes the full nuclear charges, and " + "the ECP operators are left out of the monomer potentials." + ) + warnings.warn(message, UserWarning, stacklevel=stacklevel) + logger.warning(message) + + class Psi4OutputFormatter(logging.Formatter): """The message alone, after its level ("Warning: ...") for warnings and errors.""" @@ -279,6 +313,8 @@ def __init__( dimer, psi4.core.get_global_option("BASIS") ) self.mints = psi4.core.MintsHelper(self.dimer_wfn.basisset()) + # attributed to the caller of `Dimer(...)` + warn_of_ecps(self.dimer_wfn.basisset(), stacklevel=4) # DF integrals in AO aux_basis = psi4.core.BasisSet.build( @@ -351,6 +387,12 @@ def basisset(self) -> psi4.core.BasisSet: return self.dimer_wfn.basisset() + @cached_property + def basis(self) -> Psi4Basis: + """The dimer basis set to analyse AO matrices with, see `Backend.basis`.""" + + return Psi4Basis(self.basisset) + def compute_jk( self, lefts: Sequence[np.ndarray], rights: Sequence[np.ndarray] ) -> tuple[list[np.ndarray], list[np.ndarray]]: diff --git a/prop_sapt/backends/psi4_basis.py b/prop_sapt/backends/psi4_basis.py new file mode 100644 index 0000000..d996d70 --- /dev/null +++ b/prop_sapt/backends/psi4_basis.py @@ -0,0 +1,229 @@ +"""Psi4 basis sets as the AO basis of propSAPT's analysis functions. + +The functions of `prop_sapt.evaluate`, `prop_sapt.partition`, `prop_sapt.cubes` and +`prop_sapt.forces` work from a `prop_sapt.backends.AOBasis`. They take a Psi4 basis set +as well: `prop_sapt.backends.ao_basis.as_ao_basis` makes a `Psi4Basis` of it. +""" + +from collections.abc import Iterator + +import numpy as np +import psi4 +from psi4.driver.p4util import OptionsState + +from .base import AOBasis + + +class Psi4Basis(AOBasis): + """ + A Psi4 basis set on the atoms of its molecule. + + Attributes: + basisset (psi4.core.BasisSet): The basis set. + + Args: + basisset (psi4.core.BasisSet): The basis set. + + Raises: + TypeError: If `basisset` is not a Psi4 basis set. + """ + + def __init__(self, basisset: psi4.core.BasisSet): + + if not isinstance(basisset, psi4.core.BasisSet): + raise TypeError( + "`basisset` should be of type `psi4.core.BasisSet` " + f"was `{type(basisset)}`!" + ) + + self.basisset = basisset + self._coordinates, self._charges = molecule_arrays(basisset.molecule()) + + # made when first needed, and kept + self._mints = None + + @property + def nbf(self) -> int: + """Number of basis functions.""" + + return self.basisset.nbf() + + @property + def coordinates(self) -> np.ndarray: + """Coordinates of the molecule's atoms in bohr, read-only.""" + + return self._coordinates + + @property + def charges(self) -> np.ndarray: + """Nuclear charges of the molecule's atoms, 0 for ghost atoms, read-only.""" + + return self._charges + + @property + def mints(self) -> psi4.core.MintsHelper: + """`psi4.core.MintsHelper` of the basis set.""" + + if self._mints is None: + self._mints = psi4.core.MintsHelper(self.basisset) + + return self._mints + + def values(self, points: np.ndarray) -> np.ndarray: + """Values of the basis functions at `points`, see `AOBasis.values`.""" + + for _, phi in self.value_blocks(points, max(len(points), 1)): + return phi + + return np.zeros((0, self.nbf)) + + def value_blocks( + self, points: np.ndarray, block_size: int + ) -> Iterator[tuple[slice, np.ndarray]]: + """Values of the basis functions at blocks of `points`, see + `AOBasis.value_blocks`. The Psi4 objects that compute them are made once per + loop and shared by its blocks (rebuilding them per block makes the values about + 1.5 times slower). No other loop shares them, so loops in different threads do + not interfere, and their memory is freed when the loop ends.""" + + n_points = len(points) + if n_points == 0: + return + + nbf = self.nbf + # delta = 0 switches the screening off, any positive cutoff zeroes distant + # functions + extents = psi4.core.BasisExtents(self.basisset, 0.0) + # room for the largest block: Psi4 does not check it + functions = psi4.core.BasisFunctions( + self.basisset, min(block_size, n_points), nbf + ) + + for start in range(0, n_points, block_size): + block_points = points[start : start + block_size] + n_block = len(block_points) + + block = psi4.core.BlockOPoints( + psi4.core.Vector.from_array(np.ascontiguousarray(block_points[:, 0])), + psi4.core.Vector.from_array(np.ascontiguousarray(block_points[:, 1])), + psi4.core.Vector.from_array(np.ascontiguousarray(block_points[:, 2])), + psi4.core.Vector.from_array( + np.zeros(n_block) + ), # quadrature weights, unused + extents, + ) + functions.compute_functions(block) + + # values come for the block's local functions, scatter them into Psi4 AO + # order + local_to_global = np.asarray(block.functions_local_to_global(), dtype=int) + phi = np.zeros((n_block, nbf)) + phi[:, local_to_global] = np.asarray(functions.basis_values()["PHI"])[ + :n_block, : local_to_global.size + ] + + yield slice(start, start + n_block), phi + + def overlap(self) -> np.ndarray: + """Overlap matrix (`MintsHelper.ao_overlap`).""" + + return np.asarray(self.mints.ao_overlap()) + + def potential(self, dms: np.ndarray, points: np.ndarray) -> np.ndarray: + """Electrostatic potential of the electrons of `dms` at `points` + (`MintsHelper.electrostatic_potential_value`), see `AOBasis.potential`.""" + + potential = np.zeros((len(dms), len(points))) + if len(points) == 0: + return potential + + psi4_points = psi4.core.Matrix.from_array(np.ascontiguousarray(points)) + # unit probe charge at every point, Psi4 returns the electronic potential only + probe_charges = psi4.core.Vector.from_array(np.ones(len(points))) + + for m_idx, dm in enumerate(dms): + potential[m_idx] = np.asarray( + self.mints.electrostatic_potential_value( + probe_charges, psi4_points, psi4.core.Matrix.from_array(dm) + ) + ) + + return potential + + def field_integrals(self, origin: np.ndarray) -> list[np.ndarray]: + """Electric field integrals at `origin` (`MintsHelper.electric_field`), see + `AOBasis.field_integrals`.""" + + return [ints.to_array() for ints in self.mints.electric_field(origin)] + + def molecular_grid( + self, + radial_points: int, + spherical_points: int, + nuclear_scheme: str, + bs_radius_alpha: float, + ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Psi4's molecular quadrature grid (`DFTGrid`), see `AOBasis.molecular_grid`. + The grid options are set here and do not follow the global Psi4 DFT options.""" + + int_options = { + "DFT_RADIAL_POINTS": radial_points, + "DFT_SPHERICAL_POINTS": spherical_points, + } + str_options = { + "DFT_NUCLEAR_SCHEME": str(nuclear_scheme).upper(), + "DFT_RADIAL_SCHEME": "TREUTLER", + "DFT_PRUNING_SCHEME": "NONE", + "DFT_BLOCK_SCHEME": "ATOMIC", # every block of points belongs to one atom + } + + # the Python binding takes only integer and string options, + # the radial extent is read from the global options + saved_options = OptionsState(["DFT_BS_RADIUS_ALPHA"]) + try: + psi4.core.set_global_option("DFT_BS_RADIUS_ALPHA", float(bs_radius_alpha)) + grid = psi4.core.DFTGrid.build( + self.basisset.molecule(), self.basisset, int_options, str_options + ) + finally: + saved_options.restore() + + points, weights, atom_index = [], [], [] + for block in grid.blocks(): + n_block = block.npoints() + points.append( + np.column_stack( + [np.asarray(v)[:n_block] for v in (block.x(), block.y(), block.z())] + ) + ) + weights.append(np.asarray(block.w())[:n_block]) + atom_index.append(np.full(n_block, block.parent_atom(), dtype=int)) + + atom_index = np.concatenate(atom_index) + if np.any((atom_index < 0) | (atom_index >= len(self._charges))): + raise RuntimeError("Psi4 returned grid blocks without a parent atom!") + + return np.concatenate(points), np.concatenate(weights), atom_index + + +def molecule_arrays(molecule: psi4.core.Molecule) -> tuple[np.ndarray, np.ndarray]: + """ + Coordinates and nuclear charges of a Psi4 molecule, copied, read-only. + + Returns: + tuple[np.ndarray, np.ndarray]: Coordinates in bohr, (natom, 3), and charges, + (natom,), 0 for ghost atoms. + """ + + coordinates = np.array(molecule.geometry()) + charges = np.array([molecule.Z(atom) for atom in range(molecule.natom())]) + for array in (coordinates, charges): + array.flags.writeable = False + + return coordinates, charges + + +def option_basis(molecule: psi4.core.Molecule) -> Psi4Basis: + """The basis set of the current `BASIS` option, built for a Psi4 molecule.""" + + return Psi4Basis(psi4.core.Wavefunction.build(molecule).basisset()) diff --git a/prop_sapt/checks.py b/prop_sapt/checks.py index 390109d..1f67fdb 100644 --- a/prop_sapt/checks.py +++ b/prop_sapt/checks.py @@ -34,14 +34,9 @@ import warnings from collections.abc import Mapping import numpy as np -import psi4 - -from .evaluate import ( - _check_basisset, - _get_chunk_size, - _iter_phi_chunks, - _prepare_points, -) + +from .backends.ao_basis import BasisLike, as_ao_basis +from .evaluate import _get_chunk_size, _iter_phi_chunks, _prepare_points from .options import PROPSAPT_OPTIONS logger = logging.getLogger(__name__) @@ -124,7 +119,7 @@ def check_partition_of_unity( points: np.ndarray, weights: np.ndarray, fragment_weights: Mapping[str, np.ndarray], - basisset: psi4.core.BasisSet, + basisset: BasisLike, atol: float | None = None, where: str = "", chunk_size: int | None = None, @@ -151,7 +146,7 @@ def check_partition_of_unity( last axis. fragment_weights (Mapping[str, np.ndarray]): Weight w_X of each fragment at the points, with the same shape as `weights`. - basisset (psi4.core.BasisSet): Basis set of the functions phi. + basisset (AOBasis | psi4.core.BasisSet): Basis set of the functions phi. atol (float | None, optional): Largest defect allowed. Defaults to the `check_partition_atol` option; the check is off if that is None. where (str, optional): What the weights belong to, for the message. @@ -170,7 +165,7 @@ def check_partition_of_unity( if atol is None: return None - _check_basisset(basisset) + basis = as_ao_basis(basisset) points = _prepare_points(points) chunk_size = _get_chunk_size(chunk_size) points_shape = points.shape[:-1] @@ -202,10 +197,10 @@ def check_partition_of_unity( deviating = deviation != 0.0 scaled = (weights * deviation)[deviating] - nbf = basisset.nbf() + nbf = basis.nbf defect_matrix = np.zeros((nbf, nbf)) for chunk, phi in _iter_phi_chunks( - points.reshape(-1, 3)[deviating], basisset, chunk_size + points.reshape(-1, 3)[deviating], basis, chunk_size ): defect_matrix += phi.T @ (scaled[chunk, None] * phi) defect = float(np.max(np.abs(defect_matrix), initial=0.0)) diff --git a/prop_sapt/cubes.py b/prop_sapt/cubes.py index fdddb56..09f86ca 100644 --- a/prop_sapt/cubes.py +++ b/prop_sapt/cubes.py @@ -13,11 +13,10 @@ from collections.abc import Iterable from typing import Sequence import numpy as np -import psi4 +from .backends.ao_basis import AtomsLike, atoms_and_basis from .options import PROPSAPT_OPTIONS from .evaluate import ( - _electronic_esp, _evaluate_on_points, _get_chunk_size, _nuclear_potential, @@ -374,18 +373,19 @@ def _check_same_grid( def make_cube( - mol: psi4.core.Molecule, + mol: AtomsLike, matrix: np.ndarray | Sequence[np.ndarray], obj_type: str | Iterable[str] = "density", **kwargs, ) -> Cube | list[Cube]: """ Create a `Cube` object with volumetric data of the given `matrix` - calculated on a grid for a psi4 `Molecule` object. If iterables with matrices and types + calculated on a grid around the atoms of `mol`. If iterables with matrices and types are given as `matrix` and `obj_type` returns a list with a Cube for each element of the list. Args: - mol (psi4.core.Molecule): A corresponding molecule. + mol (AOBasis | psi4.core.Molecule): The atoms, as a Psi4 molecule or an AO basis + on them, such as `Dimer.basis`. matrix (np.ndarray | Sequence[np.ndarray]): Either density matrix, orbital coefficients vector (shape (nbf,) or one column (nbf, 1) of Psi4's `Ca()`), or list of such objects. @@ -393,9 +393,10 @@ def make_cube( must be either "density", "orbital", "esp" or a list with such strings. Defaults to "density". For "esp" the `matrix` is a density matrix and the cube holds the electrostatic potential it generates, from analytic potential integrals (electrons negative). - **kwargs: `basisset` (psi4.core.BasisSet) is the basis set the matrices are in. - Without it, one is built for `mol` from the current `BASIS` option; pass it - for matrices of a `Dimer` (or use `Dimer.make_cube`, which does). + **kwargs: `basisset` (AOBasis | psi4.core.BasisSet) is the basis set the matrices + are in. Without it, that is `mol` if it is an AO basis; for a Psi4 molecule one + is built from the current `BASIS` option, so pass it for matrices of a `Dimer` + (or use `Dimer.make_cube`, which does). `grid` (dict) is a grid from `prepare_grid`, reused as given; otherwise one is built around `mol` with `grid_step` and `grid_overage` (bohr), which default to the `cube_grid_step` and `cube_grid_overage` options. @@ -409,6 +410,11 @@ def make_cube( `cube_iso_sum_level` option. Values at the grid points come from `prop_sapt.evaluate`. + Raises: + TypeError: If `mol` or `basisset` is of another type. + ValueError: If `matrix` and `obj_type` do not match, or a matrix has the wrong + shape for the basis set. + Returns: Cube | list[Cube]: Resulting cube(s). """ @@ -451,25 +457,11 @@ def make_cube( " | `make_cube` | \n" " |------------------------------------| " ) - psi4.core.tstart() # get basis set and geometry t_setup = time() - if isinstance(mol, psi4.core.Molecule): - if kwargs.get("basisset", None) is not None and isinstance( - kwargs["basisset"], psi4.core.BasisSet - ): - basisset = kwargs["basisset"] - else: - basisset = psi4.core.Wavefunction.build(mol).basisset() - geo_matrix, _, _, elez, _ = mol.to_arrays() - - else: - raise TypeError( - f"`mol` should be of type `psi4.core.Molecule` was `{type(mol)}`!" - ) - - basisset.print_out() + geo_matrix, charges, basis = atoms_and_basis(mol, kwargs.get("basisset")) + logger.info(f" Basis set : {basis.nbf} functions, {len(charges)} atoms") if kwargs.get("grid", None) is not None and isinstance(kwargs["grid"], dict): grid = kwargs["grid"] @@ -518,7 +510,7 @@ def make_cube( orbital_idx_arr = np.array(orbital_indices, dtype=int) esp_idx_arr = np.array(esp_indices, dtype=int) - nbf = basisset.nbf() + nbf = basis.nbf density_stack = ( _stack_matrices([matrix[idx] for idx in density_indices], nbf)[0] if density_indices @@ -534,8 +526,6 @@ def make_cube( if esp_indices else None ) - if esp_indices: - mints = psi4.core.MintsHelper(basisset) chunk_size = _get_chunk_size(kwargs.get("chunk_size", None)) yz_points = np.stack( @@ -552,9 +542,9 @@ def make_cube( # ESP from analytic potential integrals if esp_indices: _t0 = time() - esp = _electronic_esp(points, mints, esp_stack) + esp = basis.potential(esp_stack, points) if esp_nuclei: - esp += _nuclear_potential(points, mol) + esp += _nuclear_potential(points, geo_matrix, charges) values[esp_idx_arr, i] = esp.reshape(slice_shape) t_esp += time() - _t0 @@ -562,7 +552,7 @@ def make_cube( if density_stack is not None or orbital_columns is not None: densities, orbitals = _evaluate_on_points( points, - basisset, + basis, chunk_size, density_stack=density_stack, orbital_columns=orbital_columns, @@ -616,10 +606,10 @@ def make_cube( "comment1": "propSAPT .cube file", "comment2": comment2, "origin": [grid["x"][0], grid["y"][0], grid["z"][0]], - "n_atoms": len(elez), + "n_atoms": len(charges), "atoms": [ - (int(atom_num), float(0.0), atom_xyz) - for atom_xyz, atom_num in zip(geo_matrix, elez) + (int(atom_num), float(0.0), np.copy(atom_xyz)) + for atom_xyz, atom_num in zip(geo_matrix, charges) ], "n_x": grid["n_x"], "n_y": grid["n_y"], @@ -634,7 +624,6 @@ def make_cube( # finalize logger.info(f"...finished in {(time() - t_start):5.2f} s total.") - psi4.core.tstop() logger.info("*" * 80) if len(cubes_list) == 1: diff --git a/prop_sapt/evaluate.py b/prop_sapt/evaluate.py index 272c22c..1ea06a2 100644 --- a/prop_sapt/evaluate.py +++ b/prop_sapt/evaluate.py @@ -1,10 +1,11 @@ """ Evaluation of densities, orbitals and the electrostatic potential at arbitrary points. -All functions take `points` in bohr, as an array of shape (..., 3), and the Psi4 basis -set in which the matrices are expressed (Psi4 AO order, `basisset.nbf()` functions). -The values are returned with the shape of `points` without its last axis, preceded by -one axis over the matrices or orbitals when several are given. +All functions take `points` in bohr, as an array of shape (..., 3), and the basis set in +which the matrices are expressed, in its AO order: a `prop_sapt.backends.AOBasis`, such +as `Dimer.basis`, or a Psi4 basis set. The values are returned with the shape of `points` +without its last axis, preceded by one axis over the matrices or orbitals when several are +given. Basis function values are computed for blocks of `chunk_size` points at a time, which bounds the memory to `chunk_size * nbf` values; the default is the @@ -26,14 +27,15 @@ from time import time from typing import Sequence import numpy as np -import psi4 +from .backends.base import AOBasis +from .backends.ao_basis import BasisLike, as_ao_basis from .options import PROPSAPT_OPTIONS def evaluate_basis_functions( points: np.ndarray, - basisset: psi4.core.BasisSet, + basisset: BasisLike, chunk_size: int | None = None, ) -> np.ndarray: """ @@ -41,30 +43,31 @@ def evaluate_basis_functions( Args: points (np.ndarray): Points in bohr, shape (..., 3). - basisset (psi4.core.BasisSet): Basis set to evaluate. + basisset (AOBasis | psi4.core.BasisSet): Basis set to evaluate. chunk_size (int | None, optional): Number of points evaluated at once. Defaults to the `point_eval_chunk_size` option. Returns: - np.ndarray: Basis function values, shape (..., nbf), in Psi4 AO order. + np.ndarray: Basis function values, shape (..., nbf), in the AO order of the + basis set. """ - _check_basisset(basisset) + basis = as_ao_basis(basisset) points = _prepare_points(points) chunk_size = _get_chunk_size(chunk_size) flat_points = points.reshape(-1, 3) - phi = np.empty((len(flat_points), basisset.nbf())) - for chunk, phi_chunk in _iter_phi_chunks(flat_points, basisset, chunk_size): + phi = np.empty((len(flat_points), basis.nbf)) + for chunk, phi_chunk in _iter_phi_chunks(flat_points, basis, chunk_size): phi[chunk] = phi_chunk - return phi.reshape(points.shape[:-1] + (basisset.nbf(),)) + return phi.reshape(points.shape[:-1] + (basis.nbf,)) def evaluate_density( dm: np.ndarray | Sequence[np.ndarray], points: np.ndarray, - basisset: psi4.core.BasisSet, + basisset: BasisLike, chunk_size: int | None = None, ) -> np.ndarray: """ @@ -77,7 +80,7 @@ def evaluate_density( dm (np.ndarray | Sequence[np.ndarray]): AO density matrix, shape (nbf, nbf), or several of them, as a sequence or an array of shape (M, nbf, nbf). points (np.ndarray): Points in bohr, shape (..., 3). - basisset (psi4.core.BasisSet): Basis set of `dm`. + basisset (AOBasis | psi4.core.BasisSet): Basis set of `dm`. chunk_size (int | None, optional): Number of points evaluated at once. Defaults to the `point_eval_chunk_size` option. @@ -86,13 +89,13 @@ def evaluate_density( and (M, ...) for several. """ - _check_basisset(basisset) - dm_stack, single = _stack_matrices(dm, basisset.nbf()) + basis = as_ao_basis(basisset) + dm_stack, single = _stack_matrices(dm, basis.nbf) points = _prepare_points(points) chunk_size = _get_chunk_size(chunk_size) densities, _ = _evaluate_on_points( - points.reshape(-1, 3), basisset, chunk_size, density_stack=dm_stack + points.reshape(-1, 3), basis, chunk_size, density_stack=dm_stack ) return _shape_output(densities, single, points.shape[:-1]) @@ -101,7 +104,7 @@ def evaluate_density( def evaluate_orbital( coeffs: np.ndarray, points: np.ndarray, - basisset: psi4.core.BasisSet, + basisset: BasisLike, chunk_size: int | None = None, ) -> np.ndarray: """ @@ -115,7 +118,7 @@ def evaluate_orbital( coeffs (np.ndarray): MO coefficients, shape (nbf,) for one orbital or (nbf, k) for k orbitals. points (np.ndarray): Points in bohr, shape (..., 3). - basisset (psi4.core.BasisSet): Basis set of `coeffs`. + basisset (AOBasis | psi4.core.BasisSet): Basis set of `coeffs`. chunk_size (int | None, optional): Number of points evaluated at once. Defaults to the `point_eval_chunk_size` option. @@ -124,13 +127,13 @@ def evaluate_orbital( and (k, ...) for `coeffs` of shape (nbf, k). """ - _check_basisset(basisset) - orbital_columns, single = _stack_orbitals(coeffs, basisset.nbf()) + basis = as_ao_basis(basisset) + orbital_columns, single = _stack_orbitals(coeffs, basis.nbf) points = _prepare_points(points) chunk_size = _get_chunk_size(chunk_size) _, orbitals = _evaluate_on_points( - points.reshape(-1, 3), basisset, chunk_size, orbital_columns=orbital_columns + points.reshape(-1, 3), basis, chunk_size, orbital_columns=orbital_columns ) return _shape_output(orbitals, single, points.shape[:-1]) @@ -139,7 +142,7 @@ def evaluate_orbital( def evaluate_esp( dm: np.ndarray | Sequence[np.ndarray], points: np.ndarray, - basisset: psi4.core.BasisSet, + basisset: BasisLike, nuclei: bool = False, ) -> np.ndarray: """ @@ -152,8 +155,8 @@ def evaluate_esp( dm (np.ndarray | Sequence[np.ndarray]): AO density matrix, shape (nbf, nbf), or several of them, as a sequence or an array of shape (M, nbf, nbf). points (np.ndarray): Points in bohr, shape (..., 3). - basisset (psi4.core.BasisSet): Basis set of `dm`. - nuclei (bool, optional): Add the potential of the nuclei of `basisset.molecule()`, + basisset (AOBasis | psi4.core.BasisSet): Basis set of `dm`. + nuclei (bool, optional): Add the potential of the nuclei of the basis set's atoms, use it for total (not interaction-induced) densities. Ghost atoms carry no charge, and a nucleus lying exactly on a point is skipped at that point. Defaults to False. @@ -163,28 +166,18 @@ def evaluate_esp( and (M, ...) for several. """ - _check_basisset(basisset) - dm_stack, single = _stack_matrices(dm, basisset.nbf()) + basis = as_ao_basis(basisset) + dm_stack, single = _stack_matrices(dm, basis.nbf) points = _prepare_points(points) flat_points = points.reshape(-1, 3) - mints = psi4.core.MintsHelper(basisset) - esp = _electronic_esp(flat_points, mints, dm_stack) + esp = basis.potential(dm_stack, flat_points) if nuclei: - esp += _nuclear_potential(flat_points, basisset.molecule()) + esp += _nuclear_potential(flat_points, basis.coordinates, basis.charges) return _shape_output(esp, single, points.shape[:-1]) -def _check_basisset(basisset): - """Raises `TypeError` if `basisset` is not a Psi4 basis set.""" - - if not isinstance(basisset, psi4.core.BasisSet): - raise TypeError( - f"`basisset` should be of type `psi4.core.BasisSet` was `{type(basisset)}`!" - ) - - def _prepare_points(points) -> np.ndarray: """Returns `points` as a float array, checking that its last axis has length 3.""" @@ -221,7 +214,8 @@ def _stack_matrices(dm, nbf: int) -> tuple[np.ndarray, bool]: tuple[np.ndarray, bool]: The stack, and whether a single matrix was given. """ - if isinstance(dm, (np.ndarray, psi4.core.Matrix)): + # a Psi4 `Matrix` is an array too, through its array interface + if hasattr(dm, "__array_interface__"): stack = np.asarray(dm, dtype=float) single = stack.ndim == 2 if single: @@ -279,14 +273,14 @@ def _shape_output(values: np.ndarray, single: bool, points_shape: tuple) -> np.n def _iter_phi_chunks( - points: np.ndarray, basisset: psi4.core.BasisSet, chunk_size: int + points: np.ndarray, basis: AOBasis, chunk_size: int ) -> Iterator[tuple[slice, np.ndarray]]: """ Yields basis function values for consecutive chunks of `points`. Args: points (np.ndarray): Points in bohr, shape (n, 3). - basisset (psi4.core.BasisSet): Basis set to evaluate. + basis (AOBasis): Basis set to evaluate. chunk_size (int): Number of points per chunk. Yields: @@ -294,43 +288,12 @@ def _iter_phi_chunks( values there, shape (n_chunk, nbf). """ - n_points = len(points) - if n_points == 0: - return - - nbf = basisset.nbf() - # delta = 0 switches the screening off, any positive cutoff zeroes distant functions - extents = psi4.core.BasisExtents(basisset, 0.0) - functions = psi4.core.BasisFunctions(basisset, min(chunk_size, n_points), nbf) - - for start in range(0, n_points, chunk_size): - chunk_points = points[start : start + chunk_size] - n_chunk = len(chunk_points) - - block = psi4.core.BlockOPoints( - psi4.core.Vector.from_array(np.ascontiguousarray(chunk_points[:, 0])), - psi4.core.Vector.from_array(np.ascontiguousarray(chunk_points[:, 1])), - psi4.core.Vector.from_array(np.ascontiguousarray(chunk_points[:, 2])), - psi4.core.Vector.from_array( - np.zeros(n_chunk) - ), # quadrature weights, unused - extents, - ) - functions.compute_functions(block) - - # values come for the block's local functions, scatter them into Psi4 AO order - local_to_global = np.asarray(block.functions_local_to_global(), dtype=int) - phi = np.zeros((n_chunk, nbf)) - phi[:, local_to_global] = np.asarray(functions.basis_values()["PHI"])[ - :n_chunk, : local_to_global.size - ] - - yield slice(start, start + n_chunk), phi + yield from basis.value_blocks(points, chunk_size) def _evaluate_on_points( points: np.ndarray, - basisset: psi4.core.BasisSet, + basis: AOBasis, chunk_size: int, density_stack: np.ndarray | None = None, orbital_columns: np.ndarray | None = None, @@ -342,7 +305,7 @@ def _evaluate_on_points( Args: points (np.ndarray): Points in bohr, shape (n, 3). - basisset (psi4.core.BasisSet): Basis set of the matrices. + basis (AOBasis): Basis set of the matrices. chunk_size (int): Number of points evaluated at once. density_stack (np.ndarray | None, optional): AO density matrices, shape (M, nbf, nbf). Defaults to None. @@ -370,7 +333,7 @@ def _evaluate_on_points( t_phi = 0.0 t_contract = 0.0 _t0 = time() - for chunk, phi in _iter_phi_chunks(points, basisset, chunk_size): + for chunk, phi in _iter_phi_chunks(points, basis, chunk_size): _t1 = time() t_phi += _t1 - _t0 @@ -392,58 +355,26 @@ def _evaluate_on_points( return densities, orbitals -def _electronic_esp( - points: np.ndarray, mints: psi4.core.MintsHelper, dm_stack: np.ndarray +def _nuclear_potential( + points: np.ndarray, coordinates: np.ndarray, charges: np.ndarray ) -> np.ndarray: """ - Electrostatic potential of the electrons of each AO density matrix at `points`. - - Args: - points (np.ndarray): Points in bohr, shape (n, 3). - mints (psi4.core.MintsHelper): Integral helper built on the matrices' basis set. - dm_stack (np.ndarray): AO density matrices, shape (M, nbf, nbf). - - Returns: - np.ndarray: Potential, shape (M, n). - """ - - esp = np.zeros((len(dm_stack), len(points))) - if len(points) == 0: - return esp - - psi4_points = psi4.core.Matrix.from_array(np.ascontiguousarray(points)) - # unit probe charge at every point, Psi4 returns the electronic potential only - probe_charges = psi4.core.Vector.from_array(np.ones(len(points))) - - for m_idx, dm in enumerate(dm_stack): - esp[m_idx] = np.asarray( - mints.electrostatic_potential_value( - probe_charges, psi4_points, psi4.core.Matrix.from_array(dm) - ) - ) - - return esp - - -def _nuclear_potential(points: np.ndarray, molecule: psi4.core.Molecule) -> np.ndarray: - """ - Electrostatic potential of the nuclei of `molecule` at `points`, - sum_A Z_A / |r - R_A|. A nucleus lying exactly on a point is skipped at that point. + Electrostatic potential of nuclei at `points`, sum_A Z_A / |r - R_A|. A nucleus lying + exactly on a point is skipped at that point. Args: points (np.ndarray): Points in bohr, shape (n, 3). - molecule (psi4.core.Molecule): Molecule with the nuclei, ghost atoms have no charge. + coordinates (np.ndarray): Coordinates of the atoms in bohr, shape (natom, 3). + charges (np.ndarray): Charges of the nuclei, shape (natom,), 0 for ghost atoms. Returns: np.ndarray: Potential, shape (n,). """ - nuclei = np.asarray(molecule.geometry()) # in bohr potential = np.zeros(len(points)) # one nucleus at a time keeps the memory at the number of points - for atom_idx, nucleus in enumerate(nuclei): - charge = molecule.Z(atom_idx) + for nucleus, charge in zip(coordinates, charges): if charge == 0.0: continue diff --git a/prop_sapt/forces.py b/prop_sapt/forces.py index d1ac439..0b3742f 100644 --- a/prop_sapt/forces.py +++ b/prop_sapt/forces.py @@ -10,13 +10,17 @@ Purely nuclear-nuclear repulsion force on a given nucleus (no electron density needed). """ +import logging from typing import Sequence import numpy as np -import psi4 + +from .backends.ao_basis import AtomsLike, atoms_and_basis, atoms_of + +logger = logging.getLogger(__name__) def calc_force_at_nuc( - mol: psi4.core.Molecule, + mol: AtomsLike, rho: np.ndarray | Sequence[np.ndarray], atidx: int, add_nuclear: bool = True, @@ -32,18 +36,20 @@ def calc_force_at_nuc( provided, the electric field integrals are computed only once and reused for all matrices. Args: - mol (psi4.core.Molecule): Psi4 molecule defining the geometry and nuclear charges. + mol (AOBasis | psi4.core.Molecule): The atoms, with their nuclear charges, as a + Psi4 molecule or an AO basis on them, such as `Dimer.basis`. rho (np.ndarray | Sequence[np.ndarray]): One-particle density matrix in the AO basis, shape (nbf, nbf), or a sequence of such matrices. atidx (int): Zero-based index of the nucleus on which the force is computed. add_nuclear (bool, optional): If True, adds the nuclear-nuclear repulsion force. Set to False to obtain the electronic contribution only. Defaults to True. - **kwargs: Accepts `basisset` (psi4.core.BasisSet) to reuse a pre-built basis set - instead of constructing one from the molecule. + **kwargs: `basisset` (AOBasis | psi4.core.BasisSet) is the basis set of `rho`. + Without it, that is `mol` if it is an AO basis; for a Psi4 molecule one is + built from the current `BASIS` option. Raises: ValueError: If `rho` is an empty sequence. - TypeError: If `mol` is not a psi4.core.Molecule. + TypeError: If `mol` or `basisset` is of another type. Returns: np.ndarray | list[np.ndarray]: Force vector of shape (3,) in atomic units (Hartree/Bohr) @@ -64,32 +70,20 @@ def calc_force_at_nuc( "`rho` must be either np.ndarray or Iterable of nonzero length." ) - # check mol and get the basisset - if isinstance(mol, psi4.core.Molecule): - if kwargs.get("basisset", None) is not None and isinstance( - kwargs["basisset"], psi4.core.BasisSet - ): - basisset = kwargs["basisset"] - else: - basisset = psi4.core.Wavefunction.build(mol).basisset() - - else: - raise TypeError( - f"`mol` should be of type `psi4.core.Molecule` was `{type(mol)}`!" - ) - - # get molecular geometry and atomic numbers - geom, _, _, elez, _ = mol.to_arrays() + # get the atoms and the basis set + geom, charges, basis = atoms_and_basis(mol, kwargs.get("basisset")) + logger.info(f"Basis set: {basis.nbf} functions, {len(charges)} atoms") # prepare electric field operator integrals - basisset.print_out() - mints = psi4.core.MintsHelper(basisset) - field_ints = [ints.to_array() for ints in mints.electric_field(geom[atidx])] + field_ints = basis.field_integrals(geom[atidx]) # calculate force forces_list = [ np.array( - [elez[atidx] * np.einsum("ij,ji", rho_idx, field_ints[i]) for i in range(3)] + [ + charges[atidx] * np.einsum("ij,ji", rho_idx, field_ints[i]) + for i in range(3) + ] ) for rho_idx in rho ] @@ -106,24 +100,28 @@ def calc_force_at_nuc( return forces_list -def calc_force_nuc_nuc(mol: psi4.core.Molecule, atidx: int) -> np.ndarray: +def calc_force_nuc_nuc(mol: AtomsLike, atidx: int) -> np.ndarray: """Computes the nuclear-nuclear repulsion force on nucleus `atidx` from all other nuclei. Uses Coulomb's law: ``F_a = sum_{b != a} Z_a * Z_b * (R_a - R_b) / |R_a - R_b|^3``. Args: - mol (psi4.core.Molecule): Psi4 molecule defining the geometry and nuclear charges. + mol (AOBasis | psi4.core.Molecule): The atoms, with their nuclear charges, as a + Psi4 molecule or an AO basis on them, such as `Dimer.basis`. atidx (int): Zero-based index of the nucleus on which the force is computed. + Raises: + TypeError: If `mol` is of another type. + Returns: np.ndarray: Nuclear-nuclear force vector of shape (3,) in atomic units (Hartree/Bohr). """ - geom, _, _, elez, _ = mol.to_arrays() + geom, charges = atoms_of(mol) - Z_a = elez[atidx] + Z_a = charges[atidx] force = np.array([0.0, 0.0, 0.0]) - for i, Z_b in enumerate(elez): + for i, Z_b in enumerate(charges): if i == atidx: continue diff --git a/prop_sapt/molecule.py b/prop_sapt/molecule.py index 3448876..4f28733 100644 --- a/prop_sapt/molecule.py +++ b/prop_sapt/molecule.py @@ -14,7 +14,7 @@ from .sinfinity import sinfinity from .cubes import Cube, make_cube from .evaluate import evaluate_density, evaluate_esp, evaluate_orbital -from .backends.base import Backend +from .backends.base import AOBasis, Backend from .backends.psi4_backend import Psi4Backend from .options import PROPSAPT_OPTIONS, check_cpscf_type, check_df_basis_cpscf from .partition import ( @@ -88,6 +88,8 @@ class Dimer(sinfinity): `jk`, and so are its settings: `jk_memory` and `memory` (of the J/K objects), `psi4_options` and `fitting_bases`. + `basis` is the dimer basis set as the analysis functions take it, of any backend. + `Dimer.from_backend` makes a dimer of a backend calculation that has run already. Args: @@ -397,6 +399,37 @@ def clear_theta_amplitudes(self): self.theta_amplitudes.clear() + @property + def basis(self) -> AOBasis: + """ + The dimer basis set on the dimer's atoms, the one its density matrices are in, + for the functions of `prop_sapt.evaluate`, `prop_sapt.partition`, + `prop_sapt.cubes` and `prop_sapt.forces`. + + Raises: + NotImplementedError: If the dimer's backend has none, see `Backend.basis`. + ValueError: If the backend's basis is not of the size of the dimer's + matrices, or not on the atoms of `fragments` in their order: its fragment + weights, nuclear charges and forces would be those of other atoms. + """ + + basis = self.backend.basis + if basis.nbf != self.nbf: + raise ValueError( + f"The backend's basis has {basis.nbf} functions, but its matrices " + f"{self.nbf}!" + ) + atoms = self.backend.fragments.coordinates + if np.shape(basis.coordinates) != atoms.shape or not np.allclose( + basis.coordinates, atoms, rtol=0, atol=1e-6 + ): + raise ValueError( + "The backend's basis is not on the dimer's atoms in the order of its " + "fragments!" + ) + + return basis + def get_psi4_molecule(self) -> psi4.core.Molecule: """ Get 'psi4.core.Molecule' object of the dimer. @@ -449,24 +482,20 @@ def make_cube( either "density", "orbital", "esp" or a list with such strings. Defaults to "density". **kwargs: Passed to `prop_sapt.cubes.make_cube`, e.g. `grid_step` or `esp_nuclei`. - `basisset` defaults to the dimer's basis set, see `get_psi4_basisset`. + `basisset` defaults to the dimer's basis set, `basis`. Returns: Cube | list[Cube]: Resulting cube(s). """ - if kwargs.get("basisset") is None: - kwargs["basisset"] = self.get_psi4_basisset() - - return make_cube( - self.get_psi4_molecule(), matrix=matrix, obj_type=obj_type, **kwargs - ) + with self.backend.timer(): + return make_cube(self.basis, matrix=matrix, obj_type=obj_type, **kwargs) def evaluate_density( self, dm: np.ndarray | Sequence[np.ndarray], points: np.ndarray, - basisset: psi4.core.BasisSet | None = None, + basisset: AOBasis | psi4.core.BasisSet | None = None, chunk_size: int | None = None, ) -> np.ndarray: """ @@ -477,7 +506,7 @@ def evaluate_density( dm (np.ndarray | Sequence[np.ndarray]): AO density matrix, shape (nbf, nbf), or several of them, as a sequence or an array of shape (M, nbf, nbf). points (np.ndarray): Points in bohr, shape (..., 3). - basisset (psi4.core.BasisSet | None, optional): Basis set of `dm`. + basisset (AOBasis | psi4.core.BasisSet | None, optional): Basis set of `dm`. Defaults to the dimer basis set. chunk_size (int | None, optional): Number of points evaluated at once. Defaults to the `point_eval_chunk_size` option. @@ -488,7 +517,7 @@ def evaluate_density( """ if basisset is None: - basisset = self.get_psi4_basisset() + basisset = self.basis return evaluate_density(dm, points, basisset, chunk_size=chunk_size) @@ -496,7 +525,7 @@ def evaluate_orbital( self, coeffs: np.ndarray, points: np.ndarray, - basisset: psi4.core.BasisSet | None = None, + basisset: AOBasis | psi4.core.BasisSet | None = None, chunk_size: int | None = None, ) -> np.ndarray: """ @@ -507,8 +536,8 @@ def evaluate_orbital( coeffs (np.ndarray): MO coefficients, shape (nbf,) for one orbital or (nbf, k) for k orbitals. points (np.ndarray): Points in bohr, shape (..., 3). - basisset (psi4.core.BasisSet | None, optional): Basis set of `coeffs`. - Defaults to the dimer basis set. + basisset (AOBasis | psi4.core.BasisSet | None, optional): Basis set of + `coeffs`. Defaults to the dimer basis set. chunk_size (int | None, optional): Number of points evaluated at once. Defaults to the `point_eval_chunk_size` option. @@ -518,7 +547,7 @@ def evaluate_orbital( """ if basisset is None: - basisset = self.get_psi4_basisset() + basisset = self.basis return evaluate_orbital(coeffs, points, basisset, chunk_size=chunk_size) @@ -527,7 +556,7 @@ def evaluate_esp( dm: np.ndarray | Sequence[np.ndarray], points: np.ndarray, nuclei: bool = False, - basisset: psi4.core.BasisSet | None = None, + basisset: AOBasis | psi4.core.BasisSet | None = None, ) -> np.ndarray: """ Evaluate the electrostatic potential of AO density matrix `dm` at `points`, @@ -538,9 +567,9 @@ def evaluate_esp( or several of them, as a sequence or an array of shape (M, nbf, nbf). points (np.ndarray): Points in bohr, shape (..., 3). nuclei (bool, optional): Add the potential of the nuclei of the basis set's - molecule, use it for total (not interaction-induced) densities. + atoms, use it for total (not interaction-induced) densities. Defaults to False. - basisset (psi4.core.BasisSet | None, optional): Basis set of `dm`. + basisset (AOBasis | psi4.core.BasisSet | None, optional): Basis set of `dm`. Defaults to the dimer basis set. Returns: @@ -549,7 +578,7 @@ def evaluate_esp( """ if basisset is None: - basisset = self.get_psi4_basisset() + basisset = self.basis return evaluate_esp(dm, points, basisset, nuclei=nuclei) @@ -596,11 +625,11 @@ def fragment_operators( f"Grid options {sorted(grid_kwargs)} cannot be used with a given `grid`!" ) - basisset = self.get_psi4_basisset() + basis = self.basis if isinstance(weights, str): if grid is None: - grid = molecular_grid(basisset, **grid_kwargs) + grid = molecular_grid(basis, **grid_kwargs) if weights.lower() == "becke": fragment_weights = becke_fragment_weights( @@ -610,10 +639,10 @@ def fragment_operators( fragment_weights = hirshfeld_fragment_weights( grid.points, { - "A": 2 * np.asarray(self.wfnA.Da()), # RHF spin - "B": 2 * np.asarray(self.wfnB.Da()), + "A": 2 * self.Co_A @ self.Co_A.T, # RHF spin + "B": 2 * self.Co_B @ self.Co_B.T, }, - basisset, + basis, chunk_size=chunk_size, ) else: @@ -632,7 +661,7 @@ def fragment_operators( grid.points, grid.weights, fragment_weights, - basisset, + basis, dipole=dipole, chunk_size=chunk_size, partition_of_unity=partition_of_unity, diff --git a/prop_sapt/partition.py b/prop_sapt/partition.py index 4c43833..1722f45 100644 --- a/prop_sapt/partition.py +++ b/prop_sapt/partition.py @@ -10,11 +10,12 @@ fragment X is then a trace, Tr(D W_X), with no further grid work. The first-moment matrices (r_q times the same weights) give fragment dipoles in the same way. -Points are in bohr. Matrices are in the AO basis of the given Psi4 basis set, in Psi4 AO -order, and no spin factor is applied, as in `prop_sapt.evaluate`: the density matrices -of `calc_densities` follow the `Da` convention, pass `2 * D` for the total (RHF) density. +Points are in bohr. Matrices are in the given basis set, in its AO order (a +`prop_sapt.backends.AOBasis`, such as `Dimer.basis`, or a Psi4 basis set), and no spin +factor is applied, as in `prop_sapt.evaluate`: the density matrices of `calc_densities` +follow the `Da` convention, pass `2 * D` for the total (RHF) density. -Fragment weights come from any partitioning: the Becke partition of Psi4's molecular grid +Fragment weights come from any partitioning: the Becke partition of the molecular grid (`becke_fragment_weights`), Hirshfeld-like weights from the monomer densities (`hirshfeld_fragment_weights`), or weights computed elsewhere, e.g. LISA or MBIS weights from horton_part on its own grid, passed as arrays with that grid's points and weights. @@ -30,7 +31,8 @@ Functions --------- molecular_grid - Psi4's Becke-partitioned molecular quadrature grid of a basis set's molecule. + Becke-partitioned molecular quadrature grid of a basis set's atoms, Psi4's for a Psi4 + basis set. becke_fragment_weights Becke fragment weights on a `QuadratureGrid`, from the atoms of each fragment. hirshfeld_fragment_weights @@ -40,12 +42,10 @@ from collections.abc import Iterable, Mapping from dataclasses import dataclass import numpy as np -import psi4 -from psi4.driver import p4util +from .backends.ao_basis import BasisLike, as_ao_basis from .checks import check_charge_closure, check_partition_of_unity from .evaluate import ( - _check_basisset, _get_chunk_size, _iter_phi_chunks, _prepare_points, @@ -75,21 +75,22 @@ class QuadratureGrid: def molecular_grid( - basisset: psi4.core.BasisSet, + basisset: BasisLike, radial_points: int | None = None, spherical_points: int | None = None, nuclear_scheme: str = "TREUTLER", bs_radius_alpha: float | None = None, ) -> QuadratureGrid: """ - Build Psi4's molecular quadrature grid around the atoms of `basisset.molecule()`. + Build the molecular quadrature grid around the atoms of a basis set, with the + quantum-chemistry code of the basis set: Psi4's grid for a Psi4 basis set. Every atom, ghost atoms included, gets a Treutler radial grid times a Lebedev spherical grid, unpruned, and space is divided between the atoms by `nuclear_scheme`. The grid options are set here and do not follow the global Psi4 DFT options. Args: - basisset (psi4.core.BasisSet): Basis set whose molecule carries the grid. + basisset (AOBasis | psi4.core.BasisSet): Basis set whose atoms carry the grid. radial_points (int | None, optional): Radial points per atom. Defaults to the `quadrature_radial_points` option. spherical_points (int | None, optional): Lebedev points per radial shell, one of @@ -103,9 +104,12 @@ def molecular_grid( Returns: QuadratureGrid: Points, weights and parent atoms of the grid. + + Raises: + NotImplementedError: If the code of the basis set has no such grid. """ - _check_basisset(basisset) + basis = as_ao_basis(basisset) radial_points = _positive_int( radial_points, "quadrature_radial_points", "radial_points" ) @@ -123,50 +127,12 @@ def molecular_grid( f"`bs_radius_alpha` should be a positive number, was {bs_radius_alpha}!" ) - int_options = { - "DFT_RADIAL_POINTS": radial_points, - "DFT_SPHERICAL_POINTS": spherical_points, - } - str_options = { - "DFT_NUCLEAR_SCHEME": str(nuclear_scheme).upper(), - "DFT_RADIAL_SCHEME": "TREUTLER", - "DFT_PRUNING_SCHEME": "NONE", - "DFT_BLOCK_SCHEME": "ATOMIC", # every block of points belongs to one atom - } - - # the Python binding takes only integer and string options, - # the radial extent is read from the global options - saved_options = p4util.OptionsState(["DFT_BS_RADIUS_ALPHA"]) - try: - psi4.core.set_global_option("DFT_BS_RADIUS_ALPHA", float(bs_radius_alpha)) - grid = psi4.core.DFTGrid.build( - basisset.molecule(), basisset, int_options, str_options - ) - finally: - saved_options.restore() - - points, weights, atom_index = [], [], [] - for block in grid.blocks(): - n_block = block.npoints() - points.append( - np.column_stack( - [np.asarray(v)[:n_block] for v in (block.x(), block.y(), block.z())] - ) - ) - weights.append(np.asarray(block.w())[:n_block]) - atom_index.append(np.full(n_block, block.parent_atom(), dtype=int)) - - atom_index = np.concatenate(atom_index) - natom = basisset.molecule().natom() - if np.any((atom_index < 0) | (atom_index >= natom)): - raise RuntimeError("Psi4 returned grid blocks without a parent atom!") - - return QuadratureGrid( - points=np.concatenate(points), - weights=np.concatenate(weights), - atom_index=atom_index, + points, weights, atom_index = basis.molecular_grid( + radial_points, spherical_points, nuclear_scheme, bs_radius_alpha ) + return QuadratureGrid(points=points, weights=weights, atom_index=atom_index) + def becke_fragment_weights( grid: QuadratureGrid, fragment_atoms: Mapping[str, Iterable[int]] @@ -223,7 +189,7 @@ def becke_fragment_weights( def hirshfeld_fragment_weights( points: np.ndarray, densities: Mapping[str, np.ndarray], - basisset: psi4.core.BasisSet, + basisset: BasisLike, chunk_size: int | None = None, ) -> dict[str, np.ndarray]: """ @@ -237,7 +203,7 @@ def hirshfeld_fragment_weights( points (np.ndarray): Points in bohr, shape (..., 3). densities (Mapping[str, np.ndarray]): AO density matrix of each fragment, shape (nbf, nbf), e.g. {"A": 2 * Da_A, "B": 2 * Da_B}. - basisset (psi4.core.BasisSet): Basis set of the density matrices. + basisset (AOBasis | psi4.core.BasisSet): Basis set of the density matrices. chunk_size (int | None, optional): Number of points evaluated at once. Defaults to the `point_eval_chunk_size` option. @@ -345,7 +311,7 @@ def from_grid( points: np.ndarray, weights: np.ndarray, fragment_weights: Mapping[str, np.ndarray], - basisset: psi4.core.BasisSet, + basisset: BasisLike, dipole: bool = True, chunk_size: int | None = None, partition_of_unity: bool = True, @@ -365,7 +331,7 @@ def from_grid( without its last axis. fragment_weights (Mapping[str, np.ndarray]): Weight w_X of each fragment at the points, with the same shape as `weights`. - basisset (psi4.core.BasisSet): Basis set of the operators. + basisset (AOBasis | psi4.core.BasisSet): Basis set of the operators. dipole (bool, optional): Also compute the first-moment matrices, needed for `dipole`. Defaults to True. chunk_size (int | None, optional): Number of points evaluated at once. @@ -383,7 +349,7 @@ def from_grid( FragmentOperators: Operators of the fragments in the basis of `basisset`. """ - _check_basisset(basisset) + basis = as_ao_basis(basisset) points = _prepare_points(points) chunk_size = _get_chunk_size(chunk_size) names = _check_fragment_names(fragment_weights) @@ -403,17 +369,17 @@ def from_grid( flat_points, weights, fragment_weights, - basisset, + basis, chunk_size=chunk_size, ) - nbf = basisset.nbf() + nbf = basis.nbf overlaps = {name: np.zeros((nbf, nbf)) for name in names} first_moments = ( {name: np.zeros((3, nbf, nbf)) for name in names} if dipole else None ) - for chunk, phi in _iter_phi_chunks(flat_points, basisset, chunk_size): + for chunk, phi in _iter_phi_chunks(flat_points, basis, chunk_size): chunk_points = flat_points[chunk] for name in names: weighted_phi = (weights[chunk] * fragment_weights[name][chunk])[ @@ -436,7 +402,7 @@ def from_grid( ao_overlap = None if partition_of_unity: - ao_overlap = np.asarray(psi4.core.MintsHelper(basisset).ao_overlap()) + ao_overlap = basis.overlap() return cls(overlaps, first_moments, ao_overlap=ao_overlap) diff --git a/tests/replay_backend.py b/tests/replay_backend.py index fae50f1..5055be6 100644 --- a/tests/replay_backend.py +++ b/tests/replay_backend.py @@ -6,7 +6,9 @@ calculation, Psi4's here, and redoes only the operations, in NumPy from the recorded `Qpq`: the J/K builds and the orbital-Hessian products. A dimer on it (`Dimer.from_backend`) runs propSAPT on the contract alone, so code that still reaches -into Psi4 fails, through the Psi4 attributes of the dimer or `no_psi4_calls`. +into Psi4 fails, through the Psi4 attributes of the dimer or `no_psi4_calls`. It has no +basis functions of its own: the analysis of AO matrices needs a `basis` given to it, such +as the s-Gaussian one of `tests/s_gaussian_basis.py`. Its J/K and Hessian products are those of the fitted integrals that `Qpq` factors. They match Psi4's when Psi4 fits its own J/K in the same basis (`scf_type df` with @@ -20,7 +22,7 @@ import psi4 import pytest -from prop_sapt.backends import Backend +from prop_sapt.backends import AOBasis, Backend from .matched_integrals import df_jk @@ -50,6 +52,8 @@ class ReplayBackend(Backend): dipole_integrals (Sequence[np.ndarray]): AO integrals of the electronic dipole operator, x, y and z. nuclear_dipole (np.ndarray): Dipole moment of the nuclei. + basis (AOBasis | None, optional): The dimer basis set, in the AO order of the + recorded arrays. Defaults to none. """ def __init__( @@ -62,6 +66,7 @@ def __init__( fragments, dipole_integrals, nuclear_dipole, + basis=None, ): super().__init__( @@ -74,11 +79,13 @@ def __init__( ) self._dipole_integrals = [np.array(component) for component in dipole_integrals] self._nuclear_dipole = np.array(nuclear_dipole) + self._basis = basis @classmethod - def record(cls, backend: Backend) -> "ReplayBackend": + def record(cls, backend: Backend, basis: AOBasis | None = None) -> "ReplayBackend": """ - The replay of `backend`'s calculation, with copies of all its arrays. + The replay of `backend`'s calculation, with copies of all its arrays, and with + `basis` as its basis. Raises: ValueError: If the calculation is not RHF: the Hessian of RKS needs the @@ -109,8 +116,13 @@ def record(cls, backend: Backend) -> "ReplayBackend": fragments=backend.fragments, dipole_integrals=backend.dipole_integrals(), nuclear_dipole=backend.nuclear_dipole(), + basis=basis, ) + @property + def basis(self): + return super().basis if self._basis is None else self._basis + def compute_jk(self, lefts, rights): """J and K of each pair on the fitted integrals of `Qpq`.""" diff --git a/tests/s_gaussian_basis.py b/tests/s_gaussian_basis.py new file mode 100644 index 0000000..73f2d2e --- /dev/null +++ b/tests/s_gaussian_basis.py @@ -0,0 +1,151 @@ +"""The s-Gaussian basis: a test double of the AO basis contract, not a basis option. + +It implements `prop_sapt.backends.AOBasis` in NumPy for contracted s functions alone, as +STO-3G has on H and He, where every integral is a textbook formula. A code's basis is +what it stands in for: the analysis functions run on it with no call into Psi4, and its +numbers are independent of Psi4's. It has no molecular grid, the optional part of the +contract. +""" + +import math +from dataclasses import dataclass + +import numpy as np +import psi4 + +from prop_sapt.backends import AOBasis + + +@dataclass(frozen=True, eq=False) +class SShell: + """A contracted s function, ``sum_k coefficients_k exp(-exponents_k |r - center|^2)`` + with the normalisation in the coefficients.""" + + center: np.ndarray + exponents: np.ndarray + coefficients: np.ndarray + + +class SGaussianBasis(AOBasis): + """ + Contracted s functions on atoms, see the module docstring; `record` makes one of a + Psi4 basis set. + + Args: + shells (Sequence[SShell]): The functions, in AO order. + coordinates (np.ndarray): Coordinates of the atoms in bohr, (natom, 3). + charges (np.ndarray): Nuclear charges of the atoms, 0 for ghost atoms. + """ + + def __init__(self, shells, coordinates, charges): + self.shells = list(shells) + self._coordinates = np.array(coordinates) + self._charges = np.array(charges) + + @classmethod + def record(cls, basisset: psi4.core.BasisSet) -> "SGaussianBasis": + """ + The functions and atoms of a Psi4 basis set, copied. + + Raises: + ValueError: If the basis set has functions other than s. + """ + + if basisset.max_am() > 0: + raise ValueError("The s-Gaussian basis has s functions only.") + + molecule = basisset.molecule() + coordinates = np.array(molecule.geometry()) + shells = [] + for index in range(basisset.nshell()): + shell = basisset.shell(index) + primitives = range(shell.nprimitive) + shells.append( + SShell( + center=coordinates[basisset.shell_to_center(index)], + exponents=np.array([shell.exp(k) for k in primitives]), + coefficients=np.array([shell.coef(k) for k in primitives]), + ) + ) + + return cls( + shells, coordinates, [molecule.Z(a) for a in range(molecule.natom())] + ) + + @property + def nbf(self): + return len(self.shells) + + @property + def coordinates(self): + return self._coordinates + + @property + def charges(self): + return self._charges + + def values(self, points): + values = np.zeros((len(points), self.nbf)) + for m, shell in enumerate(self.shells): + r2 = np.sum((points - shell.center) ** 2, axis=1) + values[:, m] = np.exp(-np.outer(r2, shell.exponents)) @ shell.coefficients + + return values + + def overlap(self): + S = np.zeros((self.nbf, self.nbf)) + for m, n, p, K, _ in self._pairs(): + S[m, n] += K * (math.pi / p) ** 1.5 + + return S + + def potential(self, dms, points): + potential = np.zeros((len(dms), len(points))) + for m, n, p, K, P in self._pairs(): + t = p * np.sum((P - points) ** 2, axis=1) + integrals = 2 * math.pi / p * K * boys_0(t) + potential -= np.outer(dms[:, m, n], integrals) + + return potential + + def field_integrals(self, origin): + field = np.zeros((3, self.nbf, self.nbf)) + for m, n, p, K, P in self._pairs(): + t = p * np.sum((P - origin) ** 2) + field[:, m, n] += 4 * math.pi * K * boys_1(t) * (P - origin) + + return list(field) + + def _pairs(self): + """The products of the primitives of every two functions m and n, as Gaussians + ``K exp(-p |r - P|^2)``: yields m, n, p, K and P.""" + + for m, A in enumerate(self.shells): + for n, B in enumerate(self.shells): + separation = np.sum((A.center - B.center) ** 2) + for a, c in zip(A.exponents, A.coefficients): + for b, d in zip(B.exponents, B.coefficients): + p = a + b + K = c * d * math.exp(-a * b / p * separation) + yield m, n, p, K, (a * A.center + b * B.center) / p + + +def boys_0(t): + """Boys function F_0(t) = sqrt(pi / t) erf(sqrt(t)) / 2.""" + + t = np.asarray(t, dtype=float) + root = np.sqrt(np.maximum(t, 1e-8)) + erf = np.vectorize(math.erf, otypes=[float])(root) + + return np.where(t < 1e-8, 1 - t / 3, 0.5 * math.sqrt(math.pi) / root * erf) + + +def boys_1(t): + """Boys function F_1(t) = (F_0(t) - exp(-t)) / (2 t), by its series near 0.""" + + t = np.asarray(t, dtype=float) + series = 1 / 3 - t / 5 + t**2 / 14 - t**3 / 54 + t**4 / 264 + + return np.where( + t < 1e-3, series, (boys_0(t) - np.exp(-t)) / (2 * np.maximum(t, 1e-8)) + ) diff --git a/tests/test_ao_basis.py b/tests/test_ao_basis.py new file mode 100644 index 0000000..8b00b14 --- /dev/null +++ b/tests/test_ao_basis.py @@ -0,0 +1,337 @@ +"""The AO basis contract, `prop_sapt.backends.AOBasis`, and Psi4's, against Psi4 itself.""" + +import sys +import threading + +import numpy as np +import psi4 +import pytest + +from prop_sapt.backends import AOBasis +from prop_sapt.backends.ao_basis import as_ao_basis, atoms_and_basis, atoms_of +from prop_sapt.backends.psi4_basis import Psi4Basis, molecule_arrays + +HE_POSITION = np.array([-2.5, 0.0, 0.0]) # bohr, as in `prepare_dimer` + + +@pytest.fixture(scope="module") +def basis(prepare_dimer): + """The dimer's basis, as its backend gives it.""" + + return prepare_dimer.backend.basis + + +@pytest.fixture(scope="module") +def points(): + """Random points around the He-H2 dimer, in bohr.""" + + rng = np.random.default_rng(11) + return rng.uniform([-6.0, -3.0, -3.0], [6.0, 3.0, 3.0], size=(40, 3)) + + +@pytest.fixture(scope="module") +def phi_ref(basis, points): + """Basis function values from Psi4's per-point `compute_phi`.""" + + return np.array( + [np.asarray(basis.basisset.compute_phi(*p)).reshape(-1) for p in points] + ) + + +def test_basis_of_the_psi4_backend(prepare_dimer, basis): + """The backend's basis is the dimer basis set, on the dimer's atoms and in the AO + order of the backend's arrays.""" + + backend = prepare_dimer.backend + + assert isinstance(basis, Psi4Basis) + assert backend.basis is basis + assert basis.nbf == backend.nbf + np.testing.assert_array_equal(basis.coordinates, backend.fragments.coordinates) + np.testing.assert_array_equal(basis.charges, [2.0, 1.0, 1.0]) + np.testing.assert_allclose(basis.overlap(), backend.S, rtol=0, atol=1e-14) + + +def test_values_match_compute_phi(basis, points, phi_ref): + """The values of any number of points at once, whatever the calls before: fewer + points, more points, none.""" + + fresh = Psi4Basis(basis.basisset) + for stop in (7, 40, 1, 40, 0, 13): + values = fresh.values(points[:stop]) + assert values.shape == (stop, basis.nbf) + np.testing.assert_allclose(values, phi_ref[:stop], rtol=0, atol=1e-14) + + +def test_values_are_kept_by_the_caller(basis, points, phi_ref): + """A later call does not overwrite the values of an earlier one.""" + + values = basis.values(points[:5]) + basis.values(points[20:40]) + + np.testing.assert_allclose(values, phi_ref[:5], rtol=0, atol=1e-14) + + +@pytest.mark.parametrize("block_size", [1, 7, 40, 100]) +def test_value_blocks(basis, points, phi_ref, block_size): + """Blocks of at most `block_size` points, in order, the last one shorter, as the + contract's default makes them of `values`.""" + + blocks = list(basis.value_blocks(points, block_size)) + default = list(AOBasis.value_blocks(basis, points, block_size)) + + assert [chunk for chunk, _ in blocks] == [chunk for chunk, _ in default] + assert all(0 < chunk.stop - chunk.start <= block_size for chunk, _ in blocks) + np.testing.assert_allclose( + np.concatenate([values for _, values in blocks]), phi_ref, rtol=0, atol=1e-14 + ) + assert list(basis.value_blocks(points[:0], block_size)) == [] + + +@pytest.fixture +def frequent_thread_switches(): + """Python changes threads as often as it can.""" + + interval = sys.getswitchinterval() + sys.setswitchinterval(1e-6) + yield + sys.setswitchinterval(interval) + + +def test_values_in_two_threads(basis, points, phi_ref, frequent_thread_switches): + """Two threads that share a basis, as the calls on one dimer do, each get the values + at their own points.""" + + blocks = [slice(0, 20), slice(20, 40)] + start = threading.Barrier(len(blocks)) + wrong = [0, 0] + failures = [] + + def evaluate(thread): + try: + start.wait() + for _ in range(1000): + values = basis.values(points[blocks[thread]]) + error = np.max(np.abs(values - phi_ref[blocks[thread]])) + wrong[thread] += error > 1e-12 + except Exception as error: + failures.append(error) + + threads = [threading.Thread(target=evaluate, args=(thread,)) for thread in (0, 1)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert failures == [] + assert wrong == [0, 0] + + +def test_values_of_any_memory_layout(basis, points, phi_ref): + """Points as a strided view and in Fortran order.""" + + np.testing.assert_allclose( + basis.values(points[::2]), phi_ref[::2], rtol=0, atol=1e-14 + ) + np.testing.assert_allclose( + basis.values(np.asfortranarray(points)), phi_ref, rtol=0, atol=1e-14 + ) + + +def test_potential_matches_potential_integrals(basis, points): + """Tr(D V) with the integrals V = -<1/|r - R|> of an electron and a unit charge at + the point, of Psi4's `ExternalPotential`.""" + + rng = np.random.default_rng(3) + dms = rng.standard_normal((2, basis.nbf, basis.nbf)) + dms = dms + dms.transpose(0, 2, 1) + + potential = basis.potential(dms, points[:6]) + + assert potential.shape == (2, 6) + for i, point in enumerate(points[:6]): + external = psi4.core.ExternalPotential() + external.addCharge(1.0, *point) + integrals = np.asarray(external.computePotentialMatrix(basis.basisset)) + np.testing.assert_allclose( + potential[:, i], np.einsum("Mij,ij->M", dms, integrals), rtol=1e-9 + ) + + +def test_potential_of_non_symmetric_matrices(basis, points): + """Tr(D V) takes all elements of D, not one triangle: the potential of a matrix that + is not symmetric is that of its symmetric part, V being symmetric.""" + + rng = np.random.default_rng(17) + dm = rng.standard_normal((basis.nbf, basis.nbf)) + parts = [dm, dm.T, 0.5 * (dm + dm.T)] + triangles = [np.tril(dm) + np.tril(dm, -1).T, np.triu(dm) + np.triu(dm, 1).T] + + potential = basis.potential(np.stack(parts + triangles), points[:6]) + + np.testing.assert_allclose(potential[1], potential[0], rtol=0, atol=1e-11) + np.testing.assert_allclose(potential[2], potential[0], rtol=0, atol=1e-11) + for triangle in potential[3:]: + assert np.max(np.abs(triangle - potential[0])) > 0.1 + + +def test_potential_of_no_points(basis): + potential = basis.potential(np.zeros((3, basis.nbf, basis.nbf)), np.zeros((0, 3))) + + assert potential.shape == (3, 0) + + +def test_field_is_the_gradient_of_the_potential(basis): + """Tr(D <(r - R)/|r - R|^3>) is minus the gradient of the electrons' potential with + respect to R, by central differences.""" + + rng = np.random.default_rng(5) + dm = rng.standard_normal((basis.nbf, basis.nbf)) + dm = dm + dm.T + origin = np.array([0.3, -0.4, 0.8]) + step = 1e-3 + + displaced = np.array( + [origin + sign * step * axis for axis in np.eye(3) for sign in (1, -1)] + ) + plus_minus = basis.potential(dm[None], displaced)[0].reshape(3, 2) + gradient = (plus_minus[:, 0] - plus_minus[:, 1]) / (2 * step) + + field = [np.sum(dm * component) for component in basis.field_integrals(origin)] + + np.testing.assert_allclose(field, -gradient, rtol=1e-4) + + +def test_ghost_atoms_have_no_charge(prepare_dimer): + """Monomer A's basis set is on all atoms of the dimer, the H atoms as ghosts.""" + + basis = Psi4Basis(prepare_dimer.wfnA.basisset()) + + assert basis.nbf == prepare_dimer.nbf + assert basis.coordinates.shape == (3, 3) + np.testing.assert_array_equal(basis.coordinates[0], HE_POSITION) + np.testing.assert_array_equal(basis.charges, [2.0, 0.0, 0.0]) + + +@pytest.mark.parametrize("attribute", ["coordinates", "charges"]) +def test_atoms_are_read_only_copies(basis, attribute): + with pytest.raises(ValueError, match="read-only"): + getattr(basis, attribute)[0] = 0.0 + + +def test_psi4_basis_of_something_else(prepare_dimer): + with pytest.raises(TypeError, match="psi4.core.BasisSet"): + Psi4Basis(prepare_dimer.get_psi4_molecule()) + + +def test_as_ao_basis(basis): + wrapped = as_ao_basis(basis.basisset) + + assert as_ao_basis(basis) is basis + assert isinstance(wrapped, Psi4Basis) + assert wrapped.basisset is basis.basisset + for other in (None, "aug-cc-pvtz", basis.basisset.molecule()): + with pytest.raises(TypeError, match="`basisset` should be of type"): + as_ao_basis(other) + + +def test_atoms_and_basis(prepare_dimer, basis, he_h2_settings): + """`mol` sets the atoms and `basisset` the basis functions. An AO basis is both.""" + + mol = prepare_dimer.get_psi4_molecule() + ghosts = prepare_dimer.wfnA.basisset() + + coordinates, charges, of_basis = atoms_and_basis(basis, None) + assert of_basis is basis + assert coordinates is basis.coordinates and charges is basis.charges + + # the atoms of the molecule, all real, with another basis set's functions + coordinates, charges, of_ghosts = atoms_and_basis(mol, ghosts) + assert of_ghosts.basisset is ghosts + np.testing.assert_array_equal(coordinates, basis.coordinates) + np.testing.assert_array_equal(charges, [2.0, 1.0, 1.0]) + + # the atoms of an AO basis, with another basis set's functions + coordinates, charges, of_ghosts = atoms_and_basis(basis, ghosts) + assert of_ghosts.basisset is ghosts + np.testing.assert_array_equal(charges, [2.0, 1.0, 1.0]) + + # without a basis set, the one of the `BASIS` option + _, _, from_option = atoms_and_basis(mol, None) + assert from_option.nbf == basis.nbf + + +def test_atoms_of_updates_the_geometry(prepare_dimer, monkeypatch): + """As `Molecule.to_arrays`, the geometry of a molecule is updated first, so that + changes the user made to it count.""" + + mol = prepare_dimer.get_psi4_molecule() + update = psi4.core.Molecule.update_geometry + updated = [] + + def recorded(molecule): + updated.append(molecule) + update(molecule) + + monkeypatch.setattr(psi4.core.Molecule, "update_geometry", recorded) + + coordinates, charges = atoms_of(mol) + assert updated == [mol] + + expected, _, _, elements, _ = mol.to_arrays() + np.testing.assert_array_equal(coordinates, expected) + np.testing.assert_array_equal(charges, elements) + + +@pytest.mark.parametrize( + "atoms, basis_name, charges", + [ + ("Xe 0.0 0.0 0.0\nHe 6.0 0.0 0.0", "def2-svp", [54 - 28, 2]), + ("He 0.0 0.0 0.0\n@Ne 6.0 0.0 0.0\n@He 3.0 0.0 0.0", "cc-pvdz", [2, 0, 0]), + ], + ids=["ecp", "ghosts"], +) +def test_charges_of_ecp_and_ghost_atoms(atoms, basis_name, charges): + """The charges are those of `Molecule.to_arrays`, which the analysis functions took + before: an ECP reduces the charge of its atom once the basis set has been built, and + ghost atoms have none.""" + + molecule = psi4.core.Molecule.from_string( + f"symmetry c1\nno_com\nno_reorient\nunits bohr\n0 1\n{atoms}" + ) + molecule.update_geometry() + basisset = psi4.core.BasisSet.build(molecule, "ORBITAL", basis_name) + + expected, _, _, elements, _ = molecule.to_arrays() + np.testing.assert_array_equal(elements, charges) + for arrays in (molecule_arrays(molecule), atoms_of(Psi4Basis(basisset))): + np.testing.assert_array_equal(arrays[0], expected) + np.testing.assert_array_equal(arrays[1], elements) + + +def test_atoms_and_basis_of_something_else(prepare_dimer, basis): + mol = prepare_dimer.get_psi4_molecule() + + with pytest.raises(TypeError, match="`mol` should be of type"): + atoms_and_basis(prepare_dimer, None) + for atoms in (mol, basis): + with pytest.raises(TypeError, match="`basisset` should be of type"): + atoms_and_basis(atoms, "aug-cc-pvtz") + + +def test_no_molecular_grid_by_default(basis): + """The grid is the one optional part of the contract.""" + + class NoGrid(Psi4Basis): + molecular_grid = AOBasis.molecular_grid + + with pytest.raises(NotImplementedError, match="NoGrid has no molecular quadrature"): + NoGrid(basis.basisset).molecular_grid(20, 110, "TREUTLER", 1.0) + + +def test_basis_needs_the_operations(): + class NoOperations(AOBasis): + pass + + with pytest.raises(TypeError, match="abstract"): + NoOperations() diff --git a/tests/test_backends.py b/tests/test_backends.py index 722f91c..38bbc68 100644 --- a/tests/test_backends.py +++ b/tests/test_backends.py @@ -157,3 +157,12 @@ def test_no_cpscf_jk_types_by_default(): with pytest.raises(NotImplementedError, match="ArrayBackend has no CPSCF"): backend.build_cpscf_jk("DF") + + +def test_no_basis_by_default(): + """A backend without a basis still does energies, properties and densities.""" + + backend = ArrayBackend(**backend_data()) + + with pytest.raises(NotImplementedError, match="ArrayBackend has no `basis`"): + backend.basis diff --git a/tests/test_cubes.py b/tests/test_cubes.py index 16ea216..905bd4f 100644 --- a/tests/test_cubes.py +++ b/tests/test_cubes.py @@ -1,3 +1,5 @@ +from contextlib import contextmanager + import pytest import numpy as np @@ -7,6 +9,7 @@ Cube, add_cubes, cosine_similarity, + make_cube, read_cube_file, subtract_cubes, ) @@ -224,6 +227,78 @@ def test_dimer_cube_in_the_dimers_basis_set(prepare_dimer, density_A): np.testing.assert_array_equal(cube.volumetric_data, expected.volumetric_data) +def test_cube_of_an_ao_basis(prepare_dimer, density_A): + """An AO basis is the atoms and the basis set, as the Psi4 molecule and basis set + of the dimer are.""" + + basis = prepare_dimer.backend.basis + settings = {"obj_type": ["density", "esp"], "grid_step": 1.0, "esp_nuclei": True} + + expected = make_cube( + prepare_dimer.get_psi4_molecule(), + [density_A, density_A], + basisset=prepare_dimer.get_psi4_basisset(), + **settings, + ) + for basisset in (None, basis, basis.basisset): + cubes = make_cube(basis, [density_A] * 2, basisset=basisset, **settings) + for cube, reference in zip(cubes, expected): + np.testing.assert_array_equal( + cube.volumetric_data, reference.volumetric_data + ) + np.testing.assert_array_equal(cube.origin, reference.origin) + assert [a[0] for a in cube.atoms] == [a[0] for a in reference.atoms] + for atom, other in zip(cube.atoms, reference.atoms): + np.testing.assert_array_equal(atom[2], other[2]) + + +def test_cube_atoms_are_the_cubes_own(prepare_dimer, density_A): + """Moving the atoms of a cube moves neither the basis nor another cube's atoms.""" + + basis = prepare_dimer.backend.basis + coordinates = basis.coordinates.copy() + moved, other = make_cube(basis, [density_A] * 2, "density", grid=ESP_GRID) + + for _, _, xyz in moved.atoms: + xyz += 1.0 + + np.testing.assert_array_equal(basis.coordinates, coordinates) + np.testing.assert_array_equal([xyz for _, _, xyz in other.atoms], coordinates) + + +@pytest.mark.parametrize("basisset", ["aug-cc-pvtz", 23], ids=["name", "number"]) +def test_cube_rejects_another_basisset(prepare_dimer, density_A, basisset): + """A `basisset` of another type raises: it is not replaced by the basis set of the + `BASIS` option, whose functions the matrices are not in.""" + + with pytest.raises(TypeError, match="`basisset` should be of type"): + make_cube(prepare_dimer.get_psi4_molecule(), density_A, basisset=basisset) + with pytest.raises(TypeError, match="`basisset` should be of type"): + prepare_dimer.make_cube(density_A, basisset=basisset) + + +def test_cube_rejects_another_molecule(prepare_dimer, density_A): + with pytest.raises(TypeError, match="`mol` should be of type"): + make_cube(prepare_dimer.geometry, density_A) + + +def test_dimer_cube_in_the_backends_timer(prepare_dimer, density_A, monkeypatch): + """`Dimer.make_cube` runs in the timer of the dimer's backend.""" + + events = [] + + @contextmanager + def timer(): + events.append("start") + yield + events.append("stop") + + monkeypatch.setattr(prepare_dimer.backend, "timer", timer) + prepare_dimer.make_cube(density_A, grid=ESP_GRID) + + assert events == ["start", "stop"] + + # --- Cube objects without a dimer: construction, arithmetic, integrals, file I/O --- # skewed cell, voxel volume = det([x, y, z]) = 0.2 * 0.3 * 0.25 diff --git a/tests/test_dimer.py b/tests/test_dimer.py index 4a3a3d6..75de763 100644 --- a/tests/test_dimer.py +++ b/tests/test_dimer.py @@ -1,10 +1,14 @@ +import logging +import warnings + import numpy as np import psi4 import pytest +from psi4.driver.p4util import OptionsState from .he_h2 import HE_H2 from prop_sapt import Dimer, get_propsapt_options -from prop_sapt.backends.psi4_backend import jk_memory_doubles +from prop_sapt.backends.psi4_backend import jk_memory_doubles, warn_of_ecps HE_H = """ symmetry c1 @@ -63,6 +67,49 @@ def test_frozen_core_off_accepted(reset_freeze_core, freeze_core): Dimer(HE_H.format(atom_A="H", mult_A=2, atom_B="He", mult_B=1)) +def test_ecps_warn(caplog): + """A basis set with effective core potentials warns where the dimer is made, and in + the log, once, also when the ECP is on monomer B.""" + + psi4.core.set_output_file("output.dat", True) + saved = OptionsState(["BASIS"], ["DF_BASIS_SAPT"], ["SCF_TYPE"]) + try: + psi4.set_options( + { + "basis": "def2-svp", + "df_basis_sapt": "def2-svp-ri", + "scf_type": "df", + } + ) + with ( + pytest.warns(UserWarning, match=r"\(ECPs\), on Xe\.") as caught, + caplog.at_level(logging.WARNING, logger="prop_sapt"), + ): + Dimer(HE_H.format(atom_A="He", mult_A=1, atom_B="Xe", mult_B=1)) + finally: + saved.restore() + + ecp_warnings = [w for w in caught if "ECPs" in str(w.message)] + assert [w.filename for w in ecp_warnings] == [__file__] + assert [r.levelname for r in caplog.records if "ECPs" in r.message] == ["WARNING"] + + +def test_no_ecp_warning_without_ecps(): + """def2 basis sets have ECPs from Rb on: lighter atoms, and ghosts of heavy ones, + have none.""" + + psi4.core.set_output_file("output.dat", True) + molecule = psi4.core.Molecule.from_string( + HE_H.format(atom_A="Kr", mult_A=1, atom_B="@Xe", mult_B=1) + ) + molecule.update_geometry() + basisset = psi4.core.BasisSet.build(molecule, "ORBITAL", "def2-svp") + + with warnings.catch_warnings(): + warnings.simplefilter("error") + warn_of_ecps(basisset) + + def test_jk_memory_follows_psi4_memory(monkeypatch): """Without `memory`, the JK object gets Psi4's memory times SCF_MEM_SAFETY_FACTOR, in doubles (8 bytes each), as Psi4's SCF gives its own JK object.""" @@ -308,5 +355,16 @@ def test_basisset_is_the_dimers(prepare_dimer): assert prepare_dimer.get_psi4_basisset().nbf() == prepare_dimer.nbf wavefunction = prepare_dimer.get_psi4_wavefunction() assert wavefunction.basisset().nbf() == prepare_dimer.nbf + assert prepare_dimer.basis.nbf == prepare_dimer.nbf finally: saved_options.restore() + + +def test_basis_is_the_backends(prepare_dimer): + """The basis the analysis methods use is the backend's, in the AO order of the + dimer's matrices.""" + + assert prepare_dimer.basis is prepare_dimer.backend.basis + np.testing.assert_allclose( + prepare_dimer.basis.overlap(), prepare_dimer.S, rtol=0, atol=1e-14 + ) diff --git a/tests/test_evaluate.py b/tests/test_evaluate.py index 57aaa31..da325c6 100644 --- a/tests/test_evaluate.py +++ b/tests/test_evaluate.py @@ -273,6 +273,38 @@ def test_rejects_orbitals_as_rows(basisset, coeffs_A, points): evaluate_orbital(coeffs_A[:, :3].T, points, basisset) -def test_requires_psi4_basisset(prepare_dimer, density_A, points): - with pytest.raises(TypeError): +def test_requires_a_basis(prepare_dimer, density_A, points): + """An AO basis or a Psi4 basis set, and not e.g. a molecule.""" + + with pytest.raises(TypeError, match="`basisset` should be of type"): evaluate_density(density_A, points, prepare_dimer.get_psi4_molecule()) + + +def test_ao_basis_matches_psi4_basisset(prepare_dimer, basisset, density_A, points): + """The AO basis of the dimer's backend is taken as its Psi4 basis set is.""" + + basis = prepare_dimer.backend.basis + + np.testing.assert_array_equal( + evaluate_basis_functions(points, basis, chunk_size=7), + evaluate_basis_functions(points, basisset, chunk_size=7), + ) + np.testing.assert_array_equal( + evaluate_density(density_A, points, basis), + evaluate_density(density_A, points, basisset), + ) + np.testing.assert_array_equal( + evaluate_esp(density_A, points, basis, nuclei=True), + evaluate_esp(density_A, points, basisset, nuclei=True), + ) + + +def test_psi4_matrix(basisset, density_A, points): + """A Psi4 `Matrix` is one density matrix, not a sequence of its rows.""" + + matrix = psi4.core.Matrix.from_array(density_A) + + np.testing.assert_array_equal( + evaluate_density(matrix, points, basisset), + evaluate_density(density_A, points, basisset), + ) diff --git a/tests/test_forces.py b/tests/test_forces.py index 1c2c00e..014964a 100644 --- a/tests/test_forces.py +++ b/tests/test_forces.py @@ -2,6 +2,7 @@ import pytest import psi4 +from prop_sapt.backends.psi4_basis import Psi4Basis from prop_sapt.forces import calc_force_nuc_nuc, calc_force_at_nuc @@ -110,3 +111,30 @@ def test_nuc_nuc_h2o_newton(water): """Test 4: sum of nuc-nuc forces over all atoms is zero for H2O.""" forces = np.array([calc_force_nuc_nuc(water, i) for i in range(water.natom())]) assert np.allclose(forces.sum(axis=0), 0.0, atol=1e-12) + + +def test_force_of_an_ao_basis(h2, h2_wfn): + """An AO basis is the atoms and the basis set, as the Psi4 molecule and basis set.""" + rho = h2_wfn.Da().to_array() + basis = Psi4Basis(h2_wfn.basisset()) + + np.testing.assert_array_equal( + calc_force_at_nuc(basis, rho, atidx=0), + calc_force_at_nuc(h2, rho, atidx=0, basisset=h2_wfn.basisset()), + ) + np.testing.assert_array_equal( + calc_force_nuc_nuc(basis, atidx=1), calc_force_nuc_nuc(h2, atidx=1) + ) + + +def test_force_rejects_other_types(h2, h2_wfn): + """A `basisset` of another type raises: it is not replaced by the basis set of the + `BASIS` option, whose functions the density matrix is not in.""" + rho = h2_wfn.Da().to_array() + + with pytest.raises(TypeError, match="`basisset` should be of type"): + calc_force_at_nuc(h2, rho, atidx=0, basisset="aug-cc-pv5z") + with pytest.raises(TypeError, match="`mol` should be of type"): + calc_force_at_nuc("H2", rho, atidx=0) + with pytest.raises(TypeError, match="`mol` should be of type"): + calc_force_nuc_nuc("H2", atidx=0) diff --git a/tests/test_imports.py b/tests/test_imports.py index 8cd66cc..259b067 100644 --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -1,31 +1,32 @@ -"""Static checks of how the package imports itself.""" +"""Checks of how the package imports itself, and Psi4.""" import ast import re +import subprocess +import sys from pathlib import Path +import pytest + import prop_sapt 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. +#: backend contract (bundles, runner, configuration and finite field). The SAPT core and +#: the analysis modules are not among them. PSI4_MODULES = { "artifacts.py", + "backends/ao_basis.py", # for type annotations only "backends/psi4_backend.py", + "backends/psi4_basis.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", } @@ -82,13 +83,13 @@ def _imports_psi4(path: Path) -> bool: 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: + drivers, CPSCF) and the analysis modules do not import Psi4: their 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`).""" + for some of its output: the monomer wavefunctions of the deprecated + ``matrix_format="npy"`` (`wfnA.to_file`).""" root = Path(prop_sapt.__file__).parent importing = { @@ -99,3 +100,72 @@ def test_only_psi4_facing_modules_import_psi4(): assert sorted(importing - PSI4_MODULES) == [] assert sorted(PSI4_MODULES - importing) == [] + + +#: Imports a module of the package where Psi4 cannot be imported, in a Python of its own. +#: The package's `__init__`, which loads Psi4 through `Dimer`, is left out. +IMPORT_WITHOUT_PSI4 = """ +import importlib, sys, types + +directory, module = sys.argv[1:3] +package = types.ModuleType("prop_sapt") +package.__path__ = [directory] +sys.modules["prop_sapt"] = package +sys.modules["psi4"] = None +importlib.import_module(f"prop_sapt.{module}") +""" + +#: Without Psi4, arguments that are no AO basis are of the wrong type. +WRONG_ARGUMENTS_WITHOUT_PSI4 = """ +from prop_sapt.backends.ao_basis import as_ao_basis, atoms_and_basis + +for call in (lambda: as_ao_basis("aug-cc-pvtz"), lambda: atoms_and_basis(None, None)): + try: + call() + except TypeError: + continue + raise AssertionError("no TypeError") +""" + + +def _run_without_psi4(module: str, code: str = "") -> subprocess.CompletedProcess: + """Imports `module` of the package, and runs `code`, without Psi4.""" + + directory = Path(prop_sapt.__file__).parent + return subprocess.run( + [sys.executable, "-c", IMPORT_WITHOUT_PSI4 + code, str(directory), module], + capture_output=True, + text=True, + ) + + +@pytest.mark.parametrize( + "module", + [ + "backends", + "cpscf_solver", + "helper_SAPT_DF", + "options", + "checks", + "cubes", + "evaluate", + "forces", + "partition", + ], +) +def test_import_without_psi4(module): + """The SAPT core and the analysis modules load without Psi4: neither they nor the + modules they import need it, so another backend could replace it.""" + + result = _run_without_psi4(module) + + assert result.returncode == 0, result.stderr + + +def test_wrong_arguments_without_psi4(): + """The analysis functions take only AO bases where Psi4 is not installed, and say + so for anything else.""" + + result = _run_without_psi4("backends.ao_basis", WRONG_ARGUMENTS_WITHOUT_PSI4) + + assert result.returncode == 0, result.stderr diff --git a/tests/test_partition.py b/tests/test_partition.py index 2b0624e..8f44ac3 100644 --- a/tests/test_partition.py +++ b/tests/test_partition.py @@ -6,7 +6,7 @@ import psi4 from psi4.driver import p4util -from prop_sapt import reset_propsapt_options, set_propsapt_options +from prop_sapt import Dimer, reset_propsapt_options, set_propsapt_options from prop_sapt.checks import InvariantWarning from prop_sapt.evaluate import evaluate_density from prop_sapt.partition import ( @@ -17,6 +17,8 @@ molecular_grid, ) +from .he_h2 import HE_H2 + FRAGMENT_ATOMS = {"A": [0], "B": [1, 2]} # He | H2, as in `prepare_dimer` QUADRATURE_ATOL = 1e-6 # quadrature error of the default grid, 5e-7 measured @@ -133,6 +135,26 @@ def test_molecular_grid(grid, basisset): assert np.all(grid.weights > 0.0) +def test_ao_basis_matches_psi4_basisset(prepare_dimer, basisset): + """The AO basis of the dimer's backend is taken as its Psi4 basis set is, for the + grid and the operators.""" + + basis = prepare_dimer.backend.basis + sizes = {"radial_points": 20, "spherical_points": 110} + + grids = [molecular_grid(b, **sizes) for b in (basis, basisset)] + for name in ("points", "weights", "atom_index"): + np.testing.assert_array_equal(*[getattr(grid, name) for grid in grids]) + + weights = becke_fragment_weights(grids[0], FRAGMENT_ATOMS) + operators = [ + FragmentOperators.from_grid(grids[0].points, grids[0].weights, weights, b) + for b in (basis, basisset) + ] + np.testing.assert_array_equal(*[ops.overlap("A") for ops in operators]) + np.testing.assert_array_equal(*[ops.ao_overlap for ops in operators]) + + def test_molecular_grid_keeps_psi4_options(basisset): """The radial extent is set only while the grid is built.""" @@ -480,6 +502,77 @@ def test_dimer_fragment_operators( ) +@pytest.fixture +def damped_dimer(): + """He-H2 from damped SCFs, whose density matrices (`Da`) mix those of the last two + iterations: they are not those of the orbitals. The options it changes are restored + afterwards.""" + + psi4.core.set_output_file("output.dat", True) + saved = p4util.OptionsState( + ["BASIS"], + ["DF_BASIS_SAPT"], + ["SCF_TYPE"], + ["E_CONVERGENCE"], + ["D_CONVERGENCE"], + ["DAMPING_PERCENTAGE"], + ) + try: + psi4.set_options( + { + "basis": "aug-cc-pvdz", + "df_basis_sapt": "aug-cc-pvdz-ri", + "scf_type": "df", + "e_convergence": 1e-8, + "d_convergence": 1e-8, + "damping_percentage": 20, + } + ) + return Dimer(HE_H2) + finally: + saved.restore() + + +def test_hirshfeld_operators_of_a_damped_scf(damped_dimer): + """`Dimer.fragment_operators` takes the monomer densities of the occupied orbitals, + which the SAPT terms are made of. With a damped SCF they differ from Psi4's `Da`, by + about what the SCF convergence leaves; so do the operators.""" + + mol = damped_dimer + grid = molecular_grid(mol.basis) + of_orbitals = { + "A": 2 * mol.Co_A @ mol.Co_A.T, + "B": 2 * mol.Co_B @ mol.Co_B.T, + } + of_psi4 = {"A": 2 * np.asarray(mol.wfnA.Da()), "B": 2 * np.asarray(mol.wfnB.Da())} + + for fragment in ("A", "B"): + damping = np.max(np.abs(of_orbitals[fragment] - of_psi4[fragment])) + assert 1e-11 < damping < 1e-5 + + ops, ops_of_orbitals, ops_of_psi4 = ( + mol.fragment_operators(weights, grid=grid) + for weights in ( + "hirshfeld", + hirshfeld_fragment_weights(grid.points, of_orbitals, mol.basis), + hirshfeld_fragment_weights(grid.points, of_psi4, mol.basis), + ) + ) + for fragment in ("A", "B"): + np.testing.assert_array_equal( + ops.overlap(fragment), ops_of_orbitals.overlap(fragment) + ) + np.testing.assert_allclose( + ops.overlap(fragment), ops_of_psi4.overlap(fragment), rtol=0, atol=1e-6 + ) + np.testing.assert_allclose( + ops.population(fragment, of_orbitals[fragment]), + ops_of_psi4.population(fragment, of_orbitals[fragment]), + rtol=0, + atol=1e-7, + ) + + def test_dimer_fragment_operators_with_arrays(prepare_dimer, grid, becke_weights): """Weights given as arrays need their grid; grid options need no grid.""" diff --git a/tests/test_s_gaussian_basis.py b/tests/test_s_gaussian_basis.py new file mode 100644 index 0000000..f79997d --- /dev/null +++ b/tests/test_s_gaussian_basis.py @@ -0,0 +1,281 @@ +"""The analysis functions on a basis that is not Psi4's, the s-Gaussian test double of +`tests/s_gaussian_basis.py`, and those of a dimer on the replay backend with it: against +Psi4's numbers, with no call into Psi4.""" + +import numpy as np +import psi4 +import pytest +from psi4.driver.p4util import OptionsState + +from prop_sapt import ( + Dimer, + calc_densities, + checks, + cubes, + forces, + partition, +) +from prop_sapt.backends.psi4_basis import Psi4Basis + +from .he_h2 import HE_H2, OPTIONS +from .replay_backend import ReplayBackend, no_psi4_calls +from .s_gaussian_basis import SGaussianBasis + +# NumPy's s-Gaussian formulas against Psi4's integrals on He-H2: 2e-15 +ATOL = 1e-12 +# the density matrices of the two dimers, in the cubes `calc_densities` saves +DENSITY_CUBES_ATOL = 1e-9 + + +@pytest.fixture(scope="module") +def psi4_dimer(): + """He-H2 in STO-3G, s functions alone, with Psi4's J/K fitted in the `DF_BASIS_SAPT` + basis as the replay backend's are. The options it changes are restored afterwards. + """ + + psi4.core.set_output_file("output.dat", True) + saved = OptionsState(["BASIS"], ["SCF_TYPE"], ["DF_BASIS_SCF"], ["DF_BASIS_SAPT"]) + try: + psi4.set_options(OPTIONS) + psi4.set_options( + { + "basis": "sto-3g", + "scf_type": "df", + "df_basis_scf": OPTIONS["DF_BASIS_SAPT"], + } + ) + return Dimer(HE_H2) + finally: + saved.restore() + + +@pytest.fixture(scope="module") +def s_basis(psi4_dimer): + return SGaussianBasis.record(psi4_dimer.get_psi4_basisset()) + + +@pytest.fixture(scope="module") +def s_dimer(psi4_dimer, s_basis): + """The replay of `psi4_dimer`'s calculation, on the s-Gaussian basis.""" + + return Dimer.from_backend(ReplayBackend.record(psi4_dimer.backend, basis=s_basis)) + + +@pytest.fixture(scope="module") +def densities(psi4_dimer): + """Monomer density matrices.""" + + return { + "A": 2 * psi4_dimer.Co_A @ psi4_dimer.Co_A.T, + "B": 2 * psi4_dimer.Co_B @ psi4_dimer.Co_B.T, + } + + +@pytest.fixture(scope="module") +def points(): + """Random points around the dimer, and its He nucleus, in bohr.""" + + rng = np.random.default_rng(13) + points = rng.uniform([-6.0, -3.0, -3.0], [6.0, 3.0, 3.0], size=(30, 3)) + points[4] = [-2.5, 0.0, 0.0] + + return points + + +@pytest.fixture(scope="module") +def grid(psi4_dimer): + """Psi4's quadrature grid, for the s-Gaussian basis, which has none.""" + + return partition.molecular_grid(psi4_dimer.basis) + + +def assert_close(actual, expected, atol=ATOL): + np.testing.assert_allclose(actual, expected, rtol=0, atol=atol) + + +def test_s_gaussian_basis_matches_psi4(psi4_dimer, s_basis, densities, points): + """Every operation of the contract, so its conventions hold in two codes.""" + + psi4_basis = psi4_dimer.basis + dms = np.stack(list(densities.values())) + + assert isinstance(psi4_basis, Psi4Basis) + assert not isinstance(s_basis, Psi4Basis) + assert s_basis.nbf == psi4_basis.nbf == 3 + assert_close(s_basis.coordinates, psi4_basis.coordinates) + assert_close(s_basis.charges, psi4_basis.charges) + assert_close(s_basis.overlap(), psi4_dimer.S) + assert_close(s_basis.values(points), psi4_basis.values(points)) + assert_close(s_basis.potential(dms, points), psi4_basis.potential(dms, points)) + for point in points: + assert_close(s_basis.field_integrals(point), psi4_basis.field_integrals(point)) + + +def test_potential_of_non_symmetric_matrices(psi4_dimer, s_basis, points): + """Both codes take all elements of a matrix that is not symmetric.""" + + rng = np.random.default_rng(19) + dms = rng.standard_normal((2, s_basis.nbf, s_basis.nbf)) + assert np.max(np.abs(dms - dms.transpose(0, 2, 1))) > 0.1 + + assert_close( + s_basis.potential(dms, points), psi4_dimer.basis.potential(dms, points) + ) + + +def test_s_gaussian_basis_of_p_functions(prepare_dimer): + with pytest.raises(ValueError, match="s functions only"): + SGaussianBasis.record(prepare_dimer.get_psi4_basisset()) + + +def test_point_values(psi4_dimer, s_dimer, densities, points): + dms = list(densities.values()) + coeffs = psi4_dimer.C_A + + with no_psi4_calls(): + rho = s_dimer.evaluate_density(dms, points, chunk_size=7) + psi = s_dimer.evaluate_orbital(coeffs, points) + esp = s_dimer.evaluate_esp(dms, points, nuclei=True) + + assert_close(rho, psi4_dimer.evaluate_density(dms, points)) + assert_close(psi, psi4_dimer.evaluate_orbital(coeffs, points)) + assert_close(esp, psi4_dimer.evaluate_esp(dms, points, nuclei=True)) + + +def test_cubes(psi4_dimer, s_dimer, densities, tmp_path): + matrices = [densities["A"], psi4_dimer.C_B[:, 0], densities["B"]] + settings = {"obj_type": ["density", "orbital", "esp"], "grid_step": 0.8} + + with no_psi4_calls(): + on_s = s_dimer.make_cube(matrices, esp_nuclei=True, **settings) + standalone = cubes.make_cube(s_dimer.basis, matrices, **settings) + s_dimer.save_cube(densities["A"], filename=tmp_path / "rho.cube", grid_step=0.8) + + expected = psi4_dimer.make_cube(matrices, esp_nuclei=True, **settings) + for cube, reference in zip(on_s, expected, strict=True): + assert_close(cube.volumetric_data, reference.volumetric_data) + assert_close(cube.origin, reference.origin) + for atom, other in zip(cube.atoms, reference.atoms, strict=True): + assert atom[:2] == other[:2] + assert_close(atom[2], other[2]) + # the ESP cube above has the nuclei too, the others are the same + assert_close(standalone[0].volumetric_data, expected[0].volumetric_data) + assert (tmp_path / "rho.cube").exists() + + +@pytest.mark.parametrize("weights", ["becke", "hirshfeld"]) +def test_fragment_operators(psi4_dimer, s_dimer, densities, grid, weights): + with no_psi4_calls(): + ops = s_dimer.fragment_operators(weights, grid=grid) + population = ops.population("A", densities["A"]) + + expected = psi4_dimer.fragment_operators(weights, grid=grid) + for fragment in ("A", "B"): + assert_close(ops.overlap(fragment), expected.overlap(fragment)) + assert_close(ops.first_moment(fragment), expected.first_moment(fragment)) + assert_close(ops.ao_overlap, expected.ao_overlap) + assert_close(population, expected.population("A", densities["A"])) + + +def test_partition_check(s_basis, grid): + """The check of the fragment weights, which warns when they do not sum to 1.""" + + with no_psi4_calls(), pytest.warns(checks.InvariantWarning, match="do not sum"): + defect = checks.check_partition_of_unity( + grid.points, grid.weights, {"A": 0.5 * np.ones_like(grid.weights)}, s_basis + ) + + assert defect == pytest.approx(0.5, abs=1e-3) + + +def test_forces(psi4_dimer, s_basis, densities): + dms = list(densities.values()) + + for atom in range(3): + with no_psi4_calls(): + on_s = forces.calc_force_at_nuc(s_basis, dms, atom) + nuclear = forces.calc_force_nuc_nuc(s_basis, atom) + + assert_close(on_s, forces.calc_force_at_nuc(psi4_dimer.basis, dms, atom)) + assert_close(nuclear, forces.calc_force_nuc_nuc(psi4_dimer.basis, atom)) + + +def test_density_cubes_of_calc_densities(psi4_dimer, s_dimer, tmp_path): + """From a backend's arrays to the cube files of the density changes.""" + + with no_psi4_calls(): + calc_densities( + s_dimer, + save_cubes=True, + cubes_dir=str(tmp_path / "s"), + ) + calc_densities(psi4_dimer, save_cubes=True, cubes_dir=str(tmp_path / "psi4")) + + names = sorted(path.name for path in (tmp_path / "psi4").iterdir()) + assert names and names == sorted(path.name for path in (tmp_path / "s").iterdir()) + for name in names: + values, expected = ( + cubes.read_cube_file(tmp_path / code / name).volumetric_data + for code in ("s", "psi4") + ) + assert np.max(np.abs(expected)) > 100 * DENSITY_CUBES_ATOL + assert_close(values, expected, DENSITY_CUBES_ATOL) + + +def test_no_molecular_grid(s_dimer): + """The grid is optional: without one, the caller's grid is needed.""" + + with ( + no_psi4_calls(), + pytest.raises(NotImplementedError, match="SGaussianBasis has no molecular"), + ): + s_dimer.fragment_operators("becke") + + +@pytest.mark.parametrize( + "change, message", + [ + ("order", "not on the dimer's atoms"), + ("size", "has 2 functions, but its matrices 3"), + ], +) +def test_basis_of_other_atoms_or_functions(psi4_dimer, s_basis, grid, change, message): + """A dimer refuses a backend's basis on its atoms in another order, which would + swap the fragments' weights without an error, or with other functions.""" + + if change == "order": + basis = SGaussianBasis( + s_basis.shells, s_basis.coordinates[::-1], s_basis.charges[::-1] + ) + else: + basis = SGaussianBasis(s_basis.shells[:2], s_basis.coordinates, s_basis.charges) + dimer = Dimer.from_backend(ReplayBackend.record(psi4_dimer.backend, basis=basis)) + + for analyse in ( + lambda: dimer.basis, + lambda: dimer.fragment_operators("becke", grid=grid), + ): + with pytest.raises(ValueError, match=message): + analyse() + + +@pytest.mark.parametrize( + "analyse", + [ + lambda dimer: dimer.basis, + lambda dimer: dimer.make_cube(np.eye(dimer.nbf)), + lambda dimer: dimer.evaluate_density(np.eye(dimer.nbf), np.zeros((1, 3))), + lambda dimer: dimer.evaluate_orbital(np.ones(dimer.nbf), np.zeros((1, 3))), + lambda dimer: dimer.evaluate_esp(np.eye(dimer.nbf), np.zeros((1, 3))), + lambda dimer: dimer.fragment_operators("becke"), + ], + ids=["basis", "make_cube", "density", "orbital", "esp", "fragment_operators"], +) +def test_backend_without_a_basis(replay_dimer, analyse): + """The analysis of a dimer whose backend has no basis says so.""" + + with ( + no_psi4_calls(), + pytest.raises(NotImplementedError, match="ReplayBackend has no `basis`"), + ): + analyse(replay_dimer)