Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
--------------------------------------------------------------------------------------
Expand Down
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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`.

<a id="absolute-binding-free-energies"></a>

## 🧬 Absolute binding free energies
Expand Down
136 changes: 136 additions & 0 deletions src/somd2/_utils/_linear_angles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
######################################################################
# SOMD2: GPU accelerated alchemical free-energy engine.
#
# Copyright: 2023-2026
#
# Authors: The OpenBioSim Team <[email protected]>
#
# 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 <http://www.gnu.org/licenses/>.
#####################################################################

__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}")
86 changes: 86 additions & 0 deletions src/somd2/_utils/_schedules.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"abfe_alchemical_ion",
"annihilate",
"decouple",
"windowed_torsions",
"ring_break_morph",
"reverse_ring_break_morph",
]
Expand Down Expand Up @@ -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
38 changes: 38 additions & 0 deletions src/somd2/config/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
}

Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading