Skip to content

SS(V)PE solvation energy differs from IEF-PCM for the same molecule #3521

Open

Description

@Mjbukhari

Hello,

I am a mathematics MS student working on guaranteed error bounds for electrostatic solvation energies. While comparing PySCF's PCM variants, I noticed that SS(V)PE behaves differently from the other methods, and I would be grateful if someone could check whether this is expected or whether I am using it wrongly.

Setup

  • Recent PySCF release
  • HF/6-31+G* density from an IEF-PCM SCF, then the same frozen density passed to every PCM method
  • Default cavity (1.2 x Bondi radii), eps = 78.3553
  • Lebedev grids with 302 and 1202 points

Observation

My understanding is that for an isotropic dielectric, SS(V)PE and IEF-PCM are formally equivalent, so their energies should be close and should get closer as the surface grid is refined. For water they are close, but for ions the difference is large, and for NH4+ it grows with refinement (kcal/mol):

Molecule IEF-PCM 302 SS(V)PE 302 IEF-PCM 1202 SS(V)PE 1202
water -8.906 -8.846 -8.931 -8.847
OH- -90.741 -90.118 -90.813 -90.191
CN- -70.168 -69.514 -70.278 -69.416
formate -72.464 -70.272 -72.590 -70.321
NH4+ -80.482 -77.179 -80.533 -75.826

Independent check

I also computed two-sided bounds on the exact Poisson solvation energy for the same density and cavity, using a primal-dual method. On analytic test cases (Born ion, Kirkwood sphere) the bounding functionals reproduce the exact energy to about 1e-15 when evaluated on the exact solution. For the molecules above, C-PCM and IEF-PCM lie inside or close to my brackets, while SS(V)PE lies outside them for OH-, CN-, formate, NH4+ and acetate. For water the brackets are not tight enough to conclude anything.

Is this the expected behaviour of the SS(V)PE implementation, or is there a setting I am missing? I can share my scripts if that helps.

Thank you for your time and for maintaining PySCF.

M. Javed Bukhari
COMSATS University Islamabad, Lahore Campus

"""
Aequa-Solv (QM solutes): certified exact-Poisson electrostatic solvation energies
with escaped charge, and certified error bars for PySCF's PCM variants.

Model: -div(eps grad phi) = 4 pi rho  (atomic units), rho = nuclei + frozen SCF electron density,
eps = 1 inside the union of scaled vdW spheres (same cavity as PySCF PCM), eps_out outside.
Electron density outside the cavity ("escaped charge") is treated exactly.

Output: guaranteed bracket  L <= dG_exact <= U  for the reaction energy 1/2 int rho psi,
and for each PCM variant (C-PCM, IEF-PCM, SS(V)PE, COSMO, same density, same cavity):
a certified bound on its error.

Usage (Kaggle: pip install pyscf):
  python aequa_solv_qm.py --mol cn --budget 900
  python aequa_solv_qm.py --mol formate --budget 1800 --tol 1e-3
"""
import argparse, copy, json, math, time
import numpy as np
import torch
from pyscf import gto, scf, dft, lib
from pyscf.solvent import pcm as pyscf_pcm
from pyscf.dft import numint, gen_grid

HARTREE_KCAL = 627.509474
FOURPI = 4.0 * math.pi

MOLECULES = {  # geometries in Angstrom, net charge
    "cn":      ("C 0 0 0; N 0 0 1.172", -1),
    "ocl":     ("Cl 0 0 0; O 0 0 1.688", -1),
    "oh":      ("O 0 0 0; H 0 0 0.970", -1),
    "formate": ("C 0 0 0.000; O 0 1.128 -0.538; O 0 -1.128 -0.538; H 0 0 1.115", -1),
    "acetate": ("C 0 0 0; C 0 0 1.540; O 0 1.130 2.120; O 0 -1.130 2.120; "
                "H 1.027 0 -0.360; H -0.513 0.889 -0.360; H -0.513 -0.889 -0.360", -1),
    "phenolate": ("C 0 0 1.310; C 0 1.230 0.590; C 0 1.210 -0.800; C 0 0 -1.510; C 0 -1.210 -0.800; "
                  "C 0 -1.230 0.590; O 0 0 2.580; H 0 2.170 1.130; H 0 2.150 -1.340; H 0 0 -2.600; "
                  "H 0 -2.150 -1.340; H 0 -2.170 1.130", -1),
    "nh4":     ("N 0 0 0; H 0.629 0.629 0.629; H -0.629 -0.629 0.629; H -0.629 0.629 -0.629; H 0.629 -0.629 -0.629", 1),
    "water":   ("O 0 0 0.1173; H 0 0.7572 -0.4692; H 0 -0.7572 -0.4692", 0),
    "acetamide": ("C 0 0 0; O 0 1.220 0.140; N 0 -0.870 1.020; C 0 -0.590 -1.390; H 0 -1.860 0.860; "
                  "H 0 -0.560 1.980; H 0.890 -1.230 -1.500; H -0.890 -1.230 -1.500; H 0 0.200 -2.140", 0),
}


# =============================================================================
# 1. Quantum chemistry: frozen density and PCM reference energies
# =============================================================================
def run_qm(args):
    atom, charge = MOLECULES[args.mol]
    mol = gto.M(atom=atom, charge=charge, basis=args.basis, verbose=0)
    mf = (scf.RHF(mol) if args.xc == "hf" else dft.RKS(mol, xc=args.xc)).PCM()
    mf.with_solvent.method = "IEF-PCM"
    mf.with_solvent.eps = args.eps
    mf.kernel()
    assert mf.converged, "SCF did not converge"
    dm = mf.make_rdm1()
    pcm_e, warm = {}, None
    orders = [int(o) for o in args.pcm_orders.split(",")]
    for order in orders:
        for meth in ["C-PCM", "IEF-PCM", "SS(V)PE", "COSMO"]:
            s = pyscf_pcm.PCM(mol)
            s.method, s.eps, s.lebedev_order = meth, args.eps, order
            s.build()
            e, _ = s._get_vind(dm)
            pcm_e[f"{meth} [{gen_grid.LEBEDEV_ORDER[order]} pts]"] = float(e)
            if meth == "IEF-PCM" and order == max(orders):
                warm = dict(coords=np.array(s.surface["grid_coords"]), zeta=np.array(s.surface["charge_exp"]),
                            q=np.array(s._intermediates["q_sym"]), label=f"IEF-PCM [{gen_grid.LEBEDEV_ORDER[order]} pts]")
    radii = (1.2 * pyscf_pcm.modified_Bondi)[mol.atom_charges()]  # bohr, PySCF default cavity
    return mol, dm, pcm_e, radii, warm


def field_V(mol, dm, X, chunk=3000):
    """grad V at points X (bohr), V = sum_A Z_A/|x-R_A| - int rho_e/|x-r|."""
    out = np.zeros_like(X)
    for A, (Z, RA) in enumerate(zip(mol.atom_charges(), mol.atom_coords())):
        d = X - RA
        out -= Z * d / np.linalg.norm(d, axis=1, keepdims=True) ** 3
    for i in range(0, len(X), chunk):
        ip = mol.intor("int1e_grids_ip", grids=X[i:i + chunk])          # (3, g, nao, nao) = <d mu| 1/|r-C| |nu>
        # d/dC <mu|1/|r-C||nu> = ip + ip^T ;  V_e = -sum D <mu|..|nu>  =>  grad V_e = -2 sum D ip
        out[i:i + chunk] += -2.0 * np.einsum("xgij,ij->gx", ip, dm)
    return out


def check_field(mol, dm, rng):
    """Finite-difference check of field_V against the potential from int1e_grids."""
    X = rng.normal(size=(4, 3)) * 2.0 + mol.atom_coords().mean(0)
    def V(P):
        v = sum(Z / np.linalg.norm(P - RA, axis=1) for Z, RA in zip(mol.atom_charges(), mol.atom_coords()))
        return v - np.einsum("gij,ij->g", mol.intor("int1e_grids", grids=P), dm)
    h, g = 1e-4, np.zeros_like(X)
    for k in range(3):
        e = np.zeros(3); e[k] = h
        g[:, k] = (V(X + e) - V(X - e)) / (2 * h)
    return float(np.abs(g - field_V(mol, dm, X)).max())


def grad_pcm_potential(warm, X, dev, chunk=8192):
    """Gradient of the PCM reaction potential sum_i q_i erf(z_i r_i)/r_i (a.u.), returned in our units (/4 pi).
    Gaussian surface charges give an H1dot potential, so it is an admissible primal (Theorem 6). Runs on GPU if present."""
    T = lambda v: torch.as_tensor(v, device=dev, dtype=torch.float64)
    S, z, q = T(warm["coords"]), T(warm["zeta"]), T(warm["q"])
    out = []
    for i in range(0, len(X), chunk):
        d = T(X[i:i + chunk])[:, None, :] - S[None]
        r = d.norm(dim=2)
        zr = z[None] * r
        dfdr = (2 / math.sqrt(math.pi) * zr * torch.exp(-zr ** 2) - torch.special.erf(zr)) / r ** 2
        out.append(torch.einsum("gm,gmx->gx", q[None] * dfdr / r, d).cpu())
    return torch.cat(out).numpy() / FOURPI


def rho_e(mol, dm, X, chunk=20000):
    out = np.empty(len(X))
    for i in range(0, len(X), chunk):
        ao = numint.eval_ao(mol, X[i:i + chunk])
        out[i:i + chunk] = numint.eval_rho(mol, ao, dm)
    return out


# =============================================================================
# 2. Quadrature on R^3 for a union of spheres: power-diagram cells, split at each sphere
#    Inside each cell C_k, Omega cap C_k = B_k cap C_k, so the interface is the coordinate surface t = R_k.
# =============================================================================
def rotation(seed):
    r = np.random.default_rng(seed)
    q, rr = np.linalg.qr(r.normal(size=(3, 3)))
    return q * np.sign(np.diag(rr))


def union_grid(centers, radii, nr_in, nr_out, nmu, nphi, seed=0):
    xi, wi = np.polynomial.legendre.leggauss(nr_in)
    xo, wo = np.polynomial.legendre.leggauss(nr_out)
    mu, wmu = np.polynomial.legendre.leggauss(nmu)
    ph = (np.arange(nphi) + 0.5) * 2 * np.pi / nphi
    st = np.sqrt(1 - mu ** 2)
    dirs0 = np.stack([np.outer(st, np.cos(ph)), np.outer(st, np.sin(ph)), np.outer(mu, np.ones(nphi))], -1).reshape(-1, 3)
    wang = np.outer(wmu, np.full(nphi, 2 * np.pi / nphi)).reshape(-1)
    Xs, Ws, Is = [], [], []
    for k, (ck, Rk) in enumerate(zip(centers, radii)):
        dirs = dirs0 @ rotation(seed * 1000 + k).T
        tlo = np.zeros(len(dirs)); thi = np.full(len(dirs), np.inf)
        for j, (cj, Rj) in enumerate(zip(centers, radii)):
            if j == k:
                continue
            d = ck - cj
            al = 2 * dirs @ d
            be = Rj ** 2 - Rk ** 2 - d @ d
            pos, neg = al > 1e-14, al < -1e-14
            tlo[pos] = np.maximum(tlo[pos], be / al[pos])
            thi[neg] = np.minimum(thi[neg], be / al[neg])
            zero = ~(pos | neg)
            thi[zero & (be > 0)] = -1.0
        # inside segment [tlo, min(thi, Rk)]
        a, b = tlo, np.minimum(thi, Rk)
        ok = b > a
        t = a[ok, None] + (b - a)[ok, None] * (xi[None] + 1) / 2
        w = wang[ok, None] * (b - a)[ok, None] / 2 * wi[None] * t ** 2
        Xs.append((ck + t[..., None] * dirs[ok, None, :]).reshape(-1, 3)); Ws.append(w.reshape(-1)); Is.append(np.ones(w.size, bool))
        # outside segment [max(tlo, Rk), thi]
        a = np.maximum(tlo, Rk); b = thi
        fin = np.isfinite(b) & (b > a)
        t = a[fin, None] + (b - a)[fin, None] * (xo[None] + 1) / 2
        w = wang[fin, None] * (b - a)[fin, None] / 2 * wo[None] * t ** 2
        Xs.append((ck + t[..., None] * dirs[fin, None, :]).reshape(-1, 3)); Ws.append(w.reshape(-1)); Is.append(np.zeros(w.size, bool))
        inf = ~np.isfinite(b)
        u = (xo + 1) / 2
        t = a[inf, None] / u[None]                                    # t = T0/u, t^2 dt = T0^3 u^-4 du
        w = wang[inf, None] * 0.5 * wo[None] * a[inf, None] ** 3 / u[None] ** 4
        Xs.append((ck + t[..., None] * dirs[inf, None, :]).reshape(-1, 3)); Ws.append(w.reshape(-1)); Is.append(np.zeros(w.size, bool))
    return np.concatenate(Xs), np.concatenate(Ws), np.concatenate(Is)


