tfep.potentials.mimic.MiMiCPotential

class tfep.potentials.mimic.MiMiCPotential(cpmd_cmd: Cpmd, mdrun_cmd: GmxMdrun, grompp_cmd: GmxGrompp, gromacs_to_cpmd_atom_indices: Dict[int, int], launcher: Launcher | None = None, grompp_launcher: Launcher | None = None, positions_unit: Unit | None = None, energy_unit: Unit | None = None, precompute_gradient: bool = True, working_dir_path: str | List[str] | None = None, cleanup_working_dir: bool = False, parallelization_strategy: ParallelizationStrategy | None = None, launcher_kwargs: Dict[str, Any] | None = None, grompp_launcher_kwargs: Dict[str, Any] | None = None, n_attempts: int = 1, on_unconverged: str = 'raise', on_local_error: str = 'raise')[source]

Bases: PotentialBase

Potential energy and forces with MiMiC.

This Module wraps :class:.MiMiCPotentialEnergyFunc to provide a differentiable potential energy function for training. It also provides an API to compute energies and forces with MiMiC from batches of coordinates in numpy arrays in standard format (i.e., shape (n_atoms, 3)) rather than flattened torch.Tensor``s (i.e., shape ``(n_atoms*3,)).

__init__(cpmd_cmd: Cpmd, mdrun_cmd: GmxMdrun, grompp_cmd: GmxGrompp, gromacs_to_cpmd_atom_indices: Dict[int, int], launcher: Launcher | None = None, grompp_launcher: Launcher | None = None, positions_unit: Unit | None = None, energy_unit: Unit | None = None, precompute_gradient: bool = True, working_dir_path: str | List[str] | None = None, cleanup_working_dir: bool = False, parallelization_strategy: ParallelizationStrategy | None = None, launcher_kwargs: Dict[str, Any] | None = None, grompp_launcher_kwargs: Dict[str, Any] | None = None, n_attempts: int = 1, on_unconverged: str = 'raise', on_local_error: str = 'raise')[source]

Constructor.

Parameters:
  • cpmd_cmd (tfep.potentials.mimic.Cpmd) – The CPMD command to be run for MiMiC’s execution that encapsulates the path to the CPMD input script and options.

    The &MIMIC.PATHS option and atomic coordinates can be placeholders as they are automatically set by this function according to the working_dir_path and batch_positions arguments. All other options must be set correctly for the function to run successfully.

  • mdrun_cmd (tfep.potentials.mimic.GmxMdrun) – The GMX mdrun command to be run for MiMiC’s execution that encapsulates the path to the GROMACS input script and running options.

    The mdrun_cmd.tpr_input_file_path can be left unset since a new .tpr file with the correct positions is automatically generated with gromp_cmd.

  • grompp_cmd (tfep.potentials.mimic.GmxGrompp, optional) – This command is used to generate the .tpr file with the correct coordinates. To do so, the batch positions are first stored in a .trr file which is then passed to grompp. Thus, the GmxGrompp.tpr_output_file_path and GmxGrompp.trajectory_input_file_path options can be None.

  • gromacs_to_cpmd_atom_indices (Dict[int, int]) – A dictionary associating atom indices in GROMACS to atom indices in CPMD.

  • launcher (tfep.utils.cli.Launcher, optional) – The Launcher to use to run the cpmd_cmd and mdrun_cmd. If not passed, a new tfep.utils.cli.Launcher is created.

  • grompp_launcher (tfep.utils.cli.Launcher, optional) – The Launcher to use to run the grompp_cmd command. If not passed, a new tfep.utils.cli.Launcher is created.

  • positions_unit (pint.Unit, optional) – The unit of the positions passed. This is used to appropriately convert batch_positions to the units used by MiMiC. If None, no conversion is performed, which assumes that the input positions are in Bohr.

  • energy_unit (pint.Unit, optional) – The unit used for the returned energies (and as a consequence forces). This is used to appropriately convert MiMiC energies into the desired units. If None, no conversion is performed, which means that energies and forces will be in hartrees and hartrees/bohr respectively.

  • precompute_gradient (bool, optional) – If False, the FTRAJECTORY file is not read after executing MiMiC. This might save a small amount of time if backpropagation is not needed.

  • working_dir_path (str or List[str], optional) – The working directory to be used to run MiMiC and grompp. This must exist. If a list, batch_positions[i] is evaluated in the directory working_dir_path[i].

  • cleanup_working_dir (bool, optional) – If True and working_dir_path is passed, all the files inside the working directory are removed after executing MiMiC. The directory(s) itself is not deleted.

  • parallelization_strategy (tfep.utils.parallel.ParallelizationStrategy, optional) – The parallelization strategy used to distribute batches of energy and gradient calculations. By default, these are executed serially.

  • launcher_kwargs (Dict, optional) – Other kwargs for launcher (with the exception of cwd which is automatically determined based on working_dir_path).

  • grompp_launcher_kwargs (Dict, optional) – Other kwargs for grompp_launcher.

  • n_attempts (int, optional) – Number of times MiMiC is restarted before raising a RuntimeError when MiMiC crashes without creating an error report in the LocalError-X-X-X.log file.

  • on_unconverged (str, optional) – Specifies how to handle the case in which the self-consistent calculation did not converge. It can have the following values: - 'raise': Raises a RuntimeError and halts the execution. - 'success': Treat the calculation as converged and return the

    latest energy and force values.

    • 'nan': Return float('nan') energy and zero forces.

    If this is set to anything other than 'success', the stdout keyword argument must be included in launcher_kwargs and set to subprocess.PIPE so that Python can intercept and parse the output to detect the convergence warning message.

  • on_local_error (str, optional) – Specifies how to handle the case in which the calculation ends with an error and CPMD creates an error report in the LocalError-X-X-X.log file. It can have the following values: - 'raise': Raises a RuntimeError and halts the execution. - 'nan': Return float('nan') energy and zero forces.

See also

MiMiCPotentialEnergyFunc

More details on input parameters and implementation details.

Methods

__init__(cpmd_cmd, mdrun_cmd, grompp_cmd, ...)

Constructor.

add_module(name, module)

Add a child module to the current module.

apply(fn)

Apply fn recursively to every submodule (as returned by .children()) as well as self.

bfloat16()

Casts all floating point parameters and buffers to bfloat16 datatype.

buffers([recurse])

Return an iterator over module buffers.

children()

Return an iterator over immediate children modules.

compile(*args, **kwargs)

Compile this Module's forward using torch.compile().

cpu()

Move all model parameters and buffers to the CPU.

cuda([device])

Move all model parameters and buffers to the GPU.

default_energy_unit(unit_registry)

Return the default energy units.

default_positions_unit(unit_registry)

Return the default positions units.

double()

Casts all floating point parameters and buffers to double datatype.

energy(batch_positions, batch_cell)

Compute a the potential energy of a batch of configurations.

eval()

Set the module in evaluation mode.

extra_repr()

Set the extra representation of the module.

float()

Casts all floating point parameters and buffers to float datatype.

force(batch_positions, batch_cell)

Compute the force for a batch of configurations.

forward(batch_positions, batch_cell)

Compute a differential potential energy for a batch of configurations.

get_buffer(target)

Return the buffer given by target if it exists, otherwise throw an error.

get_extra_state()

Return any extra state to include in the module's state_dict.

get_parameter(target)

Return the parameter given by target if it exists, otherwise throw an error.

get_submodule(target)

Return the submodule given by target if it exists, otherwise throw an error.

half()

Casts all floating point parameters and buffers to half datatype.

ipu([device])

Move all model parameters and buffers to the IPU.

load_state_dict(state_dict[, strict, assign])

Copy parameters and buffers from state_dict into this module and its descendants.

modules()

Return an iterator over all modules in the network.

mtia([device])

Move all model parameters and buffers to the MTIA.

named_buffers([prefix, recurse, ...])

Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix, remove_duplicate])

Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse, ...])

Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Return an iterator over module parameters.

register_backward_hook(hook)

Register a backward hook on the module.

register_buffer(name, tensor[, persistent])

Add a buffer to the module.

register_forward_hook(hook, *[, prepend, ...])

Register a forward hook on the module.

register_forward_pre_hook(hook, *[, ...])

Register a forward pre-hook on the module.

register_full_backward_hook(hook[, prepend])

Register a backward hook on the module.

register_full_backward_pre_hook(hook[, prepend])

Register a backward pre-hook on the module.

register_load_state_dict_post_hook(hook)

Register a post-hook to be run after module's load_state_dict() is called.

register_load_state_dict_pre_hook(hook)

Register a pre-hook to be run before module's load_state_dict() is called.

register_module(name, module)

Alias for add_module().

register_parameter(name, param)

Add a parameter to the module.

register_state_dict_post_hook(hook)

