Previous
PyLammps Tutorial
Contents
PyLammps Tutorial
Overview
Comparison of lammps and PyLammps interfaces
lammps.lammps
lammps.PyLammps
Quick Start
System-wide Installation
Step 1: Building LAMMPS as a shared library
Step 2: Installing the LAMMPS Python package
Installation inside of a virtualenv
Bene ts of using a virtualenv
Creating a virtualenv with lammps installed
Creating a new instance of PyLammps
Commands
System state
Working with LAMMPS variables
Retrieving the value of an arbitrary LAMMPS expressions
Accessing atom data
Evaluating thermo data
Error handling with PyLammps
Using PyLammps in IPython notebooks and Jupyter
IPyLammps Examples
Validating a dihedral potential
Running a Monte Carlo relaxation
Using PyLammps and mpi4py (Experimental)
Feedback and Contributing
Overview
Next
PyLammps is a Python wrapper class which can be created on its own or use an existing lammps
Python object. It creates a simpler, Python-like interface to common LAMMPS functionality.
Unlike the original at C-types interface, it exposes a discoverable API. It no longer requires
knowledge of the underlying C++ code implementation. Finally, the IPyLammps wrapper builds
on top of PyLammps and adds some additional features for IPython integration into IPython
notebooks, e.g. for embedded visualization output from dump/image.
lammps.PyLammps
higher-level abstraction built on top of original C-Types interface
manipulation of Python objects
communication with LAMMPS is hidden from API user
shorter, more concise Python
better IPython integration, designed for quick prototyping
Quick Start
System-wide Installation
Step 1: Building LAMMPS as a shared library
To use LAMMPS inside of Python it has to be compiled as shared library. This library is then
loaded by the Python interface. In this example, we use the Make.py utility to create a Make le
with C++ exceptions, PNG, JPEG and FFMPEG output support enabled. Finally, we also enable
the MOLECULE package and compile using the generated auto Make le.
cd$LAMMPS_DIR/src
#generatecustomMakefile
python2Make.pyjpgpngsffmpegexceptionsmmpiafile
#addpackagesifnecessary
makeyesMOLECULE
#compilesharedlibraryusingMakefile
makemode=shlibauto
cd$LAMMPS_DIR/python
pythoninstall.py
Note
Recompiling the shared library requires reinstalling the Python package
aptgetinstallpythonvirtualenv
#activate'testing'environment
sourcetesting/bin/activate
#installLAMMPSpackageinvirtualenv
(testing)cd$LAMMPS_DIR/python
(testing)pythoninstall.py
#installotherusefulpackages
(testing)pipinstallmatplotlibjupytermpi4py
...
#returntooriginalshell
(testing)deactivate
fromlammpsimportPyLammps
L=PyLammps()
You can also initialize PyLammps on top of this existing lammps object:
fromlammpsimportlammps,PyLammps
lmp=lammps()
L=PyLammps(ptr=lmp)
Commands
Sending a LAMMPS command with the existing library interfaces is done using the command
method of the lammps object instance.
For instance, lets take the following LAMMPS command:
regionboxblock010050.50.5
In the original interface this command can be executed with the following Python code if L was a
lammps instance:
L.command("regionboxblock010050.50.5")
With the PyLammps interface, any command can be split up into arbitrary parts separated by
whitespace, passed as individual arguments to a region method.
L.region("boxblock",0,10,0,5,0.5,0.5)
Note that each parameter is set as Python literal oating-point number. In the PyLammps
interface, each command takes an arbitrary parameter list and transparently merges it to a single
command string, separating individual parameters by whitespace.
The bene t of this approach is avoiding redundant command calls and easier parameterization. In
the original interface parametrization needed to be done manually by creating formatted strings.
L.command("regionboxblock%f%f%f%f%f%f"%(xlo,xhi,ylo,yhi,zlo,zhi))
In contrast, methods of PyLammps accept parameters directly and will convert them
automatically to a nal command string.
L.region("boxblock",xlo,xhi,ylo,yhi,zlo,zhi)
System state
In addition to dispatching commands directly through the PyLammps object, it also provides
several properties which allow you to query the system state.
L.system
Is a dictionary describing the system such as the bounding box or number of atoms
L.system.xlo, L.system.xhi
L.variable("aindex2")
a=L.variables['a']
The variable value can then be easily read and written by accessing the value property of this
object.
print(a.value)
a.value=4
result=L.eval("ke")#kineticenergy
result=L.eval("pe")#potentialenergy
result=L.eval("v_t/2.0")
#accessfirstatom
L.atoms[0].id
L.atoms[0].type
#accesssecondatom
L.atoms[1].position
L.atoms[1].velocity
L.atoms[1].force
#setpositionin2Dsimulation
L.atoms[0].position=(1.0,0.0)
#setpositionin3Dsimulation
L.atoms[0].position=(1.0,0.0,1.)
Each simulation run usually produces thermo output based on system state, computes, xes or
variables. The trajectories of these values can be queried after a run via the L.runs list. This list
contains a growing list of run data. The rst element is the output of the rst run, the second
element that of the second run.
L.run(1000)
L.runs[0]#dataoffirst1000timesteps
L.run(1000)
L.runs[1]#dataofsecond1000timesteps
Each run contains a dictionary of all trajectories. Each trajectory is accessible through its thermo
name:
L.runs[0].step#listoftimestepsinfirstrun
L.runs[0].ke#listofkineticenergyvaluesinfirstrun
steps=L.runs[0].step
ke=L.runs[0].ke
plt.plot(steps,ke)
jupyternotebook
IPyLammps Examples
Examples of IPython notebooks can be found in the python/examples/pylammps subdirectory. To
open these notebooks launch jupyter notebook inside this directory and navigate to one of them.
If you compiled and installed a LAMMPS shared library with execeptions, PNG, JPEG and
FFMPEG support you should be able to rerun all of these notebooks.
pos=[(1.0,math.cos(p),math.sin(p))forpinphi]
pe=[]
forpinpos:
L.atoms[3].position=p
L.run(0)
pe.append(L.eval("pe"))
By evaluating the potential energy for each position we can verify that trajectory with the
analytical formula. To compare both solutions, we plot both trajectories over each other using
matplotlib, which embeds the generated plot inside the IPython notebook.
foriinrange(L.system.natoms):
x,y=L.atoms[i].position
dx=deltaperturb*random.uniform(1,1)
dy=deltaperturb*random.uniform(1,1)
L.atoms[i].position=(x+dx,y+dy)
L.run(0)
Finally, the Monte Carlo algorithm is implemented in Python. It continuously moves random
atoms by a random delta and only accepts certain moves.
estart=L.eval("pe")
elast=estart
naccept=0
energies=[estart]
niterations=3000
deltamove=0.1
kT=0.05
natoms=L.system.natoms
foriinrange(niterations):
iatom=random.randrange(0,natoms)
current_atom=L.atoms[iatom]
x0,y0=current_atom.position
dx=deltamove*random.uniform(1,1)
dy=deltamove*random.uniform(1,1)
current_atom.position=(x0+dx,y0+dy)
L.run(1,"prenopostno")
e=L.eval("pe")
energies.append(e)
ife<=elast:
naccept+=1
elast=e
elifrandom.random()<=math.exp(natoms*(elaste)/kT):
naccept+=1
elast=e
else:
current_atom.position=(x0,y0)
The energies of each iteration are collected in a Python list and nally plotted using matplotlib.
The IPython notebook also shows how to use dump commands and embed video les inside of the
IPython notebook.
pipinstallmpi4py
The following is a short example which reads in an existing LAMMPS input le and executes it in
parallel. You can nd in.melt in the examples/melt folder.
frommpi4pyimportMPI
fromlammpsimportPyLammps
L=PyLammps()
L.file("in.melt")
ifMPI.COMM_WORLD.rank==0:
print("Potentialenergy:",L.eval("pe"))
MPI.Finalize()
To run this script (melt.py) in parallel using 4 MPI processes we invoke the following mpirun
command:
mpirunnp4pythonmelt.py
Warning
Any command must be executed by all MPI processes. However, evaluations and querying the
system state is only available on rank 0.