From 5f3b1c4e22d90f484fc4c36235d0cf36c0f03911 Mon Sep 17 00:00:00 2001 From: hannahbaumann Date: Thu, 26 Nov 2026 16:01:36 +0100 Subject: [PATCH 1/8] Create a separte PlainMDEquilibration Unit --- .../protocols/openmm_md/plain_md_methods.py | 1399 +++++++++++------ .../openmm_utils/base_equilibration.py | 179 +++ .../openmm_md/test_plain_md_protocol.py | 121 +- .../openmm_md/test_plain_md_resume.py | 213 ++- .../protocols/test_base_equilibration.py | 138 ++ 5 files changed, 1474 insertions(+), 576 deletions(-) create mode 100644 src/openfe/protocols/openmm_utils/base_equilibration.py create mode 100644 src/openfe/tests/protocols/test_base_equilibration.py diff --git a/src/openfe/protocols/openmm_md/plain_md_methods.py b/src/openfe/protocols/openmm_md/plain_md_methods.py index 48b3fce14..c076da75b 100644 --- a/src/openfe/protocols/openmm_md/plain_md_methods.py +++ b/src/openfe/protocols/openmm_md/plain_md_methods.py @@ -57,6 +57,9 @@ system_creation, system_validation, ) +from openfe.protocols.openmm_utils.base_equilibration import ( + BaseEquilibrationUnit, EquilibrationEntry, EquilibrationInputs, +) from openfe.protocols.openmm_utils.offmolecule_utils import ( _get_offmol_metadata, _get_unique_name, @@ -254,7 +257,7 @@ def _create( comp_name = comp.name system_name += f" {comp_type}:{comp_name}" - # make the DAG from the setup and simulation units + # make the DAG from setup, equilibration, and production units n_repeats = self.settings.protocol_repeats units = [] for i in range(n_repeats): @@ -267,16 +270,25 @@ def _create( repeat_id=repeat_id, name=f"MD Setup: {system_name} repeat {i} generation 0", ) + equil = PlainMDEquilibrationUnit( + protocol=self, + stateA=stateA, + generation=0, + repeat_id=repeat_id, + setup_results=setup, + name=f"MD Equilibration: {system_name} repeat {i} generation 0", + ) sim = PlainMDSimulationUnit( protocol=self, stateA=stateA, generation=0, repeat_id=repeat_id, setup_results=setup, + equilibration_results=equil, name=f"MD Simulation: {system_name} repeat {i} generation 0", ) - units.extend([setup, sim]) + units.extend([setup, equil, sim]) return units @@ -334,415 +346,205 @@ def _set_optional_path(basepath): self.scratch_basepath = _set_optional_path(scratch_basepath) self.shared_basepath = _set_optional_path(shared_basepath) - -class PlainMDSetupUnit(PlainMDUnitMixin, gufe.ProtocolUnit): - """ - Protocol setup unit for plain MD simulations which handles charging, system building and solvation. - """ - @staticmethod - def _assign_partial_charges( - charge_settings: OpenFFPartialChargeSettings, - smc_components: dict[SmallMoleculeComponent, OFFMolecule], + def _verify_execution_environment( + setup_outputs: dict[str, Any], ) -> None: """ - Assign partial charges to SMCs. - - Parameters - ---------- - charge_settings : OpenFFPartialChargeSettings - Settings for controlling how the partial charges are assigned. - smc_components : dict[SmallMoleculeComponent, openff.toolkit.Molecule] - Dictionary of OpenFF Molecules to add, keyed by - SmallMoleculeComponent. + Check that the Python environment hasn't changed based on the + relevant Python library versions stored in the setup outputs. """ - for mol in smc_components.values(): - charge_generation.assign_offmol_partial_charges( - offmol=mol, - overwrite=False, - method=charge_settings.partial_charge_method, - toolkit_backend=charge_settings.off_toolkit_backend, - generate_n_conformers=charge_settings.number_of_conformers, - nagl_model=charge_settings.nagl_model, + try: + if ( + (gufe.__version__ != setup_outputs["gufe_version"]) + or (openfe.__version__ != setup_outputs["openfe_version"]) + or (openmm.__version__ != setup_outputs["openmm_version"]) + ): + errmsg = "Python environment has changed, cannot continue Protocol execution." + raise ProtocolUnitExecutionError(errmsg) + except KeyError: + errmsg = "Missing environment information from setup outputs." + raise ProtocolUnitExecutionError(errmsg) + + @staticmethod + def _save_pdb_subset( + simulation: openmm.app.Simulation, + output_settings: MDOutputSettings, + file_name: pathlib.Path, + ): + # get the positions + positions = to_openmm( + from_openmm( + simulation.context.getState( + getPositions=True, enforcePeriodicBox=False + ).getPositions() ) + ) + # get the subset from the output settings + mdtraj_top = mdtraj.Topology.from_openmm(simulation.topology) + selection_indices = mdtraj_top.select(output_settings.output_indices) + traj = mdtraj.Trajectory( + positions[selection_indices, :], + mdtraj_top.subset(selection_indices), + ) + traj.save_pdb(file_name) - def run( - self, - *, - dry: bool = False, + @classmethod + def _run_dynamics( + cls, + simulation: openmm.app.Simulation, + steps: int, + temperature: KelvinQuantity, + barostat_frequency: Quantity, + output_settings: MDOutputSettings, verbose: bool = True, - scratch_basepath: pathlib.Path | None = None, - shared_basepath: pathlib.Path | None = None, - ) -> dict[str, Any]: - """Setup a plain MD system. + output_path: None | pathlib.Path = None, + reinitialize_velocities: bool = True, + ): + """ + Worker method to set the temperature, barostat and run dynamics and save final structure output. + """ + # only set the velocities to temperature if we are not restarting this section + if reinitialize_velocities: + # set the velocities to temperature + simulation.context.setVelocitiesToTemperature( + to_openmm(temperature)) - Parameters - ---------- - dry : bool - Do a dry run of the calculation, creating all necessary hybrid - system components (topology, system, sampler, etc...) but without - running the simulation. - verbose : bool - Verbose output of the simulation progress. Output is provided via - INFO level logging. - scratch_basepath: pathlib.Path | None - Where to store temporary files, defaults to current working directory - shared_basepath : pathlib.Path | None - Where to run the calculation, defaults to current working directory + # Setup the barostat + for x in simulation.context.getSystem().getForces(): + if isinstance(x, (MonteCarloBarostat, MonteCarloMembraneBarostat)): + x.setFrequency(barostat_frequency.m) + + # run the simulation + t0 = time.time() + simulation.step(steps) + t1 = time.time() + if verbose: + logger.info(f"Completed dynamics in {t1 - t0} seconds") + + # save the final frame if a file path is passed + if output_path is not None: + cls._save_pdb_subset( + simulation, + output_settings, + output_path, + ) + + @staticmethod + def _get_remaining_steps( + current_step_count: int, + equil_steps_nvt: int, + equil_steps_npt: int, + prod_steps: int, + ) -> tuple[int, int, int, bool]: + """ + Work out the remaining steps for each phase of the simulation based on the current step count, + and determine if production has already started. Returns ------- - dict - Outputs created by the setup unit or the debug objects - (e.g. HybridTopologyFactory) if ``dry==True``. - - Raises - ------ - error - Exception if anything failed + equil_steps_nvt : int + The number of nvt steps left to run + equil_steps_npt : int + The number of npt steps left to run + prod_steps : int + The number of production steps left to run + production_started : bool + Whether the production phase has already started or not """ - # Prepare paths and set verbosity - self._prepare(verbose, scratch_basepath, shared_basepath) + nvt_end = equil_steps_nvt + npt_end = equil_steps_nvt + equil_steps_npt + prod_end = equil_steps_nvt + equil_steps_npt + prod_steps - if verbose: - self.logger.info("Creating system") + if npt_end < current_step_count <= prod_end: + # In the production phase + return 0, 0, prod_end - current_step_count, True - # 0. General setup and settings dependency resolution step - # Extract relevant settings - protocol_settings: PlainMDProtocolSettings = self._inputs["protocol"].settings - stateA = self._inputs["stateA"] + elif nvt_end < current_step_count <= npt_end: + # In the NPT equilibration phase + return 0, npt_end - current_step_count, prod_steps, False - forcefield_settings: settings.OpenMMSystemGeneratorFFSettings = ( - protocol_settings.forcefield_settings - ) - thermo_settings: settings.ThermoSettings = protocol_settings.thermo_settings - solvation_settings: OpenMMSolvationSettings = protocol_settings.solvation_settings - charge_settings: BasePartialChargeSettings = protocol_settings.partial_charge_settings - sim_settings: MDSimulationSettings = protocol_settings.simulation_settings - output_settings: MDOutputSettings = protocol_settings.output_settings - integrator_settings: IntegratorSettings = protocol_settings.integrator_settings - timestep = integrator_settings.timestep + else: + # In the NVT equilibration phase + return nvt_end - current_step_count, equil_steps_npt, prod_steps, False - # is the timestep good for the mass? - settings_validation.validate_timestep(forcefield_settings.hydrogen_mass, timestep) + @staticmethod + def _create_simulation( + *, + system: openmm.System, + topology: openmm.app.Topology, + protocol_settings: PlainMDProtocolSettings, + ) -> tuple[openmm.app.Simulation, openmm.Integrator]: + """Create a PlainMD OpenMM Simulation.""" - # do step validation early and pass through the units - if sim_settings.equilibration_length_nvt is not None: - equil_steps_nvt = settings_validation.get_simsteps( - sim_length=sim_settings.equilibration_length_nvt, - timestep=timestep, - mc_steps=1, - ) - else: - equil_steps_nvt = None + forcefield_settings = protocol_settings.forcefield_settings + thermo_settings = protocol_settings.thermo_settings + integrator_settings = protocol_settings.integrator_settings + engine_settings = protocol_settings.engine_settings - equil_steps_npt = settings_validation.get_simsteps( - sim_length=sim_settings.equilibration_length, - timestep=timestep, - mc_steps=1, + restrict_cpu = ( + forcefield_settings.nonbonded_method.lower() == "nocutoff" ) - prod_steps = settings_validation.get_simsteps( - sim_length=sim_settings.production_length, - timestep=timestep, - mc_steps=1, + platform = omm_compute.get_openmm_platform( + platform_name=engine_settings.compute_platform, + gpu_device_index=engine_settings.gpu_device_index, + restrict_cpu_count=restrict_cpu, ) - solvent_comp, protein_comp, small_mols = system_validation.get_components(stateA) + integrator = openmm.LangevinMiddleIntegrator( + to_openmm(thermo_settings.temperature), + to_openmm(integrator_settings.langevin_collision_rate), + to_openmm(integrator_settings.timestep), + ) - # Set the solvent component to be the protein component if the latter - # is already solvated. - if isinstance(protein_comp, SolvatedPDBComponent): - solvent_comp = protein_comp + simulation = openmm.app.Simulation( + topology, + system, + integrator, + platform, + ) - # 1. Create stateA system - # Create a dictionary of OFFMol for each SMC for bookkeeping - smc_components: dict[SmallMoleculeComponent, OFFMolecule] = { - i: i.to_openff() for i in small_mols - } + return simulation, integrator - # a. assign residue names / numbers to the small molecules. - # First gather all the unique names & resnums - used_names = _get_used_offmol_property(list(smc_components.values()), "residue_name") - used_resnums = { - int(i) - for i in _get_used_offmol_property(list(smc_components.values()), "residue_number") - } + @staticmethod + def _add_checkpoint_reporter( + simulation: openmm.app.Simulation, + checkpoint_path: pathlib.Path | None, + checkpoint_interval: int, + ) -> None: + """Attach a portable XML State checkpoint reporter.""" - # We assign everything LIG unless LIG is already a name - resname = _get_unique_name("LIG", "LG", used_names) + if checkpoint_path is not None: + simulation.reporters.append( + openmm.app.CheckpointReporter( + file=str(checkpoint_path), + reportInterval=checkpoint_interval, + writeState=True, + ) + ) - # Now we assign all the residue names & numbers - for offmol in smc_components.values(): - name = _get_offmol_metadata(offmol, "residue_name") - num = _get_offmol_metadata(offmol, "residue_number") - if name is None: - _set_offmol_metadata(offmol, "residue_name", resname) - if num is None: - resnum = _next_available_number(used_resnums) - _set_offmol_metadata(offmol, "residue_number", str(resnum)) - used_resnums.add(resnum) + @staticmethod + def _run_MD( + simulation: openmm.app.Simulation, + positions: omm_unit.Quantity, + simulation_settings: MDSimulationSettings, + output_settings: MDOutputSettings, + temperature: KelvinQuantity, + barostat_frequency: Quantity, + timestep: FemtosecondQuantity, + equil_steps_nvt: int | None, + equil_steps_npt: int, + prod_steps: int, + verbose: bool = True, + shared_basepath: pathlib.Path | None = None, + restart: bool = False, + ) -> None: + """ + Energy minimization, Equilibration and Production MD to be reused + in multiple protocols - # b. assign partial charges to smcs - self._assign_partial_charges(charge_settings, smc_components) - - # c. get a system generator - if output_settings.forcefield_cache is not None: - ffcache = self.shared_basepath / output_settings.forcefield_cache - else: - ffcache = None - - # Note: we block out the oechem backend for all systemgenerator - # linked operations to avoid any smiles operations that can - # go wrong when doing rdkit->OEchem roundtripping - with without_oechem_backend(): - system_generator = system_creation.get_system_generator( - forcefield_settings=forcefield_settings, - integrator_settings=integrator_settings, - thermo_settings=thermo_settings, - cache=ffcache, - has_solvent=solvent_comp is not None, - ) - - # Force creation of smc templates so we can solvate later - for mol in smc_components.values(): - system_generator.create_system(mol.to_topology().to_openmm(), molecules=[mol]) - - # d. get OpenMM Modeller + a resids dictionary for each component - stateA_modeller, comp_resids = system_creation.get_omm_modeller( - protein_comp=protein_comp, - solvent_comp=solvent_comp, - small_mols=smc_components, - omm_forcefield=system_generator.forcefield, - solvent_settings=solvation_settings, - ) - - # e. get topology & positions - # Note: roundtrip positions to remove vec3 issues - stateA_topology = stateA_modeller.getTopology() - stateA_positions = to_openmm(from_openmm(stateA_modeller.getPositions())) - - # f. create the stateA System - stateA_system = system_generator.create_system( - stateA_topology, - molecules=[s.to_openff() for s in small_mols], - ) - - # g. Save pdb of entire system topology to file, this is always needed for restarts - with open(self.shared_basepath / output_settings.preminimized_structure, "w") as f: - openmm.app.PDBFile.writeFile(stateA_topology, stateA_positions, file=f, keepIds=True) - - # h. Save the system and positions to file - system_outfile = self.shared_basepath / "system.xml.bz2" - serialization.serialize(stateA_system, system_outfile) - positions_outfile = self.shared_basepath / "input_positions.npy" - np.save(positions_outfile, stateA_positions.value_in_unit(omm_unit.nanometers)) - - unit_results_dict = { - "system": system_outfile, - # save the positions to higher precision - "positions": positions_outfile, - "system_pdb": self.shared_basepath / output_settings.preminimized_structure, - "equil_steps_nvt": equil_steps_nvt, - "equil_steps_npt": equil_steps_npt, - "prod_steps": prod_steps, - } - if dry: - # add non serialised stuff for testing - debug_info = { - "system": stateA_system, - "positions": stateA_positions, - "topology": stateA_topology, - } - unit_results_dict["debug"] = debug_info - - return unit_results_dict - - def _execute( - self, - ctx: gufe.Context, - **kwargs, - ) -> dict[str, Any]: - log_system_probe(logging.INFO, paths=[ctx.scratch]) - - outputs = self.run(scratch_basepath=ctx.scratch, shared_basepath=ctx.shared) - - return { - "repeat_id": self._inputs["repeat_id"], - "generation": self._inputs["generation"], - # track some version restart info to check compatibility - "openmm_version": openmm.__version__, - "openfe_version": openfe.__version__, - "gufe_version": gufe.__version__, - **outputs, - } - - -class PlainMDSimulationUnit(PlainMDUnitMixin, gufe.ProtocolUnit): - """ - Protocol unit for plain MD simulation equilibration and production runs (NonTransformation). - """ - - @staticmethod - def _check_restart(output_settings: MDOutputSettings, shared_path: pathlib.Path): - """ - Check if we are doing a restart. - - Parameters - ---------- - output_settings : MDOutputSettings - The simulation output settings - shared_path : pathlib.Path - The shared directory where we should be looking for existing files. - - Notes - ----- - For now this just checks if the checkpoint state file is present in the - shared directory but in the future this may expand depending on - how warehouse works. - """ - checkpoint = shared_path / output_settings.checkpoint_storage_filename - - return checkpoint.is_file() - - @staticmethod - def _verify_execution_environment( - setup_outputs: dict[str, Any], - ) -> None: - """ - Check that the Python environment hasn't changed based on the - relevant Python library versions stored in the setup outputs. - """ - try: - if ( - (gufe.__version__ != setup_outputs["gufe_version"]) - or (openfe.__version__ != setup_outputs["openfe_version"]) - or (openmm.__version__ != setup_outputs["openmm_version"]) - ): - errmsg = "Python environment has changed, cannot continue Protocol execution." - raise ProtocolUnitExecutionError(errmsg) - except KeyError: - errmsg = "Missing environment information from setup outputs." - raise ProtocolUnitExecutionError(errmsg) - - @staticmethod - def _save_pdb_subset( - simulation: openmm.app.Simulation, - output_settings: MDOutputSettings, - file_name: pathlib.Path, - ): - # get the positions - positions = to_openmm( - from_openmm( - simulation.context.getState( - getPositions=True, enforcePeriodicBox=False - ).getPositions() - ) - ) - # get the subset from the output settings - mdtraj_top = mdtraj.Topology.from_openmm(simulation.topology) - selection_indices = mdtraj_top.select(output_settings.output_indices) - traj = mdtraj.Trajectory( - positions[selection_indices, :], - mdtraj_top.subset(selection_indices), - ) - traj.save_pdb(file_name) - - @staticmethod - def _run_dynamics( - simulation: openmm.app.Simulation, - steps: int, - temperature: KelvinQuantity, - barostat_frequency: Quantity, - output_settings: MDOutputSettings, - verbose: bool = True, - output_path: None | pathlib.Path = None, - reinitialize_velocities: bool = True, - ): - """ - Worker method to set the temperature, barostat and run dynamics and save final structure output. - """ - # only set the velocities to temperature if we are not restarting this section - if reinitialize_velocities: - # set the velocities to temperature - simulation.context.setVelocitiesToTemperature(to_openmm(temperature)) - - # Setup the barostat - for x in simulation.context.getSystem().getForces(): - if isinstance(x, (MonteCarloBarostat, MonteCarloMembraneBarostat)): - x.setFrequency(barostat_frequency.m) - - # run the simulation - t0 = time.time() - simulation.step(steps) - t1 = time.time() - if verbose: - logger.info(f"Completed dynamics in {t1 - t0} seconds") - - # save the final frame if a file path is passed - if output_path is not None: - PlainMDSimulationUnit._save_pdb_subset( - simulation, - output_settings, - output_path, - ) - - @staticmethod - def _get_remaining_steps( - current_step_count: int, - equil_steps_nvt: int, - equil_steps_npt: int, - prod_steps: int, - ) -> tuple[int, int, int, bool]: - """ - Work out the remaining steps for each phase of the simulation based on the current step count, - and determine if production has already started. - - Returns - ------- - equil_steps_nvt : int - The number of nvt steps left to run - equil_steps_npt : int - The number of npt steps left to run - prod_steps : int - The number of production steps left to run - production_started : bool - Whether the production phase has already started or not - """ - nvt_end = equil_steps_nvt - npt_end = equil_steps_nvt + equil_steps_npt - prod_end = equil_steps_nvt + equil_steps_npt + prod_steps - - if npt_end < current_step_count <= prod_end: - # In the production phase - return 0, 0, prod_end - current_step_count, True - - elif nvt_end < current_step_count <= npt_end: - # In the NPT equilibration phase - return 0, npt_end - current_step_count, prod_steps, False - - else: - # In the NVT equilibration phase - return nvt_end - current_step_count, equil_steps_npt, prod_steps, False - - @staticmethod - def _run_MD( - simulation: openmm.app.Simulation, - positions: omm_unit.Quantity, - simulation_settings: MDSimulationSettings, - output_settings: MDOutputSettings, - temperature: KelvinQuantity, - barostat_frequency: Quantity, - timestep: FemtosecondQuantity, - equil_steps_nvt: int | None, - equil_steps_npt: int, - prod_steps: int, - verbose: bool = True, - shared_basepath: pathlib.Path | None = None, - restart: bool = False, - ) -> None: - """ - Energy minimization, Equilibration and Production MD to be reused - in multiple protocols + Legacy all-in-one path: still used by the ABFE and SepTop + pre-equilibration. Remove once those protocols use BaseEquilibrationUnit. Parameters ---------- @@ -800,12 +602,14 @@ def _run_MD( if restart: if verbose: logger.info("Restarting simulation from checkpoint state") - simulation.loadState(str(shared_basepath / output_settings.checkpoint_storage_filename)) + simulation.loadState( + str(shared_basepath / output_settings.checkpoint_storage_filename)) # workout the number of steps to run in each phase based on the current simulation step count current_step_count = simulation.context.getStepCount() equil_steps_nvt, equil_steps_npt, prod_steps, production_started = ( - PlainMDSimulationUnit._get_remaining_steps( + PlainMDUnitMixin._get_remaining_steps( + # was PlainMDSimulationUnit current_step_count=current_step_count, equil_steps_nvt=equil_steps_nvt, equil_steps_npt=equil_steps_npt, @@ -820,10 +624,11 @@ def _run_MD( if verbose: logger.info("Minimizing systems") - simulation.minimizeEnergy(maxIterations=simulation_settings.minimization_steps) + simulation.minimizeEnergy( + maxIterations=simulation_settings.minimization_steps) if output_settings.minimized_structure: - PlainMDSimulationUnit._save_pdb_subset( + PlainMDUnitMixin._save_pdb_subset( # was PlainMDSimulationUnit simulation, output_settings, shared_basepath / output_settings.minimized_structure, @@ -833,9 +638,11 @@ def _run_MD( if output_settings.checkpoint_storage_filename: simulation.reporters.append( openmm.app.CheckpointReporter( - file=str(shared_basepath / output_settings.checkpoint_storage_filename), + file=str( + shared_basepath / output_settings.checkpoint_storage_filename), reportInterval=checkpoint_interval, - writeState=True, # writes portable XML via simulation.saveState() + writeState=True, + # writes portable XML via simulation.saveState() ) ) @@ -843,17 +650,19 @@ def _run_MD( # NVT equilibration if equil_steps_nvt > 0: if verbose: - logger.info(f"Running NVT equilibration for {equil_steps_nvt} steps") + logger.info( + f"Running NVT equilibration for {equil_steps_nvt} steps") # setup the output path if we have one for the nvt equilibration if output_settings.equil_nvt_structure is not None: output_path = shared_basepath / output_settings.equil_nvt_structure else: output_path = None - PlainMDSimulationUnit._run_dynamics( + PlainMDUnitMixin._run_dynamics( # was PlainMDSimulationUnit simulation=simulation, steps=equil_steps_nvt, temperature=temperature, - barostat_frequency=0 * unit.timestep, # turn off the barostat for this stage + barostat_frequency=0 * unit.timestep, + # turn off the barostat for this stage output_settings=output_settings, verbose=verbose, output_path=output_path, @@ -865,14 +674,15 @@ def _run_MD( # NPT equilibration if equil_steps_npt > 0: if verbose: - logger.info(f"Running NPT equilibration for {equil_steps_npt} steps") + logger.info( + f"Running NPT equilibration for {equil_steps_npt} steps") # setup the output path if we have one for the npt equilibration if output_settings.equil_npt_structure is not None: output_path = shared_basepath / output_settings.equil_npt_structure else: output_path = None - PlainMDSimulationUnit._run_dynamics( + PlainMDUnitMixin._run_dynamics( # was PlainMDSimulationUnit simulation=simulation, steps=equil_steps_npt, temperature=temperature, @@ -899,11 +709,13 @@ def _run_MD( if output_settings.production_trajectory_filename: # Get the sub selection of the system to save coords for - selection_indices = mdtraj.Topology.from_openmm(simulation.topology).select( + selection_indices = mdtraj.Topology.from_openmm( + simulation.topology).select( output_settings.output_indices ) xtc_reporter = XTCReporter( - file=str(shared_basepath / output_settings.production_trajectory_filename), + file=str( + shared_basepath / output_settings.production_trajectory_filename), reportInterval=write_interval, atomSubset=selection_indices, # append to the trajectory if restarting and we have run the production stage before @@ -929,47 +741,62 @@ def _run_MD( ) ) - PlainMDSimulationUnit._run_dynamics( + PlainMDUnitMixin._run_dynamics( # was PlainMDSimulationUnit simulation=simulation, steps=prod_steps, temperature=temperature, barostat_frequency=barostat_frequency, output_settings=output_settings, verbose=verbose, - output_path=None, # the trajectory is saved for the production run so don't save again + output_path=None, + # the trajectory is saved for the production run so don't save again reinitialize_velocities=reinitialize_velocities, ) - def run( - self, - *, - system: openmm.System, - positions: openmm.unit.Quantity, - topology: openmm.app.Topology, - equil_steps_nvt: int | None, - equil_steps_npt: int, - prod_steps: int, - dry: bool = False, - verbose: bool = True, + +class PlainMDSetupUnit(PlainMDUnitMixin, gufe.ProtocolUnit): + """ + Protocol setup unit for plain MD simulations which handles charging, system building and solvation. + """ + + @staticmethod + def _assign_partial_charges( + charge_settings: OpenFFPartialChargeSettings, + smc_components: dict[SmallMoleculeComponent, OFFMolecule], + ) -> None: + """ + Assign partial charges to SMCs. + + Parameters + ---------- + charge_settings : OpenFFPartialChargeSettings + Settings for controlling how the partial charges are assigned. + smc_components : dict[SmallMoleculeComponent, openff.toolkit.Molecule] + Dictionary of OpenFF Molecules to add, keyed by + SmallMoleculeComponent. + """ + for mol in smc_components.values(): + charge_generation.assign_offmol_partial_charges( + offmol=mol, + overwrite=False, + method=charge_settings.partial_charge_method, + toolkit_backend=charge_settings.off_toolkit_backend, + generate_n_conformers=charge_settings.number_of_conformers, + nagl_model=charge_settings.nagl_model, + ) + + def run( + self, + *, + dry: bool = False, + verbose: bool = True, scratch_basepath: pathlib.Path | None = None, shared_basepath: pathlib.Path | None = None, ) -> dict[str, Any]: - """Run the MD simulation. + """Setup a plain MD system. Parameters ---------- - system : openmm.System - The System to simulate. - positions : openmm.unit.Quantity - The positions of the System. - topology: openmm.app.Topology - The topology of the System. - equil_steps_nvt : int - The number of nvt equilibration steps. - equil_steps_npt : int - The number of npt equilibration steps. - prod_steps : int - The number of production steps. dry : bool Do a dry run of the calculation, creating all necessary hybrid system components (topology, system, sampler, etc...) but without @@ -977,16 +804,16 @@ def run( verbose : bool Verbose output of the simulation progress. Output is provided via INFO level logging. - scratch_basepath: Pathlike, optional + scratch_basepath: pathlib.Path | None Where to store temporary files, defaults to current working directory - shared_basepath : Pathlike, optional + shared_basepath : pathlib.Path | None Where to run the calculation, defaults to current working directory Returns ------- dict - Outputs created in the basepath directory or the debug objects - (i.e. sampler) if ``dry==True``. + Outputs created by the setup unit or the debug objects + (e.g. HybridTopologyFactory) if ``dry==True``. Raises ------ @@ -996,129 +823,683 @@ def run( # Prepare paths and set verbosity self._prepare(verbose, scratch_basepath, shared_basepath) + if verbose: + self.logger.info("Creating system") + + # 0. General setup and settings dependency resolution step # Extract relevant settings protocol_settings: PlainMDProtocolSettings = self._inputs["protocol"].settings + stateA = self._inputs["stateA"] forcefield_settings: settings.OpenMMSystemGeneratorFFSettings = ( protocol_settings.forcefield_settings ) thermo_settings: settings.ThermoSettings = protocol_settings.thermo_settings + solvation_settings: OpenMMSolvationSettings = protocol_settings.solvation_settings + charge_settings: BasePartialChargeSettings = protocol_settings.partial_charge_settings sim_settings: MDSimulationSettings = protocol_settings.simulation_settings output_settings: MDOutputSettings = protocol_settings.output_settings - timestep = protocol_settings.integrator_settings.timestep - integrator_settings = protocol_settings.integrator_settings + integrator_settings: IntegratorSettings = protocol_settings.integrator_settings + timestep = integrator_settings.timestep - # Get platform - restrict_cpu = forcefield_settings.nonbonded_method.lower() == "nocutoff" - platform = omm_compute.get_openmm_platform( - platform_name=protocol_settings.engine_settings.compute_platform, - gpu_device_index=protocol_settings.engine_settings.gpu_device_index, - restrict_cpu_count=restrict_cpu, - ) + # is the timestep good for the mass? + settings_validation.validate_timestep(forcefield_settings.hydrogen_mass, timestep) - # Set the integrator - integrator = openmm.LangevinMiddleIntegrator( - to_openmm(thermo_settings.temperature), - to_openmm(integrator_settings.langevin_collision_rate), - to_openmm(timestep), + # do step validation early and pass through the units + if sim_settings.equilibration_length_nvt is not None: + equil_steps_nvt = settings_validation.get_simsteps( + sim_length=sim_settings.equilibration_length_nvt, + timestep=timestep, + mc_steps=1, + ) + else: + equil_steps_nvt = None + + equil_steps_npt = settings_validation.get_simsteps( + sim_length=sim_settings.equilibration_length, + timestep=timestep, + mc_steps=1, ) - # Build the simulation - simulation = openmm.app.Simulation( - topology, - system, - integrator, - platform, + prod_steps = settings_validation.get_simsteps( + sim_length=sim_settings.production_length, + timestep=timestep, + mc_steps=1, ) + solvent_comp, protein_comp, small_mols = system_validation.get_components(stateA) + + # Set the solvent component to be the protein component if the latter + # is already solvated. + if isinstance(protein_comp, SolvatedPDBComponent): + solvent_comp = protein_comp + + # 1. Create stateA system + # Create a dictionary of OFFMol for each SMC for bookkeeping + smc_components: dict[SmallMoleculeComponent, OFFMolecule] = { + i: i.to_openff() for i in small_mols + } + + # a. assign residue names / numbers to the small molecules. + # First gather all the unique names & resnums + used_names = _get_used_offmol_property(list(smc_components.values()), "residue_name") + used_resnums = { + int(i) + for i in _get_used_offmol_property(list(smc_components.values()), "residue_number") + } + + # We assign everything LIG unless LIG is already a name + resname = _get_unique_name("LIG", "LG", used_names) + + # Now we assign all the residue names & numbers + for offmol in smc_components.values(): + name = _get_offmol_metadata(offmol, "residue_name") + num = _get_offmol_metadata(offmol, "residue_number") + if name is None: + _set_offmol_metadata(offmol, "residue_name", resname) + if num is None: + resnum = _next_available_number(used_resnums) + _set_offmol_metadata(offmol, "residue_number", str(resnum)) + used_resnums.add(resnum) + + # b. assign partial charges to smcs + self._assign_partial_charges(charge_settings, smc_components) + + # c. get a system generator + if output_settings.forcefield_cache is not None: + ffcache = self.shared_basepath / output_settings.forcefield_cache + else: + ffcache = None + + # Note: we block out the oechem backend for all systemgenerator + # linked operations to avoid any smiles operations that can + # go wrong when doing rdkit->OEchem roundtripping + with without_oechem_backend(): + system_generator = system_creation.get_system_generator( + forcefield_settings=forcefield_settings, + integrator_settings=integrator_settings, + thermo_settings=thermo_settings, + cache=ffcache, + has_solvent=solvent_comp is not None, + ) + + # Force creation of smc templates so we can solvate later + for mol in smc_components.values(): + system_generator.create_system(mol.to_topology().to_openmm(), molecules=[mol]) + + # d. get OpenMM Modeller + a resids dictionary for each component + stateA_modeller, comp_resids = system_creation.get_omm_modeller( + protein_comp=protein_comp, + solvent_comp=solvent_comp, + small_mols=smc_components, + omm_forcefield=system_generator.forcefield, + solvent_settings=solvation_settings, + ) + + # e. get topology & positions + # Note: roundtrip positions to remove vec3 issues + stateA_topology = stateA_modeller.getTopology() + stateA_positions = to_openmm(from_openmm(stateA_modeller.getPositions())) + + # f. create the stateA System + stateA_system = system_generator.create_system( + stateA_topology, + molecules=[s.to_openff() for s in small_mols], + ) + + # g. Save pdb of entire system topology to file, this is always needed for restarts + with open(self.shared_basepath / output_settings.preminimized_structure, "w") as f: + openmm.app.PDBFile.writeFile(stateA_topology, stateA_positions, file=f, keepIds=True) + + # h. Save the system and positions to file + system_outfile = self.shared_basepath / "system.xml.bz2" + serialization.serialize(stateA_system, system_outfile) + positions_outfile = self.shared_basepath / "input_positions.npy" + np.save(positions_outfile, stateA_positions.value_in_unit(omm_unit.nanometers)) + + unit_results_dict = { + "system": system_outfile, + # save the positions to higher precision + "positions": positions_outfile, + "system_pdb": self.shared_basepath / output_settings.preminimized_structure, + "equil_steps_nvt": equil_steps_nvt, + "equil_steps_npt": equil_steps_npt, + "prod_steps": prod_steps, + } + if dry: + # add non serialised stuff for testing + debug_info = { + "system": stateA_system, + "positions": stateA_positions, + "topology": stateA_topology, + } + unit_results_dict["debug"] = debug_info + + return unit_results_dict + + def _execute( + self, + ctx: gufe.Context, + **kwargs, + ) -> dict[str, Any]: + log_system_probe(logging.INFO, paths=[ctx.scratch]) + + outputs = self.run(scratch_basepath=ctx.scratch, shared_basepath=ctx.shared) + + return { + "repeat_id": self._inputs["repeat_id"], + "generation": self._inputs["generation"], + # track some version restart info to check compatibility + "openmm_version": openmm.__version__, + "openfe_version": openfe.__version__, + "gufe_version": gufe.__version__, + **outputs, + } + + +class PlainMDEquilibrationUnit(PlainMDUnitMixin, BaseEquilibrationUnit): + """Run PlainMD's existing minimization, optional NVT, and NPT stages. + + ``system_pdb`` from PlainMD setup describes the entire System. A subset + PDB produced for visualization cannot construct an equivalent Simulation. + The common base does not define the physics: future alchemical protocols + must construct their own Systems, parameters, and equilibration schedules. + """ + + def _execute( + self, + ctx: gufe.Context, + setup_results: gufe.ProtocolUnitResult, + **kwargs, + ) -> dict[str, Any]: + log_system_probe(logging.INFO, paths=[ctx.scratch]) + setup = setup_results.outputs + + # Ensure that the environment hasn't changed + self._verify_execution_environment(setup) + + # PlainMD setup serializes the full System and topology. Its NumPy + # coordinates are stored in nanometers, so restore the units here. + system = serialization.deserialize(setup["system"]) + positions = np.load(setup["positions"]) * omm_unit.nanometers + topology = openmm.app.PDBFile(str(setup["system_pdb"])).getTopology() + + if len(positions) != system.getNumParticles(): + raise ValueError("Setup positions do not match System particle count") + if topology.getNumAtoms() != system.getNumParticles(): + raise ValueError("Setup topology must describe the entire OpenMM System") + + # Setup already validated the step counts; do not calculate them again. + outputs = self.run( + equilibration_inputs=EquilibrationInputs( + states=[None], + systems=system, + positions=positions, + topologies=topology, + ), + equil_steps_nvt=setup["equil_steps_nvt"] or 0, + equil_steps_npt=setup["equil_steps_npt"], + scratch_basepath=ctx.scratch, + shared_basepath=ctx.shared, + ) + return { + "repeat_id": self._inputs["repeat_id"], + "generation": self._inputs["generation"], + **outputs, + } + + @staticmethod + def _get_remaining_equilibration_steps( + *, current_step_count: int, equil_steps_nvt: int, equil_steps_npt: int + ) -> tuple[int, int]: + """Return NVT and NPT steps left from an equilibration checkpoint. + + Step counts are absolute across the two dynamics phases; minimization + does not increment the OpenMM step count. Checkpoints from production + are not valid equilibration checkpoints. + """ + nvt_end = equil_steps_nvt + npt_end = nvt_end + equil_steps_npt + if current_step_count < 0 or current_step_count > npt_end: + raise ValueError( + "Checkpoint step count is outside the equilibration interval: " + f"step={current_step_count}, equilibration_end_step={npt_end}" + ) + nvt_remaining = max(0, nvt_end - current_step_count) + npt_remaining = npt_end - max(nvt_end, current_step_count) + return nvt_remaining, npt_remaining + + def _equilibrate_state( + self, + *, + state_input: EquilibrationEntry, + output_dir: pathlib.Path, + scratch_dir: pathlib.Path, + dry: bool, + verbose: bool, + equil_steps_nvt: int, + equil_steps_npt: int, + ) -> dict[str, Any]: + """Minimize and equilibrate, resuming NVT or NPT when possible. + + A portable checkpoint written during equilibration skips minimization + and preserves velocities within the resumed phase. Starting NPT after + NVT reinitializes velocities as in the original PlainMD implementation. + The production unit manages its own checkpoint separately. + """ + self._prepare(verbose, scratch_dir, output_dir) + + protocol_settings: PlainMDProtocolSettings = self._inputs["protocol"].settings + thermo_settings = protocol_settings.thermo_settings + sim_settings = protocol_settings.simulation_settings + output_settings = protocol_settings.output_settings + integrator_settings = protocol_settings.integrator_settings + + simulation, integrator = self._create_simulation( + system=state_input.system, + topology=state_input.topology, + protocol_settings=protocol_settings, + ) try: - if not dry: # pragma: no-cover - # check for a restart - restart = self._check_restart(output_settings, self.shared_basepath) - # start the simulation - self._run_MD( - simulation, - positions, - sim_settings, - output_settings, - thermo_settings.temperature, - integrator_settings.barostat_frequency, - timestep, - equil_steps_nvt, - equil_steps_npt, - prod_steps, - shared_basepath=self.shared_basepath, - restart=restart, - verbose=self.verbose, + if dry: + return {"debug": {"system": state_input.system}} + + checkpoint_name = output_settings.checkpoint_storage_filename + checkpoint_path = output_dir / checkpoint_name if checkpoint_name else None + restart = checkpoint_path is not None and checkpoint_path.is_file() + if restart: + if verbose: + logger.info("Restarting simulation from checkpoint state") + simulation.loadState(str(checkpoint_path)) + else: + simulation.context.setPositions(state_input.positions) + if verbose: + logger.info("Minimizing systems") + simulation.minimizeEnergy( + maxIterations=sim_settings.minimization_steps) + if output_settings.minimized_structure: + self._save_pdb_subset( + simulation, + output_settings, + output_dir / output_settings.minimized_structure, + ) + + current_step_count = simulation.context.getStepCount() + nvt_remaining, npt_remaining = self._get_remaining_equilibration_steps( + current_step_count=current_step_count, + equil_steps_nvt=equil_steps_nvt, + equil_steps_npt=equil_steps_npt, + ) + + # Checkpointing starts after minimization and covers NVT/NPT. + if checkpoint_path is not None: + checkpoint_interval = settings_validation.get_simsteps( + sim_length=output_settings.checkpoint_interval, + timestep=integrator_settings.timestep, + mc_steps=1, + ) + + self._add_checkpoint_reporter( + simulation=simulation, + checkpoint_path=checkpoint_path, + checkpoint_interval=checkpoint_interval, + ) + + nvt_path = ( + output_dir / output_settings.equil_nvt_structure + if output_settings.equil_nvt_structure else None + ) + if nvt_remaining > 0: + if verbose: + logger.info( + f"Running NVT equilibration for {nvt_remaining} steps") + self._run_dynamics( + simulation=simulation, + steps=nvt_remaining, + temperature=thermo_settings.temperature, + barostat_frequency=0 * unit.timestep, + output_settings=output_settings, + verbose=verbose, + output_path=nvt_path, + # Retain checkpoint velocities when resuming inside NVT. + reinitialize_velocities=not restart, + ) + + npt_path = ( + output_dir / output_settings.equil_npt_structure + if output_settings.equil_npt_structure else None + ) + if npt_remaining > 0: + if verbose: + logger.info( + f"Running NPT equilibration for {npt_remaining} steps") + self._run_dynamics( + simulation=simulation, + steps=npt_remaining, + temperature=thermo_settings.temperature, + barostat_frequency=integrator_settings.barostat_frequency, + output_settings=output_settings, + verbose=verbose, + output_path=npt_path, + # Within NPT, preserve saved velocities. At the NVT/NPT + # boundary, initialize a new NPT velocity distribution. + reinitialize_velocities=( + not restart or current_step_count <= equil_steps_nvt + ), ) + state_path = output_dir / "equilibrated_state.xml" + # This State is suitable for PlainMD's compatible production System. + # Future restrained/alchemical Systems may need to strip or map + # Context parameters before loading the State into another System. + simulation.saveState(str(state_path)) + + minimized_path = ( + output_dir / output_settings.minimized_structure + if output_settings.minimized_structure else None + ) + return { + "equilibrated_state": state_path, + "equilibration_end_step": simulation.context.getStepCount(), + "reinitialize_velocities_for_production": equil_steps_npt == 0, + "minimized_pdb": ( + minimized_path if minimized_path is not None and minimized_path.is_file() + else None + ), + "nvt_equil_pdb": nvt_path if nvt_path is not None and nvt_path.is_file() else None, + "npt_equil_pdb": npt_path if npt_path is not None and npt_path.is_file() else None, + } finally: if not dry: del integrator, simulation - if not dry: # pragma: no-cover - output = { - "system_pdb": self.shared_basepath / output_settings.preminimized_structure, - "minimized_pdb": self.shared_basepath / output_settings.minimized_structure, - "nc": self.shared_basepath / output_settings.production_trajectory_filename, - "last_checkpoint": self.shared_basepath - / output_settings.checkpoint_storage_filename, - } - # The checkpoint file can not exist if frequency > sim length - if not output["last_checkpoint"].exists(): - output["last_checkpoint"] = None - # The NVT PDB can be omitted if we don't run the simulation - # Note: we could also just check the file exist - if ( - output_settings.equil_nvt_structure - and sim_settings.equilibration_length_nvt is not None - ): - output["nvt_equil_pdb"] = self.shared_basepath / output_settings.equil_nvt_structure - else: - output["nvt_equil_pdb"] = None +class PlainMDSimulationUnit(PlainMDUnitMixin, gufe.ProtocolUnit): + """ + Run production MD from the State written by PlainMDEquilibrationUnit. + + Setup supplies the original serialized System and full topology. Equilibration + supplies a portable XML State with coordinates, box, velocities, simulation + time/step count, and Context/integrator parameters. Both stages must use + compatible OpenMM Systems for ``Simulation.loadState`` to succeed. - if output_settings.equil_npt_structure: - output["npt_equil_pdb"] = self.shared_basepath / output_settings.equil_npt_structure + Checkpoint files in this unit's shared directory cover *production only*. + """ + + @staticmethod + def _check_restart(output_settings: MDOutputSettings, shared_path: pathlib.Path): + """ + Check if we are doing a restart. + + Parameters + ---------- + output_settings : MDOutputSettings + The simulation output settings + shared_path : pathlib.Path + The shared directory where we should be looking for existing files. + + Notes + ----- + For now this just checks if the checkpoint state file is present in the + shared directory but in the future this may expand depending on + how warehouse works. + """ + checkpoint = shared_path / output_settings.checkpoint_storage_filename + + return checkpoint.is_file() + + @staticmethod + def _get_remaining_production_steps( + *, current_step_count: int, equilibration_end_step: int, + prod_steps: int + ) -> int: + """Steps left after loading either the equilibration State or a checkpoint. + + OpenMM's State retains the absolute step count, so production starts at + ``equilibration_end_step`` rather than zero. + """ + completed = current_step_count - equilibration_end_step + if completed < 0 or completed > prod_steps: + raise ValueError( + "Loaded State step count is outside the production interval: " + f"step={current_step_count}, " + f"equilibration_end_step={equilibration_end_step}, " + f"prod_steps={prod_steps}" + ) + return prod_steps - completed + + def run( + self, + *, + system: openmm.System, + topology: openmm.app.Topology, + equilibrated_state: pathlib.Path, + equilibration_end_step: int, + prod_steps: int, + reinitialize_velocities_for_production: bool, + dry: bool = False, + verbose: bool = True, + scratch_basepath: pathlib.Path | None = None, + shared_basepath: pathlib.Path | None = None, + ) -> dict[str, Any]: + """Run only production MD, continuing from the equilibrated OpenMM State. + + On restart, load the production checkpoint instead, preserving its + velocities and appending existing trajectory and log files. The setup + System must be loaded again (rather than reusing equilibration's System). + + Parameters + ---------- + system : openmm.System + The System to simulate. + topology: openmm.app.Topology + The topology of the System. + equilibrated_state : pathlib.Path + Path to the XML State produced by PlainMDEquilibrationUnit. + equilibration_end_step : int + OpenMM step count at the end of equilibration. + prod_steps : int + Total requested production steps. + reinitialize_velocities_for_production : bool + Whether to initialize velocities when starting fresh production. + Ignored when resuming from a production checkpoint. + dry : bool + Do a dry run of the calculation, creating all necessary hybrid + system components (topology, system, sampler, etc...) but without + running the simulation. + verbose : bool + Verbose output of the simulation progress. Output is provided via + INFO level logging. + scratch_basepath: Pathlike, optional + Where to store temporary files, defaults to current working directory + shared_basepath : Pathlike, optional + Where to run the calculation, defaults to current working directory + + Returns + ------- + dict + Outputs created in the basepath directory or the debug objects + (i.e. sampler) if ``dry==True``. + + Raises + ------ + error + Exception if anything failed + """ + # Prepare paths and set verbosity + self._prepare(verbose, scratch_basepath, shared_basepath) + + # Extract relevant settings + protocol_settings: PlainMDProtocolSettings = self._inputs["protocol"].settings + thermo_settings: settings.ThermoSettings = protocol_settings.thermo_settings + output_settings: MDOutputSettings = protocol_settings.output_settings + timestep = protocol_settings.integrator_settings.timestep + integrator_settings = protocol_settings.integrator_settings + + simulation, integrator = self._create_simulation( + system=system, + topology=topology, + protocol_settings=protocol_settings, + ) + + try: + if dry: + return {"debug": {"system": system}} + # check for a restart + restart = self._check_restart(output_settings, self.shared_basepath) + if restart: + if verbose: + logger.info("Restarting simulation from checkpoint state") + state_path = self.shared_basepath / output_settings.checkpoint_storage_filename else: - output["npt_equil_pdb"] = None + state_path = pathlib.Path(equilibrated_state) - return output - else: - return {"debug": {"system": system}} + # PlainMD equilibration and production use compatible Systems. + simulation.loadState(str(state_path)) + + current_step_count = simulation.context.getStepCount() + remaining_steps = self._get_remaining_production_steps( + current_step_count=current_step_count, + equilibration_end_step=equilibration_end_step, + prod_steps=prod_steps, + ) + production_started = restart and current_step_count > equilibration_end_step + + checkpoint_interval = settings_validation.get_simsteps( + sim_length=output_settings.checkpoint_interval, + timestep=timestep, + mc_steps=1, + ) + checkpoint_name = output_settings.checkpoint_storage_filename + checkpoint_path = ( + self.shared_basepath / checkpoint_name + if checkpoint_name else None + ) + + self._add_checkpoint_reporter( + simulation=simulation, + checkpoint_path=checkpoint_path, + checkpoint_interval=checkpoint_interval, + ) + + if output_settings.production_trajectory_filename: + selection_indices = mdtraj.Topology.from_openmm( + simulation.topology).select( + output_settings.output_indices + ) + trajectory_path = self.shared_basepath / output_settings.production_trajectory_filename + simulation.reporters.append( + XTCReporter( + file=str(trajectory_path), + reportInterval=settings_validation.divmod_time_and_check( + output_settings.trajectory_write_interval, + timestep, + "trajectory_write_interval", + "timestep", + ), + atomSubset=selection_indices, + append=production_started and trajectory_path.is_file(), + ) + ) + + if output_settings.log_output: + log_path = self.shared_basepath / output_settings.log_output + simulation.reporters.append( + openmm.app.StateDataReporter( + str(log_path), + checkpoint_interval, + step=True, + time=True, + potentialEnergy=True, + kineticEnergy=True, + totalEnergy=True, + temperature=True, + volume=True, + density=True, + speed=True, + append=production_started and log_path.is_file(), + ) + ) + + if verbose: + logger.info( + f"Running production phase for {remaining_steps} steps") + if remaining_steps: + self._run_dynamics( + simulation=simulation, + steps=remaining_steps, + temperature=thermo_settings.temperature, + barostat_frequency=integrator_settings.barostat_frequency, + output_settings=output_settings, + verbose=verbose, + output_path=None, + # Preserve the checkpoint's velocities on restart. A fresh + # handoff inherits NPT velocities, but if NPT was skipped + # PlainMD traditionally initializes production velocities. + reinitialize_velocities=( + not restart and reinitialize_velocities_for_production + ), + ) + finally: + if not dry: + del integrator, simulation + + checkpoint_name = output_settings.checkpoint_storage_filename + checkpoint_path = ( + self.shared_basepath / checkpoint_name if checkpoint_name else None + ) + return { + "nc": ( + self.shared_basepath / output_settings.production_trajectory_filename + if output_settings.production_trajectory_filename else None + ), + "last_checkpoint": ( + checkpoint_path if checkpoint_path is not None and checkpoint_path.is_file() + else None + ), + } def _execute( self, ctx: gufe.Context, - setup_results, + setup_results: gufe.ProtocolUnitResult, + equilibration_results: gufe.ProtocolUnitResult, **kwargs, ) -> dict[str, Any]: log_system_probe(logging.INFO, paths=[ctx.scratch]) + setup = setup_results.outputs # Ensure that the environment hasn't changed - self._verify_execution_environment(setup_results.outputs) - - # Get the relevant inputs for running the unit - system = serialization.deserialize(setup_results.outputs["system"]) - positions = ( - np.load(setup_results.outputs["positions"]) * omm_unit.nanometers - ) # convert to openmm units - topology = openmm.app.PDBFile(str(setup_results.outputs["system_pdb"])).getTopology() - equil_steps_nvt = setup_results.outputs["equil_steps_nvt"] - equil_steps_npt = setup_results.outputs["equil_steps_npt"] - prod_steps = setup_results.outputs["prod_steps"] - + self._verify_execution_environment(setup) + + equilibrated_states = equilibration_results.outputs["equilibrated_states"] + if len(equilibrated_states) != 1 or equilibrated_states[0]["index"] != 0: + raise ValueError( + "PlainMD production expects one equilibrated state (index 0)") + equilibrated = equilibrated_states[0] + + # Deserialize a fresh, unmodified setup System: the equilibration unit + # owns and releases a separate OpenMM Context. + system = serialization.deserialize(setup["system"]) + topology = openmm.app.PDBFile(str(setup["system_pdb"])).getTopology() outputs = self.run( system=system, - positions=positions, topology=topology, - equil_steps_nvt=equil_steps_nvt, - equil_steps_npt=equil_steps_npt, - prod_steps=prod_steps, + equilibrated_state=equilibrated["equilibrated_state"], + equilibration_end_step=equilibrated["equilibration_end_step"], + prod_steps=setup["prod_steps"], + reinitialize_velocities_for_production=equilibrated[ + "reinitialize_velocities_for_production" + ], scratch_basepath=ctx.scratch, shared_basepath=ctx.shared, ) - return { "repeat_id": self._inputs["repeat_id"], "generation": self._inputs["generation"], + "system_pdb": setup["system_pdb"], + # Preserve the former simulation-unit output keys for existing + # consumers, even though equilibration now writes these files. + "minimized_pdb": equilibrated.get("minimized_pdb"), + "nvt_equil_pdb": equilibrated.get("nvt_equil_pdb"), + "npt_equil_pdb": equilibrated.get("npt_equil_pdb"), **outputs, } diff --git a/src/openfe/protocols/openmm_utils/base_equilibration.py b/src/openfe/protocols/openmm_utils/base_equilibration.py new file mode 100644 index 000000000..031d9a613 --- /dev/null +++ b/src/openfe/protocols/openmm_utils/base_equilibration.py @@ -0,0 +1,179 @@ +# This code is part of OpenFE and is licensed under the MIT license. +"""Minimal GUFE-facing infrastructure for protocol-specific equilibration units. + +This module deliberately does not define an equilibration schedule. Protocol +subclasses interpret their upstream results and implement their scientific methods. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import gufe +import openmm +from openmm import app, unit as omm_unit + + +@dataclass(frozen=True) +class EquilibrationInputs: + """In-memory inputs resolved by a protocol-specific subclass. + + ``states`` is a nonempty list/tuple. Each of ``systems``, ``positions`` and + ``topologies`` is either a shared single value or a list/tuple with exactly + one value per state. One-element lists are *not* broadcast to many states. + + Positions must be OpenMM Quantity objects carrying length units, not + bare NumPy arrays. PlainMD converts positions.npy (stored in nm) to a + Quantity in its ``_execute()``. These are execution-time objects, not + serialized GUFE ProtocolUnit inputs. + + A topology must include every particle in its corresponding OpenMM System + in the same order. A PDB subset intended for visualization is insufficient. + """ + + states: list[Any] | tuple[Any, ...] + systems: openmm.System | list[openmm.System] | tuple[openmm.System, ...] + positions: ( + omm_unit.Quantity + | list[omm_unit.Quantity] + | tuple[omm_unit.Quantity, ...] + ) + topologies: app.Topology | list[app.Topology] | tuple[app.Topology, ...] + + +@dataclass(frozen=True) +class EquilibrationEntry: + """Inputs for exactly one thermodynamic state, used only during execution.""" + + index: int + state: Any # None for PlainMD; future protocols may provide alchemical states. + system: openmm.System + positions: omm_unit.Quantity + topology: app.Topology + + +class BaseEquilibrationUnit(gufe.ProtocolUnit, ABC): + """Shared iteration and file layout for protocol-specific equilibration. + + Subclasses implement GUFE ``_execute`` to interpret upstream results and + construct ``EquilibrationInputs``. They implement ``_equilibrate_state`` + to run the appropriate protocol-specific physics. This base class only + normalizes and iterates over state inputs, organizes paths and indexes + outputs; it does not define an MD schedule or alchemical Hamiltonian. + + Broadcasting shares references; it does not copy OpenMM objects. A + subclass must not modify shared input Systems or positions in place. + """ + + @staticmethod + def _broadcast(value: Any, n_states: int, name: str) -> tuple[Any, ...]: + """Broadcast a scalar or require exactly one list/tuple value per state.""" + if isinstance(value, (list, tuple)): + if len(value) != n_states: + raise ValueError( + f"{name} must contain {n_states} entries, received {len(value)}" + ) + return tuple(value) + return (value,) * n_states + + @classmethod + def _normalise_inputs( + cls, inputs: EquilibrationInputs + ) -> tuple[EquilibrationEntry, ...]: + """Create aligned entries without copying or mutating input objects.""" + if not isinstance(inputs, EquilibrationInputs): + raise TypeError("equilibration_inputs must be EquilibrationInputs") + if not isinstance(inputs.states, (list, tuple)) or not inputs.states: + raise ValueError("states must be a non-empty list or tuple") + + n_states = len(inputs.states) + systems = cls._broadcast(inputs.systems, n_states, "systems") + positions = cls._broadcast(inputs.positions, n_states, "positions") + topologies = cls._broadcast(inputs.topologies, n_states, "topologies") + return tuple( + EquilibrationEntry( + index=index, + state=state, + system=system, + positions=position, + topology=topology, + ) + for index, (state, system, position, topology) in enumerate( + zip(inputs.states, systems, positions, topologies) + ) + ) + + @abstractmethod + def _equilibrate_state( + self, + *, + state_input: EquilibrationEntry, + output_dir: Path, + scratch_dir: Path, + dry: bool, + verbose: bool, + **state_kwargs: Any, + ) -> dict[str, Any]: + """Equilibrate one state using protocol-specific physics and settings. + + ``run()`` forwards protocol-specific keyword arguments to this hook. + Concrete subclasses should declare those arguments explicitly so + misspellings raise TypeError. The base adds the authoritative index. + """ + + def _output_dir( + self, *, state_input: EquilibrationEntry, n_entries: int, basepath: Path + ) -> Path: + """Use legacy root for PlainMD; isolate files for multiple states.""" + return basepath if n_entries == 1 else basepath / f"state_{state_input.index:03d}" + + def run( + self, + *, + equilibration_inputs: EquilibrationInputs, + dry: bool = False, + verbose: bool = True, + scratch_basepath: Path | None = None, + shared_basepath: Path | None = None, + **state_kwargs: Any, + ) -> dict[str, Any]: + """Equilibrate resolved in-memory inputs. + + For direct calls, pass ``EquilibrationInputs`` holding OpenMM objects, + not upstream GUFE ``ProtocolUnitResult`` objects. Each protocol + subclass's ``_execute()`` loads its own upstream artifacts, checks + the execution environment, and calls this method. + + Additional keyword arguments are forwarded unchanged to the concrete + ``_equilibrate_state()``. For PlainMD these are the validated NVT and + NPT step counts supplied by the setup unit. Concrete hooks should + declare these explicitly rather than swallowing arbitrary keywords. + """ + scratch_basepath = Path(".") if scratch_basepath is None else Path(scratch_basepath) + shared_basepath = Path(".") if shared_basepath is None else Path(shared_basepath) + entries = self._normalise_inputs(equilibration_inputs) + + outputs = [] + for state_input in entries: + output_dir = self._output_dir( + state_input=state_input, n_entries=len(entries), basepath=shared_basepath + ) + scratch_dir = self._output_dir( + state_input=state_input, n_entries=len(entries), basepath=scratch_basepath + ) + output_dir.mkdir(parents=True, exist_ok=True) + scratch_dir.mkdir(parents=True, exist_ok=True) + result = self._equilibrate_state( + state_input=state_input, + output_dir=output_dir, + scratch_dir=scratch_dir, + dry=dry, + verbose=verbose, + **state_kwargs, + ) + outputs.append({**result, "index": state_input.index}) + + return {"equilibrated_states": outputs} diff --git a/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py b/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py index 20d6f9c7d..deb6242da 100644 --- a/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py +++ b/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py @@ -23,6 +23,7 @@ from openfe.protocols.openmm_md.plain_md_methods import ( PlainMDProtocol, PlainMDProtocolResult, + PlainMDEquilibrationUnit, PlainMDSetupUnit, PlainMDSimulationUnit, ) @@ -33,7 +34,7 @@ HAS_OPENEYE, ) from openfe.tests.conftest import HAS_ESPALOMA - +from openfe.protocols.openmm_utils.base_equilibration import EquilibrationInputs @pytest.fixture() def vac_settings(): @@ -44,22 +45,30 @@ def vac_settings(): @pytest.mark.parametrize( - "inputs, expected", + "current_step_count, expected", [ - # inputs are current step count, nvt steps, npt steps and prod steps - # outputs are steps to run for nvt, npt, prod and if the production phase has started - pytest.param([50, 100, 100, 100], [50, 100, 100, False], id="nvt resuming"), - pytest.param([101, 100, 100, 100], [0, 99, 100, False], id="npt resuming"), - pytest.param([220, 100, 100, 100], [0, 0, 80, True], id="prod resuming"), - pytest.param([200, 100, 100, 100], [0, 0, 100, False], id="prod resuming not started"), + (200, 100), # production has not started + (220, 80), # 20 production steps completed + (300, 0), # production is complete ], ) -def test_get_remaining_steps(inputs, expected): - nvt, npt, prod, is_prod = PlainMDSimulationUnit._get_remaining_steps(*inputs) - assert nvt == expected[0] - assert npt == expected[1] - assert prod == expected[2] - assert is_prod == expected[3] +def test_get_remaining_production_steps(current_step_count, expected): + remaining = PlainMDSimulationUnit._get_remaining_production_steps( + current_step_count=current_step_count, + equilibration_end_step=200, + prod_steps=100, + ) + assert remaining == expected + + +@pytest.mark.parametrize("current_step_count", [199, 301]) +def test_get_remaining_production_steps_outside_interval(current_step_count): + with pytest.raises(ValueError, match="outside the production interval"): + PlainMDSimulationUnit._get_remaining_production_steps( + current_step_count=current_step_count, + equilibration_end_step=200, + prod_steps=100, + ) def test_create_default_settings(): @@ -114,7 +123,7 @@ def test_create_independent_repeat_ids(benzene_system): ) repeat_ids = set() - u: PlainMDSetupUnit | PlainMDSimulationUnit + u: PlainMDSetupUnit | PlainMDEquilibrationUnit | PlainMDSimulationUnit for u in dag1.protocol_units: repeat_ids.add(u.inputs["repeat_id"]) for u in dag2.protocol_units: @@ -151,6 +160,22 @@ def test_dry_run_default_vacuum(benzene_vacuum_system, vac_settings, tmp_path): ) +def test_three_unit_dag(benzene_vacuum_system, vac_settings): + protocol = PlainMDProtocol(settings=vac_settings) + dag = protocol.create( + stateA=benzene_vacuum_system, + stateB=benzene_vacuum_system, + mapping=None, + ) + setup, equil, production = list(dag.protocol_units) + assert isinstance(setup, PlainMDSetupUnit) + assert isinstance(equil, PlainMDEquilibrationUnit) + assert isinstance(production, PlainMDSimulationUnit) + assert equil.inputs["setup_results"] == setup + assert production.inputs["setup_results"] == setup + assert production.inputs["equilibration_results"] == equil + + def test_dry_run_logger_output(benzene_vacuum_system, vac_settings, tmp_path, caplog): vac_settings.simulation_settings.equilibration_length_nvt = 1 * unit.picosecond vac_settings.simulation_settings.equilibration_length = 1 * unit.picosecond @@ -166,7 +191,12 @@ def test_dry_run_logger_output(benzene_vacuum_system, vac_settings, tmp_path, ca stateB=benzene_vacuum_system, mapping=None, ) - setup_unit = list(dag.protocol_units)[0] + setup_unit, equil_unit, prod_unit = list(dag.protocol_units) + setup_path = tmp_path / "setup" + equil_path = tmp_path / "equilibration" + prod_path = tmp_path / "production" + for path in (setup_path, equil_path, prod_path): + path.mkdir() caplog.set_level(logging.INFO) setup_results = setup_unit.run( @@ -175,26 +205,40 @@ def test_dry_run_logger_output(benzene_vacuum_system, vac_settings, tmp_path, ca messages = [r.message for r in caplog.records] assert "Creating system" in messages - # now run the production unit after extracting outputs from the setup unit + + # Equilibration owns minimization, NVT and NPT. system = serialization.deserialize(setup_results["system"]) positions = np.load(setup_results["positions"]) * omm_unit.nanometers - topology = openmm.app.PDBFile(str(setup_results["system_pdb"])).getTopology() - equil_steps_nvt = setup_results["equil_steps_nvt"] - equil_steps_npt = setup_results["equil_steps_npt"] - prod_steps = setup_results["prod_steps"] - prod_unit = list(dag.protocol_units)[1] - prod_unit.run( - system=system, - positions=positions, + topology = openmm.app.PDBFile( + str(setup_results["system_pdb"])).getTopology() + equil_results = equil_unit.run( + equilibration_inputs=EquilibrationInputs( + states=[None], systems=system, positions=positions, + topologies=topology, + ), + equil_steps_nvt=setup_results["equil_steps_nvt"] or 0, + equil_steps_npt=setup_results["equil_steps_npt"], + verbose=True, + scratch_basepath=equil_path, shared_basepath=equil_path, + ) + equilibrated = equil_results["equilibrated_states"][0] + assert equilibrated["equilibrated_state"].exists() + assert equilibrated["equilibration_end_step"] == 500 + + # Production builds a fresh Context from the original setup System. + prod_results = prod_unit.run( + system=serialization.deserialize(setup_results["system"]), topology=topology, - equil_steps_nvt=equil_steps_nvt, - equil_steps_npt=equil_steps_npt, - prod_steps=prod_steps, - dry=False, + equilibrated_state=equilibrated["equilibrated_state"], + equilibration_end_step=equilibrated["equilibration_end_step"], + prod_steps=setup_results["prod_steps"], + reinitialize_velocities_for_production=equilibrated[ + "reinitialize_velocities_for_production" + ], verbose=True, - scratch_basepath=tmp_path, - shared_basepath=tmp_path, + scratch_basepath=prod_path, shared_basepath=prod_path, ) + assert prod_results["nc"].exists() messages = [r.message for r in caplog.records] assert "Minimizing systems" in messages assert "Running NVT equilibration for 250 steps" in messages @@ -610,8 +654,21 @@ def test_unit_tagging(benzene_system, tmp_path): def test_gather(solvent_protocol_dag, tmp_path): - # check .gather behaves as expected + # Mock dynamics in both units; exercise the three-unit GUFE DAG. with mock.patch( + "openfe.protocols.openmm_md.plain_md_methods.PlainMDEquilibrationUnit.run", + return_value={ + "equilibrated_states": [{ + "index": 0, + "equilibrated_state": tmp_path / "equilibrated_state.xml", + "equilibration_end_step": 0, + "reinitialize_velocities_for_production": True, + "minimized_pdb": None, + "nvt_equil_pdb": None, + "npt_equil_pdb": None, + }], + }, + ), mock.patch( "openfe.protocols.openmm_md.plain_md_methods.PlainMDSimulationUnit.run", return_value={ "nc": "simulation.xtc", diff --git a/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py b/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py index 34f44a89d..3ce32e28b 100644 --- a/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py +++ b/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py @@ -17,8 +17,11 @@ from openfe.protocols.openmm_md.plain_md_methods import ( PlainMDProtocol, PlainMDSetupUnit, + PlainMDEquilibrationUnit, PlainMDSimulationUnit, ) +from openfe.protocols.openmm_utils import serialization +from openfe.protocols.openmm_utils.base_equilibration import EquilibrationInputs from ...conftest import HAS_INTERNET @@ -91,6 +94,42 @@ def test_check_restart(vacuum_protocol_settings, plain_md_checkpoint_path): ) +@pytest.mark.parametrize( + "step, remaining", + [ + (0, (250, 250)), + (125, (125, 250)), # partial NVT + (250, (0, 250)), # exactly at NVT/NPT boundary + (375, (0, 125)), # partial NPT + (500, (0, 0)), # equilibration complete + ], +) +def test_remaining_equilibration_steps(step, remaining): + assert PlainMDEquilibrationUnit._get_remaining_equilibration_steps( + current_step_count=step, + equil_steps_nvt=250, + equil_steps_npt=250, + ) == remaining + + +@pytest.mark.parametrize("step", [-1, 501, 625]) +def test_invalid_equilibration_checkpoint_step(step): + with pytest.raises(ValueError, match="outside the equilibration interval"): + PlainMDEquilibrationUnit._get_remaining_equilibration_steps( + current_step_count=step, + equil_steps_nvt=250, + equil_steps_npt=250, + ) + + +def test_remaining_equilibration_without_nvt(): + assert PlainMDEquilibrationUnit._get_remaining_equilibration_steps( + current_step_count=125, + equil_steps_nvt=0, + equil_steps_npt=250, + ) == (0, 125) + + @pytest.mark.skipif( not os.path.exists(POOCH_CACHE) and not HAS_INTERNET, reason="Internet unavailable and test data is not cached locally", @@ -108,60 +147,164 @@ def protocol_dag(self, vacuum_protocol_settings, benzene_vacuum_system): def test_resume( self, protocol_dag, tmp_path, caplog, vacuum_protocol_settings, plain_md_checkpoint_path ): - # test that we can resume a simulation from a checkpoint - protocol_units = list(protocol_dag.protocol_units) - setup_unit: PlainMDSetupUnit = protocol_units[0] - simulation_unit: PlainMDSimulationUnit = protocol_units[1] - # copy the files over - shutil.copyfile(plain_md_checkpoint_path, tmp_path / "checkpoint.xml") + setup_unit, equil_unit, simulation_unit = list(protocol_dag.protocol_units) + assert isinstance(setup_unit, PlainMDSetupUnit) + assert isinstance(equil_unit, PlainMDEquilibrationUnit) + assert isinstance(simulation_unit, PlainMDSimulationUnit) + + setup_path = tmp_path / "setup" + equil_path = tmp_path / "equilibration" + prod_path = tmp_path / "production" + for path in (setup_path, equil_path, prod_path): + path.mkdir() + # dry run the setup unit setup_results = setup_unit.run( dry=True, scratch_basepath=tmp_path, shared_basepath=tmp_path ) - # make sure the protocol thinks it can restart + equil_results = equil_unit.run( + equilibration_inputs=EquilibrationInputs( + states=[None], + systems=serialization.deserialize(setup_results["system"]), + positions=setup_results["debug"]["positions"], + topologies=setup_results["debug"]["topology"], + ), + equil_steps_nvt=setup_results["equil_steps_nvt"] or 0, + equil_steps_npt=setup_results["equil_steps_npt"], + scratch_basepath=equil_path, + shared_basepath=equil_path, + ) + equilibrated = equil_results["equilibrated_states"][0] + assert equilibrated["equilibration_end_step"] == 500 + # Create a genuine production checkpoint at 2.5 ps (625 steps): + # the equilibrated XML State contributes the first 500 steps, then + # we simulate 125 of the 250 production steps. + checkpoint = prod_path / vacuum_protocol_settings.output_settings.checkpoint_storage_filename + partial = openmm.app.Simulation( + setup_results["debug"]["topology"], + serialization.deserialize(setup_results["system"]), + openmm.LangevinMiddleIntegrator( + 298.15 * openmm_unit.kelvin, + 1.0 / openmm_unit.picosecond, + 4 * openmm_unit.femtoseconds, + ), + ) + partial.loadState(str(equilibrated["equilibrated_state"])) + partial.step(125) + partial.saveState(str(checkpoint)) + assert partial.context.getStepCount() == 625 + del partial + assert PlainMDSimulationUnit._check_restart( output_settings=vacuum_protocol_settings.output_settings, - shared_path=tmp_path, + shared_path=prod_path, ) - # now run the simulation unit in resume mode this should be 0.5 ps of equilibration and 1 ps of production + + caplog.set_level(logging.INFO) sim_results = simulation_unit.run( - system=setup_results["debug"]["system"], - positions=setup_results["debug"]["positions"], + system=serialization.deserialize(setup_results["system"]), topology=setup_results["debug"]["topology"], - equil_steps_nvt=setup_results["equil_steps_nvt"], - equil_steps_npt=setup_results["equil_steps_npt"], + equilibrated_state=equilibrated["equilibrated_state"], + equilibration_end_step=equilibrated["equilibration_end_step"], prod_steps=setup_results["prod_steps"], + reinitialize_velocities_for_production=equilibrated[ + "reinitialize_velocities_for_production" + ], verbose=True, - scratch_basepath=tmp_path, - shared_basepath=tmp_path, + scratch_basepath=prod_path, + shared_basepath=prod_path, ) - # make sure it prints that its restarting assert "Restarting simulation from checkpoint state" in caplog.text - # check the number of npt steps to run is correct, this should be 0.5 ps at 4fs timestep - assert "Running NPT equilibration for 125 steps" in caplog.text - # make sure the production phase steps are correct, this should be the full 1ps at 4fs timestep - assert "Running production phase for 250 steps" in caplog.text - - # check the outputs of the simulation unit - assert sim_results["system_pdb"].exists() + assert "Running production phase for 125 steps" in caplog.text + assert "Running NPT equilibration" not in caplog.text assert sim_results["nc"].exists() - assert sim_results["last_checkpoint"] + assert sim_results["last_checkpoint"] is not None + assert sim_results["last_checkpoint"].exists() - # load the final checkpoint and check the simulation time is correct, this should be 3 ps - # also check the total step count - simulation = openmm.app.Simulation( + # The final checkpoint should contain the total 3 ps, 750 steps. + final = openmm.app.Simulation( setup_results["debug"]["topology"], - setup_results["debug"]["system"], + serialization.deserialize(setup_results["system"]), openmm.LangevinMiddleIntegrator( 298.15 * openmm_unit.kelvin, 1.0 / openmm_unit.picosecond, 4 * openmm_unit.femtoseconds, ), ) - simulation.context.setPositions(setup_results["debug"]["positions"]) - simulation.loadState(str(sim_results["last_checkpoint"])) - total_sim_time = simulation.context.getTime() - # check the time is 3 ps - assert total_sim_time.value_in_unit(openmm_unit.picoseconds) == pytest.approx(3) - # check the step count has been extended - assert simulation.context.getStepCount() == 750 + final.loadState(str(sim_results["last_checkpoint"])) + assert final.context.getTime().value_in_unit(openmm_unit.picoseconds) == pytest.approx(3) + assert final.context.getStepCount() == 750 + del final + + +@pytest.mark.skipif( + not os.path.exists(POOCH_CACHE) and not HAS_INTERNET, + reason="Internet unavailable and test data is not cached locally", +) +def test_resume_equilibration_from_npt_checkpoint( + vacuum_protocol_settings, benzene_vacuum_system, + plain_md_checkpoint_path, tmp_path, caplog, +): + """The legacy 1.5-ps checkpoint resumes NPT and ends at 2 ps. + + Unlike the production test, this intentionally uses the original + mid-equilibration checkpoint fixture. + """ + protocol = PlainMDProtocol(settings=vacuum_protocol_settings) + dag = protocol.create( + stateA=benzene_vacuum_system, + stateB=benzene_vacuum_system, + mapping=None, + ) + setup_unit, equil_unit, _ = list(dag.protocol_units) + setup_dir = tmp_path / "setup" + equil_dir = tmp_path / "equilibration" + setup_dir.mkdir() + equil_dir.mkdir() + setup = setup_unit.run( + dry=True, + scratch_basepath=setup_dir, + shared_basepath=setup_dir, + ) + + checkpoint_name = vacuum_protocol_settings.output_settings.checkpoint_storage_filename + shutil.copyfile(plain_md_checkpoint_path, equil_dir / checkpoint_name) + + caplog.set_level(logging.INFO) + result = equil_unit.run( + equilibration_inputs=EquilibrationInputs( + states=[None], + systems=serialization.deserialize(setup["system"]), + positions=setup["debug"]["positions"], + topologies=setup["debug"]["topology"], + ), + equil_steps_nvt=setup["equil_steps_nvt"] or 0, + equil_steps_npt=setup["equil_steps_npt"], + shared_basepath=equil_dir, + scratch_basepath=equil_dir, + ) + state = result["equilibrated_states"][0] + + assert "Restarting simulation from checkpoint state" in caplog.text + assert "Minimizing systems" not in caplog.text + assert "Running NVT equilibration" not in caplog.text + assert "Running NPT equilibration for 125 steps" in caplog.text + assert state["equilibration_end_step"] == 500 + assert state["equilibrated_state"].is_file() + assert state["reinitialize_velocities_for_production"] is False + + final = openmm.app.Simulation( + setup["debug"]["topology"], + serialization.deserialize(setup["system"]), + openmm.LangevinMiddleIntegrator( + 298.15 * openmm_unit.kelvin, + 1.0 / openmm_unit.picosecond, + 4 * openmm_unit.femtoseconds, + ), + ) + final.loadState(str(state["equilibrated_state"])) + assert final.context.getStepCount() == 500 + assert final.context.getTime().value_in_unit( + openmm_unit.picoseconds + ) == pytest.approx(2) + del final diff --git a/src/openfe/tests/protocols/test_base_equilibration.py b/src/openfe/tests/protocols/test_base_equilibration.py new file mode 100644 index 000000000..7eded4ba3 --- /dev/null +++ b/src/openfe/tests/protocols/test_base_equilibration.py @@ -0,0 +1,138 @@ +# This code is part of OpenFE and is licensed under the MIT license. +"""Tests for the shared equilibration runner (no OpenMM integration needed).""" + +from pathlib import Path + +import pytest + +from openfe.protocols.openmm_utils.base_equilibration import ( + BaseEquilibrationUnit, + EquilibrationInputs, +) + + +class RecordingUnit: + """Exercise concrete BaseEquilibrationUnit methods without a GUFE DAG. + + The real GUFE constructor requires serializable ProtocolUnit inputs; this + harness tests the base runner's in-memory inputs independently. + """ + + _normalise_inputs = BaseEquilibrationUnit._normalise_inputs + _output_dir = BaseEquilibrationUnit._output_dir + run = BaseEquilibrationUnit.run + + def __init__(self): + self.calls = [] + + def _equilibrate_state( + self, *, state_input, output_dir, scratch_dir, dry, verbose, + equil_steps_nvt, equil_steps_npt, + ): + self.calls.append({ + "state_input": state_input, + "output_dir": output_dir, + "scratch_dir": scratch_dir, + "dry": dry, + "verbose": verbose, + "nvt": equil_steps_nvt, + "npt": equil_steps_npt, + }) + return {"index": 999, "state_path": output_dir / "equilibrated_state.xml"} + + +def _inputs(n=1, **overrides): + values = dict( + states=list(range(n)), + systems=object(), + positions=object(), + topologies=object(), + ) + values.update(overrides) + return EquilibrationInputs(**values) + + +def test_one_state_preserves_plainmd_root_directories(tmp_path): + unit = RecordingUnit() + result = unit.run( + equilibration_inputs=_inputs(), + equil_steps_nvt=0, + equil_steps_npt=2, + dry=True, + verbose=False, + scratch_basepath=tmp_path / "scratch", + shared_basepath=tmp_path / "shared", + ) + assert unit.calls[0]["output_dir"] == tmp_path / "shared" + assert unit.calls[0]["scratch_dir"] == tmp_path / "scratch" + assert unit.calls[0]["dry"] is True + assert unit.calls[0]["verbose"] is False + assert (tmp_path / "scratch").is_dir() + assert (tmp_path / "shared").is_dir() + assert result["equilibrated_states"][0]["index"] == 0 # authoritative + + +def test_multiple_states_use_separate_paths_and_broadcast_scalars(tmp_path): + system, positions, topology = object(), object(), object() + unit = RecordingUnit() + result = unit.run( + equilibration_inputs=_inputs( + 2, systems=system, positions=positions, topologies=topology, + ), + equil_steps_nvt=3, + equil_steps_npt=5, + shared_basepath=tmp_path / "shared", + scratch_basepath=tmp_path / "scratch", + ) + assert [x["index"] for x in result["equilibrated_states"]] == [0, 1] + for i, call in enumerate(unit.calls): + assert call["state_input"].system is system + assert call["state_input"].positions is positions + assert call["state_input"].topology is topology + assert call["output_dir"] == tmp_path / "shared" / f"state_{i:03d}" + assert call["scratch_dir"] == tmp_path / "scratch" / f"state_{i:03d}" + assert call["nvt"] == 3 and call["npt"] == 5 + assert call["output_dir"].is_dir() and call["scratch_dir"].is_dir() + + +def test_per_state_sequence_inputs_are_aligned(): + systems, positions, topologies = [object(), object()], [object(), object()], [object(), object()] + entries = BaseEquilibrationUnit._normalise_inputs( + _inputs(2, systems=systems, positions=positions, topologies=topologies) + ) + for i, entry in enumerate(entries): + assert entry.index == i + assert entry.system is systems[i] + assert entry.positions is positions[i] + assert entry.topology is topologies[i] + + +@pytest.mark.parametrize("field", ["systems", "positions", "topologies"]) +@pytest.mark.parametrize("n_values", [0, 1, 3]) +def test_sequence_length_must_match_states(field, n_values): + with pytest.raises(ValueError, match=rf"{field} must contain 2 entries"): + BaseEquilibrationUnit._normalise_inputs( + _inputs(2, **{field: [object() for _ in range(n_values)]}) + ) + + +@pytest.mark.parametrize("states", [[], (), "one", None]) +def test_states_must_be_nonempty_list_or_tuple(states): + with pytest.raises(ValueError, match="non-empty list or tuple"): + BaseEquilibrationUnit._normalise_inputs(_inputs(states=states)) + + +def test_normalization_requires_equilibration_inputs(): + with pytest.raises(TypeError, match="EquilibrationInputs"): + BaseEquilibrationUnit._normalise_inputs({"states": [None]}) + + +def test_unknown_protocol_specific_keyword_is_rejected(tmp_path): + unit = RecordingUnit() + with pytest.raises(TypeError, match="equil_step_nvt"): + unit.run( + equilibration_inputs=_inputs(), + equil_step_nvt=2, # typo + equil_steps_npt=4, + shared_basepath=tmp_path, + ) From cf6e01f7533885d4d77e98f1769cc2116a1996c0 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:28:38 +0000 Subject: [PATCH 2/8] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../protocols/openmm_md/plain_md_methods.py | 132 ++++++++---------- .../openmm_utils/base_equilibration.py | 17 +-- .../openmm_md/test_plain_md_protocol.py | 65 +++++---- .../openmm_md/test_plain_md_resume.py | 30 ++-- .../protocols/test_base_equilibration.py | 42 ++++-- 5 files changed, 148 insertions(+), 138 deletions(-) diff --git a/src/openfe/protocols/openmm_md/plain_md_methods.py b/src/openfe/protocols/openmm_md/plain_md_methods.py index c076da75b..c62b308b2 100644 --- a/src/openfe/protocols/openmm_md/plain_md_methods.py +++ b/src/openfe/protocols/openmm_md/plain_md_methods.py @@ -58,7 +58,9 @@ system_validation, ) from openfe.protocols.openmm_utils.base_equilibration import ( - BaseEquilibrationUnit, EquilibrationEntry, EquilibrationInputs, + BaseEquilibrationUnit, + EquilibrationEntry, + EquilibrationInputs, ) from openfe.protocols.openmm_utils.offmolecule_utils import ( _get_offmol_metadata, @@ -356,9 +358,9 @@ def _verify_execution_environment( """ try: if ( - (gufe.__version__ != setup_outputs["gufe_version"]) - or (openfe.__version__ != setup_outputs["openfe_version"]) - or (openmm.__version__ != setup_outputs["openmm_version"]) + (gufe.__version__ != setup_outputs["gufe_version"]) + or (openfe.__version__ != setup_outputs["openfe_version"]) + or (openmm.__version__ != setup_outputs["openmm_version"]) ): errmsg = "Python environment has changed, cannot continue Protocol execution." raise ProtocolUnitExecutionError(errmsg) @@ -407,8 +409,7 @@ def _run_dynamics( # only set the velocities to temperature if we are not restarting this section if reinitialize_velocities: # set the velocities to temperature - simulation.context.setVelocitiesToTemperature( - to_openmm(temperature)) + simulation.context.setVelocitiesToTemperature(to_openmm(temperature)) # Setup the barostat for x in simulation.context.getSystem().getForces(): @@ -432,10 +433,10 @@ def _run_dynamics( @staticmethod def _get_remaining_steps( - current_step_count: int, - equil_steps_nvt: int, - equil_steps_npt: int, - prod_steps: int, + current_step_count: int, + equil_steps_nvt: int, + equil_steps_npt: int, + prod_steps: int, ) -> tuple[int, int, int, bool]: """ Work out the remaining steps for each phase of the simulation based on the current step count, @@ -482,9 +483,7 @@ def _create_simulation( integrator_settings = protocol_settings.integrator_settings engine_settings = protocol_settings.engine_settings - restrict_cpu = ( - forcefield_settings.nonbonded_method.lower() == "nocutoff" - ) + restrict_cpu = forcefield_settings.nonbonded_method.lower() == "nocutoff" platform = omm_compute.get_openmm_platform( platform_name=engine_settings.compute_platform, gpu_device_index=engine_settings.gpu_device_index, @@ -525,19 +524,19 @@ def _add_checkpoint_reporter( @staticmethod def _run_MD( - simulation: openmm.app.Simulation, - positions: omm_unit.Quantity, - simulation_settings: MDSimulationSettings, - output_settings: MDOutputSettings, - temperature: KelvinQuantity, - barostat_frequency: Quantity, - timestep: FemtosecondQuantity, - equil_steps_nvt: int | None, - equil_steps_npt: int, - prod_steps: int, - verbose: bool = True, - shared_basepath: pathlib.Path | None = None, - restart: bool = False, + simulation: openmm.app.Simulation, + positions: omm_unit.Quantity, + simulation_settings: MDSimulationSettings, + output_settings: MDOutputSettings, + temperature: KelvinQuantity, + barostat_frequency: Quantity, + timestep: FemtosecondQuantity, + equil_steps_nvt: int | None, + equil_steps_npt: int, + prod_steps: int, + verbose: bool = True, + shared_basepath: pathlib.Path | None = None, + restart: bool = False, ) -> None: """ Energy minimization, Equilibration and Production MD to be reused @@ -602,8 +601,7 @@ def _run_MD( if restart: if verbose: logger.info("Restarting simulation from checkpoint state") - simulation.loadState( - str(shared_basepath / output_settings.checkpoint_storage_filename)) + simulation.loadState(str(shared_basepath / output_settings.checkpoint_storage_filename)) # workout the number of steps to run in each phase based on the current simulation step count current_step_count = simulation.context.getStepCount() @@ -624,8 +622,7 @@ def _run_MD( if verbose: logger.info("Minimizing systems") - simulation.minimizeEnergy( - maxIterations=simulation_settings.minimization_steps) + simulation.minimizeEnergy(maxIterations=simulation_settings.minimization_steps) if output_settings.minimized_structure: PlainMDUnitMixin._save_pdb_subset( # was PlainMDSimulationUnit @@ -638,8 +635,7 @@ def _run_MD( if output_settings.checkpoint_storage_filename: simulation.reporters.append( openmm.app.CheckpointReporter( - file=str( - shared_basepath / output_settings.checkpoint_storage_filename), + file=str(shared_basepath / output_settings.checkpoint_storage_filename), reportInterval=checkpoint_interval, writeState=True, # writes portable XML via simulation.saveState() @@ -650,8 +646,7 @@ def _run_MD( # NVT equilibration if equil_steps_nvt > 0: if verbose: - logger.info( - f"Running NVT equilibration for {equil_steps_nvt} steps") + logger.info(f"Running NVT equilibration for {equil_steps_nvt} steps") # setup the output path if we have one for the nvt equilibration if output_settings.equil_nvt_structure is not None: output_path = shared_basepath / output_settings.equil_nvt_structure @@ -674,8 +669,7 @@ def _run_MD( # NPT equilibration if equil_steps_npt > 0: if verbose: - logger.info( - f"Running NPT equilibration for {equil_steps_npt} steps") + logger.info(f"Running NPT equilibration for {equil_steps_npt} steps") # setup the output path if we have one for the npt equilibration if output_settings.equil_npt_structure is not None: output_path = shared_basepath / output_settings.equil_npt_structure @@ -709,13 +703,11 @@ def _run_MD( if output_settings.production_trajectory_filename: # Get the sub selection of the system to save coords for - selection_indices = mdtraj.Topology.from_openmm( - simulation.topology).select( + selection_indices = mdtraj.Topology.from_openmm(simulation.topology).select( output_settings.output_indices ) xtc_reporter = XTCReporter( - file=str( - shared_basepath / output_settings.production_trajectory_filename), + file=str(shared_basepath / output_settings.production_trajectory_filename), reportInterval=write_interval, atomSubset=selection_indices, # append to the trajectory if restarting and we have run the production stage before @@ -1049,7 +1041,7 @@ def _execute( @staticmethod def _get_remaining_equilibration_steps( - *, current_step_count: int, equil_steps_nvt: int, equil_steps_npt: int + *, current_step_count: int, equil_steps_nvt: int, equil_steps_npt: int ) -> tuple[int, int]: """Return NVT and NPT steps left from an equilibration checkpoint. @@ -1114,8 +1106,7 @@ def _equilibrate_state( simulation.context.setPositions(state_input.positions) if verbose: logger.info("Minimizing systems") - simulation.minimizeEnergy( - maxIterations=sim_settings.minimization_steps) + simulation.minimizeEnergy(maxIterations=sim_settings.minimization_steps) if output_settings.minimized_structure: self._save_pdb_subset( simulation, @@ -1146,12 +1137,12 @@ def _equilibrate_state( nvt_path = ( output_dir / output_settings.equil_nvt_structure - if output_settings.equil_nvt_structure else None + if output_settings.equil_nvt_structure + else None ) if nvt_remaining > 0: if verbose: - logger.info( - f"Running NVT equilibration for {nvt_remaining} steps") + logger.info(f"Running NVT equilibration for {nvt_remaining} steps") self._run_dynamics( simulation=simulation, steps=nvt_remaining, @@ -1166,12 +1157,12 @@ def _equilibrate_state( npt_path = ( output_dir / output_settings.equil_npt_structure - if output_settings.equil_npt_structure else None + if output_settings.equil_npt_structure + else None ) if npt_remaining > 0: if verbose: - logger.info( - f"Running NPT equilibration for {npt_remaining} steps") + logger.info(f"Running NPT equilibration for {npt_remaining} steps") self._run_dynamics( simulation=simulation, steps=npt_remaining, @@ -1182,9 +1173,7 @@ def _equilibrate_state( output_path=npt_path, # Within NPT, preserve saved velocities. At the NVT/NPT # boundary, initialize a new NPT velocity distribution. - reinitialize_velocities=( - not restart or current_step_count <= equil_steps_nvt - ), + reinitialize_velocities=(not restart or current_step_count <= equil_steps_nvt), ) state_path = output_dir / "equilibrated_state.xml" @@ -1195,14 +1184,16 @@ def _equilibrate_state( minimized_path = ( output_dir / output_settings.minimized_structure - if output_settings.minimized_structure else None + if output_settings.minimized_structure + else None ) return { "equilibrated_state": state_path, "equilibration_end_step": simulation.context.getStepCount(), "reinitialize_velocities_for_production": equil_steps_npt == 0, "minimized_pdb": ( - minimized_path if minimized_path is not None and minimized_path.is_file() + minimized_path + if minimized_path is not None and minimized_path.is_file() else None ), "nvt_equil_pdb": nvt_path if nvt_path is not None and nvt_path.is_file() else None, @@ -1249,8 +1240,7 @@ def _check_restart(output_settings: MDOutputSettings, shared_path: pathlib.Path) @staticmethod def _get_remaining_production_steps( - *, current_step_count: int, equilibration_end_step: int, - prod_steps: int + *, current_step_count: int, equilibration_end_step: int, prod_steps: int ) -> int: """Steps left after loading either the equilibration State or a checkpoint. @@ -1370,10 +1360,7 @@ def run( mc_steps=1, ) checkpoint_name = output_settings.checkpoint_storage_filename - checkpoint_path = ( - self.shared_basepath / checkpoint_name - if checkpoint_name else None - ) + checkpoint_path = self.shared_basepath / checkpoint_name if checkpoint_name else None self._add_checkpoint_reporter( simulation=simulation, @@ -1382,11 +1369,12 @@ def run( ) if output_settings.production_trajectory_filename: - selection_indices = mdtraj.Topology.from_openmm( - simulation.topology).select( + selection_indices = mdtraj.Topology.from_openmm(simulation.topology).select( output_settings.output_indices ) - trajectory_path = self.shared_basepath / output_settings.production_trajectory_filename + trajectory_path = ( + self.shared_basepath / output_settings.production_trajectory_filename + ) simulation.reporters.append( XTCReporter( file=str(trajectory_path), @@ -1421,8 +1409,7 @@ def run( ) if verbose: - logger.info( - f"Running production phase for {remaining_steps} steps") + logger.info(f"Running production phase for {remaining_steps} steps") if remaining_steps: self._run_dynamics( simulation=simulation, @@ -1436,7 +1423,7 @@ def run( # handoff inherits NPT velocities, but if NPT was skipped # PlainMD traditionally initializes production velocities. reinitialize_velocities=( - not restart and reinitialize_velocities_for_production + not restart and reinitialize_velocities_for_production ), ) finally: @@ -1444,16 +1431,16 @@ def run( del integrator, simulation checkpoint_name = output_settings.checkpoint_storage_filename - checkpoint_path = ( - self.shared_basepath / checkpoint_name if checkpoint_name else None - ) + checkpoint_path = self.shared_basepath / checkpoint_name if checkpoint_name else None return { "nc": ( self.shared_basepath / output_settings.production_trajectory_filename - if output_settings.production_trajectory_filename else None + if output_settings.production_trajectory_filename + else None ), "last_checkpoint": ( - checkpoint_path if checkpoint_path is not None and checkpoint_path.is_file() + checkpoint_path + if checkpoint_path is not None and checkpoint_path.is_file() else None ), } @@ -1472,8 +1459,7 @@ def _execute( equilibrated_states = equilibration_results.outputs["equilibrated_states"] if len(equilibrated_states) != 1 or equilibrated_states[0]["index"] != 0: - raise ValueError( - "PlainMD production expects one equilibrated state (index 0)") + raise ValueError("PlainMD production expects one equilibrated state (index 0)") equilibrated = equilibrated_states[0] # Deserialize a fresh, unmodified setup System: the equilibration unit diff --git a/src/openfe/protocols/openmm_utils/base_equilibration.py b/src/openfe/protocols/openmm_utils/base_equilibration.py index 031d9a613..84078f33d 100644 --- a/src/openfe/protocols/openmm_utils/base_equilibration.py +++ b/src/openfe/protocols/openmm_utils/base_equilibration.py @@ -14,7 +14,8 @@ import gufe import openmm -from openmm import app, unit as omm_unit +from openmm import app +from openmm import unit as omm_unit @dataclass(frozen=True) @@ -36,11 +37,7 @@ class EquilibrationInputs: states: list[Any] | tuple[Any, ...] systems: openmm.System | list[openmm.System] | tuple[openmm.System, ...] - positions: ( - omm_unit.Quantity - | list[omm_unit.Quantity] - | tuple[omm_unit.Quantity, ...] - ) + positions: omm_unit.Quantity | list[omm_unit.Quantity] | tuple[omm_unit.Quantity, ...] topologies: app.Topology | list[app.Topology] | tuple[app.Topology, ...] @@ -73,16 +70,12 @@ def _broadcast(value: Any, n_states: int, name: str) -> tuple[Any, ...]: """Broadcast a scalar or require exactly one list/tuple value per state.""" if isinstance(value, (list, tuple)): if len(value) != n_states: - raise ValueError( - f"{name} must contain {n_states} entries, received {len(value)}" - ) + raise ValueError(f"{name} must contain {n_states} entries, received {len(value)}") return tuple(value) return (value,) * n_states @classmethod - def _normalise_inputs( - cls, inputs: EquilibrationInputs - ) -> tuple[EquilibrationEntry, ...]: + def _normalise_inputs(cls, inputs: EquilibrationInputs) -> tuple[EquilibrationEntry, ...]: """Create aligned entries without copying or mutating input objects.""" if not isinstance(inputs, EquilibrationInputs): raise TypeError("equilibration_inputs must be EquilibrationInputs") diff --git a/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py b/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py index deb6242da..ea37c3168 100644 --- a/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py +++ b/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py @@ -21,20 +21,21 @@ import openfe from openfe.protocols import openmm_md from openfe.protocols.openmm_md.plain_md_methods import ( + PlainMDEquilibrationUnit, PlainMDProtocol, PlainMDProtocolResult, - PlainMDEquilibrationUnit, PlainMDSetupUnit, PlainMDSimulationUnit, ) from openfe.protocols.openmm_utils import serialization +from openfe.protocols.openmm_utils.base_equilibration import EquilibrationInputs from openfe.protocols.openmm_utils.charge_generation import ( HAS_ESPALOMA_CHARGE, HAS_NAGL, HAS_OPENEYE, ) from openfe.tests.conftest import HAS_ESPALOMA -from openfe.protocols.openmm_utils.base_equilibration import EquilibrationInputs + @pytest.fixture() def vac_settings(): @@ -48,8 +49,8 @@ def vac_settings(): "current_step_count, expected", [ (200, 100), # production has not started - (220, 80), # 20 production steps completed - (300, 0), # production is complete + (220, 80), # 20 production steps completed + (300, 0), # production is complete ], ) def test_get_remaining_production_steps(current_step_count, expected): @@ -209,17 +210,19 @@ def test_dry_run_logger_output(benzene_vacuum_system, vac_settings, tmp_path, ca # Equilibration owns minimization, NVT and NPT. system = serialization.deserialize(setup_results["system"]) positions = np.load(setup_results["positions"]) * omm_unit.nanometers - topology = openmm.app.PDBFile( - str(setup_results["system_pdb"])).getTopology() + topology = openmm.app.PDBFile(str(setup_results["system_pdb"])).getTopology() equil_results = equil_unit.run( equilibration_inputs=EquilibrationInputs( - states=[None], systems=system, positions=positions, + states=[None], + systems=system, + positions=positions, topologies=topology, ), equil_steps_nvt=setup_results["equil_steps_nvt"] or 0, equil_steps_npt=setup_results["equil_steps_npt"], verbose=True, - scratch_basepath=equil_path, shared_basepath=equil_path, + scratch_basepath=equil_path, + shared_basepath=equil_path, ) equilibrated = equil_results["equilibrated_states"][0] assert equilibrated["equilibrated_state"].exists() @@ -236,7 +239,8 @@ def test_dry_run_logger_output(benzene_vacuum_system, vac_settings, tmp_path, ca "reinitialize_velocities_for_production" ], verbose=True, - scratch_basepath=prod_path, shared_basepath=prod_path, + scratch_basepath=prod_path, + shared_basepath=prod_path, ) assert prod_results["nc"].exists() messages = [r.message for r in caplog.records] @@ -655,25 +659,30 @@ def test_unit_tagging(benzene_system, tmp_path): def test_gather(solvent_protocol_dag, tmp_path): # Mock dynamics in both units; exercise the three-unit GUFE DAG. - with mock.patch( - "openfe.protocols.openmm_md.plain_md_methods.PlainMDEquilibrationUnit.run", - return_value={ - "equilibrated_states": [{ - "index": 0, - "equilibrated_state": tmp_path / "equilibrated_state.xml", - "equilibration_end_step": 0, - "reinitialize_velocities_for_production": True, - "minimized_pdb": None, - "nvt_equil_pdb": None, - "npt_equil_pdb": None, - }], - }, - ), mock.patch( - "openfe.protocols.openmm_md.plain_md_methods.PlainMDSimulationUnit.run", - return_value={ - "nc": "simulation.xtc", - "last_checkpoint": "checkpoint.chk", - }, + with ( + mock.patch( + "openfe.protocols.openmm_md.plain_md_methods.PlainMDEquilibrationUnit.run", + return_value={ + "equilibrated_states": [ + { + "index": 0, + "equilibrated_state": tmp_path / "equilibrated_state.xml", + "equilibration_end_step": 0, + "reinitialize_velocities_for_production": True, + "minimized_pdb": None, + "nvt_equil_pdb": None, + "npt_equil_pdb": None, + } + ], + }, + ), + mock.patch( + "openfe.protocols.openmm_md.plain_md_methods.PlainMDSimulationUnit.run", + return_value={ + "nc": "simulation.xtc", + "last_checkpoint": "checkpoint.chk", + }, + ), ): dagres = gufe.protocols.execute_DAG( solvent_protocol_dag, diff --git a/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py b/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py index 3ce32e28b..d84912a14 100644 --- a/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py +++ b/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py @@ -15,9 +15,9 @@ import openfe from openfe.data._registry import POOCH_CACHE from openfe.protocols.openmm_md.plain_md_methods import ( + PlainMDEquilibrationUnit, PlainMDProtocol, PlainMDSetupUnit, - PlainMDEquilibrationUnit, PlainMDSimulationUnit, ) from openfe.protocols.openmm_utils import serialization @@ -105,11 +105,14 @@ def test_check_restart(vacuum_protocol_settings, plain_md_checkpoint_path): ], ) def test_remaining_equilibration_steps(step, remaining): - assert PlainMDEquilibrationUnit._get_remaining_equilibration_steps( - current_step_count=step, - equil_steps_nvt=250, - equil_steps_npt=250, - ) == remaining + assert ( + PlainMDEquilibrationUnit._get_remaining_equilibration_steps( + current_step_count=step, + equil_steps_nvt=250, + equil_steps_npt=250, + ) + == remaining + ) @pytest.mark.parametrize("step", [-1, 501, 625]) @@ -179,7 +182,9 @@ def test_resume( # Create a genuine production checkpoint at 2.5 ps (625 steps): # the equilibrated XML State contributes the first 500 steps, then # we simulate 125 of the 250 production steps. - checkpoint = prod_path / vacuum_protocol_settings.output_settings.checkpoint_storage_filename + checkpoint = ( + prod_path / vacuum_protocol_settings.output_settings.checkpoint_storage_filename + ) partial = openmm.app.Simulation( setup_results["debug"]["topology"], serialization.deserialize(setup_results["system"]), @@ -242,8 +247,11 @@ def test_resume( reason="Internet unavailable and test data is not cached locally", ) def test_resume_equilibration_from_npt_checkpoint( - vacuum_protocol_settings, benzene_vacuum_system, - plain_md_checkpoint_path, tmp_path, caplog, + vacuum_protocol_settings, + benzene_vacuum_system, + plain_md_checkpoint_path, + tmp_path, + caplog, ): """The legacy 1.5-ps checkpoint resumes NPT and ends at 2 ps. @@ -304,7 +312,5 @@ def test_resume_equilibration_from_npt_checkpoint( ) final.loadState(str(state["equilibrated_state"])) assert final.context.getStepCount() == 500 - assert final.context.getTime().value_in_unit( - openmm_unit.picoseconds - ) == pytest.approx(2) + assert final.context.getTime().value_in_unit(openmm_unit.picoseconds) == pytest.approx(2) del final diff --git a/src/openfe/tests/protocols/test_base_equilibration.py b/src/openfe/tests/protocols/test_base_equilibration.py index 7eded4ba3..e6a40dac7 100644 --- a/src/openfe/tests/protocols/test_base_equilibration.py +++ b/src/openfe/tests/protocols/test_base_equilibration.py @@ -26,18 +26,27 @@ def __init__(self): self.calls = [] def _equilibrate_state( - self, *, state_input, output_dir, scratch_dir, dry, verbose, - equil_steps_nvt, equil_steps_npt, + self, + *, + state_input, + output_dir, + scratch_dir, + dry, + verbose, + equil_steps_nvt, + equil_steps_npt, ): - self.calls.append({ - "state_input": state_input, - "output_dir": output_dir, - "scratch_dir": scratch_dir, - "dry": dry, - "verbose": verbose, - "nvt": equil_steps_nvt, - "npt": equil_steps_npt, - }) + self.calls.append( + { + "state_input": state_input, + "output_dir": output_dir, + "scratch_dir": scratch_dir, + "dry": dry, + "verbose": verbose, + "nvt": equil_steps_nvt, + "npt": equil_steps_npt, + } + ) return {"index": 999, "state_path": output_dir / "equilibrated_state.xml"} @@ -77,7 +86,10 @@ def test_multiple_states_use_separate_paths_and_broadcast_scalars(tmp_path): unit = RecordingUnit() result = unit.run( equilibration_inputs=_inputs( - 2, systems=system, positions=positions, topologies=topology, + 2, + systems=system, + positions=positions, + topologies=topology, ), equil_steps_nvt=3, equil_steps_npt=5, @@ -96,7 +108,11 @@ def test_multiple_states_use_separate_paths_and_broadcast_scalars(tmp_path): def test_per_state_sequence_inputs_are_aligned(): - systems, positions, topologies = [object(), object()], [object(), object()], [object(), object()] + systems, positions, topologies = ( + [object(), object()], + [object(), object()], + [object(), object()], + ) entries = BaseEquilibrationUnit._normalise_inputs( _inputs(2, systems=systems, positions=positions, topologies=topologies) ) From 13209b321544c038f80757bf1affc267c3428cdc Mon Sep 17 00:00:00 2001 From: hannahbaumann Date: Thu, 26 Nov 2026 16:34:41 +0100 Subject: [PATCH 3/8] Fix mypy --- src/openfe/protocols/openmm_md/plain_md_methods.py | 14 ++++++++++++-- .../protocols/openmm_md/test_plain_md_resume.py | 2 +- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/openfe/protocols/openmm_md/plain_md_methods.py b/src/openfe/protocols/openmm_md/plain_md_methods.py index c076da75b..1e8945e64 100644 --- a/src/openfe/protocols/openmm_md/plain_md_methods.py +++ b/src/openfe/protocols/openmm_md/plain_md_methods.py @@ -1076,8 +1076,9 @@ def _equilibrate_state( scratch_dir: pathlib.Path, dry: bool, verbose: bool, - equil_steps_nvt: int, - equil_steps_npt: int, + equil_steps_nvt: int | None = None, + equil_steps_npt: int | None = None, + **state_kwargs: Any, ) -> dict[str, Any]: """Minimize and equilibrate, resuming NVT or NPT when possible. @@ -1086,6 +1087,15 @@ def _equilibrate_state( NVT reinitializes velocities as in the original PlainMD implementation. The production unit manages its own checkpoint separately. """ + if state_kwargs: + raise TypeError( + f"Unexpected equilibration arguments: {', '.join(state_kwargs)}" + ) + + if equil_steps_nvt is None or equil_steps_npt is None: + raise TypeError( + "equil_steps_nvt and equil_steps_npt must be provided" + ) self._prepare(verbose, scratch_dir, output_dir) protocol_settings: PlainMDProtocolSettings = self._inputs["protocol"].settings diff --git a/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py b/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py index 3ce32e28b..eb3f0b02d 100644 --- a/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py +++ b/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py @@ -1,5 +1,6 @@ # This code is part of OpenFE and is licensed under the MIT license. # For details, see https://github.com/OpenFreeEnergy/openfe +import logging import os import pathlib import shutil @@ -8,7 +9,6 @@ import openmm import openmm.unit as openmm_unit import pytest -from gufe import ChemicalSystem, SmallMoleculeComponent from gufe.protocols.errors import ProtocolUnitExecutionError from openff.units import unit From 891b256dd91071e7944fe20e4e333d28b473d52d Mon Sep 17 00:00:00 2001 From: hannahbaumann Date: Thu, 26 Nov 2026 16:37:29 +0100 Subject: [PATCH 4/8] Some fixes --- src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py b/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py index 5f1aa693d..c19b5801e 100644 --- a/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py +++ b/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py @@ -204,7 +204,7 @@ def test_resume( output_settings=vacuum_protocol_settings.output_settings, shared_path=prod_path, ) - + caplog.clear() caplog.set_level(logging.INFO) sim_results = simulation_unit.run( system=serialization.deserialize(setup_results["system"]), From c0a429bf398b79b068b187e697b5f6cfe85a83ae Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:39:52 +0000 Subject: [PATCH 5/8] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- src/openfe/protocols/openmm_md/plain_md_methods.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/openfe/protocols/openmm_md/plain_md_methods.py b/src/openfe/protocols/openmm_md/plain_md_methods.py index 0665bb880..96e904c79 100644 --- a/src/openfe/protocols/openmm_md/plain_md_methods.py +++ b/src/openfe/protocols/openmm_md/plain_md_methods.py @@ -1080,14 +1080,10 @@ def _equilibrate_state( The production unit manages its own checkpoint separately. """ if state_kwargs: - raise TypeError( - f"Unexpected equilibration arguments: {', '.join(state_kwargs)}" - ) + raise TypeError(f"Unexpected equilibration arguments: {', '.join(state_kwargs)}") if equil_steps_nvt is None or equil_steps_npt is None: - raise TypeError( - "equil_steps_nvt and equil_steps_npt must be provided" - ) + raise TypeError("equil_steps_nvt and equil_steps_npt must be provided") self._prepare(verbose, scratch_dir, output_dir) protocol_settings: PlainMDProtocolSettings = self._inputs["protocol"].settings From d96afc6d02620eed226f7588f91949349641d2f5 Mon Sep 17 00:00:00 2001 From: hannahbaumann Date: Thu, 26 Nov 2026 16:54:37 +0100 Subject: [PATCH 6/8] some more changes --- .../protocols/openmm_md/plain_md_methods.py | 16 +- .../openmm_utils/base_equilibration.py | 115 ++++-------- .../protocols/test_base_equilibration.py | 164 +++++++++++------- 3 files changed, 141 insertions(+), 154 deletions(-) diff --git a/src/openfe/protocols/openmm_md/plain_md_methods.py b/src/openfe/protocols/openmm_md/plain_md_methods.py index 96e904c79..fd249b7c2 100644 --- a/src/openfe/protocols/openmm_md/plain_md_methods.py +++ b/src/openfe/protocols/openmm_md/plain_md_methods.py @@ -60,7 +60,6 @@ from openfe.protocols.openmm_utils.base_equilibration import ( BaseEquilibrationUnit, EquilibrationEntry, - EquilibrationInputs, ) from openfe.protocols.openmm_utils.offmolecule_utils import ( _get_offmol_metadata, @@ -1022,12 +1021,15 @@ def _execute( # Setup already validated the step counts; do not calculate them again. outputs = self.run( - equilibration_inputs=EquilibrationInputs( - states=[None], - systems=system, - positions=positions, - topologies=topology, - ), + equilibration_inputs=[ + EquilibrationEntry( + index=0, + state=None, + system=system, + positions=positions, + topology=topology, + ), + ], equil_steps_nvt=setup["equil_steps_nvt"] or 0, equil_steps_npt=setup["equil_steps_npt"], scratch_basepath=ctx.scratch, diff --git a/src/openfe/protocols/openmm_utils/base_equilibration.py b/src/openfe/protocols/openmm_utils/base_equilibration.py index 84078f33d..782dd7d8c 100644 --- a/src/openfe/protocols/openmm_utils/base_equilibration.py +++ b/src/openfe/protocols/openmm_utils/base_equilibration.py @@ -18,29 +18,6 @@ from openmm import unit as omm_unit -@dataclass(frozen=True) -class EquilibrationInputs: - """In-memory inputs resolved by a protocol-specific subclass. - - ``states`` is a nonempty list/tuple. Each of ``systems``, ``positions`` and - ``topologies`` is either a shared single value or a list/tuple with exactly - one value per state. One-element lists are *not* broadcast to many states. - - Positions must be OpenMM Quantity objects carrying length units, not - bare NumPy arrays. PlainMD converts positions.npy (stored in nm) to a - Quantity in its ``_execute()``. These are execution-time objects, not - serialized GUFE ProtocolUnit inputs. - - A topology must include every particle in its corresponding OpenMM System - in the same order. A PDB subset intended for visualization is insufficient. - """ - - states: list[Any] | tuple[Any, ...] - systems: openmm.System | list[openmm.System] | tuple[openmm.System, ...] - positions: omm_unit.Quantity | list[omm_unit.Quantity] | tuple[omm_unit.Quantity, ...] - topologies: app.Topology | list[app.Topology] | tuple[app.Topology, ...] - - @dataclass(frozen=True) class EquilibrationEntry: """Inputs for exactly one thermodynamic state, used only during execution.""" @@ -53,52 +30,16 @@ class EquilibrationEntry: class BaseEquilibrationUnit(gufe.ProtocolUnit, ABC): - """Shared iteration and file layout for protocol-specific equilibration. + """Base class for protocol-specific equilibration units. - Subclasses implement GUFE ``_execute`` to interpret upstream results and - construct ``EquilibrationInputs``. They implement ``_equilibrate_state`` - to run the appropriate protocol-specific physics. This base class only - normalizes and iterates over state inputs, organizes paths and indexes - outputs; it does not define an MD schedule or alchemical Hamiltonian. + Subclasses resolve the upstream results into equilibration + entries and implement the protocol-specific equilibration + procedure. - Broadcasting shares references; it does not copy OpenMM objects. A - subclass must not modify shared input Systems or positions in place. + This class manages iteration, directory layout and collection + of equilibration results. """ - @staticmethod - def _broadcast(value: Any, n_states: int, name: str) -> tuple[Any, ...]: - """Broadcast a scalar or require exactly one list/tuple value per state.""" - if isinstance(value, (list, tuple)): - if len(value) != n_states: - raise ValueError(f"{name} must contain {n_states} entries, received {len(value)}") - return tuple(value) - return (value,) * n_states - - @classmethod - def _normalise_inputs(cls, inputs: EquilibrationInputs) -> tuple[EquilibrationEntry, ...]: - """Create aligned entries without copying or mutating input objects.""" - if not isinstance(inputs, EquilibrationInputs): - raise TypeError("equilibration_inputs must be EquilibrationInputs") - if not isinstance(inputs.states, (list, tuple)) or not inputs.states: - raise ValueError("states must be a non-empty list or tuple") - - n_states = len(inputs.states) - systems = cls._broadcast(inputs.systems, n_states, "systems") - positions = cls._broadcast(inputs.positions, n_states, "positions") - topologies = cls._broadcast(inputs.topologies, n_states, "topologies") - return tuple( - EquilibrationEntry( - index=index, - state=state, - system=system, - positions=position, - topology=topology, - ) - for index, (state, system, position, topology) in enumerate( - zip(inputs.states, systems, positions, topologies) - ) - ) - @abstractmethod def _equilibrate_state( self, @@ -126,39 +67,47 @@ def _output_dir( def run( self, *, - equilibration_inputs: EquilibrationInputs, + equilibration_inputs: list[EquilibrationEntry], dry: bool = False, verbose: bool = True, scratch_basepath: Path | None = None, shared_basepath: Path | None = None, **state_kwargs: Any, ) -> dict[str, Any]: - """Equilibrate resolved in-memory inputs. + """Equilibrate each supplied thermodynamic state.""" - For direct calls, pass ``EquilibrationInputs`` holding OpenMM objects, - not upstream GUFE ``ProtocolUnitResult`` objects. Each protocol - subclass's ``_execute()`` loads its own upstream artifacts, checks - the execution environment, and calls this method. + if not equilibration_inputs: + raise ValueError("At least one equilibration entry is required") - Additional keyword arguments are forwarded unchanged to the concrete - ``_equilibrate_state()``. For PlainMD these are the validated NVT and - NPT step counts supplied by the setup unit. Concrete hooks should - declare these explicitly rather than swallowing arbitrary keywords. - """ - scratch_basepath = Path(".") if scratch_basepath is None else Path(scratch_basepath) - shared_basepath = Path(".") if shared_basepath is None else Path(shared_basepath) - entries = self._normalise_inputs(equilibration_inputs) + indices = [entry.index for entry in equilibration_inputs] + + if len(indices) != len(set(indices)): + raise ValueError("Equilibration entry indices must be unique") + + scratch_basepath = ( + Path(".") if scratch_basepath is None else Path(scratch_basepath) + ) + shared_basepath = ( + Path(".") if shared_basepath is None else Path(shared_basepath) + ) outputs = [] - for state_input in entries: + + for state_input in equilibration_inputs: output_dir = self._output_dir( - state_input=state_input, n_entries=len(entries), basepath=shared_basepath + state_input=state_input, + n_entries=len(equilibration_inputs), + basepath=shared_basepath, ) scratch_dir = self._output_dir( - state_input=state_input, n_entries=len(entries), basepath=scratch_basepath + state_input=state_input, + n_entries=len(equilibration_inputs), + basepath=scratch_basepath, ) + output_dir.mkdir(parents=True, exist_ok=True) scratch_dir.mkdir(parents=True, exist_ok=True) + result = self._equilibrate_state( state_input=state_input, output_dir=output_dir, @@ -167,6 +116,8 @@ def run( verbose=verbose, **state_kwargs, ) + outputs.append({**result, "index": state_input.index}) return {"equilibrated_states": outputs} + diff --git a/src/openfe/tests/protocols/test_base_equilibration.py b/src/openfe/tests/protocols/test_base_equilibration.py index e6a40dac7..36a03442b 100644 --- a/src/openfe/tests/protocols/test_base_equilibration.py +++ b/src/openfe/tests/protocols/test_base_equilibration.py @@ -7,7 +7,7 @@ from openfe.protocols.openmm_utils.base_equilibration import ( BaseEquilibrationUnit, - EquilibrationInputs, + EquilibrationEntry, ) @@ -18,7 +18,6 @@ class RecordingUnit: harness tests the base runner's in-memory inputs independently. """ - _normalise_inputs = BaseEquilibrationUnit._normalise_inputs _output_dir = BaseEquilibrationUnit._output_dir run = BaseEquilibrationUnit.run @@ -50,15 +49,17 @@ def _equilibrate_state( return {"index": 999, "state_path": output_dir / "equilibrated_state.xml"} -def _inputs(n=1, **overrides): - values = dict( - states=list(range(n)), - systems=object(), - positions=object(), - topologies=object(), - ) - values.update(overrides) - return EquilibrationInputs(**values) +def _inputs(n=1): + return [ + EquilibrationEntry( + index=i, + state=i, + system=object(), + positions=object(), + topology=object(), + ) + for i in range(n) + ] def test_one_state_preserves_plainmd_root_directories(tmp_path): @@ -78,77 +79,110 @@ def test_one_state_preserves_plainmd_root_directories(tmp_path): assert unit.calls[0]["verbose"] is False assert (tmp_path / "scratch").is_dir() assert (tmp_path / "shared").is_dir() - assert result["equilibrated_states"][0]["index"] == 0 # authoritative + assert result["equilibrated_states"] == [ + { + "index": 0, + "state_path": tmp_path / "shared" / "equilibrated_state.xml", + } + ] -def test_multiple_states_use_separate_paths_and_broadcast_scalars(tmp_path): - system, positions, topology = object(), object(), object() +def test_multiple_states_have_separate_directories(tmp_path): unit = RecordingUnit() + inputs = _inputs(n=3) + result = unit.run( - equilibration_inputs=_inputs( - 2, - systems=system, - positions=positions, - topologies=topology, - ), - equil_steps_nvt=3, - equil_steps_npt=5, - shared_basepath=tmp_path / "shared", + equilibration_inputs=inputs, + equil_steps_nvt=2, + equil_steps_npt=4, + dry=True, + verbose=False, scratch_basepath=tmp_path / "scratch", + shared_basepath=tmp_path / "shared", ) - assert [x["index"] for x in result["equilibrated_states"]] == [0, 1] - for i, call in enumerate(unit.calls): - assert call["state_input"].system is system - assert call["state_input"].positions is positions - assert call["state_input"].topology is topology - assert call["output_dir"] == tmp_path / "shared" / f"state_{i:03d}" - assert call["scratch_dir"] == tmp_path / "scratch" / f"state_{i:03d}" - assert call["nvt"] == 3 and call["npt"] == 5 - assert call["output_dir"].is_dir() and call["scratch_dir"].is_dir() - - -def test_per_state_sequence_inputs_are_aligned(): - systems, positions, topologies = ( - [object(), object()], - [object(), object()], - [object(), object()], - ) - entries = BaseEquilibrationUnit._normalise_inputs( - _inputs(2, systems=systems, positions=positions, topologies=topologies) - ) - for i, entry in enumerate(entries): - assert entry.index == i - assert entry.system is systems[i] - assert entry.positions is positions[i] - assert entry.topology is topologies[i] - - -@pytest.mark.parametrize("field", ["systems", "positions", "topologies"]) -@pytest.mark.parametrize("n_values", [0, 1, 3]) -def test_sequence_length_must_match_states(field, n_values): - with pytest.raises(ValueError, match=rf"{field} must contain 2 entries"): - BaseEquilibrationUnit._normalise_inputs( - _inputs(2, **{field: [object() for _ in range(n_values)]}) + + assert len(unit.calls) == 3 + assert len(result["equilibrated_states"]) == 3 + + output_dirs = set() + scratch_dirs = set() + + for entry, call, output in zip( + inputs, + unit.calls, + result["equilibrated_states"], + ): + assert call["state_input"] is entry + assert call["nvt"] == 2 + assert call["npt"] == 4 + + assert call["output_dir"].is_dir() + assert call["scratch_dir"].is_dir() + + assert call["output_dir"].parent == tmp_path / "shared" + assert call["scratch_dir"].parent == tmp_path / "scratch" + + assert output["index"] == entry.index + assert output["state_path"] == ( + call["output_dir"] / "equilibrated_state.xml" + ) + + output_dirs.add(call["output_dir"]) + scratch_dirs.add(call["scratch_dir"]) + + assert len(output_dirs) == 3 + assert len(scratch_dirs) == 3 + + +def test_empty_inputs_are_rejected(tmp_path): + unit = RecordingUnit() + + with pytest.raises( + ValueError, + match="At least one equilibration entry is required", + ): + unit.run( + equilibration_inputs=[], + equil_steps_nvt=2, + equil_steps_npt=4, + scratch_basepath=tmp_path / "scratch", + shared_basepath=tmp_path / "shared", ) + assert not unit.calls + assert not (tmp_path / "scratch").exists() + assert not (tmp_path / "shared").exists() -@pytest.mark.parametrize("states", [[], (), "one", None]) -def test_states_must_be_nonempty_list_or_tuple(states): - with pytest.raises(ValueError, match="non-empty list or tuple"): - BaseEquilibrationUnit._normalise_inputs(_inputs(states=states)) +def test_duplicate_indices_are_rejected(tmp_path): + unit = RecordingUnit() + entry = _inputs()[0] + + with pytest.raises( + ValueError, + match="Equilibration entry indices must be unique", + ): + unit.run( + equilibration_inputs=[entry, entry], + equil_steps_nvt=2, + equil_steps_npt=4, + scratch_basepath=tmp_path / "scratch", + shared_basepath=tmp_path / "shared", + ) -def test_normalization_requires_equilibration_inputs(): - with pytest.raises(TypeError, match="EquilibrationInputs"): - BaseEquilibrationUnit._normalise_inputs({"states": [None]}) + assert not unit.calls + assert not (tmp_path / "scratch").exists() + assert not (tmp_path / "shared").exists() def test_unknown_protocol_specific_keyword_is_rejected(tmp_path): unit = RecordingUnit() + with pytest.raises(TypeError, match="equil_step_nvt"): unit.run( equilibration_inputs=_inputs(), equil_step_nvt=2, # typo equil_steps_npt=4, - shared_basepath=tmp_path, - ) + scratch_basepath=tmp_path / "scratch", + shared_basepath=tmp_path / "shared", + ) \ No newline at end of file From 2e3391b4f7ab0c633112c6e85ca77acb510bd409 Mon Sep 17 00:00:00 2001 From: hannahbaumann Date: Thu, 26 Nov 2026 17:16:41 +0100 Subject: [PATCH 7/8] some more changes --- .../protocols/openmm_md/plain_md_methods.py | 6 ++-- .../openmm_utils/base_equilibration.py | 16 ++++----- .../openmm_md/test_plain_md_protocol.py | 30 +++++++++-------- .../openmm_md/test_plain_md_resume.py | 33 +++++++++++-------- 4 files changed, 48 insertions(+), 37 deletions(-) diff --git a/src/openfe/protocols/openmm_md/plain_md_methods.py b/src/openfe/protocols/openmm_md/plain_md_methods.py index fd249b7c2..590cb69d8 100644 --- a/src/openfe/protocols/openmm_md/plain_md_methods.py +++ b/src/openfe/protocols/openmm_md/plain_md_methods.py @@ -59,7 +59,7 @@ ) from openfe.protocols.openmm_utils.base_equilibration import ( BaseEquilibrationUnit, - EquilibrationEntry, + EquilibrationInput, ) from openfe.protocols.openmm_utils.offmolecule_utils import ( _get_offmol_metadata, @@ -1022,7 +1022,7 @@ def _execute( # Setup already validated the step counts; do not calculate them again. outputs = self.run( equilibration_inputs=[ - EquilibrationEntry( + EquilibrationInput( index=0, state=None, system=system, @@ -1065,7 +1065,7 @@ def _get_remaining_equilibration_steps( def _equilibrate_state( self, *, - state_input: EquilibrationEntry, + state_input: EquilibrationInput, output_dir: pathlib.Path, scratch_dir: pathlib.Path, dry: bool, diff --git a/src/openfe/protocols/openmm_utils/base_equilibration.py b/src/openfe/protocols/openmm_utils/base_equilibration.py index 782dd7d8c..709d30b86 100644 --- a/src/openfe/protocols/openmm_utils/base_equilibration.py +++ b/src/openfe/protocols/openmm_utils/base_equilibration.py @@ -19,8 +19,8 @@ @dataclass(frozen=True) -class EquilibrationEntry: - """Inputs for exactly one thermodynamic state, used only during execution.""" +class EquilibrationInput: + """Inputs required to equilibrate a single thermodynamic state.""" index: int state: Any # None for PlainMD; future protocols may provide alchemical states. @@ -44,7 +44,7 @@ class BaseEquilibrationUnit(gufe.ProtocolUnit, ABC): def _equilibrate_state( self, *, - state_input: EquilibrationEntry, + state_input: EquilibrationInput, output_dir: Path, scratch_dir: Path, dry: bool, @@ -59,7 +59,7 @@ def _equilibrate_state( """ def _output_dir( - self, *, state_input: EquilibrationEntry, n_entries: int, basepath: Path + self, *, state_input: EquilibrationInput, n_entries: int, basepath: Path ) -> Path: """Use legacy root for PlainMD; isolate files for multiple states.""" return basepath if n_entries == 1 else basepath / f"state_{state_input.index:03d}" @@ -67,7 +67,7 @@ def _output_dir( def run( self, *, - equilibration_inputs: list[EquilibrationEntry], + equilibration_inputs: list[EquilibrationInput], dry: bool = False, verbose: bool = True, scratch_basepath: Path | None = None, @@ -77,12 +77,12 @@ def run( """Equilibrate each supplied thermodynamic state.""" if not equilibration_inputs: - raise ValueError("At least one equilibration entry is required") + raise ValueError("At least one equilibration input is required") - indices = [entry.index for entry in equilibration_inputs] + indices = [input.index for input in equilibration_inputs] if len(indices) != len(set(indices)): - raise ValueError("Equilibration entry indices must be unique") + raise ValueError("Equilibration input indices must be unique") scratch_basepath = ( Path(".") if scratch_basepath is None else Path(scratch_basepath) diff --git a/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py b/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py index ea37c3168..334008022 100644 --- a/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py +++ b/src/openfe/tests/protocols/openmm_md/test_plain_md_protocol.py @@ -28,7 +28,7 @@ PlainMDSimulationUnit, ) from openfe.protocols.openmm_utils import serialization -from openfe.protocols.openmm_utils.base_equilibration import EquilibrationInputs +from openfe.protocols.openmm_utils.base_equilibration import EquilibrationInput from openfe.protocols.openmm_utils.charge_generation import ( HAS_ESPALOMA_CHARGE, HAS_NAGL, @@ -177,7 +177,7 @@ def test_three_unit_dag(benzene_vacuum_system, vac_settings): assert production.inputs["equilibration_results"] == equil -def test_dry_run_logger_output(benzene_vacuum_system, vac_settings, tmp_path, caplog): +def test_run_logger_output(benzene_vacuum_system, vac_settings, tmp_path, caplog): vac_settings.simulation_settings.equilibration_length_nvt = 1 * unit.picosecond vac_settings.simulation_settings.equilibration_length = 1 * unit.picosecond vac_settings.simulation_settings.production_length = 1 * unit.picosecond @@ -201,7 +201,7 @@ def test_dry_run_logger_output(benzene_vacuum_system, vac_settings, tmp_path, ca caplog.set_level(logging.INFO) setup_results = setup_unit.run( - dry=False, verbose=True, scratch_basepath=tmp_path, shared_basepath=tmp_path + dry=False, verbose=True, scratch_basepath=setup_path, shared_basepath=setup_path ) messages = [r.message for r in caplog.records] @@ -211,13 +211,17 @@ def test_dry_run_logger_output(benzene_vacuum_system, vac_settings, tmp_path, ca system = serialization.deserialize(setup_results["system"]) positions = np.load(setup_results["positions"]) * omm_unit.nanometers topology = openmm.app.PDBFile(str(setup_results["system_pdb"])).getTopology() + equil_results = equil_unit.run( - equilibration_inputs=EquilibrationInputs( - states=[None], - systems=system, - positions=positions, - topologies=topology, - ), + equilibration_inputs=[ + EquilibrationInput( + index=0, + state=None, + system=system, + positions=positions, + topology=topology, + ), + ], equil_steps_nvt=setup_results["equil_steps_nvt"] or 0, equil_steps_npt=setup_results["equil_steps_npt"], verbose=True, @@ -258,7 +262,7 @@ def test_dry_run_ffcache_none_vacuum(benzene_vacuum_system, vac_settings, tmp_pa ) assert protocol.settings.output_settings.forcefield_cache is None - # create DAG from protocol and take first (and only) work unit from within + # create DAG from protocol and take setup unit from within dag = protocol.create( stateA=benzene_vacuum_system, stateB=benzene_vacuum_system, @@ -275,7 +279,7 @@ def test_dry_run_gaff_vacuum(benzene_vacuum_system, vac_settings, tmp_path): settings=vac_settings, ) - # create DAG from protocol and take first (and only) work unit from within + # create DAG from protocol and take setup unit from within dag = protocol.create( stateA=benzene_vacuum_system, stateB=benzene_vacuum_system, @@ -303,7 +307,7 @@ def test_dry_run_espaloma_vacuum_user_charges( expected_charges = [-0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5] benzene_openff.partial_charges = expected_charges * unit.elementary_charge benzene_system = ChemicalSystem({"ligand": SmallMoleculeComponent.from_openff(benzene_openff)}) - # create DAG from protocol and take first (and only) work unit from within + # create DAG from protocol and take setup unit from within dag = protocol.create( stateA=benzene_system, stateB=benzene_system, @@ -387,7 +391,7 @@ def test_dry_many_molecules_solvent(benzene_many_solv_system, tmp_path): protocol = PlainMDProtocol(settings=settings) - # create DAG from protocol and take first (and only) work unit from within + # create DAG from protocol and take setup unit from within dag = protocol.create( stateA=benzene_many_solv_system, stateB=benzene_many_solv_system, diff --git a/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py b/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py index c19b5801e..b00930d8d 100644 --- a/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py +++ b/src/openfe/tests/protocols/openmm_md/test_plain_md_resume.py @@ -21,7 +21,7 @@ PlainMDSimulationUnit, ) from openfe.protocols.openmm_utils import serialization -from openfe.protocols.openmm_utils.base_equilibration import EquilibrationInputs +from openfe.protocols.openmm_utils.base_equilibration import EquilibrationInput from ...conftest import HAS_INTERNET @@ -166,12 +166,15 @@ def test_resume( dry=True, scratch_basepath=tmp_path, shared_basepath=tmp_path ) equil_results = equil_unit.run( - equilibration_inputs=EquilibrationInputs( - states=[None], - systems=serialization.deserialize(setup_results["system"]), - positions=setup_results["debug"]["positions"], - topologies=setup_results["debug"]["topology"], - ), + equilibration_inputs=[ + EquilibrationInput( + index=0, + state=None, + system=serialization.deserialize(setup_results["system"]), + positions=setup_results["debug"]["positions"], + topology=setup_results["debug"]["topology"], + ), + ], equil_steps_nvt=setup_results["equil_steps_nvt"] or 0, equil_steps_npt=setup_results["equil_steps_npt"], scratch_basepath=equil_path, @@ -280,17 +283,21 @@ def test_resume_equilibration_from_npt_checkpoint( caplog.set_level(logging.INFO) result = equil_unit.run( - equilibration_inputs=EquilibrationInputs( - states=[None], - systems=serialization.deserialize(setup["system"]), - positions=setup["debug"]["positions"], - topologies=setup["debug"]["topology"], - ), + equilibration_inputs=[ + EquilibrationInput( + index=0, + state=None, + system=serialization.deserialize(setup["system"]), + positions=setup["debug"]["positions"], + topology=setup["debug"]["topology"], + ), + ], equil_steps_nvt=setup["equil_steps_nvt"] or 0, equil_steps_npt=setup["equil_steps_npt"], shared_basepath=equil_dir, scratch_basepath=equil_dir, ) + state = result["equilibrated_states"][0] assert "Restarting simulation from checkpoint state" in caplog.text From e4f5d1a4b74f733df4cd9de9a584973520c23e51 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:17:32 +0000 Subject: [PATCH 8/8] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- src/openfe/protocols/openmm_utils/base_equilibration.py | 9 ++------- src/openfe/tests/protocols/test_base_equilibration.py | 6 ++---- 2 files changed, 4 insertions(+), 11 deletions(-) diff --git a/src/openfe/protocols/openmm_utils/base_equilibration.py b/src/openfe/protocols/openmm_utils/base_equilibration.py index 709d30b86..5dbadabbe 100644 --- a/src/openfe/protocols/openmm_utils/base_equilibration.py +++ b/src/openfe/protocols/openmm_utils/base_equilibration.py @@ -84,12 +84,8 @@ def run( if len(indices) != len(set(indices)): raise ValueError("Equilibration input indices must be unique") - scratch_basepath = ( - Path(".") if scratch_basepath is None else Path(scratch_basepath) - ) - shared_basepath = ( - Path(".") if shared_basepath is None else Path(shared_basepath) - ) + scratch_basepath = Path(".") if scratch_basepath is None else Path(scratch_basepath) + shared_basepath = Path(".") if shared_basepath is None else Path(shared_basepath) outputs = [] @@ -120,4 +116,3 @@ def run( outputs.append({**result, "index": state_input.index}) return {"equilibrated_states": outputs} - diff --git a/src/openfe/tests/protocols/test_base_equilibration.py b/src/openfe/tests/protocols/test_base_equilibration.py index 36a03442b..f0748d6af 100644 --- a/src/openfe/tests/protocols/test_base_equilibration.py +++ b/src/openfe/tests/protocols/test_base_equilibration.py @@ -123,9 +123,7 @@ def test_multiple_states_have_separate_directories(tmp_path): assert call["scratch_dir"].parent == tmp_path / "scratch" assert output["index"] == entry.index - assert output["state_path"] == ( - call["output_dir"] / "equilibrated_state.xml" - ) + assert output["state_path"] == (call["output_dir"] / "equilibrated_state.xml") output_dirs.add(call["output_dir"]) scratch_dirs.add(call["scratch_dir"]) @@ -185,4 +183,4 @@ def test_unknown_protocol_specific_keyword_is_rejected(tmp_path): equil_steps_npt=4, scratch_basepath=tmp_path / "scratch", shared_basepath=tmp_path / "shared", - ) \ No newline at end of file + )