Register a post-hook for the state_dict() method.

register_state_dict_pre_hook(hook)

Register a pre-hook for the state_dict() method.

requires_grad_([requires_grad])

Change if autograd should record operations on parameters in this module.

set_extra_state(state)

Set extra state contained in the loaded state_dict.

set_submodule(target, module)

Set the submodule given by target if it exists, otherwise throw an error.

share_memory()

See torch.Tensor.share_memory_().

state_dict(*args[, destination, prefix, ...])

Return a dictionary containing references to the whole state of the module.

to(*args, **kwargs)

Move and/or cast the parameters and buffers.

to_empty(*, device[, recurse])

Move the parameters and buffers to the specified device without copying storage.

train([mode])

Set the module in training mode.

type(dst_type)

Casts all parameters and buffers to dst_type.

xpu([device])

Move all model parameters and buffers to the XPU.

zero_grad([set_to_none])

Reset gradients of all model parameters.

Attributes

DEFAULT_ENERGY_UNIT

The default energy unit.

DEFAULT_POSITIONS_UNIT

The default positions unit.

T_destination

call_super_init

dump_patches

energy_unit

The energy units of the returned potential.

positions_unit

The positions unit requested for the input.

training

DEFAULT_ENERGY_UNIT: str = 'hartree'

The default energy unit.

DEFAULT_POSITIONS_UNIT: str = 'bohr'

The default positions unit.

classmethod default_energy_unit(unit_registry) Quantity

Return the default energy units.

classmethod default_positions_unit(unit_registry) Quantity

Return the default positions units.

energy(batch_positions: Quantity, batch_cell: Quantity) Quantity[source]

Compute a the potential energy of a batch of configurations.

Parameters:
  • batch_positions (pint.Quantity) – An array of positions with units and shape: (batch_size, n_atoms, 3) or (n_atoms, 3). If no units are attached to the array, it is assumed the positions are is in self.positions_unit units (or MiMiC units if positions_unit was not provided).

    Note that the order of the atoms is assumed to be that of the GROMACS input files, not the one used internally by CPMD.

  • batch_cell (pint.Quantity) – An array of box vectors with units and shape: (batch_size, 3) or (3,) defining the orthorhombic box side lengths (the only one currently supported in MiMiC). If no units are attached to the array, it is assumed the positions are is in self.positions_unit units (or MiMiC units if positions_unit was not provided).

Returns:

potential_energiespotential_energies[i] is the potential energy of configuration batch_positions[i] and batch_cell[i].

Return type:

pint.Quantity

property energy_unit: Quantity

The energy units of the returned potential.

force(batch_positions: Quantity, batch_cell: Quantity) Quantity[source]

Compute the force for a batch of configurations.

Parameters:
  • batch_positions (pint.Quantity) – An array of positions with units and shape: (batch_size, n_atoms, 3) or (n_atoms, 3). If no units are attached to the array, it is assumed the positions are is in self.positions_unit units (or MiMiC units if positions_unit was not provided).

    Note that the order of the atoms is assumed to be that of the GROMACS input files, not the one used internally by CPMD.

  • batch_cell (pint.Quantity) – An array of box vectors with units and shape: (batch_size, 3) or (3,) defining the orthorhombic box side lengths (the only one currently supported in MiMiC). If no units are attached to the array, it is assumed the positions are is in self.positions_unit units (or MiMiC units if positions_unit was not provided).

Returns:

forcesforces[i] is the force of configuration batch_positions[i] and batch_cell[i].

Return type:

pint.Quantity

forward(batch_positions: Tensor, batch_cell: Tensor) Tensor[source]

Compute a differential potential energy for a batch of configurations.

Parameters:
  • batch_positions (torch.Tensor) – A tensor of positions in flattened format (i.e., with shape (batch_size, 3*n_atoms)) in units of self.positions_unit.

    Note that the order of the atoms is assumed to be that of the GROMACS input files, not the one used internally by CPMD.

  • batch_cell (torch.Tensor) – Shape (batch_size, 6). Unitcell dimensions. For each data point, the first 3 elements represent the vector lengths in units of self.positions_unit and the last 3 their respective angles (in degrees).

Returns:

potential_energypotential_energy[i] is the potential energy of configuration batch_positions[i] and batch_cell[i] in units of self.energy_unit (or MiMiC units if energy_unit is not provided).

Return type:

torch.Tensor

property positions_unit: Quantity

The positions unit requested for the input.