Skip to content
Closed
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
28 changes: 28 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,34 @@

All notable changes to fes-ml are listed here.

## Unreleased

### Changed

- `EMLEPotential` no longer uses Sire. It is one openmm-torch `TorchForce` (TorchScript), replayed
from a CUDA graph on CUDA devices, so no Python runs at each step. The ML charges are scaled by
1 - lambda in the NonbondedForce, and the force adds lambda * E_EMLE. lambda = 0 is now the MM
System with PME. See the new guide page, "EMLE embedding".
- With periodic boundary conditions, EMLE sums the ML-MM electrostatics over all periodic images
with PME by default (`electrostatics="pme"`).
- `EMLEPotential` keeps lambda in the global parameter `lambda_emle` (or `lambda_interpolate`
when it takes lambda from `MLInterpolation`). Windows with EMLE can share one Context.
- EMLE energies change, because the scheme is new.

### Upgrading

- The `emle` extra no longer needs Sire. PME needs an emle-engine with `electrostatics="pme"`.
- The `EMLEPotential` options `backend`, `torch_model`, `neighbour_list_frequency`,
`lambda_interpolate`, `interpolate_steps` and `dispersion_mode` raise an error. New options:
`electrostatics`, `pme_cutoff`, `pme_tolerance`, `switch_width`, `cuda_graph` and `dense_aev`.
- `EMLEPotential` and `ChargeScaling` on the same atoms raise an error.
- The OpenFF strategy no longer takes `emle_plus`.

### Removed

- The strategy inputs `mols`, `parm7`, `mm_charges`, `openmm_charges`, `top_file` and `crd_file`,
which only EMLE used, and the lambda "levers" of `AlchemicalState` and `SharedContext`.

## 0.4.0 (2026-12-04)

