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
64 changes: 55 additions & 9 deletions src/somd2/config/_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,13 @@ class Config:
"log_level": [level.lower() for level in _logger._core.levels],
"softcore_form": ["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"]
_open_choices = ["lambda_schedule", "gcmc_bulk_sampling_probability"]

# A dictionary of nargs for the various options.
_nargs = {
Expand Down Expand Up @@ -161,7 +162,7 @@ def __init__(
gcmc_standard_volume="30.543 A^3",
gcmc_num_waters=20,
gcmc_radius="4 A",
gcmc_bulk_sampling_probability=0.1,
gcmc_bulk_sampling_probability="auto",
gcmc_tolerance=0.0,
use_dispersion_correction=False,
rest2_scale=1.0,
Expand Down Expand Up @@ -490,11 +491,14 @@ def __init__(
gcmc_radius: str
The radius of the GCMC sphere.

gcmc_bulk_sampling_probability: float
gcmc_bulk_sampling_probability: float, str
The probability of performing bulk GCMC moves, i.e. within the entire simulation
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'.)
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.)

gcmc_tolerance: float
The tolerance for the GCMC acceptance probability, i.e. the minimum probability
Expand Down Expand Up @@ -2233,16 +2237,58 @@ def gcmc_radius(self, gcmc_radius):

@property
def gcmc_bulk_sampling_probability(self):
return self._gcmc_bulk_sampling_probability
# 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)

@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")
if gcmc_bulk_sampling_probability < 0.0 or gcmc_bulk_sampling_probability > 1.0:
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 between 0.0 and 1.0"
)
Expand Down
74 changes: 74 additions & 0 deletions src/somd2/runner/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,8 @@ def __init__(self, system, config):
# Store the excess chemcical potential value.
self._mu_ex = self._config.gcmc_excess_chemical_potential.value()

self._check_gcmc_bulk_moves()

# Terminal flip specific validation and setup.
if self._config.terminal_flip_frequency is not None:
from math import isclose
Expand Down Expand Up @@ -2066,6 +2068,54 @@ def _check_restart(self):

return True, systems

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 _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):
"""
Expand Down Expand Up @@ -2125,6 +2175,29 @@ 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":
Expand Down Expand Up @@ -2263,6 +2336,7 @@ 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)

@staticmethod
Expand Down
100 changes: 100 additions & 0 deletions tests/runner/test_config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pytest
import tempfile

import sire as sr
Expand Down Expand Up @@ -256,3 +257,102 @@ 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_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)
)