diff --git a/CHANGELOG.md b/CHANGELOG.md
index 91f65f5f..e37764b5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -45,6 +45,7 @@ Changelog
* Add a `torsion_window` option, `auto` by default, that changes the torsions and impropers of a perturbable molecule over only part of each stage of the lambda schedule when one of its angles becomes linear at one end state, e.g. for a C=C to C≡C perturbation. Their forces diverge as the angle's atoms become collinear, which crashed simulations at intermediate lambda. `auto` applies it when a non-zero torsion or improper passes through such an angle at the other end state. Simulations started before this option existed must be restarted with `torsion_window` set to `false` [#287](https://github.com/OpenBioSim/somd2/pull/287).
* Runners now work on a copy of the config, so that changes they make, e.g. to the lambda schedule, don't carry over to other runners created from the same config [#287](https://github.com/OpenBioSim/somd2/pull/287).
* Default the GCMC region to a sphere around the perturbed atoms, with a radius and number of ghost waters chosen automatically, via new `auto` defaults for `gcmc_selection`, `gcmc_radius` and `gcmc_num_waters`, and a `gcmc_radius_padding` option. GCMC within the entire simulation box is still available with `gcmc_selection=None` [#291](https://github.com/OpenBioSim/somd2/pull/291).
+* Default the REST2 region to the perturbed atoms and the atoms within `rest2_bonds` bonds of them, via a new `auto` default for `rest2_selection`. All atoms of the perturbable molecules can still be scaled with `rest2_selection=None` [#292](https://github.com/OpenBioSim/somd2/pull/292).
[2026.2.0](https://github.com/openbiosim/somd2/compare/2026.1.0...2026.2.0) - Sep 2026
--------------------------------------------------------------------------------------
diff --git a/README.md b/README.md
index fa28ac45..1cb1084c 100644
--- a/README.md
+++ b/README.md
@@ -619,11 +619,21 @@ perturbations involving conformational changes, e.g. ring flips. It is enabled
with the `--rest2-scale` option, which specifies the "temperature" of the REST2
region relative to the rest of the system.
-By default, the REST2 region comprises *all* atoms in perturbable molecules.
-Atoms in other, non-perturbable molecules can be added with `--rest2-selection`,
-a `Sire` selection string. If the selection includes atoms in perturbable
-molecules, only the selected atoms of those molecules are scaled, so a subset of
-a perturbable molecule can be chosen.
+By default, the REST2 region comprises the perturbed atoms, i.e. atoms whose
+element changes between the end states, including ghost atoms, and heavy atoms
+whose Lennard-Jones parameters change, along with the atoms within
+`--rest2-bonds` bonds of them (2 by default). Torsions are only scaled when all
+four atoms are in the REST2 region, so this includes the torsions about every
+bond to a perturbed atom, while keeping the region, and the change in energy
+between λ windows, small. The resolved selection is logged and written to the
+config file.
+
+A different region can be chosen with `--rest2-selection`, a `Sire` selection
+string. Use `--rest2-selection none` to scale *all* atoms in perturbable
+molecules. Atoms in other, non-perturbable molecules can be added with a
+selection. If the selection includes atoms in perturbable molecules, only the
+selected atoms of those molecules are scaled, so a subset of a perturbable
+molecule can be chosen.
The REST2 schedule is a triangular function that starts and ends at 1.0,
peaking at the value of `--rest2-scale` in the middle of the λ schedule.
diff --git a/src/somd2/_utils/_gcmc.py b/src/somd2/_utils/_gcmc.py
index cc229b0e..9b4ee102 100644
--- a/src/somd2/_utils/_gcmc.py
+++ b/src/somd2/_utils/_gcmc.py
@@ -19,7 +19,7 @@
# along with SOMD2. If not, see .
#####################################################################
-__all__ = ["auto_selection", "selection_geometry", "selection_sites", "ghost_waters"]
+__all__ = ["selection_geometry", "selection_sites", "ghost_waters"]
# The volume of a heavy atom and its hydrogens at protein density, in waters.
_HEAVY_ATOM_WATERS = 0.58
@@ -33,38 +33,6 @@
_SITE_DISTANCE = 4.0
-def perturbed_atoms(mol):
- """
- Return the indices of the atoms of a perturbable molecule that change
- between the end states: atoms whose element changes, including ghost
- atoms, and heavy atoms whose Lennard-Jones parameters change. Hydrogens
- whose Lennard-Jones parameters change are left out, since this is often
- only a change in atom type caused by changes elsewhere in the molecule. If
- no atoms change, then all atoms are returned.
-
- Parameters
- ----------
-
- mol: sire.mol.Molecule
- The perturbable molecule.
-
- Returns
- -------
-
- indices: list of int
- The indices of the perturbed atoms within the molecule.
- """
-
- def changes(atom):
- element = atom.property("element0").symbol()
- if element != atom.property("element1").symbol():
- return True
- return element != "H" and atom.property("LJ0") != atom.property("LJ1")
-
- indices = [i for i, atom in enumerate(mol.atoms()) if changes(atom)]
- return indices or list(range(mol.num_atoms()))
-
-
def vanishing_atoms(mol):
"""
Return the indices of the atoms of a perturbable molecule that vanish in
@@ -100,41 +68,6 @@ def decoupled(atom, end):
]
-def auto_selection(system):
- """
- Return a selection string for the perturbed atoms of the perturbable
- molecules in the system. Perturbable waters and single-atom ions, e.g.
- co-alchemical ions, are left out unless they are the only perturbable
- molecules. Molecules are selected by index, rather than number, so that the
- selection also works for the system reloaded from file.
-
- Parameters
- ----------
-
- system: sire.system.System
- The system containing the perturbable molecules.
-
- Returns
- -------
-
- selection: str
- The selection string.
- """
- perturbable = system.molecules("property is_perturbable")
- try:
- solutes = system.molecules("property is_perturbable and not water")
- except KeyError:
- solutes = []
- solutes = [mol for mol in solutes if mol.num_atoms() > 1] or perturbable
-
- molecules = system.molecules()
- parts = []
- for mol in solutes:
- indices = ",".join(str(i) for i in perturbed_atoms(mol))
- parts.append(f"(molidx {molecules.find(mol)} and atomidx {indices})")
- return " or ".join(parts)
-
-
def _space(system):
"""
Return the periodic space of the system, or None if it isn't periodic.
diff --git a/src/somd2/_utils/_perturbed.py b/src/somd2/_utils/_perturbed.py
new file mode 100644
index 00000000..68034ba2
--- /dev/null
+++ b/src/somd2/_utils/_perturbed.py
@@ -0,0 +1,120 @@
+######################################################################
+# SOMD2: GPU accelerated alchemical free-energy engine.
+#
+# Copyright: 2023-2026
+#
+# Authors: The OpenBioSim Team
+#
+# SOMD2 is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# SOMD2 is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with SOMD2. If not, see .
+#####################################################################
+
+__all__ = ["perturbed_atoms", "perturbed_selection"]
+
+
+def perturbed_atoms(mol):
+ """
+ Return the indices of the atoms of a perturbable molecule that change
+ between the end states: atoms whose element changes, including ghost
+ atoms, and heavy atoms whose Lennard-Jones parameters change. Hydrogens
+ whose Lennard-Jones parameters change are left out, since this is often
+ only a change in atom type caused by changes elsewhere in the molecule. If
+ no atoms change, then all atoms are returned.
+
+ Parameters
+ ----------
+
+ mol: sire.mol.Molecule
+ The perturbable molecule.
+
+ Returns
+ -------
+
+ indices: list of int
+ The indices of the perturbed atoms within the molecule.
+ """
+
+ def changes(atom):
+ element = atom.property("element0").symbol()
+ if element != atom.property("element1").symbol():
+ return True
+ return element != "H" and atom.property("LJ0") != atom.property("LJ1")
+
+ indices = [i for i, atom in enumerate(mol.atoms()) if changes(atom)]
+ return indices or list(range(mol.num_atoms()))
+
+
+def _neighbours(mol, indices, bonds):
+ """
+ Return the indices of the atoms within a number of bonds of the given
+ atoms, in either end state, including the atoms themselves.
+ """
+ from sire.legacy.Mol import AtomIdx as _AtomIdx
+
+ names = ["connectivity0", "connectivity1"]
+ if not all(mol.has_property(name) for name in names):
+ names = ["connectivity"]
+ connectivities = [mol.property(name) for name in names]
+
+ region = set(indices)
+ shell = set(indices)
+ for _ in range(bonds):
+ shell = {
+ n.value()
+ for i in shell
+ for c in connectivities
+ for n in c.connections_to(_AtomIdx(i))
+ } - region
+ region |= shell
+
+ return sorted(region)
+
+
+def perturbed_selection(system, bonds=0):
+ """
+ Return a selection string for the perturbed atoms of the perturbable
+ molecules in the system, and the atoms within a number of bonds of them.
+ Perturbable waters and single-atom ions, e.g. co-alchemical ions, are left
+ out unless they are the only perturbable molecules. Molecules are selected
+ by index, rather than number, so that the selection also works for the
+ system reloaded from file.
+
+ Parameters
+ ----------
+
+ system: sire.system.System
+ The system containing the perturbable molecules.
+
+ bonds: int
+ The number of bonds from the perturbed atoms to extend the selection.
+
+ Returns
+ -------
+
+ selection: str
+ The selection string.
+ """
+ perturbable = system.molecules("property is_perturbable")
+ try:
+ solutes = system.molecules("property is_perturbable and not water")
+ except KeyError:
+ solutes = []
+ solutes = [mol for mol in solutes if mol.num_atoms() > 1] or perturbable
+
+ molecules = system.molecules()
+ parts = []
+ for mol in solutes:
+ indices = _neighbours(mol, perturbed_atoms(mol), bonds)
+ atoms = ",".join(str(i) for i in indices)
+ parts.append(f"(molidx {molecules.find(mol)} and atomidx {atoms})")
+ return " or ".join(parts)
diff --git a/src/somd2/config/_config.py b/src/somd2/config/_config.py
index 9e555cc0..71124890 100644
--- a/src/somd2/config/_config.py
+++ b/src/somd2/config/_config.py
@@ -132,6 +132,7 @@ class Config:
"gcmc_batch_size",
"gcmc_num_attempts",
"gcmc_radius_padding",
+ "rest2_bonds",
"torsion_window",
]
)
@@ -231,7 +232,8 @@ def __init__(
gcmc_num_attempts=10000,
use_dispersion_correction=False,
rest2_scale=1.0,
- rest2_selection=None,
+ rest2_selection="auto",
+ rest2_bonds=2,
softcore_form="auto",
taylor_power=1,
beutler_alpha=0.5,
@@ -702,11 +704,20 @@ def __init__(
rest2_selection: str
A sire selection string for atoms to include in the REST2 region in
addition to any perturbable molecules. For example, "molidx 0 and residx 0,1,2"
- would select atoms from the first three residues of the first molecule. If None,
- then all atoms within perturbable molecules will be included in the REST2 region.
- When atoms within a perturbable molecule are included in the selection, then only
- those atoms will be considered as part of the REST2 region. This allows REST2 to
- be applied to protein mutations.
+ would select atoms from the first three residues of the first molecule. If 'auto'
+ (the default), then the REST2 region contains the perturbed atoms, i.e. atoms
+ whose element changes between the end states, including ghost atoms, and heavy
+ atoms whose Lennard-Jones parameters change, and the atoms within 'rest2_bonds'
+ bonds of them. If None, then all atoms within perturbable molecules will be
+ included in the REST2 region. When atoms within a perturbable molecule are
+ included in the selection, then only those atoms will be considered as part of
+ the REST2 region. This allows REST2 to be applied to protein mutations.
+
+ rest2_bonds: int
+ The number of bonds from the perturbed atoms to extend the REST2 region when
+ 'rest2_selection' is 'auto'. Torsions are only scaled when all four atoms are in
+ the REST2 region, so the default of 2 includes the torsions about every bond to
+ a perturbed atom.
softcore_form: str
The soft-core potential form to use for alchemical interactions. Valid
@@ -926,6 +937,7 @@ def __init__(
self.use_dispersion_correction = use_dispersion_correction
self.rest2_scale = rest2_scale
self.rest2_selection = rest2_selection
+ self.rest2_bonds = rest2_bonds
self.restart = restart
self.use_backup = use_backup
self.softcore_form = softcore_form
@@ -2888,8 +2900,32 @@ def rest2_selection(self, rest2_selection):
if rest2_selection is not None:
if not isinstance(rest2_selection, str):
raise TypeError("'rest2_selection' must be of type 'str'")
+ # Allow all atoms of the perturbable molecules to be chosen from the command line.
+ if rest2_selection.strip().lower() == "none":
+ rest2_selection = None
+ elif rest2_selection.strip().lower() == "auto":
+ rest2_selection = "auto"
self._rest2_selection = rest2_selection
+ @property
+ def rest2_bonds(self):
+ return self._rest2_bonds
+
+ @rest2_bonds.setter
+ def rest2_bonds(self, rest2_bonds):
+ if isinstance(rest2_bonds, bool) or (
+ isinstance(rest2_bonds, float) and not rest2_bonds.is_integer()
+ ):
+ raise ValueError("'rest2_bonds' must be an integer")
+ if not isinstance(rest2_bonds, int):
+ try:
+ rest2_bonds = int(rest2_bonds)
+ except Exception:
+ raise ValueError("'rest2_bonds' must be an integer")
+ if rest2_bonds < 0:
+ raise ValueError("'rest2_bonds' must be greater than or equal to 0")
+ self._rest2_bonds = rest2_bonds
+
@property
def restart(self):
return self._restart
diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py
index d2159434..49e117f1 100644
--- a/src/somd2/runner/_base.py
+++ b/src/somd2/runner/_base.py
@@ -898,6 +898,26 @@ def _set_schedule(self, pert_idxs, ion_indices):
is_rest2 = True
_logger.info(f"REST2 scaling factors: {self._rest2_scale_factors}")
+ # Resolve the automatic REST2 region, which is only used with REST2.
+ if self._config.rest2_selection == "auto":
+ if is_rest2:
+ from .._utils._perturbed import perturbed_selection
+
+ try:
+ self._config.rest2_selection = perturbed_selection(
+ self._system, self._config.rest2_bonds
+ )
+ except Exception as e:
+ msg = (
+ f"Unable to select the perturbed atoms for the REST2 region: {e}. "
+ "Set 'rest2_selection' explicitly."
+ )
+ _logger.error(msg)
+ raise ValueError(msg) from e
+ _logger.info(f"REST2 region: '{self._config.rest2_selection}'")
+ else:
+ self._config.rest2_selection = None
+
# Make sure the REST2 selection is valid.
if self._config.rest2_selection is not None:
try:
@@ -1077,17 +1097,13 @@ def _set_gcmc_region(self):
are resolved from the input system, so a restart resolves them to the
same values.
"""
- from .._utils._gcmc import (
- auto_selection,
- ghost_waters,
- selection_geometry,
- selection_sites,
- )
+ from .._utils._gcmc import ghost_waters, selection_geometry, selection_sites
+ from .._utils._perturbed import perturbed_selection
is_auto = self._config.gcmc_selection == "auto"
if is_auto:
try:
- self._config.gcmc_selection = auto_selection(self._system)
+ self._config.gcmc_selection = perturbed_selection(self._system)
except Exception as e:
msg = (
f"Unable to select the perturbed atoms for the GCMC sphere: {e}. "
@@ -2600,6 +2616,13 @@ def _compare_configs(config1, config2):
"'false' to restart it."
)
+ if not config1.get("rest2_selection") and config2.get("rest2_selection"):
+ raise ValueError(
+ "The simulation was started with a REST2 region containing all "
+ "atoms of the perturbable molecules. Set 'rest2_selection' to "
+ "None to restart it."
+ )
+
allowed_diffs = _Config._restart_allowed_diffs
no_gcmc = not config1.get("gcmc") and not config2.get("gcmc")
for key in config1.keys():
diff --git a/tests/_utils/test_gcmc.py b/tests/_utils/test_gcmc.py
index 6f7bf87e..256ee948 100644
--- a/tests/_utils/test_gcmc.py
+++ b/tests/_utils/test_gcmc.py
@@ -4,88 +4,12 @@
from somd2._utils._gcmc import (
_minimum_image,
_positions,
- auto_selection,
ghost_waters,
- perturbed_atoms,
selection_geometry,
selection_sites,
vanishing_atoms,
)
-
-
-def test_perturbed_atoms(ethane_methanol):
- """
- Make sure that atoms whose element changes, and heavy atoms whose LJ
- parameters change, are perturbed, but not hydrogens whose LJ parameters
- change.
- """
- mol = ethane_methanol.molecules("property is_perturbable")[0]
- indices = perturbed_atoms(mol)
-
- hydrogens = []
- for i, atom in enumerate(mol.atoms()):
- element0 = atom.property("element0").symbol()
- element1 = atom.property("element1").symbol()
- lj_changes = atom.property("LJ0") != atom.property("LJ1")
- changed = element0 != element1 or (element0 != "H" and lj_changes)
- assert (i in indices) == changed
- if element0 == element1 == "H" and lj_changes:
- hydrogens.append(i)
-
- # Some hydrogens change LJ parameters without being perturbed.
- assert hydrogens
- assert 0 < len(indices) < mol.num_atoms()
-
-
-def test_perturbed_atoms_decoupled(abfe_charge_change_mols):
- """
- Make sure that every heavy atom of a decoupled ligand is perturbed.
- """
- mol = abfe_charge_change_mols.molecules("property is_perturbable")[0]
- heavy = [
- i
- for i, atom in enumerate(mol.atoms())
- if atom.property("element0").symbol() != "H"
- ]
- assert perturbed_atoms(mol) == heavy
-
-
-def test_auto_selection_reloaded(ethane_methanol, tmp_path):
- """
- Make sure that the selection picks the same atoms from the system reloaded
- from file, as the viewer does, which has new molecule numbers.
- """
- selection = auto_selection(ethane_methanol)
- indices = ethane_methanol.atoms().find(ethane_methanol[selection].atoms())
-
- mol = ethane_methanol.molecules("property is_perturbable")[0]
- offset = ethane_methanol.atoms().find(mol.atoms()[0])
- assert indices == [offset + i for i in perturbed_atoms(mol)]
-
- reference = sr.morph.extract_reference(ethane_methanol)
- files = sr.save(reference, str(tmp_path / "system"), format=["prm7", "rst7"])
- reloaded = sr.load(files)
- assert reloaded.atoms().find(reloaded[selection].atoms()) == indices
-
-
-def test_auto_selection_skips_perturbable_waters(ethane_methanol):
- """
- Make sure that perturbable waters and single-atom ions, e.g. co-alchemical
- ions, don't move the GCMC sphere away from the perturbable solute.
- """
- water = ethane_methanol["water"].molecules()[0]
- system = ethane_methanol.clone()
- system.update(water.edit().set_property("is_perturbable", True).commit())
-
- assert auto_selection(system) == auto_selection(ethane_methanol)
-
- # A single-atom molecule, standing in for a perturbable ion.
- ion = water.edit().remove(sr.legacy.Mol.AtomIdx(2)).remove(sr.legacy.Mol.AtomIdx(1))
- ion = ion.commit().edit().renumber().set_property("is_perturbable", True).commit()
- system = ethane_methanol.clone()
- system.add(ion)
-
- assert auto_selection(system) == auto_selection(ethane_methanol)
+from somd2._utils._perturbed import perturbed_selection
def test_vanishing_atoms(ethane_methanol, abfe_charge_change_mols):
@@ -110,7 +34,7 @@ def test_selection_geometry(ethane_methanol):
"""
Make sure the extent covers the selected atoms in both end states.
"""
- selection = auto_selection(ethane_methanol)
+ selection = perturbed_selection(ethane_methanol)
centre, extent = selection_geometry(ethane_methanol, selection)
assert 0 < extent < 5
assert centre.shape == (3,)
@@ -127,7 +51,7 @@ def test_selection_geometry_periodic(ethane_methanol):
"""
import numpy as np
- selection = auto_selection(ethane_methanol)
+ selection = perturbed_selection(ethane_methanol)
centre, extent = selection_geometry(ethane_methanol, selection)
# Move one atom of the molecule by a box vector in both end states.
@@ -189,7 +113,7 @@ def test_selection_sites(ethane_methanol):
"""
import numpy as np
- selection = auto_selection(ethane_methanol)
+ selection = perturbed_selection(ethane_methanol)
assert len(selection_sites(ethane_methanol, selection)) == 1
# Add the oxygen of a water far from the perturbable molecule.
@@ -213,7 +137,7 @@ def test_ghost_waters(ethane_methanol):
Make sure the ghost waters cover the free volume of the sphere, which is
small in water, plus a margin.
"""
- selection = auto_selection(ethane_methanol)
+ selection = perturbed_selection(ethane_methanol)
centre, extent = selection_geometry(ethane_methanol, selection)
volume = 30.543
diff --git a/tests/_utils/test_perturbed.py b/tests/_utils/test_perturbed.py
new file mode 100644
index 00000000..85329c44
--- /dev/null
+++ b/tests/_utils/test_perturbed.py
@@ -0,0 +1,143 @@
+import sire as sr
+
+from somd2._utils._perturbed import perturbed_atoms, perturbed_selection
+
+
+def test_perturbed_atoms(ethane_methanol):
+ """
+ Make sure that atoms whose element changes, and heavy atoms whose LJ
+ parameters change, are perturbed, but not hydrogens whose LJ parameters
+ change.
+ """
+ mol = ethane_methanol.molecules("property is_perturbable")[0]
+ indices = perturbed_atoms(mol)
+
+ hydrogens = []
+ for i, atom in enumerate(mol.atoms()):
+ element0 = atom.property("element0").symbol()
+ element1 = atom.property("element1").symbol()
+ lj_changes = atom.property("LJ0") != atom.property("LJ1")
+ changed = element0 != element1 or (element0 != "H" and lj_changes)
+ assert (i in indices) == changed
+ if element0 == element1 == "H" and lj_changes:
+ hydrogens.append(i)
+
+ # Some hydrogens change LJ parameters without being perturbed.
+ assert hydrogens
+ assert 0 < len(indices) < mol.num_atoms()
+
+
+def test_perturbed_atoms_decoupled(abfe_charge_change_mols):
+ """
+ Make sure that every heavy atom of a decoupled ligand is perturbed.
+ """
+ mol = abfe_charge_change_mols.molecules("property is_perturbable")[0]
+ heavy = [
+ i
+ for i, atom in enumerate(mol.atoms())
+ if atom.property("element0").symbol() != "H"
+ ]
+ assert perturbed_atoms(mol) == heavy
+
+
+def test_perturbed_selection_reloaded(ethane_methanol, tmp_path):
+ """
+ Make sure that the selection picks the same atoms from the system reloaded
+ from file, as the viewer does, which has new molecule numbers.
+ """
+ selection = perturbed_selection(ethane_methanol)
+ indices = ethane_methanol.atoms().find(ethane_methanol[selection].atoms())
+
+ mol = ethane_methanol.molecules("property is_perturbable")[0]
+ offset = ethane_methanol.atoms().find(mol.atoms()[0])
+ assert indices == [offset + i for i in perturbed_atoms(mol)]
+
+ reference = sr.morph.extract_reference(ethane_methanol)
+ files = sr.save(reference, str(tmp_path / "system"), format=["prm7", "rst7"])
+ reloaded = sr.load(files)
+ assert reloaded.atoms().find(reloaded[selection].atoms()) == indices
+
+
+def test_perturbed_selection_skips_perturbable_waters(ethane_methanol):
+ """
+ Make sure that perturbable waters and single-atom ions, e.g. co-alchemical
+ ions, aren't selected alongside the perturbable solute.
+ """
+ water = ethane_methanol["water"].molecules()[0]
+ system = ethane_methanol.clone()
+ system.update(water.edit().set_property("is_perturbable", True).commit())
+
+ assert perturbed_selection(system) == perturbed_selection(ethane_methanol)
+
+ # A single-atom molecule, standing in for a perturbable ion.
+ ion = water.edit().remove(sr.legacy.Mol.AtomIdx(2)).remove(sr.legacy.Mol.AtomIdx(1))
+ ion = ion.commit().edit().renumber().set_property("is_perturbable", True).commit()
+ system = ethane_methanol.clone()
+ system.add(ion)
+
+ assert perturbed_selection(system) == perturbed_selection(ethane_methanol)
+
+
+def test_perturbed_selection_bonds(ethane_methanol):
+ """
+ Make sure the selection extends by the number of bonds, and that two bonds
+ include every proper torsion about a bond to a perturbed atom.
+ """
+ mol = ethane_methanol.molecules("property is_perturbable")[0]
+ perturbed = set(perturbed_atoms(mol))
+
+ def selected(bonds):
+ selection = perturbed_selection(ethane_methanol, bonds)
+ offset = ethane_methanol.atoms().find(mol.atoms()[0])
+ atoms = ethane_methanol[selection].atoms()
+ return {i - offset for i in ethane_methanol.atoms().find(atoms)}
+
+ assert selected(0) == perturbed
+ assert selected(0) <= selected(1) <= selected(2)
+ assert selected(2) > perturbed
+
+ region = selected(2)
+ info = mol.info()
+ for dihedral in mol.property("dihedral0").potentials():
+ idx = [
+ info.atom_idx(a).value()
+ for a in (
+ dihedral.atom0(),
+ dihedral.atom1(),
+ dihedral.atom2(),
+ dihedral.atom3(),
+ )
+ ]
+ if {idx[1], idx[2]} & perturbed:
+ assert set(idx) <= region
+
+
+def test_perturbed_selection_ring_break(ring_break_mols):
+ """
+ Make sure that bonds in either end state are followed, so that a bond only
+ present in one end state links its atoms.
+ """
+ mol = ring_break_mols.molecules("property is_perturbable")[0]
+ c0 = mol.property("connectivity0")
+ c1 = mol.property("connectivity1")
+ from sire.legacy.Mol import AtomIdx
+
+ # A bond that only exists in one end state.
+ only = [
+ (i, j.value())
+ for a, b in ((c0, c1), (c1, c0))
+ for i in range(mol.num_atoms())
+ for j in a.connections_to(AtomIdx(i))
+ if j not in b.connections_to(AtomIdx(i))
+ ]
+ assert only
+
+ from somd2._utils._perturbed import _neighbours
+
+ # Make the default connectivity one that lacks the bond, so that it can
+ # only be found through the end-state connectivities.
+ for i, j in only:
+ default = c1 if j not in c1.connections_to(AtomIdx(i)) else c0
+ edited = mol.edit().set_property("connectivity", default).commit()
+ assert j not in [n.value() for n in default.connections_to(AtomIdx(i))]
+ assert j in _neighbours(edited, [i], 1)
diff --git a/tests/runner/test_config.py b/tests/runner/test_config.py
index 64806e5e..7b6bb858 100644
--- a/tests/runner/test_config.py
+++ b/tests/runner/test_config.py
@@ -492,3 +492,55 @@ def test_gcmc_region_options():
new = Config(gcmc=True, pressure=None, gcmc_radius="4 A", gcmc_num_waters=20)
with pytest.raises(ValueError):
RunnerBase._compare_configs(old.as_dict(), new.as_dict())
+
+
+def test_rest2_region_options(ethane_methanol):
+ """
+ Validate the REST2 region options, and that the automatic region is
+ resolved and recorded when REST2 is used, and left unset otherwise.
+ """
+ from pathlib import Path
+
+ import pytest
+
+ from somd2._utils._perturbed import perturbed_selection
+
+ config = Config()
+ assert config.rest2_selection == "auto"
+ assert config.rest2_bonds == 2
+
+ config.rest2_selection = "None"
+ assert config.rest2_selection is None
+ config.rest2_selection = "AUTO"
+ assert config.rest2_selection == "auto"
+ config.rest2_bonds = "3"
+ assert config.rest2_bonds == 3
+
+ for bonds in (-1, "two", 2.5, True):
+ with pytest.raises(ValueError):
+ config.rest2_bonds = bonds
+
+ # A REST2 run started with the previous default region can't silently
+ # switch to the automatic region on restart.
+ from somd2.runner._base import RunnerBase
+
+ old = Config(rest2_scale=2.0, rest2_selection=None).as_dict()
+ new = Config(rest2_scale=2.0, rest2_selection="molidx 0 and atomidx 0").as_dict()
+ with pytest.raises(ValueError, match="'rest2_selection' to None"):
+ RunnerBase._compare_configs(old, new)
+
+ for scale, expected in (
+ (2.0, perturbed_selection(ethane_methanol, 2)),
+ (1.0, None),
+ ):
+ with tempfile.TemporaryDirectory() as tmpdir:
+ runner = Runner(
+ ethane_methanol,
+ Config(platform="cpu", output_directory=tmpdir, rest2_scale=scale),
+ )
+ assert runner._config.rest2_selection == expected
+
+ written = Config.from_yaml(str(Path(tmpdir) / "config.yaml"))
+ assert written.rest2_selection == expected
+
+ somd2._logger.remove()
diff --git a/tests/runner/test_gcmc.py b/tests/runner/test_gcmc.py
index 5577aa47..228d57cc 100644
--- a/tests/runner/test_gcmc.py
+++ b/tests/runner/test_gcmc.py
@@ -184,7 +184,8 @@ def test_runner_gcmc_auto_region(ethane_methanol):
"""
pytest.importorskip("loch")
- from somd2._utils._gcmc import auto_selection, ghost_waters, selection_geometry
+ from somd2._utils._gcmc import ghost_waters, selection_geometry
+ from somd2._utils._perturbed import perturbed_selection
with tempfile.TemporaryDirectory() as tmpdir:
config = Config(
@@ -202,7 +203,7 @@ def test_runner_gcmc_auto_region(ethane_methanol):
runner = Runner(ethane_methanol, config)
- selection = auto_selection(ethane_methanol)
+ selection = perturbed_selection(ethane_methanol)
centre, extent = selection_geometry(ethane_methanol, selection)
resolved = runner._config
assert resolved.gcmc_selection == selection