diff --git a/CHANGELOG.md b/CHANGELOG.md index 580562ba..db24b603 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +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 [#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 5916b115..31135392 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 @@ -635,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 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/_utils/_perturbed.py b/src/somd2/_utils/_perturbed.py index 68034ba2..7c396712 100644 --- a/src/somd2/_utils/_perturbed.py +++ b/src/somd2/_utils/_perturbed.py @@ -54,17 +54,80 @@ def changes(atom): return indices or list(range(mol.num_atoms())) -def _neighbours(mol, indices, bonds): +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] + + +# 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, 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: + + 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 in_ring(atom): + seeds.add(i) + 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 ring_bond(atom, n): + seen.add(n.value()) + stack.append(n.value()) + region |= seen + + return sorted(region) + + +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 - names = ["connectivity0", "connectivity1"] - if not all(mol.has_property(name) for name in names): - names = ["connectivity"] - connectivities = [mol.property(name) for name in names] + if connectivities is None: + connectivities = _connectivities(mol) region = set(indices) shell = set(indices) @@ -80,10 +143,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 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 @@ -98,6 +165,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 +184,11 @@ def perturbed_selection(system, bonds=0): molecules = system.molecules() parts = [] for mol in solutes: - indices = _neighbours(mol, perturbed_atoms(mol), bonds) + connectivities = _connectivities(mol) + indices = perturbed_atoms(mol) + if rings: + 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/_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 2f4b68ba..a188ada8 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="exponential", rest2_selection="auto", rest2_bonds=2, softcore_form="auto", @@ -703,14 +705,23 @@ 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: "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. + 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 '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. @@ -938,6 +949,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 +2921,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 65aa81ec..9e149abe 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." @@ -889,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( @@ -905,7 +909,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 = ( @@ -2632,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/_utils/test_perturbed.py b/tests/_utils/test_perturbed.py index 85329c44..f429f851 100644 --- a/tests/_utils/test_perturbed.py +++ b/tests/_utils/test_perturbed.py @@ -1,6 +1,7 @@ +import pytest 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 +142,82 @@ 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) + ) + + +@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 diff --git a/tests/runner/test_config.py b/tests/runner/test_config.py index 7b6bb858..6bc3ad57 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 == "exponential" + config.rest2_profile = "Linear" + assert config.rest2_profile == "linear" + with pytest.raises(ValueError): + config.rest2_profile = "cubic" config.rest2_selection = "None" assert config.rest2_selection is None @@ -544,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()) 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")