diff --git a/AI-USAGE.md b/AI-USAGE.md index 5918bb7..8c44460 100644 --- a/AI-USAGE.md +++ b/AI-USAGE.md @@ -156,3 +156,4 @@ The short version, for disclosures; the log below has the detail. ### 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. diff --git a/CHANGELOG.md b/CHANGELOG.md index d67d665..50a1e44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,15 @@ requests of the private repository propSAPT was developed in before it was publi ## [Unreleased] +### Fixed + +- The cube and `.npy` files of the `Ind` and `Disp` densities are now named + `delta_dm_ind-total*` and `delta_dm_disp-total*`. Their old names differ from those of + `ind` and `disp` only in case, so on a case-insensitive file system (macOS and Windows by + default) 0.4.0 and 0.5.0 wrote `Ind` and `Disp` over the `ind` and `disp` files without + an error: recompute `delta_dm_ind*` and `delta_dm_disp*` files written there. The keys + of the densities and the `densities.npz` bundle are unchanged. + ## [0.5.0] - 2026-11-16 ### Added diff --git a/docs/usage.rst b/docs/usage.rst index ce2f900..71d2bcd 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -231,7 +231,10 @@ but symmetrize such matrices with ``0.5 * (D + D.T)`` before an eigendecompositi natural orbitals) or before writing one triangle of them (e.g. into an fchk file). With :python:`save_cubes=True` the total densities are saved as :file:`.cube` files for -visualization. With :python:`save_matrices=True` the matrices are saved, always in the AO +visualization, :file:`delta_dm_.cube`. The ``Ind`` and ``Disp`` densities are saved as +:file:`delta_dm_ind-total*.cube` and :file:`delta_dm_disp-total*.cube`, because their keys +differ from ``ind`` and ``disp`` only in case, which macOS and Windows file systems do not +tell apart. With :python:`save_matrices=True` the matrices are saved, always in the AO basis, into one self-describing bundle, :file:`densities.npz`. It also holds the monomer 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 diff --git a/examples/make_cubes_from_mo_matrices.py b/examples/make_cubes_from_mo_matrices.py index 73a7a4f..5c78459 100644 --- a/examples/make_cubes_from_mo_matrices.py +++ b/examples/make_cubes_from_mo_matrices.py @@ -11,6 +11,7 @@ import psi4 from prop_sapt import load_densities +from prop_sapt.artifacts import density_file_name from prop_sapt.cubes import make_cube MATRICES_DIR = "matrices_MO" @@ -39,4 +40,4 @@ "density", basisset=basisset, # necesary in this case ) - cube.save(f"{MATRICES_DIR}/delta_dm_{key}.cube") + cube.save(f"{MATRICES_DIR}/{density_file_name(key, '.cube')}") diff --git a/prop_sapt/artifacts.py b/prop_sapt/artifacts.py index c181995..571620c 100644 --- a/prop_sapt/artifacts.py +++ b/prop_sapt/artifacts.py @@ -15,6 +15,11 @@ Nothing in the bundle is pickled: it is written and read with ``allow_pickle=False``. +Files of single densities, such as the ``.cube`` files written by `calc_densities`, are +named by `density_file_name`: ``delta_dm_``, except that the keys "Ind" and "Disp", +which differ from "ind" and "disp" only in case, are named "ind-total" and "disp-total" +(e.g. ``delta_dm_ind-total_A.cube``). Inside the bundle the entries keep the keys. + Conventions (`CONVENTIONS`): the matrices are in the AO basis of the dimer basis set, in Psi4 AO order, for one spin (the ``Da`` convention of the matrices `calc_densities` returns). The total density of a closed-shell system is twice the stored matrix, see @@ -36,13 +41,17 @@ Read a bundle, checking its conventions and, optionally, its geometry and basis set. artifact_metadata The metadata of a dimer recorded in the bundle. +density_file_name + File name of a single density, e.g. for its cube. +density_file_names + File names of several densities, checked to be distinct on any file system. """ import datetime import hashlib import json import os -from collections.abc import Mapping +from collections.abc import Iterable, Mapping from dataclasses import dataclass from pathlib import Path import numpy as np @@ -67,6 +76,15 @@ "total_density_factor": 2, } +#: Prefix of the names of the files of single densities, e.g. their cubes: see +#: `density_file_name`. +DENSITY_FILE_PREFIX = "delta_dm_" + +# Names in file names of the density components whose keys differ from others only in +# case ("Ind" and "ind", "Disp" and "disp"), which case-insensitive file systems would +# write into one file. +_FILE_COMPONENTS = {"Ind": "ind-total", "Disp": "disp-total"} + # entry names inside the bundle _METADATA_ENTRY = "metadata" _MATRIX_PREFIX = "delta_dm_" @@ -436,6 +454,60 @@ def load_densities( return densities +def density_file_name(key: str, suffix: str = "") -> str: + """ + File name of the density `key`, e.g. for its cube: ``delta_dm_``, with the + sum components "Ind" and "Disp" named "ind-total" and "disp-total". + + The keys "Ind" and "Disp" differ from "ind" and "disp" only in case, which + case-insensitive file systems (macOS and Windows by default) do not tell apart. + + Args: + key (str): Density key, e.g. "pol_A" or "Ind". + suffix (str, optional): Appended to the name, e.g. ".cube". Defaults to "". + + Returns: + str: The file name, e.g. "delta_dm_pol_A.cube" or "delta_dm_ind-total.cube". + """ + + component, monomer = _split_monomer(key) + component = _FILE_COMPONENTS.get(component, component) + + return f"{DENSITY_FILE_PREFIX}{component}{monomer}{suffix}" + + +def density_file_names(keys: Iterable[str], suffix: str = "") -> dict[str, str]: + """ + File names of the densities `keys`, see `density_file_name`, checked to be distinct + also on case-insensitive file systems. + + Args: + keys (Iterable[str]): Density keys. + suffix (str, optional): Appended to the names, e.g. ".cube". Defaults to "". + + Raises: + ValueError: If two names differ only in case, or not at all, so that one file + would be written over the other. + + Returns: + dict[str, str]: The file names by key. + """ + + names = {key: density_file_name(key, suffix) for key in keys} + + seen = {} + for key, name in names.items(): + other = seen.setdefault(name.casefold(), key) + if other != key: + raise ValueError( + f"The densities '{other}' and '{key}' would be saved into files whose " + f"names differ only in case, '{names[other]}' and '{name}', and one would " + "be written over the other on a case-insensitive file system!" + ) + + return names + + def _read_entry(npz, name: str, where: str) -> np.ndarray: """Reads one entry of an open bundle, refusing pickled data.""" @@ -555,12 +627,22 @@ def _check_basis(recorded: Mapping, basisset: psi4.core.BasisSet, where: str): ) +def _split_monomer(key: str) -> tuple[str, str]: + """Splits a matrix key into its density component and its "_A" or "_B" suffix, + which is "" for a dimer sum.""" + + if key.endswith(("_A", "_B")): + return key[:-2], key[-2:] + + return key, "" + + def _components(keys) -> list[str]: """Density components of matrix keys: the keys without a "_A" or "_B" suffix.""" components = [] for key in keys: - component = key[:-2] if key.endswith(("_A", "_B")) else key + component, _ = _split_monomer(key) if component not in components: components.append(component) diff --git a/prop_sapt/densities.py b/prop_sapt/densities.py index 90871fa..0a1674c 100644 --- a/prop_sapt/densities.py +++ b/prop_sapt/densities.py @@ -6,7 +6,7 @@ import numpy as np import opt_einsum as oe from .molecule import Dimer -from .artifacts import DENSITIES_FILENAME, save_densities +from .artifacts import DENSITIES_FILENAME, density_file_names, save_densities from .checks import check_symmetric from .cubes import Cube from .utils import trace_memory_peak, CalcTimer, prepare_path @@ -83,15 +83,17 @@ def calc_densities( dimer (Dimer): A dimer system. orbital_basis (str, optional): Select orbital basis of the returned density matrix, either "AO" or "MO". Defaults to "AO". - save_cubes (bool, optional): Whether to save density cubes. Defaults to False. + save_cubes (bool, optional): Whether to save density cubes, + ``delta_dm_.cube``, with "Ind" and "Disp" named "ind-total" and + "disp-total" (see `prop_sapt.artifacts.density_file_name`). Defaults to False. cubes_dir (str, optional): Directory to save density cubes. Defaults to ".". save_matrices (bool, optional): Whether to save density matrices. Defaults to False. 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`` and ``wfn_mon_.npy`` files; it is deprecated. - Defaults to "npz". + ``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`: @@ -140,7 +142,11 @@ def calc_densities( psi4.core.print_out("MO -> AO transformation complete.\n") - cube_filenames = {key: f"{cubes_dir}/delta_dm_{key}.cube" for key in rho_ao} + # distinct on any file system, checked before anything is written + file_names = density_file_names(rho_ao) + cube_filenames = { + key: f"{cubes_dir}/{name}.cube" for key, name in file_names.items() + } if save_matrices: @@ -185,7 +191,7 @@ def calc_densities( psi4.core.print_out(f"\nWarning: {message}\n") for key, matrix in rho_ao.items(): - np.save(f"{matrices_dir}/delta_dm_{key}.npy", matrix) + np.save(f"{matrices_dir}/{file_names[key]}.npy", matrix) psi4.core.print_out("Density matrices saved.\n") diff --git a/tests/test_artifacts.py b/tests/test_artifacts.py index 33ebb2f..81c0465 100644 --- a/tests/test_artifacts.py +++ b/tests/test_artifacts.py @@ -24,6 +24,8 @@ ArtifactError, _flatten_tree, _unflatten_tree, + density_file_name, + density_file_names, save_densities, ) from prop_sapt.checks import InvariantWarning @@ -447,6 +449,39 @@ def cached(mol, monomer, orbital_basis="AO"): } +@pytest.mark.parametrize( + "key, suffix, name", + [ + ("Ind_A", ".cube", "delta_dm_ind-total_A.cube"), + ("Ind_B", ".npy", "delta_dm_ind-total_B.npy"), + ("Disp", "", "delta_dm_disp-total"), + ("ind_A", ".cube", "delta_dm_ind_A.cube"), + ("pol_A", ".cube", "delta_dm_pol_A.cube"), + ("exch-ind_S2_B", ".cube", "delta_dm_exch-ind_S2_B.cube"), + ("total", ".h5", "delta_dm_total.h5"), + ], +) +def test_density_file_name(key, suffix, name): + assert density_file_name(key, suffix) == name + + +def test_density_file_names_are_distinct_on_case_insensitive_file_systems(): + """Every density `calc_densities` returns gets its own file also on macOS and + Windows, which do not tell "Ind" from "ind".""" + + names = density_file_names(sorted(ALL_KEYS), ".cube") + + assert len({name.casefold() for name in names.values()}) == len(ALL_KEYS) + assert names["Ind"] == "delta_dm_ind-total.cube" + assert names["Disp_B"] == "delta_dm_disp-total_B.cube" + + +@pytest.mark.parametrize("keys", [("ind_A", "IND_A"), ("Ind", "ind-total")]) +def test_density_file_names_refuse_names_equal_up_to_case(keys): + with pytest.raises(ValueError, match="names differ only in case"): + density_file_names(keys, ".cube") + + def test_calc_densities_writes_bundle_and_cubes( prepare_dimer, cached_components, tmp_path ): @@ -470,18 +505,24 @@ def test_calc_densities_writes_bundle_and_cubes( np.testing.assert_array_equal(densities.matrices[key], matrix) assert densities.metadata["extra"] == {"project": "test"} + cube_names = density_file_names(rho, ".cube") assert densities.metadata["cubes"] == { - "files": [f"../cubes/delta_dm_{key}.cube" for key in rho], + "files": [f"../cubes/{cube_names[key]}" for key in rho], "density": "total", } cubes = sorted(path.name for path in (tmp_path / "cubes").iterdir()) - assert cubes == sorted(f"delta_dm_{key}.cube" for key in rho) + assert cubes == sorted(cube_names.values()) + assert "delta_dm_ind-total_A.cube" in cubes + assert not any(name.startswith(("delta_dm_Ind", "delta_dm_Disp")) for name in cubes) cube = read_cube_file(str(tmp_path / "cubes" / "delta_dm_pol_A.cube")) assert ( cube.comment1 == "propSAPT delta_dm_pol_A: total density (2 x alpha-spin matrix)" ) + # the comment names the key of the density + cube = read_cube_file(str(tmp_path / "cubes" / "delta_dm_ind-total_A.cube")) + assert cube.comment1.startswith("propSAPT delta_dm_Ind_A:") def test_calc_densities_in_mo_basis_saves_ao_matrices( @@ -518,7 +559,8 @@ def test_calc_densities_in_mo_basis_saves_ao_matrices( ) cubes = sorted(path.name for path in (tmp_path / "cubes").iterdir()) - assert cubes == sorted(f"delta_dm_{key}.cube" for key in rho) + assert cubes == sorted(density_file_names(rho, ".cube").values()) + assert "delta_dm_disp-total_B.cube" in cubes def test_calc_densities_npy_format_is_deprecated( @@ -533,11 +575,15 @@ def test_calc_densities_npy_format_is_deprecated( ) assert sorted(path.name for path in tmp_path.iterdir()) == sorted( - [f"delta_dm_{key}.npy" for key in rho] + ["wfn_mon_A.npy", "wfn_mon_B.npy"] + list(density_file_names(rho, ".npy").values()) + + ["wfn_mon_A.npy", "wfn_mon_B.npy"] ) np.testing.assert_array_equal( np.load(tmp_path / "delta_dm_pol_A.npy"), rho["pol_A"] ) + np.testing.assert_array_equal( + np.load(tmp_path / "delta_dm_ind-total_A.npy"), rho["Ind_A"] + ) @pytest.mark.parametrize(