diff --git a/CHANGELOG.md b/CHANGELOG.md index be09aff4..91f65f5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ Changelog * Fixed the regular runner reporting success when a lambda window failed, unless it was the last to finish. The other windows still run, then `Runner.run()` raises an error listing the failed windows and `somd2` exits with a non-zero status. The overall performance is now summed over all windows rather than taken from the last to finish [#285](https://github.com/OpenBioSim/somd2/pull/285). * Add a `torsion_window` option, `auto` by default, that changes the torsions and impropers of a perturbable molecule over only part of each stage of the lambda schedule when one of its angles becomes linear at one end state, e.g. for a C=C to C≡C perturbation. Their forces diverge as the angle's atoms become collinear, which crashed simulations at intermediate lambda. `auto` applies it when a non-zero torsion or improper passes through such an angle at the other end state. Simulations started before this option existed must be restarted with `torsion_window` set to `false` [#287](https://github.com/OpenBioSim/somd2/pull/287). * Runners now work on a copy of the config, so that changes they make, e.g. to the lambda schedule, don't carry over to other runners created from the same config [#287](https://github.com/OpenBioSim/somd2/pull/287). +* Default the GCMC region to a sphere around the perturbed atoms, with a radius and number of ghost waters chosen automatically, via new `auto` defaults for `gcmc_selection`, `gcmc_radius` and `gcmc_num_waters`, and a `gcmc_radius_padding` option. GCMC within the entire simulation box is still available with `gcmc_selection=None` [#291](https://github.com/OpenBioSim/somd2/pull/291). [2026.2.0](https://github.com/openbiosim/somd2/compare/2026.1.0...2026.2.0) - Sep 2026 -------------------------------------------------------------------------------------- diff --git a/README.md b/README.md index e3872552..fa28ac45 100644 --- a/README.md +++ b/README.md @@ -636,11 +636,23 @@ in which case there must be one value for each λ window. SOMD2 also supports grand canonical Monte Carlo (GCMC) water sampling using the [loch](https://github.com/OpenBioSim/loch) package. This can be enabled -using the `--gcmc` option. To define a GCMC region, use the `--gcmc-selection` -option, which should be a `Sire` selection string that specifies the atoms -defining the centre of geometry for the GCMC region. The radius of the GCMC -sphere can be controlled using the `--gcmc-radius` option. To see all GCMC -related options, run: +using the `--gcmc` option. By default, GCMC moves are attempted within a sphere +centred on the perturbed atoms, i.e. atoms whose element changes between the +end states, including ghost atoms, and heavy atoms whose Lennard-Jones +parameters change, or the whole ligand for ABFE. The +radius covers these atoms in both end states, plus `--gcmc-radius-padding` +(5 Å by default), and enough ghost waters are added to fill the free volume of +the sphere, i.e. its volume less the waters and heavy atoms already inside, +other than atoms that vanish in either end state, plus a margin for +fluctuations. The resolved selection, radius and number of waters are logged +and written to the config file. + +To define a different GCMC region, use the `--gcmc-selection` option, which +should be a `Sire` selection string that specifies the atoms defining the centre +of geometry for the GCMC region. The radius of the GCMC sphere can be set with +the `--gcmc-radius` option, and the number of ghost waters with +`--gcmc-num-waters`. To attempt moves within the entire simulation box, use +`--gcmc-selection none`. To see all GCMC related options, run: ``` somd2 --help | grep -A2 ' --gcmc' diff --git a/src/somd2/_utils/_gcmc.py b/src/somd2/_utils/_gcmc.py new file mode 100644 index 00000000..cc229b0e --- /dev/null +++ b/src/somd2/_utils/_gcmc.py @@ -0,0 +1,361 @@ +###################################################################### +# SOMD2: GPU accelerated alchemical free-energy engine. +# +# Copyright: 2023-2026 +# +# Authors: The OpenBioSim Team +# +# SOMD2 is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# SOMD2 is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with SOMD2. If not, see . +##################################################################### + +__all__ = ["auto_selection", "selection_geometry", "selection_sites", "ghost_waters"] + +# The volume of a heavy atom and its hydrogens at protein density, in waters. +_HEAVY_ATOM_WATERS = 0.58 + +# The margin of ghost waters for fluctuations, as a fraction of the waters that +# fill the empty sphere, and its minimum. +_GHOST_WATER_MARGIN = 0.1 +_MIN_GHOST_WATER_MARGIN = 10 + +# Selected atoms closer than this, in Angstrom, belong to the same site. +_SITE_DISTANCE = 4.0 + + +def perturbed_atoms(mol): + """ + Return the indices of the atoms of a perturbable molecule that change + between the end states: atoms whose element changes, including ghost + atoms, and heavy atoms whose Lennard-Jones parameters change. Hydrogens + whose Lennard-Jones parameters change are left out, since this is often + only a change in atom type caused by changes elsewhere in the molecule. If + no atoms change, then all atoms are returned. + + Parameters + ---------- + + mol: sire.mol.Molecule + The perturbable molecule. + + Returns + ------- + + indices: list of int + The indices of the perturbed atoms within the molecule. + """ + + def changes(atom): + element = atom.property("element0").symbol() + if element != atom.property("element1").symbol(): + return True + return element != "H" and atom.property("LJ0") != atom.property("LJ1") + + indices = [i for i, atom in enumerate(mol.atoms()) if changes(atom)] + return indices or list(range(mol.num_atoms())) + + +def vanishing_atoms(mol): + """ + Return the indices of the atoms of a perturbable molecule that vanish in + either end state, i.e. ghost atoms, or atoms with no charge and no + Lennard-Jones interactions, as for a decoupled ligand. + + Parameters + ---------- + + mol: sire.mol.Molecule + The perturbable molecule. + + Returns + ------- + + indices: list of int + The indices of the vanishing atoms within the molecule. + """ + + def decoupled(atom, end): + return ( + atom.property(f"charge{end}").value() == 0 + and atom.property(f"LJ{end}").epsilon().value() == 0 + ) + + return [ + i + for i, atom in enumerate(mol.atoms()) + if "Xx" + in (atom.property("element0").symbol(), atom.property("element1").symbol()) + or decoupled(atom, 0) + or decoupled(atom, 1) + ] + + +def auto_selection(system): + """ + Return a selection string for the perturbed atoms of the perturbable + molecules in the system. Perturbable waters and single-atom ions, e.g. + co-alchemical ions, are left out unless they are the only perturbable + molecules. Molecules are selected by index, rather than number, so that the + selection also works for the system reloaded from file. + + Parameters + ---------- + + system: sire.system.System + The system containing the perturbable molecules. + + Returns + ------- + + selection: str + The selection string. + """ + perturbable = system.molecules("property is_perturbable") + try: + solutes = system.molecules("property is_perturbable and not water") + except KeyError: + solutes = [] + solutes = [mol for mol in solutes if mol.num_atoms() > 1] or perturbable + + molecules = system.molecules() + parts = [] + for mol in solutes: + indices = ",".join(str(i) for i in perturbed_atoms(mol)) + parts.append(f"(molidx {molecules.find(mol)} and atomidx {indices})") + return " or ".join(parts) + + +def _space(system): + """ + Return the periodic space of the system, or None if it isn't periodic. + """ + try: + space = system.property("space") + except Exception: + return None + return space if space.is_periodic() else None + + +def _box_matrix(space): + """ + Return the box vectors of a periodic space as the columns of a matrix. + """ + import numpy as _np + + if hasattr(space, "vector0"): + vectors = [space.vector0(), space.vector1(), space.vector2()] + return _np.array( + [[v.x().value(), v.y().value(), v.z().value()] for v in vectors] + ).T + + dimensions = space.dimensions() + return _np.diag( + [dimensions.x().value(), dimensions.y().value(), dimensions.z().value()] + ) + + +def _minimum_image(delta, space): + """ + Return the minimum image of each displacement vector in a periodic space. + """ + import itertools as _itertools + + import numpy as _np + + if space is None: + return delta + + box = _box_matrix(space) + fractional = _np.linalg.solve(box, delta.T) + fractional -= _np.round(fractional) + + # Rounding the fractional coordinates isn't the minimum image for every + # triclinic box, so take the nearest of the neighbouring images. + shifts = _np.array(list(_itertools.product((-1, 0, 1), repeat=3))).T + images = box @ (fractional[:, None, :] + shifts[:, :, None]).reshape(3, -1) + images = images.reshape(3, shifts.shape[1], -1) + nearest = _np.linalg.norm(images, axis=0).argmin(axis=0) + return images[:, nearest, _np.arange(delta.shape[0])].T + + +def _positions(system, selection, end): + """ + Return the positions of the selected atoms in an end state, in the order + of the atoms in the system. Molecules without end-state coordinates use + their current coordinates. + """ + import numpy as _np + from sire.io import get_coords_array as _get_coords_array + + atoms = system[selection].atoms() + indices = _np.array(system.atoms().find(atoms)) + xyz = _np.empty((len(indices), 3)) + + name = f"coordinates{end}" + for mol in atoms.molecules(): + offset = system.atoms().find(mol.atoms()[0]) + mask = (indices >= offset) & (indices < offset + mol.num_atoms()) + prop = name if mol.has_property(name) else "coordinates" + coords = _np.asarray(_get_coords_array(mol, map={"coordinates": prop})) + xyz[mask] = coords[indices[mask] - offset] + + return xyz + + +def selection_geometry(system, selection): + """ + Return the centre of geometry of the selected atoms in the reference state, + and their largest distance from their own centre of geometry in either end + state, in Angstrom. The GCMC sampler re-centres the sphere on the current + positions, so each end state is measured from its own centre. Positions are + imaged next to each other first, so that atoms on either side of a periodic + boundary are handled correctly. + + Parameters + ---------- + + system: sire.system.System + The system. + + selection: str + A selection string for the atoms. + + Returns + ------- + + centre: numpy.ndarray + The centre of geometry in the reference state, in Angstrom. + + extent: float + The extent of the selected atoms in Angstrom. + """ + import numpy as _np + + space = _space(system) + + centre = None + extent = 0.0 + for end in (0, 1): + xyz = _positions(system, selection, end) + xyz = xyz[0] + _minimum_image(xyz - xyz[0], space) + cog = xyz.mean(axis=0) + if centre is None: + centre = cog + extent = max(extent, float(_np.linalg.norm(xyz - cog, axis=1).max())) + + return centre, extent + + +def selection_sites(system, selection): + """ + Return the centres of geometry of the separate sites of the selected atoms + in the reference state, where atoms closer than 4 Angstrom, directly or + through other selected atoms, belong to the same site. + + Parameters + ---------- + + system: sire.system.System + The system. + + selection: str + A selection string for the atoms. + + Returns + ------- + + centres: list of numpy.ndarray + The centre of geometry of each site, in Angstrom. + """ + import numpy as _np + + xyz = _positions(system, selection, 0) + xyz = xyz[0] + _minimum_image(xyz - xyz[0], _space(system)) + close = _np.linalg.norm(xyz[:, None] - xyz[None], axis=2) < _SITE_DISTANCE + + site = -_np.ones(len(xyz), dtype=int) + centres = [] + for start in range(len(xyz)): + if site[start] >= 0: + continue + site[start] = len(centres) + stack = [start] + while stack: + i = stack.pop() + for j in _np.flatnonzero(close[i] & (site < 0)): + site[j] = site[start] + stack.append(j) + centres.append(xyz[site == site[start]].mean(axis=0)) + + return centres + + +def ghost_waters(system, centre, radius, standard_volume): + """ + Return the number of ghost waters needed to fill the free volume of a GCMC + sphere: the waters that would fill the empty sphere, less + the waters already inside and the volume of the heavy atoms of the + environment. Atoms of perturbable molecules that vanish in either end + state don't count towards the occupied volume. A margin is added for + fluctuations. + + Parameters + ---------- + + system: sire.system.System + The system. + + centre: numpy.ndarray + The centre of the sphere in Angstrom. + + radius: float + The radius of the sphere in Angstrom. + + standard_volume: float + The volume of a water molecule in bulk water, in cubic Angstrom. + + Returns + ------- + + num_waters: int + The number of ghost waters. + """ + import math as _math + + import numpy as _np + from sire.io import get_coords_array as _get_coords_array + + space = _space(system) + xyz = _np.asarray(_get_coords_array(system)) + distances = _np.linalg.norm(_minimum_image(xyz - centre, space), axis=1) + inside = distances < radius + + def indices(selection): + try: + return _np.array(system.atoms().find(system[selection].atoms()), dtype=int) + except KeyError: + return _np.array([], dtype=int) + + vanishing = [] + for mol in system.molecules("property is_perturbable"): + offset = system.atoms().find(mol.atoms()[0]) + vanishing.extend(offset + i for i in vanishing_atoms(mol)) + + heavy = _np.setdiff1d(indices("(not water) and (not element H)"), vanishing) + occupied = int(inside[heavy].sum()) + waters = int(inside[indices("water and element O")].sum()) + + empty = 4.0 / 3.0 * _math.pi * radius**3 / standard_volume + free = max(_math.ceil(empty - _HEAVY_ATOM_WATERS * occupied - waters), 0) + margin = max(_math.ceil(_GHOST_WATER_MARGIN * empty), _MIN_GHOST_WATER_MARGIN) + return free + margin diff --git a/src/somd2/config/_config.py b/src/somd2/config/_config.py index e48e9ef2..9e555cc0 100644 --- a/src/somd2/config/_config.py +++ b/src/somd2/config/_config.py @@ -131,6 +131,7 @@ class Config: "restraint_search_frequency", "gcmc_batch_size", "gcmc_num_attempts", + "gcmc_radius_padding", "torsion_window", ] ) @@ -218,11 +219,12 @@ def __init__( terminal_flip_max_mobile_atoms=None, gcmc=False, gcmc_frequency=None, - gcmc_selection=None, + gcmc_selection="auto", gcmc_excess_chemical_potential="-6.09 kcal/mol", gcmc_standard_volume="30.543 A^3", - gcmc_num_waters=20, - gcmc_radius="4 A", + gcmc_num_waters="auto", + gcmc_radius="auto", + gcmc_radius_padding="5 A", gcmc_bulk_sampling_probability=0.1, gcmc_tolerance=0.0, gcmc_batch_size=1000, @@ -626,9 +628,12 @@ def __init__( same as 'energy_frequency'. This must be a multiple of 'energy_frequency'. gcmc_selection: str - A sire sslection string specifying the atoms that define the centre of geometry - of the GCMC sphere. If None, then GCMC moves will be attempted within the entire - simulation volume. + A sire selection string specifying the atoms that define the centre of geometry + of the GCMC sphere. If 'auto' (the default), then the perturbed atoms are used, + i.e. atoms whose element changes between the end states, including ghost atoms, + and heavy atoms whose Lennard-Jones parameters change, or every atom of a + perturbable molecule in which none do. If None, then + GCMC moves will be attempted within the entire simulation volume. gcmc_excess_chemical_potential: str The excess chemical potential of water in kcal/mol. The default value is calibrated @@ -641,10 +646,22 @@ def __init__( gcmc_num_waters: int The additional number of ghost water molecules to add to the system. These are - used as placeholders for GCMC insertion moves. + used as placeholders for GCMC insertion moves. If 'auto' (the default), then + this is the number of waters that fill the free volume of the GCMC sphere, i.e. + the sphere, given 'gcmc_standard_volume', less the waters and heavy atoms already + inside, other than atoms that vanish in either end state, plus a margin for + fluctuations. When GCMC moves are attempted within the entire simulation volume, + then this is 20. gcmc_radius: str - The radius of the GCMC sphere. + The radius of the GCMC sphere. If 'auto' (the default), then this is the largest + distance of the 'gcmc_selection' atoms from their centre of geometry, in either + end state, plus 'gcmc_radius_padding'. This is unused when GCMC moves are + attempted within the entire simulation volume. + + gcmc_radius_padding: str + The distance added to the extent of the 'gcmc_selection' atoms when + 'gcmc_radius' is 'auto'. gcmc_bulk_sampling_probability: float The probability of performing bulk GCMC moves, i.e. within the entire simulation @@ -901,6 +918,7 @@ def __init__( self.gcmc_standard_volume = gcmc_standard_volume self.gcmc_num_waters = gcmc_num_waters self.gcmc_radius = gcmc_radius + self.gcmc_radius_padding = gcmc_radius_padding self.gcmc_bulk_sampling_probability = gcmc_bulk_sampling_probability self.gcmc_tolerance = gcmc_tolerance self.gcmc_batch_size = gcmc_batch_size @@ -2622,6 +2640,11 @@ def gcmc_selection(self, gcmc_selection): if gcmc_selection is not None: if not isinstance(gcmc_selection, str): raise TypeError("'gcmc_selection' must be of type 'str'") + # Allow the entire simulation volume to be chosen from the command line. + if gcmc_selection.strip().lower() == "none": + gcmc_selection = None + elif gcmc_selection.strip().lower() == "auto": + gcmc_selection = "auto" self._gcmc_selection = gcmc_selection @property @@ -2678,6 +2701,12 @@ def gcmc_num_waters(self): @gcmc_num_waters.setter def gcmc_num_waters(self, gcmc_num_waters): + if ( + isinstance(gcmc_num_waters, str) + and gcmc_num_waters.strip().lower() == "auto" + ): + self._gcmc_num_waters = "auto" + return if gcmc_num_waters is not None: if not isinstance(gcmc_num_waters, int): try: @@ -2698,6 +2727,10 @@ def gcmc_radius(self, gcmc_radius): if not isinstance(gcmc_radius, str): raise TypeError("'gcmc_radius' must be of type 'str'") + if gcmc_radius.strip().lower() == "auto": + self._gcmc_radius = "auto" + return + from sire.units import angstrom try: @@ -2712,6 +2745,33 @@ def gcmc_radius(self, gcmc_radius): self._gcmc_radius = gcmc_r + @property + def gcmc_radius_padding(self): + return self._gcmc_radius_padding + + @gcmc_radius_padding.setter + def gcmc_radius_padding(self, gcmc_radius_padding): + if not isinstance(gcmc_radius_padding, str): + raise TypeError("'gcmc_radius_padding' must be of type 'str'") + + from sire.units import angstrom + + try: + padding = _sr.u(gcmc_radius_padding) + except Exception: + raise ValueError( + "Unable to parse 'gcmc_radius_padding' as a Sire GeneralUnit: " + f"{gcmc_radius_padding}" + ) + + if not padding.has_same_units(angstrom): + raise ValueError("'gcmc_radius_padding' units are invalid.") + + if padding.value() <= 0: + raise ValueError("'gcmc_radius_padding' must be greater than 0") + + self._gcmc_radius_padding = padding + @property def gcmc_bulk_sampling_probability(self): return self._gcmc_bulk_sampling_probability diff --git a/src/somd2/runner/_base.py b/src/somd2/runner/_base.py index 597e6b38..d2159434 100644 --- a/src/somd2/runner/_base.py +++ b/src/somd2/runner/_base.py @@ -397,11 +397,6 @@ def _prepare_system(self): if value is not None: self._config._extra_args[option] = value - # GCMC LRC map options. - if self._config.gcmc and self._config.use_dispersion_correction: - self._config._extra_args["use_gcmc_lrc"] = True - self._config._extra_args["num_gcmc_waters"] = self._config.gcmc_num_waters - # Auto-generate Morse restraints for ring-breaking perturbations with no # user-supplied Morse restraints. This is done before any modification of # the bonded terms, and before the reference system is stored and the @@ -1074,6 +1069,92 @@ def _prepare_output_and_restart(self): self._config.checkpoint_frequency / self._config.energy_frequency ) + def _set_gcmc_region(self): + """ + Validate the GCMC selection and resolve the 'auto' GCMC options: the + selection of perturbed atoms, a radius that covers the selection, and + enough ghost waters to fill the free volume of the GCMC sphere. These + are resolved from the input system, so a restart resolves them to the + same values. + """ + from .._utils._gcmc import ( + auto_selection, + ghost_waters, + selection_geometry, + selection_sites, + ) + + is_auto = self._config.gcmc_selection == "auto" + if is_auto: + try: + self._config.gcmc_selection = auto_selection(self._system) + except Exception as e: + msg = ( + f"Unable to select the perturbed atoms for the GCMC sphere: {e}. " + "Set 'gcmc_selection' explicitly." + ) + _logger.error(msg) + raise ValueError(msg) + + selection = self._config.gcmc_selection + + # The radius isn't used when sampling the entire simulation box. + if selection is None: + if self._config.gcmc_num_waters == "auto": + self._config.gcmc_num_waters = 20 + _logger.info( + "GCMC moves will be attempted within the entire simulation box " + f"with {self._config.gcmc_num_waters} ghost waters." + ) + return + + try: + _sr.mol.selection_to_atoms(self._system, selection) + except Exception: + msg = "Invalid 'gcmc_selection' value." + _logger.error(msg) + raise ValueError(msg) + + try: + centre, extent = selection_geometry(self._system, selection) + + if isinstance(self._config.gcmc_radius, str): + radius = extent + self._config.gcmc_radius_padding.to("A") + self._config.gcmc_radius = f"{radius:.3f} A" + + if self._config.gcmc_num_waters == "auto": + self._config.gcmc_num_waters = ghost_waters( + self._system, + centre, + self._config.gcmc_radius.to("A"), + self._config.gcmc_standard_volume.value(), + ) + sites = selection_sites(self._system, selection) if is_auto else [] + except Exception as e: + msg = f"Unable to set up the GCMC sphere for '{selection}': {e}" + _logger.error(msg) + raise ValueError(msg) + + if len(sites) > 1: + import itertools as _itertools + + import numpy as _np + + separation = max( + _np.linalg.norm(a - b) for a, b in _itertools.combinations(sites, 2) + ) + _logger.warning( + f"The perturbed atoms form {len(sites)} separate sites, up to " + f"{separation:.1f} Å apart, so the GCMC sphere covers all of them " + f"with a radius of {self._config.gcmc_radius}. Set 'gcmc_selection' " + "to restrict it to one site." + ) + + _logger.info( + f"GCMC sphere of radius {self._config.gcmc_radius} centred on " + f"'{selection}', with {self._config.gcmc_num_waters} ghost waters." + ) + def _check_gcmc(self): """ Validate the GCMC options, if GCMC is used. @@ -1164,20 +1245,18 @@ def _check_gcmc(self): _logger.error(msg) raise ValueError(msg) - # Make sure the selection is valid. - if self._config.gcmc_selection is not None: - try: - _sr.mol.selection_to_atoms( - self._system, self._config.gcmc_selection - ) - except: - msg = "Invalid 'gcmc_selection' value." - _logger.error(msg) - raise ValueError(msg) - # Store the excess chemcical potential value. self._mu_ex = self._config.gcmc_excess_chemical_potential.value() + self._set_gcmc_region() + + # GCMC LRC map options. + if self._config.use_dispersion_correction: + self._config._extra_args["use_gcmc_lrc"] = True + self._config._extra_args["num_gcmc_waters"] = ( + self._config.gcmc_num_waters + ) + def _set_terminal_groups(self): """ Validate the terminal flip options and detect the terminal ring groups, @@ -1331,7 +1410,6 @@ def _set_dynamics_kwargs(self): "no_logger": True, "num_ghost_waters": self._config.gcmc_num_waters, "overwrite": self._config.overwrite, - "radius": str(self._config.gcmc_radius), "reference": self._config.gcmc_selection, "restart": self._is_restart, "softcore_form": self._config.softcore_form, @@ -1342,6 +1420,9 @@ def _set_dynamics_kwargs(self): "batch_size": self._config.gcmc_batch_size, "num_attempts": self._config.gcmc_num_attempts, } + # The radius is left unresolved when sampling the entire simulation box. + if not isinstance(self._config.gcmc_radius, str): + self._gcmc_kwargs["radius"] = str(self._config.gcmc_radius) if self._config.platform == "opencl": self._gcmc_kwargs["opencl_platform_index"] = ( self._config.opencl_platform_index @@ -2487,7 +2568,8 @@ def _check_restart(self): pass # Remove the additional GCMC waters from the end of the system. - for mol in system.molecules()[-self._config.gcmc_num_waters :]: + num_ghosts = self._config.gcmc_num_waters + for mol in system.molecules()[-num_ghosts:] if num_ghosts else []: _logger.debug( f"Removing GCMC water molecule {mol.number()} for {_lam_sym}={self._lambda_values[i]:.5f}" ) @@ -2519,7 +2601,11 @@ def _compare_configs(config1, config2): ) allowed_diffs = _Config._restart_allowed_diffs + no_gcmc = not config1.get("gcmc") and not config2.get("gcmc") for key in config1.keys(): + # The GCMC options are unused without GCMC, and their defaults have changed. + if no_gcmc and key.startswith("gcmc_"): + continue if key not in allowed_diffs: # Extract the config values. v1 = config1[key] diff --git a/tests/_utils/test_gcmc.py b/tests/_utils/test_gcmc.py new file mode 100644 index 00000000..6f7bf87e --- /dev/null +++ b/tests/_utils/test_gcmc.py @@ -0,0 +1,229 @@ +import pytest +import sire as sr + +from somd2._utils._gcmc import ( + _minimum_image, + _positions, + auto_selection, + ghost_waters, + perturbed_atoms, + selection_geometry, + selection_sites, + vanishing_atoms, +) + + +def test_perturbed_atoms(ethane_methanol): + """ + Make sure that atoms whose element changes, and heavy atoms whose LJ + parameters change, are perturbed, but not hydrogens whose LJ parameters + change. + """ + mol = ethane_methanol.molecules("property is_perturbable")[0] + indices = perturbed_atoms(mol) + + hydrogens = [] + for i, atom in enumerate(mol.atoms()): + element0 = atom.property("element0").symbol() + element1 = atom.property("element1").symbol() + lj_changes = atom.property("LJ0") != atom.property("LJ1") + changed = element0 != element1 or (element0 != "H" and lj_changes) + assert (i in indices) == changed + if element0 == element1 == "H" and lj_changes: + hydrogens.append(i) + + # Some hydrogens change LJ parameters without being perturbed. + assert hydrogens + assert 0 < len(indices) < mol.num_atoms() + + +def test_perturbed_atoms_decoupled(abfe_charge_change_mols): + """ + Make sure that every heavy atom of a decoupled ligand is perturbed. + """ + mol = abfe_charge_change_mols.molecules("property is_perturbable")[0] + heavy = [ + i + for i, atom in enumerate(mol.atoms()) + if atom.property("element0").symbol() != "H" + ] + assert perturbed_atoms(mol) == heavy + + +def test_auto_selection_reloaded(ethane_methanol, tmp_path): + """ + Make sure that the selection picks the same atoms from the system reloaded + from file, as the viewer does, which has new molecule numbers. + """ + selection = auto_selection(ethane_methanol) + indices = ethane_methanol.atoms().find(ethane_methanol[selection].atoms()) + + mol = ethane_methanol.molecules("property is_perturbable")[0] + offset = ethane_methanol.atoms().find(mol.atoms()[0]) + assert indices == [offset + i for i in perturbed_atoms(mol)] + + reference = sr.morph.extract_reference(ethane_methanol) + files = sr.save(reference, str(tmp_path / "system"), format=["prm7", "rst7"]) + reloaded = sr.load(files) + assert reloaded.atoms().find(reloaded[selection].atoms()) == indices + + +def test_auto_selection_skips_perturbable_waters(ethane_methanol): + """ + Make sure that perturbable waters and single-atom ions, e.g. co-alchemical + ions, don't move the GCMC sphere away from the perturbable solute. + """ + water = ethane_methanol["water"].molecules()[0] + system = ethane_methanol.clone() + system.update(water.edit().set_property("is_perturbable", True).commit()) + + assert auto_selection(system) == auto_selection(ethane_methanol) + + # A single-atom molecule, standing in for a perturbable ion. + ion = water.edit().remove(sr.legacy.Mol.AtomIdx(2)).remove(sr.legacy.Mol.AtomIdx(1)) + ion = ion.commit().edit().renumber().set_property("is_perturbable", True).commit() + system = ethane_methanol.clone() + system.add(ion) + + assert auto_selection(system) == auto_selection(ethane_methanol) + + +def test_vanishing_atoms(ethane_methanol, abfe_charge_change_mols): + """ + Make sure that ghost atoms vanish, as do the atoms of a decoupled ligand. + """ + mol = ethane_methanol.molecules("property is_perturbable")[0] + ghosts = [ + i + for i, atom in enumerate(mol.atoms()) + if "Xx" + in (atom.property("element0").symbol(), atom.property("element1").symbol()) + ] + assert ghosts + assert vanishing_atoms(mol) == ghosts + + mol = abfe_charge_change_mols.molecules("property is_perturbable")[0] + assert vanishing_atoms(mol) == list(range(mol.num_atoms())) + + +def test_selection_geometry(ethane_methanol): + """ + Make sure the extent covers the selected atoms in both end states. + """ + selection = auto_selection(ethane_methanol) + centre, extent = selection_geometry(ethane_methanol, selection) + assert 0 < extent < 5 + assert centre.shape == (3,) + + # A single atom has no extent. + _, extent = selection_geometry(ethane_methanol, "molidx 0 and atomidx 1") + assert extent == pytest.approx(0) + + +def test_selection_geometry_periodic(ethane_methanol): + """ + Make sure that a molecule split across a periodic boundary has the same + centre and extent as when it is whole. + """ + import numpy as np + + selection = auto_selection(ethane_methanol) + centre, extent = selection_geometry(ethane_methanol, selection) + + # Move one atom of the molecule by a box vector in both end states. + box = ethane_methanol.property("space") + shift = sr.maths.Vector(box.dimensions().x().value(), 0, 0) + mol = ethane_methanol.molecules("property is_perturbable")[0] + cursor = mol.cursor() + for name in ("coordinates0", "coordinates1"): + cursor.atom(0)[name] = cursor.atom(0)[name] + shift + system = ethane_methanol.clone() + system.update(cursor.commit()) + + # Without imaging, the molecule now spans the box. + raw = _positions(system, selection, 0) + assert np.ptp(raw[:, 0]) > box.dimensions().x().value() / 2 + + split_centre, split_extent = selection_geometry(system, selection) + assert split_extent == pytest.approx(extent) + + # The centres are periodic images of each other. + delta = _minimum_image(np.array([split_centre - centre]), box) + assert np.linalg.norm(delta) == pytest.approx(0, abs=1e-4) + + +def test_minimum_image_distances(ethane_methanol): + """ + Make sure distances use the nearest periodic image. + """ + import itertools + + import numpy as np + + space = ethane_methanol.property("space") + d = space.dimensions() + box = np.diag([d.x().value(), d.y().value(), d.z().value()]) + + rng = np.random.default_rng(1) + points = rng.uniform(-2 * box.max(), 2 * box.max(), (50, 3)) + centre = np.array([1.0, -2.0, 3.0]) + + expected = [ + min( + np.linalg.norm(p - centre + box @ np.array(k)) + for k in itertools.product(range(-3, 4), repeat=3) + ) + for p in points + ] + images = _minimum_image(points - centre, space) + assert np.allclose(np.linalg.norm(images, axis=1), expected) + + # Each image differs from its displacement by a whole box vector. + shifts = np.linalg.solve(box, (images - (points - centre)).T) + assert np.allclose(shifts, np.round(shifts)) + + +def test_selection_sites(ethane_methanol): + """ + Make sure that nearby atoms form one site, and distant atoms separate sites. + """ + import numpy as np + + selection = auto_selection(ethane_methanol) + assert len(selection_sites(ethane_methanol, selection)) == 1 + + # Add the oxygen of a water far from the perturbable molecule. + centre, _ = selection_geometry(ethane_methanol, selection) + space = ethane_methanol.property("space") + waters = ethane_methanol["water and element O"].atoms() + xyz = _positions(ethane_methanol, "water and element O", 0) + distances = np.linalg.norm(_minimum_image(xyz - centre, space), axis=1) + far = waters[int(np.argmax(distances > 10))] + molidx = ethane_methanol.molecules().find(far.molecule()) + two = f"({selection}) or (molidx {molidx} and atomidx {far.index().value()})" + + sites = selection_sites(ethane_methanol, two) + assert len(sites) == 2 + separation = _minimum_image(np.array([sites[0] - sites[1]]), space) + assert np.linalg.norm(separation) > 10 + + +def test_ghost_waters(ethane_methanol): + """ + Make sure the ghost waters cover the free volume of the sphere, which is + small in water, plus a margin. + """ + selection = auto_selection(ethane_methanol) + centre, extent = selection_geometry(ethane_methanol, selection) + + volume = 30.543 + small = ghost_waters(ethane_methanol, centre, extent + 5, volume) + large = ghost_waters(ethane_methanol, centre, extent + 10, volume) + assert 10 <= small < large + + # Far fewer than the waters that fill the empty sphere. + full = 4 / 3 * 3.14159 * (extent + 10) ** 3 / volume + assert large < full / 2 + + # A larger water model fills the sphere with fewer waters. + assert ghost_waters(ethane_methanol, centre, extent + 10, 2 * volume) < large diff --git a/tests/runner/test_config.py b/tests/runner/test_config.py index 7cd4851d..64806e5e 100644 --- a/tests/runner/test_config.py +++ b/tests/runner/test_config.py @@ -444,3 +444,51 @@ def test_gcmc_runs_in_nvt(): RunnerBase._compare_configs( last_config, new.as_dict(sire_compatible=sire_compatible) ) + + +def test_gcmc_region_options(): + """ + Validate the GCMC region options, and that runs without GCMC can be + restarted although the defaults of these options have changed. + """ + import pytest + + from somd2.runner._base import RunnerBase + + config = Config() + assert config.gcmc_selection == "auto" + assert config.gcmc_radius == "auto" + assert config.gcmc_num_waters == "auto" + assert config.gcmc_radius_padding == sr.u("5 A") + + config.gcmc_selection = "None" + assert config.gcmc_selection is None + config.gcmc_selection = "AUTO" + assert config.gcmc_selection == "auto" + config.gcmc_radius = "Auto" + assert config.gcmc_radius == "auto" + config.gcmc_num_waters = "12" + assert config.gcmc_num_waters == 12 + + for padding in ("-1 A", "0 A", "1 ps"): + with pytest.raises(ValueError): + config.gcmc_radius_padding = padding + + old = Config(gcmc_selection=None, gcmc_radius="4 A", gcmc_num_waters=20) + RunnerBase._compare_configs(old.as_dict(), Config().as_dict()) + + # The padding is reflected in the resolved radius, so it can change on restart. + old = Config(gcmc=True, pressure=None, gcmc_radius="8 A", gcmc_radius_padding="3 A") + new = Config(gcmc=True, pressure=None, gcmc_radius="8 A") + RunnerBase._compare_configs(old.as_dict(), new.as_dict()) + + old = Config( + gcmc=True, + pressure=None, + gcmc_selection=None, + gcmc_radius="4 A", + gcmc_num_waters=20, + ) + new = Config(gcmc=True, pressure=None, gcmc_radius="4 A", gcmc_num_waters=20) + with pytest.raises(ValueError): + RunnerBase._compare_configs(old.as_dict(), new.as_dict()) diff --git a/tests/runner/test_gcmc.py b/tests/runner/test_gcmc.py index 2bada83e..5577aa47 100644 --- a/tests/runner/test_gcmc.py +++ b/tests/runner/test_gcmc.py @@ -38,6 +38,7 @@ def test_runner_gcmc_without_a_selection(ethane_methanol): max_threads=1, num_lambda=2, gcmc=True, + gcmc_selection=None, gcmc_frequency="4fs", ) @@ -173,3 +174,57 @@ def test_runner_gcmc_runtime_remainder(ethane_methanol): # remainder, for each window. log = (Path(tmpdir) / config.log_file).read_text() assert log.count("Performing GCMC move at") == 10 + + +@pytest.mark.skipif(not has_cuda, reason="CUDA not available.") +def test_runner_gcmc_auto_region(ethane_methanol): + """ + Validate that the default GCMC region is a sphere around the perturbed atoms, + and that the resolved options are written to the config file. + """ + pytest.importorskip("loch") + + from somd2._utils._gcmc import auto_selection, ghost_waters, selection_geometry + + with tempfile.TemporaryDirectory() as tmpdir: + config = Config( + runtime="8fs", + output_directory=tmpdir, + energy_frequency="4fs", + checkpoint_frequency="4fs", + frame_frequency="4fs", + platform="cuda", + max_threads=1, + num_lambda=2, + gcmc=True, + gcmc_frequency="4fs", + ) + + runner = Runner(ethane_methanol, config) + + selection = auto_selection(ethane_methanol) + centre, extent = selection_geometry(ethane_methanol, selection) + resolved = runner._config + assert resolved.gcmc_selection == selection + assert resolved.gcmc_radius.to("A") == pytest.approx(extent + 5.0, abs=1e-3) + volume = resolved.gcmc_standard_volume.value() + assert resolved.gcmc_num_waters == ghost_waters( + ethane_methanol, centre, resolved.gcmc_radius.to("A"), volume + ) + + written = Config.from_yaml(str(Path(tmpdir) / "config.yaml")) + assert written.gcmc_selection == selection + assert written.gcmc_radius == resolved.gcmc_radius + assert written.gcmc_num_waters == resolved.gcmc_num_waters + + # An explicit radius is kept, and the ghost waters are sized for it. + with tempfile.TemporaryDirectory() as tmpdir: + config.output_directory = tmpdir + config.gcmc_radius = "8 A" + runner = Runner(ethane_methanol, config) + resolved = runner._config + assert resolved.gcmc_radius.to("A") == pytest.approx(8.0) + assert resolved.gcmc_num_waters == ghost_waters( + ethane_methanol, centre, 8.0, volume + ) + assert runner._gcmc_kwargs["radius"] == str(resolved.gcmc_radius) diff --git a/tests/runner/test_repex.py b/tests/runner/test_repex.py index 8563e599..21180ea1 100644 --- a/tests/runner/test_repex.py +++ b/tests/runner/test_repex.py @@ -1240,6 +1240,7 @@ def test_repex_gcmc_without_a_selection(ethane_methanol): "replica_exchange": True, "max_contexts": 2, "gcmc": True, + "gcmc_selection": None, "gcmc_frequency": "4fs", }