lammps_engine
Facade for LAMMPS MD engine
This is a facade to PyLammps (added in 30th-Jul-2016 version), a convenience
wrapper for the LAMMPS Python interface i.e. where Python is extended with
LAMMPS.
Defining all interaction types requires that LAMMPS was built with the MOLECULE package.
Notes
When variables are either passed to or from PyLammps, the ctypes conversion
can mean that they are unnecessarily cast, particularly from float to int.
This can cause issues as LAMMPS requires certain variables, e.g. number of
steps, to be int. Therefore it is always a good idea to be cast these
variables when they are read from PyLammps e.g.
int(lmp.variables['steps'].value).
A minor bug in LAMMPS (Dec 2018 version) means that nangletypes returned
by PyLammps is incorrectly set to ndihedraltypes. This was corrected in
Mar 2020 release.
- class MDMC.MD.engine_facades.lammps_engine.LAMMPSEngine[source]
Facade for LAMMPS
One notable issue with creating the LAMMPS facade is that some
pair_stylesare combinations of both dispersion and coulombic interactions. For example, although LAMMPS haslj/cut,coul/cut, andcoul/long, there is nolj/longpair_style; it only exists in combination withcoul/long(i.e.lj/long/coul/long). This means that the facade has to not just parse each nonbonded interaction, but also has to determine if thatpair_styleshould be combined with anotherpair_style(e.g.lj/longandcoul/longhave to be combined before passing topair_styleandpair_coeff). An additional complication of this is that when setting the coefficients (Parameters) of these interactions, they again have to be set together. So in theory a coulombic interaction needs to know the dispersion interaction it has been paired with an also pass those coefficients when callingpair_coeff. In practice a simplification can be made, at least in the case of currently implemented pair styles: As coulombicpair_stylesdo no take any coefficients, any coulombicpair_stylesthat comprise a combinedpair_stylecan be ignored for the purposes of setting the coulombicpair_style; this can be taken care of whenpair_coeffis called from the correspoding dispersion interaction, as this possesses the dispersion coefficients that also need to be passed when the coefficients of this pair style are set.- property barostat: str
Get or set the str which specifies the barostat
- Returns:
The
barostatname- Return type:
str
- clear() None[source]
Deletes all atoms of the MD engine, restores all settings to their default values, and frees all memory in LAMMPS.
- convert_trajectory(start: int = 0, stop: int = None, step: int = 1, **settings: dict) CompactTrajectory[source]
Converts between a LAMMPS trajectory dump and an MDMC
CompactTrajectoryThe LAMMPS dump must include at least
id,atom_type, andxyzpositions. Thexyzpositionsmust be consecutive and in that order. The same is true of thexyzcomponents of thevelocity, if they are provided.- Parameters:
start (int) – The index of the first trajectory, inclusive.
stop (int) – The index of the last trajectory, exclusive.
step (int) – The step size between trajectories.
**settings –
scaled_positions(bool)If the
trajectory_filehas scaledpositionsatom_IDs(list)LAMMPS
IDof the atoms which should be included. If not passed then all atoms are included in the converted trajectory.
- Returns:
The MDMC
CompactTrajectorycorresponding to the LAMMPStrajectory_file.- Return type:
CompactTrajectory- Raises:
AssertionError – If
universeis passed, and the number of atoms in thetrajectory_fileis not the same as in theuniverse.TypeError – If
trajectory_filedescribes a triclinic universe.
- property ensemble: LAMMPSEnsemble
Get or set the ensemble object which applies a
thermostatand/orbarostatto LAMMPS- Returns:
The simulation thermodynamic ensemble
- Return type:
- minimize(n_steps: int, minimize_every: int = 10, output_log: str = None, work_dir: str = None, **settings: dict) None[source]
Moves the atoms towards a potential energy minimum, by performing an MD simulation interrupted periodically by a structure relaxation. In the end, the configuration with the lowest potential energy reached during the run is kept.
- Parameters:
n_steps (int) – Number of MD simulation steps
minimize_every (int, optional, default 10) – The structure relaxation will be performed every ‘minimize_every’ steps of the MD simulation
output_log (str, optional) – Not used in this facade
work_dir (str, optional) – Not used in this facade
**settings
etol (float, energy tolerance criteria for energy minimisation)
ftol (float, force tolerance criteria for force minimisation, active only if non-zero)
maxiter (int, maximum number of steps in a single structure relaxation)
maxeval (int, maximum number of force calculations in a single structure relaxation)
- property pressure: float
Get or set the pressure of the simulation in
atm- Returns:
Pressure in
atm- Return type:
float
- run(n_steps: int, equilibration=False, output_log: str = None, work_dir: str = None, **settings: dict)[source]
Runs a simulation. Must follow a call to
setup_universe()andsetup_simulation().
- property saved_config: ndarray
Get the saved configuration of the atomic positions
- Returns:
The configuration from the start of the run. Each row of the
arraycorresponds to the LAMMPS atomID - 1(offset is due to array zero indexing) and the columns of thearrayare thex,y,zcomponents of theposition, themassand thechargeof eachAtom.- Return type:
- setup_simulation(**settings: dict) None[source]
Sets simulation parameters in LAMMPS, such as the thermodynamic variables, thermostat/barostat parameters and trajectory settings
- Parameters:
**settings – Passed to
LAMMPSSimulation
- setup_universe(universe: Universe, **settings: dict) None[source]
Creates the simulation box, the atomic configuration, and the topology in LAMMPS
- Parameters:
universe (Universe) – The MDMC
Universewhich will be setup in LAMMPS.**settings –
atom_style(str)A LAMMPS
atom_stylestr. The default setting ofrealwill generally be appropriate.
- property temperature: float
Get or set the temperature of the simulation in
K- Returns:
Temperature in
K- Return type:
float
- class MDMC.MD.engine_facades.lammps_engine.LAMMPSEnsemble(lmp, temperature: float = None, pressure: float = None, thermostat: str = None, barostat: str = None, **settings: dict)[source]
A thermodynamic ensemble determined by applying a thermostat and/or barostat
- Parameters:
lmp (PyLammps) – Set the
lmpattribute to aPyLammpsobject.temperature (float, optional) – Thermostat temperature. Default is None, which is only valid if a
thermostatis also None.pressure (float, optional) – Barostat pressure. Default is None, which is only valid if a
barostatis also None.thermostat (str) – Name of a thermostat to be applied.
barostat (str) – Name of a barostat to be applied.
**settings –
time_step(float)t_damp(int)p_damp(int)t_window(float)t_fraction(float)rescale_step(int)
- rescale_step
Number of steps between applying temperature rescaling. This only applies to rescale thermostats.
- Type:
- apply_ensemble_fixes() None[source]
Passes the required LAMMPS
fixesto apply a specific thermodynamic ensemble to the simulationRemoves all pre-existing thermostat and barostat fixes
- property barostat: str
Get or set the str which specifies the barostat
- Raises:
AttributeError – If
self.pressurehas not been set.
- remove_ensemble_fixes() None[source]
Removes all LAMMPS
fixesrelating to the ensemble i.e. removes all thermostats and barostatsThis must be done before thermostat and barostat fixes are added, so that there is no conflict with existing thermostat and barostats
fixes. It is also required for Shake and Rattlefixeswhich cannot be added after barostat fixes have been applied.
- property t_fraction: float
Get or set the fraction by which the
temperatureis rescaled to the target temperatureThis is required for the rescale
thermostat.- Returns:
Fraction (i.e. between 0.0 and 1.0 inclusive) by which the
temperatureis rescaled- Return type:
float
- Raises:
ValueError – If set to a value outside of 0.0 and 1.0 inclusive.
- property t_window: float
Get or set the
temperaturerange inKin which thetemperatureis not rescaledThis only applies to rescale
thermostats.- Returns:
temperature range in
K- Return type:
float
- property thermostat: str
Get or set the str which specifies the thermostat
- Raises:
AttributeError – If
self.temperaturehas not been set.
- class MDMC.MD.engine_facades.lammps_engine.LAMMPSSimulation(universe, traj_step: int, time_step: float = 1.0, lmp=None, **settings: dict)[source]
The attributes and methods related running a simulation in LAMMPS using a
LAMMPSUniverseobject- Parameters:
universe (Universe) – The MDMC
Universeused to create theLAMMPSUniverse.traj_step (int) – How many steps the simulation should take between dumping each
CompactTrajectoryframetime_step (float, optional) – Simulation timestep in
fs, default is1.lmp (PyLammps, optional) – Set the
lmpattribute to aPyLammpsobject. Default is None, which results in a newPyLammpsobject being initialised.**settings –
temperature(float)skin(float)neighbor_steps(int)remove_linear_momentum(int)remove_angular_momentum(int)velocity_seed(int): The seed to be used by LAMMPS to create velocities.
- traj_step
Number of simulation steps that elapse between the
CompactTrajectorybeing stored.- Type:
- ensemble
Simulation ensemble, which applies a
thermostatandbarostat.- Type:
- property ang_momentum_steps: int
Get or set the number of steps between resetting the angular momentum
- Returns:
Number of steps between the angular momentum being removed
- Return type:
int
- property barostat: str
Get or set the string which specifies the barostat
- Returns:
The barostat name
- Return type:
str
- property lin_momentum_steps: int
Get or set the number of steps between resetting the linear momentum
- Returns:
Number of steps between the linear momentum being removed
- Return type:
int
- property neighbor_steps: int
Get or set the number of steps between neighbor list updates
- Returns:
Number of steps between neighbor list updates
- Return type:
int
- property pressure: float
Get or set the pressure of the simulation in
atm- Returns:
Pressure in
atm- Return type:
float
- property skin: float
Get or set the skin distance in
Ang- Returns:
The skin distance in
Ang. This distance plus the forcecutoffdistance determines which atom pairs are stored in the neighbor list.- Return type:
float
- property temperature: float
Get or set the temperature of the simulation in
K- Returns:
Temperature in
K- Return type:
float
- class MDMC.MD.engine_facades.lammps_engine.LAMMPSUniverse(universe: Universe, lmp: PyLammps = None, **settings: dict)[source]
A class with what would be the equivalent in LAMMPS to the universe (i.e. the configuration and topology)
- Parameters:
universe (Universe) – The MDMC
Universeused to create theLAMMPSUniverselmp (PyLammps, optional) – Set the
lmpattribute to aPyLammpsobject. Default is None, which results in a newPyLammpsobject being initialised.**settings –
atom_style(str)A LAMMPS
atom_stylestring. The default setting ofrealwill generally be appropriate.nonbonded_mix(str)The name of the formula which determines non-bonded mixing
- atom_dict
A dict with {
MDMC_atom:LAMMPS_atom_id}, whereMDMC_atomis an MDMCAtomandLAMMPS_atomis the corresponding LAMMPSAtom.- Type:
- atom_types
A dict with {
type_ID:MDMC_atom_group}, where thetype_IDis a unique int andMDMC_atom_groupis a list ofAtomwhich are identical in terms of element and interactions.- Type:
- atom_type_properties
Each tuple is (
symbol,mass) for allatom_types(ordered) byatom_type, wheresymbolis a str specifying the element of theatom_typeandmassis a float specifying themassof theatom_type.- Type:
list of tuples
- proper_ID
A dict of {
proper:ID pairs} relating eachDihedralAngle(withimproper == False) to a LAMMPSID.- Type:
- improper_ID
A dict of {
improper:ID pairs} relating eachDihedralAngle(withimproper == True) to a LAMMPSID.- Type:
- apply_constraints() None[source]
Adds a constraint
fixto LAMMPS for all bonds and bond angles which are constrained
- property nonbonded_mix: str
Get or set the formula used to calculate nonbonded interactions between different
atom_typesOptions are
geometric,arithmeticandsixthpower, which are defined in the LAMMPS documentation.- Returns:
The name of the formula which determines non-bonded mixing
- Return type:
str
- Raises:
ValueError – str specifies an unsupported mix name
- set_config(config: ndarray) None[source]
Changes the positions of all of the atoms in the LAMMPS wrapper
- Parameters:
config (numpy.ndarray) – The
positions,massandchargeof theAtomobjects, used to set the LAMMPS configuration. Each row of the array must correspond to the LAMMPSatom ID - 1(offset is due toarrayzero indexing) and the columns of thearraymust be thex,y,zcomponents of theposition, themassand thechargeof eachAtom.- Raises:
IndexError – If
configdoes not contain the same number of atoms as LAMMPS possesses.
- class MDMC.MD.engine_facades.lammps_engine.PyLammpsAttribute(lmp: PyLammps = None, atom_style: str = 'full')[source]
A class which has a
PyLammpsobject as an attributeIt possesses attributes and methods relating to the
PyLammpsobject- Parameters:
lmp (PyLammps, optional) – Set the
lmpattribute to aPyLammpsobject. Default is None, which results in a newPyLammpsobject being initialised.atom_style (str, optional) – The LAMMPS
atom_style, which determines the properties that can be associated which the atoms (e.g.charge,bonds). Default isfull.
- lmp
The
PyLammpsobject owned by this class- Type:
PyLammps
- property dumps: list
Get the PyLammps wrapper list of dumps
Dumps are LAMMPS commands which write atom quantities to file for specified timesteps
- property fix_names: list[str]
Get the names of the
fixesapplied in LAMMPS- Returns:
The names of the
fixes- Return type:
list of str
- property fix_styles: list[str]
Get the styles of the
fixesapplied in LAMMPS- Returns:
The styles of the
fixes- Return type:
list of str
- property fixes: list[dict]
Get the
PyLammpswrapper list offixes- Returns:
Each dict states the
group,nameandstyleof a LAMMPS ``fix` which is applied- Return type:
list of dict
- property system_state: namedtuple
Get the
PyLammpswrapper systemstatedict- Returns:
Contains the properties of the simulation box.
- Return type:
System
- MDMC.MD.engine_facades.lammps_engine.convert_unit(value: ndarray | float, unit: Unit = None, to_lammps: bool = True)[source]
Converts between MDMC units and LAMMPS real units
- Parameters:
value (array_like or float_like) – The value of the physical property to be converted, in MDMC units. Must derive from either
ndarrayor float.unit (Unit, optional) – The unit of the
value. If None, thevaluemust possess aunitattribute i.e. derive fromUnitFloatorUnitArray. Default is None.to_lammps (bool, optional) – If True the conversion is from MDMC units to LAMMPS units. Default is True.
- Returns:
Value in LAMMPS units if
to_lammpsis True, otherwise value in MDMC units. Return type is same asvaluetype.- Return type:
float or numpy.ndarray
- MDMC.MD.engine_facades.lammps_engine.parse_all_nonbonded_styles(interactions: NonBondedInteraction) dict[tuple, list[str]][source]
Converts all
NonBondedInteractionsto LAMMPS pair stylesThis is required because LAMMPS frequently treats
CoulombicandDisperioninteractions together; these cases need to be dealt with to generate the correct input to LAMMPSpair_styles. For example, while thepair_stylesbuck,lj/cut,coul/cutandcoul/longcan all be passed separately, the dispersive and coulombic styles are combined (dispersive always preceding coulombic) as this is dealt with more efficiently in the LAMMPS engine.buck/longandlj/longonly exist as part of other pair styles, such asbuck/long/coul/longandlj/long/coul/long, so must be combined.- Parameters:
interactions (list of NonBondedInteractions) –
NonBondedInteractionsto be parsed into LAMMPSpair_styles.- Returns:
A dict with {
pair_styles:pair_modifiers} wherepair_stylesis a tuple of all of the combined LAMMPS pair styles corresponding tointeractions. Each tuple contains the combinedpair_styleas one element, and thecutoffsas the second element e.g.('lj/cut/coul/cut', 5.0 10.0). If additional arguments are required when combining styles, they will be added and returned in the tuple as the third and middle element e.g.('buck/long/coul/long', 'long long', '10.0').pair_modifiersis a list of str for settingpair_modifyfor the correspondingpair_style.- Return type:
dict
- Raises:
ValueError – If
DispersionandCoulombicinteractions have different long rangecutoff, which is not implemented in LAMMPS.ValueError – If long range
Dispersionnot defined in conjunction with a long rangeCoulombic.
- MDMC.MD.engine_facades.lammps_engine.parse_bonded_coefficients(interaction: BondedInteraction) list[str][source]
Orders MDMC
Parameterobjects for input to LAMMPSbond_coeffandangle_coeff- Parameters:
interaction (BondedInteraction) –
BondedInteractionwhere its style and parameters will be parsed.- Returns:
Style and parameters converted to the input format for LAMMPS
bond_coeffandangle_coeff- Return type:
list of str
- Raises:
NotImplementedError – If
interactionhas afunctionthat has not been implemented in the LAMMPS facade.
- MDMC.MD.engine_facades.lammps_engine.parse_bonded_styles(interaction: BondedInteraction) str[source]
Converts MDMC
InteractionFunctionnames forBondedInteractionsto LAMMP bond styles- Parameters:
interaction (BondedInteraction) –
BondedInteractionto be parsed into LAMMPS bond style.- Returns:
LAMMPS bond style corresponding to
interaction- Return type:
str
- Raises:
NotImplementedError – If
interactionhas afunctionthat has not been implemented in the LAMMPS facade.
- MDMC.MD.engine_facades.lammps_engine.parse_constraint(constraint_algorithm: ConstraintAlgorithm, bonds: list[Bond] = None, bond_ID_dict: dict = None, angles: list[BondAngle] = None, angle_ID_dict: dict = None) list[source]
Converts an MDMC
ConstraintAlgorithmfor input to LAMMPS fixAt least one of bonds and angles must be passed.
- Parameters:
constraint_algorithm (ConstraintAlgorithm) – An object that derives from
ConstraintAlgorithmto be parsed.bonds (list of Bonds, optional) – Constrained
Bondinteractions.bond_ID_dict (dict, optional) – dict with {
bond:ID pairs} relating eachBondobject to a LAMMPSID.angles (list of BondAngles, optional) – Constrained
BondAngleinteractions.angle_ID_dict (dict, optional) – dict with {
angle:ID pairs} relating eachBondAngleobject to a LAMMPSID.
- Returns:
Input parameters for LAMMPS
fix, not including the first two terms (fix ID,group-ID). The output list has a maximum length of 7, where the last four entries are optional but a minimum of two is required:[algorithm name, accuracy, max iterations, 'b', bond IDs, 'a', angle IDs]
- Return type:
list
- Raises:
TypeError – If there is not at least one
constrainedInteractionpassed.NotImplementedError – If
constraint_algorithmnot been implemented in the LAMMPS facade.
- MDMC.MD.engine_facades.lammps_engine.parse_dispersion_coefficients(interactions: list[NonBondedInteraction], nonbonded_styles: list[tuple] = None) list[str][source]
Orders MDMC
Parameterobjects for input to LAMMPSpair_coeff- Parameters:
interactions (list of NonBondedInteraction) –
NonBondedInteractionswhere their style and parameters will be parsed.nonbonded_styles (list of tuple) – The parsed
NonBondedInteractions, where the combinedpair_styleshave been created by theparse_all_nonbonded_stylesfunction. If None (default), theinteractionsare parsed manually.
- Returns:
Each element is a partial
pair_coeffcommand, containing apair_style, the orderedDispersionParameterobjects converted to the correct input format for LAMMPSpair_coeff, and thecutoff. For example, if interactions contains aBuckinghamwithParameterA, B, C = 4.184, 1.0, 4.184, andcutoff = 20.0, and aCoulombicwith acutoffof10.0, the str element of the list will be:'buck/coul/cut 1.0 1.0 1.0 20.0 10.0'- Return type:
list of str
- Raises:
NotImplementedError – If
interactionhas afunctionthat has not been implemented in the LAMMPS facade.ValueError – If the LAMMPS Buckingham parameter rho is less than or equal to zero.
- MDMC.MD.engine_facades.lammps_engine.parse_kspace_solver(solver: KSpaceSolver) list[source]
Converts an MDMC
KSpaceSolverfor input to LAMMPSkspace_style- Parameters:
solver (KSpaceSolver) – A
KSpaceSolverto be parsed.- Returns:
Style and parameters for input to LAMMPS
kspace_style- Return type:
list
- Raises:
NotImplementedError – If
solvertype has has not been implemented in the LAMMPS facade.
- MDMC.MD.engine_facades.lammps_engine.parse_nonbonded_modifications(interaction: Interaction) list[str][source]
Parses MDMC
Interactionattributes into list that can be used with LAMMPSpair_modifycommand- MDMC.MD.engine_facades.lammps_engine.interaction
The
Interactionfor which the attributes are parsed- Type:
Interaction
- Returns:
A list of str which are a valid
pair_modifycommand, or an empty list if noInteractionattributes require settingpair_modify- Return type:
list
- MDMC.MD.engine_facades.lammps_engine.parse_nonbonded_styles(interaction: NonBondedInteraction) tuple[source]
Converts MDMC
InteractionFunctionnames forNonBondedInteractionsto LAMMPS pair styles- Parameters:
interaction (NonBondedInteraction) –
NonBondedInteractionto be parsed into LAMMPS pair style.- Returns:
(
styles,mods) wherestylesis a list of str of LAMMPS pair style corresponding to theinteraction, andmodsis a list of str of LAMMPS pair modifications corresponding to the interaction- Return type:
tuple
- Raises:
NotImplementedError – If
interactionhas afunctionthat has not been implemented in the LAMMPS facade.