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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Changelog
* 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).
* 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).

[2026.2.0](https://github.com/openbiosim/somd2/compare/2026.1.0...2026.2.0) - Sep 2026
--------------------------------------------------------------------------------------
Expand Down
20 changes: 15 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -619,11 +619,21 @@ perturbations involving conformational changes, e.g. ring flips. It is enabled
with the `--rest2-scale` option, which specifies the "temperature" of the REST2
region relative to the rest of the system.

By default, the REST2 region comprises *all* atoms in perturbable molecules.
Atoms in other, non-perturbable molecules can be added with `--rest2-selection`,
a `Sire` selection string. 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.
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
config file.

A different region can be chosen with `--rest2-selection`, a `Sire` selection
string. Use `--rest2-selection none` to scale *all* atoms in perturbable
molecules. Atoms in other, non-perturbable molecules can be added with a
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.
Expand Down
69 changes: 1 addition & 68 deletions src/somd2/_utils/_gcmc.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
# along with SOMD2. If not, see <http://www.gnu.org/licenses/>.
#####################################################################

__all__ = ["auto_selection", "selection_geometry", "selection_sites", "ghost_waters"]
__all__ = ["selection_geometry", "selection_sites", "ghost_waters"]

# The volume of a heavy atom and its hydrogens at protein density, in waters.
_HEAVY_ATOM_WATERS = 0.58
Expand All @@ -33,38 +33,6 @@
_SITE_DISTANCE = 4.0


def perturbed_atoms(mol):
"""
Return the indices of the atoms of a perturbable molecule that change
between the end states: atoms whose element changes, including ghost
atoms, and heavy atoms whose Lennard-Jones parameters change. Hydrogens
whose Lennard-Jones parameters change are left out, since this is often
only a change in atom type caused by changes elsewhere in the molecule. If
no atoms change, then all atoms are returned.

Parameters
----------

mol: sire.mol.Molecule
The perturbable molecule.

Returns
-------

indices: list of int
The indices of the perturbed atoms within the molecule.
"""

def changes(atom):
element = atom.property("element0").symbol()
if element != atom.property("element1").symbol():
return True
return element != "H" and atom.property("LJ0") != atom.property("LJ1")

indices = [i for i, atom in enumerate(mol.atoms()) if changes(atom)]
return indices or list(range(mol.num_atoms()))


def vanishing_atoms(mol):
"""
Return the indices of the atoms of a perturbable molecule that vanish in
Expand Down Expand Up @@ -100,41 +68,6 @@ def decoupled(atom, end):
]


def auto_selection(system):
"""
Return a selection string for the perturbed atoms of the perturbable
molecules in the system. 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 system reloaded from file.

Parameters
----------

system: sire.system.System
The system containing the perturbable molecules.

Returns
-------

selection: str
The selection string.
"""
perturbable = system.molecules("property is_perturbable")
try:
solutes = system.molecules("property is_perturbable and not water")
except KeyError:
solutes = []
solutes = [mol for mol in solutes if mol.num_atoms() > 1] or perturbable

molecules = system.molecules()
parts = []
for mol in solutes:
indices = ",".join(str(i) for i in perturbed_atoms(mol))
parts.append(f"(molidx {molecules.find(mol)} and atomidx {indices})")
return " or ".join(parts)


def _space(system):
"""
Return the periodic space of the system, or None if it isn't periodic.
Expand Down
120 changes: 120 additions & 0 deletions src/somd2/_utils/_perturbed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
######################################################################
# 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__ = ["perturbed_atoms", "perturbed_selection"]


def perturbed_atoms(mol):
"""
Return the indices of the atoms of a perturbable molecule that change
between the end states: atoms whose element changes, including ghost
atoms, and heavy atoms whose Lennard-Jones parameters change. Hydrogens
whose Lennard-Jones parameters change are left out, since this is often
only a change in atom type caused by changes elsewhere in the molecule. If
no atoms change, then all atoms are returned.

Parameters
----------

mol: sire.mol.Molecule
The perturbable molecule.

Returns
-------

indices: list of int
The indices of the perturbed atoms within the molecule.
"""

def changes(atom):
element = atom.property("element0").symbol()
if element != atom.property("element1").symbol():
return True
return element != "H" and atom.property("LJ0") != atom.property("LJ1")

indices = [i for i, atom in enumerate(mol.atoms()) if changes(atom)]
return indices or list(range(mol.num_atoms()))


def _neighbours(mol, indices, bonds):
"""
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]

region = set(indices)
shell = set(indices)
for _ in range(bonds):
shell = {
n.value()
for i in shell
for c in connectivities
for n in c.connections_to(_AtomIdx(i))
} - region
region |= shell

return sorted(region)


def perturbed_selection(system, bonds=0):
"""
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.
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
system reloaded from file.

Parameters
----------

system: sire.system.System
The system containing the perturbable molecules.

bonds: int
The number of bonds from the perturbed atoms to extend the selection.

Returns
-------

selection: str
The selection string.
"""
perturbable = system.molecules("property is_perturbable")
try:
solutes = system.molecules("property is_perturbable and not water")
except KeyError:
solutes = []
solutes = [mol for mol in solutes if mol.num_atoms() > 1] or perturbable

molecules = system.molecules()
parts = []
for mol in solutes:
indices = _neighbours(mol, perturbed_atoms(mol), bonds)
atoms = ",".join(str(i) for i in indices)
parts.append(f"(molidx {molecules.find(mol)} and atomidx {atoms})")
return " or ".join(parts)
48 changes: 42 additions & 6 deletions src/somd2/config/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ class Config:
"gcmc_batch_size",
"gcmc_num_attempts",
"gcmc_radius_padding",
"rest2_bonds",
"torsion_window",
]
)
Expand Down Expand Up @@ -231,7 +232,8 @@ def __init__(
gcmc_num_attempts=10000,
use_dispersion_correction=False,
rest2_scale=1.0,
rest2_selection=None,
rest2_selection="auto",
rest2_bonds=2,
softcore_form="auto",
taylor_power=1,
beutler_alpha=0.5,
Expand Down Expand Up @@ -702,11 +704,20 @@ def __init__(
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 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.
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
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.

rest2_bonds: int
The number of bonds from the perturbed atoms to extend the REST2 region when
'rest2_selection' is 'auto'. Torsions are only scaled when all four atoms are in
the REST2 region, so the default of 2 includes the torsions about every bond to
a perturbed atom.

softcore_form: str
The soft-core potential form to use for alchemical interactions. Valid
Expand Down Expand Up @@ -926,6 +937,7 @@ def __init__(
self.use_dispersion_correction = use_dispersion_correction
self.rest2_scale = rest2_scale
self.rest2_selection = rest2_selection
self.rest2_bonds = rest2_bonds
self.restart = restart
self.use_backup = use_backup
self.softcore_form = softcore_form
Expand Down Expand Up @@ -2888,8 +2900,32 @@ def rest2_selection(self, rest2_selection):
if rest2_selection is not None:
if not isinstance(rest2_selection, str):
raise TypeError("'rest2_selection' must be of type 'str'")
# Allow all atoms of the perturbable molecules to be chosen from the command line.
if rest2_selection.strip().lower() == "none":
rest2_selection = None
elif rest2_selection.strip().lower() == "auto":
rest2_selection = "auto"
self._rest2_selection = rest2_selection

@property
def rest2_bonds(self):
return self._rest2_bonds

@rest2_bonds.setter
def rest2_bonds(self, rest2_bonds):
if isinstance(rest2_bonds, bool) or (
isinstance(rest2_bonds, float) and not rest2_bonds.is_integer()
):
raise ValueError("'rest2_bonds' must be an integer")
if not isinstance(rest2_bonds, int):
try:
rest2_bonds = int(rest2_bonds)
except Exception:
raise ValueError("'rest2_bonds' must be an integer")
if rest2_bonds < 0:
raise ValueError("'rest2_bonds' must be greater than or equal to 0")
self._rest2_bonds = rest2_bonds

@property
def restart(self):
return self._restart
Expand Down
37 changes: 30 additions & 7 deletions src/somd2/runner/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -898,6 +898,26 @@ def _set_schedule(self, pert_idxs, ion_indices):
is_rest2 = True
_logger.info(f"REST2 scaling factors: {self._rest2_scale_factors}")

# Resolve the automatic REST2 region, which is only used with REST2.
if self._config.rest2_selection == "auto":
if is_rest2:
from .._utils._perturbed import perturbed_selection

try:
self._config.rest2_selection = perturbed_selection(
self._system, self._config.rest2_bonds
)
except Exception as e:
msg = (
f"Unable to select the perturbed atoms for the REST2 region: {e}. "
"Set 'rest2_selection' explicitly."
)
_logger.error(msg)
raise ValueError(msg) from e
_logger.info(f"REST2 region: '{self._config.rest2_selection}'")
else:
self._config.rest2_selection = None

# Make sure the REST2 selection is valid.
if self._config.rest2_selection is not None:
try:
Expand Down Expand Up @@ -1077,17 +1097,13 @@ def _set_gcmc_region(self):
are resolved from the input system, so a restart resolves them to the
same values.
"""
from .._utils._gcmc import (
auto_selection,
ghost_waters,
selection_geometry,
selection_sites,
)
from .._utils._gcmc import ghost_waters, selection_geometry, selection_sites
from .._utils._perturbed import perturbed_selection

is_auto = self._config.gcmc_selection == "auto"
if is_auto:
try:
self._config.gcmc_selection = auto_selection(self._system)
self._config.gcmc_selection = perturbed_selection(self._system)
except Exception as e:
msg = (
f"Unable to select the perturbed atoms for the GCMC sphere: {e}. "
Expand Down Expand Up @@ -2600,6 +2616,13 @@ def _compare_configs(config1, config2):
"'false' to restart it."
)

if not config1.get("rest2_selection") and config2.get("rest2_selection"):
raise ValueError(
"The simulation was started with a REST2 region containing all "
"atoms of the perturbable molecules. Set 'rest2_selection' to "
"None 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