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 @@ -54,6 +54,8 @@ Changelog
* Pair the free and vacuum legs of relative perturbations in `somd2-view` and `somd2-summary` to give relative hydration free energies, which were previously only reported for absolute perturbations [#304](https://github.com/OpenBioSim/somd2/pull/304).
* Log the number of atoms and virtual sites in the input system, and the Boresch restraint generated for ABFE bound legs [#307](https://github.com/OpenBioSim/somd2/pull/307).
* Add an `ml_model` option to replace the force field with an ML model for the intramolecular energy of the perturbable molecule, interpolating between the ML energies of its end states, for relative and absolute free energies on the CUDA platform. The model is a standard model (`ani2x` or `mace-off23-small/medium/large`), the path to a MACE model file or a TorchScript EMLE model, or a factory (`file.py:function` or `module:function`) that returns a custom model. The `ml_emle_model` option sets the EMLE model used by `ani2x` and MACE models. The `ml_embedding` option chooses mechanical embedding, or electrostatic embedding, which adds stages to the lambda schedule that switch it on at either end state, or only at the start for the `annihilate` and `decouple` schedules. The `ml_embedding_fraction` option sets the fraction of lambda taken by each of these stages. The `ml_cutoff`, `ml_switch_width` and `ml_cuda_graph` options control the EMLE models. ML models aren't yet supported with GCMC, REST2 or `swap_end_states` [#309](https://github.com/OpenBioSim/somd2/pull/309).
* Add the same electrostatic embedding stages to the schedule of every perturbable molecule, since Sire now subtracts the MM electrostatics between the ML and MM atoms that the embedding replaces, rather than the ML molecule needing its own schedule that scales its charges [#XXX](https://github.com/OpenBioSim/somd2/pull/XXX).
* Add an `ml_selection` option to treat only part of the perturbable molecule with the ML model, e.g. a mutated residue, with link atoms at the boundary. A warning is logged if perturbed atoms are left out [#XXX](https://github.com/OpenBioSim/somd2/pull/XXX).

[2026.2.0](https://github.com/openbiosim/somd2/compare/2026.1.0...2026.2.0) - Sep 2026
--------------------------------------------------------------------------------------
Expand Down
9 changes: 6 additions & 3 deletions src/somd2/_utils/_ml.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ def ml_options(config, mol_num):
return {
"model": config.ml_model,
"emle_model": config.ml_emle_model,
"selection": config.ml_selection,
"embedding": config.ml_embedding,
"cutoff": config.ml_cutoff,
"switch_width": config.ml_switch_width,
Expand Down Expand Up @@ -154,15 +155,17 @@ def prepare_ml_dynamics(system, dynamics_kwargs, ml):
torch.device(f"cuda:{dynamics_kwargs['device']}"),
ml["emle_model"],
)
mol = system[f"molnum {ml['mol_num']}"]
ml_atoms = system[f"molnum {ml['mol_num']}"]
if ml["selection"] is not None:
ml_atoms = ml_atoms.atoms(ml["selection"])
mechanical = ml["embedding"] == "mechanical"

# Models other than those from a factory are EMLE models, which are
# evaluated with the total charge of each end state.
if ml["model"] in Config._choices["ml_model"] or os.path.isfile(ml["model"]):
system, engine = sr.qm.emle(
system,
mol,
ml_atoms,
model,
cutoff=ml["cutoff"],
switch_width=ml["switch_width"],
Expand All @@ -174,7 +177,7 @@ def prepare_ml_dynamics(system, dynamics_kwargs, ml):
else:
system, engine = sr.qm.create_engine(
system,
mol,
ml_atoms,
model,
mechanical_embedding=mechanical,
gpu_resident=True,
Expand Down
38 changes: 12 additions & 26 deletions src/somd2/_utils/_schedules.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,27 +518,23 @@ def close(a, b):
return s


def ml_embedding_stages(schedule, ml_idx, num_perturbable, fraction, decoupled=False):
def ml_embedding_stages(schedule, num_perturbable, fraction, decoupled=False):
"""
Return a copy of a lambda schedule with stages either side of its existing
stages that switch the electrostatic embedding of the ML molecule off and
on, so that the existing stages use mechanical embedding. The ML molecule's
charges are scaled to zero in these stages, since the embedding replaces
them, while those of other perturbable molecules, e.g. alchemical ions, are
held at their end-state values. Each stage takes the given fraction of
lambda in the schedule of every molecule. If the ML molecule is decoupled
from its environment at lambda = 1, only the stage that switches the
embedding off is added.
on, so that the existing stages use mechanical embedding. In these stages
Sire replaces the MM electrostatics between the ML and MM atoms with the
embedding, while all other levers are held at their end-state values.
Each stage takes the given fraction of lambda in the schedule of every
molecule. If the ML molecule is decoupled from its environment at lambda
= 1, only the stage that switches the embedding off is added.

Parameters
----------

schedule : sire.legacy.CAS.LambdaSchedule
The lambda schedule.

ml_idx : int
The index of the ML molecule among the perturbable molecules.

num_perturbable : int
The number of perturbable molecules.

Expand All @@ -558,9 +554,9 @@ def ml_embedding_stages(schedule, ml_idx, num_perturbable, fraction, decoupled=F

stages = ["embedding_off"] if decoupled else ["embedding_off", "embedding_on"]

def add_embedding_stages(schedule, **kwargs):
def add_embedding_stages(schedule):
weight = sum(schedule.get_stage_weights()) or 1.0
_add_embedding_stages(schedule, **kwargs)
_add_embedding_stages(schedule)
if decoupled:
schedule.remove_stage("embedding_on")
for stage in stages:
Expand All @@ -571,22 +567,12 @@ def add_embedding_stages(schedule, **kwargs):
s = schedule.clone()

for idx in range(num_perturbable):
if idx != ml_idx and s.has_molecule_schedule(idx):
if s.has_molecule_schedule(idx):
mol_schedule = s.get_molecule_schedule(idx)
add_embedding_stages(mol_schedule, scale_charges=False)
add_embedding_stages(mol_schedule)
s.set_molecule_schedule(idx, mol_schedule)

# The ML molecule needs its own schedule, since its charges are scaled.
ml_schedule = (
s.get_molecule_schedule(ml_idx) if s.has_molecule_schedule(ml_idx) else s
).clone()
for idx in range(num_perturbable):
if ml_schedule.has_molecule_schedule(idx):
ml_schedule.remove_molecule_schedule(idx)
add_embedding_stages(ml_schedule)

add_embedding_stages(s, scale_charges=False)
s.set_molecule_schedule(ml_idx, ml_schedule)
add_embedding_stages(s)

return s

Expand Down
16 changes: 10 additions & 6 deletions src/somd2/_viewer/_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,19 +211,23 @@ def vacuum_settings(config, ignore):
Return the settings that must match between the free and vacuum legs of a
hydration free energy, i.e. as for bound and free legs, but also ignoring
pressure, the dispersion correction and the ML embedding, which aren't
applied without water.
applied without water. The ML embedding is still compared if only part of
the molecule is ML, since it is then embedded in the rest of the molecule.
"""
no_water = {
"pressure",
"barostat_frequency",
"surface_tension",
"use_dispersion_correction",
"ml_embedding",
"ml_emle_model",
"ml_cutoff",
"ml_switch_width",
"ml_embedding_fraction",
}
if config.get("ml_selection") is None:
no_water |= {
"ml_embedding",
"ml_emle_model",
"ml_cutoff",
"ml_switch_width",
"ml_embedding_fraction",
}
return _settings(config, _leg_specific(config) | set(ignore) | no_water)


Expand Down
24 changes: 24 additions & 0 deletions src/somd2/config/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ def __init__(
morse_soft_force_constant="125 kcal mol-1 A-2",
ml_model=None,
ml_emle_model=None,
ml_selection=None,
ml_embedding="mechanical",
ml_cutoff="7.5 A",
ml_switch_width=0.2,
Expand Down Expand Up @@ -898,6 +899,13 @@ def __init__(
embedding of "ani2x" or a MACE model. If None, the default EMLE
model is used.

ml_selection: str
A Sire selection string for the atoms of the perturbable molecule
that are treated with the ML model, e.g. "resnum 3 and not atomname
N,H,C,O" for the side chain and alpha carbon of a mutated residue.
Bonds to the rest of the molecule are capped with link atoms. If
None, the whole molecule is used.

ml_embedding: str
How the ML molecule interacts electrostatically with its environment.
With "mechanical", the MM charges are used throughout. With
Expand Down Expand Up @@ -1045,6 +1053,7 @@ def __init__(
self.morse_soft_force_constant = morse_soft_force_constant
self.ml_model = ml_model
self.ml_emle_model = ml_emle_model
self.ml_selection = ml_selection
self.ml_embedding = ml_embedding
self.ml_cutoff = ml_cutoff
self.ml_switch_width = ml_switch_width
Expand Down Expand Up @@ -3778,6 +3787,21 @@ def ml_emle_model(self, ml_emle_model):

self._ml_emle_model = ml_emle_model

@property
def ml_selection(self):
return self._ml_selection

@ml_selection.setter
def ml_selection(self, ml_selection):
if ml_selection is not None:
if not isinstance(ml_selection, str):
raise TypeError("'ml_selection' must be of type 'str'")
# Allow the whole molecule to be chosen from the command line.
if ml_selection.strip().lower() == "none":
ml_selection = None

self._ml_selection = ml_selection

@property
def ml_embedding(self):
return self._ml_embedding
Expand Down
42 changes: 41 additions & 1 deletion src/somd2/runner/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,44 @@ def _apply_torsion_window(self):
f"{idx}:{start}-{end}" for idx, (_, start, end, _) in windows.items()
)

def _check_ml_selection(self, mol):
"""
Make sure that 'ml_selection' selects atoms of the ML molecule, and warn
if any of its perturbed atoms are left out, since they are treated with
MM in both end states.

Parameters
----------

mol: sire.mol.Molecule
The ML molecule.
"""
from .._utils._perturbed import perturbed_atoms

selection = self._config.ml_selection

try:
atoms = mol.atoms(selection)
except Exception as e:
msg = f"Invalid 'ml_selection' for the ML molecule: {selection}: {e}"
_logger.error(msg)
raise ValueError(msg)

selected = {mol.atoms().find(atom) for atom in atoms}
missing = sorted(set(perturbed_atoms(mol)) - selected)

if missing:
names = ", ".join(mol.atoms()[i].name().value() for i in missing)
_logger.warning(
f"'ml_selection' leaves out perturbed atoms of the ML molecule, which "
f"are treated with MM in both end states: {names}"
)

_logger.info(
f"Treating {len(atoms)} of the {mol.num_atoms()} atoms of the ML molecule "
"with the ML model."
)

def _set_ml_molecule(self, ion_indices):
"""
Find the perturbable molecule whose intramolecular energy comes from the
Expand Down Expand Up @@ -787,13 +825,15 @@ def _set_ml_molecule(self, ion_indices):
ml_idx = candidates[0]
self._ml_mol_num = perturbable[ml_idx].number()

if self._config.ml_selection is not None:
self._check_ml_selection(perturbable[ml_idx])

if self._config.ml_embedding == "electrostatic":
from .._utils._schedules import ml_embedding_stages

decoupled = self._is_abfe_schedule
self._ml_schedule = ml_embedding_stages(
self._config._lambda_schedule,
ml_idx,
len(perturbable),
self._config.ml_embedding_fraction,
decoupled=decoupled,
Expand Down
7 changes: 7 additions & 0 deletions tests/runner/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ def test_ml_options():
config = Config()
assert config.ml_model is None
assert config.ml_emle_model is None
assert config.ml_selection is None
assert config.ml_embedding == "mechanical"
assert math.isclose(config.ml_cutoff.to(sr.units.angstrom), 7.5)
assert config.ml_switch_width == 0.2
Expand Down Expand Up @@ -174,6 +175,12 @@ def test_ml_options():
with pytest.raises(ValueError, match="factory"):
Config(ml_model=ml_model)

assert Config(ml_selection="resnum 3").ml_selection == "resnum 3"
assert Config(ml_selection="None").ml_selection is None

with pytest.raises(TypeError):
Config(ml_selection=3)

with pytest.raises(ValueError, match="not recognised"):
Config(ml_embedding="polarisable")

Expand Down
73 changes: 55 additions & 18 deletions tests/runner/test_ml.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,17 @@ def test_ml_molecule(ethane_methanol, ml_embedding):

if ml_embedding == "electrostatic":
assert schedule.get_stages() == ["embedding_off", "morph", "embedding_on"]
assert schedule.has_molecule_schedule(0)
else:
assert schedule.get_stages() == ["morph"]
assert not schedule.has_molecule_schedule(0)
assert not schedule.has_molecule_schedule(0)


@pytest.mark.skipif(not has_cuda, reason="CUDA not available.")
def test_ml_electrostatic_alchemical_ion(ethane_methanol):
"""
With electrostatic embedding, the charges of an alchemical ion are held at
their end-state values in the embedding stages, where those of the ML
molecule are switched, so the ML model sees the MM charges of each end state.
With electrostatic embedding, the charges of an alchemical ion and of the
ML molecule are held at their end-state values in the embedding stages, so
the ML model sees the MM charges of each end state.
"""
import openmm

Expand Down Expand Up @@ -98,24 +97,62 @@ def charge(idx):
q = cljff.getParticleParameters(idx)[0]
return q.value_in_unit(openmm.unit.elementary_charge)

# lambda, ML charge scale in state 0 and 1, ion charge state
expected = (
(0.0, (0.0, 0.0), 0),
(0.05, (0.5, 0.0), 0),
(0.1, (1.0, 0.0), 0),
(0.9, (0.0, 1.0), 1),
(0.95, (0.0, 0.5), 1),
(1.0, (0.0, 0.0), 1),
)
# lambda and the end state of the charges
expected = ((0.0, 0), (0.05, 0), (0.1, 0), (0.9, 1), (0.95, 1), (1.0, 1))

for lam, (scale0, scale1), state in expected:
for lam, state in expected:
context.set_lambda(lam)
for idx, (q0, q1) in ml.items():
assert charge(idx) == pytest.approx(scale0 * q0 + scale1 * q1, abs=1e-6)
for idx, q in ion.items():
for idx, q in {**ml, **ion}.items():
assert charge(idx) == pytest.approx(q[state], abs=1e-6)


@pytest.mark.skipif(not has_cuda, reason="CUDA not available.")
def test_ml_selection(ethane_methanol):
"""
'ml_selection' must be a valid selection for the ML molecule, a warning is logged if
it leaves out perturbed atoms, and the selected atoms are passed to the engine.
"""
from somd2 import _logger
from somd2._utils._ml import prepare_ml_dynamics
from somd2._utils._perturbed import perturbed_atoms

mol = ethane_methanol.molecules("property is_perturbable")[0]

def runner(selection, tmpdir):
config = Config(
platform="cuda",
output_directory=tmpdir,
ml_model="ani2x",
ml_selection=selection,
overwrite=True,
)
return Runner(ethane_methanol, config)

with tempfile.TemporaryDirectory() as tmpdir:
for selection in ("not a selection (", "atomname XYZ"):
with pytest.raises(ValueError, match="Invalid 'ml_selection'"):
runner(selection, tmpdir)

# The runner reconfigures the logger, so check the selection again after.
missing = perturbed_atoms(mol)[0]
r = runner(f"not atomidx {missing}", tmpdir)
messages = []
handler = _logger.add(messages.append, level="WARNING")
try:
r._check_ml_selection(mol)
finally:
_logger.remove(handler)
assert any("leaves out perturbed atoms" in str(m) for m in messages)

r = runner("not atomname XYZ", tmpdir)
kwargs = {**r._dynamics_kwargs, "device": 0}
system, kwargs = prepare_ml_dynamics(r._system, kwargs, r._ml)
start = system.atoms().find(system[f"molnum {r._ml['mol_num']}"].atoms()[0])
assert list(kwargs["qm_engine"].get_atoms()) == list(
range(start, start + mol.num_atoms())
)


@pytest.mark.skipif(not has_cuda, reason="CUDA not available.")
@pytest.mark.parametrize("lambda_schedule", ["annihilate", "decouple"])
def test_ml_electrostatic_decoupled(ethane_methanol, lambda_schedule):
Expand Down
Loading
Loading