MDMC.utilities package

Submodules

MDMC.utilities.cli module

Command line interface for MDMC.

Notes

This is only used to provide a simple method for users to run installation tests.

MDMC.utilities.cli.get_parser() ArgumentParser[source]

Create and return a parser for sys.args.

Returns:

The setup argument parser.

Return type:

ArgumentParser

MDMC.utilities.cli.main()[source]

Entry point exposed for running installation tests.

MDMC.utilities.installation_tests module

Module containing installation tests.

These determine which features are available in an installation of MDMC.

This includes:

  • Whether MDMC can be imported.

  • Whether an MD engine can be run (e.g. LAMMPS).

  • Whether X11 forwarding is enabled and the ASE gui can run.

  • Whether the optional dependencies for the dynamic plotting utility have been installed.

These tests exist so that a user can test their installation of MDMC.

class MDMC.utilities.installation_tests.InstlTestBase[source]

Bases: ABC

Base class for installation tests.

success

A str denoting if the test has PASSED, FAILED, or is INCOMPLETE.

Type:

Literal[‘PASSED’, ‘FAILED’, ‘INCOMPLETE’]

name

Name of current test.

Type:

str

log_test_passed() None[source]

Log that the test passed.

abstract run()[source]

Run the test and sets the value of self.success.

property success: Literal['PASSED', 'FAILED', 'INCOMPLETE']

Get whether or not the test has PASSED, FAILED or is INCOMPLETE.

Returns:

One of “PASSED”, “FAILED” or “INCOMPLETE” depending on test state.

Return type:

str

Raises:

ValueError – If test state is invalid.

class MDMC.utilities.installation_tests.InstlTestCore[source]

Bases: InstlTestBase

Class to test if all MDMC subpackages can be imported.

run() None[source]

Run the test and sets the value of self.success.

class MDMC.utilities.installation_tests.InstlTestDynamicPlottingDependencies[source]

Bases: InstlTestBase

Test if the dynamic plotting optional dependencies are installed.

LOG_ERROR_MSG = 'Due to this, dynamic plotting of the refinement will not be possible.'
run() None[source]

Run the test and sets the value of self.success.

class MDMC.utilities.installation_tests.InstlTestFactory[source]

Bases: object

Testing factory class.

A factory class which keeps a registry of the installation tests and creates instances of them.

classmethod create_instl_test(name: str) InstlTestBase[source]

Instantiate the installation test for the class name.

Parameters:

name (str) – The registry name of the class to be initialized.

Returns:

Corresponding class with name name.

Return type:

InstlTestBase

classmethod register(name: str) Callable[source]

Decorator for registering installation test classes.

The name with which the test is registered should be the parameter passed to the decorator.

Parameters:

name (str) – The name with which the test is registered.

Returns:

Wrapped class registered in factory.

Return type:

function

Examples

To register the InstlTestCore class with InstlTestFactory:

@InstlTestFactory.register('core')
class InstlTestCore(InstlTestBase):
registry: Dict[str, InstlTestBase] = {'Dynamic plotting dependencies': <class 'MDMC.utilities.installation_tests.InstlTestDynamicPlottingDependencies'>, 'LAMMPS': <class 'MDMC.utilities.installation_tests.InstlTestLAMMPS'>, 'X11 forwarding': <class 'MDMC.utilities.installation_tests.InstlTestX11Forwarding'>, 'core': <class 'MDMC.utilities.installation_tests.InstlTestCore'>}
class MDMC.utilities.installation_tests.InstlTestLAMMPS[source]

Bases: InstlTestBase

Class to test if LAMMPS is installed and PyLammps interface can be accessed.

LOG_ERROR_MSG: str = 'Due to this, MDMC will not be able to run MD simulations with LAMMPS as the MD engine. Other MD engines may still be available.'
run() None[source]

Run the test and sets the value of self.success.

class MDMC.utilities.installation_tests.InstlTestX11Forwarding[source]

Bases: InstlTestBase

Class to test if tkinter can access the display.

This is used to determine if X11 forwarding is working in Docker/Singularity containers.

LOG_ERROR_MSG: str = 'Due to this, GUI elements requiring tkinter, such as the ASE viewer, will not be available. Other viewer options, such as the X3DOM viewer, can still be used.'
run() None[source]

Run the test and sets the value of self.success.

MDMC.utilities.installation_tests.run_installation_tests()[source]

Run all installation tests and print the result for each test.

MDMC.utilities.partitioning module

Partitioning utilities.

Utilities related to partitioning iterators into their composite components.

MDMC.utilities.partitioning.partition(items: iter, predicate: Callable[[any], bool]) tuple[source]

Partition an iterable using a predicate.

Parameters:
  • items (iterable) – An interable to be partitioned.

  • predicate (function) – A predicate that can be applied to items to returned True or False.

Returns:

A tuple of (gen_true, gen_false), where gen_true is a generator of all items for which the predicate returned True, and gen_false is a generator of all items for which the ``predicate returned False.

Return type:

tuple

