From 3cfcfd859c221aeed455950362a7b8e38a7d3df0 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Mon, 9 Nov 2026 09:11:01 +0000 Subject: [PATCH] Remove support for the osmotic ensemble. --- CHANGELOG.md | 1 + README.md | 18 ++------- src/loch/_sampler.py | 85 +++++++------------------------------------ tests/test_osmotic.py | 70 ----------------------------------- 4 files changed, 17 insertions(+), 157 deletions(-) delete mode 100644 tests/test_osmotic.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 43ceea4..5e92a8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ Changelog * Flag virtual sites on perturbable molecules as ghosts when their parent atom is a ghost, so that they use soft-core rather than full Coulomb interactions with the waters [#53](https://github.com/OpenBioSim/loch/pull/53). * Add an `opencl_platform_index` option so that the OpenCL device is chosen from the same platform as the OpenMM context [#55](https://github.com/OpenBioSim/loch/pull/55). * Give a trial water that overlaps a non-ghost atom in an alchemical system the overlap energy, rather than inf or NaN [#57](https://github.com/OpenBioSim/loch/pull/57). +* Remove support for the osmotic ensemble, which isn't valid for GCMC of solvent water: the number of waters is barely fixed, so it drifts. A barostat is rejected again [#63](https://github.com/OpenBioSim/loch/pull/63). [2026.2.0](https://github.com/openbiosim/loch/compare/2026.1.0...2026.2.0) - Sep 2026 -------------------------------------------------------------------------------------- diff --git a/README.md b/README.md index 43e4f5c..e86c662 100644 --- a/README.md +++ b/README.md @@ -196,21 +196,9 @@ d = gcmc_system.dynamics( > for an example of how to perform an OpenMM-to-Sire roundtrip. > [!Note] -> By default, GCMC sampling is performed in the μVT ensemble with a fixed box, -> hence the pressure is set to `None` in the above example. Bulk sampling moves -> can be used as an effective barostat. Alternatively, to sample the μpT -> (osmotic) ensemble, pass the same `pressure` to both the `GCMCSampler` and -> the dynamics object, e.g. `pressure="1 atm"`. The box volume is then read -> from the context at each move. - -> [!Warning] -> In the μpT ensemble, moves within the entire box are only well behaved when -> the chemical potential of the water depends strongly on how much is present, -> e.g. when water is adsorbed into a material or is one component of a mixture. -> When the water is the solvent of a dilute system, such as a solvated protein, -> its chemical potential is almost that of pure water, so the number of waters -> is barely fixed and can drift. For such systems, sample within a GCMC sphere, -> i.e. set a `reference`, and set `bulk_sampling_probability=0`. +> GCMC sampling must be performed in the NVT ensemble, hence the pressure +> is set to `None` in the above example. However, bulk sampling moves can +> be used as an effective barostat. In order to enable crash recovery during dynamics, we next need to bind the `GCMCSampler` to the Sire dynamics object. This makes sure that the diff --git a/src/loch/_sampler.py b/src/loch/_sampler.py index da22ff9..cba746f 100644 --- a/src/loch/_sampler.py +++ b/src/loch/_sampler.py @@ -39,16 +39,6 @@ from ._platforms._rng import RNGManager as _RNGManager from ._softcore import SoftcoreForm as _SoftcoreForm -import sys as _sys - -try: - "μ".encode(_sys.stdout.encoding or "utf-8") - _mu_sym = "μ" -except (UnicodeEncodeError, LookupError): - _mu_sym = "mu" - -del _sys - def _as_float32(arr: _np.ndarray) -> _np.ndarray: """Convert array to float32 only if not already float32.""" @@ -75,7 +65,6 @@ def __init__( excess_chemical_potential: str = "-6.09 kcal/mol", standard_volume: str = "30.543 A^3", temperature: str = "298 K", - pressure: _Optional[str] = None, adams_shift: _Union[int, float] = 0.0, num_ghost_waters: int = 20, batch_size: int = 1000, @@ -140,12 +129,6 @@ def __init__( temperature: str The temperature of the system. - pressure: str - The pressure for NPT simulation, e.g. "1 atm". If None (default), - the simulation runs in the μVT ensemble with a fixed box. When set, - the box is updated from the context at each move and the Adams value - is recomputed accordingly, sampling the μpT (osmotic) ensemble. - adams_shift: float The Adams shift. @@ -366,16 +349,6 @@ def __init__( except Exception as e: raise ValueError(f"Could not validate the 'temperature': {e}") - if pressure is not None: - try: - self._pressure = self._validate_sire_unit( - "pressure", pressure, _sr.u("atm") - ) - except Exception as e: - raise ValueError(f"Could not validate the 'pressure': {e}") - else: - self._pressure = None - if not isinstance(num_ghost_waters, int): raise ValueError("'num_ghost_waters' must be of type 'int'") self._num_ghost_waters = num_ghost_waters @@ -778,8 +751,8 @@ def __init__( * _openmm.unit.kelvin ) - # Compute the Adams values from the current box and sphere volume. - self._compute_adams_values(self._system) + # Compute the Adams values from the box and sphere volume. + self._compute_adams_values() # Coulomb energy prefactor. self._prefactor = 1.0 / (4.0 * _np.pi * _sr.units.epsilon0.value()) @@ -855,7 +828,6 @@ def __str__(self) -> str: f"excess_chemical_potential={self._excess_chemical_potential}, " f"standard_volume={self._standard_volume}, " f"temperature={self._temperature}, " - f"pressure={self._pressure}, " f"num_ghost_waters={self._num_ghost_waters}, " f"adams_shift={self._adams_shift}, " f"batch_size={self._batch_size}, " @@ -1087,32 +1059,14 @@ def compiler_log(self) -> str: """ return self._backend.compiler_log - def _compute_adams_values(self, system: _Any) -> None: + def _compute_adams_values(self) -> None: """ - Compute the Adams values from the current box and sphere volume. + Compute the Adams values from the box and sphere volume. Updates self._exp_B, self._exp_minus_B, self._exp_B_bulk, and self._exp_minus_B_bulk. - - Parameters - ---------- - - system: sire.system.System, openmm.Context, openmm.State - The molecular system, OpenMM context, or OpenMM state. """ - if isinstance(system, _sr.system.System): - volume = system.property("space").volume().value() - elif isinstance(system, _openmm.Context): - box = system.getState().getPeriodicBoxVectors(asNumpy=True) - volume = _np.linalg.det(box / _openmm.unit.angstrom) - elif isinstance(system, _openmm.State): - box = system.getPeriodicBoxVectors(asNumpy=True) - volume = _np.linalg.det(box / _openmm.unit.angstrom) - else: - raise ValueError( - "'system' must be of type 'sire.system.System', 'openmm.Context', " - "or 'openmm.State'" - ) + volume = self._space.volume().value() gcmc_volume = (4.0 * _np.pi * self._radius.value() ** 3) / 3.0 @@ -1143,8 +1097,8 @@ def set_box(self, system: _Any) -> None: Parameters ---------- - system: sire.system.System, openmm.Context, openmm.State - The molecular system, OpenMM context, or OpenMM state. + system: sire.system.System, openmm.Context + The molecular system, or OpenMM context. """ # Get the space property from the system. @@ -1154,12 +1108,8 @@ def set_box(self, system: _Any) -> None: except Exception: raise ValueError("'system' must contain a 'space' property") # Create a Sire TriclinicBox from the OpenMM box vectors. - elif isinstance(system, (_openmm.Context, _openmm.State)): - box = ( - system.getState().getPeriodicBoxVectors() - if isinstance(system, _openmm.Context) - else system.getPeriodicBoxVectors() - ) + elif isinstance(system, _openmm.Context): + box = system.getState().getPeriodicBoxVectors() v0 = [10 * box[0].x, 10 * box[0].y, 10 * box[0].z] v1 = [10 * box[1].x, 10 * box[1].y, 10 * box[1].z] v2 = [10 * box[2].x, 10 * box[2].y, 10 * box[2].z] @@ -1168,8 +1118,7 @@ def set_box(self, system: _Any) -> None: ) else: raise ValueError( - "'system' must be of type 'sire.system.System', 'openmm.Context', " - "or 'openmm.State'" + "'system' must be of type 'sire.system.System' or 'openmm.Context'" ) # Get the box information. @@ -1701,13 +1650,6 @@ def move(self, context: _openmm.Context) -> list[int]: else: initial_energy = None - # For NPT (μpT), update the box and recompute Adams values - # from the current context state so that volume fluctuations - # driven by the barostat are reflected in the acceptance criterion. - if self._pressure is not None: - self.set_box(state) - self._compute_adams_values(state) - # Sample within the GCMC sphere. if self._reference is not None and not self._is_bulk: target = self._get_target_position(positions_angstrom).astype( @@ -3421,11 +3363,10 @@ def _set_nonbonded_forces(self, context): self._nonbonded_force = force elif self._is_fep and force.getName() == "GhostNonGhostNonbondedForce": self._custom_nonbonded_force = force - elif self._pressure is None and "Barostat" in force.getName(): + elif "Barostat" in force.getName(): msg = ( - f"A barostat was detected but no pressure was set: " - f"'{force.getName()}' is not supported in the {_mu_sym}VT ensemble. " - f"Pass pressure= to enable {_mu_sym}pT (osmotic) sampling." + f"GCMC must be used at constant volume: " + f"'{force.getName()}' is not supported." ) _logger.error(msg) raise TypeError(msg) diff --git a/tests/test_osmotic.py b/tests/test_osmotic.py deleted file mode 100644 index 840801a..0000000 --- a/tests/test_osmotic.py +++ /dev/null @@ -1,70 +0,0 @@ -import os - -import openmm -import pytest - -from loch import GCMCSampler - - -@pytest.mark.skipif( - "CUDA_VISIBLE_DEVICES" not in os.environ, - reason="Requires CUDA enabled GPU.", -) -@pytest.mark.parametrize("platform", ["cuda", "opencl"]) -def test_osmotic_ensemble(water_box, platform): - """ - When pressure is set, move() updates box parameters and Adams values - from the current OpenMM context state after each call. - - Two moves are performed with the box scaled between them. After the - second move, _v_nm3, _exp_B_bulk, and _exp_minus_B_bulk must all - reflect the new volume. - """ - mols, _ = water_box - - sampler = GCMCSampler( - mols, - cutoff_type="rf", - cutoff="10 A", - pressure="1 atm", - ghost_file=None, - log_file=None, - test=True, - platform=platform, - seed=42, - ) - - # NPT dynamics so the context carries a barostat (bypasses the muVT guard). - d = sampler.system().dynamics( - cutoff_type="rf", - cutoff="10 A", - temperature="298 K", - pressure="1 atm", - constraint="h_bonds", - timestep="2 fs", - platform=platform, - ) - context = d.context() - - # First move: record initial box-dependent values. - sampler.move(context) - v_nm3_before = sampler._v_nm3 - exp_B_bulk_before = sampler._exp_B_bulk - exp_minus_B_bulk_before = sampler._exp_minus_B_bulk - - # Scale the box uniformly to simulate a barostat volume move. - scale = 1.1 - box = context.getState().getPeriodicBoxVectors(asNumpy=True) - box_nm = box.value_in_unit(openmm.unit.nanometer) - context.setPeriodicBoxVectors( - openmm.Vec3(*box_nm[0] * scale) * openmm.unit.nanometer, - openmm.Vec3(*box_nm[1] * scale) * openmm.unit.nanometer, - openmm.Vec3(*box_nm[2] * scale) * openmm.unit.nanometer, - ) - - # Second move: box parameters must now reflect the scaled volume. - sampler.move(context) - - assert sampler._v_nm3 == pytest.approx(v_nm3_before * scale**3, rel=1e-5) - assert sampler._exp_B_bulk != exp_B_bulk_before - assert sampler._exp_minus_B_bulk != exp_minus_B_bulk_before