Skip to content

Commit eda46b8

Browse files
authored
Merge pull request #22 from OpenBioSim/feature_osmotic_ensemble
2 parents b57e903 + 43349d2 commit eda46b8

3 files changed

Lines changed: 172 additions & 38 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Changelog
99
* Add support for long-range Lennard-Jones dispersion correction.
1010
* Add support for Beutler soft-core Lennard-Jones form.
1111
* Fixed type check for ``water_template``.
12+
* Add support for simulations in the osmotic ensemble.
1213

1314
[2025.2.0](https://github.com/openbiosim/loch/compare/2025.1.0...2025.2.0) - Feb 2026
1415
-------------------------------------------------------------------------------------

‎src/loch/_sampler.py‎

Lines changed: 101 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,16 @@
3939
from ._platforms._rng import RNGManager as _RNGManager
4040
from ._softcore import SoftcoreForm as _SoftcoreForm
4141

42+
import sys as _sys
43+
44+
try:
45+
"μ".encode(_sys.stdout.encoding or "utf-8")
46+
_mu_sym = "μ"
47+
except (UnicodeEncodeError, LookupError):
48+
_mu_sym = "mu"
49+
50+
del _sys
51+
4252

4353
def _as_float32(arr: _np.ndarray) -> _np.ndarray:
4454
"""Convert array to float32 only if not already float32."""
@@ -65,6 +75,7 @@ def __init__(
6575
excess_chemical_potential: str = "-6.09 kcal/mol",
6676
standard_volume: str = "30.543 A^3",
6777
temperature: str = "298 K",
78+
pressure: _Optional[str] = None,
6879
adams_shift: _Union[int, float] = 0.0,
6980
num_ghost_waters: int = 20,
7081
batch_size: int = 1000,
@@ -126,6 +137,12 @@ def __init__(
126137
temperature: str
127138
The temperature of the system.
128139
140+
pressure: str
141+
The pressure for NPT simulation, e.g. "1 atm". If None (default),
142+
the simulation runs in the μVT ensemble with a fixed box. When set,
143+
the box is updated from the context at each move and the Adams value
144+
is recomputed accordingly, sampling the μpT (osmotic) ensemble.
145+
129146
adams_shift: float
130147
The Adams shift.
131148
@@ -330,6 +347,16 @@ def __init__(
330347
except Exception as e:
331348
raise ValueError(f"Could not validate the 'temperature': {e}")
332349

350+
if pressure is not None:
351+
try:
352+
self._pressure = self._validate_sire_unit(
353+
"pressure", pressure, _sr.u("atm")
354+
)
355+
except Exception as e:
356+
raise ValueError(f"Could not validate the 'pressure': {e}")
357+
else:
358+
self._pressure = None
359+
333360
if not isinstance(num_ghost_waters, int):
334361
raise ValueError("'num_ghost_waters' must be of type 'int'")
335362
self._num_ghost_waters = num_ghost_waters
@@ -685,27 +712,8 @@ def __init__(
685712
* _openmm.unit.kelvin
686713
)
687714

688-
# Work out the volume of the system and GCMC sphere.
689-
volume = self._space.volume().value()
690-
gcmc_volume = (4.0 * _np.pi * self._radius.value() ** 3) / 3.0
691-
692-
# Work out the Adams value.
693-
B = (
694-
self._beta * self._excess_chemical_potential.value()
695-
+ _np.log(gcmc_volume / self._standard_volume.value())
696-
) + self._adams_shift
697-
698-
# Work out the bulk Adams value.
699-
B_bulk = (
700-
self._beta * self._excess_chemical_potential.value()
701-
+ _np.log(volume / self._standard_volume.value())
702-
) + self._adams_shift
703-
704-
# Store the exponentials for the Adams values.
705-
self._exp_B = _np.exp(B)
706-
self._exp_minus_B = _np.exp(-B)
707-
self._exp_B_bulk = _np.exp(B_bulk)
708-
self._exp_minus_B_bulk = _np.exp(-B_bulk)
715+
# Compute the Adams values from the current box and sphere volume.
716+
self._compute_adams_values(self._system)
709717

710718
# Coulomb energy prefactor.
711719
self._prefactor = 1.0 / (4.0 * _np.pi * _sr.units.epsilon0.value())
@@ -740,9 +748,6 @@ def __init__(
740748
self._log_file, level=self._log_level.upper(), filter="loch"
741749
)
742750

743-
# Log the Adams value.
744-
_logger.debug(f"Adams value: {B:.6f}")
745-
746751
import atexit
747752

748753
# Register the cleanup function.
@@ -772,6 +777,7 @@ def __str__(self) -> str:
772777
f"excess_chemical_potential={self._excess_chemical_potential}, "
773778
f"standard_volume={self._standard_volume}, "
774779
f"temperature={self._temperature}, "
780+
f"pressure={self._pressure}, "
775781
f"num_ghost_waters={self._num_ghost_waters}, "
776782
f"adams_shift={self._adams_shift}, "
777783
f"batch_size={self._batch_size}, "
@@ -872,15 +878,64 @@ def compiler_log(self) -> str:
872878
"""
873879
return self._backend.compiler_log
874880

881+
def _compute_adams_values(self, system: _Any) -> None:
882+
"""
883+
Compute the Adams values from the current box and sphere volume.
884+
885+
Updates self._exp_B, self._exp_minus_B, self._exp_B_bulk, and
886+
self._exp_minus_B_bulk.
887+
888+
Parameters
889+
----------
890+
891+
system: sire.system.System, openmm.Context, openmm.State
892+
The molecular system, OpenMM context, or OpenMM state.
893+
"""
894+
if isinstance(system, _sr.system.System):
895+
volume = system.property("space").volume().value()
896+
elif isinstance(system, _openmm.Context):
897+
box = system.getState().getPeriodicBoxVectors(asNumpy=True)
898+
volume = _np.linalg.det(box / _openmm.unit.angstrom)
899+
elif isinstance(system, _openmm.State):
900+
box = system.getPeriodicBoxVectors(asNumpy=True)
901+
volume = _np.linalg.det(box / _openmm.unit.angstrom)
902+
else:
903+
raise ValueError(
904+
"'system' must be of type 'sire.system.System', 'openmm.Context', "
905+
"or 'openmm.State'"
906+
)
907+
908+
gcmc_volume = (4.0 * _np.pi * self._radius.value() ** 3) / 3.0
909+
910+
B = (
911+
self._beta * self._excess_chemical_potential.value()
912+
+ _np.log(gcmc_volume / self._standard_volume.value())
913+
) + self._adams_shift
914+
915+
B_bulk = (
916+
self._beta * self._excess_chemical_potential.value()
917+
+ _np.log(volume / self._standard_volume.value())
918+
) + self._adams_shift
919+
920+
self._exp_B = _np.exp(B)
921+
self._exp_minus_B = _np.exp(-B)
922+
self._exp_B_bulk = _np.exp(B_bulk)
923+
self._exp_minus_B_bulk = _np.exp(-B_bulk)
924+
925+
_logger.debug(f"Adams value: {B:.6f}")
926+
927+
# Store the box volume in nm^3 for reuse in LRC corrections.
928+
self._v_nm3 = volume / 1000.0
929+
875930
def set_box(self, system: _Any) -> None:
876931
"""
877932
Set the box information.
878933
879934
Parameters
880935
----------
881936
882-
system: sire.system.System, openmm.Context
883-
The molecular system, or OpenMM context.
937+
system: sire.system.System, openmm.Context, openmm.State
938+
The molecular system, OpenMM context, or OpenMM state.
884939
"""
885940

886941
# Get the space property from the system.
@@ -890,8 +945,12 @@ def set_box(self, system: _Any) -> None:
890945
except Exception:
891946
raise ValueError("'system' must contain a 'space' property")
892947
# Create a Sire TriclinicBox from the OpenMM box vectors.
893-
elif isinstance(system, _openmm.Context):
894-
box = system.getState().getPeriodicBoxVectors()
948+
elif isinstance(system, (_openmm.Context, _openmm.State)):
949+
box = (
950+
system.getState().getPeriodicBoxVectors()
951+
if isinstance(system, _openmm.Context)
952+
else system.getPeriodicBoxVectors()
953+
)
895954
v0 = [10 * box[0].x, 10 * box[0].y, 10 * box[0].z]
896955
v1 = [10 * box[1].x, 10 * box[1].y, 10 * box[1].z]
897956
v2 = [10 * box[2].x, 10 * box[2].y, 10 * box[2].z]
@@ -900,7 +959,8 @@ def set_box(self, system: _Any) -> None:
900959
)
901960
else:
902961
raise ValueError(
903-
"'system' must be of type 'sire.system.System' or 'openmm.Context'"
962+
"'system' must be of type 'sire.system.System', 'openmm.Context', "
963+
"or 'openmm.State'"
904964
)
905965

906966
# Get the box information.
@@ -1304,10 +1364,12 @@ def move(self, context: _openmm.Context) -> list[int]:
13041364
else:
13051365
initial_energy = None
13061366

1307-
# Cache the box volume (NVT, so constant throughout).
1308-
if self._has_gcmc_lrc:
1309-
box = state.getPeriodicBoxVectors(asNumpy=True)
1310-
v_nm3 = _np.linalg.det(box / _openmm.unit.nanometer)
1367+
# For NPT (μpT), update the box and recompute Adams values
1368+
# from the current context state so that volume fluctuations
1369+
# driven by the barostat are reflected in the acceptance criterion.
1370+
if self._pressure is not None:
1371+
self.set_box(state)
1372+
self._compute_adams_values(state)
13111373

13121374
# Sample within the GCMC sphere.
13131375
if self._reference is not None and not self._is_bulk:
@@ -1583,7 +1645,7 @@ def move(self, context: _openmm.Context) -> list[int]:
15831645
self._lrc_w_solute
15841646
+ 2.0 * n_w_before_insert * self._lrc_ww_half
15851647
)
1586-
/ v_nm3
1648+
/ self._v_nm3
15871649
* _openmm.unit.kilojoules_per_mole
15881650
)
15891651
dE_RF += dLRC
@@ -1686,7 +1748,7 @@ def move(self, context: _openmm.Context) -> list[int]:
16861748
* (n_w_before_delete - 1.0)
16871749
* self._lrc_ww_half
16881750
)
1689-
/ v_nm3
1751+
/ self._v_nm3
16901752
* _openmm.unit.kilojoules_per_mole
16911753
)
16921754
dE_RF += dLRC
@@ -2819,10 +2881,11 @@ def _set_nonbonded_forces(self, context):
28192881
self._nonbonded_force = force
28202882
elif self._is_fep and force.getName() == "GhostNonGhostNonbondedForce":
28212883
self._custom_nonbonded_force = force
2822-
elif "Barostat" in force.getName():
2884+
elif self._pressure is None and "Barostat" in force.getName():
28232885
msg = (
2824-
f"GCMC must be used at constant volume: "
2825-
f"'{force.getName()}' is not supported."
2886+
f"A barostat was detected but no pressure was set: "
2887+
f"'{force.getName()}' is not supported in the {_mu_sym}VT ensemble. "
2888+
f"Pass pressure= to enable {_mu_sym}pT (osmotic) sampling."
28262889
)
28272890
_logger.error(msg)
28282891
raise TypeError(msg)

‎tests/test_osmotic.py‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import os
2+
3+
import openmm
4+
import pytest
5+
6+
from loch import GCMCSampler
7+
8+
9+
@pytest.mark.skipif(
10+
"CUDA_VISIBLE_DEVICES" not in os.environ,
11+
reason="Requires CUDA enabled GPU.",
12+
)
13+
@pytest.mark.parametrize("platform", ["cuda", "opencl"])
14+
def test_osmotic_ensemble(water_box, platform):
15+
"""
16+
When pressure is set, move() updates box parameters and Adams values
17+
from the current OpenMM context state after each call.
18+
19+
Two moves are performed with the box scaled between them. After the
20+
second move, _v_nm3, _exp_B_bulk, and _exp_minus_B_bulk must all
21+
reflect the new volume.
22+
"""
23+
mols, _ = water_box
24+
25+
sampler = GCMCSampler(
26+
mols,
27+
cutoff_type="rf",
28+
cutoff="10 A",
29+
pressure="1 atm",
30+
ghost_file=None,
31+
log_file=None,
32+
test=True,
33+
platform=platform,
34+
seed=42,
35+
)
36+
37+
# NPT dynamics so the context carries a barostat (bypasses the muVT guard).
38+
d = sampler.system().dynamics(
39+
cutoff_type="rf",
40+
cutoff="10 A",
41+
temperature="298 K",
42+
pressure="1 atm",
43+
constraint="h_bonds",
44+
timestep="2 fs",
45+
platform=platform,
46+
)
47+
context = d.context()
48+
49+
# First move: record initial box-dependent values.
50+
sampler.move(context)
51+
v_nm3_before = sampler._v_nm3
52+
exp_B_bulk_before = sampler._exp_B_bulk
53+
exp_minus_B_bulk_before = sampler._exp_minus_B_bulk
54+
55+
# Scale the box uniformly to simulate a barostat volume move.
56+
scale = 1.1
57+
box = context.getState().getPeriodicBoxVectors(asNumpy=True)
58+
box_nm = box.value_in_unit(openmm.unit.nanometer)
59+
context.setPeriodicBoxVectors(
60+
openmm.Vec3(*box_nm[0] * scale) * openmm.unit.nanometer,
61+
openmm.Vec3(*box_nm[1] * scale) * openmm.unit.nanometer,
62+
openmm.Vec3(*box_nm[2] * scale) * openmm.unit.nanometer,
63+
)
64+
65+
# Second move: box parameters must now reflect the scaled volume.
66+
sampler.move(context)
67+
68+
assert sampler._v_nm3 == pytest.approx(v_nm3_before * scale**3, rel=1e-5)
69+
assert sampler._exp_B_bulk != exp_B_bulk_before
70+
assert sampler._exp_minus_B_bulk != exp_minus_B_bulk_before

0 commit comments

Comments
 (0)