Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions AI-USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,11 @@ The short version, for disclosures; the log below has the detail.

- Explained when the version changes; a release workflow check that `CITATION.cff` and the install commands match the tag, `main` set to `0.5.0.dev0`, and a release checklist in `CONTRIBUTING.md`.

### 2026-11-09

- Re-audited where the package depends on Psi4 (objects, internal APIs, AO-basis inputs and outputs) for a roadmap item, and compared the integral, response and grid features of two other quantum-chemistry codes; recorded the findings and a staged plan in the development roadmap.
- propSAPT's own conjugate-gradient CPSCF solver in place of Psi4's internal one, with Psi4 supplying only the orbital-Hessian products; a warning for unconverged solves, solver unit tests and Hessian tests, checked against the old solver to 4e-13.

### 2026-11-14

- Added the second-order properties preprint (arXiv:2611.07993) to the citations: `CITATION.cff` (under `references`, schema-validated), the README, and a new Citing section in the docs with BibTeX entries for both papers.
Expand All @@ -161,3 +166,7 @@ The short version, for disclosures; the log below has the detail.
- Fixed density file names that collided on case-insensitive file systems (`Ind`/`ind`, `Disp`/`disp`): a file-name helper with a collision check in `prop_sapt.artifacts`, `Ind`/`Disp` files named `ind-total`/`disp-total`, with tests, an example, docs and a changelog entry.
- Rebased the TREXIO export PR onto `main` after the 0.5.0 release (its changelog entries moved to the Unreleased section) and after the density file-name fix, naming the TREXIO files like the cubes through `density_file_names`, with a test of the collision check.
- Addressed the Copilot review of the TREXIO PR: documented that the bundle's cube and TREXIO entries record the files requested, which are written after it, and made `export_trexio` refuse a `relative_cutoff` outside [0, 1), with tests.

### 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).
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ requests of the private repository propSAPT was developed in before it was publi
- `density_natural_orbitals`: the natural orbitals of the density changes, a few of which
usually carry most of a change, in the spirit of NOCV.

### Changed

- 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.

### Fixed

- The cube and `.npy` files of the `Ind` and `Disp` densities are now named
Expand Down
176 changes: 176 additions & 0 deletions prop_sapt/cpscf_solver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
"""Preconditioned conjugate-gradient solver of the CPSCF equations.

`conjugate_gradient` solves H x = b for several right-hand sides b at once, where H is
symmetric positive definite and known only through its products with vectors: for the
CPSCF equations, the orbital Hessian of a monomer (see
`helper_SAPT.orbital_hessian_product`). Each iteration takes the products of all
unconverged vectors in one call, which for the CPSCF equations is one J/K build for the
whole batch. Each vector converges on its own.
"""

import time
import warnings
from collections.abc import Callable, Mapping, Sequence

import numpy as np
import psi4

HessianProduct = Callable[[list[np.ndarray]], list[np.ndarray]]


def conjugate_gradient(
rhs: Sequence[np.ndarray],
hessian_product: HessianProduct,
diagonal: np.ndarray,
r_convergence: float,
maxiter: int,
title: str = "CPSCF",
) -> list[np.ndarray]:
"""
Solves H x = b for every b in `rhs` with the preconditioned conjugate-gradient method.

The preconditioner divides by `diagonal`, and the start is the preconditioned
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.

Args:
rhs (Sequence[np.ndarray]): Right-hand sides b, arrays of the shape of
`diagonal`. They are not changed.
hessian_product (Callable[[list[np.ndarray]], list[np.ndarray]]): Takes a list of
arrays x and returns the products H x, in the same order.
diagonal (np.ndarray): Positive approximation of the diagonal of H, e.g. the
orbital energy differences.
r_convergence (float): Relative residual below which a vector has converged.
maxiter (int): Maximum number of iterations, each one `hessian_product` call.
title (str, optional): Name of the solve in the output. Defaults to "CPSCF".

Returns:
list[np.ndarray]: The solutions x, in the order of `rhs`.

Warns:
RuntimeWarning: Raised if a vector has not converged in `maxiter` iterations, or
has met a direction in which H is not positive definite. Its last iterate is
returned.
"""

t_start = time.time()
b = [np.asarray(vector, dtype=np.float64) for vector in rhs]
for vector in b:
if vector.shape != diagonal.shape:
raise ValueError(
f"{title}: right-hand side of shape {vector.shape}, "
f"expected {diagonal.shape}."
)
if not b:
return []