# =============================================================================
# 3. Exactly constrained networks (theory items 4-5): primal w in H1dot, dual tau = curl A
# =============================================================================
class Geometry:
    def __init__(self, centers, radii, Q, eps_in, eps_out, dev, dt):
        T = lambda v: torch.as_tensor(v, device=dev, dtype=dt)
        self.c, self.R = T(centers), T(radii)
        self.x0 = self.c.mean(0)
        self.L = float(np.max(np.linalg.norm(centers - centers.mean(0), axis=1)) + radii.max())
        self.s = float((radii ** 2).mean())
        self.ei, self.eo = eps_in, eps_out
        self.c_inf = Q / FOURPI * (1 / eps_out - 1 / eps_in)

    def features(self, x):
        y = x - self.x0
        den = torch.sqrt(self.L ** 2 + (y ** 2).sum(1, keepdim=True))
        g = (((x[:, None, :] - self.c[None]) ** 2).sum(2) - self.R[None] ** 2).min(1, keepdim=True).values
        h = g.abs() / (self.s + g.abs())                               # kink exactly on the cavity surface
        return torch.cat([y / den, 2 * h - 1], 1), self.L / den


def mlp(din, dout, width, depth):
    layers, d = [], din
    for _ in range(depth):
        layers += [torch.nn.Linear(d, width), torch.nn.Tanh()]; d = width
    layers.append(torch.nn.Linear(d, dout))
    with torch.no_grad():
        layers[-1].weight.mul_(1e-2); layers[-1].bias.zero_()
    return torch.nn.Sequential(*layers)


class Primal(torch.nn.Module):
    """Learned part of the primal. Total primal = (PCM potential if warm start, else exact monopole) + lambda^2 N."""
    def __init__(self, G, width, depth, mono=True):
        super().__init__(); self.G = G; self.mono = mono; self.N = mlp(4, 1, width, depth)

    def forward(self, x):
        z, lam = self.G.features(x)
        out = lam[:, 0] ** 2 * self.N(z)[:, 0]
        if self.mono:
            out = out + self.G.c_inf / torch.sqrt(((x - self.G.x0) ** 2).sum(1) + self.G.L ** 2)
        return out


class Dual(torch.nn.Module):
    def __init__(self, G, width, depth):
        super().__init__(); self.G = G; self.M = mlp(4, 3, width, depth)

    def A(self, x):
        z, lam = self.G.features(x)
        return lam ** 2 * self.M(z)


def grad(fn, x, create):
    x = x.detach().requires_grad_(True)
    g, = torch.autograd.grad(fn(x).sum(), x, create_graph=create)
    return g


def curl(Afn, x, create):
    x = x.detach().requires_grad_(True)
    A = Afn(x)
    J = [torch.autograd.grad(A[:, i].sum(), x, create_graph=create, retain_graph=True)[0] for i in range(3)]
    return torch.stack([J[2][:, 1] - J[1][:, 2], J[0][:, 2] - J[2][:, 0], J[1][:, 0] - J[0][:, 1]], 1)


class Batch:
    """Quadrature nodes with precomputed Coulomb data (grad phi_C in eps_in units with eps0 absorbed)."""
    def __init__(self, G, X, W, ins, gV, gP, dev, dt):
        T = lambda v: torch.as_tensor(v, device=dev, dtype=dt)
        self.X, self.W = T(X), T(W)
        self.gP = T(gP)                                   # fixed part of the primal gradient (PCM warm start)
        self.ins = torch.as_tensor(ins, device=dev)
        self.eps = torch.where(self.ins, torch.full_like(self.W, G.ei), torch.full_like(self.W, G.eo))
        self.gC = T(gV) / (FOURPI * G.ei)              # zero inside: never used there (coefficients vanish)
        self.F = (self.eps - G.ei)[:, None] * self.gC
        self.DC = -G.ei * self.gC
        self.cU = 1 / self.eps - 1 / G.ei
        self.kL = -0.5 * (self.W * (self.eps - G.ei) * (self.gC ** 2).sum(1)).sum()
        self.kU = 0.5 * (self.W * self.cU * (self.DC ** 2).sum(1)).sum()

    @staticmethod
    def cat(batches):
        """Merge rotated grids (weights averaged) for training without re-computing Coulomb data."""
        m = object.__new__(Batch)
        for a in ("X", "eps", "gC", "F", "DC", "cU", "gP"):
            setattr(m, a, torch.cat([getattr(b, a) for b in batches]))
        m.W = torch.cat([b.W for b in batches]) / len(batches)
        m.ins = torch.cat([b.ins for b in batches])
        return m

    def L(self, gw, sl=slice(None)):
        W, F, e = self.W[sl], self.F[sl], self.eps[sl]
        return -(W * (F * gw).sum(1)).sum() - 0.5 * (W * e * (gw ** 2).sum(1)).sum()

    def U(self, tau, sl=slice(None)):
        W, c, D, e = self.W[sl], self.cU[sl], self.DC[sl], self.eps[sl]
        return (W * c * (D * tau).sum(1)).sum() + 0.5 * (W * (tau ** 2).sum(1) / e).sum()


