10. Python interface to LIGGGHTS(R)-PUBLIC¶
この節では、Pythonインタフェース経由
でLIGGGHTS(R)-PUBLICをビルドして使用する方法について説明します。
- 9.1共有ライブラリーとしての LIGGGHTS(R)-PUBLICの構築
- 9.2 PythonへのPythonラッパーのインストール
- 9.3 PythonをMPIで拡張して並列実行
- 9.4 Python-LIGGGHTS(R)-PUBLICインターフェースのテスト
- 9.5 PythonからのLIGGGHTS(R)-PUBLICの使用
- 9.6 LIGGGHTS(R)-PUBLICを使用するPythonスクリプトの例
LIGGGHTS(R)-PUBLICディス
トリビューションには、ライブラリインタフェースをLIGGGHTS(R)-PUBLICにラップするファイルpython
/
lammps.pyが含まれています。このファイルを使用すると、LIGGGHTS(R)-PUBLICコマンドを実行したり、入力スクリプトを与えたり、
LIGGGHTS(R)-PUBLIC結果を抽出したり、内部LIGGGHTS(R)-PUBLIC変数を変更したりするこ
とができ、
それらは、Pythonスクリプトから、またはPythonプロンプトか対話的に実行できます。また前者はシリアルまたはパラレルで実行できます。Pythonを拡張して
Pythonの複数のインスタンスが、あなたが入力したものを読むことを可能にするパッケージを、インストールしない限り、
Pythonを対話的に並行して実行することは一般的には機能しません。
Pythonは、LIGGGHTS(R)-PUBLICや他のパッケージのようなソフトウェアをラップするのに使用できる強
力なスクリプト言語です。これは、複数のソフトウェアを一緒に結合するために使用することができます。例えば、連成モデル、
またはマルチスケールモデルを実行する。
LIGGGHTS(R)-PUBLICを他のコードに結合する方法の詳細については、配布のマニュアルとカップルディレクトリのセクション節を参照してください。ライブラ
リとしてLIGGGHTS(R)-PUBLICを構築する方法についてはSection_start 4を、src /
library.cppとsrc /
library.hで提供されるライブラリインタフェースについてはSection_howto
19を、また必要に応じて拡張する方法についてはSection
19を参照してください。以下で説明するように、そのインタフェースはPythonに公開されているものです。機能を追加するのが容易になるように設計されています。これ
により、Pythonのインタフェースも簡単に拡張できます。以下の詳細を参照してください。
LIGGGHTS(R)-PUBLICは、Pythonインターフェイスを使用することで、LIGGGHTS(R)-
PUBLICの実行中にリアルタイムでグラフやアニメーションを表示するGUIや他の視覚化ツールと組み合わせることもでき
ます。そのようなスクリプトの例は、pythonディレクトリに含まれています。
Pythonを使用することの2つの利点は、言語がどれほど簡潔であり、対話的に実行できるため、プログラムの迅速な開発と
デバッグが可能です。妥当な数のタイムステップでシミュレーションを実行するなど、LIGGGHTS(R)-PUBLIC内
でコストのかかる操作を主に呼び出す場合は、Pythonを介してLIGGGHTS(R)-PUBLICを呼び出すオーバー
ヘッドコストは無視できます。
PythonスクリプトからLIGGGHTS(R)-PUBLICを使用する前に、2つのことを行う必要があります。動的共
有ライブラリとしてLIGGGHTS(R)-PUBLICをビルドする必要があります。そのため、Pythonでロードする
ことができます。そして、PythonにライブラリとPythonラッパーファイルpython /
lammps.pyを見つける方法を伝える必要があります。これらのステップの両方を以下で説明します。
LIGGGHTS(R)-PUBLICをPythonから並列に実行したい場合は、PythonをMPIで拡張する必要もあります。これについては、以下でも説明します。
LIGGGHTS(R)-PUBLIC用のPythonラッパーは、Pythonとライブラリ用のCインターフェースルーチンのセットの
間で必要なインターフェースコードを自動生成する、Pythonの驚くほど魅力的な(私にとって)
"ctypes"パッケージを使用します。
Ctypesはバージョン2.5以降の標準Pythonの一部です。シェルプロンプトで
"python"と入力するだけで、インストールしたPythonのバージョンを確認することができます。
This section describes how to build and use LIGGGHTS(R)-PUBLIC via a Python interface.
- 9.1 Building LIGGGHTS(R)-PUBLIC as a shared library
- 9.2 Installing the Python wrapper into Python
- 9.3 Extending Python with MPI to run in parallel
- 9.4 Testing the Python-LIGGGHTS(R)-PUBLIC interface
- 9.5 Using LIGGGHTS(R)-PUBLIC from Python
- 9.6 Example Python scripts that use LIGGGHTS(R)-PUBLIC
The LIGGGHTS(R)-PUBLIC distribution includes the file python/lammps.py which wraps the library interface to LIGGGHTS(R)-PUBLIC. This file makes it is possible to run LIGGGHTS(R)-PUBLIC, invoke LIGGGHTS(R)-PUBLIC commands or give it an input script, extract LIGGGHTS(R)-PUBLIC results, an modify internal LIGGGHTS(R)-PUBLIC variables, either from a Python script or interactively from a Python prompt. You can do the former in serial or parallel. Running Python interactively in parallel does not generally work, unless you have a package installed that extends your Python to enable multiple instances of Python to read what you type.
Python is a powerful scripting and programming language which can be used to wrap software like LIGGGHTS(R)-PUBLIC and other packages. It can be used to glue multiple pieces of software together, e.g. to run a coupled or multiscale model. See Section section of the manual and the couple directory of the distribution for more ideas about coupling LIGGGHTS(R)-PUBLIC to other codes. See Section_start 4 about how to build LIGGGHTS(R)-PUBLIC as a library, and Section_howto 19 for a description of the library interface provided in src/library.cpp and src/library.h and how to extend it for your needs. As described below, that interface is what is exposed to Python. It is designed to be easy to add functions to. This can easily extend the Python inteface as well. See details below.
By using the Python interface, LIGGGHTS(R)-PUBLIC can also be coupled with a GUI or other visualization tools that display graphs or animations in real time as LIGGGHTS(R)-PUBLIC runs. Examples of such scripts are inlcluded in the python directory.
Two advantages of using Python are how concise the language is, and that it can be run interactively, enabling rapid development and debugging of programs. If you use it to mostly invoke costly operations within LIGGGHTS(R)-PUBLIC, such as running a simulation for a reasonable number of timesteps, then the overhead cost of invoking LIGGGHTS(R)-PUBLIC thru Python will be negligible.
Before using LIGGGHTS(R)-PUBLIC from a Python script, you need to do two things. You need to build LIGGGHTS(R)-PUBLIC as a dynamic shared library, so it can be loaded by Python. And you need to tell Python how to find the library and the Python wrapper file python/lammps.py. Both these steps are discussed below. If you wish to run LIGGGHTS(R)-PUBLIC in parallel from Python, you also need to extend your Python with MPI. This is also discussed below.
The Python wrapper for LIGGGHTS(R)-PUBLIC uses the amazing and magical (to me) “ctypes” package in Python, which auto-generates the interface code needed between Python and a set of C interface routines for a library. Ctypes is part of standard Python for versions 2.5 and later. You can check which version of Python you have installed, by simply typing “python” at a shell prompt.
10.2. Installing the Python wrapper into Python¶
PythonがLIGGGHTS(R)-
PUBLICを呼び出すためには、知る必要がある2つのファイルがあります:
- python / lammps.py
- src / liblammps.so
Lammps.pyは、
LIGGGHTS(R)-PUBLICライブラリインターフェイス上のPythonラッパーです。
Liblammps.soは、前述のようにPythonがロードする共有LIGGGHTS(R)-PUBLICライブラリです。
Pythonがこれらのファイルを見つけるには、次の2つの方法があります。
- 2つの環境変数を設定する
- python / install.pyスクリプトを実行する
環境変数としてこれらのファイルへのパスを設定した場合は、それを一度だけ行えばよい。
cshまたはtcshシェルの場合は、〜/
.cshrcファイルに次のように、2つのファイルそれぞれに1行を追加します。
For Python to invoke LIGGGHTS(R)-PUBLIC, there are 2 files it needs to know about:
- python/lammps.py
- src/liblammps.so
Lammps.py is the Python wrapper on the LIGGGHTS(R)-PUBLIC library interface. Liblammps.so is the shared LIGGGHTS(R)-PUBLIC library that Python loads, as described above.
You can insure Python can find these files in one of two ways:
- set two environment variables
- run the python/install.py script
If you set the paths to these files as environment variables, you only have to do it once. For the csh or tcsh shells, add something like this to your ~/.cshrc file, one line for each of the two files:
setenv PYTHONPATH $*PYTHONPATH*:/home/sjplimp/lammps/python
setenv LD_LIBRARY_PATH $*LD_LIBRARY_PATH*:/home/sjplimp/lammps/src
python /
install.pyスクリプトを使用する場合は、LIGGGHTS(R)-PUBLICを(共有ライブラリとして)再ビルドするか、python
/ lammps.pyファイルを変更するたびに呼び出す必要があります。
pythonディレクトリから、次のようにinstall.pyを呼び出すことができます。
If you use the python/install.py script, you need to invoke it every time you rebuild LIGGGHTS(R)-PUBLIC (as a shared library) or make changes to the python/lammps.py file.
You can invoke install.py from the python directory as
% python install.py [libdir] [pydir]
オプションのlibdirは、
LIGGGHTS(R)-PUBLIC共有ライブラリをコピーする場所を指定します。 デフォルトは/ usr /
local / libです。 オプションのpydirは、lammps.pyファイルをコピーする場所を指定します。
デフォルトは、インストールスクリプトを実行しているPythonのバージョンのsite-packagesディレクト
リです。
libdirは、/ usr / local / libや/ usr /
libのように、デフォルトのLD_LIBRARY_PATHにある場所でなければならないことに注意してください。
そしてpydirは、site-packagesディレクトリのように、インポートされたモジュールに対してデフォルト
でPythonが参照する場所でなければなりません。
これらのファイルを独自のユーザー空間などの非標準の場所にコピーする場合は、上記のように、環境変数PYTHONPATHとLD_LIBRARY_PATHを設定する必
要があります。
install.pyスクリプトでファイルをシステムディレクトリにコピーできない場合は、pythonコマンドの前に
"sudo"を付けます。
これを行う場合は、rootが実行するPythonが、あなたが実行するPythonと同じであることを確認してください。
例えば、次のようなコマンドを入力する必要があるかもしれません。
The optional libdir is where to copy the LIGGGHTS(R)-PUBLIC shared library to; the default is /usr/local/lib. The optional pydir is where to copy the lammps.py file to; the default is the site-packages directory of the version of Python that is running the install script.
Note that libdir must be a location that is in your default LD_LIBRARY_PATH, like /usr/local/lib or /usr/lib. And pydir must be a location that Python looks in by default for imported modules, like its site-packages dir. If you want to copy these files to non-standard locations, such as within your own user space, you will need to set your PYTHONPATH and LD_LIBRARY_PATH environment variables accordingly, as above.
If the install.py script does not allow you to copy files into system directories, prefix the python command with “sudo”. If you do this, make sure that the Python that root runs is the same as the Python you run. E.g. you may need to do something like
% sudo /usr/local/bin/python install.py [libdir] [pydir]
また、srcディレクトリのmakeコマ ンドからinstall.pyを呼び出すこともできます。
You can also invoke install.py from the make command in the src directory as
% make install-python
このモードでは、オプションの引数を追加
することはできません。 接頭辞として "sudo"を付ける必要があります。
このモードでは、どのPythonがrootによって呼び出されるかは制御できません。
Pythonが異なるバージョンのLIGGGHTS(R)-PUBLIC共有ライブラリ(下記参照)をロードできるよう
にするには、liblammps_g
++.soのようなファイルを適切なシステムディレクトリに手動でコピーする必要があります。
上記のようにLD_LIBRARY_PATH環境変数を設定する場合、これは必要ありません。
In this mode you cannot append optional arguments. Again, you may need to prefix this with “sudo”. In this mode you cannot control which Python is invoked by root.
Note that if you want Python to be able to load different versions of the LIGGGHTS(R)-PUBLIC shared library (see this section below), you will need to manually copy files like liblammps_g++.so into the appropriate system directory. This is not needed if you set the LD_LIBRARY_PATH environment variable as described above.
10.3. Extending Python with MPI to run in parallel¶
LIGGGHTS(R)-PUBLICを
Pythonから並列に実行したい場合は、MPIへのインタフェースを使ってPythonを拡張する必要があります。こ
れにより、必要に応じてスクリプト内でPythonから直接MPI呼び出しを行うこともできます。
MPIをライブラリとしてラップし、MPI関数をPythonから呼び出すことを可能にするいくつかのPythonパッ
ケージがあります。
これらには以下を含みます。
- pyMPI
- maroonmpi
- mpi4py
- myMPI
- Pypar
これらのすべては、MPIライブラリを
ラップし、Pythonスクリプトにインターフェイスの(一部を)公開することで、pyMPIを除いて動作します。つま
り、
異なるプロセッサ上で実行されているPythonの複数のインスタンスへの対話型入力の問題に対処していないため、
Pythonを対話的に並列で使用することはできません。一つの例外はpyMPIで、この問題に対処するために
Pythonインタプリタを変更し、結果として(Python自体の代わりに)新しい代替実行ファイルを作成します。
原則として、これらのPython /
MPIパッケージは、並列でLIGGGHTS(R)-PUBLICを呼び出すように動作する必要があり、MPIはそれ自体が並列で動作するPythonスクリプトから自分
自身を呼び出します。しかし、私がダウンロードしていくつかを見て、彼らのドキュメントは不完全で、私はそれらのインス
トールに 問題があった。パッケージのいくつかがまだ活発に開発されサポートされているかどうかは不明です。
私がLIGGGHTS(R)-PUBLICでうまく使用して以来、私がお勧めするものはPyparです。
Pyparは、Python中のどこにでもあるNumpyパッケージをインストールする必要があります。
Pythonを起動した後、次のように入力します。
If you wish to run LIGGGHTS(R)-PUBLIC in parallel from Python, you need to extend your Python with an interface to MPI. This also allows you to make MPI calls directly from Python in your script, if you desire.
There are several Python packages available that purport to wrap MPI as a library and allow MPI functions to be called from Python.
These include
All of these except pyMPI work by wrapping the MPI library and exposing (some portion of) its interface to your Python script. This means Python cannot be used interactively in parallel, since they do not address the issue of interactive input to multiple instances of Python running on different processors. The one exception is pyMPI, which alters the Python interpreter to address this issue, and (I believe) creates a new alternate executable (in place of “python” itself) as a result.
In principle any of these Python/MPI packages should work to invoke LIGGGHTS(R)-PUBLIC in parallel and MPI calls themselves from a Python script which is itself running in parallel. However, when I downloaded and looked at a few of them, their documentation was incomplete and I had trouble with their installation. It’s not clear if some of the packages are still being actively developed and supported.
The one I recommend, since I have successfully used it with LIGGGHTS(R)-PUBLIC, is Pypar. Pypar requires the ubiquitous Numpy package be installed in your Python. After launching python, type
import numpy
それがインストールされているかどうかを 確認します。 インストールされていない場合は、インストールする方法(2009年4月現在のバージョン1.3.0b1)です。 numpyのtarballを解凍し、その最上位ディレクトリから次のように入力します。
to see if it is installed. If not, here is how to install it (version 1.3.0b1 as of April 2009). Unpack the numpy tarball and from its top-level directory, type
python setup.py build
sudo python setup.py install
"sudo"は、Numpyファイルを
Pythonディストリビューションのsite-packagesディレクトリにコピーする必要がある場合にのみ必要で
す。
Pypar(2012年8月現在のバージョンpypar-2.1.4_94)をインストールするには、そのファイルを解
凍し、 "source"ディレクトリから次のように入力します。
The “sudo” is only needed if required to copy Numpy files into your Python distribution’s site-packages directory.
To install Pypar (version pypar-2.1.4_94 as of Aug 2012), unpack it and from its “source” directory, type
python setup.py build
sudo python setup.py install
ここでも、「sudo」は、Pypar
ファイルをPythonディストリビューションのsite-packagesディレクトリにコピーする必要がある場合に
のみ必要です。
Pyparが正常にインストールされている場合は、Pythonを実行して、以下を入力した場合もエラーが出現しませ
ん。
Again, the “sudo” is only needed if required to copy Pypar files into your Python distribution’s site-packages directory.
If you have successully installed Pypar, you should be able to run Python and type
import pypar
また、以下のような単純なテストスクリプ トでPythonを並列に実行できるようにする必要があります。
without error. You should also be able to run python in parallel on a simple test script
% mpirun -np 4 python test.py
test.pyには、以下の行が含まれて います
where test.py contains the lines
import pypar
print "Proc %d out of %d procs" % (pypar.rank(),pypar.size())
実行しているプロセッサごとに1行の出力 が表示されます。
and see one line of output for each processor you run on.
Warning
Python からPyparとLIGGGHTS(R)-PUBLICを並列において使用するには、両方とも同じバージョンの MPIを使 用していることを保証する必要があります。 システムに1つのMPIしかインストールされていない場合、これは問題ではありませんが、MPIが複数ある場合には問題になります。 LIGGGHTS(R)-PUBLICビルドは、使用しているMPIを明示的に指定しています。これは、lo- level src / MAKE / Makefile.fooファイルで詳細を指定しているためです。 Pyparは、 "mpicc"コマンドを使用して、構築するMPIに関する情報を検索します。 LD_LIBRARY_PATHから "libmpi.so"をロードしようとします。 これは、LIGGGHTS(R)-PUBLICが使用しているMPIライブラリーを見つけようとしています。 PyparとLIGGGHTS(R)-PUBLICの両方を同時に実行する際に問題が発生した場合、これは対処する必要があるかもしれない問題です。 例えば、他のMPIインストールを移動してPyparが正しいものを見つけられるようにします。
To use Pypar and LIGGGHTS(R)-PUBLIC in parallel from Python, you must insure both are using the same version of MPI. If you only have one MPI installed on your system, this is not an issue, but it can be if you have multiple MPIs. Your LIGGGHTS(R)-PUBLIC build is explicit about which MPI it is using, since you specify the details in your lo-level src/MAKE/Makefile.foo file. Pypar uses the “mpicc” command to find information about the MPI it uses to build against. And it tries to load “libmpi.so” from the LD_LIBRARY_PATH. This may or may not find the MPI library that LIGGGHTS(R)-PUBLIC is using. If you have problems running both Pypar and LIGGGHTS(R)-PUBLIC together, this is an issue you may need to address, e.g. by moving other MPI installations so that Pypar finds the right one.
10.4. Testing the Python-LIGGGHTS(R)-PUBLIC interface¶
LIGGGHTS(R)-PUBLICが Pythonから呼び出し可能かどうかをテストするには、対話的にPythonを起動し、次のように入力します。
To test if LIGGGHTS(R)-PUBLIC is callable from Python, launch Python interactively and type:
>>> from lammps import lammps
>>> lmp = lammps()
エラーがなければ、Pythonの LIGGGHTS(R)-PUBLICを使用する準備ができています。 2番目のコマンドが失敗した場合、最もよく見られるエラーは次のとおりです。
If you get no errors, you’re ready to use LIGGGHTS(R)-PUBLIC from Python. If the 2nd command fails, the most common error to see is
OSError: Could not load LIGGGHTS(R)-PUBLIC dynamic library
これは、Pythonが
LIGGGHTS(R)-PUBLIC共有ライブラリをロードできなかったことを意味します。
これは通常、システムがLIGGGHTS(R)-PUBLIC共有ライブラリーまたはそれが依存する補助共用ライブラリーのいずれかを見つけることができない場合、または
ライブラリーについて何かがPythonと互換性がない場合に発生します。
エラーメッセージは、何がうまくいかなかったのかを示します。
また、lammps.pyファイルから最初にインポートすることなく、Pythonで直接ロードをテストすることもでき
ます:
which means Python was unable to load the LIGGGHTS(R)-PUBLIC shared library. This typically occurs if the system can’t find the LIGGGHTS(R)-PUBLIC shared library or one of the auxiliary shared libraries it depends on, or if something about the library is incompatible with your Python. The error message should give you an indication of what went wrong.
You can also test the load directly in Python as follows, without first importing from the lammps.py file:
>>> from ctypes import CDLL
>>> CDLL("liblammps.so")
エラーが発生した場合は、共有ライブラリ を構築する方法とPythonが必要な2つのファイルを見つけられるように、Section_start 5より以前の手順を注意深く行ってください。
If an error occurs, carefully go thru the steps in Section_start 5 and above about building a shared library and about insuring Python can find the necessary two files it needs.
10.4.1. Test LIGGGHTS(R)-PUBLIC and Python in serial:¶
LIGGGHTS(R)- PUBLICテストをシリアルで実行するには、これらの行をbenchディレクトリから対話的にPythonに入力 します。
To run a LIGGGHTS(R)-PUBLIC test in serial, type these lines into Python interactively from the bench directory:
>>> from lammps import lammps
>>> lmp = lammps()
>>> lmp.file("in.lj")
あるいは、同じ行をtest.py ファイルに入れ、下記のように実行します。
Or put the same lines in the file test.py and run it as
% python test.py
どちらの方法でも、シングルプロセッ サにてin.ljベンチ マークを実行した結果が画面上に表示されます。これは、次のように入力した場合と同じです。
Either way, you should see the results of running the in.lj benchmark on a single processor appear on the screen, the same as if you had typed something like:
lmp_g++ < in.lj
10.4.2. Test LIGGGHTS(R)-PUBLIC and Python in parallel:¶
LIGGGHTS(R)- PUBLICを並列に実行するには、上記のようにPyparパッケージをインストールしたと仮定して、以下の行を含 むtest.pyファイルを作成します。
To run LIGGGHTS(R)-PUBLIC in parallel, assuming you have installed the Pypar package as discussed above, create a test.py file containing these lines:
import pypar
from lammps import lammps
lmp = lammps()
lmp.file("in.lj")
print "Proc %d out of %d procs has" % (pypar.rank(),pypar.size()),lmp
pypar.finalize()
そして、次のように並列実行できま す。
You can then run it in parallel as:
% mpirun -np 4 python test.py
もしくは以下を入力すると、同じ出力 が表示 されるはずです
and you should see the same output as if you had typed
% mpirun -np 4 lmp_g++ < in.lj
Piparコマンドを指定する
test.pyの3行を省略した場合は、mpirunコマンドで指定された各Pプロセッサで
LIGGGHTS(R)-PUBLICを独立してインスタンス化して実行します。
この場合は、LIGGGHTS(R)-PUBLICが4つのプロセッサで実行されていることを示す1セットの出力ではなく、1つのプロセッサ上でLIGGGHTS(R)-
PUBLICが実行されたことを示す4セットの出力を得ることになります。
1プロセッサ出力が発生した場合、Pyparが正常に動作していないことを意味します。
また、PyParモジュールをインポートすると、PyparはMPIを初期化し、Pyparのマニュアルに記載され
ているように、Pythonスクリプトで直接MPI呼び出しを使用できます。
Pythonスクリプトの最後の行は、MPIが正しくシャットダウンされるようにpypar.finalize()にする必要があります。
Note that if you leave out the 3 lines from test.py that specify Pypar commands you will instantiate and run LIGGGHTS(R)-PUBLIC independently on each of the P processors specified in the mpirun command. In this case you should get 4 sets of output, each showing that a LIGGGHTS(R)-PUBLIC run was made on a single processor, instead of one set of output showing that LIGGGHTS(R)-PUBLIC ran on 4 processors. If the 1-processor outputs occur, it means that Pypar is not working correctly.
Also note that once you import the PyPar module, Pypar initializes MPI for you, and you can use MPI calls directly in your Python script, as described in the Pypar documentation. The last line of your Python script should be pypar.finalize(), to insure MPI is shut down correctly.
10.4.3. Running Python scripts:¶
Pythonスクリプト (LIGGGHTS(R)-PUBLICだけでなく)は、次のいずれかの方法で呼び出すことができます。
Note that any Python script (not just for LIGGGHTS(R)-PUBLIC) can be invoked in one of several ways:
% python foo.script
% python -i foo.script
% foo.script
最後のコマンドでは、スクリプトの最 初の行を次のようにする必要があります。
The last command requires that the first line of the script be something like this:
#!/usr/local/bin/python
#!/usr/local/bin/python -i
パスはPythonがインストールさ れている場所を指し、スクリプトファイルを実行可能にしています:
where the path points to where you have Python installed, and that you have made the script file executable:
% chmod +x foo.script
"-i"フラグがなければ、スクリプ トが終了するとPythonは終了します。 "-i"フラグを指定すると、スクリプトの終了時にPythonインタプリタに残されます。そのため、後続のコマンドを入力することができます。 上記のように、Pythonは、並列ではなく、単一のプロセッサ上でPythonを実行する場合にのみ対話的に実行 できます。
Without the “-i” flag, Python will exit when the script finishes. With the “-i” flag, you will be left in the Python interpreter when the script finishes, so you can type subsequent commands. As mentioned above, you can only run Python interactively when running Python on a single processor, not in parallel.
10.5. Using LIGGGHTS(R)-PUBLIC from Python¶
LIGGGHTS(R)-PUBLICへ のPythonインタフェースはPython "lammps"モジュールで構成されています。このモジュールのソースコードはpython / lammps.pyにあり、 "lammps"オブジェクトを、そのオブジェクトに対して呼び出すことのできる 一連のメソッドと共に作成します。 以下のサンプルPythonコードは、Pythonスクリプトで "lammps"モジュールを最初にインポートしたものとしています。
The Python interface to LIGGGHTS(R)-PUBLIC consists of a Python “lammps” module, the source code for which is in python/lammps.py, which creates a “lammps” object, with a set of methods that can be invoked on that object. The sample Python code below assumes you have first imported the “lammps” module in your Python script, as follows:
from lammps import lammps
これらは、lammpsモジュールによっ て定義されたメソッドです。 ファイルsrc / library.cppを見ると、C ++またはCまたはFortranプログラムからLIGGGHTS(R)-PUBLICライブラリーに1対1で対応できることがわかります。
These are the methods defined by the lammps module. If you look at the file src/library.cpp you will see that they correspond one-to-one with calls you can make to the LIGGGHTS(R)-PUBLIC library from a C++ or C or Fortran program.
lmp = lammps() # create a LIGGGHTS(R)-PUBLIC object using the default liblammps.so library
lmp = lammps("g++") # create a LIGGGHTS(R)-PUBLIC object using the liblammps_g++.so library
lmp = lammps("",list) # ditto, with command-line args, e.g. list = ["-echo","screen"]
lmp = lammps("g++",list)
lmp.close() # destroy a LIGGGHTS(R)-PUBLIC object
lmp.file(file) # run an entire input script, file = "in.lj"
lmp.command(cmd) # invoke a single LIGGGHTS(R)-PUBLIC command, cmd = "run 100"
xlo = lmp.extract_global(name,type) # extract a global quantity
# name = "boxxlo", "nlocal", etc
# type = 0 = int
# 1 = double
coords = lmp.extract_atom(name,type) # extract a per-atom quantity
# name = "x", "type", etc
# type = 0 = vector of ints
# 1 = array of ints
# 2 = vector of doubles
# 3 = array of doubles
eng = lmp.extract_compute(id,style,type) # extract value(s) from a compute
v3 = lmp.extract_fix(id,style,type,i,j) # extract value(s) from a fix
# id = ID of compute or fix
# style = 0 = global data
# 1 = per-atom data
# 2 = local data
# type = 0 = scalar
# 1 = vector
# 2 = array
# i,j = indices of value in global vector or array
var = lmp.extract_variable(name,group,flag) # extract value(s) from a variable
# name = name of variable
# group = group ID (ignored for equal-style variables)
# flag = 0 = equal-style variable
# 1 = atom-style variable
natoms = lmp.get_natoms() # total # of atoms as int
data = lmp.gather_atoms(name,type,count) # return atom attribute of all atoms gathered into data, ordered by atom ID
# name = "x", "charge", "type", etc
# count = # of per-atom values, 1 or 3, etc
lmp.scatter_atoms(name,type,count,data) # scatter atom attribute of all atoms from data, ordered by atom ID
# name = "x", "charge", "type", etc
# count = # of per-atom values, 1 or 3, etc
Warning
現在、 lammps.pyからLIGGGHTS(R)-PUBLICオブジェクトを作成しても、MPIコミュニケータは引 数として使用されません。 LIGGGHTS(R)-PUBLICインスタンスが必要に応じてプロセッサのサブセットで動作するように、これを行う方法が必要ですが、Pyparから行う方法はわかっ ていません。 今のところ、すべてのプロセッサであるMPI_COMM_WORLDで動作します。 PyparのようなMPI用のPythonラッパーの1つ以上でこれを行う方法を知りたければ、私たちに知らせてください。私たちはこれらのドキュメントページを改訂しま す。
Currently, the creation of a LIGGGHTS(R)-PUBLIC object from within lammps.py does not take an MPI communicator as an argument. There should be a way to do this, so that the LIGGGHTS(R)-PUBLIC instance runs on a subset of processors if desired, but I don’t know how to do it from Pypar. So for now, it runs with MPI_COMM_WORLD, which is all the processors. If someone figures out how to do this with one or more of the Python wrappers for MPI, like Pypar, please let us know and we will amend these doc pages.
Pythonスクリプトに複数の LIGGGHTS(R)-PUBLICオブジェクトを作成し、複数のシミュレーションを調整して実行することができま す。
Note that you can create multiple LIGGGHTS(R)-PUBLIC objects in your Python script, and coordinate and run multiple simulations, e.g.
from lammps import lammps
lmp1 = lammps()
lmp2 = lammps()
lmp1.file("in.file1")
lmp2.file("in.file2")
file()およびcommand()メ
ソッドでは、入力スクリプトまたは単一のコマンドを呼び出すことができます。
extract_global()、extract_atom()、extract_compute()、
extract_fix()、およびextract_variable()メソッドは、LIGGGHTS(R)-
PUBLICの内部のデータ構造体への値またはポインタを返します。
extract_global()については、有効な名前のリストについてはsrc /
library.cppファイルを参照してください。新しい名前を簡単に追加することができます。倍精度または整数が返されます。
type引数を使用して適切なデータ型を指定する必要があります。
extract_atom()の場合、内部のLIGGGHTS(R)-PUBLICatomベースのデータへのポインタ
が返されます。これは通常のPythonのサブスクリプトを介して使用できます。有効な名前のリストについては、src
/
atom.cppファイルのextract()メソッドを参照してください。再度、新しい名前を簡単に追加することができます。倍精度または整数のベクトルへのポインタ、
または倍精度(double **)または整数(int **)の配列へポインタが返されます。
type引数を使用して適切なデータ型を指定する必要があります。
extract_compute()およびextract_fix()の場合、computeまたはfixによって計算
されたグローバル、atomごとまたはローカルのデータにアクセスできます。返されるものは、computeまたは
fixが
スカラまたはベクトルまたは配列を計算するかどうかによって異なります。スカラの場合、単一のdouble値が返されま
す。computeやfixがベクトルや配列を計算すると、内部のLIGGGHTS(R)-PUBLICデータへのポイ
ンタが返されます。これは、通常のPythonのサブスクリプトで使用できます。ただし、グローバルベクトルまたは配列
を計算するfixでは、ベクトルまたは配列から単一のdouble値が返され、I(ベクトル)またはIおよびJ(配列)
に よってインデックスが付けられます。
I、Jはゼロベースのインデックスです。必要がなければI、Jの引数を省略することができます。グローバル、atom、ローカルのデータ、スカラー、ベクタ、および配列の
データ型については、マニュアルのSection_howto
15を参照してください。計算され保存するものの説明については、個々のcomputeとfixについてのdocページを参照してください。
extract_variable()に対しては、equal-style
variableまたはatom-style variableが評価され、その結果が返されます。
equal-style
variableの場合、単一のdouble値が返され、group引数は無視されます。atom-style
variableの 場合、double型のベクト ルが返されます。atom
ごとの一つの値は、通常のPythonのサブスクリプトを使用できるものです。指定されたグループに
ないatomの値はゼロになります。
get_natoms()メソッドは、シミュレーション内のatomの総数をintとして返します。
gather_atoms()メソッドは、count順、次にatom
ID順に整列された、名前で指定されたシミュレーション内のすべてのatomのプロパティに対し
て、長さ count *
natomsのタイプで指定された、intまたはdoubleのctypesベクトルを返します。このベクトルは、通常のPythonのサブスクリプトを介して使用できま
す。atomIDが
LIGGGHTS(R)-PUBLIC内で連続して順序付けされていない場合、エラーの表示としてNoneが返されま
す。
gather_atoms( "x")のデータ構造体は、extract_atom(
"x")が返すデータ構造体とは4通りの点で異なっていることに注意してください。
(1)Gather_atoms()は、x [i]としてインデックスを付けるベクトルを返します。
extract_atom()は、x [i] [j]としてインデックスを作成する配列を返します。
(2)Gather_atoms()は、atomIDで順序つけられるのに対し、extract_atom()はそうではない。
(3)Gathert_atoms()は、シミュレーション中のすべてのatomのリストを返しますが、
extract_atoms()は、各プロセッサにローカルなatomのみを返します。
(4)最後に、gather_atoms()データ構造体はLIGGGHTS(R)-PUBLICに内部的に格納されているatom座標のコピーであるのに対し、
extract_atom()は内部データを効果的に指し示す配列を返します。つまり、extract_atom()配
列に新しい値を代入することで、LIGGGHTS(R)-PUBLIC内の値をPythonから変更することができま
す。
gather_atoms()ベクトルでこれを行うには、ベクトルの値を変更してからscatter_atoms()メソッドを呼び出す必要があります。
scatter_atoms()メソッドは、count順、次にatomID順に整列され
た、名前で指定されたシミュレーション内のすべてのatomのプロパティに対し
て、長さ count *
natomsのタイプで指定された、intまたはdoubleのベクトルをとります。これは、LIGGGHTS(R)-PUBLIC内の各atomの対応する特性を上書き
するためにデータのベクトルを使用します。これには、 LIGGGHTS(R)-PUBLICの
"map"オプションを有効にする必要があります。詳細はatom_modifyコマンドを参照してください。そうでない場合、またはatomIDが連続して順序付けされ
ていない場合、座標はリセットされません。
scatter_atoms()に渡される座標の配列は、int型またはdoubles型のctypesベクトルでなけ
ればならず、次のように割り当てられ初期化されます。
The file() and command() methods allow an input script or single commands to be invoked.
The extract_global(), extract_atom(), extract_compute(), extract_fix(), and extract_variable() methods return values or pointers to data structures internal to LIGGGHTS(R)-PUBLIC.
For extract_global() see the src/library.cpp file for the list of valid names. New names could easily be added. A double or integer is returned. You need to specify the appropriate data type via the type argument.
For extract_atom(), a pointer to internal LIGGGHTS(R)-PUBLIC atom-based data is returned, which you can use via normal Python subscripting. See the extract() method in the src/atom.cpp file for a list of valid names. Again, new names could easily be added. A pointer to a vector of doubles or integers, or a pointer to an array of doubles (double **) or integers (int **) is returned. You need to specify the appropriate data type via the type argument.
For extract_compute() and extract_fix(), the global, per-atom, or local data calulated by the compute or fix can be accessed. What is returned depends on whether the compute or fix calculates a scalar or vector or array. For a scalar, a single double value is returned. If the compute or fix calculates a vector or array, a pointer to the internal LIGGGHTS(R)-PUBLIC data is returned, which you can use via normal Python subscripting. The one exception is that for a fix that calculates a global vector or array, a single double value from the vector or array is returned, indexed by I (vector) or I and J (array). I,J are zero-based indices. The I,J arguments can be left out if not needed. See Section_howto 15 of the manual for a discussion of global, per-atom, and local data, and of scalar, vector, and array data types. See the doc pages for individual computes and fixes for a description of what they calculate and store.
For extract_variable(), an equal-style or atom-style variable is evaluated and its result returned.
For equal-style variables a single double value is returned and the group argument is ignored. For atom-style variables, a vector of doubles is returned, one value per atom, which you can use via normal Python subscripting. The values will be zero for atoms not in the specified group.
The get_natoms() method returns the total number of atoms in the simulation, as an int.
The gather_atoms() method returns a ctypes vector of ints or doubles as specified by type, of length count*natoms, for the property of all the atoms in the simulation specified by name, ordered by count and then by atom ID. The vector can be used via normal Python subscripting. If atom IDs are not consecutively ordered within LIGGGHTS(R)-PUBLIC, a None is returned as indication of an error.
Note that the data structure gather_atoms(“x”) returns is different from the data structure returned by extract_atom(“x”) in four ways. (1) Gather_atoms() returns a vector which you index as x[i]; extract_atom() returns an array which you index as x[i][j]. (2) Gather_atoms() orders the atoms by atom ID while extract_atom() does not. (3) Gathert_atoms() returns a list of all atoms in the simulation; extract_atoms() returns just the atoms local to each processor. (4) Finally, the gather_atoms() data structure is a copy of the atom coords stored internally in LIGGGHTS(R)-PUBLIC, whereas extract_atom() returns an array that effectively points directly to the internal data. This means you can change values inside LIGGGHTS(R)-PUBLIC from Python by assigning a new values to the extract_atom() array. To do this with the gather_atoms() vector, you need to change values in the vector, then invoke the scatter_atoms() method.
The scatter_atoms() method takes a vector of ints or doubles as specified by type, of length count*natoms, for the property of all the atoms in the simulation specified by name, ordered by bount and then by atom ID. It uses the vector of data to overwrite the corresponding properties for each atom inside LIGGGHTS(R)-PUBLIC. This requires LIGGGHTS(R)-PUBLIC to have its “map” option enabled; see the atom_modify command for details. If it is not, or if atom IDs are not consecutively ordered, no coordinates are reset.
The array of coordinates passed to scatter_atoms() must be a ctypes vector of ints or doubles, allocated and initialized something like this:
from ctypes import *
natoms = lmp.get_natoms()
n3 = 3*natoms
x = (n3*c_double)()
x**0** = x coord of atom with ID 1
x**1** = y coord of atom with ID 1
x**2** = z coord of atom with ID 1
x**3** = x coord of atom with ID 2
...
x**n3-1** = z coord of atom with ID natoms
lmp.scatter_coords("x",1,3,x)
代わりに、gather_atoms( "x"、1,3)が返すベクトルの値を変更することもできます。これは、double型のctypesベクトルです。
Alternatively, you can just change values in the vector returned by gather_atoms(“x”,1,3), since it is a ctypes vector of doubles.
上記のように、これらのPythonクラ
スのメソッドは、src /
library.cppとlibrary.hのLIGGGHTS(R)-PUBLICライブラリインターフェイスの関数と一対一に対応しています。
つまり、次の手順でPythonラッパーを拡張できます。
- src / library.cppとsrc / library.hに新しいインタフェース関数を追加します。
- LIGGGHTS(R)- PUBLICを共有ライブラリとして再ビルドします。
- このインタフェース関数のための ラッパーメソッドをpython / lammps.pyに追加します。
- これで、Pythonスクリプトか
ら新しいインタフェース関数を呼び出すことができます。
As noted above, these Python class methods correspond one-to-one with the functions in the LIGGGHTS(R)-PUBLIC library interface in src/library.cpp and library.h. This means you can extend the Python wrapper via the following steps:
- Add a new interface function to src/library.cpp and src/library.h.
- Rebuild LIGGGHTS(R)-PUBLIC as a shared library.
- Add a wrapper method to python/lammps.py for this interface function.
- You should now be able to invoke the new interface function from a Python script. Isn’t ctypes amazing?
10.6. Example Python scripts that use LIGGGHTS(R)-PUBLIC¶
これらは、LIGGGHTS(R)- PUBLICディストリビューションのpython / examplesディレクトリにデモとして含まれているPythonスクリプトで、PythonがLIGGGHTS(R)-PUBLICをラップするときに可能なものの種 類を示しています。 独自のスクリプトを作成する場合は、それらをLIGGGHTS(R)-PUBLICディストリビューションに含めることができます。
These are the Python scripts included as demos in the python/examples directory of the LIGGGHTS(R)-PUBLIC distribution, to illustrate the kinds of things that are possible when Python wraps LIGGGHTS(R)-PUBLIC. If you create your own scripts, send them to us and we can include them in the LIGGGHTS(R)-PUBLIC distribution.
| trivial.py | read/run a LIGGGHTS(R)-PUBLIC input script thru Python |
| demo.py | invoke various LIGGGHTS(R)-PUBLIC library interface routines |
| simple.py | mimic operation of couple/simple/simple.cpp in Python |
| gui.py | GUI go/stop/temperature-slider to control LIGGGHTS(R)-PUBLIC |
| plot.py | real-time temeperature plot with GnuPlot via Pizza.py |
| viz_tool.py | real-time viz via some viz package |
| vizplotgui_tool.py | combination of viz_tool.py and plot.py and gui.py |
viz_tool.pyおよび
vizplotgui_tool.pyコマンドの場合は、インストールした視覚化パッケージに応じて、「tool」を
「gl」または「atomeye」または「pymol」または「vmd」に置き換えます。
GLの場合、pizzaのサブディレクトリに含まれているPizza.py
GLツールを実行できるようにする必要があることに注意してください。
詳細は、Pizza.pyのドキュメントページを参照してください。
AtomEyeはバージョン3が必要で、実行可能ファイルのパスと名前を指定する行がスクリプト内にあります。
AtomEyeのWWWページはこちらまたはこちらをご覧ください:
For the viz_tool.py and vizplotgui_tool.py commands, replace “tool” with “gl” or “atomeye” or “pymol” or “vmd”, depending on what visualization package you have installed.
Note that for GL, you need to be able to run the Pizza.py GL tool, which is included in the pizza sub-directory. See the Pizza.py doc pages for more info:
Note that for AtomEye, you need version 3, and there is a line in the scripts that specifies the path and name of the executable. See the AtomEye WWW pages here or here for more details:
http://mt.seas.upenn.edu/Archive/Graphics/A
http://mt.seas.upenn.edu/Archive/Graphics/A3/A3.html
後者のリンクは、これらのPythonス
クリプトが必要とする、スクリプティング機能を持つAtomEye 3です。
PyMolの場合、PythonにPyMolのオープンソース版をビルドしてインストールする必要があるので、
PythonスクリプトからPyMolをインポートすることができます。
詳細については、PyMolのWWWページを参照してください。
The latter link is to AtomEye 3 which has the scriping capability needed by these Python scripts.
Note that for PyMol, you need to have built and installed the open-source version of PyMol in your Python, so that you can import it from a Python script. See the PyMol WWW pages here or here for more details:
http://www.pymol.org
http://sourceforge.net/scm/?type=svn&group_id=4546
後者はオープンソース版へのリンクです。
The latter link is to the open-source version.
Pythonを実行する方法については、
python / READMEファイルを参照してください。
さまざまな視覚化パッケージオプションのためのvizplotgui_tool.pyスクリプトのスクリーンショットで
す。 クリックすると大きな画像が表示されます:
See the python/README file for instructions on how to run them and the source code for individual scripts for comments about what they do.
Here are screenshots of the vizplotgui_tool.py script in action for different visualization package options. Click to see larger images: