From 950508c8ac8fa176a08fd7bde97b44b3219dea64 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Sat, 14 Nov 2026 16:47:41 +0100 Subject: [PATCH 01/11] add natural orbitals of the density changes: density_natural_orbitals Co-Authored-By: Claude Opus 5.5 --- docs/api.rst | 8 + prop_sapt/__init__.py | 2 + prop_sapt/natural_orbitals.py | 268 +++++++++++++++++++++++++++++++++ tests/test_natural_orbitals.py | 173 +++++++++++++++++++++ 4 files changed, 451 insertions(+) create mode 100644 prop_sapt/natural_orbitals.py create mode 100644 tests/test_natural_orbitals.py diff --git a/docs/api.rst b/docs/api.rst index 46faffe..b527db0 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -35,6 +35,14 @@ Density Artifacts :undoc-members: :show-inheritance: +Natural Orbitals of Density Changes +----------------------------------- + +.. automodule:: prop_sapt.natural_orbitals + :members: + :undoc-members: + :show-inheritance: + Invariant Checks ---------------- diff --git a/prop_sapt/__init__.py b/prop_sapt/__init__.py index 738cd45..0e971f5 100644 --- a/prop_sapt/__init__.py +++ b/prop_sapt/__init__.py @@ -3,6 +3,7 @@ from .properties import calc_property from .densities import calc_density_matrix, calc_densities, DENSITY_COMPONENTS from .artifacts import load_densities +from .natural_orbitals import density_natural_orbitals from .sapt_driver import calc_sapt_energy from .finite_field import finite_field_sapt from .options import set_propsapt_options, get_propsapt_options, reset_propsapt_options @@ -16,6 +17,7 @@ "calc_densities", "DENSITY_COMPONENTS", "load_densities", + "density_natural_orbitals", "calc_sapt_energy", "finite_field_sapt", "set_propsapt_options", diff --git a/prop_sapt/natural_orbitals.py b/prop_sapt/natural_orbitals.py new file mode 100644 index 0000000..93feda9 --- /dev/null +++ b/prop_sapt/natural_orbitals.py @@ -0,0 +1,268 @@ +""" +Natural orbitals of the interaction-induced density changes. + +The density change ``dP_X`` of monomer X (AO basis, one spin) lies in the span of the +monomer's orbitals ``C_X``, which are orthonormal (``C_X^T S C_X = 1``). In that basis it +is the symmetric matrix ``D_X = C_X^T S dP_X S C_X``. The eigenvectors ``U`` of ``D_X`` +give the natural orbitals ``C_X U``, and its eigenvalues ``n`` their occupations. The +density change is then exactly ``dP_X = (C_X U) diag(n) (C_X U)^T``. + +- **Occupations:** they are for one spin, like the matrices of `calc_densities`, so the + total density change is twice theirs. They sum to ``Tr(dP_X S) = 0``: a density change + moves charge without changing the number of electrons. +- **Signs:** orbitals of positive occupation show where charge goes, and those of negative + occupation where it comes from. +- **Reading them:** a few orbitals usually carry most of a density change, so they picture + it in the spirit of natural orbitals for chemical valence (NOCV). First-order + polarisation and exchange mix only occupied with virtual orbitals, so their occupations + come in +/- pairs. +- **Dimer keys:** for the sum of both monomers (e.g. "pol"), the orbitals of A and of B + are listed together. The two sets are not orthogonal to each other, but their density is + exactly the sum. + +Classes +------- +NaturalOrbitals + Occupations and AO coefficients of natural orbitals, with the monomer of each. + +Functions +--------- +natural_orbitals + Natural orbitals of one monomer's density change. +density_natural_orbitals + Natural orbitals of the density changes of `calc_densities` or of a bundle. +""" + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass + +import numpy as np + +from .artifacts import DensitySet + +#: Largest ``|dP - C D C^T|`` allowed by `natural_orbitals`, relative to ``max|dP|``: a +#: density change of a monomer lies in the span of its orbitals, up to round-off. +SPAN_RTOL = 1.0e-8 + +_MONOMERS = ("A", "B") + + +@dataclass(frozen=True, eq=False) +class NaturalOrbitals: + """ + Natural orbitals of a density change, sorted by decreasing occupation. + """ + + #: Occupations for one spin, shape (k,): the total density change is twice theirs. + occupations: np.ndarray + #: AO coefficients, shape (nbf, k), one orbital per column as in Psi4's ``Ca()``. + coefficients: np.ndarray + #: Monomer of each orbital, "A" or "B", shape (k,). + monomers: np.ndarray + + def __len__(self) -> int: + return len(self.occupations) + + def density(self) -> np.ndarray: + """ + The density change of the orbitals, ``sum_k n_k c_k c_k^T`` (AO basis, one spin). + + Returns: + np.ndarray: AO matrix, shape (nbf, nbf). + """ + + return (self.coefficients * self.occupations) @ self.coefficients.T + + def select(self, cutoff: float) -> "NaturalOrbitals": + """ + The orbitals whose occupation is larger than `cutoff` in magnitude. + + Args: + cutoff (float): Smallest ``|n|`` kept (one spin); smaller ones are dropped. + + Returns: + NaturalOrbitals: The orbitals kept, in the same order. + """ + + keep = np.abs(self.occupations) > cutoff + return NaturalOrbitals( + self.occupations[keep], self.coefficients[:, keep], self.monomers[keep] + ) + + +def natural_orbitals( + density: np.ndarray, orbitals: np.ndarray, overlap: np.ndarray, monomer: str = "A" +) -> NaturalOrbitals: + """ + Natural orbitals of a monomer's density change, in the basis of its orbitals. + + Args: + density (np.ndarray): Density change, AO basis, shape (nbf, nbf). + orbitals (np.ndarray): The monomer's orthonormal orbitals ``C`` (e.g. `Dimer.C_A`), + shape (nbf, nmo). + overlap (np.ndarray): AO overlap matrix ``S`` (e.g. `Dimer.S`), shape (nbf, nbf). + monomer (str, optional): Monomer recorded for the orbitals. Defaults to "A". + + Raises: + ValueError: If the shapes do not match, or if `density` does not lie in the span of + `orbitals` (to `SPAN_RTOL`). That can only happen when the monomer has fewer + orbitals than basis functions (linear dependencies removed): with as many, every + matrix lies in their span, so the check cannot tell an MO-basis matrix from an AO + one. + + Returns: + NaturalOrbitals: As many orbitals as `orbitals` has columns, by decreasing + occupation. + """ + + density = np.asarray(density, dtype=np.float64) + orbitals = np.asarray(orbitals, dtype=np.float64) + overlap = np.asarray(overlap, dtype=np.float64) + nbf = overlap.shape[0] + if ( + density.shape != (nbf, nbf) + or overlap.shape != (nbf, nbf) + or orbitals.ndim != 2 + or orbitals.shape[0] != nbf + ): + raise ValueError( + f"Shapes do not match: density {density.shape}, orbitals {orbitals.shape}, " + f"overlap {overlap.shape}; the density and the overlap are AO matrices " + "(nbf, nbf) and the orbitals (nbf, nmo)!" + ) + + projector = overlap @ orbitals + in_orbitals = projector.T @ density @ projector + in_orbitals = 0.5 * (in_orbitals + in_orbitals.T) + + deviation = np.max(np.abs(orbitals @ in_orbitals @ orbitals.T - density)) + if not deviation <= SPAN_RTOL * np.max(np.abs(density)): + raise ValueError( + f"The density change does not lie in the span of the orbitals of monomer " + f"{monomer} (max deviation {deviation:.1e}): pass an AO matrix of that " + "monomer's density change, as `calc_densities` returns them in the AO basis " + "(the default)." + ) + + occupations, vectors = np.linalg.eigh(in_orbitals) + order = np.argsort(-occupations, kind="stable") + + return NaturalOrbitals( + occupations[order], + orbitals @ vectors[:, order], + np.full(len(occupations), monomer), + ) + + +def density_natural_orbitals( + densities: Mapping[str, np.ndarray] | DensitySet, + dimer=None, + keys: Iterable[str] | None = None, + cutoff: float = 0.0, +) -> dict[str, NaturalOrbitals]: + """ + Natural orbitals of interaction-induced density changes. + + Args: + densities (Mapping[str, np.ndarray] | DensitySet): The AO matrices returned by + `calc_densities` (the default ``orbital_basis="AO"``), or a bundle read by + `prop_sapt.load_densities`, whose monomer wavefunctions give the orbitals. + dimer (Dimer | None, optional): The dimer of the matrices, for its orbitals and + overlap; required with a dict of matrices, unused with a bundle. + Defaults to None. + keys (Iterable[str] | None, optional): Keys of the matrices, e.g. "pol_A" or + "pol" for the dimer, which needs "pol_A" and "pol_B". Defaults to every key of + `densities`. + cutoff (float, optional): Orbitals with ``|n|`` up to `cutoff` (one spin) are + dropped. Defaults to 0.0: every orbital is kept. + + Raises: + TypeError: If `densities` is a dict of matrices and no `dimer` is given. + KeyError: If a key, or a monomer matrix of a dimer key, is missing. + ValueError: If a bundle has no monomer wavefunctions, or a matrix is not a density + change of its monomer (see `natural_orbitals`). + + Returns: + dict[str, NaturalOrbitals]: Natural orbitals by key. For a dimer key, those of A + and B together, by decreasing occupation. + """ + + if isinstance(densities, DensitySet): + matrices = densities.matrices + orbitals, overlap = _bundle_orbitals(densities) + else: + if dimer is None: + raise TypeError( + "`dimer` is needed for its orbitals with a dict of density matrices!" + ) + matrices = densities + orbitals = {"A": np.asarray(dimer.C_A), "B": np.asarray(dimer.C_B)} + overlap = np.asarray(dimer.S) + + keys = list(matrices) if keys is None else list(keys) + + result = {} + for key in keys: + sets = [ + natural_orbitals(matrix, orbitals[monomer], overlap, monomer=monomer) + for monomer, matrix in _monomer_matrices(key, matrices) + ] + orbitals_of_key = _concatenate(sets) + result[key] = orbitals_of_key.select(cutoff) if cutoff else orbitals_of_key + + return result + + +def _monomer_matrices(key: str, matrices: Mapping[str, np.ndarray]) -> list: + """The (monomer, matrix) pairs of `key`: one for "_A" or "_B", both + monomers' for a dimer key "".""" + + for monomer in _MONOMERS: + if key.endswith(f"_{monomer}") and key in matrices: + return [(monomer, matrices[key])] + + missing = [f"{key}_{monomer}" for monomer in _MONOMERS] + missing = [name for name in missing if name not in matrices] + if missing: + raise KeyError( + f"No density matrix {key!r} of a monomer, and the dimer key needs " + f"{', '.join(repr(name) for name in missing)}; the keys are {sorted(matrices)}." + ) + + return [(monomer, matrices[f"{key}_{monomer}"]) for monomer in _MONOMERS] + + +def _concatenate(sets: list[NaturalOrbitals]) -> NaturalOrbitals: + """The orbitals of `sets` together, by decreasing occupation.""" + + if len(sets) == 1: + return sets[0] + + occupations = np.concatenate([s.occupations for s in sets]) + order = np.argsort(-occupations, kind="stable") + return NaturalOrbitals( + occupations[order], + np.concatenate([s.coefficients for s in sets], axis=1)[:, order], + np.concatenate([s.monomers for s in sets])[order], + ) + + +def _bundle_orbitals(densities: DensitySet) -> tuple[dict, np.ndarray]: + """The monomer orbitals (``Ca``) and the AO overlap of a bundle's wavefunctions.""" + + missing = [m for m in _MONOMERS if m not in densities.metadata["wavefunctions"]] + if missing: + raise ValueError( + f"Bundle '{densities.path}' has no wavefunction of monomer(s) " + f"{', '.join(missing)}: natural orbitals need the monomer orbitals, which " + "`calc_densities` saves with the matrices." + ) + + data = {monomer: densities.wavefunction_data(monomer) for monomer in _MONOMERS} + orbitals = { + monomer: np.asarray(data[monomer]["matrix"]["Ca"], dtype=np.float64) + for monomer in _MONOMERS + } + overlap = np.asarray(data["A"]["matrix"]["S"], dtype=np.float64) + + return orbitals, overlap diff --git a/tests/test_natural_orbitals.py b/tests/test_natural_orbitals.py new file mode 100644 index 0000000..56f4408 --- /dev/null +++ b/tests/test_natural_orbitals.py @@ -0,0 +1,173 @@ +"""Tests of the natural orbitals of the density changes (`prop_sapt.natural_orbitals`).""" + +import numpy as np +import pytest + +from prop_sapt import DENSITY_COMPONENTS, calc_densities, density_natural_orbitals +from prop_sapt.artifacts import DENSITIES_FILENAME, load_densities, save_densities +from prop_sapt.natural_orbitals import NaturalOrbitals, natural_orbitals + + +@pytest.fixture(scope="module") +def he_h2_densities(prepare_dimer): + """The AO density changes of He-H2, all keys, computed once.""" + + return calc_densities(prepare_dimer) + + +@pytest.fixture(scope="module") +def he_h2_orbitals(prepare_dimer, he_h2_densities): + """Their natural orbitals, all keys.""" + + return density_natural_orbitals(he_h2_densities, prepare_dimer) + + +def test_natural_orbitals_rebuild_every_density(he_h2_densities, he_h2_orbitals): + """sum_k n_k c_k c_k^T is the density change, for every key, also the dimer ones + (both monomers' orbitals together).""" + + assert set(he_h2_orbitals) == set(he_h2_densities) + for key, matrix in he_h2_densities.items(): + np.testing.assert_allclose( + he_h2_orbitals[key].density(), matrix, rtol=0, atol=1e-12, err_msg=key + ) + + +def test_natural_orbitals_are_orthonormal_and_sorted(prepare_dimer, he_h2_orbitals): + """A monomer's natural orbitals are orthonormal and sorted by decreasing occupation; + their occupations sum to Tr(dP S) = 0.""" + + overlap = prepare_dimer.S + for key, orbitals in he_h2_orbitals.items(): + assert np.all(np.diff(orbitals.occupations) <= 0.0), key + assert abs(orbitals.occupations.sum()) < 1e-12, key + if key.endswith(("_A", "_B")): + assert len(orbitals) == prepare_dimer.nmo + assert set(orbitals.monomers) == {key[-1]} + gram = orbitals.coefficients.T @ overlap @ orbitals.coefficients + np.testing.assert_allclose( + gram, np.eye(len(orbitals)), rtol=0, atol=1e-9, err_msg=key + ) + + +def test_dimer_key_lists_both_monomers(prepare_dimer, he_h2_orbitals): + """A dimer key has the orbitals of A and of B, by decreasing occupation.""" + + for component in DENSITY_COMPONENTS: + orbitals = he_h2_orbitals[component] + assert len(orbitals) == 2 * prepare_dimer.nmo + for monomer in ("A", "B"): + mine = orbitals.occupations[orbitals.monomers == monomer] + np.testing.assert_allclose( + mine, + he_h2_orbitals[f"{component}_{monomer}"].occupations, + rtol=0, + atol=1e-14, + ) + + +@pytest.mark.parametrize("component", ["pol", "exch"]) +@pytest.mark.parametrize("monomer", ["A", "B"]) +def test_first_order_orbitals_come_in_pairs( + prepare_dimer, he_h2_orbitals, component, monomer +): + """First-order polarisation and exchange mix occupied with virtual orbitals only, so + their occupations are +/- pairs, one per occupied orbital, and the rest zero.""" + + occupations = he_h2_orbitals[f"{component}_{monomer}"].occupations + ndocc = prepare_dimer.ndocc_A if monomer == "A" else prepare_dimer.ndocc_B + scale = np.abs(occupations).max() + + np.testing.assert_allclose( + occupations, -occupations[::-1], rtol=0, atol=1e-12 * scale + ) + assert np.sum(np.abs(occupations) > 1e-10 * scale) == 2 * ndocc + + +def test_cutoff_drops_small_occupations(prepare_dimer, he_h2_densities, he_h2_orbitals): + """`cutoff` drops the orbitals with |n| up to it, and keeps the order.""" + + kept = density_natural_orbitals( + he_h2_densities, prepare_dimer, keys=["Disp_A"], cutoff=1e-6 + )["Disp_A"] + full = he_h2_orbitals["Disp_A"] + + assert 0 < len(kept) < len(full) + np.testing.assert_array_equal( + kept.occupations, full.occupations[np.abs(full.occupations) > 1e-6] + ) + + +def test_bundle_gives_the_same_orbitals( + tmp_path, prepare_dimer, he_h2_densities, he_h2_orbitals +): + """A bundle's monomer wavefunctions give the same natural orbitals as the dimer.""" + + path = save_densities(tmp_path / DENSITIES_FILENAME, he_h2_densities, prepare_dimer) + from_bundle = density_natural_orbitals(load_densities(path), keys=["pol", "Disp_B"]) + + for key, orbitals in from_bundle.items(): + np.testing.assert_allclose( + orbitals.occupations, + he_h2_orbitals[key].occupations, + rtol=0, + atol=1e-14, + err_msg=key, + ) + np.testing.assert_allclose( + orbitals.density(), he_h2_densities[key], rtol=0, atol=1e-12, err_msg=key + ) + + +def test_bundle_without_wavefunctions_is_refused( + tmp_path, prepare_dimer, he_h2_densities +): + path = save_densities( + tmp_path / DENSITIES_FILENAME, + he_h2_densities, + prepare_dimer, + wavefunctions=False, + ) + + with pytest.raises(ValueError, match="no wavefunction of monomer"): + density_natural_orbitals(load_densities(path)) + + +def test_density_natural_orbitals_errors(he_h2_densities, prepare_dimer): + with pytest.raises(TypeError, match="`dimer` is needed"): + density_natural_orbitals(he_h2_densities) + + with pytest.raises(KeyError, match="needs 'pol_B'"): + density_natural_orbitals( + {"pol_A": he_h2_densities["pol_A"]}, prepare_dimer, keys=["pol"] + ) + + +def test_density_outside_the_orbitals_is_refused(prepare_dimer, he_h2_densities): + """With fewer orbitals than basis functions, a matrix outside their span is not a + density change of the monomer.""" + + orbitals = prepare_dimer.C_A[:, :-5] + rng = np.random.default_rng(3) + outside = rng.normal(size=orbitals.shape[:1] * 2) + outside = outside + outside.T + + with pytest.raises(ValueError, match="does not lie in the span"): + natural_orbitals(outside, orbitals, prepare_dimer.S) + + with pytest.raises(ValueError, match="Shapes do not match"): + natural_orbitals(he_h2_densities["pol_A"][:-1], orbitals, prepare_dimer.S) + + +def test_select_keeps_fields_together(): + orbitals = NaturalOrbitals( + np.array([0.3, 1e-9, -0.3]), + np.eye(3), + np.array(["A", "B", "A"]), + ) + + kept = orbitals.select(1e-6) + + np.testing.assert_array_equal(kept.occupations, [0.3, -0.3]) + np.testing.assert_array_equal(kept.coefficients, np.eye(3)[:, [0, 2]]) + np.testing.assert_array_equal(kept.monomers, ["A", "A"]) From a53c3f6d5bdc67531c246f03aef64c22e1bed6a6 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Sat, 14 Nov 2026 18:08:34 +0100 Subject: [PATCH 02/11] add the TREXIO export of the density changes: export_trexio, and the trexio extra The density changes are written as natural orbitals, positive occupations as alpha and negative ones as beta, so that VIAMD's alpha - beta density is the density change. Co-Authored-By: Claude Opus 5.5 --- docs/api.rst | 8 + prop-sapt.yaml | 1 + prop_sapt/trexio_export.py | 335 ++++++++++++++++++++++++++++++++++++ pyproject.toml | 2 + tests/test_trexio_export.py | 281 ++++++++++++++++++++++++++++++ tests/trexio_spec.py | 131 ++++++++++++++ 6 files changed, 758 insertions(+) create mode 100644 prop_sapt/trexio_export.py create mode 100644 tests/test_trexio_export.py create mode 100644 tests/trexio_spec.py diff --git a/docs/api.rst b/docs/api.rst index b527db0..568aeb1 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -43,6 +43,14 @@ Natural Orbitals of Density Changes :undoc-members: :show-inheritance: +TREXIO Export +------------- + +.. automodule:: prop_sapt.trexio_export + :members: + :undoc-members: + :show-inheritance: + Invariant Checks ---------------- diff --git a/prop-sapt.yaml b/prop-sapt.yaml index a096ef5..2ccc3e5 100644 --- a/prop-sapt.yaml +++ b/prop-sapt.yaml @@ -22,3 +22,4 @@ dependencies: - ipywidgets - scikit-image - pythreejs + - trexio diff --git a/prop_sapt/trexio_export.py b/prop_sapt/trexio_export.py new file mode 100644 index 0000000..13de679 --- /dev/null +++ b/prop_sapt/trexio_export.py @@ -0,0 +1,335 @@ +""" +Export of the interaction-induced density changes to TREXIO files, to view them in VIAMD. + +- **What is written:** TREXIO (https://github.com/TREX-CoE/trexio) has no AO density + matrix: a one-particle density is given by orbitals and their occupations. Each density + change is therefore written as its natural orbitals (`prop_sapt.natural_orbitals`), one + file per density, ``delta_dm_.h5``, with the names of the cube files. +- **Signs as spins:** VIAMD (https://github.com/scanberg/viamd) shows a signed density + only as the difference of the alpha and beta densities. The orbitals of positive + occupation are therefore written as alpha orbitals (``mo.spin`` 0), and those of + negative occupation as beta orbitals with ``|n|``. The occupations are for both spins + (twice the one-spin ``n``). +- **Reading a file:** its alpha - beta density is the total density change, and alpha + + beta means nothing. Every file says this in ``metadata.description``; other TREXIO + readers would take the orbitals for spin orbitals. +- **The basis set:** Psi4's basis set is written as it is, because Psi4's order of the AOs + in a shell (spherical: m = 0, +1, -1, ...; Cartesian: alphabetical) and its + normalisation are TREXIO's. +- **Nuclei:** ghost atoms are nuclei of charge 0 labelled "X". Atoms with an ECP have their + charge reduced by its core electrons; the ``ecp`` group is not written. +- **Optional dependency:** trexio is needed only here, installed with ``pip install trexio`` + or the ``trexio`` extra. It is imported when a file is written. + +Functions +--------- +export_trexio + Write density changes into TREXIO files, one per density. +import_trexio + Import trexio, explaining how to install it when it is missing. +""" + +import os +import warnings +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import psi4 + +from ._version import __version__ +from .natural_orbitals import NaturalOrbitals, density_natural_orbitals + +#: How to install the optional trexio package. +TREXIO_INSTALL = 'pip install trexio (or: pip install "prop_sapt[trexio]")' +#: Prefix of the file names, as for the cube files: ``delta_dm_.h5``. +TREXIO_PREFIX = "delta_dm_" +#: Extension of the files (TREXIO's HDF5 back end). +TREXIO_SUFFIX = ".h5" +#: Default of `export_trexio`'s `cutoff`: natural orbitals with ``|n|`` up to it (one +#: spin) are left out. +DEFAULT_CUTOFF = 1.0e-10 +#: Highest angular momentum VIAMD reads (g): it refuses files with higher shells. +VIAMD_MAX_ANGULAR_MOMENTUM = 4 +#: The encoding of the orbitals, recorded in the files and in a bundle's metadata. +ENCODING = ( + "natural orbitals of the density change: alpha orbitals carry the positive " + "occupations and beta orbitals the negative ones, as |n|; the occupations are for " + "the total density (2 x the one-spin matrix), so the density change is the " + "alpha - beta density" +) + +# Largest |coefficient - Psi4's| allowed, relative to the shell's largest coefficient +_COEFFICIENT_RTOL = 1.0e-10 + + +class TrexioExportError(RuntimeError): + """Raised when TREXIO files cannot be written: trexio is missing, or the basis set + cannot be written.""" + + +def import_trexio(): + """ + Import the trexio package. + + Raises: + TrexioExportError: If trexio is not installed, saying how to install it. + + Returns: + module: The trexio module. + """ + + try: + import trexio + except ImportError as err: + raise TrexioExportError( + f"Writing TREXIO files needs the trexio package ({err}). Install it with:\n" + f" {TREXIO_INSTALL}" + ) from err + + return trexio + + +def export_trexio( + densities: Mapping[str, np.ndarray], + directory: str | os.PathLike = ".", + *, + dimer=None, + keys: Iterable[str] | None = None, + cutoff: float = DEFAULT_CUTOFF, +) -> list[Path]: + """ + Write density changes into TREXIO files, one per density, as natural orbitals. + + See `prop_sapt.trexio_export` for the encoding. A file of the same name is replaced. + + Args: + densities (Mapping[str, np.ndarray]): AO density matrices as `calc_densities` + returns them (the default ``orbital_basis="AO"``), keyed "_A", + "_B" and "" for the dimer. + directory (str | os.PathLike, optional): Directory of the files, created if + needed. Defaults to ".". + dimer (Dimer): The dimer of the matrices: its geometry, basis set and orbitals. + keys (Iterable[str] | None, optional): The densities to write. Defaults to every + key of `densities`. + cutoff (float, optional): Natural orbitals with ``|n|`` up to `cutoff` (one spin) + are left out. Defaults to `DEFAULT_CUTOFF`. + + Raises: + TrexioExportError: If trexio is missing, or the basis set mixes spherical and + Cartesian shells. + TypeError: If no `dimer` is given. + + Warns: + UserWarning: If the basis set has shells above g, which VIAMD does not read. + + Returns: + list[Path]: The files written, in the order of `keys`. + """ + + trexio = import_trexio() + + if dimer is None: + raise TypeError("`dimer` is needed for its geometry, basis set and orbitals!") + + matrices = densities + keys = list(matrices) if keys is None else list(keys) + system = _system_arrays(dimer.fragments, dimer.get_psi4_basisset()) + orbitals = density_natural_orbitals(matrices, dimer, keys=keys, cutoff=cutoff) + + directory = Path(directory) + directory.mkdir(parents=True, exist_ok=True) + + paths = [] + for key in keys: + path = directory / f"{TREXIO_PREFIX}{key}{TREXIO_SUFFIX}" + _write_file(trexio, path, system, orbitals[key], _description(key)) + paths.append(path) + + return paths + + +@dataclass(frozen=True) +class _System: + """The nucleus, basis and ao groups of the files, the same in each.""" + + labels: list[str] + charges: np.ndarray + coordinates: np.ndarray + cartesian: bool + shell_center: list[int] + shell_am: list[int] + shell_factor: np.ndarray + prim_shell: list[int] + exponents: np.ndarray + coefficients: np.ndarray + prim_factor: np.ndarray + ao_shell: list[int] + + +def _system_arrays(fragments, basisset: psi4.core.BasisSet) -> _System: + """The nuclei of `fragments` (bohr) and `basisset`, in TREXIO's conventions.""" + + shells = [basisset.shell(index) for index in range(basisset.nshell())] + + # p shells count too: Psi4 orders spherical ones z, x, y and Cartesian ones x, y, z + pure = {shell.is_pure() for shell in shells if shell.am > 0} + if len(pure) > 1: + raise TrexioExportError( + f"Basis set {basisset.name()!r} mixes spherical and Cartesian shells, which " + "VIAMD does not read; use a basis set of one kind." + ) + + max_am = basisset.max_am() + if max_am > VIAMD_MAX_ANGULAR_MOMENTUM: + warnings.warn( + f"Basis set {basisset.name()!r} has shells up to l = {max_am}: VIAMD reads " + f"shells up to l = {VIAMD_MAX_ANGULAR_MOMENTUM} (g) and will refuse these " + "TREXIO files.", + UserWarning, + stacklevel=3, + ) + + molecule = basisset.molecule() + charges = [] + labels = [] + for atom in range(fragments.natom): + if fragments.real[atom]: + core = ( + basisset.n_ecp_core(molecule.label(atom)) if basisset.has_ECP() else 0 + ) + charges.append(float(fragments.atomic_numbers[atom] - core)) + labels.append(fragments.symbols[atom].capitalize()) + else: + charges.append(0.0) + labels.append("X") + + exponents, coefficients, prim_factor, prim_shell, shell_factor = [], [], [], [], [] + for index, shell in enumerate(shells): + exps = np.array([shell.exp(k) for k in range(shell.nprimitive)]) + coefs = np.array([shell.original_coef(k) for k in range(shell.nprimitive)]) + prim, factor = _normalisation(shell.am, exps, coefs) + + # TREXIO's normalisation of the shell is Psi4's + psi4_coefs = np.array([shell.coef(k) for k in range(shell.nprimitive)]) + if not np.max(np.abs(coefs * prim * factor - psi4_coefs)) <= ( + _COEFFICIENT_RTOL * np.max(np.abs(psi4_coefs)) + ): + raise TrexioExportError( + f"Shell {index} of basis set {basisset.name()!r} is not normalised as " + "TREXIO expects it." + ) + + exponents.extend(exps) + coefficients.extend(coefs) + prim_factor.extend(prim) + prim_shell.extend([index] * shell.nprimitive) + shell_factor.append(factor) + + return _System( + labels=labels, + charges=np.array(charges), + coordinates=np.array(fragments.coordinates, dtype=np.float64), + cartesian=not (pure.pop() if pure else basisset.has_puream()), + shell_center=[basisset.shell_to_center(index) for index in range(len(shells))], + shell_am=[shell.am for shell in shells], + shell_factor=np.array(shell_factor), + prim_shell=prim_shell, + exponents=np.array(exponents), + coefficients=np.array(coefficients), + prim_factor=np.array(prim_factor), + ao_shell=[ + index for index, shell in enumerate(shells) for _ in range(shell.nfunction) + ], + ) + + +def _double_factorial(n: int) -> int: + return 1 if n <= 0 else n * _double_factorial(n - 2) + + +def _normalisation(am: int, exps: np.ndarray, coefs: np.ndarray) -> tuple: + """The primitive factors and the shell factor that normalise the x^l component of a + contracted shell: TREXIO's ``basis.prim_factor`` and ``basis.shell_factor``.""" + + df = _double_factorial(2 * am - 1) + prim = (2 * exps / np.pi) ** 0.75 * (4 * exps) ** (am / 2) / np.sqrt(df) + weighted = coefs * prim + sums = exps[:, None] + exps[None, :] + overlap = ( + df * np.pi**1.5 / (2**am * sums ** (am + 1.5)) * np.outer(weighted, weighted) + ) + + return prim, 1.0 / np.sqrt(overlap.sum()) + + +def _description(key: str) -> str: + """The ``metadata.description`` of the file of `key`.""" + + if key.endswith("_A") or key.endswith("_B"): + what = f"monomer {key[-1]}" + else: + what = "the dimer (A + B)" + + return ( + f"propSAPT interaction-induced density change {key!r} of {what}, as {ENCODING}." + ) + + +def _write_file(trexio, path: Path, system: _System, orbitals: NaturalOrbitals, text): + """Write one TREXIO file: the system and the orbitals of `orbitals`, alpha for the + positive occupations and beta for the negative ones.""" + + if path.exists(): + path.unlink() # mode "w" adds to an existing file + + positive = np.where(orbitals.occupations > 0.0)[0] + negative = np.where(orbitals.occupations < 0.0)[0][::-1] # decreasing |n| + order = np.concatenate([positive, negative]) + + handle = trexio.File(str(path), mode="w", back_end=trexio.TREXIO_HDF5) + try: + trexio.write_metadata_code_num(handle, 2) + trexio.write_metadata_code( + handle, [f"propSAPT {__version__}", f"Psi4 {psi4.__version__}"] + ) + trexio.write_metadata_description(handle, text) + + trexio.write_nucleus_num(handle, len(system.labels)) + trexio.write_nucleus_charge(handle, system.charges) + trexio.write_nucleus_coord(handle, system.coordinates) + trexio.write_nucleus_label(handle, system.labels) + + trexio.write_basis_type(handle, "Gaussian") + trexio.write_basis_shell_num(handle, len(system.shell_am)) + trexio.write_basis_prim_num(handle, len(system.exponents)) + trexio.write_basis_nucleus_index(handle, system.shell_center) + trexio.write_basis_shell_ang_mom(handle, system.shell_am) + trexio.write_basis_shell_factor(handle, system.shell_factor) + trexio.write_basis_r_power(handle, [0] * len(system.shell_am)) + trexio.write_basis_shell_index(handle, system.prim_shell) + trexio.write_basis_exponent(handle, system.exponents) + trexio.write_basis_coefficient(handle, system.coefficients) + trexio.write_basis_prim_factor(handle, system.prim_factor) + + trexio.write_ao_cartesian(handle, int(system.cartesian)) + trexio.write_ao_num(handle, len(system.ao_shell)) + trexio.write_ao_shell(handle, system.ao_shell) + trexio.write_ao_normalization(handle, np.ones(len(system.ao_shell))) + + if len(order): + trexio.write_mo_type(handle, "Natural") + trexio.write_mo_num(handle, len(order)) + trexio.write_mo_coefficient( + handle, np.ascontiguousarray(orbitals.coefficients[:, order].T) + ) + trexio.write_mo_occupation( + handle, 2.0 * np.abs(orbitals.occupations[order]) + ) + trexio.write_mo_spin( + handle, + np.array([0] * len(positive) + [1] * len(negative), dtype=np.int32), + ) + finally: + handle.close() diff --git a/pyproject.toml b/pyproject.toml index 529d2a1..8a4bf70 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,6 +45,8 @@ test = ["pytest", "pytest-cov"] docs = ["sphinx>=5.0", "sphinx-rtd-theme>=1.0"] # `prop-sapt basis fetch bse`; the ccrepo source is installed from git, see prop_sapt/basis_fetch.py. bse = ["basis_set_exchange"] +# TREXIO files of the density changes (for VIAMD), see prop_sapt/trexio_export.py. +trexio = ["trexio"] [project.scripts] prop-sapt = "prop_sapt.cli:main" diff --git a/tests/test_trexio_export.py b/tests/test_trexio_export.py new file mode 100644 index 0000000..0cd8bb0 --- /dev/null +++ b/tests/test_trexio_export.py @@ -0,0 +1,281 @@ +"""Tests of the TREXIO export of the density changes (`prop_sapt.trexio_export`). + +The files are read back with trexio and evaluated by `tests.trexio_spec`, which follows the +TREXIO specification and is independent of Psi4. The tests that write files need trexio +and skip without it. +""" + +import importlib.util +import sys + +import numpy as np +import psi4 +import pytest + +from prop_sapt import calc_densities, reset_propsapt_options +from prop_sapt.evaluate import evaluate_basis_functions +from prop_sapt.fragments import DimerFragments +from prop_sapt.natural_orbitals import NaturalOrbitals, density_natural_orbitals +from prop_sapt.trexio_export import ( + DEFAULT_CUTOFF, + ENCODING, + TrexioExportError, + _system_arrays, + _write_file, + export_trexio, + import_trexio, +) + +from . import trexio_spec +from .he_h2 import OPTIONS + +needs_trexio = pytest.mark.skipif( + importlib.util.find_spec("trexio") is None, reason="trexio not installed" +) + +WATER_HE = """ +0 1 +O 0.000000 0.000000 0.117300 +H 0.000000 0.757200 -0.469200 +H 0.000000 -0.757200 -0.469200 +-- +0 1 +He 0.000000 0.000000 3.200000 +symmetry c1 +no_com +no_reorient +""" + + +@pytest.fixture(autouse=True, scope="module") +def restore_psi4_state(): + """Restores the global Psi4 and propSAPT state for the test modules after this one, + as the tests here build molecules and basis sets of their own.""" + + threads = psi4.core.get_num_threads() + + yield + + psi4.core.clean_options() + psi4.set_options(OPTIONS) + psi4.set_memory("2 GB") + psi4.set_num_threads(threads) + psi4.core.set_output_file("output.dat", True) + reset_propsapt_options() + + +@pytest.fixture +def restore_puream(): + """A test setting the puream option leaves it to the basis sets again.""" + + yield + psi4.core.revoke_global_option_changed("PUREAM") + + +def _points(molecule, count=400, seed=7): + rng = np.random.default_rng(seed) + centers = np.asarray(molecule.geometry()) + return centers[rng.integers(0, len(centers), count)] + rng.normal( + scale=0.9, size=(count, 3) + ) + + +def _write_aos(path, molecule, basisset): + """A file whose orbitals are the AOs of `basisset`, one by one.""" + + trexio = import_trexio() + nbf = basisset.nbf() + system = _system_arrays(DimerFragments.from_molecule(molecule), basisset) + aos = NaturalOrbitals(np.ones(nbf), np.eye(nbf), np.full(nbf, "A")) + _write_file(trexio, path, system, aos, "AOs") + + +@needs_trexio +@pytest.mark.parametrize( + "basis, puream", + [("cc-pvqz", None), ("cc-pvqz", False), ("6-31gss", None), ("sto-3g", None)], +) +def test_aos_are_psi4s(tmp_path, restore_puream, basis, puream): + """The AOs written, evaluated as the TREXIO specification defines them, are Psi4's: + spherical (up to g) and Cartesian shells, in Psi4's order and normalisation.""" + + psi4.core.set_output_file("output.dat", True) + if puream is not None: + psi4.set_options({"puream": puream}) + molecule = psi4.geometry(WATER_HE) + molecule.update_geometry() + basisset = psi4.core.BasisSet.build(molecule, "ORBITAL", basis) + path = tmp_path / "aos.h5" + + _write_aos(path, molecule, basisset) + + data = trexio_spec.read_file(path) + assert data["cartesian"] == (0 if basisset.has_puream() else 1) + points = _points(molecule) + np.testing.assert_allclose( + trexio_spec.orbital_values(data, points), + evaluate_basis_functions(points, basisset), + rtol=0, + atol=1e-12, + ) + + +@needs_trexio +def test_nuclei_ghosts_and_ecps(): + """Ghost atoms are nuclei of charge 0 labelled "X"; an ECP reduces the charge.""" + + psi4.core.set_output_file("output.dat", True) + molecule = psi4.geometry(""" +0 1 +I 0.0 0.0 0.0 +H 0.0 0.0 1.6 +-- +0 1 +He 0.0 0.0 5.0 +-- +0 1 +@Ne 0.0 3.0 0.0 +symmetry c1 +no_com +no_reorient +units bohr +""") + molecule.update_geometry() + basisset = psi4.core.BasisSet.build(molecule, "ORBITAL", "def2-svp") + + system = _system_arrays(DimerFragments.from_molecule(molecule), basisset) + + assert system.labels == ["I", "H", "He", "X"] + np.testing.assert_array_equal(system.charges, [53 - 28, 1, 2, 0]) + np.testing.assert_allclose(system.coordinates, np.asarray(molecule.geometry())) + + +@needs_trexio +def test_shells_above_g_warn(): + """VIAMD reads shells up to g: a basis set with h shells warns.""" + + psi4.core.set_output_file("output.dat", True) + molecule = psi4.geometry(""" +0 1 +Ne 0.0 0.0 0.0 +-- +0 1 +He 0.0 0.0 6.0 +symmetry c1 +no_com +no_reorient +units bohr +""") + molecule.update_geometry() + basisset = psi4.core.BasisSet.build(molecule, "ORBITAL", "cc-pv5z") + + with pytest.warns(UserWarning, match="VIAMD reads shells up to l = 4"): + _system_arrays(DimerFragments.from_molecule(molecule), basisset) + + +def test_mixed_shells_are_refused(): + """A basis set of spherical and Cartesian shells cannot be written.""" + + class Shell: + def __init__(self, am, pure): + self.am = am + self._pure = pure + + def is_pure(self): + return self._pure + + class Basis: + shells = [Shell(0, True), Shell(2, True), Shell(2, False)] + + def nshell(self): + return len(self.shells) + + def shell(self, index): + return self.shells[index] + + def name(self): + return "MIXED" + + with pytest.raises(TrexioExportError, match="mixes spherical and Cartesian"): + _system_arrays(None, Basis()) + + +# the He-H2 densities, computed once + + +@pytest.fixture(scope="module") +def he_h2_densities(prepare_dimer): + return calc_densities(prepare_dimer) + + +@needs_trexio +def test_files_hold_the_densities(tmp_path, prepare_dimer, he_h2_densities): + """Every file's alpha - beta density is the total density change (twice the one-spin + matrix): as a matrix, and at points as the specification evaluates it.""" + + paths = export_trexio(he_h2_densities, tmp_path, dimer=prepare_dimer, cutoff=0.0) + + assert [path.name for path in paths] == [ + f"delta_dm_{key}.h5" for key in he_h2_densities + ] + points = _points(prepare_dimer.get_psi4_molecule(), count=300) + for key, path in zip(he_h2_densities, paths): + data = trexio_spec.read_file(path) + signs = np.where(data["mo_spin"] == 0, 1.0, -1.0) + coefficients = data["mo_coefficient"].T + rebuilt = (coefficients * (signs * data["mo_occupation"])) @ coefficients.T + np.testing.assert_allclose( + rebuilt, 2 * he_h2_densities[key], rtol=0, atol=1e-12, err_msg=key + ) + if key in ("total", "pol_A", "Disp_B"): + np.testing.assert_allclose( + trexio_spec.difference_density(data, points), + prepare_dimer.evaluate_density(2 * he_h2_densities[key], points), + rtol=0, + atol=1e-14, + err_msg=key, + ) + + +@needs_trexio +def test_file_contents(tmp_path, prepare_dimer, he_h2_densities): + """The orbitals of a file: alpha for the positive occupations by decreasing n, beta for + the negative ones by decreasing |n|, without those up to the cutoff; the nuclei, the + description and the orbital type.""" + + (path,) = export_trexio( + he_h2_densities, tmp_path, dimer=prepare_dimer, keys=["Ind"] + ) + + data = trexio_spec.read_file(path) + orbitals = density_natural_orbitals( + he_h2_densities, prepare_dimer, keys=["Ind"], cutoff=DEFAULT_CUTOFF + )["Ind"] + n = orbitals.occupations + expected = 2 * np.concatenate([n[n > 0], -n[n < 0][::-1]]) + + np.testing.assert_allclose(data["mo_occupation"], expected, rtol=0, atol=0) + np.testing.assert_array_equal( + data["mo_spin"], [0] * np.sum(n > 0) + [1] * np.sum(n < 0) + ) + assert len(n) < 2 * prepare_dimer.nmo # the cutoff dropped some + assert data["mo_type"] == "Natural" + assert "'Ind' of the dimer (A + B)" in data["description"] + assert ENCODING in data["description"] + assert list(data["label"]) == ["He", "H", "H"] + np.testing.assert_array_equal(data["charge"], [2.0, 1.0, 1.0]) + + +@needs_trexio +def test_export_needs_a_dimer(): + with pytest.raises(TypeError, match="`dimer` is needed"): + export_trexio({"pol_A": np.zeros((2, 2))}) + + +def test_missing_trexio_is_explained(monkeypatch): + """Without trexio, writing a file says how to install it.""" + + monkeypatch.setitem(sys.modules, "trexio", None) # makes the import fail + + with pytest.raises(TrexioExportError, match="pip install trexio"): + import_trexio() diff --git a/tests/trexio_spec.py b/tests/trexio_spec.py new file mode 100644 index 0000000..e484ff5 --- /dev/null +++ b/tests/trexio_spec.py @@ -0,0 +1,131 @@ +""" +An evaluator of the orbitals in a TREXIO file, written from the TREXIO specification and +independent of Psi4: the tests of `prop_sapt.trexio_export` compare it with Psi4. + +- **AOs:** an AO is ``N'_i P(r - R) N_s sum_k f_k a_k exp(-g_k |r - R|^2)``, built from + ``ao.normalization``, ``basis.shell_factor``, ``basis.prim_factor``, + ``basis.coefficient`` and ``basis.exponent``. +- **Cartesian shells:** P is x^a y^b z^c, in alphabetical order. +- **Spherical shells:** P is the real solid harmonics, in the order m = 0, +1, -1, +2, -2, + ..., Racah-normalised and with the spec's phases (S_1^{+1} = x, S_1^{-1} = y). +- **Where the harmonics come from:** they are generated from Helgaker, Jorgensen and Olsen, + *Molecular Electronic-Structure Theory*, eqs. 6.4.47-6.4.50. Up to l = 4 these agree to + 4e-16 with trexio-tools' tables of the spec (``converters/cart_sphe.py`` times + ``normalization``). +""" + +from math import comb, factorial, sqrt + +import numpy as np + + +def cartesian_powers(l: int) -> list[tuple[int, int, int]]: + """The (a, b, c) of the Cartesian AOs of a shell, in alphabetical order.""" + + return [(a, b, l - a - b) for a in range(l, -1, -1) for b in range(l - a, -1, -1)] + + +def spherical_order(l: int) -> list[int]: + """The m of the spherical AOs of a shell: 0, +1, -1, ..., +l, -l.""" + + return [0] + [sign * k for k in range(1, l + 1) for sign in (1, -1)] + + +def solid_harmonic(l: int, m: int) -> dict[tuple[int, int, int], float]: + """The real solid harmonic S_lm as Cartesian coefficients {(a, b, c): coefficient}.""" + + am = abs(m) + norm = sqrt(2 * factorial(l + am) * factorial(l - am) / (2 if m == 0 else 1)) / ( + 2**am * factorial(l) + ) + two_vm = 0 if m >= 0 else 1 + coefficients = {} + for t in range((l - am) // 2 + 1): + for u in range(t + 1): + for two_v in range(two_vm, am + 1, 2): + c = ( + (-1) ** (t + (two_v - two_vm) // 2) + * 0.25**t + * comb(l, t) + * comb(l - t, am + t) + * comb(t, u) + * comb(am, two_v) + ) + power = (2 * t + am - 2 * u - two_v, 2 * u + two_v, l - 2 * t - am) + coefficients[power] = coefficients.get(power, 0.0) + norm * c + return coefficients + + +def read_file(path) -> dict: + """The arrays of a TREXIO file that its orbitals need.""" + + import trexio + + handle = trexio.File(str(path), mode="r", back_end=trexio.TREXIO_AUTO) + try: + data = { + "coord": trexio.read_nucleus_coord(handle), + "charge": trexio.read_nucleus_charge(handle), + "label": trexio.read_nucleus_label(handle), + "shell_center": trexio.read_basis_nucleus_index(handle), + "shell_am": trexio.read_basis_shell_ang_mom(handle), + "shell_factor": trexio.read_basis_shell_factor(handle), + "prim_shell": np.asarray(trexio.read_basis_shell_index(handle)), + "exponent": trexio.read_basis_exponent(handle), + "coefficient": trexio.read_basis_coefficient(handle) + * trexio.read_basis_prim_factor(handle), + "cartesian": trexio.read_ao_cartesian(handle), + "ao_shell": trexio.read_ao_shell(handle), + "ao_normalization": trexio.read_ao_normalization(handle), + "description": trexio.read_metadata_description(handle), + } + if trexio.has_mo_num(handle): + data["mo_type"] = trexio.read_mo_type(handle) + data["mo_coefficient"] = trexio.read_mo_coefficient(handle) + data["mo_occupation"] = trexio.read_mo_occupation(handle) + data["mo_spin"] = trexio.read_mo_spin(handle) + finally: + handle.close() + + return data + + +def ao_values(data: dict, points: np.ndarray) -> np.ndarray: + """The AOs of a file read by `read_file` at `points` (bohr), shape (npoints, nao).""" + + values = np.zeros((len(points), len(data["ao_shell"]))) + ao = 0 + for shell, l in enumerate(data["shell_am"]): + d = points - data["coord"][data["shell_center"][shell]] + r2 = np.einsum("pi,pi->p", d, d) + prims = np.where(data["prim_shell"] == shell)[0] + radial = data["shell_factor"][shell] * ( + np.exp(-np.outer(r2, data["exponent"][prims])) @ data["coefficient"][prims] + ) + if data["cartesian"]: + polynomials = [{power: 1.0} for power in cartesian_powers(l)] + else: + polynomials = [solid_harmonic(l, m) for m in spherical_order(l)] + for polynomial in polynomials: + assert data["ao_shell"][ao] == shell + angular = sum( + c * d[:, 0] ** a * d[:, 1] ** b * d[:, 2] ** e + for (a, b, e), c in polynomial.items() + ) + values[:, ao] = data["ao_normalization"][ao] * radial * angular + ao += 1 + + return values + + +def orbital_values(data: dict, points: np.ndarray) -> np.ndarray: + """The orbitals of a file at `points`, shape (npoints, nmo).""" + + return ao_values(data, points) @ data["mo_coefficient"].T + + +def difference_density(data: dict, points: np.ndarray) -> np.ndarray: + """The alpha - beta density of a file at `points`: the density change it holds.""" + + signs = np.where(np.asarray(data["mo_spin"]) == 0, 1.0, -1.0) + return orbital_values(data, points) ** 2 @ (signs * data["mo_occupation"]) From 0dc32ab71182d52a84d0ce7a97ddb180cf26ead7 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Sat, 14 Nov 2026 18:16:00 +0100 Subject: [PATCH 03/11] export_trexio leaves out only the numerically zero natural orbitals: relative_cutoff An absolute cutoff of 1e-10 changed the weaker density changes by up to 7e-6 of their largest value; 1e-12 of the largest occupation drops as many orbitals with no change. Co-Authored-By: Claude Opus 5.5 --- prop_sapt/trexio_export.py | 26 ++++++++++++++++++-------- tests/test_trexio_export.py | 17 +++++++++-------- 2 files changed, 27 insertions(+), 16 deletions(-) diff --git a/prop_sapt/trexio_export.py b/prop_sapt/trexio_export.py index 13de679..7a746d7 100644 --- a/prop_sapt/trexio_export.py +++ b/prop_sapt/trexio_export.py @@ -47,9 +47,10 @@ TREXIO_PREFIX = "delta_dm_" #: Extension of the files (TREXIO's HDF5 back end). TREXIO_SUFFIX = ".h5" -#: Default of `export_trexio`'s `cutoff`: natural orbitals with ``|n|`` up to it (one -#: spin) are left out. -DEFAULT_CUTOFF = 1.0e-10 +#: Default of `export_trexio`'s `relative_cutoff`: the natural orbitals left out are the +#: numerically zero ones (a density change has far fewer non-zero ones than orbitals), and +#: the density is unchanged to round-off. +DEFAULT_RELATIVE_CUTOFF = 1.0e-12 #: Highest angular momentum VIAMD reads (g): it refuses files with higher shells. VIAMD_MAX_ANGULAR_MOMENTUM = 4 #: The encoding of the orbitals, recorded in the files and in a bundle's metadata. @@ -97,7 +98,7 @@ def export_trexio( *, dimer=None, keys: Iterable[str] | None = None, - cutoff: float = DEFAULT_CUTOFF, + relative_cutoff: float = DEFAULT_RELATIVE_CUTOFF, ) -> list[Path]: """ Write density changes into TREXIO files, one per density, as natural orbitals. @@ -113,8 +114,9 @@ def export_trexio( dimer (Dimer): The dimer of the matrices: its geometry, basis set and orbitals. keys (Iterable[str] | None, optional): The densities to write. Defaults to every key of `densities`. - cutoff (float, optional): Natural orbitals with ``|n|`` up to `cutoff` (one spin) - are left out. Defaults to `DEFAULT_CUTOFF`. + relative_cutoff (float, optional): Natural orbitals with ``|n|`` up to + `relative_cutoff` times the largest ``|n|`` of their density are left out; 0 + keeps all but those of zero occupation. Defaults to `DEFAULT_RELATIVE_CUTOFF`. Raises: TrexioExportError: If trexio is missing, or the basis set mixes spherical and @@ -136,7 +138,7 @@ def export_trexio( matrices = densities keys = list(matrices) if keys is None else list(keys) system = _system_arrays(dimer.fragments, dimer.get_psi4_basisset()) - orbitals = density_natural_orbitals(matrices, dimer, keys=keys, cutoff=cutoff) + orbitals = density_natural_orbitals(matrices, dimer, keys=keys) directory = Path(directory) directory.mkdir(parents=True, exist_ok=True) @@ -144,12 +146,20 @@ def export_trexio( paths = [] for key in keys: path = directory / f"{TREXIO_PREFIX}{key}{TREXIO_SUFFIX}" - _write_file(trexio, path, system, orbitals[key], _description(key)) + selected = _select(orbitals[key], relative_cutoff) + _write_file(trexio, path, system, selected, _description(key)) paths.append(path) return paths +def _select(orbitals: NaturalOrbitals, relative_cutoff: float) -> NaturalOrbitals: + """The orbitals with ``|n|`` above `relative_cutoff` times the largest ``|n|``.""" + + largest = np.max(np.abs(orbitals.occupations), initial=0.0) + return orbitals.select(relative_cutoff * largest) + + @dataclass(frozen=True) class _System: """The nucleus, basis and ao groups of the files, the same in each.""" diff --git a/tests/test_trexio_export.py b/tests/test_trexio_export.py index 0cd8bb0..9d4f95b 100644 --- a/tests/test_trexio_export.py +++ b/tests/test_trexio_export.py @@ -17,7 +17,7 @@ from prop_sapt.fragments import DimerFragments from prop_sapt.natural_orbitals import NaturalOrbitals, density_natural_orbitals from prop_sapt.trexio_export import ( - DEFAULT_CUTOFF, + DEFAULT_RELATIVE_CUTOFF, ENCODING, TrexioExportError, _system_arrays, @@ -213,7 +213,9 @@ def test_files_hold_the_densities(tmp_path, prepare_dimer, he_h2_densities): """Every file's alpha - beta density is the total density change (twice the one-spin matrix): as a matrix, and at points as the specification evaluates it.""" - paths = export_trexio(he_h2_densities, tmp_path, dimer=prepare_dimer, cutoff=0.0) + paths = export_trexio( + he_h2_densities, tmp_path, dimer=prepare_dimer, relative_cutoff=0.0 + ) assert [path.name for path in paths] == [ f"delta_dm_{key}.h5" for key in he_h2_densities @@ -240,7 +242,7 @@ def test_files_hold_the_densities(tmp_path, prepare_dimer, he_h2_densities): @needs_trexio def test_file_contents(tmp_path, prepare_dimer, he_h2_densities): """The orbitals of a file: alpha for the positive occupations by decreasing n, beta for - the negative ones by decreasing |n|, without those up to the cutoff; the nuclei, the + the negative ones by decreasing |n|, without the numerically zero ones; the nuclei, the description and the orbital type.""" (path,) = export_trexio( @@ -248,17 +250,16 @@ def test_file_contents(tmp_path, prepare_dimer, he_h2_densities): ) data = trexio_spec.read_file(path) - orbitals = density_natural_orbitals( - he_h2_densities, prepare_dimer, keys=["Ind"], cutoff=DEFAULT_CUTOFF - )["Ind"] - n = orbitals.occupations + orbitals = density_natural_orbitals(he_h2_densities, prepare_dimer, keys=["Ind"]) + n = orbitals["Ind"].occupations + n = n[np.abs(n) > DEFAULT_RELATIVE_CUTOFF * np.abs(n).max()] expected = 2 * np.concatenate([n[n > 0], -n[n < 0][::-1]]) np.testing.assert_allclose(data["mo_occupation"], expected, rtol=0, atol=0) np.testing.assert_array_equal( data["mo_spin"], [0] * np.sum(n > 0) + [1] * np.sum(n < 0) ) - assert len(n) < 2 * prepare_dimer.nmo # the cutoff dropped some + assert len(n) < 2 * prepare_dimer.nmo # the numerically zero ones were dropped assert data["mo_type"] == "Natural" assert "'Ind' of the dimer (A + B)" in data["description"] assert ENCODING in data["description"] From 9820d97a7915f32f653ee56f8fa898d371aaad20 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Sat, 14 Nov 2026 18:16:54 +0100 Subject: [PATCH 04/11] calc_densities and the densities task save TREXIO files: save_trexio trexio is checked before the calculation (and when a run configuration asks for the files), and the bundle lists the files with their encoding, as it does the cubes. Co-Authored-By: Claude Opus 5.5 --- examples/run_config.yaml | 3 +- prop_sapt/config.py | 15 ++++- prop_sapt/densities.py | 44 ++++++++++++++- prop_sapt/runner.py | 2 + tests/test_config.py | 26 +++++++++ tests/test_runner.py | 2 + tests/test_trexio_export.py | 107 +++++++++++++++++++++++++++++++++++- 7 files changed, 193 insertions(+), 6 deletions(-) diff --git a/examples/run_config.yaml b/examples/run_config.yaml index ec035e1..5f43d6d 100644 --- a/examples/run_config.yaml +++ b/examples/run_config.yaml @@ -73,4 +73,5 @@ tasks: # property: {prop: dipole, results: property_results.csv} # interaction-induced density matrices (one densities.npz bundle, see # prop_sapt.load_densities) and their total-density cubes (delta_dm_*.cube) - densities: {orbital_basis: AO, save_cubes: true, save_matrices: true, matrix_format: npz} + densities: {orbital_basis: AO, save_cubes: true, save_matrices: true, matrix_format: npz, + save_trexio: false} # true: TREXIO files for VIAMD, needs `pip install trexio` diff --git a/prop_sapt/config.py b/prop_sapt/config.py index e8d404e..3a0705c 100644 --- a/prop_sapt/config.py +++ b/prop_sapt/config.py @@ -29,7 +29,7 @@ sapt_energy: {results: sapt_results.csv, response: true} property: {prop: dipole, results: property_results.csv, response: true} densities: {orbital_basis: AO, save_cubes: true, save_matrices: true, - matrix_format: npz} + matrix_format: npz, save_trexio: false} Values are taken from the built-in defaults, then the file, then the command-line flags. A `--df-basis` flag sets both fitting bases from its stem, replacing `df_basis_scf` and @@ -42,7 +42,9 @@ The densities task saves its matrices into one self-describing bundle, ``densities.npz`` (`matrix_format: npz`, read with `prop_sapt.load_densities`), or as bare ``.npy`` files (`matrix_format: npy`, deprecated). The older `compress_matrices: true/false` setting still -works, as `npz`/`npy`, with a deprecation warning. +works, as `npz`/`npy`, with a deprecation warning. With `save_trexio: true` it also saves +TREXIO files of the densities, ``delta_dm_.h5``, to view them in VIAMD; that needs the +trexio package (`prop_sapt.trexio_export`). Relative paths inside the file (`basis_overrides`, `basis_dirs`) are resolved against the directory of the file; the output directory is resolved against the current working @@ -53,6 +55,7 @@ Exchange with `prop-sapt basis fetch` (see `prop_sapt.basis_fetch`). """ +import importlib.util import json import os import re @@ -62,6 +65,7 @@ from collections.abc import Mapping from .densities import MATRIX_FORMATS +from .trexio_export import TREXIO_INSTALL from .options import _OPTION_DEFAULTS, check_if_valid_option, check_option_value from .basis_overrides import ASSIGNABLE_BASIS_NAME, load_basis_overrides @@ -86,6 +90,7 @@ class ConfigError(ValueError): "save_cubes": True, "save_matrices": True, "matrix_format": "npz", + "save_trexio": False, }, } @@ -646,6 +651,12 @@ def _check_task_settings(name: str, settings: dict) -> None: f"'tasks.densities.matrix_format' must be one of {', '.join(MATRIX_FORMATS)}." ) + if settings["save_trexio"] and importlib.util.find_spec("trexio") is None: + raise ConfigError( + "'tasks.densities.save_trexio' needs the trexio package, which is not " + f"installed. Install it with: {TREXIO_INSTALL}" + ) + def _translate_compress_matrices(settings: dict) -> dict: """Replaces the deprecated `compress_matrices` setting of the densities task with diff --git a/prop_sapt/densities.py b/prop_sapt/densities.py index 0a1674c..b570a8e 100644 --- a/prop_sapt/densities.py +++ b/prop_sapt/densities.py @@ -9,6 +9,13 @@ from .artifacts import DENSITIES_FILENAME, density_file_names, save_densities from .checks import check_symmetric from .cubes import Cube +from .trexio_export import ( + ENCODING, + TREXIO_PREFIX, + TREXIO_SUFFIX, + export_trexio, + import_trexio, +) from .utils import trace_memory_peak, CalcTimer, prepare_path from .cpscf_batching import DensityBuilder, options_cpscf_type, solve_batched from .densities_components.exch_disp import exch_disp_s2_density_builder @@ -71,13 +78,16 @@ def calc_densities( matrix_format: str | None = None, metadata: Mapping | None = None, compress_matrices: bool | None = None, + save_trexio=False, + trexio_dir=".", ) -> dict[str, np.ndarray]: """ Calculate interaction-induced changes in the density matrix of dimer (and both monomers). The matrices are for one spin (the ``Da`` convention): the total density of the closed-shell monomers is twice their sum. Saved matrices are always in the AO basis - (transformed from the MO basis if needed); saved cubes hold the total density. + (transformed from the MO basis if needed); saved cubes and TREXIO files hold the total + density. Args: dimer (Dimer): A dimer system. @@ -98,6 +108,14 @@ def calc_densities( bundle's metadata under "extra". Defaults to None. compress_matrices (bool | None, optional): Deprecated, use `matrix_format`: True is "npz" and False is "npy". + save_trexio (bool, optional): Whether to save TREXIO files of the densities, + ``delta_dm_.h5``, to view them in VIAMD (see `prop_sapt.trexio_export`). + Needs the trexio package, which is checked before the calculation. + Defaults to False. + trexio_dir (str, optional): Directory to save the TREXIO files. Defaults to ".". + + Raises: + TrexioExportError: If `save_trexio` is set and trexio is not installed. Returns: dict[str, np.ndarray]: Density matrices keyed "_A", "_B" @@ -108,6 +126,8 @@ def calc_densities( orbital_basis = orbital_basis.upper() matrix_format = _resolve_matrix_format(matrix_format, compress_matrices) + if save_trexio: + import_trexio() # before the calculation, which it would otherwise end try: # one CPSCF J/K object of the `cpscf_type` option for both monomers @@ -128,7 +148,7 @@ def calc_densities( # matrices to save, in the AO basis; nothing is added to them (they may be rho_dict) rho_ao = rho_dict - if orbital_basis != "AO" and (save_cubes or save_matrices): + if orbital_basis != "AO" and (save_cubes or save_matrices or save_trexio): psi4.core.print_out( f"\nWarning: Density matrices are in {orbital_basis} basis," @@ -147,6 +167,9 @@ def calc_densities( cube_filenames = { key: f"{cubes_dir}/{name}.cube" for key, name in file_names.items() } + trexio_filenames = [ + f"{trexio_dir}/{TREXIO_PREFIX}{key}{TREXIO_SUFFIX}" for key in rho_ao + ] if save_matrices: @@ -166,6 +189,14 @@ def calc_densities( ], "density": "total", } + if save_trexio: + bundle_metadata["trexio"] = { + "files": [ + os.path.relpath(fname, matrices_dir) + for fname in trexio_filenames + ], + "encoding": ENCODING, + } bundle = save_densities( Path(matrices_dir) / DENSITIES_FILENAME, @@ -224,6 +255,15 @@ def calc_densities( psi4.core.print_out("Density cubes saved.\n") + if save_trexio: + + psi4.core.print_out("\nSaving TREXIO files of the densities...\n") + export_trexio(rho_ao, trexio_dir, dimer=dimer) + psi4.core.print_out( + "TREXIO files saved: natural orbitals, the density change is the alpha - " + "beta density.\n" + ) + return rho_dict diff --git a/prop_sapt/runner.py b/prop_sapt/runner.py index d0320c7..45408a7 100644 --- a/prop_sapt/runner.py +++ b/prop_sapt/runner.py @@ -175,6 +175,8 @@ def _task_densities(dimer: Dimer, config: RunConfig, out_dir: Path, settings: di save_matrices=settings["save_matrices"], matrices_dir=str(out_dir), matrix_format=settings["matrix_format"], + save_trexio=settings["save_trexio"], + trexio_dir=str(out_dir), metadata={ "run": { "config_file": config.source, diff --git a/tests/test_config.py b/tests/test_config.py index c64ad68..9a0218f 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -3,7 +3,9 @@ None of these run a calculation. """ +import importlib.util import json +import sys import pytest @@ -224,6 +226,29 @@ def test_densities_matrix_format(): assert TASK_DEFAULTS["densities"]["matrix_format"] == "npz" +def test_densities_save_trexio_needs_trexio(monkeypatch): + """TREXIO files are off by default; asking for them without trexio installed fails + when the configuration is read, before any calculation.""" + + assert TASK_DEFAULTS["densities"]["save_trexio"] is False + + monkeypatch.setitem(sys.modules, "trexio", None) # trexio is not installed + with pytest.raises(ConfigError, match="pip install trexio"): + resolve_config({"tasks": {"densities": {"save_trexio": True}}}) + + config = resolve_config({"tasks": {"densities": {"save_trexio": False}}}) + assert config.tasks["densities"]["save_trexio"] is False + + +@pytest.mark.skipif( + importlib.util.find_spec("trexio") is None, reason="trexio not installed" +) +def test_densities_save_trexio(): + config = resolve_config({"tasks": {"densities": {"save_trexio": True}}}) + + assert config.tasks["densities"]["save_trexio"] is True + + @pytest.mark.parametrize("compress, matrix_format", [(True, "npz"), (False, "npy")]) def test_deprecated_compress_matrices_sets_matrix_format(compress, matrix_format): with pytest.warns(FutureWarning, match="compress_matrices' is deprecated"): @@ -316,6 +341,7 @@ def test_basis_dirs_are_resolved_against_the_config_directory(tmp_path): ({"tasks": {"sapt_energy": {"response": "yes"}}}, "response"), ({"tasks": {"property": {"response": "yes"}}}, "tasks.property.response"), ({"tasks": {"densities": {"save_cubes": "yes"}}}, "true or false"), + ({"tasks": {"densities": {"save_trexio": "yes"}}}, "true or false"), ({"tasks": {"densities": {"orbital_basis": "NO"}}}, "orbital_basis"), ({"tasks": {"densities": {"matrix_format": "hdf5"}}}, "matrix_format"), ( diff --git a/tests/test_runner.py b/tests/test_runner.py index 53b10a1..4c3ddee 100644 --- a/tests/test_runner.py +++ b/tests/test_runner.py @@ -146,6 +146,8 @@ def test_run_forwards_settings(recorder, geometry_file, tmp_path): "save_matrices": True, "matrices_dir": str(out_dir), "matrix_format": "npz", + "save_trexio": False, + "trexio_dir": str(out_dir), "metadata": { "run": { "config_file": None, diff --git a/tests/test_trexio_export.py b/tests/test_trexio_export.py index 9d4f95b..fb03380 100644 --- a/tests/test_trexio_export.py +++ b/tests/test_trexio_export.py @@ -12,7 +12,13 @@ import psi4 import pytest -from prop_sapt import calc_densities, reset_propsapt_options +import prop_sapt.densities as densities_module +from prop_sapt import ( + DENSITY_COMPONENTS, + calc_densities, + load_densities, + reset_propsapt_options, +) from prop_sapt.evaluate import evaluate_basis_functions from prop_sapt.fragments import DimerFragments from prop_sapt.natural_orbitals import NaturalOrbitals, density_natural_orbitals @@ -280,3 +286,102 @@ def test_missing_trexio_is_explained(monkeypatch): with pytest.raises(TrexioExportError, match="pip install trexio"): import_trexio() + + +# calc_densities(save_trexio=True), reusing the He-H2 components + + +@pytest.fixture +def cached_components(monkeypatch, prepare_dimer, he_h2_densities): + """Makes `calc_densities` reuse the He-H2 components instead of computing them, in + the AO basis or in the MO basis of their monomer (C^T S rho S C).""" + + orbitals = {"A": prepare_dimer.C_A, "B": prepare_dimer.C_B} + overlap = prepare_dimer.S + + def cached(mol, monomer, orbital_basis="AO"): + components = {} + for component in DENSITY_COMPONENTS: + rho = he_h2_densities[f"{component}_{monomer}"] + if orbital_basis == "MO": + C = orbitals[monomer] + rho = C.T @ overlap @ rho @ overlap @ C + components[component] = rho.copy() + return components + + monkeypatch.setattr(densities_module, "calc_density_matrix", cached) + + +@needs_trexio +def test_calc_densities_saves_trexio_files( + tmp_path, prepare_dimer, he_h2_densities, cached_components +): + """`save_trexio` writes a file per density, and the bundle lists them.""" + + rho = calc_densities( + prepare_dimer, + save_matrices=True, + matrices_dir=str(tmp_path), + save_trexio=True, + trexio_dir=str(tmp_path / "trexio"), + ) + + names = [f"delta_dm_{key}.h5" for key in rho] + assert sorted(path.name for path in (tmp_path / "trexio").iterdir()) == sorted( + names + ) + assert load_densities(tmp_path).metadata["trexio"] == { + "files": [f"trexio/{name}" for name in names], + "encoding": ENCODING, + } + + data = trexio_spec.read_file(tmp_path / "trexio" / "delta_dm_total.h5") + signs = np.where(data["mo_spin"] == 0, 1.0, -1.0) + coefficients = data["mo_coefficient"].T + np.testing.assert_allclose( + (coefficients * (signs * data["mo_occupation"])) @ coefficients.T, + 2 * he_h2_densities["total"], + rtol=0, + atol=1e-12, + ) + + +@needs_trexio +def test_calc_densities_in_the_mo_basis_saves_ao_densities( + tmp_path, prepare_dimer, he_h2_densities, cached_components +): + """In the MO basis the files hold the monomers' densities, transformed to the AO + basis: there is no dimer key, as for the cubes.""" + + calc_densities( + prepare_dimer, orbital_basis="MO", save_trexio=True, trexio_dir=str(tmp_path) + ) + + names = {path.name for path in tmp_path.iterdir()} + assert names == { + f"delta_dm_{component}_{monomer}.h5" + for component in DENSITY_COMPONENTS + for monomer in ("A", "B") + } + data = trexio_spec.read_file(tmp_path / "delta_dm_Disp_B.h5") + signs = np.where(data["mo_spin"] == 0, 1.0, -1.0) + coefficients = data["mo_coefficient"].T + np.testing.assert_allclose( + (coefficients * (signs * data["mo_occupation"])) @ coefficients.T, + 2 * he_h2_densities["Disp_B"], + rtol=0, + atol=1e-12, + ) + + +def test_calc_densities_checks_for_trexio_first(monkeypatch): + """Without trexio, `save_trexio` fails before the calculation, not after it.""" + + def calculation(*args, **kwargs): + raise AssertionError("the densities were calculated") + + monkeypatch.setattr(densities_module, "calc_density_matrix", calculation) + monkeypatch.setitem(sys.modules, "trexio", None) # trexio is not installed + + with pytest.raises(TrexioExportError, match="pip install trexio"): + calc_densities(object(), save_trexio=True) From b7257858b25a5ebee91f0efc8592df2909922aa4 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Sat, 14 Nov 2026 18:19:35 +0100 Subject: [PATCH 05/11] export_trexio reads densities.npz bundles, and the prop-sapt export trexio command The bundle's basis set is rebuilt by Psi4 and checked against the one it records; the orbitals come from its monomer wavefunctions. Co-Authored-By: Claude Opus 5.5 --- prop_sapt/__init__.py | 2 + prop_sapt/cli.py | 97 ++++++++++++++++++++++++++++++++++++- prop_sapt/trexio_export.py | 58 +++++++++++++++++----- tests/test_trexio_export.py | 96 ++++++++++++++++++++++++++++++++++++ 4 files changed, 238 insertions(+), 15 deletions(-) diff --git a/prop_sapt/__init__.py b/prop_sapt/__init__.py index 0e971f5..42fef6d 100644 --- a/prop_sapt/__init__.py +++ b/prop_sapt/__init__.py @@ -4,6 +4,7 @@ from .densities import calc_density_matrix, calc_densities, DENSITY_COMPONENTS from .artifacts import load_densities from .natural_orbitals import density_natural_orbitals +from .trexio_export import export_trexio from .sapt_driver import calc_sapt_energy from .finite_field import finite_field_sapt from .options import set_propsapt_options, get_propsapt_options, reset_propsapt_options @@ -18,6 +19,7 @@ "DENSITY_COMPONENTS", "load_densities", "density_natural_orbitals", + "export_trexio", "calc_sapt_energy", "finite_field_sapt", "set_propsapt_options", diff --git a/prop_sapt/cli.py b/prop_sapt/cli.py index 82407a0..3007e58 100644 --- a/prop_sapt/cli.py +++ b/prop_sapt/cli.py @@ -3,12 +3,15 @@ prop-sapt run CONFIG GEOMETRY [GEOMETRY ...] [--memory 32 --threads 8 ...] prop-sapt basis fetch SOURCE NAME --elements He,Li [--dir basis] + prop-sapt export trexio BUNDLE [--output-dir DIR] [--keys total pol ...] `run` runs the tasks of a configuration file (see `prop_sapt.config`) for each geometry in turn; flags override the values in the file. `basis fetch` writes a basis set missing from -Psi4's library into a file for `basis_dirs` (see `prop_sapt.basis_fetch`). +Psi4's library into a file for `basis_dirs` (see `prop_sapt.basis_fetch`). `export trexio` +writes TREXIO files of the densities of a ``densities.npz`` bundle, to view them in VIAMD +(see `prop_sapt.trexio_export`). Exit status: 0 on success, 1 if a calculation failed, 2 for an invalid configuration, -command line or basis set request. +command line, basis set request or bundle. """ import argparse @@ -82,6 +85,7 @@ def build_parser() -> argparse.ArgumentParser: ) _add_basis_parser(subparsers) + _add_export_parser(subparsers) return parser @@ -133,6 +137,56 @@ def _add_basis_parser(subparsers) -> None: ) +def _add_export_parser(subparsers) -> None: + """Adds the `prop-sapt export` commands.""" + + from .trexio_export import DEFAULT_RELATIVE_CUTOFF + + export_parser = subparsers.add_parser( + "export", help="Write the results of a calculation in other formats." + ) + export_subparsers = export_parser.add_subparsers( + dest="export_command", required=True + ) + + trexio_parser = export_subparsers.add_parser( + "trexio", + help="Write TREXIO files of the densities of a densities.npz bundle, for VIAMD.", + description=( + "Write the density changes of a densities.npz bundle into TREXIO files, " + "delta_dm_.h5, as natural orbitals: VIAMD shows a density change as the " + "alpha - beta density of its file. Needs the trexio package. Psi4 rebuilds " + "the basis set by name, so one from a run's basis_dirs or basis_overrides is " + "not available here: use prop_sapt.export_trexio after making it available " + "to Psi4." + ), + ) + trexio_parser.add_argument( + "bundle", help="Path to densities.npz, or to the directory holding it." + ) + trexio_parser.add_argument( + "--output-dir", + dest="output_dir", + help="Directory to write into (default: the bundle's directory).", + ) + trexio_parser.add_argument( + "--keys", + nargs="+", + metavar="KEY", + help="Densities to write, e.g. total pol_A (default: all of the bundle).", + ) + trexio_parser.add_argument( + "--relative-cutoff", + dest="relative_cutoff", + type=float, + default=DEFAULT_RELATIVE_CUTOFF, + help=( + "Leave out natural orbitals with |n| up to this times the largest |n| of " + f"their density (default: {DEFAULT_RELATIVE_CUTOFF:g})." + ), + ) + + def main(argv: list[str] | None = None) -> int: """Entry point of the `prop-sapt` command. @@ -152,6 +206,9 @@ def main(argv: list[str] | None = None) -> int: if args.command == "basis": return _basis_fetch_command(args) + if args.command == "export": + return _export_trexio_command(args) + return 2 # unreachable: argparse requires a known command @@ -257,3 +314,39 @@ def _basis_fetch_command(args: argparse.Namespace) -> int: print(f" basis_overrides: {{{element}: {{{option}: {basis_name}}}}}") return 0 + + +def _export_trexio_command(args: argparse.Namespace) -> int: + """Runs `prop-sapt export trexio`.""" + + import psi4 + + from .artifacts import load_densities + from .trexio_export import TrexioExportError, export_trexio, import_trexio + + try: + import_trexio() # before reading the bundle + densities = load_densities(args.bundle) + psi4.core.be_quiet() # rebuilding the basis set prints Psi4's output + output_dir = args.output_dir or densities.path.parent + paths = export_trexio( + densities, + output_dir, + keys=args.keys, + relative_cutoff=args.relative_cutoff, + ) + # ArtifactError is a ValueError + except (ValueError, TrexioExportError, KeyError, OSError) as err: + message = err.args[0] if isinstance(err, KeyError) and err.args else err + print(f"prop-sapt: error: {message}", file=sys.stderr) + return 2 + + print(f"Wrote {len(paths)} TREXIO file(s) into {Path(output_dir)}:") + for path in paths: + print(f" {path.name}") + print( + "In VIAMD, show the Electron Density with spin Difference: the alpha - beta " + "density is the density change." + ) + + return 0 diff --git a/prop_sapt/trexio_export.py b/prop_sapt/trexio_export.py index 7a746d7..969e18c 100644 --- a/prop_sapt/trexio_export.py +++ b/prop_sapt/trexio_export.py @@ -39,6 +39,7 @@ import psi4 from ._version import __version__ +from .artifacts import DensitySet, load_densities from .natural_orbitals import NaturalOrbitals, density_natural_orbitals #: How to install the optional trexio package. @@ -67,7 +68,7 @@ class TrexioExportError(RuntimeError): """Raised when TREXIO files cannot be written: trexio is missing, or the basis set - cannot be written.""" + cannot be written or, for a bundle, rebuilt.""" def import_trexio(): @@ -93,7 +94,7 @@ def import_trexio(): def export_trexio( - densities: Mapping[str, np.ndarray], + densities: Mapping[str, np.ndarray] | DensitySet | str | os.PathLike, directory: str | os.PathLike = ".", *, dimer=None, @@ -105,13 +106,22 @@ def export_trexio( See `prop_sapt.trexio_export` for the encoding. A file of the same name is replaced. + A bundle needs its basis set rebuilt by Psi4, by name (`DensitySet.wavefunction`): a + basis set given by per-element overrides or read from a basis set directory has to be + made available to Psi4 first. The basis set rebuilt is checked against the one the + bundle records. + Args: - densities (Mapping[str, np.ndarray]): AO density matrices as `calc_densities` - returns them (the default ``orbital_basis="AO"``), keyed "_A", - "_B" and "" for the dimer. + densities (Mapping[str, np.ndarray] | DensitySet | str | os.PathLike): AO density + matrices as `calc_densities` returns them (the default ``orbital_basis="AO"``), + keyed "_A", "_B" and "" for the dimer; or a + bundle, read by `prop_sapt.load_densities` or given by its path (the file or + its directory). directory (str | os.PathLike, optional): Directory of the files, created if needed. Defaults to ".". - dimer (Dimer): The dimer of the matrices: its geometry, basis set and orbitals. + dimer (Dimer | None, optional): The dimer of the matrices, for its geometry, basis + set and orbitals; required with a dict of matrices, unused with a bundle. + Defaults to None. keys (Iterable[str] | None, optional): The densities to write. Defaults to every key of `densities`. relative_cutoff (float, optional): Natural orbitals with ``|n|`` up to @@ -119,9 +129,11 @@ def export_trexio( keeps all but those of zero occupation. Defaults to `DEFAULT_RELATIVE_CUTOFF`. Raises: - TrexioExportError: If trexio is missing, or the basis set mixes spherical and - Cartesian shells. - TypeError: If no `dimer` is given. + TrexioExportError: If trexio is missing, the basis set mixes spherical and + Cartesian shells, or Psi4 cannot rebuild a bundle's basis set. + ArtifactError: If a bundle is malformed, or its basis set rebuilt differs from the + one it records. + TypeError: If a dict of matrices comes without a `dimer`. Warns: UserWarning: If the basis set has shells above g, which VIAMD does not read. @@ -132,13 +144,20 @@ def export_trexio( trexio = import_trexio() - if dimer is None: + if isinstance(densities, (str, os.PathLike)): + densities = load_densities(densities) + + if isinstance(densities, DensitySet): + fragments, basisset = densities.fragments, _bundle_basisset(densities) + elif dimer is None: raise TypeError("`dimer` is needed for its geometry, basis set and orbitals!") + else: + fragments, basisset = dimer.fragments, dimer.get_psi4_basisset() - matrices = densities + matrices = densities.matrices if isinstance(densities, DensitySet) else densities keys = list(matrices) if keys is None else list(keys) - system = _system_arrays(dimer.fragments, dimer.get_psi4_basisset()) - orbitals = density_natural_orbitals(matrices, dimer, keys=keys) + system = _system_arrays(fragments, basisset) + orbitals = density_natural_orbitals(densities, dimer, keys=keys) directory = Path(directory) directory.mkdir(parents=True, exist_ok=True) @@ -153,6 +172,19 @@ def export_trexio( return paths +def _bundle_basisset(densities: DensitySet) -> psi4.core.BasisSet: + """The basis set of a bundle, rebuilt by Psi4 and checked against the bundle's.""" + + try: + basisset = densities.wavefunction("A").basisset() + except RuntimeError as err: + raise TrexioExportError(str(err)) from err + + densities.check(basisset=basisset) + + return basisset + + def _select(orbitals: NaturalOrbitals, relative_cutoff: float) -> NaturalOrbitals: """The orbitals with ``|n|`` above `relative_cutoff` times the largest ``|n|``.""" diff --git a/tests/test_trexio_export.py b/tests/test_trexio_export.py index fb03380..9aba7e7 100644 --- a/tests/test_trexio_export.py +++ b/tests/test_trexio_export.py @@ -19,6 +19,8 @@ load_densities, reset_propsapt_options, ) +from prop_sapt.artifacts import DENSITIES_FILENAME, save_densities +from prop_sapt.cli import main from prop_sapt.evaluate import evaluate_basis_functions from prop_sapt.fragments import DimerFragments from prop_sapt.natural_orbitals import NaturalOrbitals, density_natural_orbitals @@ -385,3 +387,97 @@ def calculation(*args, **kwargs): with pytest.raises(TrexioExportError, match="pip install trexio"): calc_densities(object(), save_trexio=True) + + +# export from a densities.npz bundle, also through `prop-sapt export trexio` + + +@pytest.fixture +def bundle(tmp_path, prepare_dimer, he_h2_densities): + """A bundle of the He-H2 densities.""" + + return save_densities( + tmp_path / "run" / DENSITIES_FILENAME, he_h2_densities, prepare_dimer + ) + + +EXPORT_KEYS = ["total", "pol_A", "Disp_B"] + + +def _assert_same_files(first, second): + for path_1, path_2 in zip(first, second, strict=True): + assert path_1.name == path_2.name + data_1, data_2 = trexio_spec.read_file(path_1), trexio_spec.read_file(path_2) + for name in ("coord", "charge", "shell_am", "exponent", "coefficient"): + np.testing.assert_array_equal(data_1[name], data_2[name], err_msg=name) + np.testing.assert_allclose( + data_1["shell_factor"], data_2["shell_factor"], rtol=1e-14, atol=0 + ) + assert list(data_1["label"]) == list(data_2["label"]) + assert data_1["description"] == data_2["description"] + for data in (data_1, data_2): + signs = np.where(data["mo_spin"] == 0, 1.0, -1.0) + coefficients = data["mo_coefficient"].T + data["density"] = (coefficients * (signs * data["mo_occupation"])) @ ( + coefficients.T + ) + np.testing.assert_allclose( + data_1["density"], data_2["density"], rtol=0, atol=1e-12 + ) + + +@needs_trexio +def test_export_from_a_bundle(tmp_path, prepare_dimer, he_h2_densities, bundle): + """A bundle, by path or read, gives the files the dimer gives: its basis set is + rebuilt by Psi4 and its orbitals come from its monomer wavefunctions.""" + + from_dimer = export_trexio( + he_h2_densities, tmp_path / "dimer", dimer=prepare_dimer, keys=EXPORT_KEYS + ) + from_path = export_trexio(bundle, tmp_path / "path", keys=EXPORT_KEYS) + from_set = export_trexio( + load_densities(bundle.parent), tmp_path / "set", keys=EXPORT_KEYS + ) + + _assert_same_files(from_dimer, from_path) + _assert_same_files(from_dimer, from_set) + + +@needs_trexio +def test_cli_export_trexio(tmp_path, capsys, prepare_dimer, he_h2_densities, bundle): + """`prop-sapt export trexio` writes the files next to the bundle by default.""" + + status = main(["export", "trexio", str(bundle), "--keys", *EXPORT_KEYS]) + + assert status == 0 + expected = export_trexio( + he_h2_densities, tmp_path / "dimer", dimer=prepare_dimer, keys=EXPORT_KEYS + ) + _assert_same_files(expected, [bundle.parent / path.name for path in expected]) + output = capsys.readouterr().out + assert "Wrote 3 TREXIO file(s)" in output + assert "spin Difference" in output + + status = main( + ["export", "trexio", str(bundle.parent), "--output-dir", str(tmp_path / "out")] + ) + assert status == 0 + assert len(list((tmp_path / "out").iterdir())) == len(he_h2_densities) + + +@needs_trexio +def test_cli_export_trexio_errors(tmp_path, capsys, bundle): + assert main(["export", "trexio", str(bundle), "--keys", "polarisation"]) == 2 + assert "No density matrix 'polarisation'" in capsys.readouterr().err + + assert main(["export", "trexio", str(tmp_path / "missing.npz")]) == 2 + assert "prop-sapt: error:" in capsys.readouterr().err + + +def test_cli_export_trexio_needs_trexio(tmp_path, capsys, monkeypatch): + """Without trexio the command says how to install it, before reading the bundle.""" + + monkeypatch.setitem(sys.modules, "trexio", None) # trexio is not installed + + assert main(["export", "trexio", str(tmp_path / "missing.npz")]) == 2 + assert "pip install trexio" in capsys.readouterr().err From 0d739331d36e9c616c8edff19748e6d36a3c5673 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Sat, 14 Nov 2026 18:23:11 +0100 Subject: [PATCH 06/11] docs, example and changelog of the TREXIO export and the natural orbitals The usage guide says how to write the files and view them in VIAMD, and how to read the natural orbitals of the density changes. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +++++ docs/examples.rst | 2 + docs/index.rst | 2 + docs/installation.rst | 4 ++ docs/usage.rst | 94 ++++++++++++++++++++++++++++++++++++++- examples/README.md | 2 + examples/export_trexio.py | 76 +++++++++++++++++++++++++++++++ 7 files changed, 190 insertions(+), 2 deletions(-) create mode 100644 examples/export_trexio.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 50a1e44..36cd811 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,18 @@ requests of the private repository propSAPT was developed in before it was publi ## [Unreleased] +### Added + +- TREXIO files of the density changes, to view them interactively in + [VIAMD](https://github.com/scanberg/viamd): `calc_densities(save_trexio=True)`, the + `save_trexio` setting of the `densities` task, and `export_trexio` and + `prop-sapt export trexio` for existing `densities.npz` bundles. Each file holds the + natural orbitals of a density change, and VIAMD shows the change as its alpha - beta + density. Needs the `trexio` package (the `trexio` extra). See the + [usage guide](https://btyrcha.github.io/propSAPT/usage.html#viewing-density-changes-in-viamd). +- `density_natural_orbitals`: the natural orbitals of the density changes, a few of which + usually carry most of a change, in the spirit of NOCV. + ### Fixed - The cube and `.npy` files of the `Ind` and `Disp` densities are now named diff --git a/docs/examples.rst b/docs/examples.rst index c0f5bd3..c66658b 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -21,6 +21,8 @@ Scripts :func:`~prop_sapt.artifacts.load_densities`; run :file:`save_mo_matrices.py` first * :file:`read_subtract_save.py` - cube arithmetic on the cubes that :file:`water_dimer.py` writes to :file:`water-dimer-cubes/`; run :file:`water_dimer.py` first +* :file:`export_trexio.py` - TREXIO files of the density changes of Ne–H2, to view them in + VIAMD, and the natural orbitals of its polarisation; needs ``trexio`` * :file:`run_config.yaml` - a commented configuration for ``prop-sapt run`` For example: diff --git a/docs/index.rst b/docs/index.rst index ecd1e97..1ba58ce 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -24,6 +24,8 @@ Features of any Psi4 method, e.g. MP2 or CCSD (a supermolecular reference) * Densities, orbitals and electrostatic potentials on grids, fragment populations, and :file:`.cube` file utilities +* The natural orbitals of the density changes, and TREXIO files of them for interactive + views in VIAMD * A command-line runner, ``prop-sapt run``, for production calculations from a configuration file diff --git a/docs/installation.rst b/docs/installation.rst index 45705c1..7ce3ebd 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -53,6 +53,10 @@ basis sets through packages that propSAPT itself does not need: * the ccRepo source, installed from git: ``pip install git+https://github.com/Sheffield-Theoretical-Chemistry/ccrepo_utility colorlog tqdm requests``. +Writing the density changes into TREXIO files, to view them in VIAMD (see +:ref:`the usage guide `), needs the ``trexio`` package: ``pip install trexio``, or +the ``trexio`` extra. The conda environment of :file:`prop-sapt.yaml` includes it. + The ``docs`` extra installs Sphinx and its theme, to build this documentation (``sphinx-build -W -b html docs docs/_build/html``). diff --git a/docs/usage.rst b/docs/usage.rst index 71d2bcd..a139ad7 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -260,6 +260,94 @@ still written with :python:`matrix_format="npy"`, but it is deprecated, and so i ``compress_matrices`` argument. +.. _viamd: + +Viewing Density Changes in VIAMD +-------------------------------- + +`VIAMD `_ shows electron densities and orbitals +interactively. propSAPT writes its density changes for it into +`TREXIO `_ files, one per density, named +:file:`delta_dm_.h5` like the cube files. Writing them needs the ``trexio`` package +(see :doc:`installation`). They can be written with the calculation, from its matrices, or +from a bundle: + +.. code-block:: python + + from prop_sapt import calc_densities, export_trexio + + densities = calc_densities(dimer, save_trexio=True, trexio_dir="trexio") + export_trexio(densities, "trexio", dimer=dimer, keys=["total", "pol"]) + export_trexio("results/geo1/densities.npz", "trexio") + +A bundle can also be converted from the command line: + +.. code-block:: bash + + prop-sapt export trexio results/geo1/densities.npz --keys total pol Ind Disp + +In a run configuration, ``densities: {save_trexio: true}`` writes the files into the +output directory next to the cubes. To convert a bundle, Psi4 rebuilds its basis set by +name, so a basis set from ``basis_dirs`` or ``basis_overrides`` has to be made available +to Psi4 first, as for :meth:`~prop_sapt.artifacts.DensitySet.wavefunction`. + +**What a file holds.** TREXIO, like VIAMD, gives a density by orbitals and their +occupations, so each file holds the natural orbitals of its density change (see +:ref:`natural-orbitals`). VIAMD shows a density with signs only as the difference of the +alpha and beta densities. The orbitals of positive occupation are therefore written as +alpha orbitals, and those of negative occupation as beta orbitals: the alpha - beta density +of a file is the total density change, as in the cube files. + +**Viewing a file in VIAMD:** + +#. Open the file. Add a representation of type *Electronic Structure*, with source + *Electron Density* and spin *Difference*. Its isosurfaces show in two colours where the + density grows and where it drops. +#. Set the isovalue. VIAMD draws density isosurfaces at plus and minus the *square* of the + isovalue, and density changes are small: start near the bottom of the slider (0.01 + draws the surfaces at 1e-4). Ctrl+click the slider to type a smaller value. +#. To see single natural orbitals, set the source to *Molecular Orbital*. Spin *Alpha* + lists the orbitals that gain density and *Beta* those that lose it, the largest first. + +**Limits:** + +- The *Total* spin means nothing for these files. +- VIAMD reads basis sets up to g functions. It refuses the files of a basis set with h + functions (e.g. aug-cc-pV5Z), and propSAPT warns when writing them. +- VIAMD's own cube export of a density puts the grid origin in its header half a voxel + away from where it evaluated the density. + +.. _natural-orbitals: + +Natural orbitals of the density changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:func:`~prop_sapt.natural_orbitals.density_natural_orbitals` gives the natural orbitals of +the density changes on their own, without trexio. It works on the matrices of a +calculation and on a bundle: + +.. code-block:: python + + from prop_sapt import density_natural_orbitals + + orbitals = density_natural_orbitals(densities, dimer, keys=["pol_A", "Disp"]) + orbitals["pol_A"].occupations # one spin, largest first + orbitals["pol_A"].coefficients # AO coefficients, one orbital per column + +**How to read them:** + +- **Occupations:** a monomer's natural orbitals are orthonormal, and their occupations sum + to zero, because a density change moves charge without changing the number of + electrons. Orbitals of positive occupation show where charge goes, and those of negative + occupation where it comes from. +- **Few orbitals matter:** a few orbitals usually carry most of a density change, so they + picture it in the spirit of natural orbitals for chemical valence (NOCV). First-order + polarisation and exchange come in +/- pairs. +- **Dimer keys:** a dimer key such as ``"Disp"`` lists the orbitals of both monomers. The + two sets are not orthogonal to each other, but their density is exactly the sum. +- **On a grid:** :meth:`~prop_sapt.molecule.Dimer.make_cube` with + :python:`obj_type="orbital"` puts a single orbital on a grid. + Finite-Field Properties ----------------------- @@ -376,7 +464,8 @@ recording the resolved configuration, the Psi4 options, the package versions and fragments of the geometry. The ``densities`` task saves its matrices into :file:`densities.npz` (``matrix_format: npz``, the default), whose metadata also holds the run configuration and the basis overrides applied; ``matrix_format: npy`` (deprecated) -writes bare :file:`.npy` files. +writes bare :file:`.npy` files. With ``save_trexio: true`` it also writes TREXIO files of +the densities, to view them in VIAMD (see :ref:`viamd`). The command exits with status 0 on success, 1 if a calculation failed and 2 for an invalid configuration, so it can be used directly in batch scripts, e.g. in a SLURM array job: @@ -715,7 +804,8 @@ See the Jupyter notebooks in the ``examples/`` directory: * ``visualise_orbital.ipynb`` - Visualize molecular orbitals * ``visualise_density.ipynb`` - Visualize density matrices -For more examples, see the :doc:`examples` section. +For interactive views of the density changes and their natural orbitals in VIAMD, see +:ref:`viamd`. For more examples, see the :doc:`examples` section. .. _known-limitations: diff --git a/examples/README.md b/examples/README.md index 647055a..154ea9f 100644 --- a/examples/README.md +++ b/examples/README.md @@ -19,6 +19,8 @@ finite field, and use aug-cc-pVTZ with aug-cc-pVQZ fitting sets. `load_densities`. Run `save_mo_matrices.py` first. - **`read_subtract_save.py`**: cube arithmetic on the cubes that `water_dimer.py` writes to `water-dimer-cubes/`. Run `water_dimer.py` first. +- **`export_trexio.py`**: TREXIO files of the density changes of Ne–H2, to view them in VIAMD, + and the natural orbitals of its polarisation. Needs `trexio` (`pip install trexio`). - **`run_config.yaml`**: a commented configuration for the `prop-sapt run` command-line runner. ## Notebooks diff --git a/examples/export_trexio.py b/examples/export_trexio.py new file mode 100644 index 0000000..4eca0c8 --- /dev/null +++ b/examples/export_trexio.py @@ -0,0 +1,76 @@ +""" +This example calculates the interaction-induced densities of a Ne-H2 dimer and writes them +into TREXIO files, to view them in VIAMD (https://github.com/scanberg/viamd), and prints +the leading natural orbitals of the first-order polarisation of each monomer. + +It needs the trexio package (pip install trexio). In VIAMD, open e.g. +trexio_ne_h2/delta_dm_total.h5 and show the Electron Density with spin Difference: the +alpha - beta density of a file is its density change. +""" + +import numpy as np +import psi4 +from prop_sapt import Dimer, calc_densities, density_natural_orbitals +from prop_sapt.utils import CalcTimer + +# specify geometry in Psi4 format +GEO = """ +symmetry c1 +no_com +no_reorient +units bohr +0 1 +Ne -2.500000000 0.000000000 0.000000000 +-- +0 1 +H 1.775500000 0.000000000 0.000000000 +H 3.224500000 0.000000000 0.000000000 +""" + +# specify memory and threads +MEMORY = "4 GB" +THREADS = 4 + +# specify basis sets +BASIS = "aug-cc-pvdz" +DF_BASIS = "aug-cc-pvdz" + +# specify options +OPTIONS = { + # "option": "value", + "basis": BASIS, + "DF_BASIS_SCF": DF_BASIS + "-jkfit", + "DF_BASIS_SAPT": DF_BASIS + "-ri", + "scf_type": "df", +} + +# specify output filename and the directory of the TREXIO files +OUTPUT_FILE_PATH = "output.dat" +TREXIO_DIR = "trexio_ne_h2" + +if __name__ == "__main__": + + with CalcTimer("Example propSAPT TREXIO export"): + + ### Psi4 options + psi4.set_memory(MEMORY) + psi4.set_num_threads(THREADS) + psi4.core.set_output_file(OUTPUT_FILE_PATH, False) + psi4.set_options(OPTIONS) + + ### Initialise prop_sapt.Dimer object + dimer = Dimer(GEO) + + ### Calculate the density matrices and write a TREXIO file of each + densities = calc_densities(dimer, save_trexio=True, trexio_dir=TREXIO_DIR) + + ### The natural orbitals of the polarisation: a +/- pair per occupied orbital + orbitals = density_natural_orbitals( + densities, dimer, keys=["pol_A", "pol_B"], cutoff=1e-8 + ) + for key, natural in orbitals.items(): + occupations = np.array2string(natural.occupations, precision=6) + print(f"{key}: {len(natural)} natural orbitals, occupations {occupations}") + + ### End calculations + psi4.core.clean() From 19b7bca00a3eb7215428575862a328703a0e3a9f Mon Sep 17 00:00:00 2001 From: btyrcha Date: Mon, 16 Nov 2026 14:34:16 +0100 Subject: [PATCH 07/11] TREXIO files are named as the cubes: density_file_names export_trexio and calc_densities name the TREXIO files through density_file_names, so the Ind and Disp files are delta_dm_ind-total*.h5 and delta_dm_disp-total*.h5 and no longer collide with ind and disp on a case-insensitive file system. export_trexio checks the names before it writes anything; TREXIO_PREFIX is gone. Co-Authored-By: Claude Opus 5.5 --- prop_sapt/cli.py | 3 ++- prop_sapt/config.py | 4 ++-- prop_sapt/densities.py | 9 ++++----- prop_sapt/trexio_export.py | 18 +++++++++++------ tests/test_trexio_export.py | 39 ++++++++++++++++++++++++++++--------- 5 files changed, 50 insertions(+), 23 deletions(-) diff --git a/prop_sapt/cli.py b/prop_sapt/cli.py index 3007e58..a2f9eb2 100644 --- a/prop_sapt/cli.py +++ b/prop_sapt/cli.py @@ -154,7 +154,8 @@ def _add_export_parser(subparsers) -> None: help="Write TREXIO files of the densities of a densities.npz bundle, for VIAMD.", description=( "Write the density changes of a densities.npz bundle into TREXIO files, " - "delta_dm_.h5, as natural orbitals: VIAMD shows a density change as the " + "delta_dm_.h5 (Ind and Disp as ind-total and disp-total), as natural " + "orbitals: VIAMD shows a density change as the " "alpha - beta density of its file. Needs the trexio package. Psi4 rebuilds " "the basis set by name, so one from a run's basis_dirs or basis_overrides is " "not available here: use prop_sapt.export_trexio after making it available " diff --git a/prop_sapt/config.py b/prop_sapt/config.py index 3a0705c..9f515ad 100644 --- a/prop_sapt/config.py +++ b/prop_sapt/config.py @@ -43,8 +43,8 @@ (`matrix_format: npz`, read with `prop_sapt.load_densities`), or as bare ``.npy`` files (`matrix_format: npy`, deprecated). The older `compress_matrices: true/false` setting still works, as `npz`/`npy`, with a deprecation warning. With `save_trexio: true` it also saves -TREXIO files of the densities, ``delta_dm_.h5``, to view them in VIAMD; that needs the -trexio package (`prop_sapt.trexio_export`). +TREXIO files of the densities, ``delta_dm_.h5`` named as the cubes, to view them in +VIAMD; that needs the trexio package (`prop_sapt.trexio_export`). Relative paths inside the file (`basis_overrides`, `basis_dirs`) are resolved against the directory of the file; the output directory is resolved against the current working diff --git a/prop_sapt/densities.py b/prop_sapt/densities.py index b570a8e..6c90d29 100644 --- a/prop_sapt/densities.py +++ b/prop_sapt/densities.py @@ -11,7 +11,6 @@ from .cubes import Cube from .trexio_export import ( ENCODING, - TREXIO_PREFIX, TREXIO_SUFFIX, export_trexio, import_trexio, @@ -109,9 +108,9 @@ def calc_densities( compress_matrices (bool | None, optional): Deprecated, use `matrix_format`: True is "npz" and False is "npy". save_trexio (bool, optional): Whether to save TREXIO files of the densities, - ``delta_dm_.h5``, to view them in VIAMD (see `prop_sapt.trexio_export`). - Needs the trexio package, which is checked before the calculation. - Defaults to False. + ``delta_dm_.h5``, named as the cubes, to view them in VIAMD (see + `prop_sapt.trexio_export`). Needs the trexio package, which is checked + before the calculation. Defaults to False. trexio_dir (str, optional): Directory to save the TREXIO files. Defaults to ".". Raises: @@ -168,7 +167,7 @@ def calc_densities( key: f"{cubes_dir}/{name}.cube" for key, name in file_names.items() } trexio_filenames = [ - f"{trexio_dir}/{TREXIO_PREFIX}{key}{TREXIO_SUFFIX}" for key in rho_ao + f"{trexio_dir}/{file_names[key]}{TREXIO_SUFFIX}" for key in rho_ao ] if save_matrices: diff --git a/prop_sapt/trexio_export.py b/prop_sapt/trexio_export.py index 969e18c..8910422 100644 --- a/prop_sapt/trexio_export.py +++ b/prop_sapt/trexio_export.py @@ -4,7 +4,9 @@ - **What is written:** TREXIO (https://github.com/TREX-CoE/trexio) has no AO density matrix: a one-particle density is given by orbitals and their occupations. Each density change is therefore written as its natural orbitals (`prop_sapt.natural_orbitals`), one - file per density, ``delta_dm_.h5``, with the names of the cube files. + file per density, ``delta_dm_.h5``, named as the cube files + (`prop_sapt.artifacts.density_file_name`: "Ind" and "Disp" are "ind-total" and + "disp-total"). - **Signs as spins:** VIAMD (https://github.com/scanberg/viamd) shows a signed density only as the difference of the alpha and beta densities. The orbitals of positive occupation are therefore written as alpha orbitals (``mo.spin`` 0), and those of @@ -39,13 +41,11 @@ import psi4 from ._version import __version__ -from .artifacts import DensitySet, load_densities +from .artifacts import DensitySet, density_file_names, load_densities from .natural_orbitals import NaturalOrbitals, density_natural_orbitals #: How to install the optional trexio package. TREXIO_INSTALL = 'pip install trexio (or: pip install "prop_sapt[trexio]")' -#: Prefix of the file names, as for the cube files: ``delta_dm_.h5``. -TREXIO_PREFIX = "delta_dm_" #: Extension of the files (TREXIO's HDF5 back end). TREXIO_SUFFIX = ".h5" #: Default of `export_trexio`'s `relative_cutoff`: the natural orbitals left out are the @@ -104,7 +104,9 @@ def export_trexio( """ Write density changes into TREXIO files, one per density, as natural orbitals. - See `prop_sapt.trexio_export` for the encoding. A file of the same name is replaced. + See `prop_sapt.trexio_export` for the encoding. The files are named as the cubes, + ``delta_dm_.h5`` (`prop_sapt.artifacts.density_file_name`). A file of the same + name is replaced. A bundle needs its basis set rebuilt by Psi4, by name (`DensitySet.wavefunction`): a basis set given by per-element overrides or read from a basis set directory has to be @@ -134,6 +136,8 @@ def export_trexio( ArtifactError: If a bundle is malformed, or its basis set rebuilt differs from the one it records. TypeError: If a dict of matrices comes without a `dimer`. + ValueError: If the file names of two densities differ only in case, so that + one would be written over the other; nothing is written then. Warns: UserWarning: If the basis set has shells above g, which VIAMD does not read. @@ -156,6 +160,8 @@ def export_trexio( matrices = densities.matrices if isinstance(densities, DensitySet) else densities keys = list(matrices) if keys is None else list(keys) + # distinct on any file system, checked before anything is written + names = density_file_names(keys, TREXIO_SUFFIX) system = _system_arrays(fragments, basisset) orbitals = density_natural_orbitals(densities, dimer, keys=keys) @@ -164,7 +170,7 @@ def export_trexio( paths = [] for key in keys: - path = directory / f"{TREXIO_PREFIX}{key}{TREXIO_SUFFIX}" + path = directory / names[key] selected = _select(orbitals[key], relative_cutoff) _write_file(trexio, path, system, selected, _description(key)) paths.append(path) diff --git a/tests/test_trexio_export.py b/tests/test_trexio_export.py index 9aba7e7..2c73415 100644 --- a/tests/test_trexio_export.py +++ b/tests/test_trexio_export.py @@ -19,7 +19,11 @@ load_densities, reset_propsapt_options, ) -from prop_sapt.artifacts import DENSITIES_FILENAME, save_densities +from prop_sapt.artifacts import ( + DENSITIES_FILENAME, + density_file_names, + save_densities, +) from prop_sapt.cli import main from prop_sapt.evaluate import evaluate_basis_functions from prop_sapt.fragments import DimerFragments @@ -225,9 +229,9 @@ def test_files_hold_the_densities(tmp_path, prepare_dimer, he_h2_densities): he_h2_densities, tmp_path, dimer=prepare_dimer, relative_cutoff=0.0 ) - assert [path.name for path in paths] == [ - f"delta_dm_{key}.h5" for key in he_h2_densities - ] + assert [path.name for path in paths] == list( + density_file_names(he_h2_densities, ".h5").values() + ) points = _points(prepare_dimer.get_psi4_molecule(), count=300) for key, path in zip(he_h2_densities, paths): data = trexio_spec.read_file(path) @@ -281,6 +285,22 @@ def test_export_needs_a_dimer(): export_trexio({"pol_A": np.zeros((2, 2))}) +@needs_trexio +def test_file_names_that_differ_only_in_case_are_refused( + tmp_path, prepare_dimer, he_h2_densities +): + """Keys whose file names differ only in case are refused before anything is + written: a case-insensitive file system would write one file over the other.""" + + matrix = he_h2_densities["ind_A"] + with pytest.raises(ValueError, match="differ only in case"): + export_trexio( + {"ind_A": matrix, "IND_A": matrix}, tmp_path / "out", dimer=prepare_dimer + ) + + assert not (tmp_path / "out").exists() + + def test_missing_trexio_is_explained(monkeypatch): """Without trexio, writing a file says how to install it.""" @@ -328,7 +348,7 @@ def test_calc_densities_saves_trexio_files( trexio_dir=str(tmp_path / "trexio"), ) - names = [f"delta_dm_{key}.h5" for key in rho] + names = list(density_file_names(rho, ".h5").values()) assert sorted(path.name for path in (tmp_path / "trexio").iterdir()) == sorted( names ) @@ -360,12 +380,13 @@ def test_calc_densities_in_the_mo_basis_saves_ao_densities( ) names = {path.name for path in tmp_path.iterdir()} - assert names == { - f"delta_dm_{component}_{monomer}.h5" + keys = [ + f"{component}_{monomer}" for component in DENSITY_COMPONENTS for monomer in ("A", "B") - } - data = trexio_spec.read_file(tmp_path / "delta_dm_Disp_B.h5") + ] + assert names == set(density_file_names(keys, ".h5").values()) + data = trexio_spec.read_file(tmp_path / "delta_dm_disp-total_B.h5") signs = np.where(data["mo_spin"] == 0, 1.0, -1.0) coefficients = data["mo_coefficient"].T np.testing.assert_allclose( From 5f05252bdb4607a4d3cded14c1aca37667abeaec Mon Sep 17 00:00:00 2001 From: btyrcha Date: Sat, 14 Nov 2026 18:23:31 +0100 Subject: [PATCH 08/11] AI usage log: the TREXIO export Co-Authored-By: Claude Opus 5.5 --- AI-USAGE.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/AI-USAGE.md b/AI-USAGE.md index 8c44460..63a027f 100644 --- a/AI-USAGE.md +++ b/AI-USAGE.md @@ -16,8 +16,9 @@ The short version, for disclosures; the log below has the detail. Copilot code review on some pull requests. - **What the AI assistance did.** Implementation of new features and refactoring, tests, documentation, CI and packaging, and reviews of code written by the authors. It also - diagnosed numerical discrepancies, and implemented corrections to the - orbital-relaxation terms of the second-order properties. + diagnosed numerical discrepancies, implemented corrections to the + orbital-relaxation terms of the second-order properties, and researched external file + formats and viewers (TREXIO, VIAMD) for new features. ## Log @@ -152,8 +153,10 @@ The short version, for disclosures; the log below has the detail. ### 2026-11-14 - Added the second-order properties preprint (arXiv:2611.07993) to the citations: `CITATION.cff` (under `references`, schema-validated), the README, and a new Citing section in the docs with BibTeX entries for both papers. +- TREXIO export of the density changes for interactive viewing in VIAMD, after an investigation of the format and the viewer (its source code) with a prototype: `density_natural_orbitals`, `export_trexio` with `calc_densities(save_trexio=True)`, the runner's `save_trexio` setting and `prop-sapt export trexio`, the `trexio` extra, tests against Psi4's AOs through a TREXIO-spec evaluator, docs and an example; exact to round-off on He–H2, and a density exported back from VIAMD matched propSAPT's to 1.2e-9 rms. ### 2026-11-16 - Prepared the 0.5.0 release (version, `CITATION.cff`, install commands, changelog section), after checking that its package code is the commit the `~/densities` recalculation ran with. - Fixed density file names that collided on case-insensitive file systems (`Ind`/`ind`, `Disp`/`disp`): a file-name helper with a collision check in `prop_sapt.artifacts`, `Ind`/`Disp` files named `ind-total`/`disp-total`, with tests, an example, docs and a changelog entry. +- Rebased the TREXIO export PR onto `main` after the 0.5.0 release (its changelog entries moved to the Unreleased section) and after the density file-name fix, naming the TREXIO files like the cubes through `density_file_names`, with a test of the collision check. From 909aca072207daa23d3e99a3e4c390c1d9007ab8 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Mon, 16 Nov 2026 15:32:10 +0100 Subject: [PATCH 09/11] the bundle's cubes and trexio entries record the files requested calc_densities writes the bundle before the cube and TREXIO files, so that a failed or interrupted export cannot lose the matrices. Its "cubes" and "trexio" metadata entries therefore list the files the call was asked to write, which may be missing if writing them failed. The calc_densities docstring, a comment and the usage guide now say so. Co-Authored-By: Claude Opus 5.5 --- docs/usage.rst | 4 ++++ prop_sapt/densities.py | 11 ++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/docs/usage.rst b/docs/usage.rst index a139ad7..83ebdb5 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -239,6 +239,10 @@ basis, into one self-describing bundle, :file:`densities.npz`. It also holds the wavefunctions and the metadata: the geometry and its fragments, the basis set and the fitting bases, the method, the Psi4 and propSAPT options, the versions, and the conventions. The basis sets and the Psi4 options are those the dimer was built with. +With :python:`save_cubes` or :python:`save_trexio` the metadata also lists the cube and +TREXIO files requested. They are written after the bundle, so that a failed or +interrupted export cannot lose the matrices; a file listed may then be missing, and TREXIO +files can be written again from the bundle (see :ref:`viamd`). Nothing in it is pickled. Read it back with :func:`~prop_sapt.artifacts.load_densities`, which checks the conventions and, if asked, that the matrices belong to a geometry, a dimer or a basis set: diff --git a/prop_sapt/densities.py b/prop_sapt/densities.py index 6c90d29..f3e962d 100644 --- a/prop_sapt/densities.py +++ b/prop_sapt/densities.py @@ -100,9 +100,12 @@ def calc_densities( matrices_dir (str, optional): Directory to save density matrices. Defaults to ".". matrix_format (str | None, optional): "npz" saves the matrices, the monomer wavefunctions and their metadata into one self-describing bundle, - ``densities.npz``, read with `prop_sapt.load_densities`. "npy" saves bare - ``delta_dm_.npy`` files, named as the cubes, and ``wfn_mon_.npy`` - files; it is deprecated. Defaults to "npz". + ``densities.npz``, read with `prop_sapt.load_densities`. Its metadata also + lists the cube and TREXIO files requested ("cubes", "trexio"), which are + written after the bundle: if writing them fails, the bundle is kept and + names files that are missing. "npy" saves bare ``delta_dm_.npy`` files, + named as the cubes, and ``wfn_mon_.npy`` files; it is deprecated. + Defaults to "npz". metadata (Mapping | None, optional): JSON-serialisable entries stored in the bundle's metadata under "extra". Defaults to None. compress_matrices (bool | None, optional): Deprecated, use `matrix_format`: @@ -180,6 +183,8 @@ def calc_densities( bundle_metadata = {} if metadata: bundle_metadata["extra"] = dict(metadata) + # the files requested, written after the bundle so that a failed export + # cannot lose the matrices: the entries record the request, not the files if save_cubes: bundle_metadata["cubes"] = { "files": [ From 100a30e4c5dc2d79890c1ebd8656eb561bbe85f0 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Mon, 16 Nov 2026 15:33:35 +0100 Subject: [PATCH 10/11] export_trexio checks relative_cutoff: at least 0 and below 1 A negative cutoff kept the natural orbitals of zero occupation, and one of 1 or more, or nan, silently left out every orbital. export_trexio now refuses them with a ValueError before anything else, which prop-sapt export trexio reports as an error. Co-Authored-By: Claude Opus 5.5 --- prop_sapt/cli.py | 3 ++- prop_sapt/trexio_export.py | 14 +++++++++++--- tests/test_trexio_export.py | 17 +++++++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/prop_sapt/cli.py b/prop_sapt/cli.py index a2f9eb2..82fc4d6 100644 --- a/prop_sapt/cli.py +++ b/prop_sapt/cli.py @@ -183,7 +183,8 @@ def _add_export_parser(subparsers) -> None: default=DEFAULT_RELATIVE_CUTOFF, help=( "Leave out natural orbitals with |n| up to this times the largest |n| of " - f"their density (default: {DEFAULT_RELATIVE_CUTOFF:g})." + "their density; at least 0 and below 1 " + f"(default: {DEFAULT_RELATIVE_CUTOFF:g})." ), ) diff --git a/prop_sapt/trexio_export.py b/prop_sapt/trexio_export.py index 8910422..c2581b1 100644 --- a/prop_sapt/trexio_export.py +++ b/prop_sapt/trexio_export.py @@ -128,7 +128,8 @@ def export_trexio( key of `densities`. relative_cutoff (float, optional): Natural orbitals with ``|n|`` up to `relative_cutoff` times the largest ``|n|`` of their density are left out; 0 - keeps all but those of zero occupation. Defaults to `DEFAULT_RELATIVE_CUTOFF`. + keeps all but those of zero occupation. At least 0 and below 1. Defaults to + `DEFAULT_RELATIVE_CUTOFF`. Raises: TrexioExportError: If trexio is missing, the basis set mixes spherical and @@ -136,8 +137,9 @@ def export_trexio( ArtifactError: If a bundle is malformed, or its basis set rebuilt differs from the one it records. TypeError: If a dict of matrices comes without a `dimer`. - ValueError: If the file names of two densities differ only in case, so that - one would be written over the other; nothing is written then. + ValueError: If `relative_cutoff` is not at least 0 and below 1, or the file + names of two densities differ only in case, so that one would be written + over the other; nothing is written then. Warns: UserWarning: If the basis set has shells above g, which VIAMD does not read. @@ -146,6 +148,12 @@ def export_trexio( list[Path]: The files written, in the order of `keys`. """ + # not a number fails too; 1 and above would leave out every orbital + if not 0.0 <= relative_cutoff < 1.0: + raise ValueError( + f"`relative_cutoff` should be at least 0 and below 1, got {relative_cutoff}!" + ) + trexio = import_trexio() if isinstance(densities, (str, os.PathLike)): diff --git a/tests/test_trexio_export.py b/tests/test_trexio_export.py index 2c73415..8d3c1a1 100644 --- a/tests/test_trexio_export.py +++ b/tests/test_trexio_export.py @@ -285,6 +285,20 @@ def test_export_needs_a_dimer(): export_trexio({"pol_A": np.zeros((2, 2))}) +@pytest.mark.parametrize("cutoff", [-1e-12, 1.0, 2.0, float("nan"), float("inf")]) +def test_relative_cutoff_is_checked(tmp_path, cutoff): + """A negative cutoff would keep the orbitals of zero occupation, and one of 1 or + more, or not a number, would leave out every orbital: they are refused before + anything else.""" + + with pytest.raises(ValueError, match="`relative_cutoff` should be at least 0"): + export_trexio( + {"pol_A": np.zeros((2, 2))}, tmp_path / "out", relative_cutoff=cutoff + ) + + assert not (tmp_path / "out").exists() + + @needs_trexio def test_file_names_that_differ_only_in_case_are_refused( tmp_path, prepare_dimer, he_h2_densities @@ -494,6 +508,9 @@ def test_cli_export_trexio_errors(tmp_path, capsys, bundle): assert main(["export", "trexio", str(tmp_path / "missing.npz")]) == 2 assert "prop-sapt: error:" in capsys.readouterr().err + assert main(["export", "trexio", str(bundle), "--relative-cutoff", "nan"]) == 2 + assert "`relative_cutoff` should be at least 0" in capsys.readouterr().err + def test_cli_export_trexio_needs_trexio(tmp_path, capsys, monkeypatch): """Without trexio the command says how to install it, before reading the bundle.""" From aeb7392f97f4f1eb7216f9ae8819eb7be083abc8 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Mon, 16 Nov 2026 15:33:35 +0100 Subject: [PATCH 11/11] AI usage log: the Copilot review of the TREXIO PR Co-Authored-By: Claude Opus 5.5 --- AI-USAGE.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AI-USAGE.md b/AI-USAGE.md index 63a027f..2c2e2ea 100644 --- a/AI-USAGE.md +++ b/AI-USAGE.md @@ -160,3 +160,4 @@ The short version, for disclosures; the log below has the detail. - Prepared the 0.5.0 release (version, `CITATION.cff`, install commands, changelog section), after checking that its package code is the commit the `~/densities` recalculation ran with. - Fixed density file names that collided on case-insensitive file systems (`Ind`/`ind`, `Disp`/`disp`): a file-name helper with a collision check in `prop_sapt.artifacts`, `Ind`/`Disp` files named `ind-total`/`disp-total`, with tests, an example, docs and a changelog entry. - Rebased the TREXIO export PR onto `main` after the 0.5.0 release (its changelog entries moved to the Unreleased section) and after the density file-name fix, naming the TREXIO files like the cubes through `density_file_names`, with a test of the collision check. +- Addressed the Copilot review of the TREXIO PR: documented that the bundle's cube and TREXIO entries record the files requested, which are written after it, and made `export_trexio` refuse a `relative_cutoff` outside [0, 1), with tests.