def evaluate(B, P, D, chunk=20000):
    Lt, Ut = float(B.kL), float(B.kU)
    for i in range(0, B.X.shape[0], chunk):
        sl = slice(i, i + chunk)
        Lt += float(B.L(B.gP[sl] + grad(P, B.X[sl], False).detach(), sl))
        Ut += float(B.U(curl(D.A, B.X[sl], False).detach(), sl))
    return FOURPI * Lt, FOURPI * Ut          # Hartree


# =============================================================================
# 4. Main
# =============================================================================
def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument("--mol", default="cn", choices=list(MOLECULES))
    ap.add_argument("--basis", default="6-31+g*")
    ap.add_argument("--xc", default="hf")
    ap.add_argument("--eps", type=float, default=78.3553)
    ap.add_argument("--budget", type=float, default=900, help="training seconds")
    ap.add_argument("--tol", type=float, default=1e-3, help="certified relative error for stopping")
    ap.add_argument("--width", type=int, default=64)
    ap.add_argument("--depth", type=int, default=4)
    ap.add_argument("--adam_steps", type=int, default=300)
    ap.add_argument("--train_grid", default="12,12,20,40")
    ap.add_argument("--pool", type=int, default=16, help="number of rotated training grids")
    ap.add_argument("--merge", type=int, default=4, help="rotated grids merged per L-BFGS outer iteration")
    ap.add_argument("--eval_grid", default="20,20,32,64")
    ap.add_argument("--check_grid", default="28,28,64,128")
    ap.add_argument("--eval_every", type=int, default=100)
    ap.add_argument("--device", default="auto")
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--pcm_orders", default="29,59", help="Lebedev orders for the PCM scan (29=302 pts, 59=1202, 107=3890)")
    ap.add_argument("--warm", action="store_true",
                    help="start the primal from the IEF-PCM Gaussian-charge potential (Mode B diagnostic; weak: the blobs are rough)")
    ap.add_argument("--out", default=None, help="prefix for JSON results (one file per molecule)")
    ap.add_argument("--mols", default=None, help="comma-separated list, e.g. cn,oh,formate,water,nh4 (overrides --mol)")
    ap.add_argument("--p_width", type=int, default=128, help="width of the potential (primal) network")
    ap.add_argument("--p_ratio", type=int, default=3, help="primal L-BFGS calls per dual call")
    ap.add_argument("--freeze_tol", type=float, default=2e-4,
                    help="freeze the dual when its best bound improves less than this (relative) over 3 evaluations")
    args, _ = ap.parse_known_args(argv)      # ignores the '-f kernel.json' that Jupyter/Colab adds
    mols = [m.strip() for m in args.mols.split(",")] if args.mols else [args.mol]
    summary = []
    for m in mols:
        if m not in MOLECULES:
            print(f"skipping unknown molecule {m}; choose from {list(MOLECULES)}"); continue
        a = copy.copy(args); a.mol = m
        a.out = f"{args.out}_{m}.json" if args.out else None
        summary.append(run_one(a))
    k = HARTREE_KCAL
    print("\n================ SUMMARY (all molecules, kcal/mol) ================")
    for r in summary:
        L, U = r["bracket"]
        print(f"{r['mol']:10s} escaped {r['escaped']:.3f} e   exact in [{L:.3f}, {U:.3f}]   half-width {0.5*(U-L):.3f}")
        for meth, v in r["pcm"].items():
            print(f"    {meth:20s} {v['E']:10.3f}   certified error in [{v['err_lower']:.3f}, {v['err_upper']:.3f}]"
                  f"{'   (inside bracket)' if v['inside'] else ''}")
    if args.out:
        json.dump(summary, open(f"{args.out}_summary.json", "w"), indent=1)
    return summary