MDMC.utilities.partitioning.partition_interactions(interactions: Iterable[Interaction], names: list[str], unpartitioned: bool = False, lst: bool = False) tuple[Interaction, ...][source]

Partition an iterable of Interaction s by a list names.

This occurs by using partition to filter out one Interaction type for each loop, so previously identified Interactions are no longer considered.

Parameters:
  • interactions (iterable of Interactions) – An interable of Interaction objects to be partitioned.

  • names (list of str) – Names of Interaction classes.

  • unpartitioned (bool, optional) – If True, then a generator containing any Interaction objects that did not have a name in names is returned as an additional item in the tuple. Default is False.

  • lst (bool, optional) – If True, then the returned tuple contains list rather than generators. Interaction objects which have the name specified by names[n]. Default is False.

Returns:

A tuple of length len(names) where index n is a generator of all of the Interaction objects which have the name specified by names[n]. If unpartitioned is True, tuple is length n+1. If lst is True, the generators are replaced by list.

Return type:

tuple

Examples

Partion interactions into Bonds and BondAngles:

bonds, angles = partition_interactions(interactions,
                                       ['Bond, BondAngle'])

MDMC.utilities.plotting module

Utility functions for plotting.

These are additional functions which can be used to plot specific MDMC data, e.g. dynamic plotting during a refinement. All plotting requires matplotlib to be installed, and dynamic plotting requires execution to be performed within a Jupyter notebook in order to display correctly.

MDMC.utilities.plotting.CNVS_WIDTH = 800

Default CNVS width.

MDMC.utilities.plotting.N_TEXT_LINES = 5

Default number of text lines.

MDMC.utilities.plotting.PLOT_HEIGHT = 360

Default plot height.

MDMC.utilities.plotting.VBOX_HEIGHT = '73%'

Default VBox height.

MDMC.utilities.plotting.plot_progress(inst: Control, ynames: str) Control[source]

Plot current progress of a control.

Modifies an instance of MDMC.control.Control so that the progress of 1 or more variables is plotted with each step when refine is called.

This takes an instance of Control as a parameter and returns a modified instance, which can be treated exactly as the original instance. See the examples section for more details.

Applying plot_progress will also change the text output so that only the more recent five steps are shown.

Parameters:
  • inst (Control) – An instance of the MDMC.control.Control class.

  • ynames (str, list of str) – One or more str with the name of the variable to be displayed with each step of the refinement. These variables must correspond to the column names in inst.minimizer.history, for example the names of the parameters that are being refined. It is recommended that a maximum of 8 names is provided, as otherwise the graph sizes become too small.

Returns:

An instance of the MDMC.control.Control class, which is modified so that a plot is displayed when inst.refine is called.

Return type:

Control

Notes

This plotting should only be used in a Jupyter notebook and requires ipywidgets and matplotlib to interactively display the progress. The matplotlib backend must be set to ‘notebook’ before calling refine. This can be done by executing the following magic call within a Jupyter notebook cell:

%matplotlib notebook

Examples

Modifying a Control instance to plot the progress of the ‘FoM’ with each refinement step. This should be executed within a Jupyter notebook:

%matplotlib notebook
control = Control(...)  # ... represents some parameters
control = plot_progress(control, 'FoM')
control.refine(100)

First the matplotlib backend is set to ‘notebook’, then the Control instance is modified, and then a refinement is run. With each step of the refinement a graph of ‘FoM’ against ‘Steps’ will be plotted.

Modifying a Control instance to plot the progress of the ‘FoM’, ‘sigma’, and ‘epsilon’ with each refinement step. This should be executed within a Jupyter notebook:

%matplotlib notebook
control = Control(...)  # ... represents some parameters
control = plot_progress(control, ['FoM', 'sigma', 'epsilon'])
control.refine(100)

With each step of the refinement a graph of ‘FoM’ against ‘Steps’ will be plotted, a graph of ‘sigma’ against ‘Steps’ will be plotted, and a graph of ‘epsilon’ against ‘Steps’ will be plotted.

MDMC.utilities.structures module

Utility functions for structures.

MDMC.utilities.structures.is_atom(atom: object) bool[source]

Checks if the passed object is an instance of the Atom class.

Parameters:

atom – Object to be checked.

Returns:

True if the passed Object is an Atom.

Return type:

bool

MDMC.utilities.tinker_converter module

Read TINKER .prm files and convert them to MDMC force field python files.

MDMC.utilities.tinker_converter.convert_units(series: Series) str[source]

Convert from TINKER units (kcal) to kJ.

Parameters:

series (pandas.Series) – The Series for which the parameters will be converted.

Returns:

Value in kJ.

Return type:

str

MDMC.utilities.tinker_converter.dummy_headers(start: int, end: int) list[str][source]

Generate dummy headers c0, c1, c2, … until end (exclusive).

Parameters:
  • start (int) – The start of the header (inclusive).

  • end (int) – The end of the header (exclusive).

Returns:

A str (c{i}) for each i between start and end (exclusive).

Return type:

list of str

MDMC.utilities.tinker_converter.parse_dataframe(dataframe: DataFrame, drop: list, names: list) DataFrame[source]

