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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
--------------------------------------------------------------------------------------
Expand Down
18 changes: 3 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
85 changes: 13 additions & 72 deletions src/loch/_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand All @@ -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,
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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}, "
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand All @@ -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]
Expand All @@ -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.
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down
70 changes: 0 additions & 70 deletions tests/test_osmotic.py

This file was deleted.

Loading