From 4ab7c234686585fcb380aba47ef73aea2f141de7 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Mon, 9 Nov 2026 09:04:22 +0000 Subject: [PATCH] Run GCMC simulations in the NVT ensemble. --- CHANGELOG.md | 4 +- src/somd2/config/_config.py | 68 ++++-------------- src/somd2/runner/_base.py | 98 +++++--------------------- tests/runner/test_config.py | 134 +++++++++--------------------------- tests/runner/test_repex.py | 8 +-- 5 files changed, 70 insertions(+), 242 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab44cb47..0494ad58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,10 +36,10 @@ Changelog * Allow `equilibration_time` to be a list of times, one for each lambda window, e.g. `--equilibration-time 0ps 100ps 100ps 0ps` on the command line. Windows with a time of zero are not equilibrated. A single time is still used for every window [#265](https://github.com/OpenBioSim/somd2/pull/265). * Pass `opencl_platform_index` to the GCMC sampler, so that GCMC runs on the same OpenCL device as the dynamics when there are multiple OpenCL platforms [#266](https://github.com/OpenBioSim/somd2/pull/266). * Fixed energy trajectory times for ABFE bound legs without a Boresch restraint being offset by up to the `restraint_search_time`, since production started from the time of the restraint search frame rather than the input system [#268](https://github.com/OpenBioSim/somd2/pull/268). -* Raise an error when a `perturbed_system` with a different periodic box from the reference system is used for GCMC in the NVT ensemble, since every replica must share the same box. GCMC in the osmotic ensemble, with a pressure set, is unaffected [#271](https://github.com/OpenBioSim/somd2/pull/271). +* Raise an error when a `perturbed_system` with a different periodic box from the reference system is used for GCMC in the NVT ensemble, since every replica must share the same box [#271](https://github.com/OpenBioSim/somd2/pull/271). * Add a `chain_equilibration` option for replica exchange, which speeds up setup by starting each replica from a neighbour that has already been set up. Replicas in the first parallel batch, which is spread across lambda, are minimised and equilibrated from the input system. The rest skip minimisation and are equilibrated for `chain_equilibration_scale` times the `equilibration_time`, which defaults to a quarter [#273](https://github.com/OpenBioSim/somd2/pull/273). * Pass `beutler_alpha` to the GCMC sampler, which otherwise used its own default for the Beutler soft-core form [#275](https://github.com/OpenBioSim/somd2/pull/275). -* Default `gcmc_bulk_sampling_probability` to "auto", which uses 0.1 in the NVT ensemble and 0 when a pressure is set, since the solvent's chemical potential barely depends on the number of waters, so whole-box moves under a barostat let that number drift. A warning is logged when whole-box moves are used with a pressure. On restart, "auto" keeps the value of the last run, and other changes are refused [#278](https://github.com/OpenBioSim/somd2/pull/278). +* Run GCMC simulations in the NVT ensemble, ignoring the pressure, since the osmotic ensemble isn't valid for GCMC of solvent water: the number of waters is barely fixed, so it drifts. GCMC runs started with a pressure can't be restarted [#281](https://github.com/OpenBioSim/somd2/pull/281). [2026.2.0](https://github.com/openbiosim/somd2/compare/2026.1.0...2026.2.0) - Sep 2026 -------------------------------------------------------------------------------------- diff --git a/src/somd2/config/_config.py b/src/somd2/config/_config.py index 8db8983e..492f8c50 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -76,13 +76,12 @@ class Config: "log_level": [level.lower() for level in _logger._core.levels], "softcore_form": ["auto", "zacharias", "taylor", "beutler"], "precision": ["single", "mixed", "double"], - "gcmc_bulk_sampling_probability": ["auto"], } # Options that advertise a set of choices, but which also accept other # forms, e.g. the path to a stream file. These are validated by the setter, # rather than by argparse. - _open_choices = ["lambda_schedule", "gcmc_bulk_sampling_probability"] + _open_choices = ["lambda_schedule"] # A dictionary of nargs for the various options. _nargs = { @@ -217,7 +216,7 @@ def __init__( gcmc_standard_volume="30.543 A^3", gcmc_num_waters=20, gcmc_radius="4 A", - gcmc_bulk_sampling_probability="auto", + gcmc_bulk_sampling_probability=0.1, gcmc_tolerance=0.0, gcmc_batch_size=1000, gcmc_num_attempts=10000, @@ -265,7 +264,8 @@ def __init__( pressure: str Simulation pressure. (Simulations will run in the NVT ensemble unless - a pressure is specified.) + a pressure is specified. GCMC simulations always run in the NVT + ensemble, so the pressure is ignored.) surface_tension: str Surface tension to use for NPT simulations with a membrane barostat. @@ -603,6 +603,7 @@ def __init__( gcmc: bool Whether to perform Grand Canonical Monte Carlo (GCMC) water insertions/deletions. + GCMC simulations always run in the NVT ensemble. gcmc_frequency: str Frequency at which to attempt GCMC moves. If None, then this will be set to the @@ -629,14 +630,11 @@ def __init__( gcmc_radius: str The radius of the GCMC sphere. - gcmc_bulk_sampling_probability: float, str + gcmc_bulk_sampling_probability: float The probability of performing bulk GCMC moves, i.e. within the entire simulation - box rather than the GCMC sphere. These maintain the bulk density in the NVT - ensemble, i.e. acting as a barostat, so aren't needed when a pressure is set. - The default, "auto", uses 0.1 when 'pressure' is None and 0 otherwise. On - restart, "auto" keeps the value of the last run, and other values can't - change. (This option has no effect when 'gcmc_selection=None', where every - move is a bulk move.) + box rather than the GCMC sphere. These can be used to maintain a constant bulk + density, i.e. acting as a barostat. (This option has no affect when + 'gcmc_selection=None'.) gcmc_tolerance: float The tolerance for the GCMC acceptance probability, i.e. the minimum probability @@ -2678,58 +2676,16 @@ def gcmc_radius(self, gcmc_radius): @property def gcmc_bulk_sampling_probability(self): - # Resolved on read, so that "auto" follows later changes to the pressure. - return self._resolve_bulk_sampling_probability( - self._gcmc_bulk_sampling_probability, getattr(self, "_pressure", None) - ) - - @staticmethod - def _is_auto(value): - """ - Whether an option value is "auto", in any case. - """ - return isinstance(value, str) and value.strip().lower() == "auto" - - @staticmethod - def _unwrap(value): - """ - Convert a value from a config stored as a Sire property, e.g. in a - checkpoint file, to a Python value. Units are converted to strings. - """ - from sire.units import GeneralUnit as _GeneralUnit - - if isinstance(value, _GeneralUnit): - return str(value) - try: - return value.value() - except AttributeError: - return value - - @staticmethod - def _resolve_bulk_sampling_probability(probability, pressure): - """ - Resolve a GCMC bulk sampling probability, which may be "auto", for the - given pressure. Bulk moves act as a barostat, so aren't used with one. - """ - probability = Config._unwrap(probability) - if Config._is_auto(probability): - # A stored config records no pressure as None or False. - return 0.1 if not Config._unwrap(pressure) else 0.0 - return float(probability) + return self._gcmc_bulk_sampling_probability @gcmc_bulk_sampling_probability.setter def gcmc_bulk_sampling_probability(self, gcmc_bulk_sampling_probability): - if self._is_auto(gcmc_bulk_sampling_probability): - self._gcmc_bulk_sampling_probability = "auto" - return if not isinstance(gcmc_bulk_sampling_probability, float): try: gcmc_bulk_sampling_probability = float(gcmc_bulk_sampling_probability) except Exception: - raise ValueError( - "'gcmc_bulk_sampling_probability' must be a float or 'auto'" - ) - if not 0.0 <= gcmc_bulk_sampling_probability <= 1.0: + raise ValueError("'gcmc_bulk_sampling_probability' must be a float") + if gcmc_bulk_sampling_probability < 0.0 or gcmc_bulk_sampling_probability > 1.0: raise ValueError( "'gcmc_bulk_sampling_probability' must be between 0.0 and 1.0" ) diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index 1b9b4227..7aad9e1c 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -77,7 +77,6 @@ def __init__(self, system, config): self._set_terminal_groups() self._prepare_output_and_restart() - self._check_gcmc_bulk_moves() self._finalise_systems() self._set_dynamics_kwargs() self._limit_sire_threads() @@ -131,6 +130,14 @@ def _set_config(self, config): # user's final choice of output directory is known. self._config._setup_output_directory() + # GCMC of solvent water is only well defined at constant volume. + if self._config.gcmc and self._config.pressure is not None: + _logger.info( + "GCMC simulations are run in the NVT ensemble, so the pressure is " + "ignored." + ) + self._config.pressure = None + # Progress is reported through the logger, so silence Sire's progress # bars. This also lets Sire run dynamics in longer blocks, since the # blocks only exist to update the bar. @@ -165,8 +172,8 @@ def _check_inputs(self): _logger.error(msg) raise ValueError(msg) - # GCMC in the NVT ensemble needs every replica to share the same box. - if self._config.gcmc and self._config.pressure is None: + # GCMC runs in the NVT ensemble, so every replica must share the same box. + if self._config.gcmc: space = self._system.space() pert_space = self._config.perturbed_system.space() vectors = self._box_vectors(space) @@ -177,10 +184,9 @@ def _check_inputs(self): ): msg = ( f"The periodic box of 'perturbed_system' ({pert_space}) does not " - f"match that of the 'system' ({space}). GCMC in the NVT ensemble " - "needs both end states to share the same box. Rescale the perturbed " - "system to the reference box, or set a pressure to run in the " - "osmotic ensemble." + f"match that of the 'system' ({space}). GCMC runs in the NVT " + "ensemble, so both end states must share the same box. Rescale " + "the perturbed system to the reference box." ) _logger.error(msg) raise ValueError(msg) @@ -1066,29 +1072,6 @@ def _check_gcmc(self): # Store the excess chemcical potential value. self._mu_ex = self._config.gcmc_excess_chemical_potential.value() - def _check_gcmc_bulk_moves(self): - """ - Warn when whole-box GCMC moves are used with a pressure set. This runs - after the restart check, which can change the bulk sampling probability. - """ - if not self._config.gcmc or self._config.pressure is None: - return - - if self._config.gcmc_selection is None: - _logger.warning( - "Every GCMC move samples the whole box when 'gcmc_selection' " - "is None. With a pressure set, the number of bulk waters can " - "drift. Set a 'gcmc_selection', or 'pressure=None' to run in " - "the NVT ensemble." - ) - elif self._config.gcmc_bulk_sampling_probability > 0.0: - _logger.warning( - "Bulk GCMC moves are used with a pressure set, so the number " - "of bulk waters can drift. Set " - "'gcmc_bulk_sampling_probability=0', or 'pressure=None' to " - "run in the NVT ensemble." - ) - def _set_terminal_groups(self): """ Validate the terminal flip options and detect the terminal ring groups, @@ -1241,7 +1224,6 @@ def _set_dynamics_kwargs(self): "lambda_schedule": self._config.lambda_schedule, "no_logger": True, "num_ghost_waters": self._config.gcmc_num_waters, - "pressure": self._config.pressure, "overwrite": self._config.overwrite, "radius": str(self._config.gcmc_radius), "reference": self._config.gcmc_selection, @@ -2407,31 +2389,6 @@ def _check_restart(self): return True, systems - def _inherit_bulk_sampling_probability(self, config): - """ - When the GCMC bulk sampling probability is "auto", keep the value of the - last run, so that the run stays in one ensemble. - - Parameters - ---------- - - config: dict - The current config dictionary, which is updated to match. - """ - last = _Config._unwrap(self._last_config.get("gcmc_bulk_sampling_probability")) - if last is None or _Config._is_auto(last): - return - if not _Config._is_auto(self._config._gcmc_bulk_sampling_probability): - return - - value = float(last) - self._config.gcmc_bulk_sampling_probability = value - config["gcmc_bulk_sampling_probability"] = value - if self._config.gcmc: - _logger.info( - f"Using 'gcmc_bulk_sampling_probability={value}' from the last run." - ) - @staticmethod def _compare_configs(config1, config2): """ @@ -2464,29 +2421,6 @@ def _compare_configs(config1, config2): if v1 == v2: continue - # Compare the resolved values, so that "auto" matches the - # explicit value it stands for. A changed pressure is reported - # by its own check instead. - if key == "gcmc_bulk_sampling_probability": - if (_Config._unwrap(config1.get("pressure")) or None) != ( - _Config._unwrap(config2.get("pressure")) or None - ): - continue - p1 = _Config._resolve_bulk_sampling_probability( - v1, config1.get("pressure") - ) - p2 = _Config._resolve_bulk_sampling_probability( - v2, config2.get("pressure") - ) - if not _isclose(p1, p2): - raise ValueError( - f"{key} has changed since the last run ({p1} vs {p2}). " - "This is not allowed when using the restart option. " - f"Set gcmc_bulk_sampling_probability={p1} to continue " - "the run." - ) - continue - # Custom lambda schedules are stored as a hexademical string of # serialised object. We need to deserialise them before comparison. if key == "lambda_schedule": @@ -2577,6 +2511,11 @@ def _compare_configs(config1, config2): ) if key == "softcore_form": msg += f" Set softcore_form='{v1}' to continue the run." + elif key == "pressure" and config2.get("gcmc") is True: + msg += ( + " GCMC simulations are run in the NVT ensemble, so a run " + "started with a pressure can't be continued." + ) raise ValueError(msg) def _verify_restart_config(self): @@ -2628,7 +2567,6 @@ def get_last_config(output_directory): "Cannot validate restart config without a config.yaml file." ) - self._inherit_bulk_sampling_probability(config) self._compare_configs(self._last_config, config) # Adaptive replica exchange derives each window's sample count from its diff --git a/tests/runner/test_config.py b/tests/runner/test_config.py index 27c3a55a..d9cbf551 100644 --- a/tests/runner/test_config.py +++ b/tests/runner/test_config.py @@ -1,4 +1,3 @@ -import pytest import tempfile import sire as sr @@ -236,105 +235,6 @@ def test_auto_softcore_form(): RunnerBase._compare_configs(old, new) -def test_auto_gcmc_bulk_sampling_probability(): - """ - Validate that the "auto" bulk sampling probability follows the pressure, - that an explicit value is never overridden, and that "auto" is kept when - the config is written out. - """ - config = Config() - assert config._gcmc_bulk_sampling_probability == "auto" - assert config.gcmc_bulk_sampling_probability == 0.0 - assert config.as_dict()["gcmc_bulk_sampling_probability"] == "auto" - - config.pressure = None - assert config.gcmc_bulk_sampling_probability == 0.1 - - config.gcmc_bulk_sampling_probability = 0.2 - config.pressure = "1 atm" - assert config.gcmc_bulk_sampling_probability == 0.2 - - config.gcmc_bulk_sampling_probability = "AUTO" - assert config.gcmc_bulk_sampling_probability == 0.0 - - with pytest.raises(ValueError): - config.gcmc_bulk_sampling_probability = "nan" - - -@pytest.mark.parametrize( - "pressure,last,new,expected", - [ - ("1 atm", "auto", "auto", 0.0), - ("1 atm", 0.0, "auto", 0.0), - ("1 atm", 0.1, "auto", 0.1), - (None, 0.1, "auto", 0.1), - ("1 atm", 0.1, 0.0, None), - ("1 atm", "auto", 0.1, None), - ], -) -def test_gcmc_bulk_sampling_probability_restart(pressure, last, new, expected): - """ - Validate that, on restart, "auto" keeps the bulk sampling probability of the - last run and that any other change is refused, for a last config read from - a config file and from a checkpoint, where it is stored as a Sire property. - An expected value of None means the restart is refused. - """ - from types import SimpleNamespace - - from somd2.runner._base import RunnerBase - - old = Config(pressure=pressure, gcmc_bulk_sampling_probability=last) - - # The config as stored in a checkpoint file. - system = sr.system.System() - system.set_property("config", old.as_dict(sire_compatible=True)) - checkpoint_config = dict(system.property("config")) - - for last_config, sire_compatible in ( - (old.as_dict(), False), - (checkpoint_config, True), - ): - runner = SimpleNamespace( - _config=Config(pressure=pressure, gcmc_bulk_sampling_probability=new), - _last_config=last_config, - ) - config = runner._config.as_dict(sire_compatible=sire_compatible) - - RunnerBase._inherit_bulk_sampling_probability(runner, config) - - if expected is None: - with pytest.raises(ValueError, match="gcmc_bulk_sampling_probability="): - RunnerBase._compare_configs(runner._last_config, config) - else: - RunnerBase._compare_configs(runner._last_config, config) - assert runner._config.gcmc_bulk_sampling_probability == expected - - -def test_gcmc_bulk_sampling_probability_restart_pressure_change(): - """ - Validate that a changed pressure on restart is reported as such, rather - than as a change to the resolved bulk sampling probability. - """ - from somd2.runner._base import RunnerBase - - old = Config(pressure=None, gcmc_bulk_sampling_probability=0.1) - new = Config(pressure="1 atm") - - # The config as stored in a checkpoint file. - system = sr.system.System() - system.set_property("config", old.as_dict(sire_compatible=True)) - checkpoint_config = dict(system.property("config")) - - for last_config, sire_compatible in ( - (old.as_dict(), False), - (checkpoint_config, True), - ): - with pytest.raises(ValueError, match="^pressure has changed"): - RunnerBase._compare_configs( - last_config, new.as_dict(sire_compatible=sire_compatible) - ) - - def test_restraints_input_forms(): """Validate that all supported restraint input forms are accepted.""" import os @@ -507,3 +407,37 @@ def test_help_text_scraping(): # must not be mistaken for the start of the next parameter. assert "applied to the atoms" in action.help assert "a list of sets" in action.help + + +def test_gcmc_runs_in_nvt(): + """ + Validate that GCMC simulations ignore the pressure, and that a GCMC run + started with a pressure can't be restarted, whether the last config is + read from a config file or from a checkpoint. + """ + import pytest + + from somd2.runner._base import RunnerBase + + with tempfile.TemporaryDirectory() as tmpdir: + for gcmc in (True, False): + runner = RunnerBase.__new__(RunnerBase) + runner._set_config(Config(output_directory=tmpdir, gcmc=gcmc)) + assert (runner._config.pressure is None) == gcmc + + old = Config(gcmc=True) + new = Config(gcmc=True, pressure=None) + + # The config as stored in a checkpoint file. + system = sr.system.System() + system.set_property("config", old.as_dict(sire_compatible=True)) + checkpoint_config = dict(system.property("config")) + + for last_config, sire_compatible in ( + (old.as_dict(), False), + (checkpoint_config, True), + ): + with pytest.raises(ValueError, match="run in the NVT ensemble"): + RunnerBase._compare_configs( + last_config, new.as_dict(sire_compatible=sire_compatible) + ) diff --git a/tests/runner/test_repex.py b/tests/runner/test_repex.py index cf44c276..8563e599 100644 --- a/tests/runner/test_repex.py +++ b/tests/runner/test_repex.py @@ -2917,14 +2917,14 @@ def expected_times(num_hot, num_cold, r): ("none", (50, 50, 50), False), ("none", (50.5, 50.5, 50.5), True), ("none", (40, 50, 62.5), True), - ("1 atm", (50.5, 50.5, 50.5), False), + ("1 atm", (50.5, 50.5, 50.5), True), ], ) def test_perturbed_system_box_gcmc(ethane_methanol, pressure, dimensions, raises): """ - Validate that a perturbed system with a different box is rejected for GCMC - in the NVT ensemble, including a box of the same volume but a different - shape, but allowed in the osmotic ensemble. + Validate that a perturbed system with a different box is rejected for GCMC, + which runs in the NVT ensemble, including a box of the same volume but a + different shape, and whether or not a pressure is set. """ import sire as sr