From 7bfa2ac70c4363f80f35294a8cb9168bcba33fcb Mon Sep 17 00:00:00 2001 From: peastman Date: Thu, 20 Aug 2026 10:46:15 -0700 Subject: [PATCH] Iterative solver for charge equilibration --- mlipops/chargeequilibration.py | 24 ++++- mlipops/minres.py | 178 +++++++++++++++++++++++++++++++ tests/TestChargeEquilibration.py | 32 +++++- 3 files changed, 228 insertions(+), 6 deletions(-) create mode 100644 mlipops/minres.py diff --git a/mlipops/chargeequilibration.py b/mlipops/chargeequilibration.py index 5772361..a406cc0 100644 --- a/mlipops/chargeequilibration.py +++ b/mlipops/chargeequilibration.py @@ -3,6 +3,7 @@ from .coulombnc import CoulombNC from .coulombrf import CoulombRF from .coulombewald import CoulombEwald +from .minres import minres from .utils import pairwise_displacements @@ -22,6 +23,15 @@ class ChargeEquilibration(torch.nn.Module): one. It then solves the equations subject to a separate constraint for each molecule. This produces more realistic results, but requires that you know in advance how the atoms are divided into molecules and how the charge is divided among them. + + You can optionally provide an external electric potential that should be used to polarize the atoms. This might + be computed from a uniform external field, or by calling compute_potential() on a Coulomb calculation object to get + the potential resulting from a set of external charges. + + This class offers a choice of method for solving the system of equations. By default it uses torch.linalg.solve(), + which implements a direct algorithm. It is accurate and generally robust, but it can be slow, especially for large + systems. Alternatively you can choose MINRES, an efficient iterative algorithm. It can be much faster in some + cases, but this comes at the cost of somewhat lower accuracy. """ def __init__(self, coulomb: CoulombNC | CoulombRF | CoulombEwald): @@ -38,7 +48,8 @@ def __init__(self, coulomb: CoulombNC | CoulombRF | CoulombEwald): def forward(self, positions: torch.Tensor, electronegativity: torch.Tensor, hardness: torch.Tensor, radius: torch.Tensor, total_charge: float | None = None, molecules: list | None = None, - box_vectors: torch.Tensor | None = None, potential: torch.Tensor | None = None) -> torch.Tensor: + box_vectors: torch.Tensor | None = None, potential: torch.Tensor | None = None, + solver: str = 'direct') -> torch.Tensor: """Perform charge equilibration to compute atomic partial charges. Parameters @@ -62,6 +73,10 @@ def forward(self, positions: torch.Tensor, electronegativity: torch.Tensor, hard conditions are not used. potential: torch.Tensor a Tensor of shape (n_particles,) containing the external electric potential at the location of each particle + solver: str + the method to use for solving the system of equations. Options are 'direct' (use torch.linalg.solve() to + directly compute the result) and 'minres' (an iterative solver that tends to be faster, especially for large + systems, at the cost of slightly lower accuracy). Returns ------- @@ -113,8 +128,11 @@ def forward(self, positions: torch.Tensor, electronegativity: torch.Tensor, hard if potential is not None: rhs = rhs+potential x = torch.cat([-rhs, mol_charges]) - return torch.linalg.solve(matrix, x)[:n] - + if solver == 'direct': + return torch.linalg.solve(matrix, x)[:n] + if solver == 'minres': + return minres(matrix, x, tol=1e-7)[:n] + raise ValueError(f'Illegal value for solver: {solver}') def _compute_interactions_nc(self, positions: torch.Tensor, hardness: torch.Tensor, radius: torch.Tensor) -> torch.Tensor: """Build the interaction matrix when using CoulombNC.""" diff --git a/mlipops/minres.py b/mlipops/minres.py new file mode 100644 index 0000000..aebd640 --- /dev/null +++ b/mlipops/minres.py @@ -0,0 +1,178 @@ +# This file is from https://github.com/cvxgrp/torch_linops. It has been modified to remove a dependency on another +# class in that package, and to eliminate unused code. + + +import torch + +def minres(A, b, M=None, x0=None, tol=1e-5, maxiters=None): + """ + Code based on scipy.sparse.linalg.minres + + Copyright 2022 Parth Nobel + Copyright 2001-2002 Enthought, Inc. 2003-2022, SciPy Developers. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + """ + m, n = A.shape + assert m == n + if maxiters is None: + maxiters = 5 * n + if x0 is None: + x = torch.zeros_like(b) + else: + x = x0 + iters = 0 + + eps = torch.tensor(torch.finfo(b.dtype).eps, device=x.device) # scalar + + r1 = b - A @ x # Supports block + y = r1 if M is None else M @ r1 # Supports block + + #beta1 = r1 @ y # Needs modification + beta1 = inner(r1, y) + assert beta1.min() >= 0, "M must be PD" + if (beta1 == 0).all(): + return x + bnorm = torch.linalg.vector_norm(b, dim=0) + if bnorm.max() == 0: + return b + + beta1 = torch.sqrt(beta1) # Supports block + + oldb = torch.zeros_like(beta1) # Supports block + beta = beta1 # Supports block + dbar = torch.zeros_like(beta1) # Supports block + epsilon = torch.zeros_like(beta1) # Supports block + phibar = beta1 # Supports block + rhs1 = beta1 # Supports block + rhs2 = torch.zeros_like(beta1) # Supports block + + # Stopping criterion only + tnorm2 = torch.zeros_like(beta1) + # Only for illconditioning detection + gmax = torch.tensor(0.0, device=x.device) + # Only for illconditioning detection + gmin = torch.tensor(torch.finfo(x.dtype).max, device=x.device) + + cs = -torch.ones_like(beta1) + sn = torch.zeros_like(beta1) # Supports block + w = torch.zeros_like(b) # Supports block + w2 = torch.zeros_like(b) # Supports block + r2 = r1 # Supports block + + while iters < maxiters: + iters += 1 + s = 1.0 / beta # Supports block + v = s * y # Supports block + y = A @ v # Supports block + if iters >= 2: + y = y - (beta / oldb) * r1 + + alpha = inner(v, y) + y = y - (alpha / beta) * r2 + r1 = r2 + r2 = y + y = r2 if M is None else M @ r2 + oldb = beta + beta = inner(r2, y) + assert (beta >= 0).all() + beta = torch.sqrt(beta) + tnorm2 += alpha**2 + oldb**2 + beta**2 + if iters == 1: + if (beta / beta1).min() <= 10 * eps: + #assert False, "I think this occurs when A = c * I" + pass + + oldeps = epsilon + delta = cs * dbar + sn * alpha + gbar = sn * dbar - cs * alpha + epsilon = sn * beta + dbar = -cs * beta + root = L2norm2entry(gbar, dbar) + #Arnorm = phibar * root + + gamma = L2norm2entry(gbar, beta) + gamma = torch.maximum(gamma, eps) + cs = gbar / gamma + sn = beta / gamma + phi = cs * phibar + phibar = sn * phibar + + + denom = 1.0 / gamma + w1 = w2 + w2 = w + w = (v - oldeps * w1 - delta * w2) * denom + x = x + phi * w + + gmax = torch.max(gmax, gamma).max() + gmin = torch.min(gmin, gamma).min() + z = rhs1 / gamma + rhs1 = rhs2 - delta * z + rhs2 = - epsilon * z + + Anorm = torch.sqrt(tnorm2.max()) + ynorm = torch.linalg.norm(x, dim=0) + epsx = Anorm * ynorm * eps + qrnorm = phibar + rnorm = qrnorm + if ynorm.max() == 0 or Anorm == 0: + test1 = torch.inf + else: + test1 = rnorm / (Anorm * ynorm) + + if Anorm == 0: + test2 = torch.inf + else: + test2 = root / Anorm + Acond = gmax / gmin + t1 = 1 + test1.max() + t2 = 1 + test2.max() + if t2 <= 1: + break + if t1 <= 1: + break + + if Acond >= 0.1 / eps: + assert False, "System is ill-conditioned." + if (epsx >= beta1).any(): + assert False + if test2.max() <= tol: + break + if test1.max() <= tol: + break + return x + +def L2norm2entry(x, y): + return torch.sqrt(x**2 + y**2) + +def inner(x, y): + return (x * y).sum(axis=0) # Supports block diff --git a/tests/TestChargeEquilibration.py b/tests/TestChargeEquilibration.py index 752e5f8..e483e4c 100644 --- a/tests/TestChargeEquilibration.py +++ b/tests/TestChargeEquilibration.py @@ -36,7 +36,8 @@ def validate_minimization(coulomb, positions, charges, box_vectors, hardness, el @pytest.mark.parametrize('device', ['cpu', 'cuda']) -def test_qeq_nc(device): +@pytest.mark.parametrize('solver', ['direct', 'minres']) +def test_qeq_nc(device, solver): """Test the QEq algorithm with no cutoff.""" if not torch.cuda.is_available() and device == 'cuda': pytest.skip('No GPU') @@ -46,10 +47,10 @@ def test_qeq_nc(device): # Compare to charges computed with tad-multicharge. - charges = eq(positions, electronegativity, hardness, radius, 0) + charges = eq(positions, electronegativity, hardness, radius, 0, solver=solver) validate_minimization(coulomb, positions, charges, None, hardness, electronegativity, radius) assert torch.allclose(torch.tensor([-0.8347, -0.8347, 0.2731, 0.2886, 0.2731, 0.2731, 0.2886, 0.2731]), charges.cpu(), atol=1e-4) - charges = eq(positions, electronegativity, hardness, radius, 1) + charges = eq(positions, electronegativity, hardness, radius, 1, solver=solver) assert torch.allclose(torch.tensor([-0.6708, -0.6708, 0.3982, 0.3745, 0.3982, 0.3982, 0.3745, 0.3982]), charges.cpu(), atol=1e-4) @@ -201,3 +202,28 @@ def test_qeq_external_potential(device): potential = -(positions*field).sum(axis=1) charges = eq(positions, electronegativity, hardness, radius, 0, potential=potential) assert torch.all(charges[[0,2,3,4]] > charges[[1,5,6,7]]) + + +@pytest.mark.parametrize('device', ['cpu', 'cuda']) +@pytest.mark.parametrize('solver', ['direct', 'minres']) +def test_compile_and_pickle(device, solver): + """Test that ChargeEquilibration can be compiled and pickled.""" + if not torch.cuda.is_available() and device == 'cuda': + pytest.skip('No GPU') + positions, electronegativity, hardness, radius = get_nh3_tensors(device) + coulomb = CoulombNC(None, 1.0, device=device) + eq = ChargeEquilibration(coulomb) + + # Check that torch.compile works correctly. + + compiled = torch.compile(eq) + charges1 = eq(positions, electronegativity, hardness, radius, 0, solver=solver) + charges2 = compiled(positions, electronegativity, hardness, radius, 0, solver=solver) + assert torch.allclose(charges1, charges2) + + # Check that pickle works correctly. + + pickled = pickle.dumps(eq) + eq2 = pickle.loads(pickled) + charges3 = eq2(positions, electronegativity, hardness, radius, 0, solver=solver) + assert torch.allclose(charges1, charges3)