Parse a single dataframe.

Parses a dataframe containing single datatype (e.g. atom or angles) by dropping any unnecessary columns and setting correct header names.

If the dataframe has a header ‘c0’ this is always dropped

Parameters:
  • dataframe (pandas.DataFrame) – The dataframe to be parsed.

  • drop (list) – A list of names of headers which will be dropped.

  • names (list) – A list of the header names which will be set for the remaining columns..

Returns:

A parsed DataFrame.

Return type:

pandas.DataFrame

MDMC.utilities.tinker_converter.parse_prm(dataframe: DataFrame) tuple[DataFrame, ...][source]

Parse a .prm file into DataFrames.

Parameters:

dataframe (pandas.DataFrame) – A dataframe of raw data read from a .prm file.

Returns:

A tuple of dataframes, with each dataframe possessing only the entries starting with the corresponding definition.

Return type:

tuple[pd.DataFrame, …]

MDMC.utilities.tinker_converter.read_prm(fname: str, ncols: int = 14) DataFrame[source]

Read a TINKER .prm (force field) file.

Ignores all errors raised by incorrectly formatted data, so will be susceptible to incorrectly formatted .prm files.

Parameters:
  • fname (str) – The name of the .prm file.

  • ncols (int, optional) – The largest number of columns that should be read. The default is 14, which is the number of columns required for the torsion (proper dihedral) in oplsaa.prm.

Returns:

A dataframe with columns (named c0, c1, …) up to (but not including) ncols. Each row contains a row read correctly (i.e. no Error thrown) from the .prm file.

Return type:

pandas.DataFrame

MDMC.utilities.tinker_converter.write_data(fname: str, atoms: DataFrame, path: str = None, **settings) None[source]

Write forcefield data to a .dat file.

Parameters:
  • fname (str) – File name to write to.

  • atoms (pd.DataFrame) – Force field to write.

  • path (str, optional) – Path to read data from.

  • **settings – Extra options.

  • orig_file (str) – Original file forcefield read from.

Notes

For each of disp, bond, angle, proper and improper, there exists a pair of optional arguments: <type>s and <type>_function Which define the presence of parameters and the function to compute them.

MDMC.utilities.tinker_converter.write_force_field_module(fname: str, atoms: DataFrame, *interactions: DataFrame, path: str = None, module_docstring: str = None, class_docstring: str = None, **settings)[source]

Write a temporary module to allow Tinker potentials to be imported.

Parameters:
  • fname (str) – Name of the module (excluding the file extension) and the class.

  • atoms (pandas.DataFrame) – Atoms to dump.

  • *interactions – An arbitrary number of pandas.DataFrame objects.

  • path (str, optional) – Path to dump to.

  • module_docstring (str, optional) – Docstring for created module.

  • class_docstring (str, optional) – Docstring for created class.

  • **settings – Extra options.

Notes

Windows and Mac OS are case insensitive, so if a file exists in the specified path with the same case insensitive name as fname (e.g. if fname=’spce’ and ‘SPCE’ already exists), the existing file will be overwritten. So on case insensitive OS, fname should always be unique, without considering the case.

MDMC.utilities.trajectory_slicing module

Utility for slicing a CompactTrajectory object into sub-trajectories

MDMC.utilities.trajectory_slicing.slice_trajectory(trj: CompactTrajectory, subtrj_len: int, cont_slicing: bool = False) Iterable[CompactTrajectory][source]

Takes a CompactTrajectory object and slices it into a list of shorter CompactTrajectory objects of equal length.

Parameters:
  • trj (CompactTrajectory) – The trajectory that should be divided into smaller sub-trajectories.

  • subtrj_len (int) – The length (number of frames) of the sub-trajectories.

  • cont_slicing (bool, optional) –

    Flag to set if a rolling/continuous slicing should be used with frames allowed to appear in multiple sub-trajectories.

    If set to False (default) then the sub-trajectories are separate subsets of the CompactTrajectory with distinct frames.

    Note that if set to False it checks if len(trj)%subtrj_len==0 and if not it does not use the first len(trj)%subtrj_len frames of the CompactTrajectory.

Yields:

CompactTrajectory – Sub-trajectories of length subtrj_len.

Examples

If len(CompactTrajectory)==10 then the following examples would give:

>>> slice_trajectory(CompactTrajectory, subtrj_len=5, cont_slicing=False):
[CompactTrajectory[0:5], CompactTrajectory[5:10]]
>>> slice_trajectory(CompactTrajectory, subtrj_len=4, cont_slicing=False):
[CompactTrajectory[2:6], CompactTrajectory[6:10]]
>>> slice_trajectory(CompactTrajectory, subtrj_len=8, cont_slicing=True):
[CompactTrajectory[0:8], CompactTrajectory[1:9], CompactTrajectory[2:10]]

Module contents

Utilities relating to MDMC.

Contents

  • cli

  • installation_tests

  • tinker_converter

  • plotting

  • structures

MDMC.utilities.run_installation_tests()[source]

Run all installation tests and print the result for each test.