MDMC.common package
Submodules
MDMC.common.constants module
Module which defines physical constants
MDMC.common.decorators module
Module which defines decorators.
- MDMC.common.decorators.mod_docstring(replacements: dict[str, str]) Callable[source]
Decorator for modifying the docstring of a function, method, class or property.
This is done by replacing specified substrings. After replacement the docstring is text wrapped to ensure that line length and indentations are preserved.
While this can be used for replacements in equations, care must be taken to ensure that wrapping does not cause line breaks in invalid places in the LaTeX.
- Parameters:
replacements (dict[str, str]) – {old: new} pairs where old is a str in the docstring which will be replaced, and new is the str it should be replaced with.
- Returns:
A decorator which modifies the docstring of a function, method, class or property.
- Return type:
function
- Raises:
TypeError – If
mod_docstringis applied to an object which is not a function, method, class, or property.
Examples
To dynamically modify the docstring of a function so “this” is replaced with “that”:
@mod_docstring({'this': 'that'}) def function(): """ The word this will be replaced """
To dynamically modify the docstring of a class so “this” is replaced with “that”:
@mod_docstring({'this': 'that'}) class DocClass(): """ This is the class level docstring. The word this will be replaced. """
To dynamically modify the docstring of a property so “this” is replaced with “that”:
@property @mod_docstring({'this': 'that'}) def prop(): """ The word this will be replaced. """
- MDMC.common.decorators.repr_decorator(attribute: str, *attributes: str | None)[source]
Implement
__repr__for a class using passed attributes (including properties).The first element of all
__repr__returns is always the name of the class.Warning
Testing for
repr_decoratoris restricted to testing the decorator outputs the correct format, not whether each occurence it is used is valid. It is strongly recommended that classes decorated withrepr_decoratorare tested to ensure thatrepr(class)is valid, for instance whether the class actually has all of the attributes passed as str torepr_decorator.- Parameters:
attribute (str) – The name of an attribute of the class being decorated. This attribute (or property) will be included in the
__repr__of the class.*attributes (str) – Zero or more str with the name of an attribute (or property) of the class being decorated. These attributes will be included in the
__repr__of the class.
- Returns:
A class with
__repr__implemented such thatattributeandattributesare printed.- Return type:
class
Examples
Add a
repr_decoratorto theAtomclass to include thenameattribute and thepositionproperty:>>> @repr_decorator('name', 'position') ... Class Atom(Structure): ... ... def __init__(self, element, name, position): ... self.element = element ... self.name = name ... self.position = position ... ... @property ... def position(self): ... return self._position ... ... atom = Atom('H', 'Hydrogen', [1., 1., 1.]) ... atom < Atom {name: 'Hydrogen', position: [1., 1., 1.]}>
- MDMC.common.decorators.set_docstring(docstring: str) Callable[source]
Decorator for setting the docstring of a function, method, class or property.
The new docstring is text wrapped to ensure that the line length is valid. It is assumed that the specified docstring has the correct indentations.
- Parameters:
docstring (str) – The new docstring for the function, method, class or property.
- Returns:
A decorator which sets the docstring of a function, method, class or property.
- Return type:
function
- Raises:
TypeError – If
set_docstringis applied to an object which is not a function, method, class, or property.
Examples
To dynamically set the docstring of a function:
@set_docstring("This is the new docstring") def function(): """ This docstring will be replaced """
To dynamically set the docstring of a class:
@set_docstring("This is the new docstring") class DocClass(): """ This is a class level docstring. This docstring will be replaced. """
To dynamically set the docstring of a property:
@property @set_docstring("This is the new docstring") def prop(): """ This docstring will be replaced """
- MDMC.common.decorators.time_function_execution(func: Callable) Callable[source]
Time a given function.
Create an instance of the
TimeKeeperand stores the function execution time in TimeKeeper’s class attributes.This decorator is meant to be used on functions that are likely to be using up too much CPU time, so the scale of the problem can be assessed.
- Parameters:
func (Callable) – Function to time.
- Returns:
Decorated function with attached timer.
- Return type:
function
- MDMC.common.decorators.unit_decorator(unit: str | None) Callable[source]
Decorate
property.settermethods to add units.Adds units to the values passed to
property.settermethods. These units are displayed when eitherreprorstris called for the correspondingproperty.gettermethod.Suitable for use with setter methods that either take float (or objects that can be cast to float), or NumPy array (or objects that can be cast to NumPy array).
- Parameters:
unit (str or None) – The
unitapplied to the property. If None thenself.unitis used, which enables classes to have properties with units defined at runtime.- Returns:
A
property.setterfunction with avalueparameter which has aunit(e.g.UnitFloatorUnitNDArray).- Return type:
function
Examples
Add a
unit_decoratorto thepositionproperty:>>> Class Atom(Structure): ... ... @property ... def position(self): ... return self._position ... ... @position.setter ... @unit_decorator(unit=Unit('Ang')) ... def position(self, value): ... self._position = value
- MDMC.common.decorators.unit_decorator_getter(unit: str | None) Callable[source]
Decorate
property.gettermethods to add units.Adds units to the return values of
property.gettermethods. These units are displayed when eitherreprorstris called.Suitable for use with setter methods that either take float (or objects that can be cast to float), or NumPy array (or objects that can be cast to NumPy array). This method exists for properties which have no setter method.
- Parameters:
unit (str or None) – The
unitapplied to the property. If None thenself.unitis used, which enables classes to have properties with units defined at runtime.- Returns:
A
property.getterfunction with a return type which has a unit (e.g.UnitFloatorUnitNDArray).- Return type:
function
Examples
Add a
unit_decorator_getterto thevolumeproperty:>>> Class Universe: ... ... @property ... @unit_decorator_getter(unit=Unit('Ang') ^ 3) ... def volume(self): ... return self.dimensions ** 3
- MDMC.common.decorators.weakref_cache(maxsize: int = 128) Callable[source]
Weakref LRU cache to avoid memory leaks.
Caches on instance methods store self, which can lead to excess memory use. This avoids it by only holding a weakref to the instance.
- Parameters:
maxsize (int, optional, default=128) – Max size of LRU cache.
- Returns:
Decorated function with LRU cache.
- Return type:
function
- MDMC.common.decorators.wrap_docstring(docstring: str, line_length: int) str[source]
Wrap a docstring to a specific line length.
This maintains any indentation which exists at the start of a line. While equations should not be affected by this wrapping, it is recommended that docstrings with .. math:: are visually checked after wrapping.
- Parameters:
- Returns:
The wrapped docstring.
- Return type:
- Raises:
ValueError – If any indent has more characters than the
line_length, as the wrapping cannot then preserve the correct indent
MDMC.common.df_operations module
Contains some utility functions related to pd.DataFrames, including filtering functions.
- MDMC.common.df_operations.filter_dataframe(values: Sequence, dataframe: DataFrame, column_names: list[str]) DataFrame[source]
- MDMC.common.df_operations.filter_dataframe(values: Sequence, dataframe: DataFrame, column_regex: str) DataFrame
Ignore duplicated rows (i.e. only return the first occurence of any duplicated row).
- Parameters:
values (Sequence) – The values for which to filter. If any of these values occur in any of the columns defined by
column_namesorcolumn_regex, the row will be included in the filtered return.dataframe (pandas.DataFrame) – The
pd.DataFrameobject to be filtered.column_names (list[str], optional) –
A list of str specifying the names of the columns which will be used to filter the
Dataframe.This cannot be passed if
column_regexis also passed.column_regex (str) –
A regular expression matching one or more column names. This specifies which columns will be used to filter the
DataFrame.This cannot be passed if
column_namesis also passed.
- Returns:
A
DataFramewhich has been filtered so that each value invaluesmust occur in one of the columns ofDataFramethat are specified bycolumn_namesor matched bycolumn_regex.- Return type:
- Raises:
ValueError – If both column_names and column_regex were passed. If there are fewer column_names than values.
- MDMC.common.df_operations.filter_ordered_dataframe(values: Sequence, dataframe: DataFrame, column_names: list[str], wildcard: str = None) DataFrame[source]
- MDMC.common.df_operations.filter_ordered_dataframe(values: Sequence, dataframe: DataFrame, column_regex: str, wildcard: str = None) DataFrame
Filter a
pd.DataFramewith an iterable of ordered values.The values must occur in columns in the correct order, with the order specified by
column_names, or by the order which column order which occurs from usingcolumn_regex.This filter ignores rows which are duplicated (i.e. it only returns the first occurence of any duplicated rows).
- Parameters:
values (Sequence) – The values for which to filter. If any of these values occur in any of the columns defined by
column_namesorcolumn_regex, the row will be included in the filtered return.dataframe (pandas.DataFrame) – The
pd.DataFrameobject to be filtered.column_names (list[str], optional) –
A list of str specifying the names of the columns which will be used to filter the
Dataframe.This cannot be passed if
column_regexis also passed.column_regex (str) –
A regular expression matching one or more column names. This specifies which columns will be used to filter the
DataFrame.This cannot be passed if
column_namesis also passed.wildcard (str) – A str which will be a match in any column.
- Returns:
A
DataFramewhich has been filtered so that each value invaluesmust occur in one of the columns ofDataFramethat are specified bycolumn_namesor matched bycolumn_regex.- Return type:
- Raises:
ValueError – If both column_names and column_regex were passed. If there are fewer column_names than values.
MDMC.common.factory module
Generalised factory class.
- class MDMC.common.factory.Factory[source]
Bases:
ABCGeneral factory class.
- classmethod create(key: str, *args, **kwargs) Callable[[...], T][source]
Return an instance of given class.
- class MDMC.common.factory.ModuleFactory[source]
Bases:
Factory,ABC,Generic[T]Scan current directory for any valid types.
Supports:
scanning of files for relevant classes/functions.
exclusion of self and certain files.
- curr_path
Path to scan, usually
Path(__file__).parent.- Type:
Path
- exclude
Paths to exclude from search.
- Type:
Sequence[Path]
- class MDMC.common.factory.RegisterFactory[source]
Bases:
Factory,ABC,Generic[T]Factory requiring manual registration to data.
See also
RegisterFactory.registerRegistration mechanism.
- classmethod register(names: str | Iterable[str]) Callable[[...], T][source]
A class level decorator for registering classes.
The names of the modules with which the class is registered should be the parameter passed to the decorator.
- Parameters:
names (str) – The names of the modules with are registered
Example
To register the
SQwclass withRegisterFactory:@RegisterFactory.register('SQw') class SQw(Observable):
MDMC.common.log module
This module configures logging for MDMC.
- MDMC.common.log.create_logger(name: str = 'MDMC', logfile: str = 'MDMC.log', level: int = 20) Logger[source]
Create a formatter logger which outputs to a log file.
- Parameters:
- Returns:
Logger to handle MDMC logging.
- Return type:
MDMC.common.mathematics module
A module containing mathematical functions.
- MDMC.common.mathematics.UNIT_VECTOR = array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])
Array of standard unit vectors. Used as a standard basis of 3D space.
- MDMC.common.mathematics.correlation(input1: ndarray, *, normalise: bool = False) ndarray[source]
- MDMC.common.mathematics.correlation(input1: ndarray, input2: ndarray, normalise: bool = False) ndarray
Compute the correlation of two vectors.
The Fast Correlation Algorithm (FCA) is utilised.
If only a single input is provided, the autocorrelation is calculated.
- Parameters:
input1 (numpy.ndarray) – A 1D
arrayof data.input2 (numpy.ndarray, optional) – A 1D
arrayof data. If None, autocorrelation ofinput1is calculated. Default is None.normalise (bool, optional) – If True, the correlation is normalised at each point to the number of contributions to that point. Default is False.
- Returns:
A 1D
arrayof the same length as theinput1containing the correlation betweeninput1andinput2(or autocorrelation ofinput1ifinput2is None).- Return type:
- MDMC.common.mathematics.faster_autocorrelation(input1: ndarray, weights: ndarray | float = None) ndarray[source]
The autocorrelation of a vector.
The Fast Correlation Algorithm (FCA) is utilised.
- Parameters:
input1 (numpy.ndarray) – A 1D
arrayof data.weights (np.ndarray or float) – Either weights for each point or single weight for all points.
- Returns:
A 1D
arrayof the same length as theinput1containing the correlation betweeninput1andinput2(or autocorrelation ofinput1ifinput2is None).- Return type:
- MDMC.common.mathematics.faster_correlation(input1: ndarray, input2: ndarray) ndarray[source]
Compute the correlation of two vectors.
The Fast Correlation Algorithm (FCA) is utilised.
- Parameters:
input1 (numpy.ndarray) – A 1D
arrayof data.input2 (numpy.ndarray, optional) – A 1D
arrayof data.
- Returns:
A 1D
arrayof the same length as theinput1containing the correlation betweeninput1andinput2(or autocorrelation ofinput1ifinput2is None).- Return type:
MDMC.common.periodictable_objects module
Utility methods for dealing with periodictable atom_objects
- MDMC.common.periodictable_objects.create_list_of_element_objects(old_elements: list) list[source]
A list of strings of elements/isotopes is converted into a list of periodictable element/isotope objects. Different forms of how an atom can be specified is taken into account. The forms allowed here are (using Argon as an example) ‘Ar’, ‘Ar[36]’, ‘36-Ar’.
MDMC.common.resolution_functions module
A module for containing all resolution functions.
- MDMC.common.resolution_functions.gaussian(x: ndarray, sigma: float, mu: float = 0.0, norm: bool = True) ndarray[source]
Calculate the Gaussian distribution.
- Parameters:
x (numpy.ndarray) – The x values at which the Gaussian distribution is calculated.
sigma (float) – The standard deviation of the Gaussian.
mu (float, optional) – The offset of the Gaussian.
norm (bool, optional) – If True, resulting distribution is normalized to unity.
- Returns:
A discretised Gaussian distribution of the same length as
x.- Return type:
- MDMC.common.resolution_functions.lorentzian(x: ndarray, gamma: float, x_0: float = 0.0) ndarray[source]
Calculate the Lorentzian (Cauchy) distribution.
- Parameters:
x (numpy.ndarray) – The x values at which the Gaussian distribution is calculated.
gamma (float) – The full-width at half-maximum.
x_0 (float, optional) – The offset of the distribution.
- Returns:
A discretised Lorentzian distribution of the same length as
x.- Return type:
MDMC.common.time_keeper module
TimeKeeper class designed to track per-function level execution time.
- class MDMC.common.time_keeper.TimeKeeper[source]
Bases:
objectClass to track per-function execution time.
A class designed for storing function timing information in class variable. The idea is to access the class variables throught a class instance, typically in a function decorator called time_function_execution.
- function_called(fname: str)[source]
Increment number of the function calls for specified function.
- Parameters:
fname (str) –
A descriptive name of the function that has been called.
Typically this name will be generated by the
time_function_executiondecorator.
- summarise_results() list[tuple[str, int, float]][source]
Convert all the recorded function timing data into a list.
- time_passed(fname: str, exp_time: float)[source]
Compute accumulated execution time.
Add the execution time of the function to the accumulated execution time from all the times that function has been called.
- Parameters:
fname (str) –
A descriptive name of the function that has been called.
Typically this name will be generated by the
time_function_executiondecorator.exp_time (float) – The wall time that has expired during the function execution.
MDMC.common.units module
Module for all unit definitions and operations.
This includes defining units used in MDMC, converting units, and subclassing
data strucures (float, array) so that they have a unit
attribute. This style follows that of the Atomic Simulation Environment.
As members of units.py are set dynamically, pylintrc excludes member checking for units.py using the generated-members keyword. Care must be taken to ensure members exist when importing from units.py, as these will not be linted.
- MDMC.common.units.CODATA = {'2014': {'_Grav': 6.67408e-11, '_Nav': 6.022140857e+23, '_amu': 1.66053904e-27, '_c': 299792458.0, '_e': 1.6021766208e-19, '_hplanck': 6.62607004e-34, '_k': 1.38064852e-23, '_me': 9.10938356e-31, '_mp': 1.672621898e-27, '_mu0': 1.2566370614359173e-06}}
CODATA 2014 taken from ASE.units, originally from: http://arxiv.org/pdf/1507.07956.pdf.
- MDMC.common.units.CODATA_VERSION = '2014'
Version of CODATA constants to load.
- class MDMC.common.units.Unit(string: str, components: defaultdict[list] = None)[source]
Bases:
strA class for defining unit strings.
It possesses additional
*and/operands so that combined units can be returned.Note
NON-INTEGER POWER OPERATIONS ARE CURRENTLY NOT IMPEMENTED
- Parameters:
string (str) – The unit, which can contain
/to specify divisors and^to specify powers. It can contain int which are used to specify order of magnitude (e.g.10^6 Pa). It can also contain negative powers, but there must not be a space between the negative sign and the number (e.g.Ang ^ -1NOTAng ^ - 1). Brackets and parentheses are not supported, and any of the characters[]()will be ignored.components (defaultdict[list], optional) – Sets the
componentsattribute (see Attributes). Default is None.
- components
Contains the
componentsof theUnit, separated into two list s (numeratoranddenominator) depending on which side of the fraction each component is on. If theUnitis abaseunit i.e. initialized usingUnit(), then thecomponentsonly has anumeratorand this is theUnitstring. If it a combinedUnit(created by either__mul__,__div__or__pow__) then theUnitobjects which combined to form it make up thecomponents.- Type:
defaultdict[list]
- conversion_factor
The factor by which to multiply a value in order to express it in system units. For example
Unit('ps').conversion_factoris1000.as the system units are femtoseconds.- Type:
Examples
Base units can be set:
>>> time_unit = Unit('s')
Compound units can be set with spaces separating
baseunits which are multiplied:>>> charge_unit = Unit('A s')
Compound units can be set with
/separatingbaseunits which are divided:>>> velocity_unit = Unit('m / s')
Units raised to a power can be set with
^:>>> volume_unit = Unit('Ang ^ 3')
Compound units can be set with a combination of these operands:
>>> force_unit = Unit('kg m / s ^ 2')
To set an inverse unit, the power operation can be applied to a
Unit:>>> frequency = Unit('s') ** -1
Or set with
^within the string:>>> frequency = Unit('s ^ -1')
Or with
/within the string:>>> frequency = Unit('1 / s')
Orders of magnitude can also be included:
>>> pressure = Unit('10 ^ 6 Pa')
- property base: bool
Get whether the
Unitis abaseor compoundUnit.- Returns:
If True,
Unitis abaseUnit(only has a single element in thecomponentsnumeratorlist).- Return type:
- property conversion_factor: float
Multiplicative factor to get system units.
Calculates the factor by which a value with this
Unitshould be multiplied in order to express it in system units. This takes into account any orders of magnitude and compound units.The conversion_factor for a
Unitcomposed only of system units is therefore always 1.
- class MDMC.common.units.UnitFloat(value: float, unit: Unit | str)[source]
Bases:
floatSubclasses float so that it contains a
unitattribute.unitattribute is returned when __repr__ or __str__ are called.- Parameters:
Notes
As both
__repr__and__deepcopy__rely on the float being real, this class is not compatible with complex numbers. This should be immaterial as no quantity which possesses units is complex.
- class MDMC.common.units.UnitNDArray(shape, unit, dtype=<class 'float'>, buffer=None, offset=0, strides=None, order=None)[source]
Bases:
ndarraySubclasses
ndarrayso that it contains aunitattribute.unitattribute is returned when__repr__or__str__are called- Parameters:
shape (tuple of ints) – Shape of created
array.dtype (data-type, optional) – Any object that can be interpreted as a NumPy data type.
buffer (object exposing NumPy buffer interface, optional) – Used to fill the
arraywith data.offset (int, optional) – Offset of
arraydata inbuffer.strides (tuple of ints, optional) – Strides of data in memory.
order (str, optional) – Either
Cfor row-major orFfor column-major. Default isC.
- MDMC.common.units.create_units(codata_version: str) dict[Unit, float][source]
Create a dict of
Unitbased on the CODATA version.
- MDMC.common.units.unit_array(obj, unit: Unit | str, dtype=None) UnitNDArray[source]
Create a
UnitNDArrayfrom anarrayor any nested sequence.This mimics the manner in which NumPy creates arrays (although is in Python not C), except several arguments are excluded.
Also, unlike
np.array(None), passingobj=Nonetounit_arrayresults in None being returned. This allows classes to have properties with units which can be either have avalueor be undefined.- Parameters:
- Returns:
A
UnitArrayobject satisfying the specified requirements.- Return type:
UnitArray
Module contents
Common functions and classes used by multiple other subpackages.
constants
decorators
df_operations
mathematics
resolution_functions
units