b_norm = [np.linalg.norm(vector) for vector in b]
residual = [0.0] * len(b)
x = [vector / diagonal for vector in b]
r, z, p, rz = {}, {}, {}, {}

active = [i for i, norm in enumerate(b_norm) if norm > 0.0]
for i, product in zip(active, _products(hessian_product, x, active, title)):
r[i] = b[i] - product
residual[i] = np.linalg.norm(r[i]) / b_norm[i]
active = [i for i in active if residual[i] >= r_convergence]

for i in active:
z[i] = r[i] / diagonal
p[i] = z[i]
rz[i] = np.vdot(r[i], z[i])

_print_header(title, len(b), r_convergence, maxiter)
_print_row("Guess", residual, len(active), t_start)

# vectors stopped at a direction of non-positive curvature
stopped = []
iteration = 0
while active and iteration < maxiter:
iteration += 1
unconverged = []
for i, product in zip(active, _products(hessian_product, p, active, title)):
curvature = np.vdot(p[i], product)
if not curvature > 0.0:
stopped.append(i)
continue

alpha = rz[i] / curvature
x[i] = x[i] + alpha * p[i]
r[i] = r[i] - alpha * product
residual[i] = np.linalg.norm(r[i]) / b_norm[i]
if residual[i] < r_convergence:
continue

z[i] = r[i] / diagonal
rz_new = np.vdot(r[i], z[i])
p[i] = z[i] + (rz_new / rz[i]) * p[i]
rz[i] = rz_new
unconverged.append(i)

active = unconverged
_print_row(f"{iteration:d}", residual, len(active), t_start)

psi4.core.print_out(" " + "-" * 56 + "\n")

if active:
_warn(
f"{title}: {len(active)} of {len(b)} vectors did not converge in "
f"{maxiter} iterations (largest relative residual "
f"{max(residual[i] for i in active):.2e}, convergence {r_convergence:.1e})."
)
if stopped:
_warn(
f"{title}: {len(stopped)} of {len(b)} vectors stopped at a direction in "
"which the Hessian is not positive definite (largest relative residual "
f"{max(residual[i] for i in stopped):.2e})."
)

return x


def _products(
hessian_product: HessianProduct,
vectors: Sequence[np.ndarray] | Mapping[int, np.ndarray],
active: list[int],
title: str,
) -> list[np.ndarray]:
"""The products of H with the `active` ones of `vectors`, in one call."""

if not active:
return []

products = hessian_product([vectors[i] for i in active])
if len(products) != len(active):
raise ValueError(
f"{title}: the Hessian product returned {len(products)} vectors "
f"for {len(active)}."
)

return products


def _print_header(title: str, count: int, r_convergence: float, maxiter: int):
psi4.core.print_out(
f"\n {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"
)


def _print_row(label: str, residual: list[float], remaining: int, t_start: float):
psi4.core.print_out(
f" {label:>5} {np.mean(residual):14.3e} {np.max(residual):13.3e} "
f"{remaining:10d} {time.time() - t_start:9.1f}\n"
)


def _warn(message: str):
psi4.core.print_out(f"\n Warning: {message}\n")
warnings.warn(message, RuntimeWarning, stacklevel=3)
106 changes: 62 additions & 44 deletions prop_sapt/helper_SAPT_DF.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,9 @@
import numpy as np
import opt_einsum as oe
import psi4
from psi4.driver.p4util import message_box, cg_solver, OptionsState, OptionsStateCM
from psi4.driver.p4util import message_box, OptionsState, OptionsStateCM

from .cpscf_solver import conjugate_gradient
from .options import PROPSAPT_OPTIONS, check_cpscf_type, check_df_basis_cpscf


