Skip to content
1 change: 1 addition & 0 deletions AI-USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 7 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,13 @@ propSAPT Options
:undoc-members:
:show-inheritance:

Logging
-------

.. automodule:: prop_sapt.log
:members:
:show-inheritance:

Utility Functions
-----------------

Expand Down
23 changes: 23 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
-----------------------

Expand Down
1 change: 1 addition & 0 deletions prop_sapt/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
11 changes: 7 additions & 4 deletions prop_sapt/basis_overrides.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]+$")

Expand Down Expand Up @@ -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

Expand All @@ -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
9 changes: 6 additions & 3 deletions prop_sapt/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -28,6 +28,7 @@
fragment weights are a partition of unity.
"""

import logging
import os
import sys
import warnings
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
12 changes: 6 additions & 6 deletions prop_sapt/cpscf_batching.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand All @@ -44,15 +46,15 @@ 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.

Args:
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:
Expand Down Expand Up @@ -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

Expand Down
20 changes: 11 additions & 9 deletions prop_sapt/cpscf_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]

Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
52 changes: 25 additions & 27 deletions prop_sapt/cubes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
https://paulbourke.net/dataformats/cube/
"""

import logging
import numbers
import os
from dataclasses import dataclass
Expand All @@ -23,6 +24,8 @@
_stack_matrices,
)

logger = logging.getLogger(__name__)


@dataclass(kw_only=True, eq=False, repr=False)
class Cube:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"]))
Expand Down Expand Up @@ -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)"
)
Expand All @@ -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
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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
Loading