From 89d3dcc5cbcad319caa1f675583c8a3751ecf489 Mon Sep 17 00:00:00 2001 From: Lester Hedges Date: Tue, 17 Nov 2026 12:31:38 +0000 Subject: [PATCH] Backport fix from PR #67. [ci skip] --- src/loch/_sampler.py | 11 +++++++++-- tests/test_num_waters.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/loch/_sampler.py b/src/loch/_sampler.py index 73c97eb..cec36b9 100644 --- a/src/loch/_sampler.py +++ b/src/loch/_sampler.py @@ -773,6 +773,9 @@ def __init__( # the count for the volume that move() samples. None when unknown. self._N_region = None + # The context stored by a bulk move, which num_waters() falls back to. + self._openmm_context = None + import sys # Create a logger that writes to stderr and the log file. @@ -2063,9 +2066,9 @@ def move(self, context: _openmm.Context) -> list[int]: if self._is_pme: initial_energy = final_energy - # Return immediately if we're in test mode. + # Stop after the first accepted move if we're in test mode. if self._is_test: - return moves + break # If no moves were accepted at the PME level, then update the # number of attempts by the batch size. else: @@ -2081,6 +2084,10 @@ def move(self, context: _openmm.Context) -> list[int]: if self._reference is not None and self._is_bulk: self._openmm_context = context + # Accepted moves update self._N, so refresh the region count to match. + if not self._is_bulk: + self._N_region = self._N + return moves def _compute_energy(self, candidates_gpu: _Any, is_deletion_gpu: _Any) -> None: diff --git a/tests/test_num_waters.py b/tests/test_num_waters.py index 641d821..ff6e93b 100644 --- a/tests/test_num_waters.py +++ b/tests/test_num_waters.py @@ -1,3 +1,5 @@ +import os + import pytest from loch import GCMCSampler @@ -73,3 +75,40 @@ def test_num_waters_refuses_a_whole_box_count(): with pytest.raises(RuntimeError, match="OpenMM context is not set"): sampler.num_waters() + + +@pytest.mark.skipif( + "CUDA_VISIBLE_DEVICES" not in os.environ, + reason="Requires CUDA enabled GPU.", +) +def test_num_waters_after_a_region_move(bpti): + """ + A sampler with a region must report the stored count after a move without + a context, before any bulk move has stored one. + """ + mols, reference = bpti + + sampler = GCMCSampler( + mols, + reference=reference, + cutoff_type="rf", + cutoff="10 A", + bulk_sampling_probability=0.0, + ghost_file=None, + log_file=None, + test=True, + platform="cuda", + seed=42, + ) + + d = sampler.system().dynamics( + cutoff_type="rf", + cutoff="10 A", + pressure=None, + constraint="h_bonds", + platform="cuda", + ) + + sampler.move(d.context()) + + assert sampler.num_waters() == sampler.num_waters(d.context())