General helper functions

Small helper and utilities functions that don’t fit anywhere else.

maicos.lib.util.DOC_DICT

Dictionary containing the keys and the actual docstring used by maicos.lib.util.render_docs().

maicos.lib.util.DOI_LIST

References associated with MAICoS

class maicos.lib.util.MomentAccumulator(requested_pairs=())[source]

Bases: object

Streaming mean, variance and covariance of per-frame observables.

This is the statistics backend of AnalysisBase. Each frame’s observables are merged into running statistics with Welford’s online algorithm, so no per-frame data has to be stored. Observables may be scalars or arrays (e.g. profiles), in which case every element is accumulated independently. A frame can report a single sample per observable or, via the population / variance / covariance containers, the mean of several samples.

After the first frame is passed to register(), every following frame is merged with update(). The running statistics are exposed as Results containers keyed by observable name:

  • means: mean of each observable

  • sems: standard error of the mean

  • sums: sum of the samples

  • pop: number of samples

  • M2: sum of squared deviations from the mean

  • C: co-moment of each requested pair, keyed by make_pair_key()

cov() returns the covariance of two observable means and propagate_error() the standard error of a function of several observables, including their cross-covariances.

Parameters:

requested_pairs (iterable of tuple of str) – Canonical observable pairs (see make_pair_key()) whose off-diagonal covariance should be accumulated. The observables of each pair must broadcast against each other and be co-sampled (same population). Only the listed pairs are tracked. Empty (the default) disables covariance entirely.

Examples

Accumulate two correlated scalar observables over four frames

>>> import numpy as np
>>> from MDAnalysis.analysis.base import Results
>>> from maicos.lib.util import MomentAccumulator, make_pair_key
>>> acc = MomentAccumulator({make_pair_key("x", "y")})
>>> acc.register(Results(x=0.0, y=0.0), Results(), Results(), Results())
>>> for x, y in [(0.0, 1.0), (0.0, 1.0), (6.0, 6.0)]:
...     acc.update(Results(x=x, y=y), Results(), Results(), Results())
>>> print(acc.means.x, acc.means.y)
1.5 2.0

Covariance of the means and the error of f = x - y, which is smaller than the uncorrelated estimate because x and y are positively correlated

>>> print(acc.cov("x", "y"))
1.5
>>> print(acc.propagate_error({"x": 1.0, "y": -1.0}))
0.25
>>> print(np.sqrt(acc.sems.x**2 + acc.sems.y**2))
1.75
cov(key_i: str, key_j: str) → ndarray[source]

Covariance of the means of two observables.

The element-wise covariance \(\mathrm{Cov}(\bar x_i, \bar x_j)\) of the observable means accumulated across frames. The diagonal (key_i == key_j) equals the squared standard error of the mean, sems.

Parameters:
  • key_i (str) – Keys of the two observables.

  • key_j (str) – Keys of the two observables.

Returns:

Covariance of the means of key_i and key_j.

Return type:

numpy.ndarray

Raises:

KeyError – If the off-diagonal pair was not requested in _compute_covariance.

propagate_error(grads: dict) → ndarray[source]

Propagate observable errors through an estimator.

Computes the standard error of an estimator \(f\) from the full covariance of the observable means,

\[\sigma_f^2 = \sum_{ij} \frac{\partial f}{\partial x_i} \frac{\partial f}{\partial x_j} \mathrm{Cov}(\bar x_i, \bar x_j),\]

where grads[key] provides \(\partial f / \partial x_{key}\). The diagonal terms reproduce the independent-variable (uncorrelated) estimate; the off-diagonal terms add the cross-covariance contributions.

Parameters:

grads (dict) – Mapping of observable key to the gradient of the estimator with respect to that observable’s mean.

Returns:

Standard error of the estimator.

Return type:

numpy.ndarray

Raises:

KeyError – If two of the supplied observables have no tracked covariance (see cov()).

register(obs, _pop, _var, _cov)[source]

Seed the running containers from the first frame’s observables.

Parameters:
  • obs (MDAnalysis.analysis.base.Results) – The current frame’s observables, keyed by observable name.

  • _pop (MDAnalysis.analysis.base.Results) – The current frame’s sample count for each observable. Missing entries default to a unit population (the observable is a single sample).

  • _var (MDAnalysis.analysis.base.Results) – The current frame’s within-frame variance for each observable.

  • _cov (MDAnalysis.analysis.base.Results) – The current frame’s within-frame covariance, keyed by canonical observable pair (see maicos.lib.util.make_pair_key()).

update(obs, _pop, _var, _cov)[source]

Welford merge of the current frame into all running statistics.

Covariance is merged first, while the running means still hold their pre-frame values; the variance merge advances the means afterwards.

Parameters:
  • obs (MDAnalysis.analysis.base.Results) – The current frame’s observables, keyed by observable name.

  • _pop (MDAnalysis.analysis.base.Results) – The current frame’s sample count for each observable. Missing entries default to a unit population (the observable is a single sample).

  • _var (MDAnalysis.analysis.base.Results) – The current frame’s within-frame variance for each observable.

  • _cov (MDAnalysis.analysis.base.Results) – The current frame’s within-frame covariance, keyed by canonical observable pair (see maicos.lib.util.make_pair_key()).

