Skip to content

Commit f93f33a

Browse files
Fix triclinic minimum image and Ewald/PME real-space cutoff (#622)
1 parent 978a857 commit f93f33a

5 files changed

Lines changed: 62 additions & 7 deletions

File tree

‎pyproject.toml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ io = ["ase>=3.26", "phonopy>=3.0.0", "pymatgen>=2026.3.23"]
5252
symmetry = ["moyopy>=0.7.8"]
5353
mace = ["mace-torch>=0.3.16"]
5454
# phono3py>=4.0.0: some older 3.x sdists (e.g. 3.2.0) fail to build and break uv resolution.
55-
mattersim = ["mattersim>=1.2.5", "phono3py>=4.0.0"]
55+
# python-dateutil<3: with 3.x, uv backtracks to an old maggma whose pyzmq no longer builds.
56+
mattersim = ["mattersim>=1.2.5", "phono3py>=4.0.0", "python-dateutil<3"]
5657
metatomic = ["metatomic-torchsim>=0.1.1", "metatomic-ase>=0.1.0", "upet>=0.3.0"]
5758
orb = ["orb-models>=0.6.2"]
5859
sevenn = ["sevenn[torchsim]>=0.12.1"]

‎tests/models/test_electrostatics.py‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,10 @@
3030
def _make_charged_state(
3131
device: torch.device = DEVICE,
3232
dtype: torch.dtype = DTYPE,
33+
repeat: int = 1,
3334
) -> ts.SimState:
3435
"""Build a small NaCl-like state with alternating +1/-1 site charges."""
35-
atoms = bulk("NaCl", crystalstructure="rocksalt", a=5.64, cubic=True)
36+
atoms = bulk("NaCl", crystalstructure="rocksalt", a=5.64, cubic=True).repeat(repeat)
3637
state = ts.io.atoms_to_state(atoms, device, dtype)
3738
n = state.n_atoms
3839
charges = torch.empty(n, dtype=dtype, device=device)
@@ -271,8 +272,29 @@ def test_slab_matches_2d_lattice_sum(model_cls: type[EwaldModel | PMEModel]) ->
271272
model = model_cls(device=DEVICE, dtype=DTYPE)
272273
out = model(state)
273274
energy, forces = _slab_reference_energy_forces(positions, charges, box)
274-
torch.testing.assert_close(out["energy"][0], energy, atol=1e-3, rtol=1e-3)
275-
torch.testing.assert_close(out["forces"], forces, atol=1e-3, rtol=1e-3)
275+
torch.testing.assert_close(out["energy"][0], energy, atol=1e-4, rtol=0)
276+
torch.testing.assert_close(out["forces"], forces, atol=1e-4, rtol=0)
277+
278+
279+
@pytest.mark.parametrize(
280+
"model_cls",
281+
[pytest.param(EwaldModel, id="ewald"), pytest.param(PMEModel, id="pme")],
282+
)
283+
def test_bulk_matches_madelung_energy(model_cls: type[EwaldModel | PMEModel]) -> None:
284+
"""A 216-atom NaCl crystal should match its Madelung energy at the default cutoff."""
285+
state = _make_charged_state(repeat=3)
286+
madelung = 1.7475645946 # rocksalt, per ion pair at the nearest-neighbor distance
287+
nearest_neighbor = 5.64 / 2
288+
energy = -state.n_atoms / 2 * madelung / nearest_neighbor
289+
energy *= UnitConversion.e2_per_Ang_to_eV
290+
out = model_cls(device=DEVICE, dtype=DTYPE)(state)
291+
# nvalchemiops 0.4's approximate erfc leaves ~1e-6 relative error in the energy
292+
torch.testing.assert_close(
293+
out["energy"][0],
294+
torch.tensor(energy, dtype=DTYPE, device=DEVICE),
295+
atol=0,
296+
rtol=3e-6,
297+
)
276298

277299

278300
def test_sum_model_lj_plus_dsf() -> None:

‎tests/test_transforms.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -839,6 +839,14 @@ def test_get_fractional_coordinates_batched() -> None:
839839
torch.tensor([True, False, True], dtype=torch.bool),
840840
[[0.2, 0.0, 0.0], [0.0, 2.2, 0.0], [0.0, 0.0, 0.2]],
841841
),
842+
( # skewed cell where rounding fractional coordinates misses the image
843+
[[0.931, 0.049, 0.0]],
844+
torch.tensor(
845+
[[1.0, 0.9, 0.0], [0.0, 0.1, 0.0], [0.0, 0.0, 1.0]], dtype=DTYPE
846+
),
847+
torch.tensor([True, True, False], dtype=torch.bool),
848+
[[0.031, -0.051, 0.0]],
849+
),
842850
],
843851
)
844852
def test_minimum_image_displacement(

‎torch_sim/models/electrostatics.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from __future__ import annotations
1010

11+
import math
1112
from typing import TYPE_CHECKING
1213

1314
import torch
@@ -169,7 +170,8 @@ class EwaldModel(ModelInterface):
169170
170171
Args:
171172
cutoff: Real-space cutoff in Angstrom.
172-
accuracy: Target accuracy for auto-estimated Ewald parameters.
173+
accuracy: Target accuracy, which sets the Ewald splitting parameter and the
174+
reciprocal-space cutoff together with ``cutoff``.
173175
device: Compute device. Defaults to CUDA if available, else CPU.
174176
dtype: Floating-point dtype. Defaults to ``torch.float64``.
175177
compute_forces: Whether to return forces. Defaults to True.
@@ -237,10 +239,14 @@ def forward(self, state: SimState, **_kwargs: object) -> dict[str, torch.Tensor]
237239
state.positions.shape[0],
238240
)
239241
cell = state.row_vector_cell.contiguous()
242+
# The real-space cutoff is fixed, so alpha and k_cutoff follow from accuracy
243+
log_accuracy = math.log(self.accuracy)
240244
out = ewald_summation(
241245
positions=state.positions,
242246
charges=charges,
243247
cell=cell,
248+
alpha=math.sqrt(-log_accuracy) / self.cutoff,
249+
k_cutoff=-2.0 * log_accuracy / self.cutoff,
244250
neighbor_list=edge_index,
245251
neighbor_ptr=neighbor_ptr,
246252
neighbor_shifts=unit_shifts,
@@ -294,7 +300,8 @@ class PMEModel(ModelInterface):
294300
295301
Args:
296302
cutoff: Real-space cutoff in Angstrom.
297-
accuracy: Target accuracy for auto-estimated parameters.
303+
accuracy: Target accuracy, which sets the Ewald splitting parameter and the
304+
default mesh together with ``cutoff``.
298305
mesh_spacing: Optional mesh spacing (Angstrom) for automatic mesh sizing.
299306
mesh_dimensions: Explicit FFT mesh dimensions ``(nx, ny, nz)``.
300307
spline_order: B-spline interpolation order. Defaults to 4.
@@ -376,6 +383,8 @@ def forward(self, state: SimState, **_kwargs: object) -> dict[str, torch.Tensor]
376383
positions=state.positions,
377384
charges=charges,
378385
cell=cell,
386+
# The real-space cutoff is fixed, so alpha follows from accuracy
387+
alpha=math.sqrt(-math.log(self.accuracy)) / self.cutoff,
379388
neighbor_list=edge_index,
380389
neighbor_ptr=neighbor_ptr,
381390
neighbor_shifts=unit_shifts,

‎torch_sim/transforms.py‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,9 @@ def minimum_image_displacement(
218218
) -> torch.Tensor:
219219
"""Apply minimum image convention to displacement vectors.
220220
221+
The result is exact for orthogonal and reduced (e.g. Niggli-reduced) cells.
222+
Strongly skewed cells should be reduced first.
223+
221224
Args:
222225
dr (torch.Tensor): Displacement vectors [N, 3] or [N, N, 3].
223226
cell (Optional[torch.Tensor]): Unit cell matrix [3, 3].
@@ -240,7 +243,19 @@ def minimum_image_displacement(
240243
dr_frac -= torch.where(pbc, torch.round(dr_frac), torch.zeros_like(dr_frac))
241244

242245
# Convert back to cartesian
243-
return torch.einsum("ij,...j->...i", cell, dr_frac)
246+
dr = torch.einsum("ij,...j->...i", cell, dr_frac)
247+
248+
# Rounding is only exact for orthogonal cells, so also try the neighboring images
249+
offsets = torch.tensor([-1, 0, 1], device=dr.device, dtype=dr.dtype)
250+
shifts = torch.cartesian_prod(offsets, offsets, offsets) * pbc
251+
mic_dr, min_dist = dr, torch.linalg.vector_norm(dr, dim=-1)
252+
for shift in shifts @ cell.mT:
253+
image = dr + shift
254+
dist = torch.linalg.vector_norm(image, dim=-1)
255+
closer = dist < min_dist
256+
mic_dr = torch.where(closer.unsqueeze(-1), image, mic_dr)
257+
min_dist = torch.where(closer, dist, min_dist)
258+
return mic_dr
244259

245260

246261
def get_pair_displacements(

0 commit comments

Comments
 (0)