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 @@ -47,6 +47,8 @@ Changelog
* Default the GCMC region to a sphere around the perturbed atoms, with a radius and number of ghost waters chosen automatically, via new `auto` defaults for `gcmc_selection`, `gcmc_radius` and `gcmc_num_waters`, and a `gcmc_radius_padding` option. GCMC within the entire simulation box is still available with `gcmc_selection=None` [#291](https://github.com/OpenBioSim/somd2/pull/291).
* Default the REST2 region to the perturbed atoms and the atoms within `rest2_bonds` bonds of them, via a new `auto` default for `rest2_selection`. All atoms of the perturbable molecules can still be scaled with `rest2_selection=None` [#292](https://github.com/OpenBioSim/somd2/pull/292).
* Take the terminal ring flip angle of a distorted ring from the number of neighbours of its pivot, rather than from RDKit, which assigned 120° to aromatic rings when MDAnalysis wasn't available [#294](https://github.com/OpenBioSim/somd2/pull/294).
* Include whole ring systems containing perturbed atoms in the automatic REST2 region, so that the torsions about a perturbed ring's bonds to the rest of the molecule are scaled [#296](https://github.com/OpenBioSim/somd2/pull/296).
* Add a `rest2_profile` option. The default, `exponential`, gives a geometric ladder of REST2 scale factors, rather than the previous linear rise, which is still available as `linear`. REST2 runs started before this change must set `rest2_profile` to `linear` to restart [#296](https://github.com/OpenBioSim/somd2/pull/296).

[2026.2.0](https://github.com/openbiosim/somd2/compare/2026.1.0...2026.2.0) - Sep 2026
--------------------------------------------------------------------------------------
Expand Down
23 changes: 14 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -621,11 +621,13 @@ region relative to the rest of the system.

By default, the REST2 region comprises the perturbed atoms, i.e. atoms whose
element changes between the end states, including ghost atoms, and heavy atoms
whose Lennard-Jones parameters change, along with the atoms within
`--rest2-bonds` bonds of them (2 by default). Torsions are only scaled when all
four atoms are in the REST2 region, so this includes the torsions about every
bond to a perturbed atom, while keeping the region, and the change in energy
between λ windows, small. The resolved selection is logged and written to the
whose Lennard-Jones parameters change, along with any ring systems that contain
them or are bonded to them, and the atoms within `--rest2-bonds` bonds of these
(2 by default). Torsions are only scaled when all four atoms are in the REST2
region, so this includes the torsions about every bond to a perturbed atom, and
about the bonds joining a perturbed ring to the rest of the molecule, e.g. for
a ring that flips, while keeping the region, and the change in energy between λ
windows, small. The resolved selection is logged and written to the
config file.

A different region can be chosen with `--rest2-selection`, a `Sire` selection
Expand All @@ -635,10 +637,13 @@ selection. If the selection includes atoms in perturbable molecules, only the
selected atoms of those molecules are scaled, so a subset of a perturbable
molecule can be chosen.

The REST2 schedule is a triangular function that starts and ends at 1.0,
peaking at the value of `--rest2-scale` in the middle of the λ schedule.
Passing multiple values to `--rest2-scale` gives full control of the schedule,
in which case there must be one value for each λ window.
The REST2 schedule starts and ends at 1.0, peaking at the value of
`--rest2-scale` in the middle of the λ schedule. By default each step
multiplies the scale factor by the same ratio, giving a geometric ladder of
effective temperatures, which helps sampling propagate between windows when a
large scale factor is used. Use `--rest2-profile linear` for a linear rise
instead. Passing multiple values to `--rest2-scale` gives full control of the
schedule, in which case there must be one value for each λ window.

<a id="gcmc"></a>

Expand Down
88 changes: 81 additions & 7 deletions src/somd2/_utils/_perturbed.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,80 @@ def changes(atom):
return indices or list(range(mol.num_atoms()))


def _neighbours(mol, indices, bonds):
def _connectivities(mol):
"""
Return the connectivity of each end state of a perturbable molecule, or its
single connectivity if it doesn't change.
"""
names = ["connectivity0", "connectivity1"]
if not all(mol.has_property(name) for name in names):
names = ["connectivity"]
return [mol.property(name) for name in names]


# Rings with more atoms than this, e.g. macrocycles or loops closed by a
# disulfide, aren't treated as ring systems.
_MAX_RING_SIZE = 8


def _ring_systems(mol, indices, connectivities=None):
"""
Return the given atoms plus the atoms of every ring system, in either end
state, that contains one of them or, for an atom that isn't in a ring, is
bonded to it. A ring system is followed through the bonds of rings of at
most 8 atoms, so fused rings are included, but rings joined by a single
bond, e.g. a biaryl, and large rings such as macrocycles are not.
"""
from sire.legacy.Mol import AtomIdx as _AtomIdx

if connectivities is None:
connectivities = _connectivities(mol)

region = set(indices)
for connectivity in connectivities:

def ring_bond(a, b):
return any(
connectivity.in_ring(n, a, b, _MAX_RING_SIZE)
for n in connectivity.connections_to(a)
if n != b
)

def in_ring(a):
return any(ring_bond(a, n) for n in connectivity.connections_to(a))

seeds = set()
for i in indices:
atom = _AtomIdx(i)
if in_ring(atom):
seeds.add(i)
else:
seeds.update(
n.value() for n in connectivity.connections_to(atom) if in_ring(n)
)

seen = set(seeds)
stack = list(seeds)
while stack:
atom = _AtomIdx(stack.pop())
for n in connectivity.connections_to(atom):
if n.value() not in seen and ring_bond(atom, n):
seen.add(n.value())
stack.append(n.value())
region |= seen

return sorted(region)


def _neighbours(mol, indices, bonds, connectivities=None):
"""
Return the indices of the atoms within a number of bonds of the given
atoms, in either end state, including the atoms themselves.
"""
from sire.legacy.Mol import AtomIdx as _AtomIdx

names = ["connectivity0", "connectivity1"]
if not all(mol.has_property(name) for name in names):
names = ["connectivity"]
connectivities = [mol.property(name) for name in names]
if connectivities is None:
connectivities = _connectivities(mol)

region = set(indices)
shell = set(indices)
Expand All @@ -80,10 +143,14 @@ def _neighbours(mol, indices, bonds):
return sorted(region)


def perturbed_selection(system, bonds=0):
def perturbed_selection(system, bonds=0, rings=False):
"""
Return a selection string for the perturbed atoms of the perturbable
molecules in the system, and the atoms within a number of bonds of them.
With 'rings', ring systems containing a perturbed atom, or bonded to a
perturbed atom outside a ring, are included whole before the selection is
extended, so that a perturbed ring and the torsions about its bonds to the
rest of the molecule are covered.
Perturbable waters and single-atom ions, e.g. co-alchemical ions, are left
out unless they are the only perturbable molecules. Molecules are selected
by index, rather than number, so that the selection also works for the
Expand All @@ -98,6 +165,9 @@ def perturbed_selection(system, bonds=0):
bonds: int
The number of bonds from the perturbed atoms to extend the selection.

rings: bool
Whether to include the ring systems of the perturbed atoms whole.

Returns
-------

Expand All @@ -114,7 +184,11 @@ def perturbed_selection(system, bonds=0):
molecules = system.molecules()
parts = []
for mol in solutes:
indices = _neighbours(mol, perturbed_atoms(mol), bonds)
connectivities = _connectivities(mol)
indices = perturbed_atoms(mol)
if rings:
indices = _ring_systems(mol, indices, connectivities)
indices = _neighbours(mol, indices, bonds, connectivities)
atoms = ",".join(str(i) for i in indices)
parts.append(f"(molidx {molecules.find(mol)} and atomidx {atoms})")
return " or ".join(parts)
34 changes: 34 additions & 0 deletions src/somd2/_utils/_schedules.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"windowed_torsions",
"ring_break_morph",
"reverse_ring_break_morph",
"rest2_scale_factors",
]


Expand Down Expand Up @@ -514,3 +515,36 @@ def close(a, b):
)

return s


def rest2_scale_factors(scale, lambda_values, profile="linear"):
"""
Return the REST2 scale factor at each lambda value, rising from 1.0 at the
end states to 'scale' at lambda = 0.5.

Parameters
----------

scale: float
The scale factor at lambda = 0.5.

lambda_values: list of float
The lambda values.

profile: str
How the scale factor rises: "linear", or "exponential", where each
step multiplies the scale factor by the same ratio, i.e. a geometric
ladder of effective temperatures.

Returns
-------

factors: list of float
The scale factor at each lambda value.
"""
fractions = [1.0 - 2.0 * abs(lam - 0.5) for lam in lambda_values]
if profile == "linear":
return [1.0 + (scale - 1.0) * f for f in fractions]
if profile == "exponential":
return [scale**f for f in fractions]
raise ValueError(f"Unknown REST2 profile: {profile}")
11 changes: 7 additions & 4 deletions src/somd2/_viewer/_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -1274,10 +1274,13 @@ def load():
rest2 = config.get("rest2_scale")
if rest2 is not None:
if isinstance(rest2, (int, float)):
factors = [
1.0 + (float(rest2) - 1.0) * (1.0 - 2.0 * abs(lam - 0.5))
for lam in lambda_energy
]
from .._utils._schedules import rest2_scale_factors

factors = rest2_scale_factors(
float(rest2),
lambda_energy,
config.get("rest2_profile") or "linear",
)
else:
factors = [float(x) for x in rest2]
if len(factors) == len(lambda_energy) and any(
Expand Down
32 changes: 30 additions & 2 deletions src/somd2/config/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ class Config:
"log_level": [level.lower() for level in _logger._core.levels],
"softcore_form": ["auto", "zacharias", "taylor", "beutler"],
"torsion_window": ["auto", "true", "false"],
"rest2_profile": ["linear", "exponential"],
"precision": ["single", "mixed", "double"],
}

Expand Down Expand Up @@ -233,6 +234,7 @@ def __init__(
gcmc_num_attempts=10000,
use_dispersion_correction=False,
rest2_scale=1.0,
rest2_profile="exponential",
rest2_selection="auto",
rest2_bonds=2,
softcore_form="auto",
Expand Down Expand Up @@ -703,14 +705,23 @@ def __init__(
values are used, then the number should match the number of lambda windows at which
energies are sampled.

rest2_profile: str
How a single 'rest2_scale' rises from 1.0 at the end states to its value at
lambda = 0.5: "exponential" (the default), where each step multiplies the
scale factor by the same ratio, or "linear". The exponential profile gives a
geometric ladder of effective temperatures, which helps sampling propagate
between windows when a large scale factor is used. It has no effect when
'rest2_scale' is a list.

rest2_selection: str
A sire selection string for atoms to include in the REST2 region in
addition to any perturbable molecules. For example, "molidx 0 and residx 0,1,2"
would select atoms from the first three residues of the first molecule. If 'auto'
(the default), then the REST2 region contains the perturbed atoms, i.e. atoms
whose element changes between the end states, including ghost atoms, and heavy
atoms whose Lennard-Jones parameters change, and the atoms within 'rest2_bonds'
bonds of them. If None, then all atoms within perturbable molecules will be
atoms whose Lennard-Jones parameters change, any ring systems that contain
them or are bonded to them, and the atoms within 'rest2_bonds' bonds of
these. If None, then all atoms within perturbable molecules will be
included in the REST2 region. When atoms within a perturbable molecule are
included in the selection, then only those atoms will be considered as part of
the REST2 region. This allows REST2 to be applied to protein mutations.
Expand Down Expand Up @@ -938,6 +949,7 @@ def __init__(
self.gcmc_num_attempts = gcmc_num_attempts
self.use_dispersion_correction = use_dispersion_correction
self.rest2_scale = rest2_scale
self.rest2_profile = rest2_profile
self.rest2_selection = rest2_selection
self.rest2_bonds = rest2_bonds
self.restart = restart
Expand Down Expand Up @@ -2909,6 +2921,22 @@ def rest2_selection(self, rest2_selection):
rest2_selection = "auto"
self._rest2_selection = rest2_selection

@property
def rest2_profile(self):
return self._rest2_profile

@rest2_profile.setter
def rest2_profile(self, rest2_profile):
if not isinstance(rest2_profile, str):
raise TypeError("'rest2_profile' must be of type 'str'")
rest2_profile = rest2_profile.lower().replace(" ", "")
if rest2_profile not in self._choices["rest2_profile"]:
raise ValueError(
"'rest2_profile' not recognised. Valid options are: "
f"{', '.join(self._choices['rest2_profile'])}"
)
self._rest2_profile = rest2_profile

@property
def rest2_bonds(self):
return self._rest2_bonds
Expand Down
39 changes: 30 additions & 9 deletions src/somd2/runner/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -858,14 +858,13 @@ def _set_schedule(self, pert_idxs, ion_indices):
# Single value. Interpolate between 1.0 at the end states and rest2_scale
# at lambda = 0.5.
if isinstance(self._config.rest2_scale, float):
scale_factors = []
for lambda_value in self._lambda_energy:
scale_factors.append(
1.0
+ (self._config.rest2_scale - 1.0)
* (1.0 - 2.0 * abs(lambda_value - 0.5))
)
self._rest2_scale_factors = scale_factors
from .._utils._schedules import rest2_scale_factors

self._rest2_scale_factors = rest2_scale_factors(
self._config.rest2_scale,
self._lambda_energy,
self._config.rest2_profile,
)
else:
if len(self._config.rest2_scale) != len(self._lambda_energy):
msg = f"Length of 'rest2_scale' must match the number of {_lam_sym} values."
Expand All @@ -889,6 +888,11 @@ def _set_schedule(self, pert_idxs, ion_indices):
_logger.error(msg)
raise ValueError(msg)
self._rest2_scale_factors = self._config.rest2_scale
if self._config.rest2_profile != "linear":
_logger.warning(
"'rest2_profile' is ignored, since 'rest2_scale' gives a "
f"scale factor for each {_lam_sym} window."
)

# If there are any non-zero REST2 scale factors, then log it.
if any(
Expand All @@ -905,7 +909,7 @@ def _set_schedule(self, pert_idxs, ion_indices):

try:
self._config.rest2_selection = perturbed_selection(
self._system, self._config.rest2_bonds
self._system, self._config.rest2_bonds, rings=True
)
except Exception as e:
msg = (
Expand Down Expand Up @@ -2632,6 +2636,23 @@ def _compare_configs(config1, config2):
"None to restart it."
)

# Runs started before 'rest2_profile' existed used the linear profile.
scale = config1.get("rest2_scale")
try:
has_rest2 = scale is not None and float(scale) != 1.0
except (TypeError, ValueError):
has_rest2 = False
if (
has_rest2
and "rest2_profile" not in config1
and config2.get("rest2_profile", "linear") != "linear"
):
raise ValueError(
"The simulation was started before 'rest2_profile' existed, so it "
"used the linear REST2 profile. Set 'rest2_profile' to 'linear' to "
"restart it."
)

allowed_diffs = _Config._restart_allowed_diffs
no_gcmc = not config1.get("gcmc") and not config2.get("gcmc")
for key in config1.keys():
Expand Down
Loading
Loading