diff --git a/src/openfe/protocols/openmm_md/plain_md_methods.py b/src/openfe/protocols/openmm_md/plain_md_methods.py index 48b3fce14..590cb69d8 100644 --- a/src/openfe/protocols/openmm_md/plain_md_methods.py +++ b/src/openfe/protocols/openmm_md/plain_md_methods.py @@ -57,6 +57,10 @@ system_creation, system_validation, ) +from openfe.protocols.openmm_utils.base_equilibration import ( + BaseEquilibrationUnit, + EquilibrationInput, +) from openfe.protocols.openmm_utils.offmolecule_utils import ( _get_offmol_metadata, _get_unique_name, @@ -254,7 +258,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 +271,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,395 +347,179 @@ 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, - ) - prod_steps = settings_validation.get_simsteps( - sim_length=sim_settings.production_length, - timestep=timestep, - mc_steps=1, + 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, + 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) - - # 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 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 + if checkpoint_path is not None: + simulation.reporters.append( + openmm.app.CheckpointReporter( + file=str(checkpoint_path), + reportInterval=checkpoint_interval, + writeState=True, + ) + ) @staticmethod def _run_MD( @@ -744,6 +541,9 @@ def _run_MD( 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 ---------- simulation : openmm.app.Simulation @@ -805,7 +605,8 @@ def _run_MD( # 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, @@ -823,7 +624,7 @@ def _run_MD( 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, @@ -835,7 +636,8 @@ def _run_MD( openmm.app.CheckpointReporter( 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() ) ) @@ -849,11 +651,12 @@ def _run_MD( 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, @@ -872,7 +675,7 @@ def _run_MD( else: output_path = None - PlainMDSimulationUnit._run_dynamics( + PlainMDUnitMixin._run_dynamics( # was PlainMDSimulationUnit simulation=simulation, steps=equil_steps_npt, temperature=temperature, @@ -929,47 +732,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, - scratch_basepath: pathlib.Path | None = None, - shared_basepath: pathlib.Path | None = None, + +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 +795,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 +814,686 @@ 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=[ + EquilibrationInput( + 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, + 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: EquilibrationInput, + output_dir: pathlib.Path, + scratch_dir: pathlib.Path, + dry: bool, + verbose: bool, + 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. + + 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. + """ + 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 + 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. + + 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. - if output_settings.equil_npt_structure: - output["npt_equil_pdb"] = self.shared_basepath / output_settings.equil_npt_structure + 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..5dbadabbe --- /dev/null +++ b/src/openfe/protocols/openmm_utils/base_equilibration.py @@ -0,0 +1,118 @@ +# 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 +from openmm import unit as omm_unit + + +@dataclass(frozen=True) +class EquilibrationInput: + """Inputs required to equilibrate a single thermodynamic state.""" + + 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): + """Base class for protocol-specific equilibration units. + + Subclasses resolve the upstream results into equilibration + entries and implement the protocol-specific equilibration + procedure. + + This class manages iteration, directory layout and collection + of equilibration results. + """ + + @abstractmethod + def _equilibrate_state( + self, + *, + state_input: EquilibrationInput, + 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: 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}" + + def run( + self, + *, + equilibration_inputs: list[EquilibrationInput], + dry: bool = False, + verbose: bool = True, + scratch_basepath: Path | None = None, + shared_basepath: Path | None = None, + **state_kwargs: Any, + ) -> dict[str, Any]: + """Equilibrate each supplied thermodynamic state.""" + + if not equilibration_inputs: + raise ValueError("At least one equilibration input is required") + + indices = [input.index for input in equilibration_inputs] + + 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) + + outputs = [] + + for state_input in equilibration_inputs: + output_dir = self._output_dir( + state_input=state_input, + n_entries=len(equilibration_inputs), + basepath=shared_basepath, + ) + scratch_dir = self._output_dir( + 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, + 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..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 @@ -21,12 +21,14 @@ import openfe from openfe.protocols import openmm_md from openfe.protocols.openmm_md.plain_md_methods import ( + PlainMDEquilibrationUnit, PlainMDProtocol, PlainMDProtocolResult, PlainMDSetupUnit, PlainMDSimulationUnit, ) from openfe.protocols.openmm_utils import serialization +from openfe.protocols.openmm_utils.base_equilibration import EquilibrationInput from openfe.protocols.openmm_utils.charge_generation import ( HAS_ESPALOMA_CHARGE, HAS_NAGL, @@ -44,22 +46,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 +124,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,7 +161,23 @@ def test_dry_run_default_vacuum(benzene_vacuum_system, vac_settings, tmp_path): ) -def test_dry_run_logger_output(benzene_vacuum_system, vac_settings, tmp_path, caplog): +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_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 @@ -166,35 +192,61 @@ 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( - 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] 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, + + equil_results = equil_unit.run( + 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, + 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 @@ -210,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, @@ -227,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, @@ -255,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, @@ -339,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, @@ -610,13 +662,31 @@ def test_unit_tagging(benzene_system, tmp_path): def test_gather(solvent_protocol_dag, tmp_path): - # check .gather behaves as expected - with mock.patch( - "openfe.protocols.openmm_md.plain_md_methods.PlainMDSimulationUnit.run", - return_value={ - "nc": "simulation.xtc", - "last_checkpoint": "checkpoint.chk", - }, + # 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", + }, + ), ): 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 34f44a89d..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 @@ -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,17 +9,19 @@ 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 import openfe from openfe.data._registry import POOCH_CACHE from openfe.protocols.openmm_md.plain_md_methods import ( + PlainMDEquilibrationUnit, PlainMDProtocol, PlainMDSetupUnit, PlainMDSimulationUnit, ) +from openfe.protocols.openmm_utils import serialization +from openfe.protocols.openmm_utils.base_equilibration import EquilibrationInput from ...conftest import HAS_INTERNET @@ -91,6 +94,45 @@ 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 +150,174 @@ 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=[ + 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, + 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.clear() + 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=[ + 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 + 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..f0748d6af --- /dev/null +++ b/src/openfe/tests/protocols/test_base_equilibration.py @@ -0,0 +1,186 @@ +# 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, + EquilibrationEntry, +) + + +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. + """ + + _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): + 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): + 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"] == [ + { + "index": 0, + "state_path": tmp_path / "shared" / "equilibrated_state.xml", + } + ] + + +def test_multiple_states_have_separate_directories(tmp_path): + unit = RecordingUnit() + inputs = _inputs(n=3) + + result = unit.run( + 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 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() + + +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", + ) + + 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, + scratch_basepath=tmp_path / "scratch", + shared_basepath=tmp_path / "shared", + )