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.NarupaRunner

A 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 MolecularDynamics object 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 OpenMMIMDRunner from 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 False run in a separate thread. By default, “block” is None, which means it is automatically set to True if a number of steps is provided and to False otherwise.
  • 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 None is 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: object

Class representing parameters for IMD runners.

class narupa.ase.openmm.runner.LoggingParams(trajectory_file: Optional[str] = None, write_interval: int = 1)

Bases: object

Class representing parameters for trajectory logging

class narupa.ase.openmm.runner.OpenMMIMDRunner(*args, **kwargs)

Bases: narupa.ase.openmm.runner.ASEOpenMMRunner

class narupa.ase.openmm.runner.TrajectoryLoggerInfo(trajectory_logger: narupa.ase.trajectory_logger.TrajectoryLogger, params: narupa.ase.openmm.runner.LoggingParams)

Bases: object

Class 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, attrs will 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 repr output.
  • auto_detect (bool) –

    Instead of setting the init, repr, eq, order, and hash arguments explicitly, assume they are set to True unless 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, attrs will deduce eq=False and 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 attrs from 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 True or False to init, repr, eq, order, cmp, or hash overrides whatever auto_detect would determine.

    auto_detect requires Python 3. Setting it True on Python 2 raises an attrs.exceptions.PythonTooOldError.

  • repr (bool) – Create a __repr__ method with a human readable representation of attrs attributes..
  • str (bool) – Create a __str__ method that is identical to __repr__. This is usually not necessary except for Exceptions.
  • eq (Optional[bool]) –

    If True or None (default), add __eq__ and __ne__ methods that check two instances for equality.

    They compare the instances as if they were tuples of their attrs attributes 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. If None (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.

    1. If both are True, attrs will generate a __hash__ for you.
    2. If eq is True and frozen is False, __hash__ will be set to None, marking it unhashable (which it is).
    3. If eq is False, __hash__ will be left untouched meaning the __hash__ method of the base class will be used (if base class is object, this means it will fall back to id-based hashing.).

    Although not recommended, you can decide for yourself and force attrs to create one (e.g. if the class is immutable even though you didn’t freeze it programmatically) by passing True or 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.

  • init (bool) –

    Create a __init__ method that initializes the attrs attributes. 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 init is False, an __attrs_init__ method will be injected instead. This allows you to define a custom __init__ method that can do pre-init work such as super().__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

    1. This is achieved by installing a custom __setattr__ method on your class, so you can’t implement your own.
    2. True immutability is impossible in Python.
    3. This does have a minor a runtime performance impact <how-frozen> when initializing new instances. In other words: __init__ is slightly slower with frozen=True.
    4. If a class is frozen, you cannot modify self in __attrs_post_init__ or a self-written __init__. You can circumvent that limitation by using object.__setattr__(self, "attribute_name", value).
    5. Subclasses of a frozen class are frozen too.
  • weakref_slot (bool) – Make instances weak-referenceable. This has no effect unless slots is 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 attrs encounters a field that is set to an attr.ib but lacks a type annotation, an attr.exceptions.UnannotatedAttributeError is raised. Use field_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 using attr.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. validator on 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__ (if init is False, 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. attrs will 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 the args attribute,
    • the value of str is ignored leaving __str__ to base classes.
  • collect_by_mro (bool) –

    Setting this to True fixes the way attrs collects 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 and False for 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 = 42 or by using setattr like setattr(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 attrs finalizes 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 None as 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. __eq and __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=False injects __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

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.