Expand Down Expand Up @@ -576,23 +577,29 @@ def cpscf_batch(
Coupled perturbed HF or KS calculations for several perturbations of one monomer.

Solves the CPSCF equations of `monomer` for every (ov) matrix in `perturbations`
in one conjugate-gradient run. Each iteration builds the Hessian products of all
unconverged vectors with one J/K call, which costs much less than a call per
vector. Each vector converges on its own, to the same amplitudes as `cpscf`.
in one conjugate-gradient run (`prop_sapt.cpscf_solver`). Each iteration builds
the Hessian products of all unconverged vectors with one J/K call, which costs
much less than a call per vector. Each vector converges on its own, to the same
amplitudes as `cpscf`.

The J and K matrices come from the J/K object of the monomer SCF, or from
`cpscf_jk` if it is set (see `build_cpscf_jk`).
The amplitudes t of a perturbation omega solve H t = -omega, with H the orbital
Hessian of `orbital_hessian_product`; uncoupled, they are
omega / (eps_occ - eps_vir). The J and K matrices come from the J/K object of
the monomer SCF, or from `cpscf_jk` if it is set (see `build_cpscf_jk`).

Args:
monomer (str): "A" or "B".
perturbations (list[np.ndarray]): (ov) perturbation matrices.
r_convergence (float | None, optional): Residual convergence threshold.
Defaults to the `r_convergence` option.
r_convergence (float | None, optional): Convergence threshold of the
relative residual. Defaults to the `r_convergence` option.
maxiter (int | None, optional): Maximum number of iterations. Defaults to the
`cpscf_maxiter` option.

Returns:
list[np.ndarray]: The (vo) amplitudes, in the order of `perturbations`.

Warns:
RuntimeWarning: Raised if some amplitudes have not converged.
"""

self._check_cpscf(monomer)
Expand All @@ -607,55 +614,66 @@ def cpscf_batch(

# NOTE: Changed the monomer naming scheme:
# 'monomer' refers now to the one that returned amplitudes are for.
occ, vir, wfn = (
("a", "r", self.wfnA) if monomer == "A" else ("b", "s", self.wfnB)
occ, vir = ("a", "r") if monomer == "A" else ("b", "s")

amplitudes = conjugate_gradient(
[-np.asarray(pert_ov) for pert_ov in perturbations],
lambda vectors: self.orbital_hessian_product(monomer, vectors),
self.eps(vir) - self.eps(occ, dim=2),
r_convergence=r_convergence,
maxiter=maxiter,
title=f"CPSCF of monomer {monomer}",
)
no = self.sizes[occ]
nv = self.sizes[vir]

# Get the orbital energy differences
eps_ov = psi4.core.Matrix.from_array(self.eps(occ, dim=2) - self.eps(vir))

# apply hessian func to every active vector in one call
def _hess_x(x_vec, act_mask):
active = [x for x, on in zip(x_vec, act_mask) if on]
products = iter(wfn.cphf_Hx(active) if active else [])
return [next(products) if on else False for on in act_mask]

# preconditioner - applies denominator (for faster convergence)
def _apply_precon(x_vec, act_mask):
preconditioned = []
for x, on in zip(x_vec, act_mask):
if on:
p = x.clone()
p.apply_denominator(eps_ov)
preconditioned.append(p)
else:
preconditioned.append(False)
return preconditioned

# We want to return (vo) matrices
return [t.T for t in amplitudes]

def orbital_hessian_product(
self, monomer: str, vectors: list[np.ndarray]
) -> list[np.ndarray]:
"""
Products of the orbital Hessian of `monomer` with (ov) `vectors`, the left-hand
side of its CPSCF equations (see `cpscf_batch`).

The Hessian is the symmetric positive definite one of a real singlet
perturbation: for RHF,
H_{ar,a'r'} = (eps_r - eps_a) delta_{aa'} delta_{rr'}
+ 4 (ar|a'r') - (ar'|a'r) - (aa'|rr'),
and for RKS the exchange-correlation kernel too. Its J and K matrices come from
the J/K object of the monomer SCF, or from `cpscf_jk` if it is set (see
`build_cpscf_jk`). Psi4's `cphf_Hx` gives the products, with the opposite sign.

Args:
monomer (str): "A" or "B".
vectors (list[np.ndarray]): (ov) vectors.

Returns:
list[np.ndarray]: The (ov) products, in the order of `vectors`.
"""

self._check_cpscf(monomer)

if len(vectors) == 0:
return []

wfn = self.wfnA if monomer == "A" else self.wfnB
matrices = [
psi4.core.Matrix.from_array(np.ascontiguousarray(x)) for x in vectors
]

# `cphf_Hx` takes the J and K matrices from the wavefunction's J/K object
swap_jk = self.cpscf_jk is not None
if swap_jk:
scf_jk = wfn.jk()
wfn.set_jk(self.cpscf_jk)

# solve cpscf
try:
x_vec, _ = cg_solver(
[psi4.core.Matrix.from_array(pert_ov) for pert_ov in perturbations],
_hess_x,
_apply_precon,
printlvl=2,
maxiter=maxiter,
rcond=r_convergence,
)
products = wfn.cphf_Hx(matrices)
finally:
if swap_jk:
wfn.set_jk(scf_jk)

# We want to return (vo) matrices
return [np.array(x).reshape(no, nv).T for x in x_vec]
return [-np.asarray(product) for product in products]

def build_cpscf_jk(
self, cpscf_type: str | None, df_basis: str | None = None
Expand Down
Loading