|
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
| 5 | +import math |
5 | 6 | import traceback |
6 | 7 |
|
7 | 8 | import pytest |
|
11 | 12 | import torch_sim as ts |
12 | 13 | from tests.conftest import DEVICE, DTYPE |
13 | 14 | from tests.models.conftest import make_validate_model_outputs_test |
| 15 | +from torch_sim.units import UnitConversion |
14 | 16 |
|
15 | 17 |
|
16 | 18 | try: |
@@ -195,6 +197,69 @@ def test_ewald_pme_energy_agreement() -> None: |
195 | 197 | ) |
196 | 198 |
|
197 | 199 |
|
| 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 | + |
198 | 263 | def test_sum_model_lj_plus_dsf() -> None: |
199 | 264 | """LJ + DSF should be additive through SumModel.""" |
200 | 265 | from torch_sim.models.interface import SumModel |
|
0 commit comments