This release adds protocol files, one output file per window, MBAR analysis and provenance
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ fes-ml-analyse benzene_water_window_*.h5 --decorrelate
More in the user guide:
[λ schedules and modifications](https://michellab.github.io/fes-ml/guide/schedules/),
[running simulations](https://michellab.github.io/fes-ml/guide/running/) (one window per job, restarts),
[Sire and OpenFF strategies, EMLE](https://michellab.github.io/fes-ml/guide/strategies/),
[Sire and OpenFF strategies](https://michellab.github.io/fes-ml/guide/strategies/),
[EMLE embedding](https://michellab.github.io/fes-ml/guide/emle/),
[alchemical groups](https://michellab.github.io/fes-ml/guide/groups/),
[writing a modification](https://michellab.github.io/fes-ml/guide/extending/),
[logging](https://michellab.github.io/fes-ml/guide/logging/).
Expand Down
76 changes: 76 additions & 0 deletions docs/guide/emle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# EMLE embedding

`EMLEPotential` gives the ML region an electrostatic embedding with
[EMLE](https://github.com/chemle/emle-engine): the MM charges polarise the ML region (static and
induced terms). It runs inside OpenMM as one openmm-torch `TorchForce`, with no Sire and no Python
at each step.

## The energy

```
E(λ) = E_MM[ML charges (1 − λ) q] + λ E_EMLE
```

- The MM charges of the ML atoms are scaled by `1 − λ` with parameter offsets in the
NonbondedForce. So the MM electrostatics between the ML and MM atoms go from full at λ = 0 to
none at λ = 1, through OpenMM's own PME.
- `E_EMLE` is the EMLE embedding energy of the ML atoms in the field of the MM charges.
- The ML-ML pairs move to a separate force, as with `MLInterpolation`, so they do not change
with λ.

At λ = 0 the System is the MM System; at λ = 1 the ML-MM electrostatics are EMLE. In between, the
energy is linear in λ, except for the interaction of the ML region with its own periodic images in
the MM term, which goes as (1 − λ)².

With periodic boundary conditions, EMLE sums the electrostatics over all periodic images with PME
(`electrostatics="pme"`, the default). `electrostatics="cutoff"` uses a cutoff and a smooth switch
instead. Without periodic boundary conditions, EMLE uses all MM atoms.

λ is the OpenMM global parameter `lambda_emle` (`lambda_emle_<group>` for a named group). Without
its own λ, `EMLEPotential` uses the λ of the `MLInterpolation` of its group (`lambda_interpolate`).
So windows can share one Context.

```python
schedule = {"MLInterpolation": [1.0, 0.5, 0.0], "EMLEPotential": [1.0, 0.5, 0.0]}
modifications_kwargs = {"MLPotential": {"name": "ani2x"}}
```

## Options

| Option | Default | Meaning |
|---|---|---|
| `method` | `"electrostatic"` | EMLE method: `"electrostatic"`, `"mechanical"` or `"nonpol"` |
| `model` | `None` | EMLE model file; `None` is the default model of emle-engine |
| `alpha_mode` | `"fixed"` | how emle-engine computes the polarisabilities |
| `qm_charge` | sum of the MM charges | total charge of the ML region |
| `electrostatics` | `"pme"` if periodic | `"pme"` or `"cutoff"` |
| `pme_cutoff` | `"10A"` | real-space cutoff of PME; shorter than half the box width minus the size of the ML region |
| `pme_tolerance` | `2e-5` | Ewald error tolerance, as in OpenMM |
| `cutoff` | `"12A"` | cutoff with `electrostatics="cutoff"` |
| `switch_width` | `0.2` | part of the cutoff over which the switch goes from 1 to 0 |
| `device` | CUDA if available | device of the EMLE model |
| `cuda_graph` | `True` | replay the force from a CUDA graph (openmm-torch's `useCUDAGraphs`) |
| `dense_aev` | `True` | emle-engine's dense features, which a CUDA graph can capture (cost grows with the cube of the number of ML atoms) |
| `forceGroup` | `0` | force group of the EMLE force |

`EMLEPotential` and `ChargeScaling` cannot both scale the charges of the same atoms.

## Speed

Ethanol in 1000 waters (3009 atoms), 1 fs steps, one RTX 4090, EMLE with a CUDA graph: about
1.3 ms per step with PME, against 0.1 ms for MM alone. Without the CUDA graph, a step is 6 to 8
times slower. In float32 on CUDA, two evaluations at the same positions differ by up to about
4e-3 kJ/mol.

## Installation

The `emle` extra installs emle-engine and openmm-torch. PME needs an emle-engine with
`electrostatics="pme"`.

## Changes from fes-ml 0.4

Earlier versions ran EMLE through Sire and a Python `EMLECalculator`, with a cutoff, so λ = 0 was
not the PME MM System and the ML region lost the electrostatics beyond the cutoff. The options
`backend`, `torch_model`, `neighbour_list_frequency`, `lambda_interpolate`, `interpolate_steps` and
`dispersion_mode` are gone: the ML energy comes from `MLPotential` or `MLInterpolation`, and λ
comes from the schedule.
5 changes: 2 additions & 3 deletions docs/guide/extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,8 @@ options in `modifications_kwargs["MassScaling"]`.
[groups and dependencies](groups.md).
- If `apply` needs data that only the creation strategy has, declare it:
`inputs = ("topology",)`. The strategy then passes it as a keyword argument, computed once per
group. Both strategies provide `topology` (OpenMM), `mols` (Sire), `parm7` and `mm_charges`; the
OpenFF strategy also provides `positions`, `topology_off`, `original_offxml`, `openmm_charges`,
and `top_file`/`crd_file` when EMLE needs them.
group. Both strategies provide `topology` (OpenMM); the OpenFF strategy also provides
`positions`, `topology_off` and `original_offxml`.
- To let a Context change your λ without rebuilding the System, keep λ in an OpenMM global
parameter named by `self.lambda_parameter` and set the class attribute `LAMBDA_PARAMETER`
(for example `"lambda_mass"`); named groups get the suffix `_<group>` automatically.
Expand Down
7 changes: 4 additions & 3 deletions docs/guide/schedules.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ values outside [0, 1] give a warning. `None` in a window leaves that modificatio
| `ChargeScaling` | full charges | zero charges (intermolecular electrostatics only) | — |
| `MLInterpolation` | ML potential for the alchemical region | MM potential | `ml` extra |
| `MLCorrection` | MM + (ML − MM) Δ-learning correction | MM | `ml` extra |
| `EMLEPotential` | electrostatic embedding | mechanical embedding | `emle` extra |
| `EMLEPotential` | EMLE electrostatic embedding | MM electrostatics | `emle` extra |
| `CustomLJ` | optimised LJ parameters (from an offxml) | original LJ parameters | `openff` extra |
| `ChargeTransfer` | short-ranged charge-transfer term on | off | `openff` extra |

Expand All @@ -51,7 +51,7 @@ The options of each modification are the keyword arguments of its `apply` method

## λ as OpenMM global parameters

`LJSoftCore`, `ChargeScaling`, `ChargeTransfer`, `MLInterpolation` and `MLCorrection` keep λ in an OpenMM global
`LJSoftCore`, `ChargeScaling`, `ChargeTransfer`, `MLInterpolation`, `MLCorrection` and `EMLEPotential` keep λ in an OpenMM global
parameter, so an existing Context can be moved to another λ with `context.setParameter(...)`:

| Modification | Parameter |
Expand All @@ -60,9 +60,10 @@ parameter, so an existing Context can be moved to another λ with `context.setPa
| `ChargeScaling` | `lambda_electrostatics` (NonbondedForce parameter offsets) |
| `ChargeTransfer` | `lambda_charge_transfer` |
| `MLInterpolation`, `MLCorrection` | `lambda_interpolate` |
| `EMLEPotential` | `lambda_emle` (or `lambda_interpolate`, without its own λ) |

For a named [group](groups.md), the name gets the suffix `_<group>`, for example
`lambda_sterics_ligand`. `CustomLJ` and `EMLEPotential` build their λ into the System.
`lambda_sterics_ligand`. `CustomLJ` builds its λ into the System.

`{"ChargeScaling": {"use_global_parameter": False}}` writes the scaled charges into the System
instead. The two forms agree exactly on the Reference platform. On CUDA, OpenMM's PME takes a
Expand Down
8 changes: 3 additions & 5 deletions docs/guide/strategies.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,13 @@ Results can depend on the Sire version that built the system, so record it with

### EMLE

Options of the [`EMLECalculator`](https://github.com/chemle/emle-engine) go to the
`EMLEPotential` modification:
`EMLEPotential` works with both strategies and does not need Sire; see [EMLE embedding](emle.md):

```python
modifications_kwargs = {"EMLEPotential": {"method": "electrostatic", "backend": "torchani", "device": "cpu"}}
modifications_kwargs = {"EMLEPotential": {"method": "electrostatic", "cutoff": "12A"}}
```

The strategy provides the files and charges EMLE needs. The old `emle_kwargs` argument still works
but is deprecated.
The old `emle_kwargs` argument still works but is deprecated.

## OpenFF

Expand Down
3 changes: 2 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ fes-ml-analyse benzene_water_window_*.h5 --decorrelate
- [Installation](installation.md): which extras you need.
- [λ schedules and modifications](guide/schedules.md): what each modification does.
- [Running simulations](guide/running.md): minimisation, equilibration, production, restarts.
- [Creation strategies](guide/strategies.md): Sire or OpenFF, dynamics options and EMLE.
- [EMLE embedding](guide/emle.md): electrostatic embedding of the ML region, without Sire.
- [Creation strategies](guide/strategies.md): Sire or OpenFF, and dynamics options.
- [Alchemical groups and dependencies](guide/groups.md): several regions in one schedule, and how
the modifications are ordered.
- [Writing a modification](guide/extending.md): add your own.
Expand Down
2 changes: 1 addition & 1 deletion docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ system builders and potentials are optional extras, so you install only what you
| `sire` | the Sire creation strategy (Amber files) | `sire` |
| `openff` | the OpenFF creation strategy (the default), `CustomLJ`, `ChargeTransfer` | `openff-toolkit`, `openff-interchange` |
| `ml` | `MLPotential`, `MLInterpolation`, `MLCorrection` | `openmm-ml`, `openmm-torch`, `torch`, `torchani` |
| `emle` | `EMLEPotential` (electrostatic embedding) | `emle-engine`, `sire` |
| `emle` | `EMLEPotential` (electrostatic embedding) | `emle-engine`, `openmm-torch` |
| `analysis` | MBAR | `pymbar` |
| `viz` | plots | `matplotlib` |
| `dev` | tests, linting, type checks | `pytest`, `ruff`, `mypy`, `pre-commit` |
Expand Down
8 changes: 4 additions & 4 deletions environment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ dependencies:
# OpenMM 8.5 is built against NumPy 2, which mace-torch (pip) installs (#17)
- openmm>=8.5
- coloredlogs
# Sire strategy, EMLE
# Sire strategy
- sire
# OpenFF strategy, CustomLJ, ChargeTransfer
- openff-toolkit
- openff-interchange
- ambertools
# packmol-memgen (ambertools) imports pkg_resources, which setuptools 82 removes
- setuptools<82
# ML modifications
# ML modifications and EMLE
- openmm-torch
- openmm-ml
- pytorch=*=*cuda*
Expand All @@ -34,6 +34,6 @@ dependencies:
- pymbar
- pip
- pip:
# Pinned: the default branch moves (2026-12-03)
- git+https://github.com/chemle/emle-engine.git@85bb26207bff651fda4c765b16516a11ae1625db
# Pinned: PME for EMLE (electrostatics="pme") is in chemle/emle-engine pull request 133, not merged yet
- git+https://github.com/JMorado/emle-engine.git@17af21f2263672551c4e59be21a04651cca5e0ca
- mace-torch
9 changes: 4 additions & 5 deletions examples/ml_mm_emle/ml_mm_emle.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
The alchemical schedule consists of a single stage:
1. ML Interpolation: Gradually transitions from MM to ML representation of the solute in solution
(MLInterpolation: 1.0 -> 0.0, where 1.0 is ML and 0.0 is MM)
2. EMLE Potential: Gradually transitions from mechanical embedding to electrostatic embedding (EMLE)
representation of the solute in solution
(EMLEPotential: 1.0 -> 0.0, where 1.0 is electrostatic embedding and 0.0 is mechanical embedding)
2. EMLE Potential: Gradually transitions from MM electrostatics to the EMLE electrostatic embedding
of the solute in solution
(EMLEPotential: 1.0 -> 0.0, where 1.0 is EMLE embedding and 0.0 is MM electrostatics)

Usage:
python ml_mm_emle.py <script> <window> [options]
Expand Down Expand Up @@ -101,8 +101,7 @@
modifications_kwargs = {
"MLPotential": {"name": "mace-off23-small"},
"EMLEPotential": {
"torch_model": False,
"device": "cuda",
"device": "cuda", # PME for the embedding by default
"model": None, # use the default model
"qm_charge": 0,
},
Expand Down
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ nav:
- λ schedules and modifications: guide/schedules.md
- Running simulations: guide/running.md
- Output files and analysis: guide/analysis.md
- EMLE embedding: guide/emle.md
- Creation strategies: guide/strategies.md
- Groups and dependencies: guide/groups.md
- Writing a modification: guide/extending.md
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ content-type = "text/markdown"
sire = ["sire"]
openff = ["openff-toolkit", "openff-interchange"]
ml = ["openmm-ml", "openmm-torch", "torch", "torchani"]
emle = ["emle-engine", "sire"]
emle = ["emle-engine", "openmm-torch", "torch"]
viz = ["matplotlib"]
analysis = ["pymbar"]
protocol = ["pyyaml"]
Expand Down
2 changes: 1 addition & 1 deletion src/fes_ml/_optional.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"sire": (("sire",), "sire"),
"openff": (("openff.toolkit", "openff.interchange"), "openff"),
"ml": (("openmmml", "openmmtorch", "torch"), "ml"),
"emle": (("emle", "sire"), "emle"),
"emle": (("emle", "emle.models", "openmmtorch"), "emle"),
"viz": (("matplotlib",), "viz"),
"analysis": (("pymbar", "pymbar.timeseries"), "analysis"),
"protocol": (("yaml",), "protocol"),
Expand Down
5 changes: 1 addition & 4 deletions src/fes_ml/alchemical/alchemical_state.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Module that defines the AlchemicalState dataclass."""

from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Union
from typing import Any, Dict, Optional, Union

import openmm as _mm
import openmm.app as _app
Expand Down Expand Up @@ -34,8 +34,6 @@ class AlchemicalState:
windows (``FES.create_alchemical_states(..., shared_context=True)``).
shared : fes_ml.sampling.SharedContext, optional
The shared Context, or None if the state has a Context of its own.
levers : dict, optional
Callbacks that change lambdas held outside OpenMM (EMLE's calculator), by parameter name.
"""

# OpenMM objects
Expand All @@ -54,7 +52,6 @@ class AlchemicalState:
# Windows that share one Context (R3)
parameters: Optional[Dict[str, float]] = field(repr=False, default=None)
shared: Optional[Any] = field(repr=False, default=None)
levers: Optional[Dict[str, List[Callable[[float], None]]]] = field(repr=False, default=None)

def activate(self) -> None:
"""Make the Context simulate this window (a no-op unless the Context is shared)."""
Expand Down
1 change: 0 additions & 1 deletion src/fes_ml/alchemical/modifications/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,3 @@
ml_interpolation as ml_interpolation,
ml_potential as ml_potential,
)
from .emle_potential import _EMLE_CALCULATORS as _EMLE_CALCULATORS
73 changes: 73 additions & 0 deletions src/fes_ml/alchemical/modifications/_emle_torch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""
TorchScript modules of the EMLE force (see :mod:`fes_ml.alchemical.modifications.emle_potential`).

They are in their own module, which imports torch, so that fes-ml imports torch only for EMLE.
"""

from typing import List, Optional

import torch

from .emle_potential import HARTREE_TO_KJ_MOL


class _Embedding(torch.nn.Module):
"""``lambda * E_EMLE`` in kJ/mol, from the positions in nm (and the box, if periodic)."""

ml: torch.Tensor
mm: torch.Tensor
atomic_numbers: torch.Tensor
charges_mm: torch.Tensor

def __init__(
self,
model: torch.nn.Module,
ml: List[int],
n_atoms: int,
atomic_numbers: List[int],
charges: List[float],
qm_charge: int,
cutoff_mode: bool,
) -> None:
super().__init__()
is_mm = torch.ones(n_atoms, dtype=torch.bool)
is_mm[torch.tensor(ml, dtype=torch.long)] = False
self.model = model
self.register_buffer("ml", torch.tensor(ml, dtype=torch.long))
self.register_buffer("mm", torch.arange(n_atoms, dtype=torch.long)[is_mm])
self.register_buffer("atomic_numbers", torch.tensor(atomic_numbers, dtype=torch.long))
self.register_buffer("charges_mm", torch.tensor(charges, dtype=torch.float32)[is_mm])
self.qm_charge = int(qm_charge)
self.cutoff_mode = cutoff_mode
self.hartree_to_kj_mol = HARTREE_TO_KJ_MOL

def embedding(self, positions: torch.Tensor, cell: Optional[torch.Tensor], lam: torch.Tensor) -> torch.Tensor:
# OpenMM's minimiser can evaluate the System on the CPU: compute on the model's
# device, and give the energy back on the device of the positions
device = self.ml.device
xyz = positions.to(device=device, dtype=torch.float32) * 10.0
if cell is not None:
cell = cell.to(device=device, dtype=torch.float32) * 10.0
energies = self.model(
self.atomic_numbers,
self.charges_mm,
xyz[self.ml],
xyz[self.mm],
cell=cell,
qm_charge=self.qm_charge,
preprocess=self.cutoff_mode and cell is not None,
use_switching_function=self.cutoff_mode,
)
energy = lam.to(device=device, dtype=torch.float32) * energies.sum()
result: torch.Tensor = (energy.to(torch.float64) * self.hartree_to_kj_mol).to(positions.device)
return result


class PeriodicEmbedding(_Embedding):
def forward(self, positions: torch.Tensor, boxvectors: torch.Tensor, lam: torch.Tensor) -> torch.Tensor:
return self.embedding(positions, boxvectors, lam)


class VacuumEmbedding(_Embedding):
def forward(self, positions: torch.Tensor, lam: torch.Tensor) -> torch.Tensor:
return self.embedding(positions, None, lam)
Loading
Loading