Skip to content

Commit c40d28e

Browse files
committed
fix(electrostatics): apply slab correction in Ewald and PME
1 parent 9167a3a commit c40d28e

2 files changed

Lines changed: 75 additions & 0 deletions

File tree

‎tests/models/test_electrostatics.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import math
56
import traceback
67

78
import pytest
@@ -11,6 +12,7 @@
1112
import torch_sim as ts
1213
from tests.conftest import DEVICE, DTYPE
1314
from tests.models.conftest import make_validate_model_outputs_test
15+
from torch_sim.units import UnitConversion
1416

1517

1618
try:
@@ -195,6 +197,69 @@ def test_ewald_pme_energy_agreement() -> None:
195197
)
196198

197199

200+
def _slab_reference_energy_forces(
201+
positions: torch.Tensor, charges: torch.Tensor, box: float, n_max: int = 100
202+
) -> tuple[torch.Tensor, torch.Tensor]:
203+
"""Reference slab energy and forces from a direct Coulomb sum over x and y images.
204+
205+
Images within a circle of radius n_max * box are summed directly, and the
206+
cells outside it are added analytically as point dipoles.
207+
"""
208+
positions = positions.clone().requires_grad_()
209+
# In-plane image shifts within the circle
210+
idx = torch.arange(-n_max, n_max + 1, dtype=positions.dtype, device=DEVICE)
211+
# The z shift is always zero because a slab has no images along z
212+
shifts = torch.cartesian_prod(idx, idx, torch.zeros_like(idx[:1])) * box
213+
shifts = shifts[shifts.norm(dim=-1) <= n_max * box]
214+
# Pair distances and charge products over all images
215+
pair_vectors = positions[:, None] - positions[None, :] + shifts[:, None, None]
216+
dist_sq = pair_vectors.pow(2).sum(dim=-1)
217+
pair_charges = (charges[:, None] * charges[None, :]).expand_as(dist_sq)
218+
# Direct sum without the i = j, n = 0 terms
219+
is_pair = dist_sq > 0
220+
energy = 0.5 * (pair_charges[is_pair] * dist_sq[is_pair].rsqrt()).sum()
221+
# Dipole term of the cells outside the circle
222+
dipole_sq = (charges[:, None] * positions).sum(dim=0).pow(2)
223+
energy = energy + math.pi * (dipole_sq[2] - 0.5 * dipole_sq[:2].sum()) / (
224+
n_max * box**3
225+
)
226+
# e^2 / Angstrom to eV
227+
energy = energy * UnitConversion.e2_per_Ang_to_eV
228+
forces = -torch.autograd.grad(energy, positions)[0]
229+
return energy.detach(), forces
230+
231+
232+
@pytest.mark.parametrize(
233+
"model_cls",
234+
[pytest.param(EwaldModel, id="ewald"), pytest.param(PMEModel, id="pme")],
235+
)
236+
def test_slab_matches_2d_lattice_sum(model_cls: type[EwaldModel | PMEModel]) -> None:
237+
"""A slab state should match the direct Coulomb sum over its 2D lattice."""
238+
box = 6.0
239+
positions = torch.tensor(
240+
[[0.3, 0.4, 8.8], [3.1, 2.7, 11.1], [1.4, 4.2, 10.6], [4.4, 1.0, 9.3]],
241+
dtype=DTYPE,
242+
device=DEVICE,
243+
)
244+
charges = torch.tensor([1.0, -1.0, 0.5, -0.5], dtype=DTYPE, device=DEVICE)
245+
state = ts.SimState(
246+
positions=positions,
247+
masses=torch.ones(4, dtype=DTYPE, device=DEVICE),
248+
cell=torch.diag(
249+
torch.tensor([box, box, 20.0], dtype=DTYPE, device=DEVICE)
250+
).unsqueeze(0),
251+
pbc=[True, True, False],
252+
atomic_numbers=torch.tensor([11, 17, 11, 17], dtype=torch.int64, device=DEVICE),
253+
)
254+
state._atom_extras["partial_charges"] = charges # noqa: SLF001
255+
256+
model = model_cls(device=DEVICE, dtype=DTYPE)
257+
out = model(state)
258+
energy, forces = _slab_reference_energy_forces(positions, charges, box)
259+
torch.testing.assert_close(out["energy"][0], energy, atol=1e-3, rtol=1e-3)
260+
torch.testing.assert_close(out["forces"], forces, atol=1e-3, rtol=1e-3)
261+
262+
198263
def test_sum_model_lj_plus_dsf() -> None:
199264
"""LJ + DSF should be additive through SumModel."""
200265
from torch_sim.models.interface import SumModel

‎torch_sim/models/electrostatics.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,9 @@ class EwaldModel(ModelInterface):
164164
165165
Requires periodic boundary conditions.
166166
167+
Systems with one non-periodic axis are treated as slabs and get the slab
168+
correction.
169+
167170
Args:
168171
cutoff: Real-space cutoff in Angstrom.
169172
accuracy: Target accuracy for auto-estimated Ewald parameters.
@@ -245,6 +248,8 @@ def forward(self, state: SimState, **_kwargs: object) -> dict[str, torch.Tensor]
245248
compute_forces=self._compute_forces,
246249
compute_virial=self._compute_stress,
247250
accuracy=self.accuracy,
251+
pbc=state.pbc.expand(state.n_systems, 3),
252+
slab_correction=not state.pbc.all(),
248253
)
249254
if not isinstance(out, tuple):
250255
out = (out,)
@@ -279,6 +284,9 @@ class PMEModel(ModelInterface):
279284
280285
Requires periodic boundary conditions.
281286
287+
Systems with one non-periodic axis are treated as slabs and get the slab
288+
correction.
289+
282290
Args:
283291
cutoff: Real-space cutoff in Angstrom.
284292
accuracy: Target accuracy for auto-estimated parameters.
@@ -371,6 +379,8 @@ def forward(self, state: SimState, **_kwargs: object) -> dict[str, torch.Tensor]
371379
compute_virial=self._compute_stress,
372380
accuracy=self.accuracy,
373381
spline_order=self.spline_order,
382+
pbc=state.pbc.expand(state.n_systems, 3),
383+
slab_correction=not state.pbc.all(),
374384
)
375385
if self.mesh_spacing is not None:
376386
pme_kwargs["mesh_spacing"] = self.mesh_spacing

0 commit comments

Comments
 (0)