diff --git a/CHANGELOG.md b/CHANGELOG.md
index f1ec51c2..be09aff4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +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 `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 f83d23a4..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.
@@ -662,6 +662,19 @@ 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 (`--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 `--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 `--torsion-window false`.
+
## 🧬 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..cb1ba429
--- /dev/null
+++ b/src/somd2/_utils/_linear_angles.py
@@ -0,0 +1,136 @@
+######################################################################
+# 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_bounds"]
+
+# Angles with an equilibrium value of at least this many degrees are linear.
+_LINEAR_ANGLE = 170.0
+
+
+def find_linear_angles(mol, max_angle=_LINEAR_ANGLE):
+ """
+ Find the angles of a perturbable molecule that are linear at only one end
+ 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
+ ----------
+
+ mol : sire.mol.Molecule
+ The perturbable molecule.
+
+ max_angle : float
+ The equilibrium angle, in degrees, at or above which an angle is
+ linear.
+
+ Returns
+ -------
+
+ 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 the other end state and at the end
+ state where it's linear.
+ """
+ from math import degrees
+
+ from sire.legacy.CAS import Symbol
+ from sire.legacy.MM import AmberAngle
+
+ info = mol.info()
+ theta = Symbol("theta")
+
+ def potentials(name):
+ if not mol.has_property(name):
+ return []
+ return mol.property(name).potentials()
+
+ def theta0s(state):
+ result = {}
+ for p in potentials(f"angle{state}"):
+ 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
+
+ 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)]
+
+ 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:
+ linear.append((key, 0 if linear0 else 1))
+
+ if not linear:
+ return []
+
+ terms = [spanned(0), spanned(1)]
+
+ return [
+ (key, state, frozenset(key) in terms[1 - state], frozenset(key) in terms[state])
+ for key, state in linear
+ ]
+
+
+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.
+
+ 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..61a4f160 100644
--- a/src/somd2/_utils/_schedules.py
+++ b/src/somd2/_utils/_schedules.py
@@ -23,6 +23,7 @@
"abfe_alchemical_ion",
"annihilate",
"decouple",
+ "windowed_torsions",
"ring_break_morph",
"reverse_ring_break_morph",
]
@@ -428,3 +429,88 @@ def reverse_ring_break_morph():
The lambda schedule.
"""
return ring_break_morph().reverse()
+
+
+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
+ 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. Within the window they
+ follow a smoothstep, which spreads out the costly change to and from zero
+ at its ends.
+
+ 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()
+
+ 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):
+ 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))
+
+ allowed = {str(symbol) for symbol in (lam, initial, final)}
+
+ for stage in s.get_stages():
+ for lever in ("torsion_k", "torsion_phase"):
+ 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))):
+ 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..e48e9ef2 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"],
+ "torsion_window": ["auto", "true", "false"],
"precision": ["single", "mixed", "double"],
}
@@ -130,9 +131,14 @@ class Config:
"restraint_search_frequency",
"gcmc_batch_size",
"gcmc_num_attempts",
+ "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 = {"torsion_windows": ""}
+
def __init__(
self,
log_level="info",
@@ -158,6 +164,7 @@ def __init__(
lambda_energy=None,
lambda_schedule="standard_morph",
charge_scale_factor=0.2,
+ torsion_window="auto",
swap_end_states=False,
shift_coulomb="1 A",
shift_delta="1.5 A",
@@ -332,6 +339,15 @@ def __init__(
charge_scale_factor: float
Factor by which to scale charges for charge scaled morph.
+ 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
+ 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 +844,7 @@ def __init__(
self.lambda_values = lambda_values
self.lambda_energy = lambda_energy
self.charge_scale_factor = charge_scale_factor
+ self.torsion_window = torsion_window
self.swap_end_states = swap_end_states
self.shift_coulomb = shift_coulomb
self.shift_delta = shift_delta
@@ -964,6 +981,9 @@ def from_yaml(path):
d = _yaml_to_dict(path)
+ # Recorded by a runner, rather than set by the user.
+ d.pop("torsion_windows", None)
+
return Config(**d)
def as_dict(self, sire_compatible=False):
@@ -1560,6 +1580,24 @@ def charge_scale_factor(self, charge_scale_factor):
self._charge_scale_factor
)
+ @property
+ def torsion_window(self):
+ return self._torsion_window
+
+ @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(
+ "'torsion_window' not recognised. Valid options are: "
+ f"{', '.join(self._choices['torsion_window'])}"
+ )
+ self._torsion_window = torsion_window
+
@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..597e6b38 100644
--- a/src/somd2/runner/_base.py
+++ b/src/somd2/runner/_base.py
@@ -123,7 +123,11 @@ def _set_config(self, config):
msg = "'config' must be of type 'somd2.config.Config'"
_logger.error(msg)
raise TypeError(msg)
- self._config = config
+ # 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))
self._config._extra_args = {}
# Create the output directory and configure the logger now that the
@@ -605,6 +609,106 @@ def _add_alchemical_ions(self):
return ion_indices
+ 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 'torsion_window' option.
+ """
+ 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(
+ "'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_bounds
+ from .._utils._schedules import windowed_torsions
+
+ schedule = self._config._lambda_schedule
+ perturbable = self._system.molecules()["perturbable"].molecules()
+
+ windows = {}
+ for idx, mol in enumerate(perturbable):
+ 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 {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_bounds({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 = windowed_torsions(base, start, end)
+ except ValueError as e:
+ msg = f"Unable to apply 'torsion_window' to perturbable molecule {idx}: {e}"
+ if mode == "true":
+ _logger.error(msg)
+ raise ValueError(msg)
+ _logger.warning(msg)
+ continue
+
+ # 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(
+ "'torsion_window' 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"{atoms} ({_lam_sym} = {state})" for atoms, 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."
+ )
+ 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._torsion_windows = ";".join(
+ f"{idx}:{start}-{end}" for idx, (_, start, end, _) in windows.items()
+ )
+
def _set_schedule(self, pert_idxs, ion_indices):
"""
Set the soft-core form, the lambda schedule and values, and the REST2
@@ -687,6 +791,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_torsion_window()
+
# Set the lambda values.
if self._config.lambda_values:
self._lambda_values = self._config.lambda_values
@@ -2402,6 +2508,16 @@ def _compare_configs(config1, config2):
from sire.units import GeneralUnit as _GeneralUnit
+ 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 'torsion_window' existed. Set 'torsion_window' to "
+ "'false' to restart it."
+ )
+
allowed_diffs = _Config._restart_allowed_diffs
for key in config1.keys():
if key not in allowed_diffs:
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_torsion_window.py b/tests/schedules/test_torsion_window.py
new file mode 100644
index 00000000..cc475ec3
--- /dev/null
+++ b/tests/schedules/test_torsion_window.py
@@ -0,0 +1,298 @@
+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_bounds
+from somd2._utils._schedules import ring_break_morph, windowed_torsions
+
+
+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_windowed_torsions_window(window, expected):
+ """
+ Torsions change over the window only, and other levers are unchanged.
+ """
+ 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_windowed_torsions_stages():
+ """
+ The window applies within each stage in which the torsions change linearly.
+ """
+ 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_windowed_torsions_smoothstep():
+ """
+ Torsions follow a smoothstep within the window.
+ """
+ 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_windowed_torsions_idempotent():
+ schedule = windowed_torsions(LambdaSchedule.standard_morph(), 0.0, 0.5)
+ assert windowed_torsions(schedule, 0.0, 0.5) == schedule
+
+
+def test_windowed_torsions_invalid():
+ with pytest.raises(ValueError):
+ 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):
+ windowed_torsions(schedule, 0.0, 0.5)
+
+
+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_bounds(set())
+
+
+def _linearise(mol, angle, state, remove_terms=()):
+ """
+ Set the equilibrium value of an angle to 180 degrees at an end state, and
+ remove the dihedrals and impropers that pass through it at the given end
+ states.
+ """
+ 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()
+
+ 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()
+
+
+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 _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) == []
+
+ angle = _spanned_angle(mol)
+ key = (min(angle[0], angle[2]), angle[1], max(angle[0], angle[2]))
+
+ 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, True, False)]
+
+ linear = _linearise(mol, angle, 1, remove_terms=(0,))
+ assert find_linear_angles(linear) == [(key, 1, False, True)]
+
+ bare = _linearise(mol, angle, 0, remove_terms=(0, 1))
+ assert find_linear_angles(bare) == [(key, 0, False, 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_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"):
+ windowed_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"):
+ windowed_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_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
+ unchanged.
+ """
+ from somd2.config import Config
+
+ mols = _linear_system(diphenylethane_mols)
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ 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])
+ 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)
+
+ d = runner._config.as_dict()
+ 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").torsion_window == mode
+
+
+def test_runner_torsion_window_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()["torsion_windows"] == ""
+
+
+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.
+ """
+ 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="torsion_window"):
+ _runner(mols, tmpdir, torsion_window="true", lambda_schedule=schedule)
+
+
+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({}, {"torsion_windows": ""})
+ with pytest.raises(ValueError, match="torsion_window"):
+ RunnerBase._compare_configs({}, {"torsion_windows": "0:0.0-0.5"})
+
+
+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.
+ """
+ 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()["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