narupa.ase.openmm.runner module¶
Interactive molecular dynamics runner for ASE with OpenMM.
-
class
narupa.ase.openmm.runner.ASEOpenMMRunner(simulation: pretends.Simulation, imd_params: Optional[narupa.ase.openmm.runner.ImdParams] = None, logging_params: Optional[narupa.ase.openmm.runner.LoggingParams] = None)¶ Bases:
narupa.app.runner.NarupaRunnerA wrapper class for running an interactive OpenMM simulation with ASE.
:param simulation OpenMM simulation to run interactively. :param params IMD parameters to tune the server. :param logging_params Parameters for logging the trajectory of the simulation.
-
app_server¶ Get the underlying app of the runner.
-
close()¶ Closes the connection and stops the dynamics.
-
discovery_port¶
-
dynamics¶ Gets the ASE
MolecularDynamicsobject that is running the dynamics.Returns: The ASE molecular dynamics object.
-
dynamics_interval¶ Minimum interval, in seconds, between frames sent to the frame publisher.
-
frame_interval¶ Gets the interval at which frames are sent, in steps.
Returns: The frame interval, in steps.
-
classmethod
from_xml(simulation_xml, params: Optional[narupa.ase.openmm.runner.ImdParams] = None, logging_params: Optional[narupa.ase.openmm.runner.LoggingParams] = None)¶ Initialises a
OpenMMIMDRunnerfrom a simulation XML file serialised with :fun:`serializer.serialize_simulation`.Parameters: - simulation_xml – Path to XML file.
- params – The :class: ImdParams to run the server with.
- logging_params – The :class:LoggingParams to set up trajectory logging with.
Returns: An OpenMM simulation runner.
-
is_running¶ Whether or not the molecular dynamics is currently running on a background thread or not.
Returns: True, if molecular dynamics is running, False otherwise.
-
pause()¶ Pause the simulation, by cancelling any current run.
This method is called whenever a client runs the pause command, described in :mod:narupa.trajectory.frame_server.
-
play()¶ Run the simulation indefinitely
Cancels any current run and then begins running the simulation on a background thread.
This method is called whenever a client runs the play command, described in :mod:narupa.trajectory.frame_server.
-
reset()¶
-
run(steps: Optional[int] = None, block: Optional[bool] = None, reset_energy: Optional[float] = None)¶ Runs the molecular dynamics.
Parameters: - steps – If passed, will run the given number of steps, otherwise will run forever on a background thread and immediately return.
- block – If
Falserun in a separate thread. By default, “block” isNone, which means it is automatically set toTrueif a number of steps is provided and toFalseotherwise. - reset_energy – Threshold of total energy in kJ/mol above which
the simulation is reset to its initial conditions. If a value is
provided, the simulation is reset if the total energy is greater
than this value, or if the total energy is nan or infinite. If
Noneis provided instead, then the simulation will not be automatically reset.
-
running_discovery¶
-
step()¶ Take a single step of the simulation and stop.
This method is called whenever a client runs the step command, described in :mod:narupa.trajectory.frame_server.
-
time_step¶ Gets the time step of the simulation, in femtoseconds.
Returns: The time step of the simulation.
-
verbose¶ Whether this OpenMM runner is set to run in verbose mode. If it is, it will print state information every 100 steps using an :class: MDLogger.
Returns: True if set to run verbosely, False otherwise.
-
-
class
narupa.ase.openmm.runner.ImdParams(address: Optional[str] = None, port: Optional[int] = None, frame_interval: int = 5, time_step: float = 1.0, verbose: bool = False, walls: bool = False, name: Optional[str] = None, discovery: bool = True, discovery_port: Optional[int] = None)¶ Bases:
objectClass representing parameters for IMD runners.
-
class
narupa.ase.openmm.runner.LoggingParams(trajectory_file: Optional[str] = None, write_interval: int = 1)¶ Bases:
objectClass representing parameters for trajectory logging
-
class
narupa.ase.openmm.runner.OpenMMIMDRunner(*args, **kwargs)¶
-
class
narupa.ase.openmm.runner.TrajectoryLoggerInfo(trajectory_logger: narupa.ase.trajectory_logger.TrajectoryLogger, params: narupa.ase.openmm.runner.LoggingParams)¶ Bases:
objectClass giving a view into an ASE MD runners logger parameters.
Parameters: - trajectory_logger – Trajectory logger performing the logging.
- params – Logging parameters.
-
base_trajectory_path¶ The base trajectory path, without timestamps.
Returns: The base trajectory path.
-
close()¶ Close the log.
-
trajectory_path¶ The current trajectory path being outputted to.
Returns: The current trajectory path.
-
write_interval¶ The interval at which log writing is occurring.
Returns: The interval at which log writing is occurring, in steps.
-
narupa.ase.openmm.runner.dataclass(maybe_cls=None, these=None, repr_ns=None, repr=None, cmp=None, hash=None, init=None, slots=False, frozen=False, weakref_slot=True, str=False, *, auto_attribs=True, kw_only=False, cache_hash=False, auto_exc=False, eq=None, order=None, auto_detect=False, collect_by_mro=False, getstate_setstate=None, on_setattr=None, field_transformer=None, match_args=True)¶ A class decorator that adds dunder-methods according to the specified attributes using attr.ib or the these argument.
Parameters: - these (dict of str to attr.ib) –
A dictionary of name to attr.ib mappings. This is useful to avoid the definition of your attributes within the class body because you can’t (e.g. if you want to add
__repr__methods to Django models) or don’t want to.If these is not
None,attrswill not search the class body for attributes and will not remove any attributes from it.If these is an ordered dict (dict on Python 3.6+, collections.OrderedDict otherwise), the order is deduced from the order of the attributes inside these. Otherwise the order of the definition of the attributes is used.
- repr_ns (str) – When using nested classes, there’s no way in Python 2
to automatically detect that. Therefore it’s possible to set the
namespace explicitly for a more meaningful
reproutput. - auto_detect (bool) –
Instead of setting the init, repr, eq, order, and hash arguments explicitly, assume they are set to
Trueunless any of the involved methods for one of the arguments is implemented in the current class (i.e. it is not inherited from some base class).So for example by implementing
__eq__on a class yourself,attrswill deduceeq=Falseand will create neither__eq__nor__ne__(but Python classes come with a sensible__ne__by default, so it should be enough to only implement__eq__in most cases).Warning
If you prevent
attrsfrom creating the ordering methods for you (order=False, e.g. by implementing__le__), it becomes your responsibility to make sure its ordering is sound. The best way is to use the functools.total_ordering decorator.Passing
TrueorFalseto init, repr, eq, order, cmp, or hash overrides whatever auto_detect would determine.auto_detect requires Python 3. Setting it
Trueon Python 2 raises an attrs.exceptions.PythonTooOldError. - repr (bool) – Create a
__repr__method with a human readable representation ofattrsattributes.. - str (bool) – Create a
__str__method that is identical to__repr__. This is usually not necessary except for Exceptions. - eq (Optional[bool]) –
If
TrueorNone(default), add__eq__and__ne__methods that check two instances for equality.They compare the instances as if they were tuples of their
attrsattributes if and only if the types of both classes are identical! - order (Optional[bool]) – If
True, add__lt__,__le__,__gt__, and__ge__methods that behave like eq above and allow instances to be ordered. IfNone(default) mirror value of eq. - cmp (Optional[bool]) – Setting cmp is equivalent to setting eq and order to the same value. Must not be mixed with eq or order.
- hash (Optional[bool]) –
If
None(default), the__hash__method is generated according how eq and frozen are set.- If both are True,
attrswill generate a__hash__for you. - If eq is True and frozen is False,
__hash__will be set to None, marking it unhashable (which it is). - If eq is False,
__hash__will be left untouched meaning the__hash__method of the base class will be used (if base class isobject, this means it will fall back to id-based hashing.).
Although not recommended, you can decide for yourself and force
attrsto create one (e.g. if the class is immutable even though you didn’t freeze it programmatically) by passingTrueor not. Both of these cases are rather special and should be used carefully.See our documentation on hashing, Python’s documentation on object.__hash__, and the GitHub issue that led to the default behavior for more details.
- If both are True,
- init (bool) –
Create a
__init__method that initializes theattrsattributes. Leading underscores are stripped for the argument name. If a__attrs_pre_init__method exists on the class, it will be called before the class is initialized. If a__attrs_post_init__method exists on the class, it will be called after the class is fully initialized.If
initisFalse, an__attrs_init__method will be injected instead. This allows you to define a custom__init__method that can do pre-init work such assuper().__init__(), and then call__attrs_init__()and__attrs_post_init__(). - slots (bool) – Create a slotted class <slotted classes> that’s more memory-efficient. Slotted classes are generally superior to the default dict classes, but have some gotchas you should know about, so we encourage you to read the glossary entry <slotted classes>.
- frozen (bool) –
Make instances immutable after initialization. If someone attempts to modify a frozen instance, attr.exceptions.FrozenInstanceError is raised.
Note
- This is achieved by installing a custom
__setattr__method on your class, so you can’t implement your own. - True immutability is impossible in Python.
- This does have a minor a runtime performance impact
<how-frozen> when initializing new instances. In other words:
__init__is slightly slower withfrozen=True. - If a class is frozen, you cannot modify
selfin__attrs_post_init__or a self-written__init__. You can circumvent that limitation by usingobject.__setattr__(self, "attribute_name", value). - Subclasses of a frozen class are frozen too.
- This is achieved by installing a custom
- weakref_slot (bool) – Make instances weak-referenceable. This has no
effect unless
slotsis also enabled. - auto_attribs (bool) –
If
True, collect PEP 526-annotated attributes (Python 3.6 and later only) from the class body.In this case, you must annotate every field. If
attrsencounters a field that is set to an attr.ib but lacks a type annotation, an attr.exceptions.UnannotatedAttributeError is raised. Usefield_name: typing.Any = attr.ib(...)if you don’t want to set a type.If you assign a value to those attributes (e.g.
x: int = 42), that value becomes the default value like if it were passed usingattr.ib(default=42). Passing an instance of attrs.Factory also works as expected in most cases (see warning below).Attributes annotated as typing.ClassVar, and attributes that are neither annotated nor set to an attr.ib are ignored.
Warning
For features that use the attribute name to create decorators (e.g. validators <validators>), you still must assign attr.ib to them. Otherwise Python will either not find the name or try to use the default value to call e.g.
validatoron it.These errors can be quite confusing and probably the most common bug report on our bug tracker.
- kw_only (bool) – Make all attributes keyword-only (Python 3+)
in the generated
__init__(ifinitisFalse, this parameter is ignored). - cache_hash (bool) – Ensure that the object’s hash code is computed
only once and stored on the object. If this is set to
True, hashing must be either explicitly or implicitly enabled for this class. If the hash code is cached, avoid any reassignments of fields involved in hash code computation or mutations of the objects those fields point to after object creation. If such changes occur, the behavior of the object’s hash code is undefined. - auto_exc (bool) –
If the class subclasses BaseException (which implicitly includes any subclass of any exception), the following happens to behave like a well-behaved Python exceptions class:
- the values for eq, order, and hash are ignored and the
instances compare and hash by the instance’s ids (N.B.
attrswill not remove existing implementations of__hash__or the equality methods. It just won’t add own ones.), - all attributes that are either passed into
__init__or have a default value are additionally available as a tuple in theargsattribute, - the value of str is ignored leaving
__str__to base classes.
- the values for eq, order, and hash are ignored and the
instances compare and hash by the instance’s ids (N.B.
- collect_by_mro (bool) –
Setting this to True fixes the way
attrscollects attributes from base classes. The default behavior is incorrect in certain cases of multiple inheritance. It should be on by default but is kept off for backward-compatibility.See issue #428 for more details.
- getstate_setstate (Optional[bool]) –
Note
This is usually only interesting for slotted classes and you should probably just set auto_detect to True.
If True,
__getstate__and__setstate__are generated and attached to the class. This is necessary for slotted classes to be pickleable. If left None, it’s True by default for slotted classes andFalsefor dict classes.If auto_detect is True, and getstate_setstate is left None, and either
__getstate__or__setstate__is detected directly on the class (i.e. not inherited), it is set to False (this is usually what you want). - on_setattr –
A callable that is run whenever the user attempts to set an attribute (either by assignment like
i.x = 42or by using setattr likesetattr(i, "x", 42)). It receives the same arguments as validators: the instance, the attribute that is being modified, and the new value.If no exception is raised, the attribute is set to the return value of the callable.
If a list of callables is passed, they’re automatically wrapped in an attrs.setters.pipe.
- field_transformer (Optional[callable]) – A function that is called with the original class object and all
fields right before
attrsfinalizes the class. You can use this, e.g., to automatically add converters or validators to fields based on their types. See transform-fields for more details. - match_args (bool) – If True (default), set
__match_args__on the class to support PEP 634 (Structural Pattern Matching). It is a tuple of all positional-only__init__parameter names on Python 3.10 and later. Ignored on older Python versions.
New in version 16.0.0: slots
New in version 16.1.0: frozen
New in version 16.3.0: str
New in version 16.3.0: Support for
__attrs_post_init__.Changed in version 17.1.0: hash supports
Noneas value which is also the default now.New in version 17.3.0: auto_attribs
Changed in version 18.1.0: If these is passed, no attributes are deleted from the class body.
Changed in version 18.1.0: If these is ordered, the order is retained.
New in version 18.2.0: weakref_slot
Deprecated since version 18.2.0:
__lt__,__le__,__gt__, and__ge__now raise a DeprecationWarning if the classes compared are subclasses of each other.__eqand__ne__never tried to compared subclasses to each other.Changed in version 19.2.0:
__lt__,__le__,__gt__, and__ge__now do not consider subclasses comparable anymore.New in version 18.2.0: kw_only
New in version 18.2.0: cache_hash
New in version 19.1.0: auto_exc
Deprecated since version 19.2.0: cmp Removal on or after 2021-06-01.
New in version 19.2.0: eq and order
New in version 20.1.0: auto_detect
New in version 20.1.0: collect_by_mro
New in version 20.1.0: getstate_setstate
New in version 20.1.0: on_setattr
New in version 20.3.0: field_transformer
Changed in version 21.1.0:
init=Falseinjects__attrs_init__Changed in version 21.1.0: Support for
__attrs_pre_init__Changed in version 21.1.0: cmp undeprecated
New in version 21.3.0: match_args
- these (dict of str to attr.ib) –
-
narupa.ase.openmm.runner.openmm_ase_frame_adaptor(ase_atoms: ase.atoms.Atoms, frame_publisher: narupa.trajectory.frame_publisher.FramePublisher)¶ Generates and sends frames for a simulation using an :class: OpenMMCalculator.