1 "LAMMPS WWW Site"_lws - "LAMMPS Documentation"_ld - "LAMMPS Commands"_lc :c
3 :link(lws,http://lammps.sandia.gov)
5 :link(lc,Section_commands.html#comm)
13 python func keyword args ... :pre
15 func = name of Python function :ulb,l
16 one or more keyword/args pairs must be appended :l
17 keyword = {invoke} or {input} or {return} or {format} or {length} or {file} or {here} or {exists}
18 {invoke} arg = none = invoke the previously defined Python function
19 {input} args = N i1 i2 ... iN
20 N = # of inputs to function
21 i1,...,iN = value, SELF, or LAMMPS variable name
22 value = integer number, floating point number, or string
23 SELF = reference to LAMMPS itself which can be accessed by Python function
24 variable = v_name, where name = name of LAMMPS variable, e.g. v_abc
25 {return} arg = varReturn
26 varReturn = v_name = LAMMPS variable name which return value of function will be assigned to
27 {format} arg = fstring with M characters
28 M = N if no return value, where N = # of inputs
29 M = N+1 if there is a return value
30 fstring = each character (i,f,s,p) corresponds in order to an input or return value
31 'i' = integer, 'f' = floating point, 's' = string, 'p' = SELF
33 Nlen = max length of string returned from Python function
35 filename = file of Python code, which defines func
37 inline = one or more lines of Python code which defines func
38 must be a single argument, typically enclosed between triple quotes
39 {exists} arg = none = Python code has been loaded by previous python command :pre
44 python pForce input 2 v_x 20.0 return v_f format fff file force.py
45 python pForce invoke :pre
47 python factorial input 1 myN return v_fac format ii here """
50 return n * factorial(n-1)
53 python loop input 1 SELF return v_value format -f here """
54 def loop(lmpptr,N,cut0):
55 from lammps import lammps
56 lmp = lammps(ptr=lmpptr) :pre
58 # loop N times, increasing cutoff each time :pre
62 lmp.set_variable("cut",cut) # set a variable in LAMMPS
63 lmp.command("pair_style lj/cut $\{cut\}") # LAMMPS commands
64 lmp.command("pair_coeff * * 1.0 1.0")
65 lmp.command("run 100")
70 NOTE: It is not currently possible to use the "python"_python.html
71 command described in this section with Python 3, only with Python 2.
72 The C API changed from Python 2 to 3 and the LAMMPS code is not
75 Define a Python function or execute a previously defined function.
76 Arguments, including LAMMPS variables, can be passed to the function
77 from the LAMMPS input script and a value returned by the Python
78 function to a LAMMPS variable. The Python code for the function can
79 be included directly in the input script or in a separate Python file.
80 The function can be standard Python code or it can make "callbacks" to
81 LAMMPS through its library interface to query or set internal values
82 within LAMMPS. This is a powerful mechanism for performing complex
83 operations in a LAMMPS input script that are not possible with the
84 simple input script and variable syntax which LAMMPS defines. Thus
85 your input script can operate more like a true programming language.
87 Use of this command requires building LAMMPS with the PYTHON package
88 which links to the Python library so that the Python interpreter is
89 embedded in LAMMPS. More details about this process are given below.
91 There are two ways to invoke a Python function once it has been
92 defined. One is using the {invoke} keyword. The other is to assign
93 the function to a "python-style variable"_variable.html defined in
94 your input script. Whenever the variable is evaluated, it will
95 execute the Python function to assign a value to the variable. Note
96 that variables can be evaluated in many different ways within LAMMPS.
97 They can be substituted for directly in an input script. Or they can
98 be passed to various commands as arguments, so that the variable is
99 evaluated during a simulation run.
101 A broader overview of how Python can be used with LAMMPS is
102 given in "Section 11"_Section_python.html. There is an
103 examples/python directory which illustrates use of the python
108 The {func} setting specifies the name of the Python function. The
109 code for the function is defined using the {file} or {here} keywords
112 If the {invoke} keyword is used, no other keywords can be used, and a
113 previous python command must have defined the Python function
114 referenced by this command. This invokes the Python function with the
115 previously defined arguments and return value processed as explained
116 below. You can invoke the function as many times as you wish in your
119 The {input} keyword defines how many arguments {N} the Python function
120 expects. If it takes no arguments, then the {input} keyword should
121 not be used. Each argument can be specified directly as a value,
122 e.g. 6 or 3.14159 or abc (a string of characters). The type of each
123 argument is specified by the {format} keyword as explained below, so
124 that Python will know how to interpret the value. If the word SELF is
125 used for an argument it has a special meaning. A pointer is passed to
126 the Python function which it converts into a reference to LAMMPS
127 itself. This enables the function to call back to LAMMPS through its
128 library interface as explained below. This allows the Python function
129 to query or set values internal to LAMMPS which can affect the
130 subsequent execution of the input script. A LAMMPS variable can also
131 be used as an argument, specified as v_name, where "name" is the name
132 of the variable. Any style of LAMMPS variable can be used, as defined
133 by the "variable"_variable.html command. Each time the Python
134 function is invoked, the LAMMPS variable is evaluated and its value is
135 passed to the Python function.
137 The {return} keyword is only needed if the Python function returns a
138 value. The specified {varReturn} must be of the form v_name, where
139 "name" is the name of a python-style LAMMPS variable, defined by the
140 "variable"_variable.html command. The Python function can return a
141 numeric or string value, as specified by the {format} keyword.
143 As explained on the "variable"_variable.html doc page, the definition
144 of a python-style variable associates a Python function name with the
145 variable. This must match the {func} setting for this command. For
146 exampe these two commands would be self-consistent:
148 variable foo python myMultiply
149 python myMultiply return v_foo format f file funcs.py :pre
151 The two commands can appear in either order in the input script so
152 long as both are specified before the Python function is invoked for
155 The {format} keyword must be used if the {input} or {return} keyword
156 is used. It defines an {fstring} with M characters, where M = sum of
157 number of inputs and outputs. The order of characters corresponds to
158 the N inputs, followed by the return value (if it exists). Each
159 character must be one of the following: "i" for integer, "f" for
160 floating point, "s" for string, or "p" for SELF. Each character
161 defines the type of the corresponding input or output value of the
162 Python function and affects the type conversion that is performed
163 internally as data is passed back and forth between LAMMPS and Python.
164 Note that it is permissible to use a "python-style
165 variable"_variable.html in a LAMMPS command that allows for an
166 equal-style variable as an argument, but only if the output of the
167 Python function is flagged as a numeric value ("i" or "f") via the
170 If the {return} keyword is used and the {format} keyword specifies the
171 output as a string, then the default maximum length of that string is
172 63 characters (64-1 for the string terminator). If you want to return
173 a longer string, the {length} keyword can be specified with its {Nlen}
174 value set to a larger number (the code allocates space for Nlen+1 to
175 include the string terminator). If the Python function generates a
176 string longer than the default 63 or the specified {Nlen}, it will be
181 Either the {file}, {here}, or {exists} keyword must be used, but only
182 one of them. These keywords specify what Python code to load into the
183 Python interpreter. The {file} keyword gives the name of a file,
184 which should end with a ".py" suffix, which contains Python code. The
185 code will be immediately loaded into and run in the "main" module of
186 the Python interpreter. Note that Python code which contains a
187 function definition does not "execute" the function when it is run; it
188 simply defines the function so that it can be invoked later.
190 The {here} keyword does the same thing, except that the Python code
191 follows as a single argument to the {here} keyword. This can be done
192 using triple quotes as delimiters, as in the examples above. This
193 allows Python code to be listed verbatim in your input script, with
194 proper indentation, blank lines, and comments, as desired. See
195 "Section 3.2"_Section_commands.html#cmd_2, for an explanation of how
196 triple quotes can be used as part of input script syntax.
198 The {exists} keyword takes no argument. It means that Python code
199 containing the required Python function defined by the {func} setting,
200 is assumed to have been previously loaded by another python command.
202 Note that the Python code that is loaded and run must contain a
203 function with the specified {func} name. To operate properly when
204 later invoked, the function code must match the {input} and
205 {return} and {format} keywords specified by the python command.
206 Otherwise Python will generate an error.
210 This section describes how Python code can be written to work with
213 Whether you load Python code from a file or directly from your input
214 script, via the {file} and {here} keywords, the code can be identical.
215 It must be indented properly as Python requires. It can contain
216 comments or blank lines. If the code is in your input script, it
217 cannot however contain triple-quoted Python strings, since that will
218 conflict with the triple-quote parsing that the LAMMPS input script
221 All the Python code you specify via one or more python commands is
222 loaded into the Python "main" module, i.e. __main__. The code can
223 define global variables or statements that are outside of function
224 definitions. It can contain multiple functions, only one of which
225 matches the {func} setting in the python command. This means you can
226 use the {file} keyword once to load several functions, and the
227 {exists} keyword thereafter in subsequent python commands to access
228 the other functions previously loaded.
230 A Python function you define (or more generally, the code you load)
231 can import other Python modules or classes, it can make calls to other
232 system functions or functions you define, and it can access or modify
233 global variables (in the "main" module) which will persist between
234 successive function calls. The latter can be useful, for example, to
235 prevent a function from being invoke multiple times per timestep by
236 different commands in a LAMMPS input script that access the returned
237 python-style variable associated with the function. For example,
238 consider this function loaded with two global variables defined
239 outside the function:
244 def expensive(nstep):
245 global nsteplast,nvaluelast
246 if nstep == nsteplast: return nvaluelast
248 # perform complicated calculation
253 Nsteplast stores the previous timestep the function was invoked
254 (passed as an argument to the function). Nvaluelast stores the return
255 value computed on the last function invocation. If the function is
256 invoked again on the same timestep, the previous value is simply
257 returned, without re-computing it. The "global" statement inside the
258 Python function allows it to overwrite the global variables.
260 Note that if you load Python code multiple times (via multiple python
261 commands), you can overwrite previously loaded variables and functions
262 if you are not careful. E.g. if the code above were loaded twice, the
263 global variables would be re-initialized, which might not be what you
264 want. Likewise, if a function with the same name exists in two chunks
265 of Python code you load, the function loaded second will override the
266 function loaded first.
268 It's important to realize that if you are running LAMMPS in parallel,
269 each MPI task will load the Python interpreter and execute a local
270 copy of the Python function(s) you define. There is no connection
271 between the Python interpreters running on different processors.
272 This implies three important things.
274 First, if you put a print statement in your Python function, you will
275 see P copies of the output, when running on P processors. If the
276 prints occur at (nearly) the same time, the P copies of the output may
277 be mixed together. Welcome to the world of parallel programming and
280 Second, if your Python code loads modules that are not pre-loaded by
281 the Python library, then it will load the module from disk. This may
282 be a bottleneck if 1000s of processors try to load a module at the
283 same time. On some large supercomputers, loading of modules from disk
284 by Python may be disabled. In this case you would need to pre-build a
285 Python library that has the required modules pre-loaded and link
286 LAMMPS with that library.
288 Third, if your Python code calls back to LAMMPS (discussed in the
289 next section) and causes LAMMPS to perform an MPI operation requires
290 global communication (e.g. via MPI_Allreduce), such as computing the
291 global temperature of the system, then you must insure all your Python
292 functions (running independently on different processors) call back to
293 LAMMPS. Otherwise the code may hang.
297 Your Python function can "call back" to LAMMPS through its
298 library interface, if you use the SELF input to pass Python
299 a pointer to LAMMPS. The mechanism for doing this in your
300 Python function is as follows:
303 from lammps import lammps
304 lmp = lammps(ptr=lmpptr)
305 lmp.command('print "Hello from inside Python"')
308 The function definition must include a variable (lmpptr in this case)
309 which corresponds to SELF in the python command. The first line of
310 the function imports the Python module lammps.py in the python dir of
311 the distribution. The second line creates a Python object "lmp" which
312 wraps the instance of LAMMPS that called the function. The
313 "ptr=lmpptr" argument is what makes that happen. The thrid line
314 invokes the command() function in the LAMMPS library interface. It
315 takes a single string argument which is a LAMMPS input script command
316 for LAMMPS to execute, the same as if it appeared in your input
317 script. In this case, LAMMPS should output
319 Hello from inside Python :pre
321 to the screen and log file. Note that since the LAMMPS print command
322 itself takes a string in quotes as its argument, the Python string
323 must be delimited with a different style of quotes.
325 "Section 11.7"_Section_python.html#py_7 describes the syntax for how
326 Python wraps the various functions included in the LAMMPS library
329 A more interesting example is in the examples/python/in.python script
330 which loads and runs the following function from examples/python/funcs.py:
332 def loop(N,cut0,thresh,lmpptr):
333 print "LOOP ARGS",N,cut0,thresh,lmpptr
334 from lammps import lammps
335 lmp = lammps(ptr=lmpptr)
336 natoms = lmp.get_natoms() :pre
339 cut = cut0 + i*0.1 :pre
341 lmp.set_variable("cut",cut) # set a variable in LAMMPS
342 lmp.command("pair_style lj/cut $\{cut\}") # LAMMPS command
343 #lmp.command("pair_style lj/cut %d" % cut) # LAMMPS command option :pre
345 lmp.command("pair_coeff * * 1.0 1.0") # ditto
346 lmp.command("run 10") # ditto
347 pe = lmp.extract_compute("thermo_pe",0,0) # extract total PE from LAMMPS
348 print "PE",pe/natoms,thresh
349 if pe/natoms < thresh: return :pre
351 with these input script commands:
353 python loop input 4 10 1.0 -4.0 SELF format iffp file funcs.py
354 python loop invoke :pre
356 This has the effect of looping over a series of 10 short runs (10
357 timesteps each) where the pair style cutoff is increased from a value
358 of 1.0 in distance units, in increments of 0.1. The looping stops
359 when the per-atom potential energy falls below a threshhold of -4.0 in
360 energy units. More generally, Python can be used to implement a loop
361 with complex logic, much more so than can be created using the LAMMPS
362 "jump"_jump.html and "if"_if.html commands.
364 Several LAMMPS library functions are called from the loop function.
365 Get_natoms() returns the number of atoms in the simulation, so that it
366 can be used to normalize the potential energy that is returned by
367 extract_compute() for the "thermo_pe" compute that is defined by
368 default for LAMMPS thermodynamic output. Set_variable() sets the
369 value of a string variable defined in LAMMPS. This library function
370 is a useful way for a Python function to return multiple values to
371 LAMMPS, more than the single value that can be passed back via a
372 return statement. This cutoff value in the "cut" variable is then
373 substituted (by LAMMPS) in the pair_style command that is executed
374 next. Alternatively, the "LAMMPS command option" line could be used
375 in place of the 2 preceeding lines, to have Python insert the value
376 into the LAMMPS command string.
378 NOTE: When using the callback mechanism just described, recognize that
379 there are some operations you should not attempt because LAMMPS cannot
380 execute them correctly. If the Python function is invoked between
381 runs in the LAMMPS input script, then it should be OK to invoke any
382 LAMMPS input script command via the library interface command() or
383 file() functions, so long as the command would work if it were
384 executed in the LAMMPS input script directly at the same point.
386 However, a Python function can also be invoked during a run, whenever
387 an associated LAMMPS variable it is assigned to is evaluted. If the
388 variable is an input argument to another LAMMPS command (e.g. "fix
389 setforce"_fix_setforce.html), then the Python function will be invoked
390 inside the class for that command, in one of its methods that is
391 invoked in the middle of a timestep. You cannot execute arbitrary
392 input script commands from the Python function (again, via the
393 command() or file() functions) at that point in the run and expect it
394 to work. Other library functions such as those that invoke computes
395 or other variables may have hidden side effects as well. In these
396 cases, LAMMPS has no simple way to check that something illogical is
401 If you run Python code directly on your workstation, either
402 interactively or by using Python to launch a Python script stored in a
403 file, and your code has an error, you will typically see informative
404 error messages. That is not the case when you run Python code from
405 LAMMPS using an embedded Python interpreter. The code will typically
406 fail silently. LAMMPS will catch some errors but cannot tell you
407 where in the Python code the problem occurred. For example, if the
408 Python code cannot be loaded and run because it has syntax or other
409 logic errors, you may get an error from Python pointing to the
410 offending line, or you may get one of these generic errors from
413 Could not process Python file
414 Could not process Python string :pre
416 When the Python function is invoked, if it does not return properly,
417 you will typically get this generic error from LAMMPS:
419 Python function evaluation failed :pre
421 Here are three suggestions for debugging your Python code while
422 running it under LAMMPS.
424 First, don't run it under LAMMPS, at least to start with! Debug it
425 using plain Python. Load and invoke your function, pass it arguments,
426 check return values, etc.
428 Second, add Python print statements to the function to check how far
429 it gets and intermediate values it calculates. See the discussion
430 above about printing from Python when running in parallel.
432 Third, use Python exception handling. For example, say this statement
433 in your Python function is failing, because you have not initialized the
438 If you put one (or more) statements inside a "try" statement,
442 print "Inside simple function"
444 foo += 1 # one or more statements here
446 print "FOO error:",e :pre
448 then you will get this message printed to the screen:
450 FOO error: local variable 'foo' referenced before assignment :pre
452 If there is no error in the try statements, then nothing is printed.
453 Either way the function continues on (unless you put a return or
454 sys.exit() in the except clause).
460 This command is part of the PYTHON package. It is only enabled if
461 LAMMPS was built with that package. See the "Making
462 LAMMPS"_Section_start.html#start_3 section for more info.
464 Building LAMMPS with the PYTHON package will link LAMMPS with the
465 Python library on your system. Settings to enable this are in the
466 lib/python/Makefile.lammps file. See the lib/python/README file for
467 information on those settings.
469 If you use Python code which calls back to LAMMPS, via the SELF input
470 argument explained above, there is an extra step required when
471 building LAMMPS. LAMMPS must also be built as a shared library and
472 your Python function must be able to to load the Python module in
473 python/lammps.py that wraps the LAMMPS library interface. These are
474 the same steps required to use Python by itself to wrap LAMMPS.
475 Details on these steps are explained in "Section
476 python"_Section_python.html. Note that it is important that the
477 stand-alone LAMMPS executable and the LAMMPS shared library be
478 consistent (built from the same source code files) in order for this
479 to work. If the two have been built at different times using
480 different source files, problems may occur.
482 As described above, you can use the python command to invoke a Python
483 function which calls back to LAMMPS through its Python-wrapped library
484 interface. However you cannot do the opposite. I.e. you cannot call
485 LAMMPS from Python and invoke the python command to "callback" to
486 Python and execute a Python function. LAMMPS will generate an error
487 if you try to do that. Note that we think there actually should be a
488 way to do that, but haven't yet been able to figure out how to do it
493 "shell"_shell.html, "variable"_variable.html