\(\renewcommand{\AA}{\text{Å}}\)
2.4. The lammps
Python module
The LAMMPS Python interface is implemented as a module called lammps
which is defined in the lammps
package in the python
folder of the
LAMMPS source code distribution. After compilation of LAMMPS, the module can
be installed into a Python system folder or a user folder with make
install-python
. Components of the module can then loaded into a Python
session with the import
command.
There are multiple Python interface classes in the lammps
module:
the
lammps
class. This is a wrapper around the C-library interface and its member functions try to replicate the C-library API closely. This is the most feature-complete Python API.the
PyLammps
class. This is a more high-level and more Python style class implemented on top of thelammps
class.the
IPyLammps
class is derived fromPyLammps
and adds embedded graphics features to conveniently include LAMMPS into Jupyter notebooks.
Version check
The lammps
module stores the version number of the LAMMPS
version it is installed from. When initializing the
lammps
class, this version is checked to
be the same as the result from lammps.version()
, the version
of the LAMMPS shared library that the module interfaces to. If the
they are not the same an AttributeError exception is raised since a
mismatch of versions (e.g. due to incorrect use of the
LD_LIBRARY_PATH
or PYTHONPATH
environment variables can lead
to crashes or data corruption and otherwise incorrect behavior.
LAMMPS module global members:
- lammps.__version__
Numerical representation of the LAMMPS version this module was taken from. Has the same format as the result of
lammps.version()
.
2.4.1. The lammps
class API
The lammps
class is the core of the LAMMPS
Python interfaces. It is a wrapper around the LAMMPS C library
API using the Python ctypes module and a shared library
compiled from the LAMMPS sources code. The individual methods in this
class try to closely follow the corresponding C functions. The handle
argument that needs to be passed to the C functions is stored internally
in the class and automatically added when calling the C library
functions. Below is a detailed documentation of the API.
- class lammps.lammps(name='', cmdargs=None, ptr=None, comm=None)
Create an instance of the LAMMPS Python class.
This is a Python wrapper class that exposes the LAMMPS C-library interface to Python. It either requires that LAMMPS has been compiled as shared library which is then dynamically loaded via the ctypes Python module or that this module called from a Python function that is called from a Python interpreter embedded into a LAMMPS executable, for example through the python invoke command. When the class is instantiated it calls the
lammps_open()
function of the LAMMPS C-library interface, which in turn will create an instance of theLAMMPS
C++ class. The handle to this C++ class is stored internally and automatically passed to the calls to the C library interface.- Parameters:
name (string) – “machine” name of the shared LAMMPS library (“mpi” loads
liblammps_mpi.so
, “” loadsliblammps.so
)cmdargs (list) – list of command line arguments to be passed to the
lammps_open()
function. The executable name is automatically added.ptr (pointer) – pointer to a LAMMPS C++ class instance when called from an embedded Python interpreter. None means load symbols from shared library.
comm (MPI_Comm) – MPI communicator (as provided by mpi4py).
None
means useMPI_COMM_WORLD
implicitly.
- property numpy
Return object to access numpy versions of API
It provides alternative implementations of API functions that return numpy arrays instead of ctypes pointers. If numpy is not installed, accessing this property will lead to an ImportError.
- Returns:
instance of numpy wrapper object
- Return type:
- close()
Explicitly delete a LAMMPS instance through the C-library interface.
This is a wrapper around the
lammps_close()
function of the C-library interface.
- finalize()
Shut down the MPI communication and Kokkos environment (if active) through the library interface by calling
lammps_mpi_finalize()
andlammps_kokkos_finalize()
.You cannot create or use any LAMMPS instances after this function is called unless LAMMPS was compiled without MPI and without Kokkos support.
- error(error_type, error_text)
Forward error to the LAMMPS Error class.
New in version 3Nov2022.
This is a wrapper around the
lammps_error()
function of the C-library interface.- Parameters:
error_type (int) –
error_text (string) –
- version()
Return a numerical representation of the LAMMPS version in use.
This is a wrapper around the
lammps_version()
function of the C-library interface.- Returns:
version number
- Return type:
int
- get_os_info()
Return a string with information about the OS and compiler runtime
This is a wrapper around the
lammps_get_os_info()
function of the C-library interface.- Returns:
OS info string
- Return type:
string
- get_mpi_comm()
Get the MPI communicator in use by the current LAMMPS instance
This is a wrapper around the
lammps_get_mpi_comm()
function of the C-library interface. It will returnNone
if either the LAMMPS library was compiled without MPI support or the mpi4py Python module is not available.- Returns:
MPI communicator
- Return type:
MPI_Comm
- file(path)
Read LAMMPS commands from a file.
This is a wrapper around the
lammps_file()
function of the C-library interface. It will open the file with the name/path file and process the LAMMPS commands line by line until the end. The function will return when the end of the file is reached.- Parameters:
path (string) – Name of the file/path with LAMMPS commands
- command(cmd)
Process a single LAMMPS input command from a string.
This is a wrapper around the
lammps_command()
function of the C-library interface.- Parameters:
cmd (string) – a single lammps command
- commands_list(cmdlist)
Process multiple LAMMPS input commands from a list of strings.
This is a wrapper around the
lammps_commands_list()
function of the C-library interface.- Parameters:
cmdlist (list of strings) – a single lammps command
- commands_string(multicmd)
Process a block of LAMMPS input commands from a string.
This is a wrapper around the
lammps_commands_string()
function of the C-library interface.- Parameters:
multicmd (string) – text block of lammps commands
- get_natoms()
Get the total number of atoms in the LAMMPS instance.
Will be precise up to 53-bit signed integer due to the underlying
lammps_get_natoms()
function returning a double.- Returns:
number of atoms
- Return type:
int
- extract_box()
Extract simulation box parameters
This is a wrapper around the
lammps_extract_box()
function of the C-library interface. Unlike in the C function, the result is returned as a list.- Returns:
list of the extracted data: boxlo, boxhi, xy, yz, xz, periodicity, box_change
- Return type:
[ 3*double, 3*double, double, double, 3*int, int]
- reset_box(boxlo, boxhi, xy, yz, xz)
Reset simulation box parameters
This is a wrapper around the
lammps_reset_box()
function of the C-library interface.- Parameters:
boxlo (list of 3 floating point numbers) – new lower box boundaries
boxhi (list of 3 floating point numbers) – new upper box boundaries
xy (float) – xy tilt factor
yz (float) – yz tilt factor
xz (float) – xz tilt factor
- get_thermo(name)
Get current value of a thermo keyword
This is a wrapper around the
lammps_get_thermo()
function of the C-library interface.- Parameters:
name (string) – name of thermo keyword
- Returns:
value of thermo keyword
- Return type:
double or None
- property last_thermo_step
Get the last timestep where thermodynamic data was computed
- Returns:
the timestep or a negative number if there has not been any thermo output yet
- Return type:
int
- last_thermo()
Get a dictionary of the last thermodynamic output
This is a wrapper around the
lammps_last_thermo()
function of the C-library interface. It collects the cached thermo data from the last timestep into a dictionary. The return value is None, if there has not been any thermo output yet.- Returns:
a dictionary containing the last computed thermo output values
- Return type:
dict or None
- extract_setting(name)
Query LAMMPS about global settings that can be expressed as an integer.
This is a wrapper around the
lammps_extract_setting()
function of the C-library interface. Its documentation includes a list of the supported keywords.- Parameters:
name (string) – name of the setting
- Returns:
value of the setting
- Return type:
int
- extract_global_datatype(name)
Retrieve global property datatype from LAMMPS
This is a wrapper around the
lammps_extract_global_datatype()
function of the C-library interface. Its documentation includes a list of the supported keywords. This function returnsNone
if the keyword is not recognized. Otherwise it will return a positive integer value that corresponds to one of the data type constants define in thelammps
module.- Parameters:
name (string) – name of the property
- Returns:
data type of global property, see Data Types
- Return type:
int
- extract_global(name, dtype=None)
Query LAMMPS about global settings of different types.
This is a wrapper around the
lammps_extract_global()
function of the C-library interface. Since there are no pointers in Python, this method will - unlike the C function - return the value or a list of values. Thelammps_extract_global()
documentation includes a list of the supported keywords and their data types. Since Python needs to know the data type to be able to interpret the result, by default, this function will try to auto-detect the data type by asking the library. You can also force a specific data type. For that purpose thelammps
module contains data type constants. This function returnsNone
if either the keyword is not recognized, or an invalid data type constant is used.- Parameters:
name (string) – name of the property
dtype (int, optional) – data type of the returned data (see Data Types)
- Returns:
value of the property or list of values or None
- Return type:
int, float, list, or NoneType
- extract_atom_datatype(name)
Retrieve per-atom property datatype from LAMMPS
This is a wrapper around the
lammps_extract_atom_datatype()
function of the C-library interface. Its documentation includes a list of the supported keywords. This function returnsNone
if the keyword is not recognized. Otherwise it will return an integer value that corresponds to one of the data type constants defined in thelammps
module.- Parameters:
name (string) – name of the property
- Returns:
data type of per-atom property (see Data Types)
- Return type:
int
- extract_atom(name, dtype=None)
Retrieve per-atom properties from LAMMPS
This is a wrapper around the
lammps_extract_atom()
function of the C-library interface. Its documentation includes a list of the supported keywords and their data types. Since Python needs to know the data type to be able to interpret the result, by default, this function will try to auto-detect the data type by asking the library. You can also force a specific data type by settingdtype
to one of the data type constants defined in thelammps
module. This function returnsNone
if either the keyword is not recognized, or an invalid data type constant is used.Note
While the returned arrays of per-atom data are dimensioned for the range [0:nmax] - as is the underlying storage - the data is usually only valid for the range of [0:nlocal], unless the property of interest is also updated for ghost atoms. In some cases, this depends on a LAMMPS setting, see for example comm_modify vel yes.
- Parameters:
name (string) – name of the property
dtype (int, optional) – data type of the returned data (see Data Types)
- Returns:
requested data or
None
- Return type:
ctypes.POINTER(ctypes.c_int32), ctypes.POINTER(ctypes.POINTER(ctypes.c_int32)), ctypes.POINTER(ctypes.c_int64), ctypes.POINTER(ctypes.POINTER(ctypes.c_int64)), ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.POINTER(ctypes.c_double)), or NoneType
- extract_compute(cid, cstyle, ctype)
Retrieve data from a LAMMPS compute
This is a wrapper around the
lammps_extract_compute()
function of the C-library interface. This function returnsNone
if either the compute id is not recognized, or an invalid combination of cstyle and ctype constants is used. The names and functionality of the constants are the same as for the corresponding C-library function. For requests to return a scalar or a size, the value is returned, otherwise a pointer.- Parameters:
cid (string) – compute ID
cstyle (int) – style of the data retrieve (global, atom, or local), see Style Constants
ctype (int) – type or size of the returned data (scalar, vector, or array), see Type Constants
- Returns:
requested data as scalar, pointer to 1d or 2d double array, or None
- Return type:
c_double, ctypes.POINTER(c_double), ctypes.POINTER(ctypes.POINTER(c_double)), or NoneType
- extract_fix(fid, fstyle, ftype, nrow=0, ncol=0)
Retrieve data from a LAMMPS fix
This is a wrapper around the
lammps_extract_fix()
function of the C-library interface. This function returnsNone
if either the fix id is not recognized, or an invalid combination of fstyle and ftype constants is used. The names and functionality of the constants are the same as for the corresponding C-library function. For requests to return a scalar or a size, the value is returned, also when accessing global vectors or arrays, otherwise a pointer.- Parameters:
fid (string) – fix ID
fstyle (int) – style of the data retrieve (global, atom, or local), see Style Constants
ftype (int) – type or size of the returned data (scalar, vector, or array), see Type Constants
nrow (int) – index of global vector element or row index of global array element
ncol (int) – column index of global array element
- Returns:
requested data or None
- Return type:
c_double, ctypes.POINTER(c_double), ctypes.POINTER(ctypes.POINTER(c_double)), or NoneType
- extract_variable(name, group=None, vartype=None)
Evaluate a LAMMPS variable and return its data
This function is a wrapper around the function
lammps_extract_variable()
of the C library interface, evaluates variable name and returns a copy of the computed data. The memory temporarily allocated by the C-interface is deleted after the data is copied to a Python variable or list. The variable must be either an equal-style (or equivalent) variable or an atom-style variable. The variable type can be provided as thevartype
parameter, which may be one of several constants:LMP_VAR_EQUAL
,LMP_VAR_ATOM
,LMP_VAR_VECTOR
, orLMP_VAR_STRING
. If omitted orNone
, LAMMPS will determine its value for you based on a call tolammps_extract_variable_datatype()
from the C library interface. The group parameter is only used for atom-style variables and defaults to the group “all”.- Parameters:
name (string) – name of the variable to execute
group (string, only for atom-style variables) – name of group for atom-style variable
vartype (int) – type of variable, see Variable Type Constants
- Returns:
the requested data
- Return type:
c_double, (c_double), or NoneType
- flush_buffers()
Flush output buffers
This is a wrapper around the
lammps_flush_buffers()
function of the C-library interface.
- set_variable(name, value)
Set a new value for a LAMMPS string style variable
This is a wrapper around the
lammps_set_variable()
function of the C-library interface.- Parameters:
name (string) – name of the variable
value (any. will be converted to a string) – new variable value
- Returns:
either 0 on success or -1 on failure
- Return type:
int
- gather_bonds()
Retrieve global list of bonds
New in version 28Jul2021.
This is a wrapper around the
lammps_gather_bonds()
function of the C-library interface.This function returns a tuple with the number of bonds and a flat list of ctypes integer values with the bond type, bond atom1, bond atom2 for each bond.
- Returns:
a tuple with the number of bonds and a list of c_int or c_long
- Return type:
(int, 3*nbonds*c_tagint)
- gather_angles()
Retrieve global list of angles
New in version 8Feb2023.
This is a wrapper around the
lammps_gather_angles()
function of the C-library interface.This function returns a tuple with the number of angles and a flat list of ctypes integer values with the angle type, angle atom1, angle atom2, angle atom3 for each angle.
- Returns:
a tuple with the number of angles and a list of c_int or c_long
- Return type:
(int, 4*nangles*c_tagint)
- gather_dihedrals()
Retrieve global list of dihedrals
New in version 8Feb2023.
This is a wrapper around the
lammps_gather_dihedrals()
function of the C-library interface.This function returns a tuple with the number of dihedrals and a flat list of ctypes integer values with the dihedral type, dihedral atom1, dihedral atom2, dihedral atom3, dihedral atom4 for each dihedral.
- Returns:
a tuple with the number of dihedrals and a list of c_int or c_long
- Return type:
(int, 5*ndihedrals*c_tagint)
- gather_impropers()
Retrieve global list of impropers
New in version 8Feb2023.
This is a wrapper around the
lammps_gather_impropers()
function of the C-library interface.This function returns a tuple with the number of impropers and a flat list of ctypes integer values with the improper type, improper atom1, improper atom2, improper atom3, improper atom4 for each improper.
- Returns:
a tuple with the number of impropers and a list of c_int or c_long
- Return type:
(int, 5*nimpropers*c_tagint)
- encode_image_flags(ix, iy, iz)
convert 3 integers with image flags for x-, y-, and z-direction into a single integer like it is used internally in LAMMPS
This method is a wrapper around the
lammps_encode_image_flags()
function of library interface.- Parameters:
ix (int) – x-direction image flag
iy (int) – y-direction image flag
iz (int) – z-direction image flag
- Returns:
encoded image flags
- Return type:
lammps.c_imageint
- decode_image_flags(image)
Convert encoded image flag integer into list of three regular integers.
This method is a wrapper around the
lammps_decode_image_flags()
function of library interface.- Parameters:
image (lammps.c_imageint) – encoded image flags
- Returns:
list of three image flags in x-, y-, and z- direction
- Return type:
list of 3 int
- create_atoms(n, id, type, x, v=None, image=None, shrinkexceed=False)
Create N atoms from list of coordinates and properties
This function is a wrapper around the
lammps_create_atoms()
function of the C-library interface, and the behavior is similar except that the v, image, and shrinkexceed arguments are optional and default to None, None, and False, respectively. With None being equivalent to aNULL
pointer in C.The lists of coordinates, types, atom IDs, velocities, image flags can be provided in any format that may be converted into the required internal data types. Also the list may contain more than N entries, but not fewer. In the latter case, the function will return without attempting to create atoms. You may use the
encode_image_flags
method to properly combine three integers with image flags into a single integer.- Parameters:
n (int) – number of atoms for which data is provided
id (list of lammps.tagint) – list of atom IDs with at least n elements or None
type (list of int) – list of atom types
x (list of float) – list of coordinates for x-, y-, and z (flat list of 3n entries)
v (list of float) – list of velocities for x-, y-, and z (flat list of 3n entries) or None (optional)
image (list of lammps.imageint) – list of encoded image flags (optional)
shrinkexceed (bool) – whether to expand shrink-wrap boundaries if atoms are outside the box (optional)
- Returns:
number of atoms created. 0 if insufficient or invalid data
- Return type:
int
- property has_mpi_support
Report whether the LAMMPS shared library was compiled with a real MPI library or in serial.
This is a wrapper around the
lammps_config_has_mpi_support()
function of the library interface.- Returns:
False when compiled with MPI STUBS, otherwise True
- Return type:
bool
- property is_running
Report whether being called from a function during a run or a minimization
New in version 9Oct2020.
Various LAMMPS commands must not be called during an ongoing run or minimization. This property allows to check for that. This is a wrapper around the
lammps_is_running()
function of the library interface.- Returns:
True when called during a run otherwise false
- Return type:
bool
- force_timeout()
Trigger an immediate timeout, i.e. a “soft stop” of a run.
New in version 9Oct2020.
This function allows to cleanly stop an ongoing run or minimization at the next loop iteration. This is a wrapper around the
lammps_force_timeout()
function of the library interface.
- property has_exceptions
Report whether the LAMMPS shared library was compiled with C++ exceptions handling enabled
This is a wrapper around the
lammps_config_has_exceptions()
function of the library interface.- Returns:
state of C++ exception support
- Return type:
bool
- property has_gzip_support
Report whether the LAMMPS shared library was compiled with support for reading and writing compressed files through
gzip
.This is a wrapper around the
lammps_config_has_gzip_support()
function of the library interface.- Returns:
state of gzip support
- Return type:
bool
- property has_png_support
Report whether the LAMMPS shared library was compiled with support for writing images in PNG format.
This is a wrapper around the
lammps_config_has_png_support()
function of the library interface.- Returns:
state of PNG support
- Return type:
bool
- property has_jpeg_support
Report whether the LAMMPS shared library was compiled with support for writing images in JPEG format.
This is a wrapper around the
lammps_config_has_jpeg_support()
function of the library interface.- Returns:
state of JPEG support
- Return type:
bool
- property has_ffmpeg_support
State of support for writing movies with
ffmpeg
in the LAMMPS shared libraryThis is a wrapper around the
lammps_config_has_ffmpeg_support()
function of the library interface.- Returns:
state of ffmpeg support
- Return type:
bool
- has_package(name)
Report if the named package has been enabled in the LAMMPS shared library.
New in version 3Nov2022.
This is a wrapper around the
lammps_config_has_package()
function of the library interface.- Parameters:
name (string) – name of the package
- Returns:
state of package availability
- Return type:
bool
- property accelerator_config
Return table with available accelerator configuration settings.
This is a wrapper around the
lammps_config_accelerator()
function of the library interface which loops over all known packages and categories and returns enabled features as a nested dictionary with all enabled settings as list of strings.- Returns:
nested dictionary with all known enabled settings as list of strings
- Return type:
dictionary
- property has_gpu_device
Availability of GPU package compatible device
This is a wrapper around the
lammps_has_gpu_device()
function of the C library interface.- Returns:
True if a GPU package compatible device is present, otherwise False
- Return type:
bool
- get_gpu_device_info()
Return a string with detailed information about any devices that are usable by the GPU package.
This is a wrapper around the
lammps_get_gpu_device_info()
function of the C-library interface.- Returns:
GPU device info string
- Return type:
string
- property installed_packages
List of the names of enabled packages in the LAMMPS shared library
This is a wrapper around the functions
lammps_config_package_count()
and :cpp:func`lammps_config_package_name` of the library interface.:return
- has_style(category, name)
Returns whether a given style name is available in a given category
This is a wrapper around the function
lammps_has_style()
of the library interface.- Parameters:
category (string) – name of category
name (string) – name of the style
- Returns:
true if style is available in given category
- Return type:
bool
- available_styles(category)
Returns a list of styles available for a given category
This is a wrapper around the functions
lammps_style_count()
andlammps_style_name()
of the library interface.- Parameters:
category (string) – name of category
- Returns:
list of style names in given category
- Return type:
list
- has_id(category, name)
Returns whether a given ID name is available in a given category
New in version 9Oct2020.
This is a wrapper around the function
lammps_has_id()
of the library interface.- Parameters:
category (string) – name of category
name (string) – name of the ID
- Returns:
true if ID is available in given category
- Return type:
bool
- available_ids(category)
Returns a list of IDs available for a given category
New in version 9Oct2020.
This is a wrapper around the functions
lammps_id_count()
andlammps_id_name()
of the library interface.- Parameters:
category (string) – name of category
- Returns:
list of id names in given category
- Return type:
list
- available_plugins(category)
Returns a list of plugins available for a given category
New in version 10Mar2021.
This is a wrapper around the functions
lammps_plugin_count()
andlammps_plugin_name()
of the library interface.- Returns:
list of style/name pairs of loaded plugins
- Return type:
list
- set_fix_external_callback(fix_id, callback, caller=None)
Set the callback function for a fix external instance with a given fix ID.
Optionally also set a reference to the calling object.
This is a wrapper around the
lammps_set_fix_external_callback()
function of the C-library interface. However this is set up to call a Python function with the following arguments.object is the value of the “caller” argument
ntimestep is the current timestep
nlocal is the number of local atoms on the current MPI process
tag is a 1d NumPy array of integers representing the atom IDs of the local atoms
x is a 2d NumPy array of doubles of the coordinates of the local atoms
f is a 2d NumPy array of doubles of the forces on the local atoms that will be added
Changed in version 28Jul2021.
- Parameters:
fix_id – Fix-ID of a fix external instance
callback – Python function that will be called from fix external
caller – reference to some object passed to the callback function
- Type:
string
- Type:
function
- Type:
object, optional
- fix_external_get_force(fix_id)
Get access to the array with per-atom forces of a fix external instance with a given fix ID.
New in version 28Jul2021.
This is a wrapper around the
lammps_fix_external_get_force()
function of the C-library interface.- Parameters:
fix_id – Fix-ID of a fix external instance
- Type:
string
- Returns:
requested data
- Return type:
ctypes.POINTER(ctypes.POINTER(ctypes.double))
- fix_external_set_energy_global(fix_id, eng)
Set the global energy contribution for a fix external instance with the given ID.
New in version 28Jul2021.
This is a wrapper around the
lammps_fix_external_set_energy_global()
function of the C-library interface.- Parameters:
fix_id – Fix-ID of a fix external instance
eng – potential energy value to be added by fix external
- Type:
string
- Type:
float
- fix_external_set_virial_global(fix_id, virial)
Set the global virial contribution for a fix external instance with the given ID.
New in version 28Jul2021.
This is a wrapper around the
lammps_fix_external_set_virial_global()
function of the C-library interface.- Parameters:
fix_id – Fix-ID of a fix external instance
eng – list of 6 floating point numbers with the virial to be added by fix external
- Type:
string
- Type:
float
- fix_external_set_energy_peratom(fix_id, eatom)
Set the per-atom energy contribution for a fix external instance with the given ID.
New in version 28Jul2021.
This is a wrapper around the
lammps_fix_external_set_energy_peratom()
function of the C-library interface.- Parameters:
fix_id – Fix-ID of a fix external instance
eatom – list of potential energy values for local atoms to be added by fix external
- Type:
string
- Type:
float
- fix_external_set_virial_peratom(fix_id, vatom)
Set the per-atom virial contribution for a fix external instance with the given ID.
New in version 28Jul2021.
This is a wrapper around the
lammps_fix_external_set_virial_peratom()
function of the C-library interface.- Parameters:
fix_id – Fix-ID of a fix external instance
vatom – list of natoms lists with 6 floating point numbers to be added by fix external
- Type:
string
- Type:
float
- fix_external_set_vector_length(fix_id, length)
Set the vector length for a global vector stored with fix external for analysis
New in version 28Jul2021.
This is a wrapper around the
lammps_fix_external_set_vector_length()
function of the C-library interface.- Parameters:
fix_id – Fix-ID of a fix external instance
length – length of the global vector
- Type:
string
- Type:
int
- fix_external_set_vector(fix_id, idx, val)
Store a global vector value for a fix external instance with the given ID.
New in version 28Jul2021.
This is a wrapper around the
lammps_fix_external_set_vector()
function of the C-library interface.- Parameters:
fix_id – Fix-ID of a fix external instance
idx – 1-based index of the value in the global vector
val – value to be stored in the global vector
- Type:
string
- Type:
int
- Type:
float
- get_neighlist(idx)
Returns an instance of
NeighList
which wraps access to the neighbor list with the given indexSee
lammps.numpy.get_neighlist()
if you want to use NumPy arrays instead ofc_int
pointers.
- get_neighlist_size(idx)
Return the number of elements in neighbor list with the given index
- Parameters:
idx (int) – neighbor list index
- Returns:
number of elements in neighbor list with index idx
- Return type:
int
- get_neighlist_element_neighbors(idx, element)
Return data of neighbor list entry
- Parameters:
element (int) – neighbor list index
element – neighbor list element index
- Returns:
tuple with atom local index, number of neighbors and array of neighbor local atom indices
- Return type:
(int, int, POINTER(c_int))
- find_pair_neighlist(style, exact=True, nsub=0, reqid=0)
Find neighbor list index of pair style neighbor list
Search for a neighbor list requested by a pair style instance that matches “style”. If exact is True, the pair style name must match exactly. If exact is False, the pair style name is matched against “style” as regular expression or sub-string. If the pair style is a hybrid pair style, the style is instead matched against the hybrid sub-styles. If the same pair style is used as sub-style multiple types, you must set nsub to a value n > 0 which indicates the nth instance of that sub-style to be used (same as for the pair_coeff command). The default value of 0 will fail to match in that case.
Once the pair style instance has been identified, it may have requested multiple neighbor lists. Those are uniquely identified by a request ID > 0 as set by the pair style. Otherwise the request ID is 0.
- Parameters:
style (string) – name of pair style that should be searched for
exact (bool, optional) – controls whether style should match exactly or only must be contained in pair style name, defaults to True
nsub (int, optional) – match nsub-th hybrid sub-style, defaults to 0
reqid (int, optional) – list request id, > 0 in case there are more than one, defaults to 0
- Returns:
neighbor list index if found, otherwise -1
- Return type:
int
- find_fix_neighlist(fixid, reqid=0)
Find neighbor list index of fix neighbor list
The fix instance requesting the neighbor list is uniquely identified by the fix ID. In case the fix has requested multiple neighbor lists, those are uniquely identified by a request ID > 0 as set by the fix. Otherwise the request ID is 0 (the default).
- Parameters:
fixid (string) – name of fix
reqid (int, optional) – id of neighbor list request, in case there are more than one request, defaults to 0
- Returns:
neighbor list index if found, otherwise -1
- Return type:
int
- find_compute_neighlist(computeid, reqid=0)
Find neighbor list index of compute neighbor list
The compute instance requesting the neighbor list is uniquely identified by the compute ID. In case the compute has requested multiple neighbor lists, those are uniquely identified by a request ID > 0 as set by the compute. Otherwise the request ID is 0 (the default).
- Parameters:
computeid (string) – name of compute
reqid (int, optional) – index of neighbor list request, in case there are more than one request, defaults to 0
- Returns:
neighbor list index if found, otherwise -1
- Return type:
int
- class lammps.numpy_wrapper.numpy_wrapper(lmp)
lammps API NumPy Wrapper
This is a wrapper class that provides additional methods on top of an existing
lammps
instance. The methods transform raw ctypes pointers into NumPy arrays, which give direct access to the original data while protecting against out-of-bounds accesses.There is no need to explicitly instantiate this class. Each instance of
lammps
has anumpy
property that returns an instance.- extract_atom(name, dtype=None, nelem=None, dim=None)
Retrieve per-atom properties from LAMMPS as NumPy arrays
This is a wrapper around the
lammps.extract_atom()
method. It behaves the same as the original method, but returns NumPy arrays instead ofctypes
pointers.Note
The returned arrays of per-atom data are by default dimensioned for the range [0:nlocal] since that data is always valid. The underlying storage for the data, however, is typically allocated for the range of [0:nmax]. Whether there is valid data in the range [nlocal:nlocal+nghost] depends on whether the property of interest is also updated for ghost atoms. This is not often the case. In some cases, it depends on a LAMMPS setting, see for example comm_modify vel yes. By using the optional nelem parameter the size of the returned NumPy can be overridden. There is no check whether the number of elements chosen is valid.
- Parameters:
name (string) – name of the property
dtype (int, optional) – type of the returned data (see Data Types)
nelem (int, optional) – number of elements in array
dim (int, optional) – dimension of each element
- Returns:
requested data as NumPy array with direct access to C data or None
- Return type:
numpy.array or NoneType
- extract_compute(cid, cstyle, ctype)
Retrieve data from a LAMMPS compute
This is a wrapper around the
lammps.extract_compute()
method. It behaves the same as the original method, but returns NumPy arrays instead ofctypes
pointers.- Parameters:
cid (string) – compute ID
cstyle (int) – style of the data retrieve (global, atom, or local), see Style Constants
ctype (int) – type of the returned data (scalar, vector, or array), see Type Constants
- Returns:
requested data either as float, as NumPy array with direct access to C data, or None
- Return type:
float, numpy.array, or NoneType
- extract_fix(fid, fstyle, ftype, nrow=0, ncol=0)
Retrieve data from a LAMMPS fix
This is a wrapper around the
lammps.extract_fix()
method. It behaves the same as the original method, but returns NumPy arrays instead ofctypes
pointers.- Parameters:
fid (string) – fix ID
fstyle (int) – style of the data retrieve (global, atom, or local), see Style Constants
ftype (int) – type or size of the returned data (scalar, vector, or array), see Type Constants
nrow (int) – index of global vector element or row index of global array element
ncol (int) – column index of global array element
- Returns:
requested data
- Return type:
integer or double value, pointer to 1d or 2d double array or None
- extract_variable(name, group=None, vartype=0)
Evaluate a LAMMPS variable and return its data
This function is a wrapper around the function
lammps.extract_variable()
method. It behaves the same as the original method, but returns NumPy arrays instead ofctypes
pointers.- Parameters:
name (string) – name of the variable to execute
group (string) – name of group for atom-style variable (ignored for equal-style variables)
vartype (int) – type of variable, see Variable Type Constants
- Returns:
the requested data or None
- Return type:
c_double, numpy.array, or NoneType
- gather_bonds()
Retrieve global list of bonds as NumPy array
New in version 28Jul2021.
This is a wrapper around
lammps.gather_bonds()
It behaves the same as the original method, but returns a NumPy array instead of actypes
list.- Returns:
the requested data as a 2d-integer numpy array
- Return type:
numpy.array(nbonds,3)
- gather_angles()
Retrieve global list of angles as NumPy array
New in version 8Feb2023.
This is a wrapper around
lammps.gather_angles()
It behaves the same as the original method, but returns a NumPy array instead of actypes
list.- Returns:
the requested data as a 2d-integer numpy array
- Return type:
numpy.array(nangles,4)
- gather_dihedrals()
Retrieve global list of dihedrals as NumPy array
New in version 8Feb2023.
This is a wrapper around
lammps.gather_dihedrals()
It behaves the same as the original method, but returns a NumPy array instead of actypes
list.- Returns:
the requested data as a 2d-integer numpy array
- Return type:
numpy.array(ndihedrals,5)
- gather_impropers()
Retrieve global list of impropers as NumPy array
New in version 8Feb2023.
This is a wrapper around
lammps.gather_impropers()
It behaves the same as the original method, but returns a NumPy array instead of actypes
list.- Returns:
the requested data as a 2d-integer numpy array
- Return type:
numpy.array(nimpropers,5)
- fix_external_get_force(fix_id)
Get access to the array with per-atom forces of a fix external instance with a given fix ID.
Changed in version 28Jul2021.
This function is a wrapper around the
lammps.fix_external_get_force()
method. It behaves the same as the original method, but returns a NumPy array instead of actypes
pointer.- Parameters:
fix_id – Fix-ID of a fix external instance
- Type:
string
- Returns:
requested data
- Return type:
numpy.array
- fix_external_set_energy_peratom(fix_id, eatom)
Set the per-atom energy contribution for a fix external instance with the given ID.
New in version 28Jul2021.
This function is an alternative to
lammps.fix_external_set_energy_peratom()
method. It behaves the same as the original method, but accepts a NumPy array instead of a list as argument.- Parameters:
fix_id – Fix-ID of a fix external instance
eatom – per-atom potential energy
- Type:
string
- Type:
numpy.array
- fix_external_set_virial_peratom(fix_id, vatom)
Set the per-atom virial contribution for a fix external instance with the given ID.
New in version 28Jul2021.
This function is an alternative to
lammps.fix_external_set_virial_peratom()
method. It behaves the same as the original method, but accepts a NumPy array instead of a list as argument.- Parameters:
fix_id – Fix-ID of a fix external instance
eatom – per-atom potential energy
- Type:
string
- Type:
numpy.array
- get_neighlist(idx)
Returns an instance of
NumPyNeighList
which wraps access to the neighbor list with the given index- Parameters:
idx (int) – index of neighbor list
- Returns:
an instance of
NumPyNeighList
wrapping access to neighbor list data- Return type:
- get_neighlist_element_neighbors(idx, element)
Return data of neighbor list entry
This function is a wrapper around the function
lammps.get_neighlist_element_neighbors()
method. It behaves the same as the original method, but returns a NumPy array containing the neighbors instead of actypes
pointer.- Parameters:
element (int) – neighbor list index
element – neighbor list element index
- Returns:
tuple with atom local index and numpy array of neighbor local atom indices
- Return type:
(int, numpy.array)
2.4.2. The PyLammps
class API
The PyLammps
class is a wrapper that creates a
simpler, more “Pythonic” interface to common LAMMPS functionality. LAMMPS
data structures are exposed through objects and properties. This makes Python
scripts shorter and more concise. See the PyLammps Tutorial for an introduction on how to use this interface.
- class lammps.PyLammps(name='', cmdargs=None, ptr=None, comm=None, verbose=False)
This is a Python wrapper class around the lower-level
lammps
class, exposing a more Python-like, object-oriented interface for prototyping system inside of IPython and Jupyter notebooks.It either creates its own instance of
lammps
or can be initialized with an existing instance. The arguments are the same of the lower-level interface. The original interface can still be accessed viaPyLammps.lmp
.- Parameters:
name (string) – “machine” name of the shared LAMMPS library (“mpi” loads
liblammps_mpi.so
, “” loadsliblammps.so
)cmdargs (list) – list of command line arguments to be passed to the
lammps_open()
function. The executable name is automatically added.ptr (pointer) – pointer to a LAMMPS C++ class instance when called from an embedded Python interpreter. None means load symbols from shared library.
comm (MPI_Comm) – MPI communicator (as provided by mpi4py).
None
means useMPI_COMM_WORLD
implicitly.verbose (bool) – print all LAMMPS output to stdout
- Variables:
lmp (
lammps
) – instance of original LAMMPS Python interfaceruns – list of completed runs, each storing the thermo output
- close()
Explicitly delete a LAMMPS instance
This is a wrapper around the
lammps.close()
of the Python interface.
- version()
Return a numerical representation of the LAMMPS version in use.
This is a wrapper around the
lammps.version()
function of the Python interface.- Returns:
version number
- Return type:
int
- file(file)
Read LAMMPS commands from a file.
This is a wrapper around the
lammps.file()
function of the Python interface.- Parameters:
path (string) – Name of the file/path with LAMMPS commands
- property enable_cmd_history
- Getter:
Return whether command history is saved
- Setter:
Set if command history should be saved
- Type:
bool
- write_script(filepath)
Write LAMMPS script file containing all commands executed up until now
- Parameters:
filepath (string) – path to script file that should be written
- clear_cmd_history()
Clear LAMMPS command history up to this point
- command(cmd)
Execute LAMMPS command
If
PyLammps.enable_cmd_history
is set toTrue
, commands executed will be recorded. The entire command history can be written to a file usingPyLammps.write_script()
. To clear the command history, usePyLammps.clear_cmd_history()
.- Parameters:
cmd – command string that should be executed
- Type:
cmd: string
- run(*args, **kwargs)
Execute LAMMPS run command with given arguments
Thermo data of the run is recorded and saved as new entry in
PyLammps.runs
. The latest run can be retrieved byPyLammps.last_run
.Note, for recording of all thermo steps during a run, the PYTHON package needs to be enabled in LAMMPS. Otherwise, it will only capture the final timestep.
- property last_run
Return data produced of last completed run command
- Getter:
Returns an object containing information about the last run command
- Type:
dict
- property atoms
All atoms of this LAMMPS instance
- Getter:
Returns a list of atoms currently in the system
- Type:
- property system
The system state of this LAMMPS instance
- Getter:
Returns an object with properties storing the current system state
- Type:
namedtuple
- property communication
The communication state of this LAMMPS instance
- Getter:
Returns an object with properties storing the current communication state
- Type:
namedtuple
- property computes
The list of active computes of this LAMMPS instance
- Getter:
Returns a list of computes that are currently active in this LAMMPS instance
- Type:
list
- property dumps
The list of active dumps of this LAMMPS instance
- Getter:
Returns a list of dumps that are currently active in this LAMMPS instance
- Type:
list
- property fixes
The list of active fixes of this LAMMPS instance
- Getter:
Returns a list of fixes that are currently active in this LAMMPS instance
- Type:
list
- property groups
The list of active atom groups of this LAMMPS instance
- Getter:
Returns a list of atom groups that are currently active in this LAMMPS instance
- Type:
list
- property variables
Returns a dictionary of all variables defined in the current LAMMPS instance
- Getter:
Returns a dictionary of all variables that are defined in this LAMMPS instance
- Type:
dict
- eval(expr)
Evaluate expression
- Parameters:
expr (string) – the expression string that should be evaluated inside of LAMMPS
- Returns:
the value of the evaluated expression
- Return type:
float if numeric, string otherwise
- lmp_print(s)
needed for Python2 compatibility, since print is a reserved keyword
- class lammps.AtomList(pylammps_instance)
A dynamic list of atoms that returns either an
Atom
orAtom2D
instance for each atom. Instances are only allocated when accessed.- Variables:
natoms – total number of atoms
dimensions – number of dimensions in system
- class lammps.Atom(pylammps_instance, index)
A wrapper class then represents a single atom inside of LAMMPS
It provides access to properties of the atom and allows you to change some of them.
- property id
Return the atom ID
- Type:
int
- property type
Return the atom type
- Type:
int
- property mol
Return the atom molecule index
- Type:
int
- property mass
Return the atom mass
- Type:
float
- property radius
Return the particle radius
- Type:
float
- property position
- Getter:
Return position of atom
- Setter:
Set position of atom
- Type:
numpy.array (float, float, float)
- property velocity
- Getter:
Return velocity of atom
- Setter:
Set velocity of atom
- Type:
numpy.array (float, float, float)
- property force
Return the total force acting on the atom
- Type:
numpy.array (float, float, float)
- property omega
Return the rotational velocity of the particle
- Type:
numpy.array (float, float, float)
- property torque
Return the total torque acting on the particle
- Type:
numpy.array (float, float, float)
- property angular_momentum
Return the angular momentum of the particle
- Type:
numpy.array (float, float, float)
- property charge
Return the atom charge
- Type:
float
- class lammps.Atom2D(pylammps_instance, index)
A wrapper class then represents a single 2D atom inside of LAMMPS
Inherits all properties from the
Atom
class, but returns 2D versions of position, velocity, and force.It provides access to properties of the atom and allows you to change some of them.
- property position
Access to coordinates of an atom
- Getter:
Return position of atom
- Setter:
Set position of atom
- Type:
numpy.array (float, float)
- property velocity
Access to velocity of an atom :getter: Return velocity of atom :setter: Set velocity of atom :type: numpy.array (float, float)
- property force
Access to force of an atom :getter: Return force of atom :setter: Set force of atom :type: numpy.array (float, float)
2.4.3. The IPyLammps
class API
The IPyLammps
class is an extension of
PyLammps
, adding additional functions to
quickly display visualizations such as images and videos inside of IPython.
See the PyLammps Tutorial for examples.
- class lammps.IPyLammps(name='', cmdargs=None, ptr=None, comm=None)
IPython wrapper for LAMMPS which adds embedded graphics capabilities to PyLammmps interface
It either creates its own instance of
lammps
or can be initialized with an existing instance. The arguments are the same of the lower-level interface. The original interface can still be accessed viaPyLammps.lmp
.- Parameters:
name (string) – “machine” name of the shared LAMMPS library (“mpi” loads
liblammps_mpi.so
, “” loadsliblammps.so
)cmdargs (list) – list of command line arguments to be passed to the
lammps_open()
function. The executable name is automatically added.ptr (pointer) – pointer to a LAMMPS C++ class instance when called from an embedded Python interpreter. None means load symbols from shared library.
comm (MPI_Comm) – MPI communicator (as provided by mpi4py).
None
means useMPI_COMM_WORLD
implicitly.
- image(filename='snapshot.png', group='all', color='type', diameter='type', size=None, view=None, center=None, up=None, zoom=1.0, background_color='white')
Generate image using write_dump command and display it
See dump image for more information.
- Parameters:
filename (string) – Name of the image file that should be generated. The extension determines whether it is PNG or JPEG
group (string) – the group of atoms write_image should use
color (string) – name of property used to determine color
diameter (string) – name of property used to determine atom diameter
size (tuple (width, height)) – dimensions of image
view (tuple (theta, phi)) – view parameters
center (tuple (flag, center_x, center_y, center_z)) – center parameters
up (tuple (up_x, up_y, up_z)) – vector pointing to up direction
zoom (float) – zoom factor
background_color (string) – background color of scene
- Returns:
Image instance used to display image in notebook
- Return type:
IPython.core.display.Image
- video(filename)
Load video from file
Can be used to visualize videos from dump movie.
- Parameters:
filename (string) – Path to video file
- Returns:
HTML Video Tag used by notebook to embed a video
- Return type:
IPython.display.HTML
2.4.4. Additional components of the lammps
module
The lammps
module additionally contains several constants
and the NeighList
class:
Data Types
- LAMMPS_INT, LAMMPS_INT_2D, LAMMPS_DOUBLE, LAMMPS_DOUBLE_2D, LAMMPS_INT64, LAMMPS_INT64_2D, LAMMPS_STRING
Constants in the
lammps
module to indicate how to cast data when the C library function returns a void pointer. Used inlammps.extract_global()
andlammps.extract_atom()
. See_LMP_DATATYPE_CONST
for the equivalent constants in the C library interface.
Style Constants
- LMP_STYLE_GLOBAL, LMP_STYLE_ATOM, LMP_STYLE_LOCAL
Constants in the
lammps
module to select what style of data to request from computes or fixes. See_LMP_STYLE_CONST
for the equivalent constants in the C library interface. Used inlammps.extract_compute()
,lammps.extract_fix()
, and their NumPy variantslammps.numpy.extract_compute()
andlammps.numpy.extract_fix()
.
Type Constants
- LMP_TYPE_SCALAR, LMP_TYPE_VECTOR, LMP_TYPE_ARRAY, LMP_SIZE_VECTOR, LMP_SIZE_ROWS, LMP_SIZE_COLS
Constants in the
lammps
module to select what type of data to request from computes or fixes. See_LMP_TYPE_CONST
for the equivalent constants in the C library interface. Used inlammps.extract_compute()
,lammps.extract_fix()
, and their NumPy variantslammps.numpy.extract_compute()
andlammps.numpy.extract_fix()
.
Variable Type Constants
- LMP_VAR_EQUAL, LMP_VAR_ATOM
Constants in the
lammps
module to select what type of variable to query when callinglammps.extract_variable()
. See also: variable command.
Classes representing internal objects
- class lammps.NeighList(lmp, idx)
This is a wrapper class that exposes the contents of a neighbor list.
It can be used like a regular Python list. Each element is a tuple of:
the atom local index
its number of neighbors
and a pointer to an c_int array containing local atom indices of its neighbors
Internally it uses the lower-level LAMMPS C-library interface.
- property size
- Returns:
number of elements in neighbor list
- get(element)
Access a specific neighbor list entry. “element” must be a number from 0 to the size-1 of the list
- Returns:
tuple with atom local index, number of neighbors and ctypes pointer to neighbor’s local atom indices
- Return type:
(int, int, ctypes.POINTER(c_int))
- find(iatom)
Find the neighbor list for a specific (local) atom iatom. If there is no list for iatom, (-1, None) is returned.
- Returns:
tuple with number of neighbors and ctypes pointer to neighbor’s local atom indices
- Return type:
(int, ctypes.POINTER(c_int))
- class lammps.numpy_wrapper.NumPyNeighList(lmp, idx)
This is a wrapper class that exposes the contents of a neighbor list.
It can be used like a regular Python list. Each element is a tuple of:
the atom local index
a NumPy array containing the local atom indices of its neighbors
Internally it uses the lower-level LAMMPS C-library interface.
- get(element)
Access a specific neighbor list entry. “element” must be a number from 0 to the size-1 of the list
- Returns:
tuple with atom local index, numpy array of neighbor local atom indices
- Return type:
(int, numpy.array)
- find(iatom)
Find the neighbor list for a specific (local) atom iatom. If there is no list for iatom, None is returned.
- Returns:
numpy array of neighbor local atom indices
- Return type:
numpy.array or None