def run_one(args):
    dev = torch.device("cuda" if (args.device == "auto" and torch.cuda.is_available()) else
                       (args.device if args.device != "auto" else "cpu"))
    dt = torch.float64
    torch.manual_seed(args.seed); rng = np.random.default_rng(args.seed)
    t_start = time.time()

    print(f"[1/4] SCF ({args.xc}/{args.basis}, IEF-PCM eps={args.eps}) for {args.mol} ...", flush=True)
    mol, dm, pcm_e, radii, warm = run_qm(args)
    if not args.warm:
        warm = None
    centers = mol.atom_coords()
    print(f"      field check (analytic vs finite difference): {check_field(mol, dm, rng):.2e}")
    for k, v in pcm_e.items():
        print(f"      {k:20s} reaction energy (frozen density): {v*HARTREE_KCAL:10.4f} kcal/mol")

    G = Geometry(centers, radii, float(mol.charge), 1.0, args.eps, dev, dt)

    def make_batch(spec, seeds):
        """Merge several randomly rotated grids (weights averaged) and attach Coulomb data outside the cavity."""
        parts = [union_grid(centers, radii, *[int(v) for v in spec.split(",")], seed=sd) for sd in seeds]
        X = np.concatenate([p[0] for p in parts]); W = np.concatenate([p[1] for p in parts]) / len(parts)
        ins = np.concatenate([p[2] for p in parts])
        gV = np.zeros_like(X)
        gV[~ins] = field_V(mol, dm, X[~ins])
        gP = grad_pcm_potential(warm, X, dev) if warm is not None else np.zeros_like(X)
        return Batch(G, X, W, ins, gV, gP, dev, dt), (X, W, ins)

    print("[2/4] Quadrature grids and Coulomb data ...", flush=True)
    # pool of randomly rotated training grids; every optimisation step sees a fresh random subset,
    # so the networks cannot exploit the quadrature error of one fixed grid
    pool = [make_batch(args.train_grid, [100 + i])[0] for i in range(args.pool)]
    EB, (Xe, We, Ie) = make_batch(args.eval_grid, [7])
    re = rho_e(mol, dm, Xe)                                                    # escaped-charge diagnostic
    n_el, n_out = float((We * re).sum()), float((We * re * (~Ie)).sum())
    print(f"      electrons by quadrature {n_el:.6f} (exact {mol.nelectron}); escaped charge outside cavity {n_out:.4f} e")
    print(f"      cavity volume {float(We[Ie].sum()):.4f} bohr^3, eval nodes {len(We)}")

    P, D = Primal(G, args.p_width, args.depth, mono=warm is None).to(dev, dt), Dual(G, args.width, args.depth).to(dev, dt)
    if warm is not None:   # Mode B (Theorem 7): PCM potential alone as primal, before any training
        with torch.no_grad():
            Lw = FOURPI * float(EB.kL + EB.L(EB.gP))
            kLh = FOURPI * float(EB.kL)
        print(f"      warm start: {warm['label']} potential as primal gives lower bound {Lw*HARTREE_KCAL:.4f} kcal/mol")
    S = abs(float(EB.kU))
    opt = torch.optim.Adam(list(P.parameters()) + list(D.parameters()), lr=2e-3)
    mk = lambda ps: torch.optim.LBFGS(ps, lr=1.0, max_iter=20, history_size=50, line_search_fn="strong_wolfe",
                                      tolerance_grad=1e-14, tolerance_change=1e-16)
    import copy
    best = dict(L=-float("inf"), U=float("inf"), P=copy.deepcopy(P.state_dict()), D=copy.deepcopy(D.state_dict()))
    dual_frozen, ub_hist = False, []

    print(f"[3/4] Training on {dev} (budget {args.budget:.0f} s, certified stop at {args.tol*100:.3f}%) ...", flush=True)
    hist, step, t0, stopped = [], 0, time.time(), None
    while True:
        if step < args.adam_steps:
            B = pool[int(rng.integers(len(pool)))]
            loss = (B.U(curl(D.A, B.X, True)) - B.L(B.gP + grad(P, B.X, True))) / S
            opt.zero_grad(); loss.backward(); opt.step(); step += 1
        else:
            # fresh random merged grid and fresh L-BFGS state at every outer iteration
            B0 = Batch.cat([pool[i] for i in rng.choice(len(pool), size=min(args.merge, len(pool)), replace=False)])
            lp, ld = mk(list(P.parameters())), mk(list(D.parameters()))
            def cp():
                lp.zero_grad(); l = -B0.L(B0.gP + grad(P, B0.X, True)) / S; l.backward(); return l
            def cd():
                ld.zero_grad(); l = B0.U(curl(D.A, B0.X, True)) / S; l.backward(); return l
            for _ in range(args.p_ratio):          # the primal is the bottleneck: give it more iterations
                lp.step(cp)
            if not dual_frozen:
                ld.step(cd)
            step += 20
            del B0
        el = time.time() - t0
        if step % args.eval_every == 0 or el > args.budget:
            te = time.time()
            Lh, Uh = evaluate(EB, P, D)
            # keep the best primal and the best dual separately: any pair gives a valid bracket
            if Lh > best["L"]:
                best["L"], best["P"] = Lh, copy.deepcopy(P.state_dict())
            if Uh < best["U"]:
                best["U"], best["D"] = Uh, copy.deepcopy(D.state_dict())
            width = best["U"] - best["L"]
            ub_hist.append(best["U"])
            if (not dual_frozen and step > args.adam_steps and len(ub_hist) >= 4
                    and ub_hist[-4] - ub_hist[-1] < args.freeze_tol * abs(ub_hist[-1])):
                dual_frozen = True
                print("      (dual converged: frozen, all remaining time goes to the primal)")
            # roll back a network that has drifted well away from its best (protects against quadrature exploitation)
            if Uh - best["U"] > 0.25 * width:
                D.load_state_dict(best["D"]); print("      (dual rolled back to best)")
            if best["L"] - Lh > 0.25 * width:
                P.load_state_dict(best["P"]); print("      (primal rolled back to best)")
            cert = width / (2 * abs(best["U"])) if best["U"] < 0 else float("inf")
            hist.append(dict(step=step, time=el, L=Lh, U=Uh, Lbest=best["L"], Ubest=best["U"], cert=cert))
            print(f"      step {step:5d}  t={el:7.1f}s  current [{Lh*HARTREE_KCAL:.4f}, {Uh*HARTREE_KCAL:.4f}]  "
                  f"best bracket [{best['L']*HARTREE_KCAL:.4f}, {best['U']*HARTREE_KCAL:.4f}] kcal/mol  "
                  f"width {width*HARTREE_KCAL:.4f}  certified rel. error {cert*100:.4f}%", flush=True)
            t0 += time.time() - te
            if cert < args.tol:
                stopped = el
                print(f"      certified stop at t={el:.1f}s")
                break
            if el > args.budget:
                break
    P.load_state_dict(best["P"]); D.load_state_dict(best["D"])
    hist_last = dict(L=best["L"], U=best["U"])

    print("[4/4] Final certificate on three independent finer grids ...", flush=True)
    finals = []
    for sd in (11, 12, 13):
        CB, _ = make_batch(args.check_grid, [sd])
        finals.append(evaluate(CB, P, D)); del CB
        print(f"      grid seed {sd}: [{finals[-1][0]*HARTREE_KCAL:.5f}, {finals[-1][1]*HARTREE_KCAL:.5f}] kcal/mol", flush=True)
    Ls, Us = np.array([f[0] for f in finals]), np.array([f[1] for f in finals])
    L1, U1 = Ls.mean(), Us.mean()
    dq = max(Ls.max() - Ls.min(), Us.max() - Us.min())          # level-1 quadrature error estimate (spread)
    Lc, Uc = L1 - dq, U1 + dq
    k = HARTREE_KCAL
    print("\n================ RESULT ================")
    print(f"molecule {args.mol}  ({args.xc}/{args.basis}, frozen IEF-PCM density, eps_out = {args.eps})")
    print(f"escaped charge: {n_out:.4f} e outside the cavity")
    print(f"certified exact-Poisson reaction energy:  [{Lc*k:.4f}, {Uc*k:.4f}] kcal/mol   "
          f"(midpoint {0.5*(Lc+Uc)*k:.4f}, half-width {0.5*(Uc-Lc)*k:.4f}, quadrature estimate {dq*k:.1e})")
    print(f"{'method':20s} {'energy':>11s} {'inside?':>8s} {'certified error <=':>19s} {'certified error >=':>19s}")
    rows = {}
    for m, e in pcm_e.items():
        up = max(e - Lc, Uc - e)
        lo = max(0.0, Lc - e, e - Uc)
        rows[m] = dict(E=e * k, inside=bool(Lc <= e <= Uc), err_upper=up * k, err_lower=lo * k)
        print(f"{m:20s} {e*k:11.4f} {str(Lc <= e <= Uc):>8s} {up*k:19.4f} {lo*k:19.4f}")
    if warm is not None:
        print(f"warm-start primal ({warm['label']} potential) lower bound before training: {Lw*k:.4f} kcal/mol")
        # Theorem 7: ||grad(psi_PCM - psi)||_eps <= sqrt(2 gap); relative to ||grad psi||_eps >= sqrt(2 (L - kL))
        print(f"certified relative energy-norm error of that PCM reaction potential <= "
              f"{100*math.sqrt(max(Uc-Lw, 0)/max(Lw-kLh, 1e-300)):.3f}%")
    print(f"total wall time {time.time()-t_start:.0f} s")
    if args.out:
        json.dump(dict(args=vars(args), escaped=n_out, bracket_kcal=[Lc * k, Uc * k], quad_err_kcal=dq * k,
                       pcm=rows, hist=hist, stopped=stopped), open(args.out, "w"), indent=1)
    return dict(mol=args.mol, escaped=n_out, bracket=[Lc * k, Uc * k], quad_err=dq * k, pcm=rows)


