diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b59b58..b76a49d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 -------------------------------------------------------------------------------------- diff --git a/src/somd2/_utils/_ml.py b/src/somd2/_utils/_ml.py index 5ddbaea..4453e91 100644 --- a/src/somd2/_utils/_ml.py +++ b/src/somd2/_utils/_ml.py @@ -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, @@ -154,7 +155,9 @@ 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 @@ -162,7 +165,7 @@ def prepare_ml_dynamics(system, dynamics_kwargs, ml): 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"], @@ -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, diff --git a/src/somd2/_utils/_schedules.py b/src/somd2/_utils/_schedules.py index b75250b..9e997e5 100644 --- a/src/somd2/_utils/_schedules.py +++ b/src/somd2/_utils/_schedules.py @@ -518,17 +518,16 @@ 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 ---------- @@ -536,9 +535,6 @@ def ml_embedding_stages(schedule, ml_idx, num_perturbable, fraction, decoupled=F 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. @@ -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: @@ -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 diff --git a/src/somd2/_viewer/_summary.py b/src/somd2/_viewer/_summary.py index 33cfc8a..8cd21e3 100644 --- a/src/somd2/_viewer/_summary.py +++ b/src/somd2/_viewer/_summary.py @@ -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) diff --git a/src/somd2/config/_config.py b/src/somd2/config/_config.py index bb92563..7519667 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -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, @@ -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 @@ -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 @@ -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 diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index 7365546..6beb2ad 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -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 @@ -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, diff --git a/tests/runner/test_config.py b/tests/runner/test_config.py index f690187..c3178eb 100644 --- a/tests/runner/test_config.py +++ b/tests/runner/test_config.py @@ -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 @@ -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") diff --git a/tests/runner/test_ml.py b/tests/runner/test_ml.py index 1029c88..276e4ec 100644 --- a/tests/runner/test_ml.py +++ b/tests/runner/test_ml.py @@ -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 @@ -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): diff --git a/tests/schedules/test_ml_embedding.py b/tests/schedules/test_ml_embedding.py index adc1642..e46bb3d 100644 --- a/tests/schedules/test_ml_embedding.py +++ b/tests/schedules/test_ml_embedding.py @@ -10,7 +10,7 @@ def test_ml_embedding_stages(): """ The embedding stages are added to every schedule, line up in lambda, and - only scale the charges of the ML molecule. + hold the charges at their end-state values. """ q0, q1 = 0.4, -0.2 @@ -23,7 +23,7 @@ def test_ml_embedding_stages(): schedule.set_molecule_schedule(0, ml_schedule) schedule.set_molecule_schedule(1, LambdaSchedule.standard_morph()) - s = ml_embedding_stages(schedule, 0, 2, 1 / 3) + s = ml_embedding_stages(schedule, 2, 1 / 3) # The original schedule is unchanged. assert schedule.get_stages() == ["morph"] @@ -44,28 +44,20 @@ def test_ml_embedding_stages(): ] expected_embed = (1.0, 0.5, 0.0, 0.0, 0.5, 1.0) - expected_ml = (0.0, 0.5 * q0, q0, q1, 0.5 * q1, 0.0) expected_held = (q0, q0, q0, q1, q1, q1) - for lam, embed, ml, held in zip( - _LAMBDAS, expected_embed, expected_ml, expected_held - ): + for lam, embed, held in zip(_LAMBDAS, expected_embed, expected_held): assert s.morph("qmff", "embed", 1.0, 1.0, lam) == pytest.approx(embed) - assert s.get_molecule_schedule(0).morph( - "clj", "charge", q0, q1, lam - ) == pytest.approx(ml) - assert s.get_molecule_schedule(1).morph( - "clj", "charge", q0, q1, lam - ) == pytest.approx(held) - assert s.morph("clj", "charge", q0, q1, lam) == pytest.approx(held) + for sched in (s, s.get_molecule_schedule(0), s.get_molecule_schedule(1)): + assert sched.morph("clj", "charge", q0, q1, lam) == pytest.approx(held) def test_ml_embedding_stages_no_molecule_schedule(): - """The ML molecule gets its own schedule if it doesn't have one.""" - s = ml_embedding_stages(LambdaSchedule.standard_morph(), 0, 1, 1 / 3) + """No molecule schedules are added.""" + s = ml_embedding_stages(LambdaSchedule.standard_morph(), 1, 1 / 3) - assert s.has_molecule_schedule(0) - assert s.get_molecule_schedule(0).morph("clj", "charge", 0.4, -0.2, 0.0) == 0.0 + assert not s.has_molecule_schedule(0) + assert s.morph("qmff", "embed", 1.0, 1.0, 0.0) == pytest.approx(1.0) assert s.morph("clj", "charge", 0.4, -0.2, 0.0) == pytest.approx(0.4) @@ -77,7 +69,7 @@ def test_ml_embedding_stages_fraction(): schedule = LambdaSchedule.standard_morph() schedule.set_molecule_schedule(0, ml_schedule) - s = ml_embedding_stages(schedule, 0, 1, 0.1) + s = ml_embedding_stages(schedule, 1, 0.1) lambdas = (0.0, 0.05, 0.1, 0.9, 0.95, 1.0) expected_embed = (1.0, 0.5, 0.0, 0.0, 0.5, 1.0) @@ -93,15 +85,14 @@ def test_ml_embedding_stages_decoupled(): q0 = 0.4 - s = ml_embedding_stages(decouple(), 0, 1, 0.1, decoupled=True) + s = ml_embedding_stages(decouple(), 1, 0.1, decoupled=True) assert s.get_stages() == ["embedding_off", "decharge", "decouple"] - ml = s.get_molecule_schedule(0) lambdas = (0.0, 0.05, 0.1, 1.0) expected_embed = (1.0, 0.5, 0.0, 0.0) - expected_ml = (0.0, 0.5 * q0, q0, 0.0) + expected_charge = (q0, q0, q0, 0.0) - for lam, embed, charge in zip(lambdas, expected_embed, expected_ml): + for lam, embed, charge in zip(lambdas, expected_embed, expected_charge): assert s.morph("qmff", "embed", 1.0, 1.0, lam) == pytest.approx(embed) - assert ml.morph("clj", "charge", q0, 0.0, lam) == pytest.approx(charge) + assert s.morph("clj", "charge", q0, 0.0, lam) == pytest.approx(charge) diff --git a/tests/viewer/test_summary.py b/tests/viewer/test_summary.py index 1a62900..2fa917c 100644 --- a/tests/viewer/test_summary.py +++ b/tests/viewer/test_summary.py @@ -217,3 +217,28 @@ def test_vacuum_settings_ml_embedding(): vacuum["ml_model"] = "mace-off23-small" assert vacuum_settings(free, set()) != vacuum_settings(vacuum, set()) + + +def test_vacuum_settings_ml_selection(): + """ + Make sure that the ML embedding settings are compared when only part of the + molecule is ML, since the rest of the molecule is MM in the vacuum leg. + """ + from somd2._viewer._summary import vacuum_settings + + selection = "resnum 3 and not atomname N,H,C,O" + free = { + "ml_model": "ani2x", + "ml_selection": selection, + "ml_embedding": "electrostatic", + } + vacuum = { + "ml_model": "ani2x", + "ml_selection": selection, + "ml_embedding": "mechanical", + } + + assert vacuum_settings(free, set()) != vacuum_settings(vacuum, set()) + + vacuum["ml_embedding"] = "electrostatic" + assert vacuum_settings(free, set()) == vacuum_settings(vacuum, set())