maicos.lib.util.PathLike: TypeAlias = str | os.PathLike[str]

Type for arguments accepting a file system path.

class maicos.lib.util.Unit_vector(*args, **kwargs)[source]

Bases: Protocol

Protocol class for unit vector methods type hints.

maicos.lib.util.atomgroup_header(AtomGroup: AtomGroup) → str[source]

Return a string containing infos about the AtomGroup.

Infos include the total number of atoms, the including residues and the number of residues. Useful for writing output file headers.

Parameters:

AtomGroup (MDAnalysis.core.groups.AtomGroup) – The AtomGroup object containing the atoms.

Returns:

A string containing the AtomGroup information.

Return type:

str

maicos.lib.util.charge_neutral(filter: str) → Callable[source]

Raise a Warning when AtomGroup is not charge neutral.

Class Decorator to raise an Error/Warning when AtomGroup in an AnalysisBase class is not charge neutral. The behaviour of the warning can be controlled with the filter attribute. If the AtomGroup’s corresponding universe is non-neutral an ValueError is raised.

Parameters:

filter (str) – Filter type to control warning filter. Common values are: “error” or “default” See warnings.simplefilter() for more options.

maicos.lib.util.check_file_extension(filename: str | PathLike[str], extension: str) → str[source]

Ensure filename ends with extension, appending it with a warning.

If filename does not end with extension, the extension is appended and a UserWarning is issued.

Parameters:
  • filename (str or os.PathLike) – Name of the file to be checked.

  • extension (str) – Expected file extension, including the leading dot (e.g. ".dat").

Returns:

filename as a string, with extension appended if necessary.

Return type:

str

maicos.lib.util.citation_reminder(*dois: str) → str[source]

Prints citations in order to remind users to give due credit.

Parameters:

dois (list) – dois associated with the method which calls this. Possible dois are registered in maicos.lib.util.DOI_LIST.

Returns:

cite – formatted citation reminders

Return type:

str

maicos.lib.util.correlation_analysis(timeseries: ndarray) → float[source]

Timeseries correlation analysis.

Analyses a timeseries for correlation and prints a warning if the correlation time is larger than the step size.

Parameters:

timeseries (numpy.ndarray) – Array of (possibly) correlated data.

Returns:

corrtime – Estimated correlation time of timeseries.

Return type:

float

maicos.lib.util.get_center(atomgroup: AtomGroup, bin_method: str, compound: str) → ndarray[source]

Center attribute for an MDAnalysis.core.groups.AtomGroup.

This function acts as a wrapper for the MDAnalysis.core.groups.AtomGroup.center() method, providing a more user-friendly interface by automatically determining the appropriate weights based on the chosen binning method.

Parameters:
  • atomgroup (MDAnalysis.core.groups.AtomGroup) – A AtomGroup for which the calculations are performed.

  • bin_method ({"com", "cog", "coc"}) –

    Method for the position binning.

    The possible options are center of mass ("com"), center of geometry ("cog"), and center of charge ("coc").

  • compound ({"group", "segments", "residues", "molecules", "fragments"}) – The compound to be used in the center calculation. For example, "residue", "segment", etc.

Returns:

The coordinates of the calculated center.

Return type:

np.ndarray

Raises:

ValueError – If the provided bin_method is not one of {"com", "cog", "coc"}.

maicos.lib.util.get_cli_input() → str[source]

Return a proper formatted string of the command line input.

Returns:

A string representing the command line input in a proper format.

Return type:

str

maicos.lib.util.get_compound(atomgroup: AtomGroup) → str[source]

Returns the highest order topology attribute.

The order is “molecules”, “fragments”, “residues”. If the topology contains none of those attributes, an AttributeError is raised.

Parameters:

atomgroup (MDAnalysis.core.groups.AtomGroup) – A AtomGroup for which the calculations are performed.

Returns:

Name of the topology attribute.

Return type:

str

Raises:

AttributeError – atomgroup is missing any connection information”

maicos.lib.util.get_module_input_str(module_obj)[source]

Make a string with all the modules parameters.

maicos.lib.util.maicos_banner(version: str = '', frame_char: str = '-') → str[source]

Prints ASCII banner resembling the MAICoS Logo with 80 chars width.

Parameters:
  • version (str) – Version string to add to the banner.

  • frame_char (str) – Character used to as framing around the banner.

Returns:

banner – formatted banner

Return type:

str

maicos.lib.util.make_pair_key(key_i: str, key_j: str) → tuple[str, str][source]

Return a canonical pair key for two observable keys.

The key is ordered so that make_pair_key(a, b) == make_pair_key(b, a), guaranteeing deterministic lookups regardless of argument order.

Parameters:
  • key_i (str) – Keys of the two observables.

  • key_j (str) – Keys of the two observables.

Returns:

Canonical (smaller, larger) pair key.

Return type:

