From 3c689bc3fe9e4d0c8fcfa84e7a252127c9fb6972 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Thu, 19 Nov 2026 18:08:03 +0100 Subject: [PATCH 1/7] the prop_sapt logger and a handler that writes its records into Psi4's output file prop_sapt.log sets up the `prop_sapt` logger: INFO and above, written into Psi4's output file by Psi4OutputHandler, warnings and errors after their level. Module loggers are its children, so the standard logging calls quiet or redirect propSAPT's output. The package imports it first, and a reload keeps one handler. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019ZeFQEY3P12DGTNcvWEyhT --- prop_sapt/__init__.py | 1 + prop_sapt/log.py | 60 +++++++++++++++++++++++++++++++ tests/test_log.py | 83 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 144 insertions(+) create mode 100644 prop_sapt/log.py create mode 100644 tests/test_log.py diff --git a/prop_sapt/__init__.py b/prop_sapt/__init__.py index 42fef6d..9002f78 100644 --- a/prop_sapt/__init__.py +++ b/prop_sapt/__init__.py @@ -1,4 +1,5 @@ from ._version import __version__ +from . import log # the `prop_sapt` logger writes into Psi4's output file from .molecule import Dimer from .properties import calc_property from .densities import calc_density_matrix, calc_densities, DENSITY_COMPONENTS diff --git a/prop_sapt/log.py b/prop_sapt/log.py new file mode 100644 index 0000000..9f02e49 --- /dev/null +++ b/prop_sapt/log.py @@ -0,0 +1,60 @@ +"""The `prop_sapt` logger and the handler that writes its records into Psi4's output +file. + +Every module of the package logs through `logging.getLogger(__name__)`, a child of the +`prop_sapt` logger, and this module is the only one that writes to Psi4's output. By +default the records go to Psi4's output file, like propSAPT's output always has. The +standard `logging` calls quiet or redirect them, e.g. +`logging.getLogger("prop_sapt").setLevel(logging.WARNING)` keeps only the warnings, and +`logging.getLogger("prop_sapt.cpscf_solver")` is the logger of the CPSCF iterations. +""" + +import logging + +import psi4 + +logger = logging.getLogger("prop_sapt") + + +class Psi4OutputFormatter(logging.Formatter): + """The message alone, after its level ("Warning: ...") for warnings and errors.""" + + def format(self, record: logging.LogRecord) -> str: + text = super().format(record) + if record.levelno >= logging.WARNING: + return f"{record.levelname.capitalize()}: {text}" + + return text + + +class Psi4OutputHandler(logging.Handler): + """Writes each log record into Psi4's output file, ended by a newline.""" + + # marks the handler of this module across reloads, which create a new class + _prop_sapt_psi4_output = True + + def __init__(self, level: int = logging.NOTSET): + super().__init__(level) + self.setFormatter(Psi4OutputFormatter()) + + def emit(self, record: logging.LogRecord): + try: + psi4.core.print_out(self.format(record) + "\n") + except Exception: + self.handleError(record) + + +def _install_psi4_output(): + """Sends the `prop_sapt` records to Psi4's output file, once, and logs INFO and above + unless the logger's level was set before the package was imported.""" + + if not any( + getattr(handler, "_prop_sapt_psi4_output", False) for handler in logger.handlers + ): + logger.addHandler(Psi4OutputHandler()) + + if logger.level == logging.NOTSET: + logger.setLevel(logging.INFO) + + +_install_psi4_output() diff --git a/tests/test_log.py b/tests/test_log.py new file mode 100644 index 0000000..d262a5e --- /dev/null +++ b/tests/test_log.py @@ -0,0 +1,83 @@ +"""The `prop_sapt` logger and its handler writing into Psi4's output file.""" + +import importlib +import logging + +import psi4 +import pytest + +import prop_sapt.log + + +@pytest.fixture +def psi4_output(tmp_path): + """Psi4's output file for one test; returns a function reading it. The test session's + `output.dat` is reopened in append mode afterwards, as `conftest.py` opens it.""" + + path = tmp_path / "output.dat" + psi4.core.set_output_file(str(path), False) + + def read() -> str: + psi4.core.flush_outfile() + return path.read_text() + + yield read + + psi4.core.set_output_file("output.dat", True) + + +@pytest.fixture +def prop_sapt_level(): + """Restores the level of the `prop_sapt` logger after a test.""" + + logger = logging.getLogger("prop_sapt") + level = logger.level + yield logger + logger.setLevel(level) + + +def _handlers(): + return [ + handler + for handler in logging.getLogger("prop_sapt").handlers + if getattr(handler, "_prop_sapt_psi4_output", False) + ] + + +def test_module_records_go_to_the_psi4_output_file(psi4_output): + """A record of a module logger lands in Psi4's output file, one line per message.""" + + logging.getLogger("prop_sapt.cpscf_solver").info("solver message") + logging.getLogger("prop_sapt").info("first line\nsecond line") + + assert psi4_output().endswith("solver message\nfirst line\nsecond line\n") + + +def test_warnings_carry_their_level(psi4_output): + logging.getLogger("prop_sapt.checks").warning("not symmetric") + + assert psi4_output().endswith("Warning: not symmetric\n") + + +def test_level_quiets_the_output(psi4_output, prop_sapt_level): + prop_sapt_level.setLevel(logging.WARNING) + logging.getLogger("prop_sapt.densities").info("quiet") + logging.getLogger("prop_sapt.densities").warning("loud") + + text = psi4_output() + assert "quiet" not in text + assert text.endswith("Warning: loud\n") + + +def test_info_is_logged_by_default(): + assert logging.getLogger("prop_sapt").getEffectiveLevel() == logging.INFO + + +def test_reload_keeps_one_handler(psi4_output): + assert len(_handlers()) == 1 + + importlib.reload(prop_sapt.log) + + assert len(_handlers()) == 1 + logging.getLogger("prop_sapt").info("once") + assert psi4_output().count("once") == 1 From 9068020a20b9c4d75cdb90d935a11b1e57120f23 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Thu, 19 Nov 2026 18:11:06 +0100 Subject: [PATCH 2/7] the SAPT core logs through module loggers in place of psi4.core.print_out Dimer and helper_SAPT, the SAPT driver, the densities, the CPSCF solver and batching, S^inf, the checks, the basis overrides and the timers log through logging.getLogger(__name__). Messages have no blank lines around them, and multi-line tables are one record. The warnings of the checks, the CPSCF solver, the deprecations and a missing GRAC shift are WARNING records next to their Python warnings. Modules that no longer use Psi4 stop importing it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019ZeFQEY3P12DGTNcvWEyhT --- prop_sapt/basis_overrides.py | 11 +++-- prop_sapt/checks.py | 9 +++-- prop_sapt/cpscf_batching.py | 12 +++--- prop_sapt/cpscf_solver.py | 20 ++++----- prop_sapt/densities.py | 37 +++++++++-------- prop_sapt/helper_SAPT_DF.py | 78 +++++++++++++++++------------------- prop_sapt/molecule.py | 17 ++++---- prop_sapt/sapt_driver.py | 55 ++++++++++++------------- prop_sapt/sinfinity.py | 10 +++-- prop_sapt/utils.py | 19 +++++---- tests/test_log.py | 34 ++++++++++++++++ 11 files changed, 172 insertions(+), 130 deletions(-) diff --git a/prop_sapt/basis_overrides.py b/prop_sapt/basis_overrides.py index 8f907f9..39c90ad 100644 --- a/prop_sapt/basis_overrides.py +++ b/prop_sapt/basis_overrides.py @@ -17,11 +17,14 @@ """ import json +import logging import os import re from collections.abc import Mapping from pathlib import Path +logger = logging.getLogger(__name__) + # Basis set names that `psi4.basis_helper` can assign to an element. ASSIGNABLE_BASIS_NAME = re.compile(r"^[-+*()\w]+$") @@ -133,8 +136,8 @@ def apply_basis_overrides( option_key = option_keys.get(basis_option) if option_key is None: - psi4.core.print_out( - f"\nBasis overrides: skipping {basis_option}, not used by this calculation.\n" + logger.info( + f"Basis overrides: skipping {basis_option}, not used by this calculation." ) continue @@ -152,8 +155,8 @@ def apply_basis_overrides( applied.append(basis_option) substitutes = ", ".join(f"{el} -> {name}" for el, name in element_map.items()) - psi4.core.print_out( - f"\nBasis overrides: {basis_option} defaults to {default_basis}; {substitutes}.\n" + logger.info( + f"Basis overrides: {basis_option} defaults to {default_basis}; {substitutes}." ) return applied diff --git a/prop_sapt/checks.py b/prop_sapt/checks.py index b67b2b3..390109d 100644 --- a/prop_sapt/checks.py +++ b/prop_sapt/checks.py @@ -2,7 +2,7 @@ Invariant checks: cheap checks of properties that propSAPT results must have. A failed check warns with `InvariantWarning`, attributed to the first caller outside -propSAPT, and writes the same message into the Psi4 output file; it never stops a +propSAPT, and logs the same message as a warning (see `prop_sapt.log`); it never stops a calculation. Turn the warnings into errors with ``warnings.simplefilter("error", InvariantWarning)``. Each check takes its tolerance from a propSAPT option, and setting the option to None turns the check off. @@ -28,6 +28,7 @@ fragment weights are a partition of unity. """ +import logging import os import sys import warnings @@ -43,6 +44,8 @@ ) from .options import PROPSAPT_OPTIONS +logger = logging.getLogger(__name__) + # number of failing matrices listed by index in a closure warning _LISTED_INDICES = 10 # warnings are attributed to the first frame outside this directory @@ -348,7 +351,7 @@ def _tolerance(atol, option_key: str) -> float | None: def _warn(message: str): """Warns `InvariantWarning`, attributed to the first caller outside propSAPT, and - writes `message` into the Psi4 output file.""" + logs `message` as a warning.""" # stack level 1 is this function; count the frames inside the package above it stacklevel = 1 @@ -360,4 +363,4 @@ def _warn(message: str): stacklevel += 1 warnings.warn(message, InvariantWarning, stacklevel=stacklevel) - psi4.core.print_out(f"\nWarning: {message}\n") + logger.warning(message) diff --git a/prop_sapt/cpscf_batching.py b/prop_sapt/cpscf_batching.py index 7e35605..da2ddc4 100644 --- a/prop_sapt/cpscf_batching.py +++ b/prop_sapt/cpscf_batching.py @@ -12,17 +12,19 @@ """ import inspect +import logging import time from collections.abc import Callable, Generator, Mapping from contextlib import AbstractContextManager, nullcontext import numpy as np -import psi4 from .molecule import Dimer from .options import PROPSAPT_OPTIONS from .utils import CalcTimer +logger = logging.getLogger(__name__) + CPSCFRequest = tuple[str, np.ndarray] DensityBuilder = Generator[list[CPSCFRequest], list[np.ndarray], np.ndarray] @@ -44,7 +46,7 @@ def solve_batched( Every builder runs up to its next request. The requests then pending are solved with one `Dimer.cpscf_batch` call per monomer, and the amplitudes are sent back to the builders, which run on to their next requests or finish. The time each builder - takes, without the solves, is printed under its name. The builders run in the + takes, without the solves, is logged under its name. The builders run in the context of `options_cpscf_type`, so all their CPSCF solves, including those of `Dimer.get_cpscf_ra` and `Dimer.get_cpscf_sb`, are of the `cpscf_type` option. @@ -52,7 +54,7 @@ def solve_batched( mol (Dimer): The dimer. builders (Mapping[str, Generator]): Builders keyed by the name of what they calculate, e.g. "Second-order Induction density calculation". - report (bool, optional): Whether to print the timings to the Psi4 output. + report (bool, optional): Whether to log the timings. Defaults to True. Returns: @@ -112,9 +114,7 @@ def advance(name, amplitudes): advance(name, amplitudes[name]) for name, seconds in timings.items() if report else (): - psi4.core.print_out( - f"...{name} took a total of {seconds: .2f} seconds, besides CPSCF.\n" - ) + logger.info(f"...{name} took a total of {seconds: .2f} seconds, besides CPSCF.") return results diff --git a/prop_sapt/cpscf_solver.py b/prop_sapt/cpscf_solver.py index 54129f3..4bcddaa 100644 --- a/prop_sapt/cpscf_solver.py +++ b/prop_sapt/cpscf_solver.py @@ -8,12 +8,14 @@ whole batch. Each vector converges on its own. """ +import logging import time import warnings from collections.abc import Callable, Mapping, Sequence import numpy as np -import psi4 + +logger = logging.getLogger(__name__) HessianProduct = Callable[[list[np.ndarray]], list[np.ndarray]] @@ -33,7 +35,7 @@ def conjugate_gradient( right-hand side, b / `diagonal`: for the CPSCF equations, the uncoupled solution. A vector has converged when its relative residual ||b - H x|| / ||b|| is below `r_convergence`. A zero right-hand side has the solution zero. The progress is - printed to Psi4's output file. + logged by the `prop_sapt.cpscf_solver` logger. Args: rhs (Sequence[np.ndarray]): Right-hand sides b, arrays of the shape of @@ -113,7 +115,7 @@ def conjugate_gradient( active = unconverged _print_row(f"{iteration:d}", residual, len(active), t_start) - psi4.core.print_out(" " + "-" * 56 + "\n") + logger.info(" " + "-" * 56) if active: _warn( @@ -153,24 +155,24 @@ def _products( def _print_header(title: str, count: int, r_convergence: float, maxiter: int): - psi4.core.print_out( - f"\n {title}: preconditioned conjugate gradient\n" + logger.info( + f" {title}: preconditioned conjugate gradient\n" f" Equations = {count:11d}\n" f" Convergence = {r_convergence:11.3e}\n" f" Maxiter = {maxiter:11d}\n\n" f" {'Iter':>5} {'Residual mean':>14} {'Residual max':>13} " f"{'Remaining':>10} {'Time [s]':>9}\n" - " " + "-" * 56 + "\n" + " " + "-" * 56 ) def _print_row(label: str, residual: list[float], remaining: int, t_start: float): - psi4.core.print_out( + logger.info( f" {label:>5} {np.mean(residual):14.3e} {np.max(residual):13.3e} " - f"{remaining:10d} {time.time() - t_start:9.1f}\n" + f"{remaining:10d} {time.time() - t_start:9.1f}" ) def _warn(message: str): - psi4.core.print_out(f"\n Warning: {message}\n") + logger.warning(message) warnings.warn(message, RuntimeWarning, stacklevel=3) diff --git a/prop_sapt/densities.py b/prop_sapt/densities.py index f3e962d..bfbfd69 100644 --- a/prop_sapt/densities.py +++ b/prop_sapt/densities.py @@ -1,3 +1,4 @@ +import logging import os import warnings from collections.abc import Mapping @@ -23,6 +24,8 @@ exch_ind_s2_density_builder, ) +logger = logging.getLogger(__name__) + #: Keys of the density components returned by `calc_density_matrix`, in order; #: `calc_densities` returns them as "_A", "_B" and, in the AO basis, "". DENSITY_COMPONENTS = ( @@ -152,9 +155,9 @@ def calc_densities( rho_ao = rho_dict 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," - "attempting MO -> AO transformation, for saving...\n" + logger.warning( + f"Density matrices are in {orbital_basis} basis, " + "attempting MO -> AO transformation, for saving..." ) rho_ao = { @@ -162,7 +165,7 @@ def calc_densities( for key, rho in rho_dict.items() } - psi4.core.print_out("MO -> AO transformation complete.\n") + logger.info("MO -> AO transformation complete.") # distinct on any file system, checked before anything is written file_names = density_file_names(rho_ao) @@ -175,7 +178,7 @@ def calc_densities( if save_matrices: - psi4.core.print_out("\nSaving density matrices...\n") + logger.info("Saving density matrices...") prepare_path(matrices_dir + "/dummy") # create matrices_dir if it doesn't exist if matrix_format == "npz": @@ -209,9 +212,9 @@ def calc_densities( metadata=bundle_metadata, ) - psi4.core.print_out( + logger.info( f"Density matrices and monomer wavefunctions saved into {bundle}.\n" - "To load use `prop_sapt.load_densities`.\n" + "To load use `prop_sapt.load_densities`." ) else: @@ -223,24 +226,24 @@ def calc_densities( "`prop_sapt.load_densities`." ) warnings.warn(message, FutureWarning, stacklevel=2) - psi4.core.print_out(f"\nWarning: {message}\n") + logger.warning(message) for key, matrix in rho_ao.items(): np.save(f"{matrices_dir}/{file_names[key]}.npy", matrix) - psi4.core.print_out("Density matrices saved.\n") + logger.info("Density matrices saved.") # Save wavefunction information - psi4.core.print_out("\nSaving monomer Wfn objects...\n") + logger.info("Saving monomer Wfn objects...") dimer.wfnA.to_file(f"{matrices_dir}/wfn_mon_A.npy") dimer.wfnB.to_file(f"{matrices_dir}/wfn_mon_B.npy") - psi4.core.print_out( - "Monomer Wfn objects saved. To load use `psi4.core.Wavefunction.from_file`\n" + logger.info( + "Monomer Wfn objects saved. To load use `psi4.core.Wavefunction.from_file`" ) if save_cubes: - psi4.core.print_out("\nSaving density cubes...\n") + logger.info("Saving density cubes...") prepare_path(cubes_dir + "/dummy") # create cubes_dir if it doesn't exist @@ -257,15 +260,15 @@ def calc_densities( ) cube.save(cube_filenames[key]) - psi4.core.print_out("Density cubes saved.\n") + logger.info("Density cubes saved.") if save_trexio: - psi4.core.print_out("\nSaving TREXIO files of the densities...\n") + logger.info("Saving TREXIO files of the densities...") export_trexio(rho_ao, trexio_dir, dimer=dimer) - psi4.core.print_out( + logger.info( "TREXIO files saved: natural orbitals, the density change is the alpha - " - "beta density.\n" + "beta density." ) return rho_dict diff --git a/prop_sapt/helper_SAPT_DF.py b/prop_sapt/helper_SAPT_DF.py index ededbfa..b4c8e5e 100644 --- a/prop_sapt/helper_SAPT_DF.py +++ b/prop_sapt/helper_SAPT_DF.py @@ -49,6 +49,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ +import logging import time from typing import overload, Literal, Any from functools import wraps @@ -60,6 +61,8 @@ from .cpscf_solver import conjugate_gradient from .options import PROPSAPT_OPTIONS, check_cpscf_type, check_df_basis_cpscf +logger = logging.getLogger(__name__) + @overload def psi4_energy(name: str, return_wfn: Literal[False] = False, **kwargs) -> float: ... @@ -136,15 +139,14 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): # Initialize time tinit_start = time.time() - psi4.core.print_out("\nInitializing SAPT object...\n") - psi4.core.print_out( - f""" --------------------------------------------------------- - helper_SAPT_DF - {reference} Reference - --------------------------------------------------------- - """ + logger.info("Initializing SAPT object...") + logger.info( + " ---------------------------------------------------------\n" + " helper_SAPT_DF\n" + f" {reference} Reference\n" + " ---------------------------------------------------------" ) - psi4.core.print_out(f"\nSelected reference is {reference}\n") + logger.info(f"Selected reference is {reference}") # Set a few crucial attributes self.reference = reference.upper() @@ -163,9 +165,9 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): psi4.core.clean() raise ValueError(f"Found {nfrags:d} fragments, must be at least 2.") elif nfrags > 2: - psi4.core.print_out( + logger.info( f"Found {nfrags:d} fragments, using first 2 as monomers, " - "and the rest as extra basis functions (ghosts).\n" + "and the rest as extra basis functions (ghosts)." ) # Grab monomers in DCBS @@ -186,7 +188,7 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): ) # Compute monomer properties - psi4.core.print_out(message_box(f"Monomer A {reference}") + "\n") + logger.info(message_box(f"Monomer A {reference}").strip("\n")) tstart = time.time() if reference == "RHF": self.rhfA, self.wfnA = psi4_energy( @@ -197,9 +199,8 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): if kwargs.get("grac_A"): psi4.set_options({"dft_grac_shift": kwargs["grac_A"]}) else: - psi4.core.print_out( - "\n*** WARNING!: GRAC shift for monomer A not specified! ***\n" - "Running without GRAC.\n" + logger.warning( + "GRAC shift for monomer A not specified; running without GRAC." ) self.dftA, self.wfnA = psi4_energy( dft_functional, return_wfn=True, molecule=monomerA @@ -207,11 +208,11 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): self.V_A = np.asarray( psi4.core.MintsHelper(self.wfnA.basisset()).ao_potential() ) - psi4.core.print_out( - f"\n{reference} for monomer A finished in {time.time() - tstart:.2f} seconds.\n\n" + logger.info( + f"{reference} for monomer A finished in {time.time() - tstart:.2f} seconds." ) - psi4.core.print_out(message_box(f"Monomer B {reference}") + "\n") + logger.info(message_box(f"Monomer B {reference}").strip("\n")) tstart = time.time() if reference == "RHF": self.rhfB, self.wfnB = psi4_energy( @@ -222,9 +223,8 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): if kwargs.get("grac_B"): psi4.set_options({"dft_grac_shift": kwargs["grac_B"]}) else: - psi4.core.print_out( - "\n*** WARNING!: GRAC shift for monomer B not specified! ***\n" - "Running without GRAC.\n" + logger.warning( + "GRAC shift for monomer B not specified; running without GRAC." ) self.dftB, self.wfnB = psi4_energy( dft_functional, return_wfn=True, molecule=monomerB @@ -232,8 +232,8 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): self.V_B = np.asarray( psi4.core.MintsHelper(self.wfnB.basisset()).ao_potential() ) - psi4.core.print_out( - f"\n{reference} for monomer B finished in {time.time() - tstart:.2f} seconds.\n\n" + logger.info( + f"{reference} for monomer B finished in {time.time() - tstart:.2f} seconds." ) # Setup a few variables @@ -360,16 +360,16 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): } ### Number of basis functions - psi4.core.print_out("\nNumber of molecular orbitals per type:\n") - psi4.core.print_out("-" * 38 + "\n") - psi4.core.print_out("".join([f"{dim:>5}" for dim in self.sizes]) + "\n") - psi4.core.print_out("-" * 38 + "\n") - psi4.core.print_out("".join([f"{dim:5d}" for _, dim in self.sizes.items()])) - psi4.core.print_out("\n\n") + rule = "-" * 38 + labels = "".join(f"{name:>5}" for name in self.sizes) + counts = "".join(f"{dim:5d}" for dim in self.sizes.values()) + logger.info( + f"Number of molecular orbitals per type:\n{rule}\n{labels}\n{rule}\n{counts}" + ) ### Compute DF ERIs for dimer basis tstart = time.time() - psi4.core.print_out("\nCompute DF integrals for dimer-centered basis...\n") + logger.info("Compute DF integrals for dimer-centered basis...") self.dimer_wfn = psi4.core.Wavefunction.build( dimer, psi4.core.get_global_option("BASIS") @@ -401,12 +401,10 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): Ppq = np.squeeze(Ppq) self.Qpq = np.array(oe.contract("QP,Ppq->Qpq", metric, Ppq)) - psi4.core.print_out( - f"... DF integrals finished in {time.time() - tstart:.2f} seconds.\n" - ) + logger.info(f"... DF integrals finished in {time.time() - tstart:.2f} seconds.") # JK object - psi4.core.print_out("\nInitialize JK objects...\n") + logger.info("Initialize JK objects...") tstart = time.time() aux_basis = psi4.core.BasisSet.build( self.dimer_wfn.molecule(), @@ -423,9 +421,7 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): self.jk = psi4.core.JK.build(self.dimer_wfn.basisset(), aux_basis) self.jk.set_memory(self.jk_memory) self.jk.initialize() - psi4.core.print_out( - f"\n...initialized JK objects in {time.time() - tstart:.2f} seconds." - ) + logger.info(f"...initialized JK objects in {time.time() - tstart:.2f} seconds.") self.J_A, self.K_A = self.compute_jk(self.Co_A, self.Co_A) self.J_B, self.K_B = self.compute_jk(self.Co_B, self.Co_B) @@ -445,8 +441,8 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): self.S_AB = oe.contract("ui,vj,uv->ij", self.C_A, self.C_B, self.S) hsapt_init_time = time.time() - tinit_start - psi4.core.print_out( - f"\n...finished initializing SAPT object in {hsapt_init_time:5.2f} seconds.\n\n" + logger.info( + f"...finished initializing SAPT object in {hsapt_init_time:5.2f} seconds." ) # Gets transformed DF integrals in MO @@ -733,7 +729,7 @@ def build_cpscf_jk( ) tstart = time.time() - psi4.core.print_out(f"\nInitialize the {cpscf_type} J/K object of CPSCF...\n") + logger.info(f"Initialize the {cpscf_type} J/K object of CPSCF...") jk = psi4.core.JK.build( wfn.basisset(), aux=aux, @@ -750,8 +746,8 @@ def build_cpscf_jk( wfn.set_jk(scf_jk) fitting = f", fitting basis {aux.name()} ({aux.nbf()} functions)" if aux else "" - psi4.core.print_out( - f"...initialized {jk.name()}{fitting} in {time.time() - tstart:.2f} seconds.\n" + logger.info( + f"...initialized {jk.name()}{fitting} in {time.time() - tstart:.2f} seconds." ) return jk diff --git a/prop_sapt/molecule.py b/prop_sapt/molecule.py index 4547af0..45b893b 100644 --- a/prop_sapt/molecule.py +++ b/prop_sapt/molecule.py @@ -2,6 +2,7 @@ Definition of a core Dimer (molecule-like) class. """ +import logging import os import warnings from time import time @@ -24,6 +25,8 @@ ) from .utils import changed_psi4_options +logger = logging.getLogger(__name__) + class Dimer(sinfinity): """ @@ -67,12 +70,12 @@ def __init__(self, geometry, reference="RHF", memory=None, **kwargs): "which the dimer follows by default." ) warnings.warn(message, FutureWarning, stacklevel=2) - psi4.core.print_out(f"\nWarning: {message}\n") + logger.warning(message) # starting initialisation t_start = time() - psi4.core.print_out("*" * 80) - psi4.core.print_out("\nInitializing Dimer object...\n\n") + logger.info("*" * 80) + logger.info("Initializing Dimer object...") psi4.core.tstart() # create Psi4 Molecule object @@ -103,13 +106,11 @@ def __init__(self, geometry, reference="RHF", memory=None, **kwargs): self._theta_cpscf_key: tuple[str, str | None] | None = None # print time - psi4.core.print_out( - f"...finished initializing Dimer object in {(time() - t_start):5.2f} seconds.\n" + logger.info( + f"...finished initializing Dimer object in {(time() - t_start):5.2f} seconds." ) psi4.core.tstop() - psi4.core.print_out("\n") - psi4.core.print_out("*" * 80) - psi4.core.print_out("\n") + logger.info("*" * 80) def get_cpscf_ra(self) -> np.ndarray: """ diff --git a/prop_sapt/sapt_driver.py b/prop_sapt/sapt_driver.py index 45b2373..69d27b3 100644 --- a/prop_sapt/sapt_driver.py +++ b/prop_sapt/sapt_driver.py @@ -3,6 +3,8 @@ This module provides a function to calculate the SAPT energy components for a dimer system. """ +import logging + import psi4 import pandas as pd @@ -18,6 +20,8 @@ calc_disp2_energy, ) +logger = logging.getLogger(__name__) + def print_sapt_summary(results: pd.Series, **kwargs): """Prints a summary of the SAPT energy components. @@ -29,36 +33,31 @@ def print_sapt_summary(results: pd.Series, **kwargs): line_width = 93 # Header - psi4.core.print_out("\n") - psi4.core.print_out(" |------------------------------------| \n") - psi4.core.print_out(" | SAPT Summary Table | \n") - psi4.core.print_out(" |------------------------------------| \n") + logger.info( + " |------------------------------------| \n" + " | SAPT Summary Table | \n" + " |------------------------------------| " + ) # Table header - psi4.core.print_out("\n") - psi4.core.print_out("=" * line_width + "\n") - psi4.core.print_out( - " Term Value (mEh) Value (kcal/mol) Value (kJ/mol)\n" + logger.info( + "=" * line_width + + "\n Term Value (mEh) Value (kcal/mol)" + + " Value (kJ/mol)\n" + + "=" * line_width ) - psi4.core.print_out("=" * line_width + "\n") # Electrostatics - psi4.core.print_out("\n") - psi4.core.print_out("Electrostatics\n") - psi4.core.print_out("-" * line_width + "\n") + logger.info(f"Electrostatics\n{'-' * line_width}") energy_printer("ELST1", results["ELST1"], output="psi4") # Exchange - psi4.core.print_out("\n") - psi4.core.print_out("Exchange\n") - psi4.core.print_out("-" * line_width + "\n") + logger.info(f"Exchange\n{'-' * line_width}") energy_printer("EXCH1", results["EXCH1"], output="psi4") energy_printer("EXCH1(S^2)", results["EXCH1(S^2)"], output="psi4") # Induction - psi4.core.print_out("\n") - psi4.core.print_out("Induction\n") - psi4.core.print_out("-" * line_width + "\n") + logger.info(f"Induction\n{'-' * line_width}") if kwargs.get("response") is True: energy_printer("IND2,R_A", results["IND2,R_A"], output="psi4") energy_printer("IND2,R_B", results["IND2,R_B"], output="psi4") @@ -75,16 +74,13 @@ def print_sapt_summary(results: pd.Series, **kwargs): energy_printer("EXCH-IND2", results["EXCH-IND2"], output="psi4") # Dispersion - psi4.core.print_out("\n") - psi4.core.print_out("Dispersion\n") - psi4.core.print_out("-" * line_width + "\n") + logger.info(f"Dispersion\n{'-' * line_width}") energy_printer("DISP2", results["DISP2"], output="psi4") energy_printer("EXCH-DISP2", results["EXCH-DISP2"], output="psi4") # Total energy - psi4.core.print_out("\n") energy_printer("TOTAL", results["TOTAL"], output="psi4") - psi4.core.print_out("=" * line_width + "\n") + logger.info("=" * line_width) @trace_memory_peak @@ -123,13 +119,12 @@ def calc_sapt_energy(dimer: Dimer, **kwargs) -> pd.Series: """ # Print header - psi4.core.print_out("\n") - psi4.core.print_out("*" * 80) - psi4.core.print_out("\n\n") - psi4.core.print_out(" |-------------------------------------| \n") - psi4.core.print_out(" | Second-Quantized SAPT | \n") - psi4.core.print_out(" |-------------------------------------| \n") - psi4.core.print_out("\n") + logger.info("*" * 80) + logger.info( + " |-------------------------------------| \n" + " | Second-Quantized SAPT | \n" + " |-------------------------------------| " + ) psi4.core.tstart() with CalcTimer("SAPT energy calculations"): diff --git a/prop_sapt/sinfinity.py b/prop_sapt/sinfinity.py index 43a47f3..e94326a 100644 --- a/prop_sapt/sinfinity.py +++ b/prop_sapt/sinfinity.py @@ -2,12 +2,14 @@ Second-quantized SAPT S^infinity """ +import logging from time import time -import psi4 import numpy as np import opt_einsum as oe from .helper_SAPT_DF import helper_SAPT +logger = logging.getLogger(__name__) + def get_A_bb(s_ba, s_ab): gamma_bb = oe.contract("Ba,ab->Bb", s_ba, s_ab) @@ -41,7 +43,7 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): super().__init__(dimer, reference, memory, **kwargs) ### Starting initialisation - psi4.core.print_out("\nInitializing Sinfinity object...\n") + logger.info("Initializing Sinfinity object...") t_start = time() ### Matrices and tensors from helper_sapt @@ -236,6 +238,6 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): self.tA_sb = self.omegaA_bs.T * self.eps_sb ### Print time - psi4.core.print_out( - f"...finished initializing Sinfinity object in {(time() - t_start):5.2f} seconds.\n\n" + logger.info( + f"...finished initializing Sinfinity object in {(time() - t_start):5.2f} seconds." ) diff --git a/prop_sapt/utils.py b/prop_sapt/utils.py index 16e3779..440e68b 100644 --- a/prop_sapt/utils.py +++ b/prop_sapt/utils.py @@ -1,10 +1,12 @@ +import logging import os import time from functools import wraps from collections.abc import Callable from importlib import metadata import tracemalloc -import psi4 + +logger = logging.getLogger(__name__) def trace_memory_peak(func: Callable): @@ -22,8 +24,8 @@ def wrapper(*args, **kwargs): result = func(*args, **kwargs) _, peak_size = tracemalloc.get_traced_memory() - psi4.core.print_out(f"\nFunction: {func}\n") - psi4.core.print_out(f"...peak memory usage: {peak_size*1e-6:.2f} MB\n\n") + logger.info(f"Function: {func}") + logger.info(f"...peak memory usage: {peak_size*1e-6:.2f} MB") tracemalloc.reset_peak() tracemalloc.stop() @@ -102,17 +104,17 @@ def __enter__(self): """ self.start = time.time() - psi4.core.print_out(f"\nStarting {self.name}...\n") + logger.info(f"Starting {self.name}...") return self def __exit__(self, *args): """ - Stops the timer. And prints out the time taken for the operation into the output file. + Stops the timer and logs the time taken for the operation. """ t = time.time() - self.start - psi4.core.print_out(f"...{self.name} took a total of {t: .2f} seconds.\n") + logger.info(f"...{self.name} took a total of {t: .2f} seconds.") def energy_printer(name: str, value: float, output: str = "psi4", **kwargs): @@ -121,7 +123,8 @@ def energy_printer(name: str, value: float, output: str = "psi4", **kwargs): Args: name (str): Name of the energy term. value (float): Value of the energy term in Hartree. - output (str, optional): Output method. Defaults to "psi4" - Psi4's output file. + output (str, optional): Output method. Defaults to "psi4": the propSAPT log, + which goes into Psi4's output file (see `prop_sapt.log`). Raises: ValueError: If an unknown output type is provided. @@ -136,7 +139,7 @@ def energy_printer(name: str, value: float, output: str = "psi4", **kwargs): ) if output == "psi4": - psi4.core.print_out(energy_output_string + "\n") + logger.info(energy_output_string) elif output == "stdout": print(energy_output_string) diff --git a/tests/test_log.py b/tests/test_log.py index d262a5e..b65bc29 100644 --- a/tests/test_log.py +++ b/tests/test_log.py @@ -8,6 +8,8 @@ import prop_sapt.log +from .test_cpscf_solver import DenseHessian, right_hand_sides, solve + @pytest.fixture def psi4_output(tmp_path): @@ -81,3 +83,35 @@ def test_reload_keeps_one_handler(psi4_output): assert len(_handlers()) == 1 logging.getLogger("prop_sapt").info("once") assert psi4_output().count("once") == 1 + + +def _solver_records(caplog): + return [ + record for record in caplog.records if record.name == "prop_sapt.cpscf_solver" + ] + + +def test_cpscf_progress_is_logged(caplog): + """The CPSCF table is made of INFO records of the `prop_sapt.cpscf_solver` logger, + which reach `caplog` by propagation, each without blank lines around it.""" + + with caplog.at_level(logging.INFO, logger="prop_sapt"): + solve(DenseHessian(), right_hand_sides(2)) + + records = _solver_records(caplog) + messages = [record.getMessage() for record in records] + assert "CPSCF: preconditioned conjugate gradient" in messages[0] + assert {record.levelno for record in records} == {logging.INFO} + assert not [m for m in messages if m.startswith("\n") or m.endswith("\n")] + + +def test_unconverged_solve_logs_a_warning(caplog): + with ( + pytest.warns(RuntimeWarning), + caplog.at_level(logging.INFO, logger="prop_sapt"), + ): + solve(DenseHessian(), right_hand_sides(2), maxiter=2) + + warned = [r for r in _solver_records(caplog) if r.levelno == logging.WARNING] + assert len(warned) == 1 + assert "did not converge" in warned[0].getMessage() From b40732c0d25c59436ef2030f24efa68892f52946 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Thu, 19 Nov 2026 18:11:50 +0100 Subject: [PATCH 3/7] make_cube and the finite-field calculations log through module loggers The cube setup, timings and isocontours and the finite-field banners and steps are INFO records. The progress of make_cube over the x-slices, a line rewritten with \r in Psi4's output file, is a DEBUG record per slice. A test checks that only prop_sapt.log writes into Psi4's output file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019ZeFQEY3P12DGTNcvWEyhT --- prop_sapt/cubes.py | 52 ++++++++++++++++----------------- prop_sapt/finite_field/core.py | 19 ++++++------ prop_sapt/finite_field/utils.py | 30 ++++++++++--------- tests/test_log.py | 21 +++++++++++++ 4 files changed, 72 insertions(+), 50 deletions(-) diff --git a/prop_sapt/cubes.py b/prop_sapt/cubes.py index c80ff40..fdddb56 100644 --- a/prop_sapt/cubes.py +++ b/prop_sapt/cubes.py @@ -5,6 +5,7 @@ https://paulbourke.net/dataformats/cube/ """ +import logging import numbers import os from dataclasses import dataclass @@ -23,6 +24,8 @@ _stack_matrices, ) +logger = logging.getLogger(__name__) + @dataclass(kw_only=True, eq=False, repr=False) class Cube: @@ -442,13 +445,12 @@ def make_cube( # initialize t_start = time() - psi4.core.print_out("\n") - psi4.core.print_out("*" * 80) - psi4.core.print_out("\n\n") - psi4.core.print_out(" |------------------------------------| \n") - psi4.core.print_out(" | `make_cube` | \n") - psi4.core.print_out(" |------------------------------------| \n") - psi4.core.print_out("\n") + logger.info("*" * 80) + logger.info( + " |------------------------------------| \n" + " | `make_cube` | \n" + " |------------------------------------| " + ) psi4.core.tstart() # get basis set and geometry @@ -479,26 +481,25 @@ def make_cube( grid = prepare_grid(geo_matrix, grid_step, grid_overage) n_points = grid["n_x"] * grid["n_y"] * grid["n_z"] - psi4.core.print_out( + logger.info( f" Grid size : {grid['n_x']} x {grid['n_y']} x {grid['n_z']}" - f" ({n_points} points)\n" + f" ({n_points} points)" ) - psi4.core.print_out( + logger.info( f" Grid step : {grid['step_x']:.4f} x {grid['step_y']:.4f}" - f" x {grid['step_z']:.4f} bohr\n" + f" x {grid['step_z']:.4f} bohr" ) n_density = sum(1 for t in obj_type if t == "density") n_orbital = sum(1 for t in obj_type if t == "orbital") n_esp = sum(1 for t in obj_type if t == "esp") - psi4.core.print_out( + logger.info( f" Matrices : {len(matrix)}" - f" ({n_density} density, {n_orbital} orbital, {n_esp} esp)\n" + f" ({n_density} density, {n_orbital} orbital, {n_esp} esp)" ) esp_nuclei = kwargs.get("esp_nuclei", False) if n_esp > 0: - psi4.core.print_out(f" ESP nuclei : {'yes' if esp_nuclei else 'no'}\n") - psi4.core.print_out(f" Setup time : {(time() - t_setup):5.2f} s\n") - psi4.core.print_out("\n") + logger.info(f" ESP nuclei : {'yes' if esp_nuclei else 'no'}") + logger.info(f" Setup time : {(time() - t_setup):5.2f} s") # compute values on the grid one x-slice at a time values = np.zeros((len(matrix), grid["n_x"], grid["n_y"], grid["n_z"])) @@ -573,8 +574,8 @@ def make_cube( values[orbital_idx_arr, i] = orbitals.reshape(slice_shape) # progress report every x-slice - psi4.core.print_out( - f"\r Grid progress : x-slice {i + 1:4d} / {grid['n_x']:4d}" + logger.debug( + f" Grid progress : x-slice {i + 1:4d} / {grid['n_x']:4d}" f" (phi: {timings['phi']:6.2f} s, contract: {timings['contract']:6.2f} s," f" esp: {t_esp:6.2f} s, elapsed: {(time() - t_grid):6.2f} s)" ) @@ -583,13 +584,13 @@ def make_cube( t_phi = timings["phi"] t_contract = timings["contract"] t_overhead = t_grid_total - t_phi - t_contract - t_esp - psi4.core.print_out( - f"\n\n Grid evaluation : {t_grid_total:5.2f} s total\n" + logger.info( + f" Grid evaluation : {t_grid_total:5.2f} s total\n" f" basis values : {t_phi:5.2f} s ({100 * t_phi / t_grid_total:.1f}%)\n" f" contractions : {t_contract:5.2f} s ({100 * t_contract / t_grid_total:.1f}%)\n" f" esp integrals : {t_esp:5.2f} s ({100 * t_esp / t_grid_total:.1f}%)\n" f" overhead : {t_overhead:5.2f} s" - f" ({100 * t_overhead / t_grid_total:.1f}%)\n" + f" ({100 * t_overhead / t_grid_total:.1f}%)" ) # get isocontour values @@ -632,12 +633,9 @@ def make_cube( cubes_list.append(Cube(**cube_dict)) # finalize - psi4.core.print_out("\n") - psi4.core.print_out(f"...finished in {(time() - t_start):5.2f} s total.\n") + logger.info(f"...finished in {(time() - t_start):5.2f} s total.") psi4.core.tstop() - psi4.core.print_out("\n") - psi4.core.print_out("*" * 80) - psi4.core.print_out("\n\n") + logger.info("*" * 80) if len(cubes_list) == 1: return cubes_list[0] @@ -1090,6 +1088,6 @@ def calculate_isocontour( negative_isoval = flatened_vals[i] do_negative = False - psi4.core.print_out(f" Isocontour : {(time() - t_iso):5.2f} s\n") + logger.info(f" Isocontour : {(time() - t_iso):5.2f} s") return (positive_isoval, negative_isoval) # pyright: ignore reportReturnType diff --git a/prop_sapt/finite_field/core.py b/prop_sapt/finite_field/core.py index 6d2dd42..d7807dc 100644 --- a/prop_sapt/finite_field/core.py +++ b/prop_sapt/finite_field/core.py @@ -2,6 +2,7 @@ Finite field property calculations and finite field SAPT. """ +import logging from typing import Dict, Optional, cast import numpy as np @@ -21,6 +22,8 @@ from ..options import PROPSAPT_OPTIONS +logger = logging.getLogger(__name__) + def validate_property(prop: str | np.ndarray) -> None: """Validate that the requested property is supported. @@ -165,8 +168,8 @@ def calculate_ff_dipole_along_axis( if cp_correction: psi4_energy_kwargs["bsse_type"] = "cp" - psi4.core.print_out( - f"\nCalculating finite field dipole moment along {axis}-axis with field strength {field_strength:.6f} a.u.\n" + logger.info( + f"Calculating finite field dipole moment along {axis}-axis with field strength {field_strength:.6f} a.u." ) # Build energies dict using helper utilities @@ -213,9 +216,7 @@ def calculate_ff_dipole_along_axis( cast(float, dipole_moment), method.upper(), energies, formula, field_strength ) - psi4.core.print_out( - f"Finite field dipole moment calculation along {axis}-axis completed.\n" - ) + logger.info(f"Finite field dipole moment calculation along {axis}-axis completed.") return results @@ -341,8 +342,8 @@ def calculate_ff_sapt_dipole_along_axis( psi4.core.clean() raise ValueError(f"Unknown finite difference formula: {formula}") - psi4.core.print_out( - f"\nCalculating finite field SAPT dipole moment along {axis}-axis with field strength {field_strength:.6f} a.u.\n" + logger.info( + f"Calculating finite field SAPT dipole moment along {axis}-axis with field strength {field_strength:.6f} a.u." ) # Prepare dimer kwargs @@ -400,8 +401,8 @@ def calculate_ff_sapt_dipole_along_axis( ### Calculate the finite field difference data = apply_finite_difference_formula(sapt_energies, formula, field_strength) - psi4.core.print_out( - f"Finite field SAPT dipole moment calculation along {axis}-axis completed.\n" + logger.info( + f"Finite field SAPT dipole moment calculation along {axis}-axis completed." ) return cast(pd.Series, data) diff --git a/prop_sapt/finite_field/utils.py b/prop_sapt/finite_field/utils.py index e3435d4..1409b70 100644 --- a/prop_sapt/finite_field/utils.py +++ b/prop_sapt/finite_field/utils.py @@ -2,6 +2,7 @@ Utilities for finite field property calculations and finite field SAPT. """ +import logging from typing import Dict, Callable, Optional import psi4 @@ -12,6 +13,8 @@ from ..molecule import Dimer from ..sapt_driver import calc_sapt_energy +logger = logging.getLogger(__name__) + def get_field_vector(axis: str, magnitude: float) -> list: """Generate a field vector for a given axis and magnitude. @@ -70,8 +73,8 @@ def calculate_perturbed_energy( } ) - psi4.core.print_out( - f"Computing energy with {sign} field ({magnitude:.6f}) along {axis}-axis...\n" + logger.info( + f"Computing energy with {sign} field ({magnitude:.6f}) along {axis}-axis..." ) energy = psi4.energy(method, molecule=molecule, **energy_kwargs) @@ -123,8 +126,8 @@ def calculate_perturbed_sapt_energies( } ) - psi4.core.print_out( - f"Computing SAPT energy with {sign} field ({magnitude:.6f}) along {axis}-axis...\n" + logger.info( + f"Computing SAPT energy with {sign} field ({magnitude:.6f}) along {axis}-axis..." ) dimer = Dimer( @@ -174,7 +177,7 @@ def apply_finite_difference_formula( "two_point formula requires 'plus_h' and 'minus_h' energies" ) - psi4.core.print_out("Using two-point finite difference formula.\n") + logger.info("Using two-point finite difference formula.") derivative = (energies["plus_h"] - energies["minus_h"]) / (2 * field_strength) elif formula == "four_point": @@ -182,7 +185,7 @@ def apply_finite_difference_formula( if not all(key in energies for key in required_keys): raise ValueError(f"four_point formula requires all of: {required_keys}") - psi4.core.print_out("Using four-point finite difference formula.\n") + logger.info("Using four-point finite difference formula.") derivative = ( -energies["plus_2h"] + 8 * energies["plus_h"] @@ -234,24 +237,23 @@ def build_result_series( def print_finite_field_banner(title: str, details: Dict[str, str | float]) -> None: - """Print a formatted banner with title and details for finite field calculations. + """Log a formatted banner with title and details for finite field calculations. Args: title (str): Title to display in the banner (e.g., "FINITE FIELD PROPERTY CALCULATIONS"). details (Dict[str, str | float]): Dictionary of detail key-value pairs to display. Keys will be formatted as " Key: value". """ - psi4.core.print_out("\n" + "=" * 70 + "\n") - psi4.core.print_out(f" {title}\n") - psi4.core.print_out("=" * 70 + "\n") - + rule = "=" * 70 + lines = [rule, f" {title}", rule] for key, value in details.items(): if isinstance(value, float): - psi4.core.print_out(f" {key}: {value:.6f} a.u.\n") + lines.append(f" {key}: {value:.6f} a.u.") else: - psi4.core.print_out(f" {key}: {value}\n") + lines.append(f" {key}: {value}") + lines.append(rule) - psi4.core.print_out("=" * 70 + "\n") + logger.info("\n".join(lines)) def apply_to_cartesian_axes( diff --git a/tests/test_log.py b/tests/test_log.py index b65bc29..70a4d28 100644 --- a/tests/test_log.py +++ b/tests/test_log.py @@ -2,6 +2,7 @@ import importlib import logging +from pathlib import Path import psi4 import pytest @@ -115,3 +116,23 @@ def test_unconverged_solve_logs_a_warning(caplog): warned = [r for r in _solver_records(caplog) if r.levelno == logging.WARNING] assert len(warned) == 1 assert "did not converge" in warned[0].getMessage() + + +def _calls(pattern: str) -> list[str]: + """The `path:line` of every line of the package's modules containing `pattern`.""" + + root = Path(prop_sapt.log.__file__).parent + found = [] + for path in sorted(root.rglob("*.py")): + for number, line in enumerate(path.read_text().splitlines(), start=1): + if pattern in line: + found.append(f"{path.relative_to(root).as_posix()}:{number}") + return found + + +def test_only_the_log_module_writes_to_psi4_output(): + """The modules log, and only `prop_sapt.log` writes into Psi4's output file, so a + backend other than Psi4 needs only another handler.""" + + calls = _calls("psi4.core.print_out(") + assert [call.split(":")[0] for call in calls] == ["log.py"] From 1c93ba88f1751cd4a677ecdbc15183d7205ad7f4 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Thu, 19 Nov 2026 18:12:17 +0100 Subject: [PATCH 4/7] Psi4's scratch files are cleaned at the end of jobs, not before raising The 36 psi4.core.clean() calls before a raise go: Psi4 cleans its scratch files at exit and between jobs, which calc_sapt_energy, calc_property and the runner still do. calc_property checks the response without a try/except, and the densities module no longer imports Psi4. A test checks that clean is called only at the ends of jobs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019ZeFQEY3P12DGTNcvWEyhT --- prop_sapt/densities.py | 7 ------- prop_sapt/finite_field/core.py | 4 ---- prop_sapt/helper_SAPT_DF.py | 22 ---------------------- prop_sapt/molecule.py | 1 - prop_sapt/properties.py | 7 +------ prop_sapt/sapt_driver.py | 1 - tests/test_log.py | 7 +++++++ 7 files changed, 8 insertions(+), 41 deletions(-) diff --git a/prop_sapt/densities.py b/prop_sapt/densities.py index bfbfd69..462def8 100644 --- a/prop_sapt/densities.py +++ b/prop_sapt/densities.py @@ -3,7 +3,6 @@ import warnings from collections.abc import Mapping from pathlib import Path -import psi4 import numpy as np import opt_einsum as oe from .molecule import Dimer @@ -66,7 +65,6 @@ def density_mo_to_ao( elif monomer == "B": return dimer.C_B.dot(density_matrix).dot(dimer.C_B.T) else: - psi4.core.clean() raise ValueError(f"Invalid monomer: {monomer}") @@ -280,7 +278,6 @@ def _resolve_matrix_format(matrix_format: str | None, compress_matrices) -> str: if compress_matrices is not None: if matrix_format is not None: - psi4.core.clean() raise TypeError( "`compress_matrices` is deprecated, use `matrix_format` alone!" ) @@ -299,7 +296,6 @@ def _resolve_matrix_format(matrix_format: str | None, compress_matrices) -> str: not isinstance(matrix_format, str) or matrix_format.lower() not in MATRIX_FORMATS ): - psi4.core.clean() raise ValueError( f"`matrix_format` should be one of {MATRIX_FORMATS}, was {matrix_format!r}!" ) @@ -707,12 +703,10 @@ def calc_density_matrix( """ if monomer not in ["A", "B"]: - psi4.core.clean() raise ValueError(f"'{monomer}' is not a valid monomer for density matrix.") orbital_basis = orbital_basis.upper() if orbital_basis not in ["MO", "AO"]: - psi4.core.clean() raise ValueError( f"Argument 'orbital_basis' should be either 'MO' or 'AO' but was '{orbital_basis}'!" ) @@ -804,7 +798,6 @@ def calc_density_matrix( else: - psi4.core.clean() raise ValueError( f"Argument 'orbital_basis' should be either 'MO' or 'AO' but was '{orbital_basis}'!" ) diff --git a/prop_sapt/finite_field/core.py b/prop_sapt/finite_field/core.py index d7807dc..7494429 100644 --- a/prop_sapt/finite_field/core.py +++ b/prop_sapt/finite_field/core.py @@ -35,11 +35,9 @@ def validate_property(prop: str | np.ndarray) -> None: ValueError: If the property is not supported. """ if isinstance(prop, np.ndarray): - psi4.core.clean() raise ValueError("Property for general external operator is not implemented.") if prop != "dipole": - psi4.core.clean() raise ValueError( f"Property {prop} is not implemented. " "Please provide a valid property name or a property matrix." @@ -160,7 +158,6 @@ def calculate_ff_dipole_along_axis( # Validate formula if formula not in ["two_point", "four_point"]: - psi4.core.clean() raise ValueError(f"Unknown finite difference formula: {formula}") molecule = psi4.geometry(geometry) @@ -339,7 +336,6 @@ def calculate_ff_sapt_dipole_along_axis( # Validate formula if formula not in ["two_point", "four_point"]: - psi4.core.clean() raise ValueError(f"Unknown finite difference formula: {formula}") logger.info( diff --git a/prop_sapt/helper_SAPT_DF.py b/prop_sapt/helper_SAPT_DF.py index b4c8e5e..32fd7c1 100644 --- a/prop_sapt/helper_SAPT_DF.py +++ b/prop_sapt/helper_SAPT_DF.py @@ -117,19 +117,16 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): # propSAPT is all-electron: reject frozen core instead of ignoring it if psi4.core.get_global_option("FREEZE_CORE") not in ("FALSE", "0"): - psi4.core.clean() raise ValueError( "propSAPT does not support frozen core; set FREEZE_CORE to false." ) # Verify reference if reference not in ["RHF", "ROHF", "UHF", "RKS", "UKS"]: - psi4.core.clean() raise ValueError(f"Unsupported reference type '{reference}'.") if reference in ["ROHF", "UHF", "UKS"]: # NOTE: Future upgrades - psi4.core.clean() raise ValueError(f"Reference '{reference}' not implemented yet.") # Check if the functional is specified for DFT @@ -162,7 +159,6 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): nfrags = dimer.nfragments() if nfrags < 2: - psi4.core.clean() raise ValueError(f"Found {nfrags:d} fragments, must be at least 2.") elif nfrags > 2: logger.info( @@ -181,7 +177,6 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): # closed-shell references only, fail before any SCF is run for label, mult in (("A", self.mult_A), ("B", self.mult_B)): if mult != 1: - psi4.core.clean() raise ValueError( f"Monomer {label} has multiplicity {mult}, " f"{reference} reference requires singlet monomers." @@ -253,7 +248,6 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): occA = self.ndocc_A + self.nsocc_A elif reference == "UHF" or reference == "UKS": - psi4.core.clean() raise NotImplementedError(f"Reference {reference} not implemented yet.") elif reference == "RHF" or reference == "RKS": @@ -262,7 +256,6 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): occA = self.ndocc_A else: - psi4.core.clean() raise ValueError(f"Unknown reference type: {reference}.") self.C_A = np.asarray(self.wfnA.Ca()) @@ -282,7 +275,6 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): occB = self.ndocc_B + self.nsocc_B elif reference == "UHF" or reference == "UKS": - psi4.core.clean() raise NotImplementedError(f"Reference {reference} not implemented yet.") elif reference == "RHF" or reference == "RKS": @@ -291,7 +283,6 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): occB = self.ndocc_B else: - psi4.core.clean() raise ValueError(f"Unknown reference type: {reference}.") self.C_B = np.asarray(self.wfnB.Ca()) @@ -448,7 +439,6 @@ def __init__(self, dimer, reference="RHF", memory=None, **kwargs): # Gets transformed DF integrals in MO def df_ints(self, string): if len(string) != 2: - psi4.core.clean() raise ValueError(f"S: string {string} does not have 2 elements.") return np.array( @@ -463,7 +453,6 @@ def df_ints(self, string): # Grab MO overlap matrices def s(self, string): if len(string) != 2: - psi4.core.clean() raise ValueError(f"S: string {string} does not have 2 elements.") # Compute on the fly, an empty orbital block gives a correctly shaped empty array @@ -472,7 +461,6 @@ def s(self, string): # Grab epsilons, reshape if requested def eps(self, string, dim=1): if len(string) != 1: - psi4.core.clean() raise ValueError(f"Epsilon: string {string} does not have 1 element.") shape = (-1,) + tuple([1] * (dim - 1)) @@ -482,13 +470,11 @@ def eps(self, string, dim=1): elif (string == "j") or (string == "b") or (string == "s"): return self.eps_B[self.slices[string]].reshape(shape) else: - psi4.core.clean() raise ValueError(f"Unknown orbital type in eps: {string}.") # Grab MO potential matrices def potential(self, string, side): if len(string) != 2: - psi4.core.clean() raise ValueError(f"Potential: string {string} does not have 2 elements.") # Two separate cases @@ -504,7 +490,6 @@ def potential(self, string, side): (self.orbitals[string[0]].T).dot(self.V_B).dot(self.orbitals[string[1]]) ) else: - psi4.core.clean() raise ValueError( f"helper_SAPT.potential side must be either A or B, not {side}." ) @@ -756,15 +741,12 @@ def _check_cpscf(self, monomer): """Raises ValueError unless CPSCF is implemented for this reference and `monomer`.""" if self.reference in ["ROHF", "UHF", "UKS"]: - psi4.core.clean() raise ValueError( f"CPSCF solver for a {self.reference} reference not implemented yet." ) if self.reference not in ["RHF", "RKS"]: - psi4.core.clean() raise ValueError(f"Unknown reference type: {self.reference}.") if monomer not in ["A", "B"]: - psi4.core.clean() raise ValueError(f"'{monomer}' is not a valid monomer for CPSCF.") def chain_dot(self, *dot_list): @@ -781,7 +763,6 @@ def transform_ao_to_mo(self, x, string): """ if len(string) != 2: - psi4.core.clean() raise ValueError(f"S: string {string} does not have 2 elements.") return self.orbitals[string[0]].T.dot(x).dot(self.orbitals[string[1]]) @@ -789,7 +770,6 @@ def transform_ao_to_mo(self, x, string): def compute_jk(self, Cleft, Cright, tensor=None): if self.reference == "ROHF": - psi4.core.clean() raise NotImplementedError( "JK generation not yet implemented for ROHF reference." ) @@ -806,7 +786,6 @@ def compute_jk(self, Cleft, Cright, tensor=None): return_single = True if len(Cleft) != len(Cright): - psi4.core.clean() raise ValueError("Cleft list is not the same length as Cright list") zero_append = [] @@ -822,7 +801,6 @@ def compute_jk(self, Cleft, Cright, tensor=None): mor = Cr.shape[1] if (tensor[num].shape[0] != mol) or (tensor[num].shape[1] != mor): - psi4.core.clean() raise ValueError( f"compute_sapt_JK: Tensor size does not match Cl ({mol}) " f"/Cr ({mor}) : {tensor[num].shape}" diff --git a/prop_sapt/molecule.py b/prop_sapt/molecule.py index 45b893b..51486f1 100644 --- a/prop_sapt/molecule.py +++ b/prop_sapt/molecule.py @@ -550,7 +550,6 @@ def save_cube( # check before the grid evaluation, which is the expensive part if len(filename) != len(matrix): - psi4.core.clean() raise ValueError( f"One filename per matrix is required, got {len(matrix)} matrices " f"and {len(filename)} filenames." diff --git a/prop_sapt/properties.py b/prop_sapt/properties.py index ae6dbc4..65dfb12 100644 --- a/prop_sapt/properties.py +++ b/prop_sapt/properties.py @@ -755,11 +755,7 @@ def calc_property( pd.DataFrame: DataFrame with results. """ - try: - _check_response(response) - except ValueError: - psi4.core.clean() - raise + _check_response(response) with CalcTimer("Interaction-induced property calculations"): ### Results output file @@ -775,7 +771,6 @@ def calc_property( results = calc_induced_dipole(dimer, response=response) else: - psi4.core.clean() raise ValueError( f"Property {prop} is not implemented. " "Please provide a valid property name or a property matrix." diff --git a/prop_sapt/sapt_driver.py b/prop_sapt/sapt_driver.py index 69d27b3..f83227e 100644 --- a/prop_sapt/sapt_driver.py +++ b/prop_sapt/sapt_driver.py @@ -156,7 +156,6 @@ def calc_sapt_energy(dimer: Dimer, **kwargs) -> pd.Series: ) else: - psi4.core.clean() raise ValueError( "Invalid value for 'response'. Must be True, False or 'both'." ) diff --git a/tests/test_log.py b/tests/test_log.py index 70a4d28..18f4bdb 100644 --- a/tests/test_log.py +++ b/tests/test_log.py @@ -136,3 +136,10 @@ def test_only_the_log_module_writes_to_psi4_output(): calls = _calls("psi4.core.print_out(") assert [call.split(":")[0] for call in calls] == ["log.py"] + + +def test_psi4_scratch_cleaned_only_at_the_end_of_jobs(): + """Psi4's scratch files are cleaned between jobs, not before raising an error.""" + + files = [call.split(":")[0] for call in _calls("psi4.core.clean()")] + assert files == ["properties.py", "runner.py", "sapt_driver.py"] From a7d2061eef7a184280a35622e6f87622ba8657e3 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Thu, 19 Nov 2026 18:14:25 +0100 Subject: [PATCH 5/7] the SAPT summary table is one log record, with its blank lines between sections print_sapt_summary builds the table from format_energy, the line energy_printer writes, and logs it at once, so the table keeps the layout it had in Psi4's output file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019ZeFQEY3P12DGTNcvWEyhT --- prop_sapt/sapt_driver.py | 84 +++++++++++++++++----------------------- prop_sapt/utils.py | 23 ++++++++--- 2 files changed, 52 insertions(+), 55 deletions(-) diff --git a/prop_sapt/sapt_driver.py b/prop_sapt/sapt_driver.py index f83227e..c7408d6 100644 --- a/prop_sapt/sapt_driver.py +++ b/prop_sapt/sapt_driver.py @@ -9,7 +9,7 @@ import pandas as pd from .molecule import Dimer -from .utils import trace_memory_peak, CalcTimer, energy_printer +from .utils import trace_memory_peak, CalcTimer, format_energy from .sapt_components import ( calc_elst1_energy, @@ -24,7 +24,7 @@ def print_sapt_summary(results: pd.Series, **kwargs): - """Prints a summary of the SAPT energy components. + """Logs a summary table of the SAPT energy components. Args: results (pd.Series): A pandas Series containing the SAPT energy components. @@ -32,55 +32,41 @@ def print_sapt_summary(results: pd.Series, **kwargs): line_width = 93 - # Header - logger.info( - " |------------------------------------| \n" - " | SAPT Summary Table | \n" - " |------------------------------------| " - ) - - # Table header - logger.info( - "=" * line_width - + "\n Term Value (mEh) Value (kcal/mol)" - + " Value (kJ/mol)\n" - + "=" * line_width - ) - - # Electrostatics - logger.info(f"Electrostatics\n{'-' * line_width}") - energy_printer("ELST1", results["ELST1"], output="psi4") - - # Exchange - logger.info(f"Exchange\n{'-' * line_width}") - energy_printer("EXCH1", results["EXCH1"], output="psi4") - energy_printer("EXCH1(S^2)", results["EXCH1(S^2)"], output="psi4") - - # Induction - logger.info(f"Induction\n{'-' * line_width}") if kwargs.get("response") is True: - energy_printer("IND2,R_A", results["IND2,R_A"], output="psi4") - energy_printer("IND2,R_B", results["IND2,R_B"], output="psi4") - energy_printer("IND2,R", results["IND2,R"], output="psi4") - energy_printer("EXCH-IND2,R_A", results["EXCH-IND2,R_A"], output="psi4") - energy_printer("EXCH-IND2,R_B", results["EXCH-IND2,R_B"], output="psi4") - energy_printer("EXCH-IND2,R", results["EXCH-IND2,R"], output="psi4") + induction = ["IND2,R_A", "IND2,R_B", "IND2,R"] + induction += ["EXCH-IND2,R_A", "EXCH-IND2,R_B", "EXCH-IND2,R"] else: - energy_printer("IND2_A", results["IND2_A"], output="psi4") - energy_printer("IND2_B", results["IND2_B"], output="psi4") - energy_printer("IND2", results["IND2"], output="psi4") - energy_printer("EXCH-IND2_A", results["EXCH-IND2_A"], output="psi4") - energy_printer("EXCH-IND2_B", results["EXCH-IND2_B"], output="psi4") - energy_printer("EXCH-IND2", results["EXCH-IND2"], output="psi4") - - # Dispersion - logger.info(f"Dispersion\n{'-' * line_width}") - energy_printer("DISP2", results["DISP2"], output="psi4") - energy_printer("EXCH-DISP2", results["EXCH-DISP2"], output="psi4") - - # Total energy - energy_printer("TOTAL", results["TOTAL"], output="psi4") - logger.info("=" * line_width) + induction = [ + "IND2_A", + "IND2_B", + "IND2", + "EXCH-IND2_A", + "EXCH-IND2_B", + "EXCH-IND2", + ] + sections = { + "Electrostatics": ["ELST1"], + "Exchange": ["EXCH1", "EXCH1(S^2)"], + "Induction": induction, + "Dispersion": ["DISP2", "EXCH-DISP2"], + } + + lines = [ + " |------------------------------------| ", + " | SAPT Summary Table | ", + " |------------------------------------| ", + "", + "=" * line_width, + " Term Value (mEh) Value (kcal/mol)" + " Value (kJ/mol)", + "=" * line_width, + ] + for title, terms in sections.items(): + lines += ["", title, "-" * line_width] + lines += [format_energy(term, results[term]) for term in terms] + lines += ["", format_energy("TOTAL", results["TOTAL"]), "=" * line_width] + + logger.info("\n".join(lines)) @trace_memory_peak diff --git a/prop_sapt/utils.py b/prop_sapt/utils.py index 440e68b..316e5da 100644 --- a/prop_sapt/utils.py +++ b/prop_sapt/utils.py @@ -117,6 +117,22 @@ def __exit__(self, *args): logger.info(f"...{self.name} took a total of {t: .2f} seconds.") +def format_energy(name: str, value: float) -> str: + """The line of an energy term: its name and its value in mEh, kcal/mol and kJ/mol. + + Args: + name (str): Name of the energy term. + value (float): Value of the energy term in Hartree. + """ + + name_padding = " " * (20 - len(name)) + return ( + name + + name_padding + + f"{value* 1000: 16.8f} mEh {value* 627.509: 16.8f} kcal/mol {value* 2625.50: 16.8f} kJ/mol" + ) + + def energy_printer(name: str, value: float, output: str = "psi4", **kwargs): """Prints out the energy value in mH and kcal/mol. @@ -131,12 +147,7 @@ def energy_printer(name: str, value: float, output: str = "psi4", **kwargs): ValueError: If the output filename is not provided when output is 'file'. """ - name_padding = " " * (20 - len(name)) - energy_output_string = ( - name - + name_padding - + f"{value* 1000: 16.8f} mEh {value* 627.509: 16.8f} kcal/mol {value* 2625.50: 16.8f} kJ/mol" - ) + energy_output_string = format_energy(name, value) if output == "psi4": logger.info(energy_output_string) From eafb2ee4e08e0a4ba11679655ecf4eb1a893cb8e Mon Sep 17 00:00:00 2001 From: btyrcha Date: Thu, 19 Nov 2026 18:14:57 +0100 Subject: [PATCH 6/7] docs, changelog and AI usage log for the logging layer The usage guide's Output and logging section shows how to quiet or redirect propSAPT's output, the API reference lists prop_sapt.log, and the changelog says the output goes through logging, still into Psi4's output file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019ZeFQEY3P12DGTNcvWEyhT --- AI-USAGE.md | 1 + CHANGELOG.md | 5 +++++ docs/api.rst | 7 +++++++ docs/usage.rst | 23 +++++++++++++++++++++++ 4 files changed, 36 insertions(+) diff --git a/AI-USAGE.md b/AI-USAGE.md index adec6ee..0cdb3b9 100644 --- a/AI-USAGE.md +++ b/AI-USAGE.md @@ -170,3 +170,4 @@ The short version, for disclosures; the log below has the detail. ### 2026-11-19 - Rebased the CPSCF solver PR onto `main` after the 0.5.0 release and the TREXIO export (its changelog entry moved to the Unreleased section). +- Planned and implemented the logging layer (step 1.2 of the backend roadmap): the `prop_sapt` logger with a handler writing into Psi4's output file, about 120 `psi4.core.print_out` calls in 15 modules replaced by module loggers with messages free of blank lines, the SAPT summary table as one record, `make_cube` progress at DEBUG, the 36 `psi4.core.clean()` calls before raises removed, with tests, docs and a changelog entry; results unchanged on He–H2 (energies, properties, densities and finite field within run-to-run round-off). diff --git a/CHANGELOG.md b/CHANGELOG.md index 91d0f86..5927dc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,11 @@ requests of the private repository propSAPT was developed in before it was publi - propSAPT solves the CPSCF equations with its own conjugate-gradient solver, with the same results. A solve that has not converged in `cpscf_maxiter` iterations now warns, where it used to go on silently. +- propSAPT writes its output through Python's `logging`, under the `prop_sapt` logger. + It still goes into Psi4's output file, with fewer blank lines, and the standard + `logging` calls now quiet or redirect it, in whole or per module. The progress of + `make_cube` over the grid is logged at the DEBUG level. See the + [usage guide](https://btyrcha.github.io/propSAPT/usage.html#output-and-logging). ### Fixed diff --git a/docs/api.rst b/docs/api.rst index 568aeb1..305d69a 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -131,6 +131,13 @@ propSAPT Options :undoc-members: :show-inheritance: +Logging +------- + +.. automodule:: prop_sapt.log + :members: + :show-inheritance: + Utility Functions ----------------- diff --git a/docs/usage.rst b/docs/usage.rst index 83ebdb5..dbcf640 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -572,6 +572,29 @@ You can customize various aspects of the calculation using Psi4 options before c } ) +Output and logging +~~~~~~~~~~~~~~~~~~ + +propSAPT writes its output through Python's :mod:`logging`, under the ``prop_sapt`` +logger, and by default into Psi4's output file next to Psi4's own output. Each module +logs under its own name, e.g. ``prop_sapt.cpscf_solver`` for the CPSCF iterations, so +the standard ``logging`` calls quiet or redirect any part of it: + +.. code-block:: python + + import logging + + # only warnings from propSAPT + logging.getLogger("prop_sapt").setLevel(logging.WARNING) + + # no CPSCF iteration tables + logging.getLogger("prop_sapt.cpscf_solver").setLevel(logging.WARNING) + + # also into a file of its own + logging.getLogger("prop_sapt").addHandler(logging.FileHandler("prop_sapt.log")) + +The progress of ``make_cube`` over the grid is logged at the ``DEBUG`` level. + Hellmann-Feynman Forces ----------------------- From 7eaa97edf7385a79f04b20b702995e812d8d93d6 Mon Sep 17 00:00:00 2001 From: btyrcha Date: Thu, 19 Nov 2026 18:22:12 +0100 Subject: [PATCH 7/7] the finite-field banner test checks the log record, not print_out calls The banner is one INFO record now, so the test reads it with caplog: its logger, level, title and formatted details. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019ZeFQEY3P12DGTNcvWEyhT --- tests/test_finite_field.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/tests/test_finite_field.py b/tests/test_finite_field.py index c1bfa10..6783264 100644 --- a/tests/test_finite_field.py +++ b/tests/test_finite_field.py @@ -1,5 +1,6 @@ """Minimal tests for finite_field module - core functionality only.""" +import logging import math import pandas as pd @@ -141,17 +142,21 @@ def test_build_result_series_four_point(self): class TestBannerPrinting: """Test banner printing.""" - @patch("psi4.core.print_out") - def test_print_finite_field_banner(self, mock_print): - """Test print_finite_field_banner calls psi4.core.print_out.""" - print_finite_field_banner( - "TEST BANNER", - {"Method": "HF", "Field strength": 0.001}, - ) + def test_print_finite_field_banner(self, caplog): + """The banner is one INFO record with the title and the details.""" + with caplog.at_level(logging.INFO, logger="prop_sapt"): + print_finite_field_banner( + "TEST BANNER", + {"Method": "HF", "Field strength": 0.001}, + ) - assert mock_print.call_count >= 5 - calls_str = str(mock_print.call_args_list) - assert "TEST BANNER" in calls_str + (record,) = caplog.records + assert record.name == "prop_sapt.finite_field.utils" + assert record.levelno == logging.INFO + lines = record.getMessage().splitlines() + assert lines[1] == " TEST BANNER" + assert " Method: HF" in lines + assert " Field strength: 0.001000 a.u." in lines class TestDipoleTwoPointFormula: