Repository navigation
Description
Summary
Functions defined in the python interpreter's main module are not found by lammps.
E.g. python end_of_step_callback input 1 SELF format p exists always fails if the function is defined in __main__.
Minimal reproducible example below.
LAMMPS Version and Platform
LAMMPS (23 Jun 2022), compiled from source
OS: OSX 13.0
Architecture: arm64
Python : 3.10.6
Python distribution: conda-forge
Expected Behavior
When called from python via the python library, lammps allows calling and using in fixes python functions, by first assigning them a name and specifying their argument format; this functions can be defined with the same name in the main module.
Documentation here https://docs.lammps.org/python.html .
Actual Behavior
Exception thrown here
lammps/src/PYTHON/python_impl.cpp
Line 251 in 9cbc77f
| error->all(FLERR, "Could not find Python function {}", pfuncs[ifunc].name); |
Steps to Reproduce
Download and compile from source the same lammps version (I used conda-forge compilers and tools).
Run the script below:
import lammps
script = """
units lj
atom_style atomic
#setup test data
lattice sc 1
region box block 0 3 0 2 0 2
create_box 3 box # (number of atom types)
create_atoms 1 box
mass * 1.0
python end_of_step_callback input 1 SELF format p exists
"""
def end_of_step_callback(ptr):
lmp = lammps.lammps(ptr=ptr)
def main():
lmp = lammps.lammps(cmdargs=['-log','none','-nocite','-echo','log'])
lmp.commands_string(script)
if __name__=='__main__':
main()Output:
#output
"""
LAMMPS (23 Jun 2022)
Lattice spacing in x,y,z = 1 1 1
Created orthogonal box = (0 0 0) to (3 2 2)
1 by 1 by 1 MPI processor grid
Created 12 atoms
using lattice units in orthogonal box = (0 0 0) to (3 2 2)
create_atoms CPU = 0.000 seconds
AttributeError: module '__main__' has no attribute 'end_of_step_callback'
ERROR: Could not find Python function end_of_step_callback (src/PYTHON/python_impl.cpp:246)
Last command: python end_of_step_callback input 1 SELF format p here ""
Traceback (most recent call last):
File ".../lammps_python_invoke_test.py", line 34, in <module>
main()
File ".../lammps_python_invoke_test.py", line 31, in main
lmp.commands_string(script)
File "$PREFIX/lib/python3.10/site-packages/lammps/core.py", line 617, in commands_string
with ExceptionCheck(self):
File "$PREFIX/lib/python3.10/site-packages/lammps/core.py", line 49, in __exit__
raise self.lmp._lammps_exception
Exception: ERROR: Could not find Python function end_of_step_callback (src/PYTHON/python_impl.cpp:246)
Total wall time: 0:00:00
"""
Further Information, Files, and Links
Either I am forgetting something in the parameters for the python command, in which case I am really sorry for everyone's time, or something weird is going on with __main__.
I looked at #3204 ; the python I compiled against has a shared library in $CONDA_PREFIX/lib/libpython3.10.dylib.
However the python executable itself python3.10 does not reference this library, while liblammps.dylib does.
from distutils import sysconfig; print(sysconfig.get_config_var('Py_ENABLE_SHARED')) prints 0.
>otool -L $(which python)
$CONDA_PREFIX/bin/python:
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1292.0.0)
>otool -L $PREFIX/lib/liblammps.dylib
liblammps.dylib:
@rpath/liblammps.0.dylib (compatibility version 0.0.0, current version 0.0.0)
@rpath/libjpeg.9.dylib (compatibility version 15.0.0, current version 15.0.0)
@rpath/libpng16.16.dylib (compatibility version 55.0.0, current version 55.0.0)
@rpath/libpython3.10.dylib (compatibility version 3.10.0, current version 3.10.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1319.0.0)
@rpath/libc++.1.dylib (compatibility version 1.0.0, current version 1.0.0)Build script:
#!/bin/bash
SRC_DIR=$(pwd)
BUILD_DIR=${SRC_DIR}/build
mkdir "${BUILD_DIR}"
cd "${BUILD_DIR}" || (
echo "can't move to build directory"
exit 1
)
cmake \
-D BUILD_MPI=no \
-D BUILD_OMP=no \
-D PKG_PYTHON=on \
-D BUILD_SHARED_LIBS=on \
-D LAMMPS_EXCEPTIONS=yes \
-D PKG_OPENMP=yes \
-D CMAKE_INSTALL_PREFIX="${PREFIX}" \
"$SRC_DIR"/cmake
make -j$(nproc)
make install
Activity
akohlmey commentedon Nov 9, 2022
Please try with the 3Nov2022 version of LAMMPS. This is likely a known technical limitation of MacOS that possibly addressed with the changes in PR #3458
I do not see a problem on Linux with 3Nov2022. I currently have no access to a suitable MacOS machine.
akohlmey commentedon Nov 9, 2022
Another issue could be that if you obtained python through conda, you may run into issues with how conda builds its python development support. If the python interpreter is linked to a static version of the python library and LAMMPS to a dynamic version, than there are going to be problems at runtime with inconsistent symbol handling and errors or segmentation faults (also on Linux).
LunarLanding commentedon Nov 10, 2022
Thanks for the quick reply and testing on Linux.
I have tried with the 3Nov2022 version (output below), unfortunately I still get the same issue:
It seems I hit a quite niche use case, given that conda is widely used for python and they do not provide by default a python executable with enable-shared. Currently I am trying to compile python with enabled-shared while maintaining compatibility with conda's distribution by using the same build script, but it is not being easy.
I might have to drop either using python modifiers or calling lammps from python. I have scripts that run logic in python by using python->lammps; and I also have implemented some solutions for dynamic reactions using python modifiers.
I tried doing lammps->python logic->lammps, since this should just use libpython, but it just crashed at the
lattice sc 1command:Output:
For anyone on OSX, I had to add
export DYLD_LIBRARY_PATH=".:$PREFIX/lib64:$PREFIX/lib:${DYLD_LIBRARY_PATH-}"to my environment so the python lammps module could findliblammps.dylib.akohlmey commentedon Nov 10, 2022
@LunarLanding I cannot reproduce the segfault on Linux either.
I am preparing a pull request that will document the limitation of having to use a Python interpreter linked to a shared python runtime library when also using the LAMMPS python module. I am also slightly changing the syntax for the
python sourcecommand by dropping the need for a dummy function name and restructuring the documentation a bit. Also, the code needs more specific error messages since in most cases it currently prints "illegal python command" without any hint of what went wrong where.What would work in your case with the static linked python interpreter is to not define the function directly in python but writing the function definition to a file and then use the "source" keyword of the "python command" (example "python dummy source mydef.py") to import/source the python code. This delays the function definition and moves it to be done when the main module is the one used by the LAMMPS shared library.
In general, it looks to me, that what you are doing is needlessly adding at least one (if not two) levels of indirection to the process. In your test case there isn't really much of a difference to processing the LAMMPS input from Python versus using the LAMMPS executable as the top level and reading the heredoc string as regular LAMMPS input.
So you are somewhat inviting trouble.
akohlmey commentedon Nov 10, 2022
How did you install the LAMMPS python module? Did you do "make install" or "make install-python". In the latter case it should not be needed to set any environment variables since a copy of the shared library is placed into the same folder as the python code. For "make install" is is expected that you set the environment variable since you would be installing LAMMPS globally or to a folder where shared libraries should be automatically found.
LunarLanding commentedon Nov 11, 2022
I gave a minimal example, it is not intended to justify this usage, just to showcase this bug with the python->lammps->python sandwich. But it is easy to arrive at. For instance my use-case uses python to define and run a state machine that manages restarts and recovering from lammps errors, while interfacing directly with lammps to read global state; python fixes are used to add custom forces.
I think with this method I would not be able to initialize the simulation box with python, but I will have to try it.
I installed via the build script above, so
make install. Something must have changed, right now I don't need DYLD_LIBRARY_PATH set. The script is adapted from the build.sh on the lammps feedstock on conda-forge. It both installs the python module and an executable.Meanwhile I managed to install python with enable-shared and the minimal example above runs with no issue.
akohlmey commentedon Nov 11, 2022
If you want to set up a system from custom commands, you can just as well put the LAMMPS command that you now put in strings into a file and read/process the file with
lmp.file('somefilename')from the python interface or withinclude somefilenamefrom LAMMPS commands.There are always alternatives. It is mostly a question at looking a problems from a different perspective.
In my experience, Conda is not a good template. There have been multiple problems with LAMMPS due to the peculiarities of how Conda does its packaging and in my (day) job as manager of HPC resources we see recurring problems with people trying to use Conda to install/manage their own software stacks (i.e. not just LAMMPS) that we don't see with our environment modules or compiling from plain sources.
And to top it off you are running on MacOS which in the last decade has become increasingly problematic and causing unexpected porting issues thanks to the effort of Apple engineers to "think different". MacOS used to be extremely similar to *BSD unix machines which only required a little care with some system calls and shell scripts, but has since acquired a long list of quirks that require special treatment.
In the end you can still get things to work, but from the software maintenance perspective it has turned into a never ending game or playing catch-up. LAMMPS development is mostly done on Linux machines and occasionally on Windows but rarely on MacOS, so the chances that something breaks unintentionally are higher, especially if you have an unusual use case that is no (yet) covered by the automated testing.