tuple[str, str]

maicos.lib.util.render_docs(func: Callable) → Callable[source]

Replace all template phrases in the functions docstring.

Keys for the replacement are taken from in maicos.lib.util.DOC_DICT.

Parameters:

func (callable) – The callable (function, class) where the phrase old should be replaced.

Returns:

callable with replaced phrase

Return type:

Callable

maicos.lib.util.times_to_frames(start: str, stop: str, step: str, dt: float) → dict[source]

Convert ‘start’, ‘stop’, ‘step’ into their frame number based on given dt.

Parameters:
  • start (str) – start in a ‘12ps’ format

  • stop (str) – stop in a ‘12ps’ format

  • step (str) – step in a ‘12ps’ format

  • dt (float) – the time step in ps

Returns:

Dictionnary containing start, stop and step frames

Return type:

dict

Example

>>> times_to_frames("2ps", "12ps", "2ps", 1)
{'start': 2, 'stop': 12, 'step': 2}
>>> times_to_frames("0ns", "2ns", "10ps", 0.01)
{'start': 0, 'stop': 200000, 'step': 1000}
maicos.lib.util.trajectory_precision(trajectory: ReaderBase, dim: int = 2) → ndarray[source]

Detect the precision of a trajectory.

Parameters:
Returns:

precision – Precision of each frame of the trajectory.

If the trajectory has a high precision, its resolution will not be detected, and a value of 1e-4 is returned.

Return type:

numpy.ndarray

maicos.lib.util.triclinic_to_orthorhombic(dimensions: ndarray) → ndarray[source]

Convert triclinic box dimensions to an orthorhombic bounding box.

Computes the orthorhombic box that corresponds to the GROMACS representation of a triclinic cell. For orthorhombic input, the box is returned unchanged (with angles set to 90).

Parameters:

dimensions (numpy.ndarray) – Box dimensions in MDAnalysis format [a, b, c, alpha, beta, gamma], where lengths are in Angstrom and angles in degrees.

Returns:

Orthorhombic box dimensions [xx, yy, zz, 90, 90, 90].

Return type:

numpy.ndarray

maicos.lib.util.unit_vectors_cylinder(atomgroup: AtomGroup, grouping: str, bin_method: str, dim: int, pdim: str) → ndarray[source]

Calculate cylindrical unit vectors in cartesian coordinates.

Parameters:
  • atomgroup (MDAnalysis.core.groups.AtomGroup) – A AtomGroup for which the calculations are performed.

  • grouping ({"atoms", "residues", "segments", "molecules", "fragments"}) –

    Atom grouping for the calculations.

    The possible grouping options are the atom positions (in the case where grouping="atoms") or the center of mass of the specified grouping unit (in the case where grouping="residues", "segments", "molecules" or "fragments").

  • bin_method ({"com", "cog", "coc"}) –

    Method for the position binning.

    The possible options are center of mass ("com"), center of geometry ("cog"), and center of charge ("coc").

  • dim ({0, 1, 2}) – Dimension for binning (x=0, y=1, z=1).

  • pdim ({"r", "z"}) – direction of the projection

Returns:

Array of the calculated unit vectors with shape (3,) for pdim='z' and shape (3,n) for pdim='r'. The length of n depends on the grouping.

Return type:

numpy.ndarray

maicos.lib.util.unit_vectors_planar(atomgroup: AtomGroup, grouping: str, pdim: int) → ndarray[source]

Calculate unit vectors in planar geometry.

Parameters:
  • atomgroup (MDAnalysis.core.groups.AtomGroup) – A AtomGroup for which the calculations are performed.

  • grouping ({"atoms", "residues", "segments", "molecules", "fragments"}) –

    Atom grouping for the calculations.

    The possible grouping options are the atom positions (in the case where grouping="atoms") or the center of mass of the specified grouping unit (in the case where grouping="residues", "segments", "molecules" or "fragments").

  • pdim ({0, 1, 2}) – direction of the projection

Returns:

the unit vector

Return type:

numpy.ndarray

maicos.lib.util.unit_vectors_sphere(atomgroup: AtomGroup, grouping: str, bin_method: str) → ndarray[source]

Calculate spherical unit vectors in cartesian coordinates.

Parameters:
  • atomgroup (MDAnalysis.core.groups.AtomGroup) – A AtomGroup for which the calculations are performed.

  • grouping ({"atoms", "residues", "segments", "molecules", "fragments"}) –

    Atom grouping for the calculations.

    The possible grouping options are the atom positions (in the case where grouping="atoms") or the center of mass of the specified grouping unit (in the case where grouping="residues", "segments", "molecules" or "fragments").

  • bin_method ({"com", "cog", "coc"}) –

    Method for the position binning.

    The possible options are center of mass ("com"), center of geometry ("cog"), and center of charge ("coc").

Returns:

Array of the calculated unit vectors with shape (3,n). The length of n depends on the grouping.

Return type:

numpy.ndarray

maicos.lib.util.unwrap_refgroup(original_class)[source]

Class decorator error if unwrap = False and refgroup != None.