From 518b8b4a125709f908462f227cb62a454217e155 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Tue, 17 Nov 2026 09:23:27 +0000 Subject: [PATCH 1/4] Include perturbed ring systems in the REST2 region. --- CHANGELOG.md | 1 + README.md | 12 ++++--- src/somd2/_utils/_perturbed.py | 65 ++++++++++++++++++++++++++++++---- src/somd2/config/_config.py | 4 +-- src/somd2/runner/_base.py | 2 +- tests/_utils/test_perturbed.py | 37 ++++++++++++++++++- 6 files changed, 106 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 580562ba..98e4129d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,7 @@ Changelog * 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). * Take the terminal ring flip angle of a distorted ring from the number of neighbours of its pivot, rather than from RDKit, which assigned 120° to aromatic rings when MDAnalysis wasn't available [#294](https://github.com/OpenBioSim/somd2/pull/294). +* Include whole ring systems containing perturbed atoms in the automatic REST2 region, so that the torsions about a perturbed ring's bonds to the rest of the molecule are scaled [#XXX](https://github.com/OpenBioSim/somd2/pull/XXX). [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 5916b115..079267fe 100644 --- a/README.md +++ b/README.md @@ -621,11 +621,13 @@ region relative to the rest of the system. 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 +whose Lennard-Jones parameters change, along with any ring systems that contain +them or are bonded to them, and the atoms within `--rest2-bonds` bonds of these +(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, and +about the bonds joining a perturbed ring to the rest of the molecule, e.g. for +a ring that flips, 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 diff --git a/src/somd2/_utils/_perturbed.py b/src/somd2/_utils/_perturbed.py index 68034ba2..3050ce91 100644 --- a/src/somd2/_utils/_perturbed.py +++ b/src/somd2/_utils/_perturbed.py @@ -54,6 +54,52 @@ def changes(atom): return indices or list(range(mol.num_atoms())) +def _connectivities(mol): + """ + Return the connectivity of each end state of a perturbable molecule, or its + single connectivity if it doesn't change. + """ + names = ["connectivity0", "connectivity1"] + if not all(mol.has_property(name) for name in names): + names = ["connectivity"] + return [mol.property(name) for name in names] + + +def _ring_systems(mol, indices): + """ + Return the given atoms plus the atoms of every ring system, in either end + state, that contains one of them or is bonded to one of them. A ring system + is followed through ring bonds only, so fused rings are included, but rings + joined by a single bond, e.g. a biaryl, are not. + """ + from sire.legacy.Mol import AtomIdx as _AtomIdx + + region = set(indices) + for connectivity in _connectivities(mol): + seeds = set() + for i in indices: + atom = _AtomIdx(i) + if connectivity.in_ring(atom): + seeds.add(i) + seeds.update( + n.value() + for n in connectivity.connections_to(atom) + if connectivity.in_ring(n) + ) + + seen = set(seeds) + stack = list(seeds) + while stack: + atom = _AtomIdx(stack.pop()) + for n in connectivity.connections_to(atom): + if n.value() not in seen and connectivity.in_ring(atom, n): + seen.add(n.value()) + stack.append(n.value()) + region |= seen + + return sorted(region) + + def _neighbours(mol, indices, bonds): """ Return the indices of the atoms within a number of bonds of the given @@ -61,10 +107,7 @@ def _neighbours(mol, indices, bonds): """ 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] + connectivities = _connectivities(mol) region = set(indices) shell = set(indices) @@ -80,10 +123,14 @@ def _neighbours(mol, indices, bonds): return sorted(region) -def perturbed_selection(system, bonds=0): +def perturbed_selection(system, bonds=0, rings=False): """ 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. + With 'rings', ring systems containing a perturbed atom, or bonded to one, + are included whole before the selection is extended, so that a perturbed + ring and the torsions about its bonds to the rest of the molecule are + covered. 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 @@ -98,6 +145,9 @@ def perturbed_selection(system, bonds=0): bonds: int The number of bonds from the perturbed atoms to extend the selection. + rings: bool + Whether to include the ring systems of the perturbed atoms whole. + Returns ------- @@ -114,7 +164,10 @@ def perturbed_selection(system, bonds=0): molecules = system.molecules() parts = [] for mol in solutes: - indices = _neighbours(mol, perturbed_atoms(mol), bonds) + indices = perturbed_atoms(mol) + if rings: + indices = _ring_systems(mol, indices) + indices = _neighbours(mol, indices, 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 2f4b68ba..4cd8dd21 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -709,8 +709,8 @@ def __init__( 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 + atoms whose Lennard-Jones parameters change, any ring systems that contain + them or are bonded to them, and the atoms within 'rest2_bonds' bonds of these. 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. diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index 65aa81ec..f7e3582d 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -905,7 +905,7 @@ def _set_schedule(self, pert_idxs, ion_indices): try: self._config.rest2_selection = perturbed_selection( - self._system, self._config.rest2_bonds + self._system, self._config.rest2_bonds, rings=True ) except Exception as e: msg = ( diff --git a/tests/_utils/test_perturbed.py b/tests/_utils/test_perturbed.py index 85329c44..d2293a53 100644 --- a/tests/_utils/test_perturbed.py +++ b/tests/_utils/test_perturbed.py @@ -1,6 +1,6 @@ import sire as sr -from somd2._utils._perturbed import perturbed_atoms, perturbed_selection +from somd2._utils._perturbed import _ring_systems, perturbed_atoms, perturbed_selection def test_perturbed_atoms(ethane_methanol): @@ -141,3 +141,38 @@ def test_perturbed_selection_ring_break(ring_break_mols): 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) + + +def test_ring_systems(diphenylethane_mols): + """ + A ring is included whole when one of its atoms, or an atom bonded to it, is + given, but rings joined only through other atoms are not. + """ + from sire.legacy.Mol import AtomIdx + + mol = diphenylethane_mols.molecules("property is_perturbable")[0] + c = mol.property("connectivity") + rings = [i for i in range(mol.num_atoms()) if c.in_ring(AtomIdx(i))] + + # One ring atom gives its whole ring and nothing of the other ring. + first = _ring_systems(mol, [rings[0]]) + ring = [i for i in first if c.in_ring(AtomIdx(i))] + assert len(ring) == 6 + assert set(rings) - set(ring) + + # An atom bonded to the ring, but not in it, also brings in the ring. + outside = next( + n.value() + for i in ring + for n in c.connections_to(AtomIdx(i)) + if not c.in_ring(n) + ) + assert set(ring) | {outside} <= set(_ring_systems(mol, [outside])) + + +def test_perturbed_selection_rings_without_rings(ethane_methanol): + """Including ring systems changes nothing for a molecule without rings.""" + for bonds in (0, 2): + assert perturbed_selection(ethane_methanol, bonds, rings=True) == ( + perturbed_selection(ethane_methanol, bonds) + ) From 4a1428d91ed59c1bde229a2a161cefafbde4190c Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Tue, 17 Nov 2026 09:23:30 +0000 Subject: [PATCH 2/4] Add an exponential REST2 profile. --- CHANGELOG.md | 1 + README.md | 11 +++++++---- src/somd2/_utils/_schedules.py | 34 ++++++++++++++++++++++++++++++++++ src/somd2/_viewer/_data.py | 11 +++++++---- src/somd2/config/_config.py | 27 +++++++++++++++++++++++++++ src/somd2/runner/_base.py | 15 +++++++-------- tests/runner/test_config.py | 5 +++++ tests/runner/test_repex.py | 20 ++++++++++++++++++++ tests/schedules/test_rest2.py | 34 ++++++++++++++++++++++++++++++++++ 9 files changed, 142 insertions(+), 16 deletions(-) create mode 100644 tests/schedules/test_rest2.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 98e4129d..c3c14e1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,7 @@ Changelog * 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). * Take the terminal ring flip angle of a distorted ring from the number of neighbours of its pivot, rather than from RDKit, which assigned 120° to aromatic rings when MDAnalysis wasn't available [#294](https://github.com/OpenBioSim/somd2/pull/294). * Include whole ring systems containing perturbed atoms in the automatic REST2 region, so that the torsions about a perturbed ring's bonds to the rest of the molecule are scaled [#XXX](https://github.com/OpenBioSim/somd2/pull/XXX). +* Add a `rest2_profile` option, which can be set to `exponential` for a geometric ladder of REST2 scale factors rather than a linear one [#XXX](https://github.com/OpenBioSim/somd2/pull/XXX). [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 079267fe..5b3e8c73 100644 --- a/README.md +++ b/README.md @@ -637,10 +637,13 @@ 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. -Passing multiple values to `--rest2-scale` gives full control of the schedule, -in which case there must be one value for each λ window. +The REST2 schedule starts and ends at 1.0, peaking at the value of +`--rest2-scale` in the middle of the λ schedule. By default it rises linearly. +With `--rest2-profile exponential`, each step instead multiplies the scale +factor by the same ratio, giving a geometric ladder of effective temperatures, +which helps sampling propagate between windows when a large scale factor is +used. Passing multiple values to `--rest2-scale` gives full control of the +schedule, in which case there must be one value for each λ window. diff --git a/src/somd2/_utils/_schedules.py b/src/somd2/_utils/_schedules.py index 61a4f160..c72fa452 100644 --- a/src/somd2/_utils/_schedules.py +++ b/src/somd2/_utils/_schedules.py @@ -26,6 +26,7 @@ "windowed_torsions", "ring_break_morph", "reverse_ring_break_morph", + "rest2_scale_factors", ] @@ -514,3 +515,36 @@ def close(a, b): ) return s + + +def rest2_scale_factors(scale, lambda_values, profile="linear"): + """ + Return the REST2 scale factor at each lambda value, rising from 1.0 at the + end states to 'scale' at lambda = 0.5. + + Parameters + ---------- + + scale: float + The scale factor at lambda = 0.5. + + lambda_values: list of float + The lambda values. + + profile: str + How the scale factor rises: "linear", or "exponential", where each + step multiplies the scale factor by the same ratio, i.e. a geometric + ladder of effective temperatures. + + Returns + ------- + + factors: list of float + The scale factor at each lambda value. + """ + fractions = [1.0 - 2.0 * abs(lam - 0.5) for lam in lambda_values] + if profile == "linear": + return [1.0 + (scale - 1.0) * f for f in fractions] + if profile == "exponential": + return [scale**f for f in fractions] + raise ValueError(f"Unknown REST2 profile: {profile}") diff --git a/src/somd2/_viewer/_data.py b/src/somd2/_viewer/_data.py index c08935ef..06dd3651 100644 --- a/src/somd2/_viewer/_data.py +++ b/src/somd2/_viewer/_data.py @@ -1274,10 +1274,13 @@ def load(): rest2 = config.get("rest2_scale") if rest2 is not None: if isinstance(rest2, (int, float)): - factors = [ - 1.0 + (float(rest2) - 1.0) * (1.0 - 2.0 * abs(lam - 0.5)) - for lam in lambda_energy - ] + from .._utils._schedules import rest2_scale_factors + + factors = rest2_scale_factors( + float(rest2), + lambda_energy, + config.get("rest2_profile") or "linear", + ) else: factors = [float(x) for x in rest2] if len(factors) == len(lambda_energy) and any( diff --git a/src/somd2/config/_config.py b/src/somd2/config/_config.py index 4cd8dd21..80ed967b 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -76,6 +76,7 @@ class Config: "log_level": [level.lower() for level in _logger._core.levels], "softcore_form": ["auto", "zacharias", "taylor", "beutler"], "torsion_window": ["auto", "true", "false"], + "rest2_profile": ["linear", "exponential"], "precision": ["single", "mixed", "double"], } @@ -233,6 +234,7 @@ def __init__( gcmc_num_attempts=10000, use_dispersion_correction=False, rest2_scale=1.0, + rest2_profile="linear", rest2_selection="auto", rest2_bonds=2, softcore_form="auto", @@ -703,6 +705,14 @@ def __init__( values are used, then the number should match the number of lambda windows at which energies are sampled. + rest2_profile: str + How a single 'rest2_scale' rises from 1.0 at the end states to its value at + lambda = 0.5: "linear" (the default), or "exponential", where each step + multiplies the scale factor by the same ratio. The exponential profile gives a + geometric ladder of effective temperatures, which helps sampling propagate + between windows when a large scale factor is used. It has no effect when + 'rest2_scale' is a list. + 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" @@ -938,6 +948,7 @@ def __init__( self.gcmc_num_attempts = gcmc_num_attempts self.use_dispersion_correction = use_dispersion_correction self.rest2_scale = rest2_scale + self.rest2_profile = rest2_profile self.rest2_selection = rest2_selection self.rest2_bonds = rest2_bonds self.restart = restart @@ -2909,6 +2920,22 @@ def rest2_selection(self, rest2_selection): rest2_selection = "auto" self._rest2_selection = rest2_selection + @property + def rest2_profile(self): + return self._rest2_profile + + @rest2_profile.setter + def rest2_profile(self, rest2_profile): + if not isinstance(rest2_profile, str): + raise TypeError("'rest2_profile' must be of type 'str'") + rest2_profile = rest2_profile.lower().replace(" ", "") + if rest2_profile not in self._choices["rest2_profile"]: + raise ValueError( + "'rest2_profile' not recognised. Valid options are: " + f"{', '.join(self._choices['rest2_profile'])}" + ) + self._rest2_profile = rest2_profile + @property def rest2_bonds(self): return self._rest2_bonds diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index f7e3582d..9409d5e3 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -858,14 +858,13 @@ def _set_schedule(self, pert_idxs, ion_indices): # Single value. Interpolate between 1.0 at the end states and rest2_scale # at lambda = 0.5. if isinstance(self._config.rest2_scale, float): - scale_factors = [] - for lambda_value in self._lambda_energy: - scale_factors.append( - 1.0 - + (self._config.rest2_scale - 1.0) - * (1.0 - 2.0 * abs(lambda_value - 0.5)) - ) - self._rest2_scale_factors = scale_factors + from .._utils._schedules import rest2_scale_factors + + self._rest2_scale_factors = rest2_scale_factors( + self._config.rest2_scale, + self._lambda_energy, + self._config.rest2_profile, + ) else: if len(self._config.rest2_scale) != len(self._lambda_energy): msg = f"Length of 'rest2_scale' must match the number of {_lam_sym} values." diff --git a/tests/runner/test_config.py b/tests/runner/test_config.py index 7b6bb858..5f887261 100644 --- a/tests/runner/test_config.py +++ b/tests/runner/test_config.py @@ -508,6 +508,11 @@ def test_rest2_region_options(ethane_methanol): config = Config() assert config.rest2_selection == "auto" assert config.rest2_bonds == 2 + assert config.rest2_profile == "linear" + config.rest2_profile = "Exponential" + assert config.rest2_profile == "exponential" + with pytest.raises(ValueError): + config.rest2_profile = "cubic" config.rest2_selection = "None" assert config.rest2_selection is None diff --git a/tests/runner/test_repex.py b/tests/runner/test_repex.py index 21180ea1..06575962 100644 --- a/tests/runner/test_repex.py +++ b/tests/runner/test_repex.py @@ -710,6 +710,26 @@ def test_rest2_scale(ethane_methanol, rest2_scale, is_valid): runner = RunnerBase(ethane_methanol, Config(**config)) +def test_rest2_profile(ethane_methanol): + """The runner uses the chosen profile for a single REST2 scale factor.""" + from somd2._utils._schedules import rest2_scale_factors + + for profile in ("linear", "exponential"): + with tempfile.TemporaryDirectory() as tmpdir: + config = Config( + output_directory=tmpdir, + platform="CPU", + max_threads=1, + num_lambda=5, + replica_exchange=True, + rest2_scale=4.0, + rest2_profile=profile, + ) + runner = RunnerBase(ethane_methanol, config) + expected = rest2_scale_factors(4.0, runner._lambda_energy, profile) + assert runner._rest2_scale_factors == pytest.approx(expected) + + @pytest.mark.parametrize( "rest2_selection, is_valid", [ diff --git a/tests/schedules/test_rest2.py b/tests/schedules/test_rest2.py new file mode 100644 index 00000000..478e05ee --- /dev/null +++ b/tests/schedules/test_rest2.py @@ -0,0 +1,34 @@ +import math + +import pytest + +from somd2._utils._schedules import rest2_scale_factors + + +@pytest.mark.parametrize("profile", ["linear", "exponential"]) +def test_rest2_scale_factors_ends(profile): + """Both profiles are 1.0 at the end states and the scale at lambda = 0.5.""" + factors = rest2_scale_factors(4.0, [0.0, 0.25, 0.5, 0.75, 1.0], profile) + assert factors[0] == pytest.approx(1.0) + assert factors[2] == pytest.approx(4.0) + assert factors[4] == pytest.approx(1.0) + assert factors[1] == pytest.approx(factors[3]) + + +def test_rest2_scale_factors_profiles(): + """The linear profile rises in equal steps, the exponential one by equal ratios.""" + lambdas = [i / 10 for i in range(6)] + + linear = rest2_scale_factors(4.0, lambdas, "linear") + steps = [b - a for a, b in zip(linear, linear[1:])] + assert steps == pytest.approx([steps[0]] * len(steps)) + + exponential = rest2_scale_factors(4.0, lambdas, "exponential") + ratios = [b / a for a, b in zip(exponential, exponential[1:])] + assert ratios == pytest.approx([4.0 ** (1 / 5)] * len(ratios)) + assert math.prod(ratios) == pytest.approx(4.0) + + +def test_rest2_scale_factors_unknown_profile(): + with pytest.raises(ValueError): + rest2_scale_factors(2.0, [0.0, 1.0], "cubic") From f60d3d63b75f6816eec27a05f57da3496b65d090 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Tue, 17 Nov 2026 09:32:10 +0000 Subject: [PATCH 3/4] Limit REST2 ring systems to small rings and warn about an unused profile. --- CHANGELOG.md | 4 +-- src/somd2/_utils/_perturbed.py | 61 +++++++++++++++++++++++----------- src/somd2/config/_config.py | 3 +- src/somd2/runner/_base.py | 5 +++ tests/_utils/test_perturbed.py | 45 +++++++++++++++++++++++++ 5 files changed, 95 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3c14e1e..dc42e608 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,8 +47,8 @@ Changelog * 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). * Take the terminal ring flip angle of a distorted ring from the number of neighbours of its pivot, rather than from RDKit, which assigned 120° to aromatic rings when MDAnalysis wasn't available [#294](https://github.com/OpenBioSim/somd2/pull/294). -* Include whole ring systems containing perturbed atoms in the automatic REST2 region, so that the torsions about a perturbed ring's bonds to the rest of the molecule are scaled [#XXX](https://github.com/OpenBioSim/somd2/pull/XXX). -* Add a `rest2_profile` option, which can be set to `exponential` for a geometric ladder of REST2 scale factors rather than a linear one [#XXX](https://github.com/OpenBioSim/somd2/pull/XXX). +* Include whole ring systems containing perturbed atoms in the automatic REST2 region, so that the torsions about a perturbed ring's bonds to the rest of the molecule are scaled [#296](https://github.com/OpenBioSim/somd2/pull/296). +* Add a `rest2_profile` option, which can be set to `exponential` for a geometric ladder of REST2 scale factors rather than a linear one [#296](https://github.com/OpenBioSim/somd2/pull/296). [2026.2.0](https://github.com/openbiosim/somd2/compare/2026.1.0...2026.2.0) - Sep 2026 -------------------------------------------------------------------------------------- diff --git a/src/somd2/_utils/_perturbed.py b/src/somd2/_utils/_perturbed.py index 3050ce91..7c396712 100644 --- a/src/somd2/_utils/_perturbed.py +++ b/src/somd2/_utils/_perturbed.py @@ -65,34 +65,53 @@ def _connectivities(mol): return [mol.property(name) for name in names] -def _ring_systems(mol, indices): +# Rings with more atoms than this, e.g. macrocycles or loops closed by a +# disulfide, aren't treated as ring systems. +_MAX_RING_SIZE = 8 + + +def _ring_systems(mol, indices, connectivities=None): """ Return the given atoms plus the atoms of every ring system, in either end - state, that contains one of them or is bonded to one of them. A ring system - is followed through ring bonds only, so fused rings are included, but rings - joined by a single bond, e.g. a biaryl, are not. + state, that contains one of them or, for an atom that isn't in a ring, is + bonded to it. A ring system is followed through the bonds of rings of at + most 8 atoms, so fused rings are included, but rings joined by a single + bond, e.g. a biaryl, and large rings such as macrocycles are not. """ from sire.legacy.Mol import AtomIdx as _AtomIdx + if connectivities is None: + connectivities = _connectivities(mol) + region = set(indices) - for connectivity in _connectivities(mol): + for connectivity in connectivities: + + def ring_bond(a, b): + return any( + connectivity.in_ring(n, a, b, _MAX_RING_SIZE) + for n in connectivity.connections_to(a) + if n != b + ) + + def in_ring(a): + return any(ring_bond(a, n) for n in connectivity.connections_to(a)) + seeds = set() for i in indices: atom = _AtomIdx(i) - if connectivity.in_ring(atom): + if in_ring(atom): seeds.add(i) - seeds.update( - n.value() - for n in connectivity.connections_to(atom) - if connectivity.in_ring(n) - ) + else: + seeds.update( + n.value() for n in connectivity.connections_to(atom) if in_ring(n) + ) seen = set(seeds) stack = list(seeds) while stack: atom = _AtomIdx(stack.pop()) for n in connectivity.connections_to(atom): - if n.value() not in seen and connectivity.in_ring(atom, n): + if n.value() not in seen and ring_bond(atom, n): seen.add(n.value()) stack.append(n.value()) region |= seen @@ -100,14 +119,15 @@ def _ring_systems(mol, indices): return sorted(region) -def _neighbours(mol, indices, bonds): +def _neighbours(mol, indices, bonds, connectivities=None): """ 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 - connectivities = _connectivities(mol) + if connectivities is None: + connectivities = _connectivities(mol) region = set(indices) shell = set(indices) @@ -127,10 +147,10 @@ def perturbed_selection(system, bonds=0, rings=False): """ 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. - With 'rings', ring systems containing a perturbed atom, or bonded to one, - are included whole before the selection is extended, so that a perturbed - ring and the torsions about its bonds to the rest of the molecule are - covered. + With 'rings', ring systems containing a perturbed atom, or bonded to a + perturbed atom outside a ring, are included whole before the selection is + extended, so that a perturbed ring and the torsions about its bonds to the + rest of the molecule are covered. 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 @@ -164,10 +184,11 @@ def perturbed_selection(system, bonds=0, rings=False): molecules = system.molecules() parts = [] for mol in solutes: + connectivities = _connectivities(mol) indices = perturbed_atoms(mol) if rings: - indices = _ring_systems(mol, indices) - indices = _neighbours(mol, indices, bonds) + indices = _ring_systems(mol, indices, connectivities) + indices = _neighbours(mol, indices, bonds, connectivities) 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 80ed967b..e1b55610 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -720,7 +720,8 @@ def __init__( (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, any ring systems that contain - them or are bonded to them, and the atoms within 'rest2_bonds' bonds of these. If None, then all atoms within perturbable molecules will be + them or are bonded to them, and the atoms within 'rest2_bonds' bonds of + these. 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. diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index 9409d5e3..6b05a431 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -888,6 +888,11 @@ def _set_schedule(self, pert_idxs, ion_indices): _logger.error(msg) raise ValueError(msg) self._rest2_scale_factors = self._config.rest2_scale + if self._config.rest2_profile != "linear": + _logger.warning( + "'rest2_profile' is ignored, since 'rest2_scale' gives a " + f"scale factor for each {_lam_sym} window." + ) # If there are any non-zero REST2 scale factors, then log it. if any( diff --git a/tests/_utils/test_perturbed.py b/tests/_utils/test_perturbed.py index d2293a53..f429f851 100644 --- a/tests/_utils/test_perturbed.py +++ b/tests/_utils/test_perturbed.py @@ -1,3 +1,4 @@ +import pytest import sire as sr from somd2._utils._perturbed import _ring_systems, perturbed_atoms, perturbed_selection @@ -176,3 +177,47 @@ def test_perturbed_selection_rings_without_rings(ethane_methanol): assert perturbed_selection(ethane_methanol, bonds, rings=True) == ( perturbed_selection(ethane_methanol, bonds) ) + + +@pytest.mark.parametrize( + "smiles, seed_in_ring, size", + [ + # A biaryl: a ring atom at the junction brings in only its own ring. + ("c1ccccc1-c1ccccc1", True, 6), + # Fused rings form one ring system. + ("c1ccc2ccccc2c1", True, 10), + # Large rings, e.g. macrocycles, aren't ring systems. + ("C1CCCCCCCCCCC1", True, 1), + # A substituent on a ring brings in the ring. + ("Cc1ccccc1", False, 7), + ], +) +def test_ring_systems_smiles(smiles, seed_in_ring, size): + """ + Make sure ring systems stop at bonds between rings and at large rings. + """ + from sire.legacy.Mol import AtomIdx + + mol = sr.smiles(smiles) + c = mol.property("connectivity") + heavy = [i for i, a in enumerate(mol.atoms()) if a.element().symbol() != "H"] + + if seed_in_ring: + # A ring atom bonded to a heavy atom in a different ring, or any ring atom. + seed = next( + ( + i + for i in heavy + if any( + n.value() in heavy and not c.in_ring(AtomIdx(i), n) + for n in c.connections_to(AtomIdx(i)) + ) + and c.in_ring(AtomIdx(i)) + ), + heavy[0], + ) + else: + seed = next(i for i in heavy if not c.in_ring(AtomIdx(i))) + + region = [i for i in _ring_systems(mol, [seed]) if i in heavy] + assert len(region) == size From b79db1032794b9951cd522e6e54b2de9a1117e36 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Tue, 17 Nov 2026 09:37:46 +0000 Subject: [PATCH 4/4] Make the exponential REST2 profile the default. --- CHANGELOG.md | 2 +- README.md | 10 +++++----- src/somd2/config/_config.py | 6 +++--- src/somd2/runner/_base.py | 17 +++++++++++++++++ tests/runner/test_config.py | 27 +++++++++++++++++++++++++-- 5 files changed, 51 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc42e608..db24b603 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,7 +48,7 @@ Changelog * 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). * Take the terminal ring flip angle of a distorted ring from the number of neighbours of its pivot, rather than from RDKit, which assigned 120° to aromatic rings when MDAnalysis wasn't available [#294](https://github.com/OpenBioSim/somd2/pull/294). * Include whole ring systems containing perturbed atoms in the automatic REST2 region, so that the torsions about a perturbed ring's bonds to the rest of the molecule are scaled [#296](https://github.com/OpenBioSim/somd2/pull/296). -* Add a `rest2_profile` option, which can be set to `exponential` for a geometric ladder of REST2 scale factors rather than a linear one [#296](https://github.com/OpenBioSim/somd2/pull/296). +* Add a `rest2_profile` option. The default, `exponential`, gives a geometric ladder of REST2 scale factors, rather than the previous linear rise, which is still available as `linear`. REST2 runs started before this change must set `rest2_profile` to `linear` to restart [#296](https://github.com/OpenBioSim/somd2/pull/296). [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 5b3e8c73..31135392 100644 --- a/README.md +++ b/README.md @@ -638,11 +638,11 @@ selected atoms of those molecules are scaled, so a subset of a perturbable molecule can be chosen. The REST2 schedule starts and ends at 1.0, peaking at the value of -`--rest2-scale` in the middle of the λ schedule. By default it rises linearly. -With `--rest2-profile exponential`, each step instead multiplies the scale -factor by the same ratio, giving a geometric ladder of effective temperatures, -which helps sampling propagate between windows when a large scale factor is -used. Passing multiple values to `--rest2-scale` gives full control of the +`--rest2-scale` in the middle of the λ schedule. By default each step +multiplies the scale factor by the same ratio, giving a geometric ladder of +effective temperatures, which helps sampling propagate between windows when a +large scale factor is used. Use `--rest2-profile linear` for a linear rise +instead. Passing multiple values to `--rest2-scale` gives full control of the schedule, in which case there must be one value for each λ window. diff --git a/src/somd2/config/_config.py b/src/somd2/config/_config.py index e1b55610..a188ada8 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -234,7 +234,7 @@ def __init__( gcmc_num_attempts=10000, use_dispersion_correction=False, rest2_scale=1.0, - rest2_profile="linear", + rest2_profile="exponential", rest2_selection="auto", rest2_bonds=2, softcore_form="auto", @@ -707,8 +707,8 @@ def __init__( rest2_profile: str How a single 'rest2_scale' rises from 1.0 at the end states to its value at - lambda = 0.5: "linear" (the default), or "exponential", where each step - multiplies the scale factor by the same ratio. The exponential profile gives a + lambda = 0.5: "exponential" (the default), where each step multiplies the + scale factor by the same ratio, or "linear". The exponential profile gives a geometric ladder of effective temperatures, which helps sampling propagate between windows when a large scale factor is used. It has no effect when 'rest2_scale' is a list. diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index 6b05a431..9e149abe 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -2636,6 +2636,23 @@ def _compare_configs(config1, config2): "None to restart it." ) + # Runs started before 'rest2_profile' existed used the linear profile. + scale = config1.get("rest2_scale") + try: + has_rest2 = scale is not None and float(scale) != 1.0 + except (TypeError, ValueError): + has_rest2 = False + if ( + has_rest2 + and "rest2_profile" not in config1 + and config2.get("rest2_profile", "linear") != "linear" + ): + raise ValueError( + "The simulation was started before 'rest2_profile' existed, so it " + "used the linear REST2 profile. Set 'rest2_profile' to 'linear' 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/runner/test_config.py b/tests/runner/test_config.py index 5f887261..6bc3ad57 100644 --- a/tests/runner/test_config.py +++ b/tests/runner/test_config.py @@ -508,9 +508,9 @@ def test_rest2_region_options(ethane_methanol): config = Config() assert config.rest2_selection == "auto" assert config.rest2_bonds == 2 - assert config.rest2_profile == "linear" - config.rest2_profile = "Exponential" assert config.rest2_profile == "exponential" + config.rest2_profile = "Linear" + assert config.rest2_profile == "linear" with pytest.raises(ValueError): config.rest2_profile = "cubic" @@ -549,3 +549,26 @@ def test_rest2_region_options(ethane_methanol): assert written.rest2_selection == expected somd2._logger.remove() + + +def test_rest2_profile_restart(): + """ + A REST2 run started before 'rest2_profile' existed can't silently switch to + the exponential profile on restart, while runs without REST2 are unaffected. + """ + import pytest + + from somd2.runner._base import RunnerBase + + def old_config(**kwargs): + config = Config(**kwargs).as_dict() + config.pop("rest2_profile") + return config + + new = Config(rest2_scale=2.0).as_dict() + with pytest.raises(ValueError, match="'rest2_profile' to 'linear'"): + RunnerBase._compare_configs(old_config(rest2_scale=2.0), new) + + linear = Config(rest2_scale=2.0, rest2_profile="linear").as_dict() + RunnerBase._compare_configs(old_config(rest2_scale=2.0), linear) + RunnerBase._compare_configs(old_config(), Config().as_dict())