if __name__ == "__main__":
    import sys
    if "ipykernel" in sys.modules:   # pasted into a notebook cell: call main([...]) yourself in the next cell
        print('Notebook detected. Run e.g.:  main(["--mols", "cn,oh,formate,water,nh4", "--budget", "1800", "--out", "run1"])')
    else:
        main()

Activity

  1. jeanwsr commented on Oct 17, 2026

    @jeanwsr
    Collaborator

    Keep it neutral; don't use the word bug.

    Have to remind you that issue title is not a LLM prompt.

  2. Mjbukhari commented on Oct 17, 2026

    @Mjbukhari
    Author
  3. changed the title [-]SS(V)PE solvation energies outside independent two-sided bounds for small molecules. Keep it neutral; don't use the word bug.[/-] [+]SS(V)PE solvation energy differs from IEF-PCM for the same molecule[/+] on Oct 17, 2026
  4. JustinKyleKirkland commented on Nov 16, 2026

    @JustinKyleKirkland
    Contributor

    I was able to reproduce this with PySCF. For NH4+ (HG/6-31+G*, frozen IEF-PCM density, eps = 78.3553):

    302 pts 1202 pts 3890 pts
    IEF-PCM -80.48 -80.53 -80.55
    SS(V)PE -77.18 -75.83 -76.66

    I could be wrong but, as far as I can tell, this comes from the discretization and is not an implementation error. The current code uses the standard SS(V)PE matrices, K = S - f/(4pi)(DAS + SAD^T) and R = -f(1-DA/(2pi)).

    The formal equivalents with IEF-PCM depends on an operator identity that the discrete D and S matrices satisfy only approximately. On a union of spheres with SWIG, the identity fails badly in the regions where spheres intersect, at points with very small switching function values. A practical consequence is that SS(V)PE violates Gauss's law there. For NH4+, the total induced charge should be -0.987. IEF-PCM gives -0.991 to -0.992, while SS(V)PE gives -0.941 (302 pts) and -0.930 (1202 pts). That deficit is about the size needed to explain the energy gap. K is also poorly conditioned in this case (condition number around 1e7 to 1e9), which fits the non-monotonic behavior under grid refinement.

    As a check, for single-sphere ions (F-, Na+) there are no intersections, and SS(V)PE and IEF-PCM agree to about 1e-4 kcal/mol at every grid size.

    This matches what Lange and Herbert reported (Chem. Phys. Lett. 509, 77 (2011)): the symmetric and asymmetric discretizations can differ by several kcal/mol or more on van der Waals cavities, but not on isodensity cavities.

    For ions on the default cavity, I would recommend IEF-PCM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions