From e8444a65928a09fb515a015947a56a06cb05fa8f Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Wed, 11 Nov 2026 11:16:27 +0000 Subject: [PATCH 1/7] Add linear_torsions option to avoid torsion singularities at linear angles. --- CHANGELOG.md | 1 + README.md | 11 ++ src/somd2/_utils/_linear_angles.py | 131 +++++++++++++++++++ src/somd2/_utils/_schedules.py | 66 ++++++++++ src/somd2/config/_config.py | 30 +++++ src/somd2/runner/_base.py | 50 ++++++++ tests/runner/test_config.py | 5 +- tests/schedules/test_linear_torsions.py | 159 ++++++++++++++++++++++++ 8 files changed, 452 insertions(+), 1 deletion(-) create mode 100644 src/somd2/_utils/_linear_angles.py create mode 100644 tests/schedules/test_linear_torsions.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f1ec51c2..3b6b3b42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,7 @@ Changelog * Run GCMC simulations in the NVT ensemble, ignoring the pressure, since the osmotic ensemble isn't valid for GCMC of solvent water: the number of waters is barely fixed, so it drifts. GCMC runs started with a pressure can't be restarted [#281](https://github.com/OpenBioSim/somd2/pull/281). * Added support for Python 3.13 and 3.14, and dropped support for Python 3.10 and 3.11 [#283](https://github.com/OpenBioSim/somd2/pull/283). * Fixed the regular runner reporting success when a lambda window failed, unless it was the last to finish. The other windows still run, then `Runner.run()` raises an error listing the failed windows and `somd2` exits with a non-zero status. The overall performance is now summed over all windows rather than taken from the last to finish [#285](https://github.com/OpenBioSim/somd2/pull/285). +* Add a `linear_torsions` option, `auto` by default, that changes torsions and impropers over only part of each stage of the lambda schedule when an angle 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 [#287](https://github.com/OpenBioSim/somd2/pull/287). [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 f83d23a4..5f6807e3 100644 --- a/README.md +++ b/README.md @@ -662,6 +662,17 @@ relative binding free energy (RBFE) simulations. The available schedules are: For the `annihilate`, `decouple`, and ring-breaking schedules, appropriate restraints can be generated automatically. See the sections below. +When an angle becomes linear at one end state, e.g. a C=C bond that becomes a +C≡C bond, the forces from torsions and impropers through it diverge as its +atoms become collinear, which can crash simulations at intermediate λ. By +default (`--linear-torsions auto`), SOMD2 detects angles that are linear at +only one end state and have a non-zero torsion or improper through them, and +then changes all torsions and impropers over only part of each stage of the +schedule: the first half when the angles are linear at λ = 1, the second half +when they are linear at λ = 0, or the middle half when both occur. The angles +are logged. Use `--linear-torsions true` to apply this whenever an angle becomes +linear, or `false` to disable it. + ## 🧬 Absolute binding free energies diff --git a/src/somd2/_utils/_linear_angles.py b/src/somd2/_utils/_linear_angles.py new file mode 100644 index 00000000..566e799d --- /dev/null +++ b/src/somd2/_utils/_linear_angles.py @@ -0,0 +1,131 @@ +###################################################################### +# 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__ = ["find_linear_angles", "torsion_window"] + +# Angles with an equilibrium value of at least this many degrees are linear. +_LINEAR_ANGLE = 170.0 + + +def find_linear_angles(mol, require_terms=True, max_angle=_LINEAR_ANGLE): + """ + Find the angles of a perturbable molecule that are linear at only one end + state. + + Parameters + ---------- + + mol : sire.mol.Molecule + The perturbable molecule. + + require_terms : bool + Whether to only return angles that a non-zero dihedral or improper + passes through at either end state, i.e. with three consecutive atoms + of the term being the atoms of the angle. + + max_angle : float + The equilibrium angle, in degrees, at or above which an angle is + linear. + + Returns + ------- + + angles : list of ((int, int, int), int) + The atom indices of each angle, with the central atom in the middle, + and the end state at which it is linear. + """ + from math import degrees + + from sire.legacy.CAS import Symbol + from sire.legacy.MM import AmberAngle + + info = mol.info() + theta = Symbol("theta") + + def theta0s(state): + result = {} + for p in mol.property(f"angle{state}").potentials(): + i, j, k = ( + info.atom_idx(a).value() for a in (p.atom0(), p.atom1(), p.atom2()) + ) + try: + theta0 = degrees(AmberAngle(p.function(), theta).theta0()) + except Exception: + continue + result[(min(i, k), j, max(i, k))] = theta0 + return result + + theta0 = [theta0s(0), theta0s(1)] + + angles = [] + for key in sorted(theta0[0].keys() & theta0[1].keys()): + linear0 = theta0[0][key] >= max_angle + linear1 = theta0[1][key] >= max_angle + if linear0 != linear1: + angles.append((key, 0 if linear0 else 1)) + + if not require_terms or not angles: + return angles + + spanned = set() + for state in (0, 1): + for name in ("dihedral", "improper"): + try: + potentials = mol.property(f"{name}{state}").potentials() + except Exception: + continue + for p in potentials: + if p.function().is_zero(): + continue + idx = [ + info.atom_idx(a).value() + for a in (p.atom0(), p.atom1(), p.atom2(), p.atom3()) + ] + spanned.add(frozenset(idx[:3])) + spanned.add(frozenset(idx[1:])) + + return [(key, state) for key, state in angles if frozenset(key) in spanned] + + +def torsion_window(states): + """ + Return the fraction of each morph stage over which torsions should change, + given the end states at which angles become linear. + + Parameters + ---------- + + states : set of int + The end states at which angles become linear. + + Returns + ------- + + window : (float, float) + The start and end of the window. + """ + if states == {1}: + return 0.0, 0.5 + if states == {0}: + return 0.5, 1.0 + if states == {0, 1}: + return 0.25, 0.75 + raise ValueError("'states' must be a non-empty subset of {0, 1}") diff --git a/src/somd2/_utils/_schedules.py b/src/somd2/_utils/_schedules.py index 7c017932..35d0e145 100644 --- a/src/somd2/_utils/_schedules.py +++ b/src/somd2/_utils/_schedules.py @@ -23,6 +23,7 @@ "abfe_alchemical_ion", "annihilate", "decouple", + "linear_torsions", "ring_break_morph", "reverse_ring_break_morph", ] @@ -428,3 +429,68 @@ def reverse_ring_break_morph(): The lambda schedule. """ return ring_break_morph().reverse() + + +def linear_torsions(schedule, start, end): + """ + Return a copy of a lambda schedule in which the torsion levers change over + the fraction [start, end] of each stage where they change linearly, and + are held at their initial and final values either side of it. This keeps + torsions and impropers through an angle that becomes linear at one end + state at that end state's values while the angle is near linear, since + their forces diverge as its atoms become collinear. + + Parameters + ---------- + + schedule : sire.legacy.CAS.LambdaSchedule + The lambda schedule. + + start : float + The fraction of each stage at which the torsions start to change. + + end : float + The fraction of each stage at which the torsions reach their final + values. + + Returns + ------- + + schedule : sire.legacy.CAS.LambdaSchedule + The modified lambda schedule. + """ + from sire.legacy.CAS import Expression, Max, Min, Values + + if not 0 <= start < end <= 1: + raise ValueError("'start' and 'end' must satisfy 0 <= start < end <= 1") + + s = schedule.clone() + lam, initial, final = s.lam(), s.initial(), s.final() + + f = Min(Expression(1), Max(Expression(0), (lam - start) * (1 / (end - start)))) + target = (1 - f) * initial + f * final + + def values(equation): + return [ + equation.evaluate(Values({lam: x, initial: 2.0, final: 5.0})) + for x in (0.0, 0.2, 0.4, 0.6, 0.8, 1.0) + ] + + linear = [2.0 + 3.0 * x for x in (0.0, 0.2, 0.4, 0.6, 0.8, 1.0)] + staged = values(target) + + def close(a, b): + return all(abs(x - y) < 1e-8 for x, y in zip(a, b)) + + for stage in s.get_stages(): + for lever in ("torsion_k", "torsion_phase"): + v = values(s.get_equation(stage=stage, lever=lever)) + if close(v, linear): + s.set_equation(stage=stage, lever=lever, equation=target) + elif not (close(v, staged) or close(v, [v[0]] * len(v))): + raise ValueError( + f"The '{lever}' lever in stage '{stage}' doesn't change " + "linearly, so the torsion window can't be applied." + ) + + return s diff --git a/src/somd2/config/_config.py b/src/somd2/config/_config.py index 492f8c50..9a95370d 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -75,6 +75,7 @@ class Config: ], "log_level": [level.lower() for level in _logger._core.levels], "softcore_form": ["auto", "zacharias", "taylor", "beutler"], + "linear_torsions": ["auto", "true", "false"], "precision": ["single", "mixed", "double"], } @@ -158,6 +159,7 @@ def __init__( lambda_energy=None, lambda_schedule="standard_morph", charge_scale_factor=0.2, + linear_torsions="auto", swap_end_states=False, shift_coulomb="1 A", shift_delta="1.5 A", @@ -332,6 +334,15 @@ def __init__( charge_scale_factor: float Factor by which to scale charges for charge scaled morph. + linear_torsions: str + Whether to change torsions and impropers over only part of each + morph stage, so that those through an angle that becomes linear at + one end state are at that end state's values while the angle is + near linear. Their forces diverge as the angle's atoms become + collinear. Valid options are "auto" (default), "true", and "false". + "auto" applies it when a non-zero torsion or improper passes through + such an angle, and "true" whenever an angle becomes linear. + swap_end_states: bool Whether to swap the end states of the alchemical system. @@ -828,6 +839,7 @@ def __init__( self.lambda_values = lambda_values self.lambda_energy = lambda_energy self.charge_scale_factor = charge_scale_factor + self.linear_torsions = linear_torsions self.swap_end_states = swap_end_states self.shift_coulomb = shift_coulomb self.shift_delta = shift_delta @@ -1560,6 +1572,24 @@ def charge_scale_factor(self, charge_scale_factor): self._charge_scale_factor ) + @property + def linear_torsions(self): + return self._linear_torsions + + @linear_torsions.setter + def linear_torsions(self, linear_torsions): + if isinstance(linear_torsions, bool): + linear_torsions = str(linear_torsions) + if not isinstance(linear_torsions, str): + raise TypeError("'linear_torsions' must be of type 'str' or 'bool'") + linear_torsions = linear_torsions.lower().replace(" ", "") + if linear_torsions not in self._choices["linear_torsions"]: + raise ValueError( + "'linear_torsions' not recognised. Valid options are: " + f"{', '.join(self._choices['linear_torsions'])}" + ) + self._linear_torsions = linear_torsions + @property def swap_end_states(self): return self._swap_end_states diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index 7aad9e1c..8fcc9f7d 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -605,6 +605,54 @@ def _add_alchemical_ions(self): return ion_indices + def _apply_linear_torsions(self): + """ + Change torsions over part of each morph stage when an angle of a + perturbable molecule becomes linear at one end state, according to + the 'linear_torsions' option. + """ + mode = self._config.linear_torsions + if mode == "false" or self._config._lambda_schedule_name in ( + "annihilate", + "decouple", + ): + return + + from .._utils._linear_angles import find_linear_angles, torsion_window + from .._utils._schedules import linear_torsions + + found = [] + for mol in self._system["property is_perturbable"].molecules(): + for angle, state in find_linear_angles(mol, require_terms=mode == "auto"): + found.append((mol.number().value(), angle, state)) + + if not found: + if mode == "true": + _logger.warning( + "'linear_torsions' is enabled, but no angle of a perturbable " + "molecule becomes linear, so the lambda schedule is unchanged." + ) + return + + start, end = torsion_window({state for _, _, state in found}) + try: + schedule = linear_torsions(self._config._lambda_schedule, start, end) + except ValueError as e: + _logger.warning(f"Unable to apply 'linear_torsions': {e}") + return + self._config._lambda_schedule = schedule + + angles = ", ".join( + f"molecule {num} atoms {'-'.join(str(i) for i in angle)} " + f"({_lam_sym} = {state})" + for num, angle, state in found + ) + _logger.info( + f"Angles become linear at one end state: {angles}. Torsions and " + f"impropers will change over the fraction [{start}, {end}] of each " + "stage in which they change." + ) + def _set_schedule(self, pert_idxs, ion_indices): """ Set the soft-core form, the lambda schedule and values, and the REST2 @@ -687,6 +735,8 @@ def _set_schedule(self, pert_idxs, ion_indices): for pert_idx in ion_indices: schedule.set_molecule_schedule(pert_idx, ion_schedule) + self._apply_linear_torsions() + # Set the lambda values. if self._config.lambda_values: self._lambda_values = self._config.lambda_values diff --git a/tests/runner/test_config.py b/tests/runner/test_config.py index d9cbf551..7cd4851d 100644 --- a/tests/runner/test_config.py +++ b/tests/runner/test_config.py @@ -78,7 +78,10 @@ def test_logfile_creation(): assert not Path.exists(config.output_directory / config.log_file) # Test that a logfile is created once a runner object is initialised. - runner = Runner(mols, Config(output_directory=tmpdir, log_file="test1.log")) + runner = Runner( + mols, + Config(platform="cpu", output_directory=tmpdir, log_file="test1.log"), + ) assert runner._config.log_file is not None assert Path.exists(runner._config.output_directory / runner._config.log_file) diff --git a/tests/schedules/test_linear_torsions.py b/tests/schedules/test_linear_torsions.py new file mode 100644 index 00000000..4ba3714c --- /dev/null +++ b/tests/schedules/test_linear_torsions.py @@ -0,0 +1,159 @@ +import math +import tempfile + +import pytest +from sire.cas import LambdaSchedule +from sire.legacy.CAS import Symbol +from sire.legacy.MM import AmberAngle, FourAtomFunctions, ThreeAtomFunctions + +from somd2._utils._linear_angles import find_linear_angles, torsion_window +from somd2._utils._schedules import linear_torsions, ring_break_morph + + +def _torsion_k(schedule, lambda_values): + return [schedule.morph("*", "torsion_k", 4.0, 0.0, x) for x in lambda_values] + + +@pytest.mark.parametrize( + "window, expected", + [ + ((0.0, 0.5), [4.0, 2.0, 0.0, 0.0, 0.0]), + ((0.5, 1.0), [4.0, 4.0, 4.0, 2.0, 0.0]), + ((0.25, 0.75), [4.0, 4.0, 2.0, 0.0, 0.0]), + ], +) +def test_linear_torsions_window(window, expected): + """ + Torsions change over the window only, and other levers are unchanged. + """ + schedule = linear_torsions(LambdaSchedule.standard_morph(), *window) + assert _torsion_k(schedule, [0.0, 0.25, 0.5, 0.75, 1.0]) == pytest.approx(expected) + assert schedule.morph("*", "angle_size", 2.0, 4.0, 0.25) == pytest.approx(2.5) + + +def test_linear_torsions_stages(): + """ + The window applies within each stage in which the torsions change linearly. + """ + schedule = linear_torsions(ring_break_morph(), 0.0, 0.5) + values = _torsion_k(schedule, [0.2, 0.4, 0.5, 0.6]) + assert values == pytest.approx([4.0, 2.4, 0.0, 0.0]) + + +def test_linear_torsions_idempotent(): + schedule = linear_torsions(LambdaSchedule.standard_morph(), 0.0, 0.5) + assert linear_torsions(schedule, 0.0, 0.5) == schedule + + +def test_linear_torsions_invalid(): + with pytest.raises(ValueError): + linear_torsions(LambdaSchedule.standard_morph(), 0.5, 0.5) + + schedule = LambdaSchedule.standard_morph() + schedule.set_equation( + stage="morph", lever="torsion_k", equation=schedule.lam() ** 2 + ) + with pytest.raises(ValueError): + linear_torsions(schedule, 0.0, 0.5) + + +def test_torsion_window(): + assert torsion_window({1}) == (0.0, 0.5) + assert torsion_window({0}) == (0.5, 1.0) + assert torsion_window({0, 1}) == (0.25, 0.75) + with pytest.raises(ValueError): + torsion_window(set()) + + +def _linearise(mol, angle, state, remove_terms=False): + """ + Set the equilibrium value of an angle to 180 degrees at an end state, and + optionally remove the dihedrals and impropers that pass through it. + """ + info = mol.info() + theta = Symbol("theta") + atoms = set(angle) + + angles = ThreeAtomFunctions(info) + for p in mol.property(f"angle{state}").potentials(): + idx = [info.atom_idx(a) for a in (p.atom0(), p.atom1(), p.atom2())] + function = p.function() + if {i.value() for i in idx} == atoms and idx[1].value() == angle[1]: + k = AmberAngle(function, theta).k() + function = AmberAngle(k, math.pi).to_expression(theta) + angles.set(*idx, function) + + cursor = mol.edit().set_property(f"angle{state}", angles).molecule() + + if remove_terms: + for name in ("dihedral", "improper"): + for s in (0, 1): + terms = FourAtomFunctions(info) + for p in mol.property(f"{name}{s}").potentials(): + idx = [ + info.atom_idx(a) + for a in (p.atom0(), p.atom1(), p.atom2(), p.atom3()) + ] + values = [i.value() for i in idx] + if atoms in (set(values[:3]), set(values[1:])): + continue + terms.set(*idx, p.function()) + cursor = cursor.set_property(f"{name}{s}", terms).molecule() + + return cursor.commit() + + +def _spanned_angle(mol): + """ + Return an angle of the molecule that a non-zero dihedral passes through at + both end states. + """ + info = mol.info() + for p in mol.property("dihedral0").potentials(): + if p.function().is_zero(): + continue + idx = [info.atom_idx(a).value() for a in (p.atom0(), p.atom1(), p.atom2())] + return tuple(idx) + raise ValueError("No non-zero dihedrals") + + +def test_find_linear_angles(diphenylethane_mols): + mol = diphenylethane_mols.molecules("property is_perturbable")[0] + assert find_linear_angles(mol) == [] + + angle = _spanned_angle(mol) + key = (min(angle[0], angle[2]), angle[1], max(angle[0], angle[2])) + + linear = _linearise(mol, angle, 1) + assert find_linear_angles(linear) == [(key, 1)] + + bare = _linearise(mol, angle, 0, remove_terms=True) + assert find_linear_angles(bare) == [] + assert find_linear_angles(bare, require_terms=False) == [(key, 0)] + + +@pytest.mark.parametrize("mode", ["auto", "false"]) +def test_runner_linear_torsions(diphenylethane_mols, mode): + """ + The runner changes the schedule only when the option allows it. + """ + from somd2.config import Config + from somd2.runner import Runner + + mols = diphenylethane_mols.clone() + mol = mols.molecules("property is_perturbable")[0] + mols.update(_linearise(mol, _spanned_angle(mol), 1)) + + with tempfile.TemporaryDirectory() as tmpdir: + config = Config( + platform="cpu", + output_directory=tmpdir, + linear_torsions=mode, + ghost_modifications=False, + ) + runner = Runner(mols, config) + + expected = [4.0, 0.0] if mode == "auto" else [4.0, 2.0] + assert _torsion_k(runner._config.lambda_schedule, [0.0, 0.5]) == ( + pytest.approx(expected) + ) From 260fabaa52a8bccf946ae150ac9b7434dba98789 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Wed, 11 Nov 2026 11:44:29 +0000 Subject: [PATCH 2/7] Scope linear_torsions per molecule, copy the runner config, and check restarts. --- CHANGELOG.md | 3 +- README.md | 12 +- src/somd2/_utils/_linear_angles.py | 62 ++++++---- src/somd2/_utils/_schedules.py | 19 ++- src/somd2/config/_config.py | 9 ++ src/somd2/runner/_base.py | 104 +++++++++++----- tests/schedules/test_linear_torsions.py | 153 ++++++++++++++++++------ 7 files changed, 265 insertions(+), 97 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b6b3b42..3d8ed461 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,7 +42,8 @@ Changelog * Run GCMC simulations in the NVT ensemble, ignoring the pressure, since the osmotic ensemble isn't valid for GCMC of solvent water: the number of waters is barely fixed, so it drifts. GCMC runs started with a pressure can't be restarted [#281](https://github.com/OpenBioSim/somd2/pull/281). * Added support for Python 3.13 and 3.14, and dropped support for Python 3.10 and 3.11 [#283](https://github.com/OpenBioSim/somd2/pull/283). * Fixed the regular runner reporting success when a lambda window failed, unless it was the last to finish. The other windows still run, then `Runner.run()` raises an error listing the failed windows and `somd2` exits with a non-zero status. The overall performance is now summed over all windows rather than taken from the last to finish [#285](https://github.com/OpenBioSim/somd2/pull/285). -* Add a `linear_torsions` option, `auto` by default, that changes torsions and impropers over only part of each stage of the lambda schedule when an angle 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 [#287](https://github.com/OpenBioSim/somd2/pull/287). +* Add a `linear_torsions` 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 `linear_torsions` 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). [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 5f6807e3..e7608441 100644 --- a/README.md +++ b/README.md @@ -666,12 +666,14 @@ When an angle becomes linear at one end state, e.g. a C=C bond that becomes a C≡C bond, the forces from torsions and impropers through it diverge as its atoms become collinear, which can crash simulations at intermediate λ. By default (`--linear-torsions auto`), SOMD2 detects angles that are linear at -only one end state and have a non-zero torsion or improper through them, and -then changes all torsions and impropers over only part of each stage of the -schedule: the first half when the angles are linear at λ = 1, the second half -when they are linear at λ = 0, or the middle half when both occur. The angles +only one end state and have a non-zero torsion or improper through them at the +other end state. The torsions and impropers of each affected molecule then +change over only part of each stage of the schedule: the first half when its +angles are linear at λ = 1, the second half when they are linear at λ = 0, or +the middle half when both occur. Other molecules are unaffected, and the angles are logged. Use `--linear-torsions true` to apply this whenever an angle becomes -linear, or `false` to disable it. +linear, or `false` to disable it. Simulations started before this option +existed must be restarted with `--linear-torsions false`. diff --git a/src/somd2/_utils/_linear_angles.py b/src/somd2/_utils/_linear_angles.py index 566e799d..5a8fbdf5 100644 --- a/src/somd2/_utils/_linear_angles.py +++ b/src/somd2/_utils/_linear_angles.py @@ -38,8 +38,8 @@ def find_linear_angles(mol, require_terms=True, max_angle=_LINEAR_ANGLE): require_terms : bool Whether to only return angles that a non-zero dihedral or improper - passes through at either end state, i.e. with three consecutive atoms - of the term being the atoms of the angle. + passes through at the end state where the angle isn't linear, i.e. + with three consecutive atoms of the term being the atoms of the angle. max_angle : float The equilibrium angle, in degrees, at or above which an angle is @@ -48,9 +48,10 @@ def find_linear_angles(mol, require_terms=True, max_angle=_LINEAR_ANGLE): Returns ------- - angles : list of ((int, int, int), int) + angles : list of ((int, int, int), int, bool) The atom indices of each angle, with the central atom in the middle, - and the end state at which it is linear. + the end state at which it is linear, and whether a non-zero dihedral + or improper passes through it at that end state. """ from math import degrees @@ -60,9 +61,15 @@ def find_linear_angles(mol, require_terms=True, max_angle=_LINEAR_ANGLE): info = mol.info() theta = Symbol("theta") + def potentials(name): + try: + return mol.property(name).potentials() + except Exception: + return [] + def theta0s(state): result = {} - for p in mol.property(f"angle{state}").potentials(): + for p in potentials(f"angle{state}"): i, j, k = ( info.atom_idx(a).value() for a in (p.atom0(), p.atom1(), p.atom2()) ) @@ -73,36 +80,39 @@ def theta0s(state): result[(min(i, k), j, max(i, k))] = theta0 return result + def spanned(state): + result = set() + for name in ("dihedral", "improper"): + for p in potentials(f"{name}{state}"): + if p.function().is_zero(): + continue + idx = [ + info.atom_idx(a).value() + for a in (p.atom0(), p.atom1(), p.atom2(), p.atom3()) + ] + result.add(frozenset(idx[:3])) + result.add(frozenset(idx[1:])) + return result + theta0 = [theta0s(0), theta0s(1)] - angles = [] + linear = [] for key in sorted(theta0[0].keys() & theta0[1].keys()): linear0 = theta0[0][key] >= max_angle linear1 = theta0[1][key] >= max_angle if linear0 != linear1: - angles.append((key, 0 if linear0 else 1)) + linear.append((key, 0 if linear0 else 1)) - if not require_terms or not angles: - return angles + if not linear: + return [] - spanned = set() - for state in (0, 1): - for name in ("dihedral", "improper"): - try: - potentials = mol.property(f"{name}{state}").potentials() - except Exception: - continue - for p in potentials: - if p.function().is_zero(): - continue - idx = [ - info.atom_idx(a).value() - for a in (p.atom0(), p.atom1(), p.atom2(), p.atom3()) - ] - spanned.add(frozenset(idx[:3])) - spanned.add(frozenset(idx[1:])) + terms = [spanned(0), spanned(1)] - return [(key, state) for key, state in angles if frozenset(key) in spanned] + return [ + (key, state, frozenset(key) in terms[state]) + for key, state in linear + if not require_terms or frozenset(key) in terms[1 - state] + ] def torsion_window(states): diff --git a/src/somd2/_utils/_schedules.py b/src/somd2/_utils/_schedules.py index 35d0e145..be17cbd7 100644 --- a/src/somd2/_utils/_schedules.py +++ b/src/somd2/_utils/_schedules.py @@ -482,9 +482,26 @@ def values(equation): def close(a, b): return all(abs(x - y) < 1e-8 for x, y in zip(a, b)) + allowed = {str(symbol) for symbol in (lam, initial, final)} + for stage in s.get_stages(): for lever in ("torsion_k", "torsion_phase"): - v = values(s.get_equation(stage=stage, lever=lever)) + if any( + s.has_force_specific_equation(stage, force, lever) + for force in s.get_forces() + ): + raise ValueError( + f"The '{lever}' lever in stage '{stage}' has a force-specific " + "equation, so the torsion window can't be applied." + ) + equation = s.get_equation(stage=stage, lever=lever) + if not {str(symbol) for symbol in equation.symbols()} <= allowed: + raise ValueError( + f"The '{lever}' lever in stage '{stage}' depends on symbols " + "other than lambda, initial and final, so the torsion window " + "can't be applied." + ) + v = values(equation) if close(v, linear): s.set_equation(stage=stage, lever=lever, equation=target) elif not (close(v, staged) or close(v, [v[0]] * len(v))): diff --git a/src/somd2/config/_config.py b/src/somd2/config/_config.py index 9a95370d..50b8d651 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -134,6 +134,10 @@ class Config: ] ) + # The behaviour of options added after a simulation was started, which + # restarts must match when the saved config doesn't include them. + _restart_legacy_values = {"linear_torsions": "false"} + def __init__( self, log_level="info", @@ -1015,6 +1019,11 @@ def as_dict(self, sire_compatible=False): # Record the form that is used, so that restarts compare like with like. d["softcore_form"] = self.softcore_form + # Likewise, record whether a runner applied the torsion window. + applied = d.pop("linear_torsions_applied", None) + if applied is not None: + d["linear_torsions"] = str(applied).lower() + # Handle the lambda schedule separately so that we can use simplified # keyword options. diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index 8fcc9f7d..42e21b52 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -123,7 +123,12 @@ def _set_config(self, config): msg = "'config' must be of type 'somd2.config.Config'" _logger.error(msg) raise TypeError(msg) - self._config = config + # The runner modifies its config, e.g. the lambda schedule, so work on a + # copy to keep the user's config unchanged. Sire objects don't support + # deepcopy, but the config pickles, as for spawned worker processes. + import pickle as _pickle + + self._config = _pickle.loads(_pickle.dumps(config)) self._config._extra_args = {} # Create the output directory and configure the logger now that the @@ -612,21 +617,62 @@ def _apply_linear_torsions(self): the 'linear_torsions' option. """ mode = self._config.linear_torsions - if mode == "false" or self._config._lambda_schedule_name in ( - "annihilate", - "decouple", - ): + self._config._linear_torsions_applied = False + + if mode == "false": + return + if self._config._lambda_schedule_name in ("annihilate", "decouple"): + if mode == "true": + _logger.warning( + "'linear_torsions' is ignored for the " + f"'{self._config._lambda_schedule_name}' lambda schedule." + ) return from .._utils._linear_angles import find_linear_angles, torsion_window from .._utils._schedules import linear_torsions - found = [] - for mol in self._system["property is_perturbable"].molecules(): - for angle, state in find_linear_angles(mol, require_terms=mode == "auto"): - found.append((mol.number().value(), angle, state)) + schedule = self._config._lambda_schedule + perturbable = self._system.molecules()["perturbable"].molecules() - if not found: + windows = {} + for idx, mol in enumerate(perturbable): + found = find_linear_angles(mol, require_terms=mode == "auto") + if not found: + continue + + for angle, state, singular in found: + if singular: + _logger.warning( + f"A non-zero torsion or improper passes through angle " + f"{'-'.join(str(i) for i in angle)} of perturbable molecule " + f"{idx} at {_lam_sym} = {state}, where the angle is linear. " + "The lambda schedule can't prevent its force diverging." + ) + + start, end = torsion_window({state for _, state, _ in found}) + base = ( + schedule.get_molecule_schedule(idx) + if schedule.has_molecule_schedule(idx) + else schedule + ) + try: + mol_schedule = linear_torsions(base, start, end) + except ValueError as e: + msg = f"Unable to apply 'linear_torsions' to perturbable molecule {idx}: {e}" + if mode == "true": + _logger.error(msg) + raise ValueError(msg) + _logger.warning(msg) + continue + + for other in range(len(perturbable)): + if mol_schedule.has_molecule_schedule(other): + mol_schedule.remove_molecule_schedule(other) + + windows[idx] = (mol_schedule, start, end, found) + + if not windows: if mode == "true": _logger.warning( "'linear_torsions' is enabled, but no angle of a perturbable " @@ -634,24 +680,20 @@ def _apply_linear_torsions(self): ) return - start, end = torsion_window({state for _, _, state in found}) - try: - schedule = linear_torsions(self._config._lambda_schedule, start, end) - except ValueError as e: - _logger.warning(f"Unable to apply 'linear_torsions': {e}") - return - self._config._lambda_schedule = schedule + for idx, (mol_schedule, start, end, found) in windows.items(): + schedule.set_molecule_schedule(idx, mol_schedule) + angles = ", ".join( + f"{'-'.join(str(i) for i in angle)} ({_lam_sym} = {state})" + for angle, state, _ in found + ) + _logger.info( + f"Angles of perturbable molecule {idx} become linear at one end " + f"state (atom indices within the molecule): {angles}. Its torsions " + f"and impropers will change over the fraction [{start}, {end}] of " + "each stage in which they change." + ) - angles = ", ".join( - f"molecule {num} atoms {'-'.join(str(i) for i in angle)} " - f"({_lam_sym} = {state})" - for num, angle, state in found - ) - _logger.info( - f"Angles become linear at one end state: {angles}. Torsions and " - f"impropers will change over the fraction [{start}, {end}] of each " - "stage in which they change." - ) + self._config._linear_torsions_applied = True def _set_schedule(self, pert_idxs, ion_indices): """ @@ -2452,6 +2494,14 @@ def _compare_configs(config1, config2): from sire.units import GeneralUnit as _GeneralUnit + for key, legacy in _Config._restart_legacy_values.items(): + if key not in config1 and config2.get(key, legacy) != legacy: + raise ValueError( + f"{key} is '{config2[key]}', but the simulation was started " + f"before this option existed, when it was '{legacy}'. Set " + f"{key} to '{legacy}' to restart it." + ) + allowed_diffs = _Config._restart_allowed_diffs for key in config1.keys(): if key not in allowed_diffs: diff --git a/tests/schedules/test_linear_torsions.py b/tests/schedules/test_linear_torsions.py index 4ba3714c..7303ab6f 100644 --- a/tests/schedules/test_linear_torsions.py +++ b/tests/schedules/test_linear_torsions.py @@ -65,10 +65,11 @@ def test_torsion_window(): torsion_window(set()) -def _linearise(mol, angle, state, remove_terms=False): +def _linearise(mol, angle, state, remove_terms=()): """ Set the equilibrium value of an angle to 180 degrees at an end state, and - optionally remove the dihedrals and impropers that pass through it. + remove the dihedrals and impropers that pass through it at the given end + states. """ info = mol.info() theta = Symbol("theta") @@ -85,20 +86,19 @@ def _linearise(mol, angle, state, remove_terms=False): cursor = mol.edit().set_property(f"angle{state}", angles).molecule() - if remove_terms: - for name in ("dihedral", "improper"): - for s in (0, 1): - terms = FourAtomFunctions(info) - for p in mol.property(f"{name}{s}").potentials(): - idx = [ - info.atom_idx(a) - for a in (p.atom0(), p.atom1(), p.atom2(), p.atom3()) - ] - values = [i.value() for i in idx] - if atoms in (set(values[:3]), set(values[1:])): - continue - terms.set(*idx, p.function()) - cursor = cursor.set_property(f"{name}{s}", terms).molecule() + for name in ("dihedral", "improper"): + for s in remove_terms: + terms = FourAtomFunctions(info) + for p in mol.property(f"{name}{s}").potentials(): + idx = [ + info.atom_idx(a) + for a in (p.atom0(), p.atom1(), p.atom2(), p.atom3()) + ] + values = [i.value() for i in idx] + if atoms in (set(values[:3]), set(values[1:])): + continue + terms.set(*idx, p.function()) + cursor = cursor.set_property(f"{name}{s}", terms).molecule() return cursor.commit() @@ -117,6 +117,17 @@ def _spanned_angle(mol): raise ValueError("No non-zero dihedrals") +def _linear_system(mols, remove_terms=(1,)): + """ + Return a copy of the system with an angle of the perturbable molecule made + linear at lambda = 1. + """ + mols = mols.clone() + mol = mols.molecules("property is_perturbable")[0] + mols.update(_linearise(mol, _spanned_angle(mol), 1, remove_terms)) + return mols + + def test_find_linear_angles(diphenylethane_mols): mol = diphenylethane_mols.molecules("property is_perturbable")[0] assert find_linear_angles(mol) == [] @@ -124,36 +135,104 @@ def test_find_linear_angles(diphenylethane_mols): angle = _spanned_angle(mol) key = (min(angle[0], angle[2]), angle[1], max(angle[0], angle[2])) - linear = _linearise(mol, angle, 1) - assert find_linear_angles(linear) == [(key, 1)] + # Terms through the angle at the linear end state are flagged. + assert find_linear_angles(_linearise(mol, angle, 1)) == [(key, 1, True)] + + linear = _linearise(mol, angle, 1, remove_terms=(1,)) + assert find_linear_angles(linear) == [(key, 1, False)] - bare = _linearise(mol, angle, 0, remove_terms=True) + # Terms only at the linear end state don't trigger detection. + linear = _linearise(mol, angle, 1, remove_terms=(0,)) + assert find_linear_angles(linear) == [] + assert find_linear_angles(linear, require_terms=False) == [(key, 1, True)] + + bare = _linearise(mol, angle, 0, remove_terms=(0, 1)) assert find_linear_angles(bare) == [] - assert find_linear_angles(bare, require_terms=False) == [(key, 0)] + assert find_linear_angles(bare, require_terms=False) == [(key, 0, False)] + + +def test_find_linear_angles_no_angles(diphenylethane_mols): + mol = diphenylethane_mols.molecules("property is_perturbable")[0] + mol = mol.edit().remove_property("angle1").molecule().commit() + assert find_linear_angles(mol) == [] + + +def test_linear_torsions_unsupported(): + schedule = LambdaSchedule.standard_morph() + schedule.set_equation( + stage="morph", force="torsion", lever="torsion_k", equation=schedule.final() + ) + with pytest.raises(ValueError, match="force-specific"): + linear_torsions(schedule, 0.0, 0.5) + + schedule = LambdaSchedule.standard_morph() + schedule.set_constant("scale", 0.5) + schedule.set_equation( + stage="morph", + lever="torsion_k", + equation=schedule.get_constant_symbol("scale") * schedule.final(), + ) + with pytest.raises(ValueError, match="symbols"): + linear_torsions(schedule, 0.0, 0.5) + + +def _runner(mols, tmpdir, **kwargs): + from somd2.config import Config + from somd2.runner import Runner + + config = Config( + platform="cpu", output_directory=tmpdir, ghost_modifications=False, **kwargs + ) + return config, Runner(mols, config) @pytest.mark.parametrize("mode", ["auto", "false"]) def test_runner_linear_torsions(diphenylethane_mols, mode): """ - The runner changes the schedule only when the option allows it. + The runner gives the affected molecule its own schedule only when the + option allows it, and leaves the user's config unchanged. """ - from somd2.config import Config - from somd2.runner import Runner - - mols = diphenylethane_mols.clone() - mol = mols.molecules("property is_perturbable")[0] - mols.update(_linearise(mol, _spanned_angle(mol), 1)) + mols = _linear_system(diphenylethane_mols) with tempfile.TemporaryDirectory() as tmpdir: - config = Config( - platform="cpu", - output_directory=tmpdir, - linear_torsions=mode, - ghost_modifications=False, + config, runner = _runner(mols, tmpdir, linear_torsions=mode) + schedule = runner._config.lambda_schedule + + assert _torsion_k(schedule, [0.0, 0.5]) == pytest.approx([4.0, 2.0]) + assert schedule.has_molecule_schedule(0) == (mode == "auto") + if mode == "auto": + assert _torsion_k(schedule.get_molecule_schedule(0), [0.0, 0.5]) == ( + pytest.approx([4.0, 0.0]) + ) + + assert not config.lambda_schedule.has_molecule_schedule(0) + assert runner._config.as_dict()["linear_torsions"] == ( + "true" if mode == "auto" else "false" ) - runner = Runner(mols, config) - expected = [4.0, 0.0] if mode == "auto" else [4.0, 2.0] - assert _torsion_k(runner._config.lambda_schedule, [0.0, 0.5]) == ( - pytest.approx(expected) - ) + +def test_runner_linear_torsions_true_fails(diphenylethane_mols): + """ + A window that can't be applied is an error when the option is forced on. + """ + schedule = LambdaSchedule.standard_morph() + schedule.set_equation( + stage="morph", lever="torsion_k", equation=schedule.lam() ** 2 + ) + mols = _linear_system(diphenylethane_mols) + + with tempfile.TemporaryDirectory() as tmpdir: + with pytest.raises(ValueError, match="linear_torsions"): + _runner(mols, tmpdir, linear_torsions="true", lambda_schedule=schedule) + + +def test_restart_legacy_linear_torsions(): + """ + Restarting a simulation saved before the option existed requires the + option's behaviour at the time. + """ + from somd2.runner._base import RunnerBase + + RunnerBase._compare_configs({}, {"linear_torsions": "false"}) + with pytest.raises(ValueError, match="linear_torsions"): + RunnerBase._compare_configs({}, {"linear_torsions": "true"}) From f829ccb90b322a58f0c161b8b54e2e691ac714a9 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Wed, 11 Nov 2026 12:07:23 +0000 Subject: [PATCH 3/7] Record applied torsion windows and warn about terms at linear end states. --- src/somd2/_utils/_linear_angles.py | 23 ++++---- src/somd2/config/_config.py | 15 +++--- src/somd2/runner/_base.py | 71 ++++++++++++++----------- tests/schedules/test_linear_torsions.py | 52 ++++++++++++------ 4 files changed, 92 insertions(+), 69 deletions(-) diff --git a/src/somd2/_utils/_linear_angles.py b/src/somd2/_utils/_linear_angles.py index 5a8fbdf5..e2bf261d 100644 --- a/src/somd2/_utils/_linear_angles.py +++ b/src/somd2/_utils/_linear_angles.py @@ -25,10 +25,11 @@ _LINEAR_ANGLE = 170.0 -def find_linear_angles(mol, require_terms=True, max_angle=_LINEAR_ANGLE): +def find_linear_angles(mol, max_angle=_LINEAR_ANGLE): """ Find the angles of a perturbable molecule that are linear at only one end - state. + state, and whether non-zero dihedrals or impropers pass through them, i.e. + have three consecutive atoms that are the atoms of the angle. Parameters ---------- @@ -36,11 +37,6 @@ def find_linear_angles(mol, require_terms=True, max_angle=_LINEAR_ANGLE): mol : sire.mol.Molecule The perturbable molecule. - require_terms : bool - Whether to only return angles that a non-zero dihedral or improper - passes through at the end state where the angle isn't linear, i.e. - with three consecutive atoms of the term being the atoms of the angle. - max_angle : float The equilibrium angle, in degrees, at or above which an angle is linear. @@ -48,10 +44,11 @@ def find_linear_angles(mol, require_terms=True, max_angle=_LINEAR_ANGLE): Returns ------- - angles : list of ((int, int, int), int, bool) + angles : list of ((int, int, int), int, bool, bool) The atom indices of each angle, with the central atom in the middle, the end state at which it is linear, and whether a non-zero dihedral - or improper passes through it at that end state. + or improper passes through it at the other end state and at the end + state where it's linear. """ from math import degrees @@ -62,10 +59,9 @@ def find_linear_angles(mol, require_terms=True, max_angle=_LINEAR_ANGLE): theta = Symbol("theta") def potentials(name): - try: - return mol.property(name).potentials() - except Exception: + if not mol.has_property(name): return [] + return mol.property(name).potentials() def theta0s(state): result = {} @@ -109,9 +105,8 @@ def spanned(state): terms = [spanned(0), spanned(1)] return [ - (key, state, frozenset(key) in terms[state]) + (key, state, frozenset(key) in terms[1 - state], frozenset(key) in terms[state]) for key, state in linear - if not require_terms or frozenset(key) in terms[1 - state] ] diff --git a/src/somd2/config/_config.py b/src/somd2/config/_config.py index 50b8d651..330efa58 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -131,12 +131,13 @@ class Config: "restraint_search_frequency", "gcmc_batch_size", "gcmc_num_attempts", + "linear_torsions", ] ) - # The behaviour of options added after a simulation was started, which - # restarts must match when the saved config doesn't include them. - _restart_legacy_values = {"linear_torsions": "false"} + # Values recorded by runners that didn't exist when a simulation was + # started, which restarts must match when the saved config lacks them. + _restart_legacy_values = {"linear_torsion_windows": ""} def __init__( self, @@ -980,6 +981,9 @@ def from_yaml(path): d = _yaml_to_dict(path) + # Recorded by a runner, rather than set by the user. + d.pop("linear_torsion_windows", None) + return Config(**d) def as_dict(self, sire_compatible=False): @@ -1019,11 +1023,6 @@ def as_dict(self, sire_compatible=False): # Record the form that is used, so that restarts compare like with like. d["softcore_form"] = self.softcore_form - # Likewise, record whether a runner applied the torsion window. - applied = d.pop("linear_torsions_applied", None) - if applied is not None: - d["linear_torsions"] = str(applied).lower() - # Handle the lambda schedule separately so that we can use simplified # keyword options. diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index 42e21b52..c8e8eb6a 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -123,9 +123,8 @@ def _set_config(self, config): msg = "'config' must be of type 'somd2.config.Config'" _logger.error(msg) raise TypeError(msg) - # The runner modifies its config, e.g. the lambda schedule, so work on a - # copy to keep the user's config unchanged. Sire objects don't support - # deepcopy, but the config pickles, as for spawned worker processes. + # Copy the config, since the runner modifies it, e.g. the lambda schedule. + # Pickle it, as for worker processes, since Sire objects can't be deep copied. import pickle as _pickle self._config = _pickle.loads(_pickle.dumps(config)) @@ -617,7 +616,7 @@ def _apply_linear_torsions(self): the 'linear_torsions' option. """ mode = self._config.linear_torsions - self._config._linear_torsions_applied = False + self._config._linear_torsion_windows = "" if mode == "false": return @@ -637,25 +636,31 @@ def _apply_linear_torsions(self): windows = {} for idx, mol in enumerate(perturbable): - found = find_linear_angles(mol, require_terms=mode == "auto") - if not found: - continue - - for angle, state, singular in found: - if singular: + found = [] + for angle, state, bent_terms, linear_terms in find_linear_angles(mol): + atoms = "-".join(str(i) for i in angle) + if linear_terms: _logger.warning( - f"A non-zero torsion or improper passes through angle " - f"{'-'.join(str(i) for i in angle)} of perturbable molecule " - f"{idx} at {_lam_sym} = {state}, where the angle is linear. " - "The lambda schedule can't prevent its force diverging." + f"A non-zero torsion or improper passes through angle {atoms} " + f"of perturbable molecule {idx} at {_lam_sym} = {state}, where " + "the angle is linear. The lambda schedule can't prevent its " + "force diverging." ) + if bent_terms or mode == "true": + found.append((atoms, state)) + if not found: + continue - start, end = torsion_window({state for _, state, _ in found}) + start, end = torsion_window({state for _, state in found}) base = ( schedule.get_molecule_schedule(idx) if schedule.has_molecule_schedule(idx) else schedule - ) + ).clone() + for other in range(len(perturbable)): + if base.has_molecule_schedule(other): + base.remove_molecule_schedule(other) + try: mol_schedule = linear_torsions(base, start, end) except ValueError as e: @@ -666,25 +671,25 @@ def _apply_linear_torsions(self): _logger.warning(msg) continue - for other in range(len(perturbable)): - if mol_schedule.has_molecule_schedule(other): - mol_schedule.remove_molecule_schedule(other) + # Torsions that don't change need no window. + if mol_schedule == base: + continue windows[idx] = (mol_schedule, start, end, found) if not windows: if mode == "true": _logger.warning( - "'linear_torsions' is enabled, but no angle of a perturbable " - "molecule becomes linear, so the lambda schedule is unchanged." + "'linear_torsions' is enabled, but no torsions of a perturbable " + "molecule with an angle that becomes linear change, so the " + "lambda schedule is unchanged." ) return for idx, (mol_schedule, start, end, found) in windows.items(): schedule.set_molecule_schedule(idx, mol_schedule) angles = ", ".join( - f"{'-'.join(str(i) for i in angle)} ({_lam_sym} = {state})" - for angle, state, _ in found + f"{atoms} ({_lam_sym} = {state})" for atoms, state in found ) _logger.info( f"Angles of perturbable molecule {idx} become linear at one end " @@ -693,7 +698,9 @@ def _apply_linear_torsions(self): "each stage in which they change." ) - self._config._linear_torsions_applied = True + self._config._linear_torsion_windows = ";".join( + f"{idx}:{start}-{end}" for idx, (_, start, end, _) in windows.items() + ) def _set_schedule(self, pert_idxs, ion_indices): """ @@ -2494,13 +2501,15 @@ def _compare_configs(config1, config2): from sire.units import GeneralUnit as _GeneralUnit - for key, legacy in _Config._restart_legacy_values.items(): - if key not in config1 and config2.get(key, legacy) != legacy: - raise ValueError( - f"{key} is '{config2[key]}', but the simulation was started " - f"before this option existed, when it was '{legacy}'. Set " - f"{key} to '{legacy}' to restart it." - ) + legacy = _Config._restart_legacy_values["linear_torsion_windows"] + windows = config2.get("linear_torsion_windows", legacy) + if "linear_torsion_windows" not in config1 and windows != legacy: + raise ValueError( + "Angles that become linear were detected, so torsion windows " + f"would be applied ({windows}), but the simulation was started " + "before 'linear_torsions' existed. Set 'linear_torsions' to " + "'false' to restart it." + ) allowed_diffs = _Config._restart_allowed_diffs for key in config1.keys(): diff --git a/tests/schedules/test_linear_torsions.py b/tests/schedules/test_linear_torsions.py index 7303ab6f..5eb89d51 100644 --- a/tests/schedules/test_linear_torsions.py +++ b/tests/schedules/test_linear_torsions.py @@ -135,20 +135,16 @@ def test_find_linear_angles(diphenylethane_mols): angle = _spanned_angle(mol) key = (min(angle[0], angle[2]), angle[1], max(angle[0], angle[2])) - # Terms through the angle at the linear end state are flagged. - assert find_linear_angles(_linearise(mol, angle, 1)) == [(key, 1, True)] + assert find_linear_angles(_linearise(mol, angle, 1)) == [(key, 1, True, True)] linear = _linearise(mol, angle, 1, remove_terms=(1,)) - assert find_linear_angles(linear) == [(key, 1, False)] + assert find_linear_angles(linear) == [(key, 1, True, False)] - # Terms only at the linear end state don't trigger detection. linear = _linearise(mol, angle, 1, remove_terms=(0,)) - assert find_linear_angles(linear) == [] - assert find_linear_angles(linear, require_terms=False) == [(key, 1, True)] + assert find_linear_angles(linear) == [(key, 1, False, True)] bare = _linearise(mol, angle, 0, remove_terms=(0, 1)) - assert find_linear_angles(bare) == [] - assert find_linear_angles(bare, require_terms=False) == [(key, 0, False)] + assert find_linear_angles(bare) == [(key, 0, False, False)] def test_find_linear_angles_no_angles(diphenylethane_mols): @@ -190,8 +186,11 @@ def _runner(mols, tmpdir, **kwargs): def test_runner_linear_torsions(diphenylethane_mols, mode): """ The runner gives the affected molecule its own schedule only when the - option allows it, and leaves the user's config unchanged. + option allows it, records the window, and leaves the user's config + unchanged. """ + from somd2.config import Config + mols = _linear_system(diphenylethane_mols) with tempfile.TemporaryDirectory() as tmpdir: @@ -206,9 +205,30 @@ def test_runner_linear_torsions(diphenylethane_mols, mode): ) assert not config.lambda_schedule.has_molecule_schedule(0) - assert runner._config.as_dict()["linear_torsions"] == ( - "true" if mode == "auto" else "false" - ) + + d = runner._config.as_dict() + assert d["linear_torsions"] == mode + assert d["linear_torsion_windows"] == ("0:0.0-0.5" if mode == "auto" else "") + + from somd2.io import dict_to_yaml + + dict_to_yaml(d, "saved.yaml", tmpdir) + assert Config.from_yaml(f"{tmpdir}/saved.yaml").linear_torsions == mode + + +def test_runner_linear_torsions_constant(diphenylethane_mols): + """ + No window is applied when the schedule doesn't change the torsions. + """ + schedule = LambdaSchedule.standard_morph() + for lever in ("torsion_k", "torsion_phase"): + schedule.set_equation(stage="morph", lever=lever, equation=schedule.initial()) + mols = _linear_system(diphenylethane_mols) + + with tempfile.TemporaryDirectory() as tmpdir: + _, runner = _runner(mols, tmpdir, lambda_schedule=schedule) + assert not runner._config.lambda_schedule.has_molecule_schedule(0) + assert runner._config.as_dict()["linear_torsion_windows"] == "" def test_runner_linear_torsions_true_fails(diphenylethane_mols): @@ -228,11 +248,11 @@ def test_runner_linear_torsions_true_fails(diphenylethane_mols): def test_restart_legacy_linear_torsions(): """ - Restarting a simulation saved before the option existed requires the - option's behaviour at the time. + A simulation saved before the option existed can only be restarted without + torsion windows. """ from somd2.runner._base import RunnerBase - RunnerBase._compare_configs({}, {"linear_torsions": "false"}) + RunnerBase._compare_configs({}, {"linear_torsion_windows": ""}) with pytest.raises(ValueError, match="linear_torsions"): - RunnerBase._compare_configs({}, {"linear_torsions": "true"}) + RunnerBase._compare_configs({}, {"linear_torsion_windows": "0:0.0-0.5"}) From 044a54a93a13297b02a7f4b2150abae0953c269f Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Wed, 11 Nov 2026 12:24:41 +0000 Subject: [PATCH 4/7] Use a smoothstep for the linear_torsions window. --- src/somd2/_utils/_schedules.py | 7 +++++-- tests/schedules/test_linear_torsions.py | 11 ++++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/somd2/_utils/_schedules.py b/src/somd2/_utils/_schedules.py index be17cbd7..07d1a734 100644 --- a/src/somd2/_utils/_schedules.py +++ b/src/somd2/_utils/_schedules.py @@ -438,7 +438,9 @@ def linear_torsions(schedule, start, end): are held at their initial and final values either side of it. This keeps torsions and impropers through an angle that becomes linear at one end state at that end state's values while the angle is near linear, since - their forces diverge as its atoms become collinear. + their forces diverge as its atoms become collinear. Within the window they + follow a smoothstep, which spreads out the costly change to and from zero + at its ends. Parameters ---------- @@ -467,7 +469,8 @@ def linear_torsions(schedule, start, end): s = schedule.clone() lam, initial, final = s.lam(), s.initial(), s.final() - f = Min(Expression(1), Max(Expression(0), (lam - start) * (1 / (end - start)))) + x = Min(Expression(1), Max(Expression(0), (lam - start) * (1 / (end - start)))) + f = x * x * (3 - 2 * x) target = (1 - f) * initial + f * final def values(equation): diff --git a/tests/schedules/test_linear_torsions.py b/tests/schedules/test_linear_torsions.py index 5eb89d51..6b340639 100644 --- a/tests/schedules/test_linear_torsions.py +++ b/tests/schedules/test_linear_torsions.py @@ -37,7 +37,16 @@ def test_linear_torsions_stages(): """ schedule = linear_torsions(ring_break_morph(), 0.0, 0.5) values = _torsion_k(schedule, [0.2, 0.4, 0.5, 0.6]) - assert values == pytest.approx([4.0, 2.4, 0.0, 0.0]) + assert values == pytest.approx([4.0, 2.592, 0.0, 0.0]) + + +def test_linear_torsions_smoothstep(): + """ + Torsions follow a smoothstep within the window. + """ + schedule = linear_torsions(LambdaSchedule.standard_morph(), 0.0, 0.5) + values = _torsion_k(schedule, [0.125, 0.375]) + assert values == pytest.approx([3.375, 0.625]) def test_linear_torsions_idempotent(): From a7f782ba42ab4663581edfd5635f325e8fbdb80d Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Wed, 11 Nov 2026 12:26:25 +0000 Subject: [PATCH 5/7] Warn when angles become linear at both end states. --- src/somd2/runner/_base.py | 7 ++++++ tests/schedules/test_linear_torsions.py | 31 +++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index c8e8eb6a..2ab7a273 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -697,6 +697,13 @@ def _apply_linear_torsions(self): f"and impropers will change over the fraction [{start}, {end}] of " "each stage in which they change." ) + if len({state for _, state in found}) > 1: + _logger.warning( + f"Angles of perturbable molecule {idx} become linear at both end " + "states, so its torsions change over the middle of each stage. " + "This leaves them less margin before the angles are near " + "linear, so check this perturbation for instabilities." + ) self._config._linear_torsion_windows = ";".join( f"{idx}:{start}-{end}" for idx, (_, start, end, _) in windows.items() diff --git a/tests/schedules/test_linear_torsions.py b/tests/schedules/test_linear_torsions.py index 6b340639..cfe1f585 100644 --- a/tests/schedules/test_linear_torsions.py +++ b/tests/schedules/test_linear_torsions.py @@ -265,3 +265,34 @@ def test_restart_legacy_linear_torsions(): RunnerBase._compare_configs({}, {"linear_torsion_windows": ""}) with pytest.raises(ValueError, match="linear_torsions"): RunnerBase._compare_configs({}, {"linear_torsion_windows": "0:0.0-0.5"}) + + +def test_runner_linear_torsions_both_ends(diphenylethane_mols): + """ + A molecule with angles that become linear at both end states gets the + middle window and a warning. + """ + from somd2 import _logger + + mols = diphenylethane_mols.clone() + mol = mols.molecules("property is_perturbable")[0] + info = mol.info() + + angles = [] + for p in mol.property("dihedral0").potentials(): + if p.function().is_zero(): + continue + idx = tuple(info.atom_idx(a).value() for a in (p.atom0(), p.atom1(), p.atom2())) + if all(set(idx) != set(a) for a in angles): + angles.append(idx) + mol = _linearise(mol, angles[0], 1) + mol = _linearise(mol, angles[1], 0) + mols.update(mol) + + with tempfile.TemporaryDirectory() as tmpdir: + _, runner = _runner(mols, tmpdir) + assert runner._config.as_dict()["linear_torsion_windows"] == "0:0.25-0.75" + log = (runner._config.output_directory / runner._config.log_file).read_text() + _logger.remove() + + assert "both end states" in log From 7b8497b7f90d8e6330608413164f30378c60e941 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Wed, 11 Nov 2026 12:37:08 +0000 Subject: [PATCH 6/7] Rename linear_torsions to torsion_window. --- CHANGELOG.md | 2 +- README.md | 6 +- src/somd2/_utils/_linear_angles.py | 4 +- src/somd2/_utils/_schedules.py | 4 +- src/somd2/config/_config.py | 40 +++++----- src/somd2/runner/_base.py | 34 ++++----- ...ear_torsions.py => test_torsion_window.py} | 76 +++++++++---------- 7 files changed, 83 insertions(+), 83 deletions(-) rename tests/schedules/{test_linear_torsions.py => test_torsion_window.py} (79%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d8ed461..be09aff4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,7 +42,7 @@ Changelog * Run GCMC simulations in the NVT ensemble, ignoring the pressure, since the osmotic ensemble isn't valid for GCMC of solvent water: the number of waters is barely fixed, so it drifts. GCMC runs started with a pressure can't be restarted [#281](https://github.com/OpenBioSim/somd2/pull/281). * Added support for Python 3.13 and 3.14, and dropped support for Python 3.10 and 3.11 [#283](https://github.com/OpenBioSim/somd2/pull/283). * Fixed the regular runner reporting success when a lambda window failed, unless it was the last to finish. The other windows still run, then `Runner.run()` raises an error listing the failed windows and `somd2` exits with a non-zero status. The overall performance is now summed over all windows rather than taken from the last to finish [#285](https://github.com/OpenBioSim/somd2/pull/285). -* Add a `linear_torsions` 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 `linear_torsions` set to `false` [#287](https://github.com/OpenBioSim/somd2/pull/287). +* 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). [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 e7608441..670e5f8a 100644 --- a/README.md +++ b/README.md @@ -665,15 +665,15 @@ restraints can be generated automatically. See the sections below. When an angle becomes linear at one end state, e.g. a C=C bond that becomes a C≡C bond, the forces from torsions and impropers through it diverge as its atoms become collinear, which can crash simulations at intermediate λ. By -default (`--linear-torsions auto`), SOMD2 detects angles that are linear at +default (`--torsion-window auto`), SOMD2 detects angles that are linear at only one end state and have a non-zero torsion or improper through them at the other end state. The torsions and impropers of each affected molecule then change over only part of each stage of the schedule: the first half when its angles are linear at λ = 1, the second half when they are linear at λ = 0, or the middle half when both occur. Other molecules are unaffected, and the angles -are logged. Use `--linear-torsions true` to apply this whenever an angle becomes +are logged. Use `--torsion-window true` to apply this whenever an angle becomes linear, or `false` to disable it. Simulations started before this option -existed must be restarted with `--linear-torsions false`. +existed must be restarted with `--torsion-window false`. diff --git a/src/somd2/_utils/_linear_angles.py b/src/somd2/_utils/_linear_angles.py index e2bf261d..cb1ba429 100644 --- a/src/somd2/_utils/_linear_angles.py +++ b/src/somd2/_utils/_linear_angles.py @@ -19,7 +19,7 @@ # along with SOMD2. If not, see . ##################################################################### -__all__ = ["find_linear_angles", "torsion_window"] +__all__ = ["find_linear_angles", "torsion_window_bounds"] # Angles with an equilibrium value of at least this many degrees are linear. _LINEAR_ANGLE = 170.0 @@ -110,7 +110,7 @@ def spanned(state): ] -def torsion_window(states): +def torsion_window_bounds(states): """ Return the fraction of each morph stage over which torsions should change, given the end states at which angles become linear. diff --git a/src/somd2/_utils/_schedules.py b/src/somd2/_utils/_schedules.py index 07d1a734..61a4f160 100644 --- a/src/somd2/_utils/_schedules.py +++ b/src/somd2/_utils/_schedules.py @@ -23,7 +23,7 @@ "abfe_alchemical_ion", "annihilate", "decouple", - "linear_torsions", + "windowed_torsions", "ring_break_morph", "reverse_ring_break_morph", ] @@ -431,7 +431,7 @@ def reverse_ring_break_morph(): return ring_break_morph().reverse() -def linear_torsions(schedule, start, end): +def windowed_torsions(schedule, start, end): """ Return a copy of a lambda schedule in which the torsion levers change over the fraction [start, end] of each stage where they change linearly, and diff --git a/src/somd2/config/_config.py b/src/somd2/config/_config.py index 330efa58..e48e9ef2 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -75,7 +75,7 @@ class Config: ], "log_level": [level.lower() for level in _logger._core.levels], "softcore_form": ["auto", "zacharias", "taylor", "beutler"], - "linear_torsions": ["auto", "true", "false"], + "torsion_window": ["auto", "true", "false"], "precision": ["single", "mixed", "double"], } @@ -131,13 +131,13 @@ class Config: "restraint_search_frequency", "gcmc_batch_size", "gcmc_num_attempts", - "linear_torsions", + "torsion_window", ] ) # Values recorded by runners that didn't exist when a simulation was # started, which restarts must match when the saved config lacks them. - _restart_legacy_values = {"linear_torsion_windows": ""} + _restart_legacy_values = {"torsion_windows": ""} def __init__( self, @@ -164,7 +164,7 @@ def __init__( lambda_energy=None, lambda_schedule="standard_morph", charge_scale_factor=0.2, - linear_torsions="auto", + torsion_window="auto", swap_end_states=False, shift_coulomb="1 A", shift_delta="1.5 A", @@ -339,7 +339,7 @@ def __init__( charge_scale_factor: float Factor by which to scale charges for charge scaled morph. - linear_torsions: str + torsion_window: str Whether to change torsions and impropers over only part of each morph stage, so that those through an angle that becomes linear at one end state are at that end state's values while the angle is @@ -844,7 +844,7 @@ def __init__( self.lambda_values = lambda_values self.lambda_energy = lambda_energy self.charge_scale_factor = charge_scale_factor - self.linear_torsions = linear_torsions + self.torsion_window = torsion_window self.swap_end_states = swap_end_states self.shift_coulomb = shift_coulomb self.shift_delta = shift_delta @@ -982,7 +982,7 @@ def from_yaml(path): d = _yaml_to_dict(path) # Recorded by a runner, rather than set by the user. - d.pop("linear_torsion_windows", None) + d.pop("torsion_windows", None) return Config(**d) @@ -1581,22 +1581,22 @@ def charge_scale_factor(self, charge_scale_factor): ) @property - def linear_torsions(self): - return self._linear_torsions + def torsion_window(self): + return self._torsion_window - @linear_torsions.setter - def linear_torsions(self, linear_torsions): - if isinstance(linear_torsions, bool): - linear_torsions = str(linear_torsions) - if not isinstance(linear_torsions, str): - raise TypeError("'linear_torsions' must be of type 'str' or 'bool'") - linear_torsions = linear_torsions.lower().replace(" ", "") - if linear_torsions not in self._choices["linear_torsions"]: + @torsion_window.setter + def torsion_window(self, torsion_window): + if isinstance(torsion_window, bool): + torsion_window = str(torsion_window) + if not isinstance(torsion_window, str): + raise TypeError("'torsion_window' must be of type 'str' or 'bool'") + torsion_window = torsion_window.lower().replace(" ", "") + if torsion_window not in self._choices["torsion_window"]: raise ValueError( - "'linear_torsions' not recognised. Valid options are: " - f"{', '.join(self._choices['linear_torsions'])}" + "'torsion_window' not recognised. Valid options are: " + f"{', '.join(self._choices['torsion_window'])}" ) - self._linear_torsions = linear_torsions + self._torsion_window = torsion_window @property def swap_end_states(self): diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index 2ab7a273..597e6b38 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -609,27 +609,27 @@ def _add_alchemical_ions(self): return ion_indices - def _apply_linear_torsions(self): + def _apply_torsion_window(self): """ Change torsions over part of each morph stage when an angle of a perturbable molecule becomes linear at one end state, according to - the 'linear_torsions' option. + the 'torsion_window' option. """ - mode = self._config.linear_torsions - self._config._linear_torsion_windows = "" + mode = self._config.torsion_window + self._config._torsion_windows = "" if mode == "false": return if self._config._lambda_schedule_name in ("annihilate", "decouple"): if mode == "true": _logger.warning( - "'linear_torsions' is ignored for the " + "'torsion_window' is ignored for the " f"'{self._config._lambda_schedule_name}' lambda schedule." ) return - from .._utils._linear_angles import find_linear_angles, torsion_window - from .._utils._schedules import linear_torsions + from .._utils._linear_angles import find_linear_angles, torsion_window_bounds + from .._utils._schedules import windowed_torsions schedule = self._config._lambda_schedule perturbable = self._system.molecules()["perturbable"].molecules() @@ -651,7 +651,7 @@ def _apply_linear_torsions(self): if not found: continue - start, end = torsion_window({state for _, state in found}) + start, end = torsion_window_bounds({state for _, state in found}) base = ( schedule.get_molecule_schedule(idx) if schedule.has_molecule_schedule(idx) @@ -662,9 +662,9 @@ def _apply_linear_torsions(self): base.remove_molecule_schedule(other) try: - mol_schedule = linear_torsions(base, start, end) + mol_schedule = windowed_torsions(base, start, end) except ValueError as e: - msg = f"Unable to apply 'linear_torsions' to perturbable molecule {idx}: {e}" + msg = f"Unable to apply 'torsion_window' to perturbable molecule {idx}: {e}" if mode == "true": _logger.error(msg) raise ValueError(msg) @@ -680,7 +680,7 @@ def _apply_linear_torsions(self): if not windows: if mode == "true": _logger.warning( - "'linear_torsions' is enabled, but no torsions of a perturbable " + "'torsion_window' is enabled, but no torsions of a perturbable " "molecule with an angle that becomes linear change, so the " "lambda schedule is unchanged." ) @@ -705,7 +705,7 @@ def _apply_linear_torsions(self): "linear, so check this perturbation for instabilities." ) - self._config._linear_torsion_windows = ";".join( + self._config._torsion_windows = ";".join( f"{idx}:{start}-{end}" for idx, (_, start, end, _) in windows.items() ) @@ -791,7 +791,7 @@ def _set_schedule(self, pert_idxs, ion_indices): for pert_idx in ion_indices: schedule.set_molecule_schedule(pert_idx, ion_schedule) - self._apply_linear_torsions() + self._apply_torsion_window() # Set the lambda values. if self._config.lambda_values: @@ -2508,13 +2508,13 @@ def _compare_configs(config1, config2): from sire.units import GeneralUnit as _GeneralUnit - legacy = _Config._restart_legacy_values["linear_torsion_windows"] - windows = config2.get("linear_torsion_windows", legacy) - if "linear_torsion_windows" not in config1 and windows != legacy: + legacy = _Config._restart_legacy_values["torsion_windows"] + windows = config2.get("torsion_windows", legacy) + if "torsion_windows" not in config1 and windows != legacy: raise ValueError( "Angles that become linear were detected, so torsion windows " f"would be applied ({windows}), but the simulation was started " - "before 'linear_torsions' existed. Set 'linear_torsions' to " + "before 'torsion_window' existed. Set 'torsion_window' to " "'false' to restart it." ) diff --git a/tests/schedules/test_linear_torsions.py b/tests/schedules/test_torsion_window.py similarity index 79% rename from tests/schedules/test_linear_torsions.py rename to tests/schedules/test_torsion_window.py index cfe1f585..cc475ec3 100644 --- a/tests/schedules/test_linear_torsions.py +++ b/tests/schedules/test_torsion_window.py @@ -6,8 +6,8 @@ from sire.legacy.CAS import Symbol from sire.legacy.MM import AmberAngle, FourAtomFunctions, ThreeAtomFunctions -from somd2._utils._linear_angles import find_linear_angles, torsion_window -from somd2._utils._schedules import linear_torsions, ring_break_morph +from somd2._utils._linear_angles import find_linear_angles, torsion_window_bounds +from somd2._utils._schedules import ring_break_morph, windowed_torsions def _torsion_k(schedule, lambda_values): @@ -22,56 +22,56 @@ def _torsion_k(schedule, lambda_values): ((0.25, 0.75), [4.0, 4.0, 2.0, 0.0, 0.0]), ], ) -def test_linear_torsions_window(window, expected): +def test_windowed_torsions_window(window, expected): """ Torsions change over the window only, and other levers are unchanged. """ - schedule = linear_torsions(LambdaSchedule.standard_morph(), *window) + schedule = windowed_torsions(LambdaSchedule.standard_morph(), *window) assert _torsion_k(schedule, [0.0, 0.25, 0.5, 0.75, 1.0]) == pytest.approx(expected) assert schedule.morph("*", "angle_size", 2.0, 4.0, 0.25) == pytest.approx(2.5) -def test_linear_torsions_stages(): +def test_windowed_torsions_stages(): """ The window applies within each stage in which the torsions change linearly. """ - schedule = linear_torsions(ring_break_morph(), 0.0, 0.5) + schedule = windowed_torsions(ring_break_morph(), 0.0, 0.5) values = _torsion_k(schedule, [0.2, 0.4, 0.5, 0.6]) assert values == pytest.approx([4.0, 2.592, 0.0, 0.0]) -def test_linear_torsions_smoothstep(): +def test_windowed_torsions_smoothstep(): """ Torsions follow a smoothstep within the window. """ - schedule = linear_torsions(LambdaSchedule.standard_morph(), 0.0, 0.5) + schedule = windowed_torsions(LambdaSchedule.standard_morph(), 0.0, 0.5) values = _torsion_k(schedule, [0.125, 0.375]) assert values == pytest.approx([3.375, 0.625]) -def test_linear_torsions_idempotent(): - schedule = linear_torsions(LambdaSchedule.standard_morph(), 0.0, 0.5) - assert linear_torsions(schedule, 0.0, 0.5) == schedule +def test_windowed_torsions_idempotent(): + schedule = windowed_torsions(LambdaSchedule.standard_morph(), 0.0, 0.5) + assert windowed_torsions(schedule, 0.0, 0.5) == schedule -def test_linear_torsions_invalid(): +def test_windowed_torsions_invalid(): with pytest.raises(ValueError): - linear_torsions(LambdaSchedule.standard_morph(), 0.5, 0.5) + windowed_torsions(LambdaSchedule.standard_morph(), 0.5, 0.5) schedule = LambdaSchedule.standard_morph() schedule.set_equation( stage="morph", lever="torsion_k", equation=schedule.lam() ** 2 ) with pytest.raises(ValueError): - linear_torsions(schedule, 0.0, 0.5) + windowed_torsions(schedule, 0.0, 0.5) -def test_torsion_window(): - assert torsion_window({1}) == (0.0, 0.5) - assert torsion_window({0}) == (0.5, 1.0) - assert torsion_window({0, 1}) == (0.25, 0.75) +def test_torsion_window_bounds(): + assert torsion_window_bounds({1}) == (0.0, 0.5) + assert torsion_window_bounds({0}) == (0.5, 1.0) + assert torsion_window_bounds({0, 1}) == (0.25, 0.75) with pytest.raises(ValueError): - torsion_window(set()) + torsion_window_bounds(set()) def _linearise(mol, angle, state, remove_terms=()): @@ -162,13 +162,13 @@ def test_find_linear_angles_no_angles(diphenylethane_mols): assert find_linear_angles(mol) == [] -def test_linear_torsions_unsupported(): +def test_windowed_torsions_unsupported(): schedule = LambdaSchedule.standard_morph() schedule.set_equation( stage="morph", force="torsion", lever="torsion_k", equation=schedule.final() ) with pytest.raises(ValueError, match="force-specific"): - linear_torsions(schedule, 0.0, 0.5) + windowed_torsions(schedule, 0.0, 0.5) schedule = LambdaSchedule.standard_morph() schedule.set_constant("scale", 0.5) @@ -178,7 +178,7 @@ def test_linear_torsions_unsupported(): equation=schedule.get_constant_symbol("scale") * schedule.final(), ) with pytest.raises(ValueError, match="symbols"): - linear_torsions(schedule, 0.0, 0.5) + windowed_torsions(schedule, 0.0, 0.5) def _runner(mols, tmpdir, **kwargs): @@ -192,7 +192,7 @@ def _runner(mols, tmpdir, **kwargs): @pytest.mark.parametrize("mode", ["auto", "false"]) -def test_runner_linear_torsions(diphenylethane_mols, mode): +def test_runner_torsion_window(diphenylethane_mols, mode): """ The runner gives the affected molecule its own schedule only when the option allows it, records the window, and leaves the user's config @@ -203,7 +203,7 @@ def test_runner_linear_torsions(diphenylethane_mols, mode): mols = _linear_system(diphenylethane_mols) with tempfile.TemporaryDirectory() as tmpdir: - config, runner = _runner(mols, tmpdir, linear_torsions=mode) + config, runner = _runner(mols, tmpdir, torsion_window=mode) schedule = runner._config.lambda_schedule assert _torsion_k(schedule, [0.0, 0.5]) == pytest.approx([4.0, 2.0]) @@ -216,16 +216,16 @@ def test_runner_linear_torsions(diphenylethane_mols, mode): assert not config.lambda_schedule.has_molecule_schedule(0) d = runner._config.as_dict() - assert d["linear_torsions"] == mode - assert d["linear_torsion_windows"] == ("0:0.0-0.5" if mode == "auto" else "") + assert d["torsion_window"] == mode + assert d["torsion_windows"] == ("0:0.0-0.5" if mode == "auto" else "") from somd2.io import dict_to_yaml dict_to_yaml(d, "saved.yaml", tmpdir) - assert Config.from_yaml(f"{tmpdir}/saved.yaml").linear_torsions == mode + assert Config.from_yaml(f"{tmpdir}/saved.yaml").torsion_window == mode -def test_runner_linear_torsions_constant(diphenylethane_mols): +def test_runner_torsion_window_constant(diphenylethane_mols): """ No window is applied when the schedule doesn't change the torsions. """ @@ -237,10 +237,10 @@ def test_runner_linear_torsions_constant(diphenylethane_mols): with tempfile.TemporaryDirectory() as tmpdir: _, runner = _runner(mols, tmpdir, lambda_schedule=schedule) assert not runner._config.lambda_schedule.has_molecule_schedule(0) - assert runner._config.as_dict()["linear_torsion_windows"] == "" + assert runner._config.as_dict()["torsion_windows"] == "" -def test_runner_linear_torsions_true_fails(diphenylethane_mols): +def test_runner_torsion_window_true_fails(diphenylethane_mols): """ A window that can't be applied is an error when the option is forced on. """ @@ -251,23 +251,23 @@ def test_runner_linear_torsions_true_fails(diphenylethane_mols): mols = _linear_system(diphenylethane_mols) with tempfile.TemporaryDirectory() as tmpdir: - with pytest.raises(ValueError, match="linear_torsions"): - _runner(mols, tmpdir, linear_torsions="true", lambda_schedule=schedule) + with pytest.raises(ValueError, match="torsion_window"): + _runner(mols, tmpdir, torsion_window="true", lambda_schedule=schedule) -def test_restart_legacy_linear_torsions(): +def test_restart_legacy_torsion_window(): """ A simulation saved before the option existed can only be restarted without torsion windows. """ from somd2.runner._base import RunnerBase - RunnerBase._compare_configs({}, {"linear_torsion_windows": ""}) - with pytest.raises(ValueError, match="linear_torsions"): - RunnerBase._compare_configs({}, {"linear_torsion_windows": "0:0.0-0.5"}) + RunnerBase._compare_configs({}, {"torsion_windows": ""}) + with pytest.raises(ValueError, match="torsion_window"): + RunnerBase._compare_configs({}, {"torsion_windows": "0:0.0-0.5"}) -def test_runner_linear_torsions_both_ends(diphenylethane_mols): +def test_runner_torsion_window_both_ends(diphenylethane_mols): """ A molecule with angles that become linear at both end states gets the middle window and a warning. @@ -291,7 +291,7 @@ def test_runner_linear_torsions_both_ends(diphenylethane_mols): with tempfile.TemporaryDirectory() as tmpdir: _, runner = _runner(mols, tmpdir) - assert runner._config.as_dict()["linear_torsion_windows"] == "0:0.25-0.75" + assert runner._config.as_dict()["torsion_windows"] == "0:0.25-0.75" log = (runner._config.output_directory / runner._config.log_file).read_text() _logger.remove() From 9cdf0ef15534a03a663cb9dacb7e4297d019fb11 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Wed, 11 Nov 2026 12:43:00 +0000 Subject: [PATCH 7/7] Link perturbations in README features to the lambda schedules section. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 670e5f8a..8051f58a 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ simulations. Built on top of [Sire](https://github.com/OpenBioSim/sire) and ## ✨ Features -- 🧬 **Perturbations**: relative binding free energies, +- 🧬 **[Perturbations](#lambda-schedules)**: relative binding free energies, [absolute binding free energies](#absolute-binding-free-energies), [ring-breaking](#ring-breaking-perturbations), [charge-change](#charge-change-perturbations), and protein mutations.