Ase Manual
Ase Manual
Ase Manual
Release 3.9.0.3746
CAMd
CONTENTS
3
4
Overview
Installation requirements
Download
4.1 Latest stable release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.2 Latest development release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11
11
11
Installation
5.1 Installation on OS X . . . . . . . . . . . . .
5.2 Installation with package manager on Linux .
5.3 Windows . . . . . . . . . . . . . . . . . . .
5.4 Manual installation . . . . . . . . . . . . . .
5.5 Run the tests . . . . . . . . . . . . . . . . .
5.6 Video tutorial . . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
13
13
13
14
15
15
16
Tutorials
6.1 Python . . . .
6.2 ASE . . . . . .
6.3 NumPy . . . .
6.4 Further reading
6.5 Videos . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
17
17
20
48
49
54
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
55
55
67
69
69
69
73
75
82
86
101
106
106
111
114
151
157
159
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
7.18
7.19
7.20
7.21
7.22
7.23
7.24
7.25
7.26
7.27
7.28
7.29
7.30
7.31
Phonon calculations . . . . . . . . . . . .
Example . . . . . . . . . . . . . . . . . .
Thermochemistry . . . . . . . . . . . . . .
Infrared intensities . . . . . . . . . . . . .
Molecular dynamics . . . . . . . . . . . .
Density Functional Theory . . . . . . . . .
Electron transport . . . . . . . . . . . . .
The data module . . . . . . . . . . . . . .
Trajectory files . . . . . . . . . . . . . . .
Utillity functions and classes . . . . . . . .
Building neighbor-lists . . . . . . . . . . .
Setting up an OPLS force field calculation
A database for atoms . . . . . . . . . . . .
Dimer method . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
161
161
164
170
172
177
186
187
189
193
194
194
196
201
205
205
205
206
Glossary
207
10 Mailing Lists
209
10.1 Internet Relay Chat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
11 License
11.1 Human-readable version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.2 Legal version of the license . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
11.3 What happens when ASE Calculators are under another license? . . . . . . . . . . . . . . . . . .
211
211
211
211
12 ASE development
213
12.1 Development topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
12.2 Creating an encrypted password for SVN access . . . . . . . . . . . . . . . . . . . . . . . . . . 240
13 Bugs!
241
13.1 Bug report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
13.2 Known bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
14 Porting old ASE-2 code to version 3
243
14.1 The ASE2ase tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Bibliography
245
247
Index
249
ii
CONTENTS
CONTENTS
CHAPTER
ONE
Gaussian
Mopac
1.1 News
ASE version 3.8.0 released (22 October 2013).
ASE version 3.7.0 released (13 May 2013).
ASE version 3.6.0 released (24 February 2012).
Bugfix release: ASE version 3.5.1 (24 May 2011).
ASE version 3.5.0 released (13 April 2011).
ASE version 3.4.1 released (11 August 2010).
ASE version 3.4 released (23 April 2010).
ASE version 3.3 released (11 January 2010).
ASE version 3.2 released (4 September 2009).
ASE has reached revision 1000 (16 July 2009).
ASE version 3.1.0 released (27 March 2009).
Improved ase.vibrations module:
intensities (13 March 2009).
1.1. News
CHAPTER
TWO
OVERVIEW
ASE is an Atomistic Simulation Environment written in the Python programming language with the aim of setting
up, steering, and analyzing atomistic simulations. The ASE has been constructed with a number of design goals
that make it:
Easy to use:
Setting up an atomistic total energy calculation or molecular dynamics simulation with ASE is simple and
straightforward. ASE can be used via a graphical user interface, a Command line tool and the
Python language. Python scripts are easy to follow (see What is Python? for a short introduction). It is
simple for new users to get access to all of the functionality of ASE.
Flexible:
Since ASE is based on the Python scripting language it is possible to perform very complicated simulation
tasks without any code modifications. For example, a sequence of calculations may be performed with the
use of simple for-loop constructions. There exist ASE modules for performing many standard simulation
tasks.
Customizable:
The Python code in ASE is structured in modules intended for different purposes. There are
ase.calculators for calculating energies, forces and stresses, ase.md and ase.optimize
modules for controlling the motion of atoms, constraints objects and filters for performing
nudged-elastic-band calculations etc. The modularity of the object-oriented code make it simple
to contribute new functionality to ASE.
Pythonic:
It fits nicely into the rest of the Python world with use of the popular NumPy package for numerical work
(see Numeric arrays in Python for a short introduction). The use of the Python language allows ASE to be
used both interactively as well as in scripts.
Open to participation:
The CAMPOS Atomic Simulation Environment is released under the GNU Lesser General Public License
version 2.1 or any later version. See the files COPYING and COPYING.LESSER which accompany the
downloaded files, or see the license at GNUs web server at http://www.gnu.org/licenses/. Everybody is
invited to participate in using and developing the code.
Chapter 2. Overview
CHAPTER
THREE
INSTALLATION REQUIREMENTS
The following packages are required for basic ASE functionality:
1. Python 2.6 - 2.7.
2. NumPy.
It is highly recommended (but not required) to install also these:
3. matplotlib.
4. libpng.
5. pygtk.
6. SciPy.
Matplotlib and libpng are needed for writing png files, and together with pygtk are needed for ASEs
simple GUI (called ase-gui, see ase.gui). Some of these packages may already be installed on your system.
Specific information for different operating systems is provided at Installation.
10
CHAPTER
FOUR
DOWNLOAD
4.1 Latest stable release
The latest stable release can be obtained from SVN or as a tar-file.
Note: The recommended installation path is $HOME.
When using svn please set the following variable:
bash:
export ASE_TAGS=https://svn.fysik.dtu.dk/projects/ase/tags/
csh/tcsh:
setenv ASE_TAGS https://svn.fysik.dtu.dk/projects/ase/tags/
Release
3.8.1
3.8.0
3.7.1
3.7.0
3.6.0
3.5.1
3.4.1
3.4.0
3.3.1
3.2.0
3.1.0
3.0.0
Date
Nov 22 2013
Oct 22 2013
May 16 2013
May 13 2013
Feb 24 2012
May 24 2011
Aug 11 2010
Apr 23 2010
Jan 20 2010
Sep 4 2009
Mar 27 2009
Nov 13 2008
Retrieve as tar-file
python-ase-3.8.1.3440.tar.gz
python-ase-3.8.0.3420.tar.gz
python-ase-3.7.1.3184.tar.gz
python-ase-3.7.0.3168.tar.gz
python-ase-3.6.0.2515.tar.gz
python-ase-3.5.1.2175.tar.gz
python-ase-3.4.1.1765.tar.gz
python-ase-3.4.0.1574.tar.gz
python-ase-3.3.1.1390.tar.gz
python-ase-3.2.0.1121.tar.gz
python-ase-3.1.0.846.tar.gz
python-ase-3.0.0.657.tar.gz
11
12
Chapter 4. Download
CHAPTER
FIVE
INSTALLATION
After performing the installation do not forget to Run the tests!
5.1 Installation on OS X
For installation with http://mxcl.github.com/homebrew/ please follow instructions at Homebrew.
openSUSE 13.1:
zypper ar -f http://download.opensuse.org/repositories/home:/dtufys/openSUSE_13.1/home:dtufys
yast -i python-ase
yast -i python-matplotlib # optionally
Debian 7.0:
sudo
wget
sudo
sudo
sudo
Ubuntu 14.04:
sudo
wget
sudo
sudo
sudo
13
Note: If you prefer to install manually, proceed to Manual installation, or alternatively, manually unpack the
RPMS, e.g.:
#
$
#
$
#
$
#
$
#
$
#
$
#
$
This method works for all the RPM packages from the repository (like gpaw), however not for the external,
distribution provided packages, which may require manually creating the environment scripts.
5.3 Windows
Note: ASE is not yet fully functional on Windows! https://trac.fysik.dtu.dk/projects/ase/ticket/62
On Windows the following packages need to installed. On the command prompt:
Note:
installation assumes the python TARGETDIR C:\Python27, leave also the default C:\Program
Files\pythonxy.
pythonxy. Download the exe installer and install with:
Python(x,y)-2.7.2.2.exe /Log="%TMP%\pythonxy_install.log" /S
Note: Open Task Manager and control when the process in finished.
pygtk_win32. Download the msi pygtk-all-in-one installer. Specify the correct TARGETDIR and install:
Note: If performing clicking-installation make sure that the default python Windows TARGETDIR is selected.
Download the python-ase-win32.msi installer and install with:
14
Chapter 5. Installation
Note: You can build the msi ASE package on Windows with:
python setup.py bdist_msi
if retrieved as tar-file:
$ cd $HOME
$ tar zxf python-ase-3.8.0.3420.tar.gz
$ ln -s python-ase-3.8.0.3420 ase
It is sufficient to put the directory $HOME/ase in your PYTHONPATH environment variable, and the directory
$HOME/ase/tools in your PATH environment variable. Do this permanently in your ~/.bashrc file:
export PYTHONPATH=$HOME/ase:$PYTHONPATH
export PATH=$HOME/ase/tools:$PATH
This way, the ASE modules are found on the python path without any explicit configuration, though you still need
to ensure that $HOME/.local/bin (or on Windows, %APPDATA%/Python/Scripts) is on your PATH.
Optional, NOT recommended way of installing ASE system-wide is:
$ cd ase
$ sudo python setup.py install
15
Note: The last test ase/test/COCu111.py requires closing the graphics windows to terminate the whole test-suite.
Note: If matplotlib or pygtk is not installed, this test will fail - avoid this with display=False.
If any of the tests fail, then please send us testase.log (see Bugs!).
16
Chapter 5. Installation
CHAPTER
SIX
TUTORIALS
6.1 Python
If you are not familiar with Python please read What is Python?.
You can also put the print hello line in a file (hello.py) and execute it as a Python script:
$ python hello.py
hello
Or like this:
$ python -i hello.py
hello
>>> print hi!
hi!
Finally, you can put #!/usr/bin/env python in the first line of the hello.py file, make it executable
(chmod +x hello.py) and execute it like any other executable.
Tip: For interactive Python sessions, it is very convenient to have a personal .pythonrc file:
17
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")
from ase import *
and point the PYTHONSTARTUP environment variable at it (see here for details).
Types
Python has the following predefined types:
type
bool
int
float
complex
str
tuple
list
dict
file
description
boolean
integer
floating point number
complex number
string
tuple
list
dictionary
file
example
False
117
1.78
0.5 + 2.0j
abc
(1, hmm, 2.0)
[1, hmm, 2.0]
{a: 7.0, 23: True}
open(stuff.dat, w)
In this example all keys are strings and all values are integers. Types can be freely mixed in the same dictionary;
any type can be used as a value and most types can be used as keys (mutable objects cannot be keys).
A list object is an ordered collection of arbitrary objects:
>>> l = [1, (gg, 7), hmm]
>>> l[1]
(gg, 7)
>>>
>>> l
[1, (gg, 7), hmm, 1.2]
>>> l[-2]
hmm
Indexing a list with negative numbers counts from the end of the list, so element -2 is the second last.
A tuple behaves like a list - except that it cant be modified in place. Objects of types list and dict are
mutable - all the other types listed in the table are immutable, which means that once an object has been created,
it can not change. Tuples can therefore be used as dictionary keys, lists cannot.
Note: List and dictionary objects can change. Variables in Python are references to objects - think of the =
operator as a naming operator, not as an assignment operator. This is demonstrated here:
>>>
>>>
>>>
>>>
18
a = [q, w]
b = a
a.append(e)
a
Chapter 6. Tutorials
[q, w, e]
>>> b
[q, w, e]
The line b = a gives a new name to the array, and both names now refer to the same list.
However, often a new object is created and named at the same time, in this example the number 42 is not modified,
a new number 47 is created and given the name d. And later, e is a name for the number 47, but then a new number
48 is created, and e now refers to that number:
>>> c = 42
>>> d = c + 5
>>> c
42
>>> d
47
>>> e = d
>>> e += 1
>>> (d, e)
(47, 48)
Note: Another very important type is the ndarray type described here: Numeric arrays in Python. It is an array
type for efficient numerics, and is heavily used in ASE.
Loops
A loop in Python can be done like this:
>>> things = [a, 7]
>>> for x in things:
...
print x
...
a
7
The things object could be any sequence. Strings, tuples, lists, dictionaries, ndarrays and files are sequences.
Try looping over some of these types.
Often you need to loop over a range of numbers:
>>> for i in range(5):
...
print i, i*i
...
0 0
1 1
2 4
3 9
4 16
6.1. Python
19
Here f is a function, x is an argument, m and n are keywords with default values 2 and 1 and y is a variable.
A class is defined like this:
>>> class A:
...
def __init__(self, b):
...
self.c = b
...
def m(self, x):
...
return self.c * x
...
def get_c(self)
...
return self.c
You can think of a class as a template for creating user defined objects. The __init__() function is called a
constructor, it is being called when objects of this type are being created.
In the class A __init__ is a constructor, c is an attribute and m and get_c are methods.
>>>
>>>
7
>>>
7
>>>
21
a = A(7)
a.c
a.get_c()
a.m(3)
or:
import stuff
print stuff.f(1, 2)
print stuff.C(1).m(2)
or:
import stuff as st
print st.f(1, 2)
print st.C(1).m(2)
6.2 ASE
Most of the tutorials will use the EMT potential, but any other Calculator could be plugged in instead.
20
Chapter 6. Tutorials
h = 1.85
d = 1.10
slab = fcc111(Cu, size=(4,4,2), vacuum=10.0)
slab.set_calculator(EMT())
e_slab = slab.get_potential_energy()
molecule = Atoms(2N, positions=[(0., 0., 0.), (0., 0., d)])
molecule.set_calculator(EMT())
e_N2 = molecule.get_potential_energy()
add_adsorbate(slab, molecule, h, ontop)
constraint = FixAtoms(mask=[a.symbol != N for a in slab])
slab.set_constraint(constraint)
dyn = QuasiNewton(slab, trajectory=N2Cu.traj)
dyn.run(fmax=0.05)
print Adsorption energy:, e_slab + e_N2 - slab.get_potential_energy()
#view(slab)
Assuming you have ASE setup correctly (Installation requirements) run the script:
python N2Cu.py
6.2. ASE
21
Atoms
The Atoms object is a collection of atoms. Here is how to define a N2 molecule by directly specifying the position
of two nitrogen atoms:
from ase import Atoms
d = 1.10
molecule = Atoms(2N, positions=[(0., 0., 0.), (0., 0., d)])
You can also build crystals using, for example, the lattice module which returns Atoms objects corresponding to
common crystal structures. Let us make a Cu (111) surface:
from ase.lattice.surface import fcc111
slab = fcc111(Cu, size=(4,4,2), vacuum=10.0)
Calculators
Many ase.calculators can be used with ASE, including emt, Asap, Dacapo, GPAW, Abinit, Vasp. See the
ASE home page for the full list.
In this overview we use the effective medium theory (EMT) calculator, as it is very fast and hence useful for
getting started.
We can attach a calculator to the previously created Atoms objects:
from ase.calculators.emt import EMT
slab.set_calculator(EMT())
molecule.set_calculator(EMT())
and use it to calculate the total energies for the systems by using the get_potential_energy() method
from the Atoms class:
e_slab = slab.get_potential_energy()
e_N2 = molecule.get_potential_energy()
Structure relaxation
Lets use the QuasiNewton minimizer to optimize the structure of the N2 molecule adsorbed on the Cu surface.
First add the adsorbate to the Cu slab, for example in the on-top position:
h = 1.85
add_adsorbate(slab, molecule, h, ontop)
In order to speed up the relaxation, let us keep the Cu atoms fixed in the slab by using FixAtoms from the
constraints module. Only the N2 molecule is then allowed to relax to the equilibrium structure:
from ase.constraints import FixAtoms
constraint = FixAtoms(mask=[a.symbol != N for a in slab])
slab.set_constraint(constraint)
Now attach the QuasiNewton minimizer to the system and save the trajectory file. Run the minimizer with the
convergence criteria that the force on all atoms should be less than some fmax:
from ase.optimize import QuasiNewton
dyn = QuasiNewton(slab, trajectory=N2Cu.traj)
dyn.run(fmax=0.05)
Note: The general documentation on structure optimizations contains information about different algorithms,
saving the state of an optimizer and other functionality which should be considered when performing expensive
relaxations.
22
Chapter 6. Tutorials
Input-output
Writing the atomic positions to a file is done with the write() function:
from ase.io import write
write(slab.xyz, slab)
description
Simple xyz-format
Gaussian cube file
Protein data bank file
ASEs own trajectory format
Python script
If the file contains several configurations, the default behavior of the write() function is to return the last
configuration. However, we can load a specific configuration by doing:
read(slab.traj)
read(slab.traj, -1)
read(slab.traj, 0)
# last configuration
# same as above
# first configuration
Visualization
The simplest way to visualize the atoms is the view() function:
from ase.visualize import view
view(slab)
This will pop up a ase.gui window. Alternative viewers can be used by specifying the optional keyword
viewer=... - use one of ase.gui, gopenmol, vmd, or rasmol. (Note that these alternative viewers are not
a part of ASE and will need to be installed by the user separately.) The VMD viewer can take an optional data
argument to show 3D data:
view(slab, viewer=VMD, data=array)
Molecular dynamics
Let us look at the nitrogen molecule as an example of molecular dynamics with the VelocityVerlet algorithm. We first create the VelocityVerlet object giving it the molecule and the time step for the integration
of Newtons law. We then perform the dynamics by calling its run() method and giving it the number of steps
to take:
from ase.md.verlet import VelocityVerlet
from ase import units
dyn = VelocityVerlet(molecule, dt=1.0 * units.fs)
for i in range(10):
pot = molecule.get_potential_energy()
kin = molecule.get_kinetic_energy()
print %2d: %.5f eV, %.5f eV, %.5f eV % (i, pot + kin, pot, kin)
dyn.run(steps=20)
6.2. ASE
23
Now, setup a p(2x2) cell in a hexagonal surface. Here, a is the fcc lattice constant, the cell is 10 layers high:
>>> from numpy import sqrt
>>> a = 3.55
>>> cell = [(2/sqrt(2.)*a, 0, 0),
...
(1/sqrt(2.)*a, sqrt(3./2.)*a, 0),
...
(0, 0, 10*sqrt(3.)/3.*a)]
>>> cell
[(5.0204581464244864, 0, 0),
(2.5102290732122432, 4.3478442934401409, 0),
(0, 0, 20.495934556231713)]
>>> atoms.set_cell(cell, scale_atoms=True)
24
Chapter 6. Tutorials
The argument scale_atoms=True indicates that the atomic positions should be scaled with the unit cell. The
default is scale_atoms=False indicating that the cartesian coordinates remain the same when the cell is changed.
>>> atoms.get_positions()
array([[ 0.
, 0.
,
[ 2.51022907, 0.
,
[ 1.25511454, 2.17392215,
[ 3.76534361, 2.17392215,
0.
0.
0.
0.
],
],
],
]])
Within the viewer (called ase-gui) it is possible to repeat the unit cell in all three directions (using the Repeat
View window).
We now add an adatom. Since the supercell is now declared as the unit cell for our atoms we can either add the
atom using its cartesian coordinates in Angstrom or rescale the unit cell and use scaled coordinates. We try the
latter:
>>>
>>>
>>>
>>>
>>>
>>>
6.2. ASE
25
>>> view(atoms)
First, an Atoms object containing one nitrogen is created and a fast EMT calculator is attached to it simply as an
argument. The total energy for the isolated atom is then calculated and stored in the e_atom variable.
The molecule object is defined, holding the nitrogen molecule at the experimental bond length. The EMT
calculator is then attached to the molecule and the total energy is extracted into the e_molecule variable.
Running the script will produce the output:
Nitrogen atom energy: 4.97 eV
Nitrogen molecule energy: 0.04 eV
Atomization energy: 9.90 eV
26
Chapter 6. Tutorials
Finally, we do the 9 calculations (three values for a and three for c):
from ase.lattice import bulk
from ase.calculators.emt import EMT
eps = 0.01
for a in a0 * np.linspace(1 - eps, 1 + eps, 3):
for c in c0 * np.linspace(1 - eps, 1 + eps, 3):
ni = bulk(Ni, hcp, a=a, c=c)
ni.set_calculator(EMT())
ni.get_potential_energy()
traj.write(ni)
Analysis
Now, we need to extract the data from the trajectory. Try this:
>>> from ase.lattice import bulk
>>> ni = bulk(Ni, hcp, a=2.5, c=4.0)
>>> ni.cell
array([[ 2.5
, 0.
, 0.
[-1.25
, 2.16506351, 0.
[ 0.
, 0.
, 4.
],
],
]])
Results:
a
2.466
c
4.023
6.2. ASE
27
If you want the optimization path in a trajectory, add these lines before calling the run() method:
traj = PickleTrajectory(path.traj, w, ni)
opt.attach(traj)
This will write a trajectory file containing five configurations of FCC silver for five different lattice constans. Now,
analyse the result with the EquationOfState class and this script:
from ase.io import read
from ase.units import kJ
from ase.utils.eos import EquationOfState
configs = read(Ag.traj@0:5) # read 5 configurations
# Extract volumes and energies:
volumes = [ag.get_volume() for ag in configs]
energies = [ag.get_potential_energy() for ag in configs]
eos = EquationOfState(volumes, energies)
v0, e0, B = eos.fit()
print B / kJ * 1.0e24, GPa
eos.plot(Ag-eos.png)
28
Chapter 6. Tutorials
6.2. ASE
29
Aluminium (fcc)
The spacegroup argument can also be entered with its Hermann-Mauguin symbol, e.g. spacegroup=225 is equivalent to spacegroup=F m -3 m.
Iron (bcc)
Magnesium (hcp)
Diamond
30
Chapter 6. Tutorials
Sodium chloride
Rutile
6.2. ASE
31
CoSb3 skutterudite
Skutterudites are quite interesting structures with 32 atoms in the unit cell.
from ase.lattice.spacegroup import crystal
a = 9.04
skutterudite = crystal((Co, Sb),
basis=[(0.25,0.25,0.25), (0.0, 0.335, 0.158)],
spacegroup=204,
cellpar=[a, a, a, 90, 90, 90])
#ase.view(skutterudite)
Often this structure is visualised with the Cobalt atoms on the corners. This can easily be accomplished with
ASE using ase.utils.geometry.cut(). Below is the origo argument used to put the Cobalt atom on the
corners and extend to include all corner and edge atoms, even those belonging to neighbouring unit cells.
32
Chapter 6. Tutorials
import numpy as np
import ase.utils.geometry as geometry
import ase.io as io
# Create a new atoms instance with Co at origo including all atoms on the
# surface of the unit cell
cosb3 = geometry.cut(skutterudite, origo=(0.25, 0.25, 0.25), extend=1.01)
# Define the atomic bonds to show
bondatoms = []
symbols = cosb3.get_chemical_symbols()
for i in xrange(len(cosb3)):
for j in xrange(i):
if (symbols[i] == symbols[j] == Co and
cosb3.get_distance(i, j) < 4.53):
bondatoms.append((i, j))
elif (symbols[i] == symbols[j] == Sb and
cosb3.get_distance(i, j) < 2.99):
bondatoms.append((i, j))
# Create nice-looking image using povray
io.write(spacegroup-cosb3.pov, cosb3,
transparent=False,
display=False,
run_povray=True,
camera_type=perspective,
canvas_width=320,
radii=0.4,
rotation=90y,
bondlinewidth=0.07,
bondatoms=bondatoms,
)
6.2. ASE
33
print
print
print
print
print
print
print
print
or simply
print sg
Or, if you want to figure out what sites in the unit cell are equivalent to (0, 0, 0.5), simply do
sites,kinds = sg.equivalent_sites([(0, 0, 0.5)])
where sites will be an array containing the scaled positions of the four symmetry-equivalent sites.
Initial state.
Add the molecule:
= a / 2.
= a * 3. ** .5 / 6.
= 1.8
= 1.10 # N2 bond length
34
Chapter 6. Tutorials
initial = read(N2.traj)
final = read(2N.traj)
configs = [initial.copy() for i in range(8)] + [final]
constraint = FixAtoms(mask=[atom.symbol != N for atom in initial])
for config in configs:
config.set_calculator(EMT())
config.set_constraint(constraint)
band = NEB(configs)
band.interpolate()
# Create a quickmin object:
relax = QuasiNewton(band)
relax.run(steps=20)
e0 = initial.get_potential_energy()
for config in configs:
d = config[-2].position - config[-1].position
print np.linalg.norm(d), config.get_potential_energy() - e0
6.2. ASE
35
from
from
from
from
Note: Notice how the tags are used to select the constrained atoms
Now, do the NEB calculation:
from
from
from
from
from
initial = read(initial.traj)
final = read(final.traj)
36
Chapter 6. Tutorials
Note: For this reaction, the reaction coordinate is very simple: The x-coordinate of the Au atom. In such cases,
the NEB method is overkill, and a simple constraint method should be used like in this tutorial: Diffusion of gold
atom on Al(100) surface (constraint).
See Also:
ase.neb
ase.constraints
Diffusion of gold atom on Al(100) surface (constraint)
fcc100()
Parallelizing over images
Instead of having one process do the calculations for all three internal images in turn, it will be faster to have three
processes do one image each. This can be done like this:
from
from
from
from
from
from
6.2. ASE
37
38
Chapter 6. Tutorials
qn.run(fmax=0.05)
slab[-1].x += slab.get_cell()[0, 0] / 8
The result can be analysed with the command ase-gui mep?.traj -n -1 (choose Tools NEB). The barrier is
found to be 0.35 eV - exactly as in the NEB tutorial.
Here is a side-view of the path (unit cell repeated twice):
See Also:
ase.neb
ase.constraints
Diffusion of gold atom on Al(100) surface (NEB)
fcc100()
6.2. ASE
39
size = 3
# Set up a crystal
atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], symbol="Cu",
size=(size,size,size), pbc=True)
# Describe the interatomic interactions with the Effective Medium Theory
atoms.set_calculator(EMT())
# Set the momenta corresponding to T=300K
MaxwellBoltzmannDistribution(atoms, 300*units.kB)
# We want to run MD with constant energy using the VelocityVerlet algorithm.
dyn = VelocityVerlet(atoms, 5*units.fs) # 5 fs time step.
#Function to print the potential, kinetic and total energy
def printenergy(a):
epot = a.get_potential_energy() / len(a)
ekin = a.get_kinetic_energy() / len(a)
print ("Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK)
(epot, ekin, ekin/(1.5*units.kB), epot+ekin))
Etot = %.3feV" %
Note how the total energy is conserved, but the kinetic energy quickly drops to half the expected value. Why?
Instead of printing within a loop, it is possible to use an observer to observe the atoms and do the printing (or
more sophisticated analysis).
"Demonstrates molecular dynamics with constant energy."
from
from
from
from
from
40
Chapter 6. Tutorials
Constant temperature MD
Often, you want to control the temperature of an MD simulation. This can be done with the Langevin dynamics
module. In the previous examples, replace the line dyn = VelocityVerlet(...) with:
dyn = Langevin(atoms, 5*units.fs, T*units.kB, 0.002)
where T is the desired temperature in Kelvin. You also need to import Langevin, see the class below.
The Langevin dynamics will then slowly adjust the total energy of the system so the temperature approaches the
desired one.
As a slightly less boring example, let us use this to melt a chunk of copper by starting the simulation without any
momentum of the atoms (no kinetic energy), and with a desired temperature above the melting point. We will also
save information about the atoms in a trajectory file called moldyn3.traj.
"Demonstrates molecular dynamics with constant energy."
from
from
from
from
from
T = 1500 # Kelvin
# Set up a crystal
atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], symbol="Cu",
size=(size,size,size), pbc=False)
# Describe the interatomic interactions with the Effective Medium Theory
atoms.set_calculator(EMT())
# We want to run MD with constant energy using the Langevin algorithm
# with a time step of 5 fs, the temperature T and the friction
# coefficient to 0.02 atomic units.
dyn = Langevin(atoms, 5*units.fs, T*units.kB, 0.002)
#Function to print the potential, kinetic and total energy.
def printenergy(a=atoms):
#store a reference to atoms in the definition.
epot = a.get_potential_energy() / len(a)
ekin = a.get_kinetic_energy() / len(a)
print ("Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) Etot = %.3feV" %
(epot, ekin, ekin/(1.5*units.kB), epot+ekin))
dyn.attach(printenergy, interval=50)
#We also want to save the positions of all atoms after every 100th time step.
6.2. ASE
41
After running the simulation, you can study the result with the command
ase-gui moldyn3.traj
Try plotting the kinetic energy. You will not see a well-defined melting point due to finite size effects (including
surface melting), but you will probably see an almost flat region where the inside of the system melts. The
outermost layers melt at a lower temperature.
Note: The Langevin dynamics will by default keep the position and momentum of the center of mass unperturbed.
This is another improvement over just setting momenta corresponding to a temperature, as we did before.
Isolated particle MD
When simulating isolated particles with MD, it is sometimes preferable to set random momenta corresponding to
a specific temperature and let the system evolve freely. With a relatively high temperature, the is however a risk
that the collection of atoms will drift out of the simulation box because the randomized momenta gave the center
of mass a small but non-zero velocity too.
Let us see what happens when we propagate a nanoparticle for a long time:
"Demonstrates molecular dynamics for isolated particles."
ase.calculators.emt import EMT
ase.cluster.cubic import FaceCenteredCubic
ase.optimize import QuasiNewton
ase.md.velocitydistribution import MaxwellBoltzmannDistribution, \
Stationary, ZeroRotation
from ase.md.verlet import VelocityVerlet
from ase import units
from
from
from
from
42
Chapter 6. Tutorials
After running the simulation, use ase-gui to compare the results with how it looks if you comment out either the
line that says Stationary (atoms), ZeroRotation (atoms) or both.
ase-gui moldyn4.traj
Try playing the movie with a high frame rate and set frame skipping to a low number. Can you spot the subtle
difference?
6.2. ASE
43
44
Chapter 6. Tutorials
6.2. ASE
45
This script will produce 10 molecular dynamics and 11 optimization files. It will also produce a file called
minima.traj which contains all of the accepted minima. You can look at the progress of the algorithm in the
file hop.log in combination with the trajectory files.
Alternatively, there is a utility to allow you to visualize the progress of the algorithm. You can run this from within
the same directory as your algorithm as:
from ase.optimize.minimahopping import MHPlot
mhplot = MHPlot()
mhplot.save_figure(summary.png)
This will make a summary figure, which should look something like the one below. As the search is inherently
random, yours will look different than this (and this will look different each time the documentation is rebuilt). In
this figure, you will see on the Epot axes the energy levels of the conformers found. The flat bars represent the
energy at the end of each local optimization step. The checkmark indicates the local minimum was accepted; red
arrows indicate it was rejected for the three possible reasons. The black path between steps is the potential energy
during the molecular dynamics (MD) portion of the step; the dashed line is the local optimization on termination
of the MD step. Note the y axis is broken to allow different energy scales between the local minima and the space
explored in the MD simulations. The T and Ediff plots show the values of the self-adjusting parameters as the
algorithm progresses.
46
Chapter 6. Tutorials
You can see examples of the implementation of this for real adsorbates as well as find suitable parameters for the
Hookean constraints:
Andrew Peterson
Global optimization of adsorbatesurface structures while preserving molecular identity
Top. Catal., Vol. 57, 40 (2014)
6.2. ASE
47
6.3 NumPy
If your ASE scripts make extensive use of matrices you may want to familiarize yourself with Numeric arrays in
Python.
import numpy as np
# Make a random hermitian matrix, H
H = np.random.rand(6, 6) + 1.j * np.random.rand(6, 6)
H = H + H.T.conj()
# Determine eigenvalues and rotation matrix
eps, U = np.linalg.eigh(H)
# Sort eigenvalues
sorted_indices = eps.real.argsort()
eps = eps[sorted_indices]
U = U[:, sorted_indices]
# Make print of numpy arrays less messy:
np.set_printoptions(precision=3, suppress=True)
# Check that U diagonalizes H:
print np.dot(np.dot(U.T.conj(), H), U) - np.diag(eps)
print np.allclose(np.dot(np.dot(U.T.conj(), H), U), np.diag(eps))
# The eigenvectors of H are the *coloumns* of U:
np.allclose(np.dot(H, U[:, 3]), eps[3] * U[:, 3])
np.allclose(np.dot(H, U), eps * U)
Chapter 6. Tutorials
The exact same rules apply for adding and subtracting 1D arrays to / from 2D arrays.
6.4.1 Exercises
Note: CAMd summer school participants should read this page before doing the SIESTA exercises.
Exercise 2 contains a script which takes somewhat long time. For this reason you may want to submit the script
to Niflheim in advance, before analyzing the results in Exercise 1.
Siesta 1: Basis Sets
This exercise is intended to illustrate the definition of basis sets with different numbers of orbitals and localization
radii in SIESTA. It is based on the H2 O molecule. You will first use standard basis sets generated by SIESTA,
and then a basis set specifically optimized for the H2 O molecule. The tips at the end of this page will help you in
analyzing the results of the calculations.
We are going to use the ASE interface to the siesta calculator, for the official SIESTA documentation see here.
Part 1: Standard basis sets
In the following script you will relax the structure of the H2 O molecule to find its equilibrium structure.
49
import time
import numpy as np
from ase import Atoms, units
from ase.optimize import QuasiNewton
from ase.calculators.siesta import Siesta
# Set up a H2O molecule by specifying atomic positions
h2o = Atoms(symbols=H2O,
positions=[( 0.776070, 0.590459, 0.00000),
(-0.776070, 0.590459, 0.00000),
(0.000000, -0.007702, -0.000001)],
pbc=(1,1,1))
# Center the molecule in the cell with some vacuum around
h2o.center(vacuum=6.0)
# Select some energy-shifts for the basis orbitals
e_shifts = [0.01,0.1,0.2,0.3,0.4,0.5]
# Run the relaxation for each energy shift, and print out the
# corresponding total energy, bond length and angle
Run the script using three different basis sets: single-Z (SZ), double-Z (DZ) and double-Z plus polarization (DZP).
Run it in different directories for each basis set, since the run will produce a large amount of output files. The
bases are defined in the script through these three lines:
calc.set_fdf(PAO.BasisSize,SZ)
calc.set_fdf(PAO.EnergyShift,e_s * eV)
calc.set_fdf(PAO.SplitNorm,0.15)
For each of the basis sets the script will run the relaxation for different EnergyShift parameters. Look at the
results as a function of basis size and localization radius (or energy shift).
50
Chapter 6. Tutorials
Note that you will get a trajectory file .traj for each energy shift in the loop.
Try to get plots like the following, obtained for a SZ basis:
51
3. What do you consider a reasonable basis for the molecule, if you need an accuracy in the geometry of about
1%?
4. In order to assess convergence with respect to basis set size, should you compare the results with the experimental ones, or with those of a converged basis set calculation?
Part 2: Optimized basis sets
You will now do the same calculations as in Part 1, but now using a basis set specifically optimized for the H2 O
molecule. Use the following optimized block instead of the basis-definition lines in Part1:
calc.set_fdf(PAO.Basis,
["""H
2
0.22
n=1
0
2
E
2.07
4.971
1.771
1.000
1.000
n=2
1
1
E
0.89
4.988
1.000
O
3
-0.20
n=2
0
2
E
0.00
5.000
2.581
1.000
1.000
n=2
1
2
E
0.00
6.500
2.487
1.000
1.000
n=3
2
1
E
104.31
3.923
1.000"""])
0.00
0.01
1.31
5.28
0.00
Tip 1: You can see the radii of the orbitals in the output file, just after the line reading:
printput: Basis input ----------------------------------------------
Tip 2: You can look at the shape of the orbitals by plotting the contents of the ORB* files generated by SIESTA.
Tip 3: You will find a lot of information on the run in the .txt output file
Tip 4: In ag you can select View VMD to start the VMD viewer. There you can change the atom representation
to what you feel is more convenient. Do that by selecting Graphics Representations in the top bar.
Tip 5: SIESTA will store basis functions in ORB.* files. These files can be plotted using the xmgrace command
on the GBAR like this:
$ xmgrace ORB.S1.1.O ORB.S2.1.O
52
Chapter 6. Tutorials
from
from
from
from
from
# Read in the geometry from a xyz file, set the cell, boundary conditions and center
atoms = read(geom.xyz)
atoms.set_cell([7.66348,7.66348,7.66348*2])
atoms.set_pbc((1,1,1))
atoms.center()
# Set initial velocities for hydrogen atoms along the z-direction
p = atoms.get_momenta()
p[0,2]= -1.5
p[1,2]= -1.5
atoms.set_momenta(p)
# Keep some atoms fixed during the simulation
atoms.set_constraint(FixAtoms(indices=range(18,38)))
# Set the calculator and attach it to the system
calc = Siesta(si001+h2,basis=SZ,xc=PBE,meshcutoff=50*units.Ry)
calc.set_fdf(PAO.EnergyShift, 0.25 * units.eV)
calc.set_fdf(PAO.SplitNorm, 0.15)
atoms.set_calculator(calc)
# Set the VelocityVerlet algorithm and run it
dyn = VelocityVerlet(atoms,dt=1.0 * units.fs,trajectory=si001+h2.traj)
dyn.run(steps=100)
Note that both H atoms are given an initial velocity towards the surface through the lines:
p = atoms.get_momenta()
p[0,2]= -1.5
p[1,2]= -1.5
atoms.set_momenta(p)
Run the program, and check the results. You can visualize the dynamics using the trajectory file with the help of
the ASE gui. For example you can visualize the behaviour of the potential and total energies during the dynamics
by doing:
$ ase-gui -b si001+h2.traj -g i,e,e+ekin
The -b option turns on plotting of bonds between the atoms. Check that the total energy is a conserved quantity
in this microcanonical simulation.
You can also use VMD to visualize the trajectory. To do this, you need a .xyz file that you can write using
ase-gui:
$ ase-gui si001+h2.traj -o si.xyz -r 2,2,1
and set Graphics/Representations from the main menu in order to get a nice picture.
You can also try to repeat the simulation with a different dynamics. For instance you can model a canonical
ensemble with the Langevin dynamics, which couples the system to a heat bath:
dyn = Langevin(atoms, 1 * fs, kB * 300, 0.002, trajectory=traj)
53
6.5 Videos
The following video tutorials are available:
Overview and installation of ASE, by Anthony Goodrow (duration: ~5min 30sec; size: 26 MB) - en:
54
Chapter 6. Tutorials
CHAPTER
SEVEN
atoms
dft
io
optimize
structure
units
vtk
calculators
data
lattice
parallel
surface
utils
constraints
gui
md
phonons
transport
vibrations
See Also:
Tutorials
Automatically generated documentation (API)
Source code
List of all modules:
Here, the first argument specifies the type of the atoms and we used the positions keywords to specify their
positions. Other possible keywords are: numbers, tags, momenta, masses, magmoms and charges.
Here is how you could make an infinite gold wire with a bond length of 2.9 :
from ase import Atoms
d = 2.9
L = 10.0
wire = Atoms(Au,
positions=[(0, L / 2, L / 2)],
cell=(d, L, L),
pbc=(1, 0, 0))
55
Here is the full list of the get/set methods operating on all the atoms at once. The get methods return an array
of quantities, one for each atom; the set methods take similar arrays. E.g. get_positions() return N * 3
numbers, get_atomic_numbers() return N integers.
These methods return copies of the internal arrays, it is thus safe to modify the returned arrays.
56
get_atomic_numbers()
get_charges()
get_chemical_symbols()
get_initial_magnetic_moments()
get_magnetic_moments()
get_masses()
get_momenta()
get_forces()
get_positions()
get_potential_energies()
get_scaled_positions()
get_stresses()
get_tags()
get_velocities()
set_atomic_numbers()
set_charges()
set_chemical_symbols()
set_initial_magnetic_moments()
set_masses()
set_momenta()
set_positions()
set_scaled_positions()
set_tags()
set_velocities()
There are also a number of get/set methods that operate on quantities common to all the atoms or defined for the
collection of atoms:
get_calculator()
get_cell()
get_center_of_mass()
get_kinetic_energy()
get_magnetic_moment()
get_number_of_atoms()
get_pbc()
get_potential_energy()
get_stress()
get_total_energy()
get_volume()
set_calculator()
set_cell()
set_pbc()
0.],
0.],
1.]])
The cell can be defined or changed using the set_cell() method. Changing the unit cell does per default not
move the atoms:
>>> a.set_cell(2 * identity(3))
>>> a.get_cell()
array([[ 2., 0., 0.],
[ 0., 2., 0.],
[ 0., 0., 2.]])
>>> a.get_positions()
array([[ 2., 0., 0.],
[ 1., 1., 0.],
[ 2., 2., 0.]])
However if we set scale_atoms=True the atomic positions are scaled with the unit cell:
>>> a.set_cell(identity(3), scale_atoms=True)
>>> a.get_positions()
array([[ 1. , 0. , 0. ],
[ 0.5, 0.5, 0. ],
[ 1. , 1. , 0. ]])
57
The set_pbc() method specifies whether periodic boundary conditions are to be used in the directions of the
three vectors of the unit cell. A slab calculation with periodic boundary conditions in x and y directions and free
boundary conditions in the z direction is obtained through
>>> a.set_pbc((True, True, False))
After the calculator has been appropriately setup the energy of the atoms can be obtained through
>>> a.get_potential_energy()
The term potential energy here means for example the total energy of a DFT calculation, which includes both
kinetic, electrostatic, and exchange-correlation energy for the electrons. The reason it is called potential energy is
that the atoms might also have a kinetic energy (from the moving nuclei) and that is obtained with
>>> a.get_kinetic_energy()
In case of a DFT calculator, it is up to the user to check exactly what the get_potential_energy() method
returns. For example it may be the result of a calculation with a finite temperature smearing of the occupation
numbers extrapolated to zero temperature. More about this can be found for the different ase.calculators.
The following methods can only be called if a calculator is present:
58
get_potential_energy()
get_potential_energies()
get_forces()
get_stress()
get_stresses()
get_total_energy()
get_magnetic_moments()
get_magnetic_moment()
Not all of these methods are supported by all calculators.
7.1.5 List-methods
method
+
+=, extend()
append()
*
*=, repeat()
len
del
pop()
example
wire2 = wire + co
wire += co
wire.extend(co)
wire.append(Atom(H))
wire3 = wire * (3, 1, 1)
wire *= (3, 1, 1)
wire.repeat((3, 1, 1))
len(co)
del wire3[0]
del wire3[[1,3]]
oxygen = wire2.pop()
Note that the del method can be used with the more powerful numpy-style indexing, as in the second example
above. This can be combined with python list comprehension in order to selectively delete atoms within an ASE
Atoms object. For example, the below code creates an ethanol molecule and subsequently strips all the hydrogen
atoms from it:
from ase.structure import molecule
atoms = molecule(CH3CH2OH)
del atoms[[atom.index for atom in atoms if atom.symbol==H]]
59
get_center_of_mass()
get_distance()
get_volume()
has()
edit()
60
adsorbate_info:
Items in the info attribute survives copy and slicing and can be store to and retrieved from trajectory
files given that the key is a string, the value is picklable and, if the value is a user-defined object, its
base class is importable. One should not make any assumptions about the existence of keys.
Examples:
These three are equivalent:
>>>
>>>
>>>
>>>
d
a
a
a
=
=
=
=
1.104 # N2 bondlength
Atoms(N2, [(0, 0, 0), (0, 0, d)])
Atoms(numbers=[7, 7], positions=[(0, 0, 0), (0, 0, d)])
Atoms([Atom(N, (0, 0, 0)), Atom(N, (0, 0, d)])
FCC gold:
>>> a = 4.05 # Gold lattice constant
>>> b = a / 2
>>> fcc = Atoms(Au,
...
cell=[(0, b, b), (b, 0, b), (b, b, 0)],
...
pbc=True)
Hydrogen wire:
>>> d = 0.9 # H-H distance
>>> L = 7.0
>>> h = Atoms(H, positions=[(0, L / 2, L / 2)],
...
cell=(d, L, L),
...
pbc=(1, 0, 0))
append(atom)
Append atom to end.
calc
Calculator object.
cell
Attribute for direct manipulation of the unit cell.
center(vacuum=None, axis=(0, 1, 2))
Center atoms in unit cell.
Centers the atoms in the unit cell, so there is the same amount of vacuum on all sides.
vacuum: float (default: None) If specified adjust the amount of vacuum when centering. If vacuum=10.0 there will thus be 10 Angstrom of vacuum on each side.
axis: int or sequence of ints Axis or axes to act on. Default: Act on all axes.
constraints
Constraints of the atoms.
copy()
Return a copy.
edit()
Modify atoms interactively through ase-gui viewer.
Conflicts leading to undesirable behaviour might arise when matplotlib has been pre-imported with
certain incompatible backends and while trying to use the plot feature inside the interactive ag. To
circumvent, please set matplotlib.use(gtk) before calling this method.
extend(other)
Extend atoms object by appending atoms from other.
get_angle(list)
Get angle formed by three atoms.
61
calculate angle between the vectors list[1]->list[0] and list[1]->list[2], where list contains the atomic
indexes in question.
get_angular_momentum()
Get total angular momentum with respect to the center of mass.
get_array(name, copy=True)
Get an array.
Returns a copy unless the optional argument copy is false.
get_atomic_numbers()
Get integer array of atomic numbers.
get_calculation_done()
Let the calculator calculate its thing, using the current input.
get_calculator()
Get currently attached calculator object.
get_cell()
Get the three unit cell vectors as a 3x3 ndarray.
get_celldisp()
Get the unit cell displacement vectors .
get_center_of_mass(scaled=False)
Get the center of mass.
If scaled=True the center of mass in scaled coordinates is returned.
get_charges()
Get calculated charges.
get_chemical_formula(mode=hill)
Get the chemial formula as a string based on the chemical symbols.
Parameters:
mode: There are three different modes available:
all: The list of chemical symbols are contracted to at string, e.g. [C, H, H, H, O, H]
becomes CHHHOH.
reduce: The same as all where repeated elements are contracted to a single symbol and a
number, e.g. CHHHOCHHH is reduced to CH3OCH3.
hill: The list of chemical symbols are contracted to a string following the Hill notation (alphabetical order with C and H first), e.g. CHHHOCHHH is reduced to C2H6O and SOOHOHO
to H2O4S. This is default.
get_chemical_symbols(reduce=False)
Get list of chemical symbol strings.
get_dihedral(list)
Calculate dihedral angle.
Calculate dihedral angle between the vectors list[0]->list[1] and list[2]->list[3], where list contains the
atomic indexes in question.
get_dipole_moment()
Calculate the electric dipole moment for the atoms object.
Only available for calculators which has a get_dipole_moment() method.
get_distance(a0, a1, mic=False)
Return distance between two atoms.
Use mic=True to use the Minimum Image Convention.
62
get_forces(apply_constraint=True)
Calculate atomic forces.
Ask the attached calculator to calculate the forces and apply constraints. Use apply_constraint=False
to get the raw forces.
get_initial_charges()
Get array of initial charges.
get_initial_magnetic_moments()
Get array of initial magnetic moments.
get_isotropic_pressure(stress)
Get the current calculated pressure, assume isotropic medium. in Bar
get_kinetic_energy()
Get the kinetic energy.
get_magnetic_moment()
Get calculated total magnetic moment.
get_magnetic_moments()
Get calculated local magnetic moments.
get_masses()
Get array of masses.
get_momenta()
Get array of momenta.
get_moments_of_inertia(vectors=False)
Get the moments of inertia along the principal axes.
The three principal moments of inertia are computed from the eigenvalues of the symmetric inertial tensor. Periodic boundary conditions are ignored. Units of the moments of inertia are
amu*angstrom**2.
get_number_of_atoms()
Returns the number of atoms.
Equivalent to len(atoms) in the standard ASE Atoms class.
get_pbc()
Get periodic boundary condition flags.
get_positions(wrap=False)
Get array of positions. If wrap==True, wraps atoms back into unit cell.
get_potential_energies()
Calculate the potential energies of all the atoms.
Only available with calculators supporting per-atom energies (e.g. classical potentials).
get_potential_energy(force_consistent=False, apply_constraint=True)
Calculate potential energy.
Ask the attached calculator to calculate the potential energy and apply constraints.
ply_constraint=False to get the raw forces.
Use ap-
When supported by the calculator, either the energy extrapolated to zero Kelvin or the energy consistent with the forces (the free energy) can be returned.
get_reciprocal_cell()
Get the three reciprocal lattice vectors as a 3x3 ndarray.
Note that the commonly used factor of 2 pi for Fourier transforms is not included here.
get_scaled_positions()
Get positions relative to unit cell.
63
Atoms outside the unit cell will be wrapped into the cell in those directions with periodic boundary
conditions so that the scaled coordinates are between zero and one.
get_stress(voigt=True)
Calculate stress tensor.
Returns an array of the six independent components of the symmetric stress tensor, in the traditional
Voigt order (xx, yy, zz, yz, xz, xy) or as a 3x3 matrix. Default is Voigt order.
get_stresses()
Calculate the stress-tensor of all the atoms.
Only available with calculators supporting per-atom energies and stresses (e.g. classical potentials).
Even for such calculators there is a certain arbitrariness in defining per-atom stresses.
get_tags()
Get integer array of tags.
get_temperature()
Get the temperature. in Kelvin
get_total_energy()
Get the total energy - potential plus kinetic energy.
get_velocities()
Get array of velocities.
get_volume()
Get volume of unit cell.
has(name)
Check for existence of array.
name must be one of: tags, momenta, masses, magmoms, charges.
new_array(name, a, dtype=None, shape=None)
Add new array.
If shape is not None, the shape of a will be checked.
numbers
Attribute for direct manipulation of the atomic numbers.
pbc
Attribute for direct manipulation of the periodic boundary condition flags.
pop(i=-1)
Remove and return atom at index i (default last).
positions
Attribute for direct manipulation of the positions.
rattle(stdev=0.001, seed=42)
Randomly displace atoms.
This method adds random displacements to the atomic positions, taking a possible constraint into
account. The random numbers are drawn from a normal distribution of standard deviation stdev.
For a parallel calculation, it is important to use the same seed on all processors!
repeat(rep)
Create new repeated atoms object.
The rep argument should be a sequence of three positive integers like (2,3,1) or a single integer (r)
equivalent to (r,r,r).
rotate(v, a=None, center=(0, 0, 0), rotate_cell=False)
Rotate atoms based on a vector and an angle, or two vectors.
Parameters:
64
v: Vector to rotate the atoms around. Vectors can be given as strings: x, -x, y, ... .
a = None: Angle that the atoms is rotated around the vecor v. If an angle is not specified, the length
of v is used as the angle (default). The angle can also be a vector and then v is rotated into a.
center = (0, 0, 0): The center is kept fixed under the rotation. Use COM to fix the center of mass,
COP to fix the center of positions or COU to fix the center of cell.
rotate_cell = False: If true the cell is also rotated.
Examples:
Rotate 90 degrees around the z-axis, so that the x-axis is rotated into the y-axis:
>>>
>>>
>>>
>>>
>>>
>>>
a = pi / 2
atoms.rotate(z, a)
atoms.rotate((0, 0, 1), a)
atoms.rotate(-z, -a)
atoms.rotate((0, 0, a))
atoms.rotate(x, y)
65
Examples:
Two equivalent ways to define an orthorhombic cell:
>>> a.set_cell([a, b, c])
>>> a.set_cell([(a, 0, 0), (0, b, 0), (0, 0, c)])
set_charges(charges=None)
Deprecated method. Use set_initial_charges.
set_chemical_symbols(symbols)
Set chemical symbols.
set_constraint(constraint=None)
Apply one or more constrains.
The constraint argument must be one constraint object or a list of constraint objects.
set_dihedral(list, angle, mask=None)
set the dihedral angle between vectors list[0]->list[1] and list[2]->list[3] by changing the atom indexed
by list[3] if mask is not None, all the atoms described in mask (read: the entire subgroup) are moved
example: the following defines a very crude ethane-like molecule and twists one half of it by 30
degrees.
>>> atoms = Atoms(HHCCHH, [[-1, 1, 0], [-1, -1, 0], [0, 0, 0],
[1, 0, 0], [2, 1, 0], [2, -1, 0]])
>>> atoms.set_dihedral([1,2,3,4],7*pi/6,mask=[0,0,0,1,1,1])
66
set_velocities(velocities)
Set the momenta by specifying the velocities.
translate(displacement)
Translate atomic positions.
The displacement argument can be a float an xyz vector or an nx3 array (where n is the number of
atoms).
write(filename, format=None, **kwargs)
Write yourself to a file.
from
a1 =
a2 =
a3 =
# same is a1
class ase.atom.Atom(symbol=X, position=(0, 0, 0), tag=None, momentum=None, mass=None, magmom=None, charge=None, atoms=None, index=None)
Class for representing a single atom.
Parameters:
symbol: str or int Can be a chemical symbol (str) or an atomic number (int).
position: sequence of 3 floats Atomi position.
tag: int Special purpose tag.
momentum: sequence of 3 floats Momentum for atom.
mass: float Atomic mass in atomic units.
magmom: float or 3 floats Magnetic moment.
charge: float Atomic charge.
The first argument to the constructor of an Atom object is the chemical symbol, and the second argument is the
position in units (see ase.units). The position can be any numerical sequence of length three. The properties
of an atom can also be set using keywords like it is done in the a2 and a3 examples above.
More examples:
>>> a = Atom(O, charge=-2)
>>> b = Atom(8, charge=-2)
>>> c = Atom(H, (1, 2, 3), magmom=1)
>>> print a.charge, a.position
-2 [ 0. 0. 0.]
>>> c.x = 0.0
>>> c.position
array([ 0., 2., 3.])
>>> b.symbol
O
>>> c.tag = 42
>>> c.number
1
>>> c.symbol = Li
>>> c.number
3
67
If the atom object belongs to an Atoms object, then assigning values to the atom attributes will change the corresponding arrays of the atoms object:
>>> OH = Atoms(OH)
>>> OH[0].charge = -1
>>> OH.get_charges()
array([-1., 0.])
Another example:
>>> for atom in bulk:
...
if atom.symbol == Ni:
...
atom.magmom = 0.7 # set initial magnetic moment
The different properties of an atom can be obtained and changed via attributes (position, number, tag,
momentum, mass, magmom, charge, x, y, z):
>>> a1.position = [1, 0, 0]
>>> a1.position
array([ 1., 0., 0.])
>>> a1.z = 2.5
>>> a1.position
array([ 1. , 0. , 2.5])
>>> a2.magmom = 1.0
That last line will set the initial magnetic moment that some calculators use (similar to the
set_initial_magnetic_moments() method).
Note: The position and momentum attributes refer to mutable objects, so in some cases, you may want to
use a1.position.copy() in order to avoid changing the position of a1 by accident.
See Also:
Atom: All the details!
ase.atoms: More information about how to use collections of atoms.
ase.calculators: Information about how to calculate forces and energies of atoms.
68
7.3 Units
Physical units are defined in the ase/units.py module. Electron volts (eV) and angstroms (Ang) are defined as 1.0.
Other units are nm, Bohr, Hartree or Ha, kJ, kcal, mol, Rydberg or Ry, second, fs and kB.
Note: All constants are taken from the 1986 CODATA.
Examples:
>>> from ase.units import *
>>> 2 * Bohr
1.0583545150138329
>>> 25 * Rydberg
340.14244569396635
>>> 100 * kJ/mol
1.0364272141304978
>>> 300 * kB
0.025852157076770025
>>> 0.1 * fs
0.009822693531550318
>>> print 1 Hartree = +str(Hartree*mol/kcal)+ kcal/mol
If you dont know the atomic number of some element, then you can look it up in the atomic_numbers
dictionary:
>>> from ase.data import atomic_numbers, covalent_radii
>>> atomic_numbers[Cu]
29
>>> covalent_radii[29]
1.1699999999999999
7.3. Units
69
Known formats:
70
format
GPAW restart-file
Dacapo netCDF output file
Old ASE netCDF trajectory
Virtual Nano Lab file
ASE pickle trajectory
ASE bundle trajectory
GPAW text output
CUBE file
XCrySDen Structure File
Dacapo text output
XYZ-file
VASP POSCAR/CONTCAR file
VASP OUTCAR file
SIESTA STRUCT file
ABINIT input file
V_Sim ascii file
Protein Data Bank
CIF-file
FHI-aims geometry file
FHI-aims output file
VTK XML Image Data
VTK XML Structured Grid
VTK XML Unstructured Grid
TURBOMOLE coord file
TURBOMOLE gradient file
exciting input
AtomEye configuration
WIEN2k structure file
DftbPlus input file
CASTEP geom file
CASTEP output file
CASTEP trajectory file
ETSF format
DFTBPlus GEN format
CMR db/cmr-file
CMR db/cmr-file
LAMMPS dump file
EON reactant.con file
Gromacs coordinates
Gaussian com (input) file
Gaussian output file
Quantum espresso in file
Quantum espresso out file
Extended XYZ file
short name
gpw
dacapo
nc
vnl
traj
bundle
gpaw-text
cube
xsf
dacapo-text
xyz
vasp
vasp_out
struct_out
abinit
v_sim
pdb
cif
aims
aims_out
vti
vts
vtu
tmol
tmol-gradient
exi
cfg
struct
dftb
cell
castep
geom
etsf.nc
gen
db
cmr
lammps
eon
gro
gaussian
gaussian_out
esp_in
esp_out
extxyz
71
format
ASE pickle trajectory
ASE bundle trajectory
CUBE file
XYZ-file
VASP POSCAR/CONTCAR file
ABINIT input file
Protein Data Bank
CIF-file
XCrySDen Structure File
FHI-aims geometry file
gOpenMol .plt file
Python script
Encapsulated Postscript
Portable Network Graphics
Persistance of Vision
VTK XML Image Data
VTK XML Structured Grid
VTK XML Unstructured Grid
TURBOMOLE coord file
exciting
AtomEye configuration
WIEN2k structure file
CASTEP cell file
DftbPlus input file
ETSF
DFTBPlus GEN format
CMR db/cmr-file
CMR db/cmr-file
EON reactant.con file
Gromacs coordinates
GROMOS96 (only positions)
X3D
X3DOM HTML
Extended XYZ file
short name
traj
bundle
cube
xyz
vasp
abinit
pdb
cif
xsf
aims
plt
py
eps
png
pov
vti
vts
vtu
tmol
exi
cfg
struct
cell
dftb
etsf.nc
gen
db
cmr
eon
gro
g96
x3d
html
extxyz
72
7.6 Examples
from ase.lattice.surface import *
adsorbate = Atoms(CO)
adsorbate[1].z = 1.1
a = 3.61
slab = fcc111(Cu, (2, 2, 3), a=a, vacuum=7.0)
add_adsorbate(slab, adsorbate, 1.8, ontop)
This will write both a slab.pov and a slab.ini file. Convert to PNG with the command povray
slab.ini or use the run_povray=True option:
7.6. Examples
73
Note that the XYZ-format does not contain information about the unic cell:
>>> write(slab.xyz, slab)
>>> a = read(slab.xyz)
>>> a.get_cell()
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> a.get_pbc()
array([False, False, False], dtype=bool)
1.99569088e-16],
7.11236625e-17],
1.32527034e+01]])
A script showing all of the povray parameters, and generating the image below, can be found here:
save_pov.py
74
An other example showing how to change colors and textures in pov can be found here:
../tutorials/saving_graphics.py.
7.7 ASE-GUI
The graphical user-interface allows users to visualize, manipulate, and render molecular systems and atoms objects. It also allows to setup and run a number of calculations and can be used to transfer between different file
formats.
7.7. ASE-GUI
75
measurement
xyz position and atomic symbol
interatomic distance and symbols
all three internal angles and symbols
Measures the dihedral angle, e.g. the angle between bonds 12 and 34
chemical composition of selection.
Comment
XYZ file
ASE trajectory
PDB file
Gaussian cube file
Python script
VNL file
Portable Network Graphics
Persistance of Vision
Encapsulated PostScript
FHI-aims geometry input
VASP geometry input
ASE bundle trajectory
Crystallographic Information File
Files
The ase-gui program can read all the file formats the ASEs read() function can understand.
$ ase-gui N2Fe110-path.traj
ase-gui
ase-gui
ase-gui
ase-gui
ase-gui
ase-gui
ase-gui
x.traj@0:10:1
x.traj@0:10
x.traj@:10
x.traj@-10:
x.traj@0
x.traj@-1
x.traj@::2
#
#
#
#
#
#
#
first 10 images
first 10 images
first 10 images
last 10 images
first image
last image
every second image
If you want to select the same range from many files, the you can use the -n or --image-number option:
$ ase-gui -n -1 *.traj
$ ase-gui -n 0 *.traj
Writing files
$ ase-gui -n -1 a*.traj -o new.traj
Possible formats are: traj, xyz, cube, pdb, eps, png, and pov. For details, see the io module documentation.
Interactive use
The ase-gui program can also be launched directly from a Python script or interactive session:
>>> from ase import *
>>> atoms = ...
>>> view(atoms)
or
>>> view(atoms, repeat=(3, 3, 2))
NEB calculations
Use Tools NEB to plot energy barrier.
$ ase-gui --interpolate 3 initial.xyz final.xyz -o interpolated_path.traj
The symbols are the same as used in the plotting data function.
Defaults for ase-gui
Using a file ~/.ase/gui.py, certain defaults can be set. If it exists, this file is executed after initializing the
variables and colours normally used in ase-gui. One can change the default graphs that are plotted, and the default
radii for displaying specific atoms. This example will display the energy evolution and the maximal force in a
graph and also display Cu atoms (Z=29) with a radius of 1.6 Angstrom.
gui_default_settings[gui_graphs_string] = "i, e - min(E), fmax"
gui_default_settings[covalent_radii] = [[29,1.6]]
7.7. ASE-GUI
77
To change the color scheme of graphs it is necessary to change the default behaviour of Matplotlib in a similar
way by using a file ~/.matplotlib/matplotlibrc.
patch.edgecolor
text.color
axes.facecolor
axes.edgecolor
axes.labelcolor
axes.color_cycle
xtick.color
ytick.color
grid.color
figure.facecolor
figure.edgecolor
:
:
:
:
:
:
:
:
:
:
:
white
white
black
white
white
b, g, r, c, m, y, w
white
white
white
0.1
black
Finally, the color scheme of the windows themselves (i.e. menus, buttons and text etc.) can be changed by
choosing a different desktop theme. In Ubuntu it is possible to get white on a dark background by selecting the
theme HighContrastInverse under Appearances in the system settings dialog.
7.7.2 Edit
Add atoms
Allows to add single atoms or a group of atoms to an existing atoms object. If the description is an atom or a
known molecule from the g1, g2, or g3 set (e.g. CH4), then the structure from the data molecule is used. In
addition, a molecule can also be imported from file via the load molecule button.
The specified position can either be absolute, or determined automatically via
auto+<dist>
where auto is the centre of mass of the currently selected atoms, and <dist> is the distance toward the viewing
plane.
The molecule-to-be is rotated into the current viewing plane before addition into the system. Two options exist for
choosing the origin within the new atoms, it can be either the centre of mass or the origin of the loaded geometry.
Modify
Menu to allow modification of the atomic symbol, an attached tag, or its magnetic moment.
Copy/Paste
Allows to copy parts of an existing system to a clipboard, and pastes via the same infrastructure as the Add
atoms functionality. Note that the on-screen orientation of the pasted atoms will be the same as at the time of
copying. Note also that, by default, the origin of the pasted system is taken to be the atom furthest away from the
viewing point.
7.7.3 View
Repeat
Menu to allow repetition of periodic unit cells. Use the Set unit cell button to set the overall unit cell to the
current one.
78
Rotate
Menu to manually fine tune the viewing angle. Use Update button to set the menu to the current angle.
Colors
The colors menu allows numerous ways to change the color scheme and to encode additional information into
the display colors. This includes automatic coloring by atomic numbers (default), user-specified atomic number
scheme, coloring by tags, forces, or completely manually specified colors. In addition, several standard color
scales are available.
Settings
Basic viewing settings. Also allows to constrain/unconstrain atoms and to mark selected atoms as invisible.
7.7.4 Tools
Graphs
Allows to graph different quantities for a given trajectory. A save button also gives the opportunity to save the
data to file.
This example plots the maximal force for each image i and could help in investigating the convergence properties
for relaxations:
i, e-min(E), fmax
Interpretation
total energy
potential energy
kinetic energy
maximum force
average force
distance between two atoms
position of atom number n
current image number
energy of image number i
force on atom number n
magnetic moment of atom number n
unit-cell basis vectors
path length
tangle between atoms n1, n2 and n3, centered on n2
dihedral angle between n1, n2, n3, and n4
temperature (requires velocity)
Movie
Allows to play the current trajectory as a movie using a number of different settings. Default duration is 5 s.
Expert mode
Python interface to all ase-gui functions, with numerous extra commands defined that help to modify and visualize
a system. The commands come in two flavors, the first is interpreted on an atom-by-atom basis (e.g. operates on
7.7. ASE-GUI
79
position, color, etc) and the second is based on the entire frame. The flavor of a given line is determined from the
first command. Note that the frame-based commands can be used in atom-based operations, but not vice versa.
See below for some examples.
Regular python syntax applies to the commands and numpy has been imported as np.
Two buttons allow to reduce the operation to a given frame:
Only selected
atoms (sa)
Only current
frame (cf)
Restricts operation only to the selected atoms. The text command sa activates or
deactivates this button.
Restricts operation only to the current frame, useful for long trajectories. The text
command cf activates or deactivates this button.
rad
s
f
Z
m
d
Interpretation
Cartesian coordinates. Example: x += A[0][0]
Color components, invoking the expert mode changes the color mode to manual and allows to
address all colors individually. Example: r =
(z-min(R[:,2]))/(max(R[:,2])-min(R[:,2]))
atomic display radius
Boolean to control the selection of an atom. Example: s = Z == 6 and x > 5 or s = d
== False
force on an atom
atomic number
magnetic moment
dynamic, e.g. d = False fixes an atom
List of frame-based and global commands and global objects with examples:
Command
e
fmax
A
E
F
M
R
S
D
del S
sa,cf
frame
center
cov
self
gui
img
Interpretation
total energy
maximal force
unit cell
total energy array of all frames. Example: e-min(E)
all forces in one frame
all magnetic moments
all atomic positions
boolean array of the entire selection
boolean array of dynamic atoms (False = atom is fixed)
deletes current selection
toggles the selected-atoms-only or the current-frame-only buttons
provides and edits the frame number in a trajectory
centers system in its unit cell
array of original covalent radii
expert mode window
ase-gui GUI object, this controls the entire ase-gui session
ase-gui images object, all physical data is stored here
To save data between commands, one has to assign variables to parent objects in the gui, e.g. via
self.temp_var = R-img.P[0,:]. DISCLAIMER: Doing so might risk the functionality of the entire
ase-gui session if you accidentally overwrite basic functionality of the gui or the image objects stored within.
Finally, recurring selections of commands collected as scripts can be executed as
exec <filename>
If the file in question is saved in the directory ~/.ase/ then just the filename will also do.
80
Constraints
Allows to set (or remove) constraints based on the currently selected atoms.
Render scene
Graphical interface to the ASE povray interface, ideally it requires that povray is installed on your computer to
function, but it also can be used just to export the complete set of povray files.
The texture of each atom is adjustable: The default texture is applied to all atoms, but then additional textures
can be defined based on selections (Create new texture from current selection). These can be
obtained either from selecting atoms by hand or by defining a selection with a boolean expression, for example
Z==6 and x>5 and y<0 will select all carbons with coordinates x>5 and y<0. The available commands are
listed in the Help on textures window.
A movie-making mode (render all N frames) is also available. After rendering, the frames can be stitched
together using the convert unix program e.g.
localhost:doc hanke$ convert -delay 4.17 temp.*.png temp.gif
For this particular application it might be a good idea to use a white background instead of the default transparent
option.
Move atoms
Allows selected atoms to be moved using the arrow keys. The direction is always parallel to the plane of the
screen. Two possible movements are available: Just pressing the arrow keys will move by 0.1 Angstrom, shift
+ arrow keys will move by 0.01 Angstrom.
Rotate atoms
Allows sets of atoms to be rotated using the arrow keys. Different rotation modes are available depending on the
number of selected atoms. Again, two modes are available. Just the arrow keys will rotate by 2.5 degrees, and
shift + arrow keys will rotate by 0.5 deg.
number of
atoms labeled
0 atoms, 1, 3, 5
or more atoms
2 atoms
4 atoms,
selected
sequentially
rotation mode
uses the centre of mass of the atoms to be rotated as the rotation centre.
Defines the vector connecting the two atoms as rotation axis.
Defines the vector connecting the two atoms as rotation axis. This mode has the advantage
that the dihedral angle is measured at the same time, thus allowing one to monitor the
degree of rotation.
Orient atoms
stub
NEB
stub
Bulk Modulus
stub
7.7. ASE-GUI
81
7.7.5 Setup
The setup menus allow for the intuitive creation of numerous standard surfaces, nanoparticles, graphene and
graphene nanoribbons, as well as nanotubes.
Along with creating the geometry within ase-gui, a button provides the necessary python code allowing one to
recreate the exact same geometry in ASE scripts.
7.7.6 Calculate
Set calculator
Allows gui to choose a calculator for internal computations (see below). Different density functional codes and
force fields, as well as the EMT calculator are available. For the FHI-aims and VASP calculators, it is also possible
to export an entire set of input files.
Energy and forces
Invokes the currently set calculator and provides energies and optional forces for all atoms.
Energy minimization
Runs an ASE relaxation using the currently selected calculator with a choice of relaxation algorithm and convergence criteria. Great for quickly (pre-)relaxing a molecule before placing it into a bigger system.
Scale system
Stub
The name of the calculator must be lower case and will default to EMT. The task must be molecule or bulk.
There are several ways to specify the system or systems to perform the calculations on:
Chemical names: H2O or Fe. Default molecule definitions are used.
Range of chemical symbols: Sc-Zn (3d-metals)
Special names: G2, G2_1 or S22
File names: benzene.xyz or slab.traj
The exact meaning of these names will depend on the task.
Simple examples:
$ ase emt H2 --relax=0.01
$ ase abinit bulk Si -a 5.5 -p ecut=150 -k 4,4,4
82
-t TAG, --tag=TAG
Skip calculations where the json lock-file or result file already exists.
struc-
83
7.8.2 Molecules
Example:
$ ase abinit H2 -p ecut=200,xc=LDA -F 5,1 --atomize
This will calculate the energy of a H2 molecule using Abinit with a planewave cutoff of 200 eV and the LDA
XC-functional. A fit using 5 points and a variation of the bond length from -1 % to +1 % is made and in addition
the energy of a single hydrogen atom is also calculated.
Results are written to json files and can be analysed with:
$ ase abinit H H2 -s
name
E
eV
H2
-29.703
H
-12.426
E-E0
eV
0.022
d0
Ang
0.770
hnu
meV
556.096
Ea
eV
4.852
Ea0
eV
4.873
Note: The json files are simple text files that can be more or lessed or pretty printed with python -m
json.tool H2-molecule-abinit.jon.
Here we used the default EMT potential and the result is:
$ ase bulk Ni Cu Pd Ag Pt Au -s
name
E
E-E0
eV
eV
Ni
-0.009
0.005
Ag
0.002
0.002
Pt
-0.000
0.000
Au
0.003
0.003
Pd
0.000
0.001
Cu
-0.006
0.001
V0
Ang^3
10.600
16.775
15.080
16.684
14.588
11.565
B
GPa
175.978
100.151
278.087
173.868
179.105
134.439
More examples
Anti-ferromagnetic bcc iron:
$ ase vasp bulk -x bcc Fe -C -M 2.3,-2.3 -p xc=PBE -k 8,8,8
84
The molecule task will expand G2_1 to a lot of molecules, so it makes sense to use -l option
(--use-lock-files) and submit the same job many times. A lock file will be created for each started calculation and calculations with existing lock file skipped. Moreover the calculations can be run in parallel (if parallel
version of GPAW is installed):
$ mpiexec gpaw-python which ase gpaw G2_1 -v 6.0 -p xc=vdW-DF,h=0.18 -R 0.02 -l
class M13Task(MoleculeTask):
taskname = m13
def build_system(self, name):
if self.bond_length is None:
b = 2 * covalent_radii[atomic_numbers[name]]
else:
b = self.bond_length
return FaceCenteredCubic(name, [(1, 0, 0)], [1],
latticeconstant=b * sqrt(2))
task = M13Task()
Then do this:
$ ase m13.py Pt -R 0.01
The relaxed EMT bondlength of 2.62 can be extracted from the created trajectory like this:
$ ase-gui -tg
10.9824302706
10.0805658256
9.61654400875
9.57510700742
9.57424531861
"e,fmax,d(0,9)" Pt-m13-emt.traj
2.27575724833 2.72
1.45353946744 2.68
0.447140179352 2.64
0.0656434401881 2.6222281202
0.00239771758341 2.62450316817
or like this:
>>> from ase.io import read
>>> pt = read(Pt-m13-emt.traj)
>>> pt.get_distance(0, 9)
2.6245031681662452
Convergence test
See convergence.py.
7.8.6 To be done
Optimize c/a ratio.
7.8. Command line tool
85
Implement different way of cell sampling for eos: [a0 + s for s in [x * np.array(range(- N/2 + 1, N/2 +
1))]] where x is sampling step length, N number of steps. Current way of sampling gives different length of
sampling interval depending on the lattice constant guess a0. DONE
Write results to file (pickel, csv, cmr (db), traj, ...) per system, together with json file!
Split off EnergyTask from Task.
Set correct magnetic moments for atoms. DONE
Allow setting charges in ase.tasks.task
Check occupation numbers and requested total magnetic moments for molecules/atoms. DONE
Add exclude option.
Relax cell. DONE
Optimize first then fit. DONE
Behavior of -w option?
Reaction task?
Rethink analysis and summary stuff:
it would be nice to calculate for example cohesive energies on the command line, i.e. using
species belonging to different tasks
analysis should be more modular: one may want for example to calculate zpe energies for adsorption systems including molecules and surfaces and print the zpe correction for a given reaction.
ase.tasks.main - print complete architecture string in case of error (like in ase/test/__init__.py)
7.9.1 Molecules
The G2-database of common molecules is available:
ase.structure.molecule(name, data=None, **kwargs)
Create formula base on data. If data is None assume G2 set. kwargs currently not used.
Example:
>>> from ase.structure import molecule
>>> atoms = molecule(H2O)
86
crystalstructure: str Must be one of sc, fcc, bcc, hcp, diamond, zincblende, rocksalt, cesiumchloride, or
fluorite.
a: float Lattice constant.
c: float Lattice constant.
covera: float c/a raitio used for hcp. Use sqrt(8/3.0) for ideal ratio.
orthorhombic: bool Construct orthorhombic unit cell instead of primitive cell which is the default.
cubic: bool Construct cubic unit cell if possible.
examples:
>>> from ase.lattice import bulk
>>> a1 = bulk(Cu, fcc, a=3.6)
>>> a2 = bulk(Cu, fcc, a=3.6, orthorhombic=True)
>>> a3 = bulk(Cu, fcc, a=3.6, cubic=True)
>>> a1.cell
array([[ 0. , 1.8, 1.8],
[ 1.8, 0. , 1.8],
[ 1.8, 1.8, 0. ]])
>>> a2.cell
array([[ 2.54558441, 0.
, 0.
],
[ 0.
, 2.54558441, 0.
],
[ 0.
, 0.
, 3.6
]])
>>> a3.cell
array([[ 3.6, 0. , 0. ],
[ 0. , 3.6, 0. ],
[ 0. , 0. , 3.6]])
7.9.3 Nanotubes
ase.structure.nanotube(n, m, length=1, bond=1.42, symbol=C, verbose=False)
examples:
>>> from ase.structure import nanotube
>>> cnt1 = nanotube(6, 0, length=4)
>>> cnt2 = nanotube(3, 3, length=6, bond=1.4, symbol=Si)
87
7.9.5 Surfaces
Common surfaces
A number of utility functions are provided to set up the most common surfaces, to add vacuum layers, and to add
adsorbates to a surface. In general, all surfaces can be set up with the modules described in the section General
crystal structures and surfaces, but these utility functions make common tasks easier.
88
Example
This will produce a slab 2x2x3 times the minimal possible size, with a (111) surface in the z direction. A 10
vacuum layer is added on each side.
To set up the same surface with with a hydrogen atom adsorbed in an on-top position 1.5 above the top layer:
from ase.lattice.surface import fcc111, add_adsorbate
slab = fcc111(Al, size=(2,2,3))
add_adsorbate(slab, H, 1.5, ontop)
slab.center(vacuum=10.0, axis=2)
Note that in this case is is probably not meaningful to use the vacuum keyword to fcc111, as we want to leave 10
of vacuum after the adsorbate has been added. Instead, the center() method of the Atoms is used to add
the vacuum and center the system.
The atoms in the slab will have tags set to the layer number: First layer atoms will have tag=1, second layer atoms
will have tag=2, and so on. Adsorbates get tag=0:
>>> print atoms.get_tags()
[3 3 3 3 2 2 2 2 1 1 1 1 0]
This can be useful for setting up ase.constraints (see Diffusion of gold atom on Al(100) surface (NEB)).
Utility functions for setting up surfaces
89
fcc100
fcc110
bcc100
hcp10m10
diamond100
ase.lattice.surface.fcc111(symbol, size, a=None, vacuum=0.0, orthogonal=False)
ase.lattice.surface.fcc211(symbol, size, a=None, vacuum=0.0, orthogonal=True)
ase.lattice.surface.bcc110(symbol, size, a=None, vacuum=0.0, orthogonal=False)
90
91
fcc111
fcc211
not implemented
bcc110
bcc111
hcp0001
92
diamond111
hollow
fcc
hcp
bridge
shortbridge
longbridge
Adding new utility functions If you need other surfaces than the ones above, the easiest is to look in the source
file surface.py, and adapt one of the existing functions. Please contribute any such function that you make either
by checking it into SVN or by mailing it to the developers.
Adding adsorbates
After a slab has been created, a vacuum layer can be added. It is also possible to add one or more adsorbates.
ase.lattice.surface.add_adsorbate(slab, adsorbate, height, position=(0, 0), offset=None,
mol_index=0)
Add an adsorbate to a surface.
This function adds an adsorbate to a slab. If the slab is produced by one of the utility functions in
ase.lattice.surface, it is possible to specify the position of the adsorbate by a keyword (the supported keywords depend on which function was used to create the slab).
If the adsorbate is a molecule, the atom indexed by the mol_index optional argument is positioned on top
of the adsorption position on the surface, and it is the responsibility of the user to orient the adsorbate in a
sensible way.
This function can be called multiple times to add more than one adsorbate.
Parameters:
slab: The surface onto which the adsorbate should be added.
adsorbate: The adsorbate. Must be one of the following three types: A string containing the chemical
symbol for a single atom. An atom object. An atoms object (for a molecular adsorbate).
height: Height above the surface.
position: The x-y position of the adsorbate, either as a tuple of two numbers or as a keyword (if the surface is produced by one of the functions in ase.lattice.surfaces).
offset (default: None): Offsets the adsorbate by a number of unit cells.
more than one adsorbate.
mol_index (default: 0): If the adsorbate is a molecule, index of the atom to be positioned above the location specified by the position argument.
Note position is given in absolute xy coordinates (or as a keyword), whereas offset is specified in unit cells.
This can be used to give the positions in units of the unit cell by using offset instead.
ase.lattice.surface.add_vacuum(atoms, vacuum)
Add vacuum layer to the atoms.
Parameters:
atoms: An Atoms object most likely created by one of the ase.lattice modules.
vacuum: The thickness of the vacuum layer (in Angstrom).
Create specific non-common surfaces
New in version 3.5.2. In addition to the most normal surfaces, a function has been constructed to create more
uncommon surfaces that one could be interested in. It is constructed upon the Miller Indices defining the surface
and can be used for both fcc, bcc and hcp structures. The theory behind the implementation can be found here:
general_surface.pdf.
93
This is the easy way, where you use the experimental lattice constant for gold bulk structure. You can write:
from ase.visualize import view
view(s1)
94
Next example is a molybdenum bcc(321) surface where we decide what lattice constant to use:
from ase.lattice import bulk
Mobulk = bulk(Mo, bcc, a=3.16, cubic=True)
s2 = surface(Mobulk, (3, 2, 1), 9)
s2.center(vacuum=10, axis=2)
95
As the last example, creation of alloy surfaces is also very easily carried out with this module. In this example,
two Pt3 Rh fcc(211) surfaces will be created:
a = 4.0
from ase import Atoms
Pt3Rh = Atoms(Pt3Rh,
scaled_positions=[(0, 0, 0),
(0.5, 0.5, 0),
(0.5, 0, 0.5),
(0, 0.5, 0.5)],
cell=[a, a, a],
pbc=True)
s3 = surface(Pt3Rh, (2, 1, 1), 9)
s3.center(vacuum=10, axis=2)
Pt3Rh.set_chemical_symbols(PtRhPt2)
s4 = surface(Pt3Rh , (2, 1, 1), 9)
s4.center(vacuum=10, axis=2)
96
97
The minimal unit cell is repeated 2*2*3 times. The lattice constant is taken from the database of lattice constants in
ase.data module. There are periodic boundary conditions along the x and y axis, but free boundary conditions
along the z axis. Since the three directions are perpendicular, a (111) surface is created.
To set up a slab of BCC copper with [100] along the first axis, [010] along the second axis, and [111] along the
third axis use:
from ase.lattice.cubic import BodyCenteredCubic
atoms = BodyCenteredCubic(directions=[[1,0,0], [0,1,0], [1,1,1]],
size=(2,2,3), symbol=Cu, pbc=(1,1,0),
latticeconstant=4.0)
Since BCC is not the natural crystal structure for Cu, a lattice constant has to be specified. Note that since the
repeat directions of the unit cell are not orthogonal, the Miller indices of the surfaces will not be the same as the
Miller indices of the axes. The indices of the surfaces in this example will be (1,0,-1), (0,1,-1) and (0,0,1).
Available crystal lattices
The following modules are currently available (the * mark lattices with a basis):
lattice.cubic
SimpleCubic
FaceCenteredCubic
BodyCenteredCubic
Diamond (*)
lattice.tetragonal
SimpleTetragonal
CenteredTetragonal
lattice.orthorhombic
SimpleOrthorhombic
BaseCenteredOrthorhombic
FaceCenteredOrthorhombic
BodyCenteredOrthorhombic
lattice.monoclinic
SimpleMonoclinic
BaseCenteredMonoclinic
lattice.triclinic
Triclinic
lattice.hexagonal
Hexagonal
HexagonalClosedPacked (*)
Graphite (*)
98
The rhombohedral (or trigonal) lattices are not implemented. They will be implemented when the need
arises (and if somebody can tell me the precise definition of the 4-number Miller indices - I only know that
they are almost the same as in hexagonal lattices).
lattice.compounds
Lattices with more than one element. These are mainly intended as examples allowing you to define new
such lattices. Currenly, the following are defined
B1 = NaCl = Rocksalt
B2 = CsCl
B3 = ZnS = Zincblende
L1_2 = AuCu3
L1_0 = AuCu
Usage
The lattice objects are called with a number of arguments specifying e.g. the size and orientation of the lattice.
All arguments should be given as named arguments. At a minimum the symbol argument must be specified.
symbol The element, specified by the atomic number (an integer) or by the atomic symbol (i.e. Au). For
compounds, a tuple or list of elements should be given. This argument is mandatory.
directions and/or miller: Specifies the orientation of the lattice as the Miller indices of the three basis vectors of the supercell (directions=...) and/or as the Miller indices of the three surfaces
(miller=...). Normally, one will specify either three directions or three surfaces, but any combination that is both complete and consistent is allowed, e.g. two directions and two surface miller indices (this
example is slightly redundant, and consistency will be checked). If only some directions/miller indices are
specified, the remaining should be given as None. If you intend to generate a specific surface, and prefer to
specify the miller indices of the unit cell basis (directions=...), it is a good idea to give the desired
Miller index of the surface as well to allow the module to test for consistency. Example:
>>> atoms = BodyCenteredCubic(directions=[[1,-1,0],[1,1,-1],[0,0,1]],
...
miller=[None, None, [1,1,2]], ...)
Lattice constants
a
(a, c)
(a, b, c)
(a, b, c, , , )
(a, b, c, alpha)
(a, c)
Dictionary-keys
a
a, c or c/a
a, b or b/a, c or c/a
a, b or b/a, c or c/a, alpha, beta, gamma
a, b or b/a, c or c/a, alpha
a, c or c/a
Example:
>>> atoms = Monoclinic( ... , latticeconstant={a: 3.06,
...
b/a: 0.95, c/a: 1.07, alpha: 74})
debug: Controls the amount of information printed. 0: no info is printed. 1 (the default): The indices of surfaces
and unit cell vectors are printed. 2: Debugging info is printed.
99
Lattices with more than one element is made in the same way. A new attribute, element_basis, is added,
giving which atoms in the basis are which element. If there are four atoms in the basis, and element_basis is
(0,0,1,0), then the first, second and fourth atoms are one element, and the third is the other element. As an
example, the AuCu3 structure (also known as L12 ) is defined as:
# The L1_2 structure is "based on FCC", but is really simple cubic
# with a basis.
class AuCu3Factory(SimpleCubicFactory):
"A factory for creating AuCu3 (L1_2) lattices."
bravais_basis = [[0, 0, 0], [0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]]
element_basis = (0, 1, 1, 1)
AuCu3 = L1_2 = AuCu3Factory()
Sometimes, more than one crystal structure can be used to define the crystal structure, for example the Rocksalt
structure is two interpenetrating FCC lattices, one with one kind of atoms and one with another. It would be
tempting to define it as
class NaClFactory(FaceCenteredCubicFactory):
"A factory for creating NaCl (B1, Rocksalt) lattices."
bravais_basis = [[0, 0, 0], [0.5, 0.5, 0.5]]
element_basis = (0, 1)
but if this is used to define a finite system, one surface would be covered with one type of atoms, and the opposite
surface with the other. To maintain the stochiometry of the surfaces, it is better to use the simple cubic lattice with
a larger basis:
# To prevent a layer of element one on one side, and a layer of
# element two on the other side, NaCl is based on SimpleCubic instead
# of on FaceCenteredCubic
class NaClFactory(SimpleCubicFactory):
"A factory for creating NaCl (B1, Rocksalt) lattices."
bravais_basis = [[0, 0, 0], [0, 0, 0.5], [0, 0.5, 0], [0, 0.5, 0.5],
[0.5, 0, 0], [0.5, 0, 0.5], [0.5, 0.5, 0],
[0.5, 0.5, 0.5]]
element_basis = (0, 1, 1, 0, 1, 0, 0, 1)
100
See Also:
Performance test for all ASE local optimizers.
MDMin and FIRE both use Newtonian dynamics with added friction, to converge to an energy minimum, whereas
the others are of the quasi-Newton type, where the forces of consecutive steps are used to dynamically update a
101
Hessian describing the curvature of the potential energy landscape. You can use the QuasiNewton synonym for
BFGSLineSearch because this algorithm is in many cases the optimal of the quasi-Newton algorithms.
All of the local optimizer classes have the following structure:
class Optimizer:
def __init__(self, atoms, restart=None, logfile=None):
def run(self, fmax=0.05, steps=100000000):
def get_number_of_steps():
The convergence criterion is that the force on all individual atoms should be less than fmax:
max |F~a | < fmax
a
BFGS
The BFGS object is one of the minimizers in the ASE package. The below script uses BFGS to optimize the
structure of a water molecule, starting with the experimental geometry:
from ase import Atoms
from ase.optimize import BFGS
from ase.calculators.emt import EMT
import numpy as np
d = 0.9575
t = np.pi / 180 * 104.51
water = Atoms(H2O,
positions=[(d, 0, 0),
(d * np.cos(t), d * np.sin(t), 0),
(0, 0, 0)],
calculator=EMT())
dyn = BFGS(water)
dyn.run(fmax=0.05)
which produces the following output. The columns are the solver name, step number, clock time, potential energy
(eV), and maximum force.:
BFGS:
BFGS:
BFGS:
BFGS:
BFGS:
0
1
2
3
4
19:45:25
19:45:25
19:45:25
19:45:25
19:45:25
2.769633
2.154560
1.906812
1.880255
1.879488
8.6091
4.4644
1.3097
0.2056
0.0205
When doing structure optimization, it is useful to write the trajectory to a file, so that the progress of the optimization run can be followed during or after the run:
dyn = BFGS(water, trajectory=H2O.traj)
dyn.run(fmax=0.05)
Use the command ase-gui H2O.traj to see what is going on (more here: ase.gui). The trajectory file can
also be accessed using the module ase.io.trajectory.
The attach method takes an optional argument interval=n that can be used to tell the structure optimizer
object to write the configuration to the trajectory file only every n steps.
During a structure optimization, the BFGS and LBFGS optimizers use two quantities to decide where to move the
atoms on each step:
the forces on each atom, as returned by the associated Calculator object
the Hessian matrix, i.e. the matrix of second derivatives
coordinates.
102
2E
xi xj
If the atoms are close to the minimum, such that the potential energy surface is locally quadratic, the Hessian
and forces accurately determine the required step to reach the optimal structure. The Hessian is very expensive to
calculate a priori, so instead the algorithm estimates it by means of an initial guess which is adjusted along the
way depending on the information obtained on each step of the structure optimization.
It is frequently practical to restart or continue a structure optimization with a geometry obtained from a previous
relaxation. Aside from the geometry, the Hessian of the previous run can and should be retained for the second
run. Use the restart keyword to specify a file in which to save the Hessian:
dyn = BFGS(atoms=system, trajectory=qn.traj, restart=qn.pckl)
This will create an optimizer which saves the Hessian to qn.pckl (using the Python pickle module) on each
step. If the file already exists, the Hessian will also be initialized from that file.
The trajectory file can also be used to restart a structure optimization, since it contains the history of all forces and
positions, and thus whichever information about the Hessian was assembled so far:
dyn = BFGS(atoms=system, trajectory=qn.traj)
dyn.replay_trajectory(history.traj)
This will read through each iteration stored in history.traj, performing adjustments to the Hessian as appropriate. Note that these steps will not be written to qn.traj. If restarting with more than one previous trajectory
file, use ase-gui to concatenate them into a single trajectory file first:
$ ase-gui part1.traj part2.traj -o history.traj
where the trajectory and the restart save the trajectory of the optimization and the vectors needed to generate the
Hessian Matrix.
FIRE
Read about this algorithm here:
Erik Bitzek, Pekka Koskinen, Franz Ghler, Michael Moseler, and Peter Gumbsch
Structural Relaxation Made Simple
Physical Review Letters, Vol. 97, 170201 (2006)
MDMin
The MDmin algorithm is a modification of the usual velocity-Verlet molecular dynamics algorithm. Newtons
second law is solved numerically, but after each time step the dot product between the forces and the momenta is
checked. If it is zero, the system has just passed through a (local) minimum in the potential energy, the kinetic
7.10. Structure optimization
103
energy is large and about to decrease again. At this point, the momentum is set to zero. Unlike a real molecular
dynamics, the masses of the atoms are not used, instead all masses are set to one.
The MDmin algorithm exists in two flavors, one where each atom is tested and stopped individually, and one
where all coordinates are treated as one long vector, and all momenta are set to zero if the dot product between the
momentum vector and force vector (both of length 3N) is zero. This module implements the latter version.
Although the algorithm is primitive, it performs very well because it takes advantage of the physics of the problem.
Once the system is so near the minimum that the potential energy surface is approximately quadratic it becomes
advantageous to switch to a minimization method with quadratic convergence, such as Conjugate Gradient or
Quasi Newton.
SciPy optimizers
SciPy provides a number of optimizers. An interface module for a couple of these have been written for ASE.
Most notable are the optimizers SciPyFminBFGS and SciPyFminCG. These are called with the regular syntax and
can be imported as:
from ase.optimize.sciopt import SciPyFminBFGS, SciPyFminCG
call-
Initialize object
Parameters:
callback_always: book Should the callback be run after each force call (also in the linesearch)
alpha: float Initial guess for the Hessian (curvature of energy surface). A conservative value of 70.0 is the
default, but number of needed steps to converge might be less if a lower value is used. However, a
lower value also means risk of instability.
class ase.optimize.sciopt.SciPyFminCG(atoms,
logfile=-,
trajectory=None,
back_always=False, alpha=70.0)
Non-linear (Polak-Ribiere) conjugate gradient algorithm
call-
Initialize object
Parameters:
callback_always: book Should the callback be run after each force call (also in the linesearch)
alpha: float Initial guess for the Hessian (curvature of energy surface). A conservative value of 70.0 is the
default, but number of needed steps to converge might be less if a lower value is used. However, a
lower value also means risk of instability.
See Also:
SciPyFminBFGS, SciPyFminCG
BFGSLineSearch
BFGSLineSearch is the BFGS algorithm with a line search mechanism that enforces the step taken fulfills the
Wolfe conditions, so that the energy and absolute value of the force decrease monotonically. Like the LBFGS
algorithm the inverse of the Hessian Matrix is updated.
The usage of BFGSLineSearch algorithm is similar to other BFGS type algorithms. A typical optimization should
look like:
from ase.optimize.bfgslinesearch import BFGSLineSearch
dyn = BFGSLineSearch(atoms=system, trajectory=bfgs_ls.traj, restart=bfgs_ls.pckl)
104
where the trajectory and the restart save the trajectory of the optimization and the information needed to generate
the Hessian Matrix.
Note: In many of the examples, tests, exercises and tutorials, QuasiNewton is used it is a synonym for
BFGSLineSearch.
The BFGSLineSearch algorithm is not compatible with nudged elastic band calculations.
105
This will run the algorithm until 10 steps are taken; alternatively, if totalsteps is not specified the algorithm will
run indefinitely (or until stopped by a batch system). A number of optional arguments can be fed when initializing
the algorithm as keyword pairs. The keywords and default values are:
T0: 1000., # K, initial MD temperature
beta1: 1.1, # temperature adjustment parameter
beta2: 1.1, # temperature adjustment parameter
beta3: 1. / 1.1, # temperature adjustment parameter
Ediff0: 0.5, # eV, initial energy acceptance threshold
alpha1 : 0.98, # energy threshold adjustment parameter
alpha2 : 1. / 0.98, # energy threshold adjustment parameter
mdmin : 2, # criteria to stop MD simulation (no. of minima)
logfile: hop.log, # text log
minima_threshold : 0.5, # A, threshold for identical configs
timestep : 1.0, # fs, timestep for MD simulations
optimizer : QuasiNewton, # local optimizer to use
minima_traj : minima.traj, # storage file for minima list
Specific definitions of the alpha, beta, and mdmin parameters can be found in the publication by Goedecker.
minima_threshold is used to determine if two atomic configurations are identical; if any atom has moved by
more than this amount it is considered a new configuration. Note that the code tries to do this in an intelligent
manner: atoms are considered to be indistinguishable, and translations are allowed in the directions of the periodic
boundary conditions. Therefore, if a CO is adsorbed in an ontop site on a (211) surface it will be considered
identical no matter which ontop site it occupies.
The trajectory file minima_traj will be populated with the accepted minima as they are found. A log of the
progress is kept in logfile.
The code is written such that a stopped simulation (e.g., killed by the batching system when the maximum wall
time was exceeded) can usually be restarted without too much effort by the user. In most cases, the script can be
resubmitted without any modification if the logfile and minima_traj are found, the script will attempt
to use these to resume. (Note that you may need to clean up files left in the directory by the calculator, however,
such as the .nc file produced by Jacapo.)
Note that these searches can be quite slow, so it can pay to have multiple searches running at a time. Multiple
searches can run in parallel and share one list of minima. (Run each script from a separate directory but specify
the location to the same absolute location for minima_traj). Each search will use the global information of the
list of minima, but will keep its own local information of the initial temperature and Ediff .
For an example of use, see the Constrained minima hopping (global optimization) tutorial.
7.12 Visualization
ase.visualize.view(atoms, data=None, viewer=None, repeat=None)
106
This provides an interface to various visualization tools, such as ase.gui, ase.visualize.vtk, RasMol,
VMD, VTK, gOpenMol, or Avogadro. The default viewer is the ase.gui, described in the ase.gui module. The
simplest invocation is:
>>> from ase import view
>>> view(atoms)
where atoms is any Atoms object. Alternative viewers can be used by specifying the optional keyword
viewer=... - use one of ase.gui, gopenmol, vmd, or rasmol. The VMD and Avogadro viewers can
take an optional data argument to show 3D data, such as charge density:
>>> view(atoms, viewer=VMD, data=array)
If you do not wish to open an interactive gui, but rather visualize your structure by dumping directly to a graphics
file; you can use the write command of the ase.io module, which can write eps, png, and pov files
directly, like this:
>>> write(image.png, atoms)
7.12.1 VTK
The Visualization Toolkit (VTK) is a powerful platform-independent graphics engine, which comes as an open
source graphics toolkit licensed under the BSD license. It is available for a wide range of programming languages,
including easily scriptable interfaces in Python and Tcl.
In the scientific community, VTK is used by thousands of researchers and developers for 3D computer graphics,
image processing, and visualization. VTK includes a suite of 3D interaction widgets within the development
framework for information visualization, integrating GUI toolkits such as Qt and Tk into a highly flexible design
platform.
For visualization purposes within ASE, two different VTK-approaches are supported, namely:
Scripted on-the-fly rendering ASE includes VTK-scripting for easy data visualization using the
vtk module. Development is in progress, so you might want to check out the latest development
release from SVN (see Latest development release).
Interactive rendering MayaVi is an easy-to-use GUI for VTK. With Enthoughts traits-based VTKwrapper (TVTK), constructing VTK pipelines has been simplified greatly by introducing three
basic concepts: data sources, filters and visualization modules. MayaVi also supports the VTK
file formats, including the flexible VTK XML, which in ASE can be used to export atomic
positions, forces and volume data using the write command in the io module.
A key feature of VTK is the inherent ability to use MPI for parallel rending, which is provided with built-in
parallel composite rendering objects to handle domain decomposition and subsequent recombination of the raster
information. This is particularly useful for non-interactive ray tracing, batch isosurface generation and in-situ
visualization of simulation data in cluster computing.
See Also:
ParaView is a VTK-based open-source, multi-platform data analysis and visualization application for extremely
large data-sets using distributed memory computing resources and parallel rendering through MPI.
7.12.2 PrimiPlotter
The PrimiPlotter is intended to do on-the-fly plotting of the positions of the atoms during long molecular dynamics
simulations. The module ase.visualize.primiplotter contains the PrimiPlotter and the various output
modules, see below.
class ase.visualize.primiplotter.PrimiPlotter(atoms, verbose=0, timing=0, interval=1,
initframe=0)
Primitive PostScript-based plots during a simulation.
7.12. Visualization
107
The PrimiPlotter plots atoms during simulations, extracting the relevant information from the list of atoms.
It is created using the list of atoms as an argument to the constructor. Then one or more output devices must
be attached using set_output(device). The list of supported output devices is at the end.
The atoms are plotted as circles. The system is first rotated using the angles specified by set_rotation([vx,
vy, vz]). The rotation is vx degrees around the x axis (positive from the y toward the z axis), then vy degrees
around the y axis (from x toward z), then vz degrees around the z axis (from x toward y). The rotation
matrix is the same as the one used by RasMol.
Per default, the system is scaled so it fits within the canvas (autoscale mode). Autoscale mode is enabled and
disables using autoscale(on) or autoscale(off). A manual scale factor can be set with set_scale(scale),
this implies autoscale(off). The scale factor (from the last autoscale event or from set_scale) can be
obtained with get_scale(). Finally, an explicit autoscaling can be triggered with autoscale(now), this is
mainly useful before calling get_scale or before disabling further autoscaling. Finally, a relative scaling
factor can be set with SetRelativeScaling(), it is multiplied to the usual scale factor (from autoscale or from
set_scale). This is probably only useful in connection with autoscaling.
The radii of the atoms are obtained from the first of the following methods which work:
1.If the radii are specified using PrimiPlotter.set_radii(r), they are used. Must be an array, or a single
number.
2.If the atoms has a get_atomic_radii() method, it is used. This is unlikely.
3.If the atoms has a get_atomic_numbers() method, the corresponding covalent radii are extracted from
the ASE.ChemicalElements module.
4.If all else fails, the radius is set to 1.0 Angstrom.
The atoms are colored using the first of the following methods which work.
1.If colors are explicitly set using PrimiPlotter.set_colors(), they are used.
2.If these colors are specified as a dictionary, the tags (from atoms.get_tags()) are used as an index into
the dictionary to get the actual colors of the atoms.
3.If a color function has been set using PrimiPlotter.set_color_function(), it is called with the atoms as
an argument, and is expected to return an array of colors.
4.If the atoms have a get_colors() method, it is used to get the colors.
5.If these colors are specified as a dictionary, the tags (from atoms.get_tags()) are used as an index into
the dictionary to get the actual colors of the atoms.
6.If all else fails, the atoms will be white.
The colors are specified as an array of colors, one color per atom. Each color is either a real number from
0.0 to 1.0, specifying a grayscale (0.0 = black, 1.0 = white), or an array of three numbers from 0.0 to 1.0,
specifying RGB values. The colors of all atoms are thus a Numerical Python N-vector or a 3xN matrix.
In cases 1a and 3a above, the keys of the dictionary are integers, and the values are either numbers
(grayscales) or 3-vectors (RGB values), or strings with X11 color names, which are then translated to RGB
values. Only in case 1a and 3a are strings recognized as colors.
Some atoms may be invisible, and thus left out of the plot. Invisible atoms are determined from the following
algorithm. Unlike the radius or the coloring, all points below are tried and if an atom is invisible by any
criterion, it is left out of the plot.
1.All atoms are visible.
2.If PrimiPlotter.set_invisible() has be used to specify invisible atoms, any atoms for which the value is
non-zero becomes invisible.
3.If an invisiblility function has been set with PrimiPlotter.set_invisibility_function(), it is called with
the atoms as argument. It is expected to return an integer per atom, any non-zero value makes that
atom invisible.
4.If a cut has been specified using set_cut, any atom outside the cut is made invisible.
108
Note that invisible atoms are still included in the algorithm for positioning and scaling the plot.
The following output devices are implemented.
PostScriptFile(prefix): Create PS files names prefix0000.ps etc.
PnmFile(prefix): Similar, but makes PNM files.
GifFile(prefix): Similar, but makes GIF files.
JpegFile(prefix): Similar, but makes JPEG files.
X11Window(): Show the plot in an X11 window using ghostscript.
Output devices writing to files take an extra optional argument to the constructor, compress, specifying if
the output file should be gzipped. This is not allowed for some (already compressed) file formats.
Instead of a filename prefix, a filename containing a % can be used. In that case the filename is expected to
expand to a real filename when used with the Python string formatting operator (%) with the frame number
as argument. Avoid generating spaces in the file names: use e.g. %03d instead of %3d.
Parameters to the constructor:
atoms: The atoms to be plottet.
verbose = 0: Write progress information to stderr.
timing = 0: Collect timing information.
interval = 1: If specified, a plot is only made every intervalth time update() is called. Deprecated, normally
you should use the interval argument when attaching the plotter to e.g. the dynamics.
initframe = 0: Initial frame number, i.e. the number of the first plot.
log(message)
logs a message to the file set by set_log.
plot()
Create a plot now. Does not respect the interval timer.
This method makes a plot unconditionally. It does not look at the interval variable, nor is this plot
taken into account in the counting done by the update() method if an interval variable was specified.
set_color_function(colors)
Set a color function, to be used to color the atoms.
set_colors(colors)
Explicitly set the colors of the atoms.
The colors can either be a dictionary mapping tags to colors or an array of colors, one per atom.
Each color is specified as a greyscale value from 0.0 to 1.0 or as three RGB values from 0.0 to 1.0.
set_dimensions(dims)
Set the size of the canvas (a 2-tuple).
set_invisibility_function(invfunc)
Set an invisibility function.
set_invisible(inv)
Choose invisible atoms.
set_log(log)
Sets a file for logging.
log may be an open file or a filename.
set_output(device)
Attach an output device to the plotter.
set_radii(radii)
Set the atomic radii. Give an array or a single number.
7.12. Visualization
109
set_rotation(rotation)
Set the rotation angles (in degrees).
update(newatoms=None)
Cause a plot (respecting the interval setting).
update causes a plot to be made. If the interval variable was specified when the plotter was create, it
will only produce a plot with that interval. update takes an optional argument, newatoms, which can
be used to replace the list of atoms with a new one.
7.12.3 FieldPlotter
The FieldPlotter is intended to plot fields defined on the atoms in large-scale simulations. The fields could be e.g.
pressure, stress or temperature (kinetic energy), i.e. any quantity that in a given simulation is best defined on a
per-atom basis, but is best interpreted as a continuum field.
The current version of FieldPlotter only works if the number of atoms is at least 5-10 times larger than the number
of pixels in the plot.
class ase.visualize.fieldplotter.FieldPlotter(atoms, datasource=None, verbose=0,
timing=0, interval=1, initframe=0)
log(message)
logs a message to the file set by set_log.
plot(data=None)
Create a plot now. Does not respect the interval timer.
This method makes a plot unconditionally. It does not look at the interval variable, nor is this plot
taken into account in the counting done by the update() method if an interval variable was specified.
If data is specified, it must be an array of numbers with the same length as the atoms. That data will
then be plotted. If no data is given, the data source specified when creating the plotter is used.
set_background(value)
Set the data value of the background. See also set_background_color
Set the value of the background (parts of the plot without atoms) to a specific value, or to min or
max representing the minimal or maximal data values on the atoms.
Calling set_background cancels previous calls to set_background_color.
set_background_color(color)
Set the background color. See also set_background.
Set the background color. Use a single value in the range [0, 1[ for gray values, or a tuple of three such
values as an RGB color.
Calling set_background_color cancels previous calls to set_background.
set_black_white_colors(reverse=False)
Set the color to Black-White (greyscale)
set_color_function(colors)
Set a color function, to be used to color the atoms.
set_data_range(range1, range2=None)
Set the range of the data used when coloring.
This function sets the range of data values mapped unto colors in the final plot.
Three possibilities:
data: Autoscale using the data on visible atoms. The range goes from the lowest to the highest
value present on the atoms. If only a few atoms have extreme values, the entire color range may
not be used on the plot, as many values may be averaged on each point in the plot.
110
plot: Autoscale using the data on the plot. Unlike data this guarantees that the entire color
range is used.
min, max: Use the range [min, max]
set_dimensions(dims)
Set the size of the canvas (a 2-tuple).
set_invisibility_function(invfunc)
Set an invisibility function.
set_invisible(inv)
Choose invisible atoms.
set_log(log)
Sets a file for logging.
log may be an open file or a filename.
set_output(device)
Attach an output device to the plotter.
set_plot_plane(plane)
Set the plotting plane to xy, xz or yz (default: xy)
set_radii(radii)
Set the atomic radii. Give an array or a single number.
set_red_yellow_colors(reverse=False)
Set colors to Black-Red-Yellow-White (a.k.a. STM colors)
set_rotation(rotation)
Set the rotation angles (in degrees).
update(newatoms=None)
Cause a plot (respecting the interval setting).
update causes a plot to be made. If the interval variable was specified when the plotter was create, it
will only produce a plot with that interval. update takes an optional argument, newatoms, which can
be used to replace the list of atoms with a new one.
7.13 ASE-VTK
For ASE, the vtk interface consists of Python modules for automatic visualization of positions, bonds, forces and
volume data (e.g. wave functions) from an Atoms object, provided such data is made available by the calculator.
Note: The Python modules in ASE are intended to wrap lower-level functionality of the VTK object models
in small and easy-to-comprehend classes. To be able to distinguish between build-in VTK objects and their
wrappers, and because VTK uses the CamelCase naming convention whereas ASE uses lower-case cf. our coding
conventions, all variables referring to VTK built-in types are prefixed by vtk_. However, both VTK and wrapper
classes are named according to the standard vtkFooBar.
7.13. ASE-VTK
111
Example:
>>>
>>>
>>>
>>>
va = vtkAtoms(atoms)
va.add_forces()
va.add_axes()
XXX va.add_to_renderer(vtk_ren)
cell = vtkUnitCellModule(atoms)
apos = vtkAtomicPositions(atoms.get_positions(), cell)
apos.add_scalar_property(atoms.get_charges(), charges)
apos.add_vector_property(atoms.get_forces(), forces)
112
atoms = molecule(C60)
cell = vtkUnitCellModule(atoms)
apos = vtkAtomicPositions(atoms.get_positions(), cell)
vtk_ugd = apos.get_unstructured_grid()
glyph_source = vtkAtomSource(C)
glyph_module = vtkGlyphModule(vtk_ugd, glyph_source)
Construct VTK-representation of a module containing glyphs. These glyphs share a common source, defining their geometrical shape, which is cloned and oriented according to the input data.
vtk_pointset: Instance of vtkPointSet or subclass thereof A vtkPointSet defines a set of positions,
which may then be assigned specific scalar of vector data across the entire set.
glyph_source: Instance of ~vtk.vtkCustomGlyphSource or subclass thereof Provides the basic shape
to distribute over the point set.
get_actor()
Return the actor representing this module in a rendering scene.
set_actor(vtk_act)
Set the actor representing this module in a rendering scene.
set_property(vtk_property)
Set the property of the actor representing this module.
7.13. ASE-VTK
113
7.14 Calculators
For ASE, a calculator is a black box that can take atomic numbers and atomic positions from an Atoms object
and calculate the energy and forces and sometimes also stresses.
In order to calculate forces and energies, you need to attach a calculator object to your atoms object:
>>> a = read(molecule.xyz)
>>> e = a.get_potential_energy()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jjmo/ase/ase/atoms.py", line 399, in get_potential_energy
raise RuntimeError(Atoms object has no calculator.)
RuntimeError: Atoms object has no calculator.
>>> from ase.calculators.abinit import Abinit
>>> calc = Abinit(...)
>>> a.set_calculator(calc)
>>> e = a.get_potential_energy()
>>> print e
-42.0
or this:
atoms.calc = Abinit(...)
114
name
Asap
GPAW
Hotbit
abinit
castep
dftb
eam
elk
exciting
aims
fleur
gaussian
gromacs
jacapo
lammps
mopac ...
nwchem
siesta
turbomole
vasp
emt
lj
morse
description
Highly efficient EMT code
Real-space/plane-wave/LCAO PAW code
DFT based tight binding
Plane-wave pseudopotential code
Plane-wave pseudopotential code
DFT based tight binding
Embedded Atom Method
Full Potential LAPW code
Full Potential LAPW code
Numeric atomic orbital, full potential code
Full Potential LAPW code
Gaussian based electronic structure code
Classical molecular dynamics code
Plane-wave ultra-soft pseudopotential code
Classical molecular dynamics code
Gaussian based electronic structure code
LCAO pseudopotential code
Fast atom orbital code
Plane-wave PAW code
Effective Medium Theory calculator
Lennard-Jones potential
Morse potential
where abc is the module name and ABC is the class name.
7.14. Calculators
115
The Embedded Atom Method (EAM) 1 is a classical potential which is good for modelling metals, particularly
fcc materials. Because it is an equiaxial potential the EAM does not model directional bonds well. However, the
Angular Dependent Potential (ADP) 2 which is an extended version of EAM is able to model directional bonds
and is also included in the EAM calculator.
Generally all that is required to use this calculator is to supply a potential file or as a set of functions that describe
the potential. The files containing the potentials for this calculator are not included but many suitable potentials
can be downloaded from The Interatomic Potentials Repository Project at http://www.ctcms.nist.gov/potentials/
Theory
A single element EAM potential is defined by three functions: the embedded energy, electron density and the pair
potential. A two element alloy contains the individual three functions for each element plus cross pair interactions.
The ADP potential has two additional sets of data to define the dipole and quadrupole directional terms for each
alloy and their cross interactions.
The total energy Etot of an arbitrary arrangement of atoms is given by the EAM potential as
Etot =
X
i
1
2
F (
i ) +
1X
(rij )
2
i6=j
M.S. Daw and M.I. Baskes, Phys. Rev. Letters 50 (1983) 1285.
Y. Mishin, M.J. Mehl, and D.A. Papaconstantopoulos, Acta Materialia 53 2005 40294041.
116
and
i =
(rij )
where F is an embedding function, namely the energy to embed an atom i in the combined electron density
i which is contributed from each of its neighbouring atoms j by an amount (rij ), (rij ) is the pair potential
function representing the energy in bond ij which is due to the short-range electro-static interaction between
atoms, and rij is the distance between an atom and its neighbour for that bond.
The ADP potential is defined as
Etot =
F (
i ) +
1 X 2 1 X 2 1 X 2
1X
(rij ) +
( ) +
(i )
2
2 i, i
2
6 i i
i6=j
i,,
where
i is the dipole vector, i is the quadrupole tensor and i is the trace of i .
EAM calculates the cohesive atom energy and forces. Internally the potential functions are defined by splines
which may be directly supplied or created by reading the spline points from a data file from which a spline
function is created. The LAMMPS compatible .alloy and .adp formats are supported. The LAMMPS .eam
format is slightly different from the .alloy format and is currently not supported.
For example:
from ase.calculators.eam import EAM
mishin = EAM(potential=Al99.eam.alloy)
mishin.write_potential(new.eam.alloy)
mishin.plot()
slab.set_calculator(mishin)
slab.get_potential_energy()
slab.get_forces()
The breakdown of energy contribution from the indvidual components are stored in the calculator instance
.results[energy_components]
7.14. Calculators
117
Arguments
Keyword
Description
potential
file of potential in .alloy or .adp format (This is generally all you need to supply)
elements[N] array of N element abbreviations
embedded_energy[N]
arrays of embedded energy functions
electron_density[N]
arrays of electron density functions
phi[N,N]
arrays of pair potential functions
d_embedded_energy[N]
arrays of derivative embedded energy functions
d_electron_density[N]
arrays of derivative electron density functions
d_phi[N,N]
arrays of derivative pair potentials functions
d[N,N],
ADP dipole and quadrupole function
q[N,N]
d_d[N,N],
ADP dipole and quadrupole derivative functions
d_q[N,N]
skin
skin distance passed to NeighborList(). If no atom has moved more than the skin-distance
since the last call to the update() method then the neighbor list can be reused. Defaults
to 1.0.
form
the form of the potential alloy or adp. This will be determined from the file suffix or
must be set if using equations
Additional parameters for writing potential files
The following parameters are only required for writing a potential in .alloy or .adp format file.
Keyword
header
Z[N]
mass[N]
a[N]
lattice[N]
nrho
drho
nr
dr
Description
Three line text header. Default is standard message.
Array of atomic number of each element
Atomic mass of each element
Array of lattice parameters for each element
Lattice type
No. of rho samples along embedded energy curve
Increment for sampling density
No. of radial points along density and pair potential curves
Increment for sampling radius
Special features
.plot() Plots the individual functions. This may be called from multiple EAM potentials to compare the shape
of the individual curves. This function requires the installation of the Matplotlib libraries.
Notes/Issues
Although currently not fast, this calculator can be good for trying small calculations or for creating new
potentials by matching baseline data such as from DFT results. The format for these potentials is compatible
with LAMMPS and so can be used either directly by LAMMPS or with the ASE LAMMPS calculator
interface.
Supported formats are the LAMMPS .alloy and .adp. The .eam format is currently not supported.
The form of the potential will be determined from the file suffix.
Any supplied values will override values read from the file.
The derivative functions, if supplied, are only used to calculate forces.
There is a bug in early versions of scipy that will cause eam.py to crash when trying to evaluate splines of a
potential with one neighbor such as caused by evaluating a dimer.
118
Example:
import numpy as np
from ase.calculators.eam import EAM
from ase.lattice import bulk
# test to generate an EAM potential file using a simplified
# approximation to the Mishin potential Al99.eam.alloy data
from scipy.interpolate import InterpolatedUnivariateSpline as spline
cutoff = 6.28721
n = 21
rs = np.arange(0, n) * (cutoff / n)
rhos = np.arange(0, 2, 2. / n)
#
#
#
#
#
generated from
mishin = EAM(potential=../potentials/Al99.eam.alloy)
m_density = mishin.electron_density[0](rs)
m_embedded = mishin.embedded_energy[0](rhos)
m_phi = mishin.phi[0,0](rs)
m_density = np.array([2.78589606e-01,
1.06069912e-01,
7.76263116e-02,
8.13915861e-02,
2.27910928e-02,
3.65836583e-03,
1.48749693e-03,
2.02694937e-01,
8.42517168e-02,
8.23214224e-02,
6.59095390e-02,
1.13713167e-02,
2.60587564e-03,
7.40019174e-04,
1.45334053e-01,
7.65140344e-02,
8.53322309e-02,
4.28915711e-02,
6.05020311e-03,
2.06750708e-03,
6.21225205e-05])
7.14. Calculators
119
al.set_calculator(mishin_approx)
mishin_approx_energy = al.get_potential_energy()
mishin_approx.write_potential(Al99-test.eam.alloy)
mishin_check = EAM(potential=Al99-test.eam.alloy)
al.set_calculator(mishin_check)
mishin_check_energy = al.get_potential_energy()
print Cohesive Energy for Al = , mishin_approx_energy, eV
error = (mishin_approx_energy - mishin_check_energy) / mishin_approx_energy
print read/write check error = , error
assert abs(error) < 1e-4
ASE_ABINIT_COMMAND
Must be set to something like this:
abinis < PREFIX.files > PREFIX.log
120
export ABINIT_PP_PATH=$PP/GGA_FHI:$ABINIT_PP_PATH
export ABINIT_PP_PATH=$PP/GGA_HGHK:$ABINIT_PP_PATH
export ABINIT_PP_PATH=$PP/GGA_PAW:$ABINIT_PP_PATH
ABINIT Calculator
Abinit does not specify a default value for the plane-wave cutoff energy. You need to set them as in the example
at the bottom of the page, otherwise calculations will fail. Calculations wihout k-points are not parallelized by
default and will fail! To enable band paralellization specify Number of BanDs in a BLOCK (nbdblock)
see http://www.abinit.org/Infos_v5.2/tutorial/lesson_parallelism.html.
Pseudopotentials
Pseudopotentials in the ABINIT format are available on the pseudopotentials website. A database of user contributed pseudopotentials is also available there.
Example 1
Here is an example of how to calculate the total energy for bulk Silicon ase/test/abinit/abinit_Si.py.
CASTEP
Introduction
CASTEP 3 W is a software package which uses density functional theory to provide a good atomic-level description of all manner of materials and molecules. CASTEP can give information about total energies, forces and
stresses on an atomic system, as well as calculating optimum geometries, band structures, optical spectra, phonon
spectra and much more. It can also perform molecular dynamics simulations.
The CASTEP calculator interface class offers intuitive access to all CASTEP settings and most results. All
CASTEP specific settings are accessible via attribute access (i.e. calc.param.keyword = ... or
calc.cell.keyword = ...)
Getting Started:
Note: alternatively to CASTEP_PP_PATH one can set PSPOT_DIR as CASTEP consults this by default, i.e.
>>> export PSPOT_DIR= ...
7.14. Calculators
121
To do a minimal run one only needs to set atoms, this will use all default settings of CASTEP, meaning LDA,
singlepoint, etc..
With a generated castep_keywords.py in place all options are accessible by inspection, i.e. tab-completion.
This works best when using ipython.
All options can be accessed via calc.param.<TAB>
or calc.cell.<TAB> and documentation is printed with calc.param.<keyword> ?
or
calc.cell.<keyword> ?. All options can also be set directly using calc.keyword = ... or
calc.KEYWORD = ... or even calc.KeYwOrD or directly as named arguments in the call to the
constructor (e.g. Castep(task=GeometryOptimization)).
All options that go into the .param file are held in an CastepParam instance, while all options that go into
the .cell file and dont belong to the atoms object are held in an CastepCell instance. Each instance can
be created individually and can be added to calculators by attribute assignment, i.e. calc.param = param or
calc.cell = cell.
All internal variables of the calculator start with an underscore (_). All cell attributes that clearly belong into
the atoms object are blocked. Setting calc.atoms_attribute (e.g. = positions) is sent directly to the
atoms object.
Arguments:
KeyDescription
word
directory
The relative path where all input and output files will be placed. If this does not exist, it will be
created. Existing directories will be moved to directory-TIMESTAMP unless
self._rename_existing_dir is set to false.
label The prefix of .param, .cell, .castep, etc. files.
122
Additional Settings
Internal
Description
Setting
_castep_command
(=castep): the actual shell command used to call CASTEP.
_check_checkfile
(=True): this makes write_param() only write a continue or reuse statement if the
addressed .check or .castep_bin file exists in the directory.
_copy_pspots (=False): if set to True the calculator will actually copy the needed pseudo-potential
(*.usp) file, usually it will only create symlinks.
_export_settings
(=True): if this is set to True, all calculator internal settings shown here will be included
in the .param in a comment line (#) and can be read again by merge_param. merge_param
can be forced to ignore this directive using the optional argument
ignore_internal_keys=True.
_force_write (=True): this controls wether the *cell and *param will be overwritten.
_prepare_input_only
(=False): If set to True, the calculator will create *cell und *param file but not start the
calculation itself. If this is used to prepare jobs locally and run on a remote cluster it is
recommended to set _copy_pspots = True.
_castep_pp_path
(=.) : the place where the calculator will look for pseudo-potential files.
_rename_existing_dir
(=True) : when using a new instance of the calculator, this will move directories out of
the way that would be overwritten otherwise, appending a date string.
_set_atoms
(=False) : setting this to True will overwrite any atoms object previously attached to the
calculator when reading a .castep file. By de- fault, the read() function will only create a
new atoms object if none has been attached and other- wise try to assign forces etc. based
on the atoms positions. _set_atoms=True could be necessary if one uses CASTEPs
internal geometry optimization (calc.param.task=GeometryOptimization)
because then the positions get out of sync. Warning: this option is generally not
recommended unless one knows one really needs it. There should never be any need, if
CASTEP is used as a single-point calculator.
_track_output(=False) : if set to true, the interface will append a number to the label on all input and
output files, where n is the number of calls to this instance. Warning: this setting may consume a lot more disk space because of the additio- nal *check files.
_try_reuse
(=_track_output) : when setting this, the in- terface will try to fetch the reuse file
from the previous run even if _track_output is True. By de- fault it is equal to
_track_output, but may be overridden.
Since this behavior may not always be desirable for single-point calculations. Regular
reuse for e.g. a geometry-optimization can be achieved by setting calc.param.reuse
= True.
Special features:
.dryrun_ok() Runs castep_command seed -dryrun in a temporary directory return True if all variables initialized ok. This is a fast way to catch errors in the input. Afterwards _kpoints_used is set.
.merge_param() Takes a filename or filehandler of a .param file or CastepParam instance and merges it into
the current calculator instance, overwriting current settings
.keyword.clear() Can be used on any option like calc.param.keyword.clear() or
calc.cell.keyword.clear() to return to the CASTEP default.
.initialize() Creates all needed input in the _directory. This can then copied to and run in a place
without ASE or even python.
.set_pspot(<library>) This automatically sets the pseudo-potential for all present species to
<Species>_<library>.usp. Make sure that _castep_pp_path is set correctly.
print(calc) Prints a short summary of the calculator settings and atoms.
ase.io.castep.read_seed(path-to/seed) Given
you
have
a
combination
of
seed.{param,cell,castep} this will return an atoms object with the last ionic positions in the .castep
7.14. Calculators
123
file and all other settings parsed from the .cell and .param file. If no .castep file is found the positions are
taken from the .cell file. The output directory will be set to the same directory, only the label is preceded
by copy_of_ to avoid overwriting.
Notes/Issues:
Currently only the FixAtoms constraint is fully supported for reading and writing.
There is no support for the CASTEP unit system. Units of eV and Angstrom are used throughout. In particular when converting total energies from different calculators, one should check that the same CODATA
version is used for constants and conversion factors, respectively.
Example:
"""This simple demo calculates the total energy of CO molecules
using once LDA and once PBE as xc-functional. Obviously
some parts in this scripts are longer than necessary, but are shown
to demonstrate some more features."""
import ase
import ase.calculators.castep, ase.io.castep
calc = ase.calculators.castep.Castep()
directory = CASTEP_ASE_DEMO
# include interface settings in .param file
calc._export_settings = True
# reuse the same directory
calc._directory = directory
calc._rename_existing_dir = False
calc._label = CO_LDA
# necessary for tasks with changing positions
# such as GeometryOptimization or MolecularDynamics
calc._set_atoms = True
# Param settings
calc.param.xc_functional = LDA
calc.param.cut_off_energy = 400
# Prevent CASTEP from writing *wvfn* files
calc.param.num_dump_cycles = 0
# Cell settings
calc.cell.kpoint_mp_grid = 1 1 1
calc.cell.fix_com = False
calc.cell.fix_all_cell = True
# Set and clear and reset settings (just for shows)
calc.param.task = SinglePoint
# Reset to CASTEP default
calc.param.task.clear()
# all of the following are identical
calc.param.task = GeometryOptimization
calc.task = GeometryOptimization
calc.TASK = GeometryOptimization
calc.Task = GeometryOptimization
124
# Prepare atoms
mol = ase.atoms.Atoms(CO, [[0, 0, 0], [0, 0, 1.2]], cell=[10, 10, 10])
mol.set_calculator(calc)
# Check for correct input
if calc.dryrun_ok():
print(%s : %s % (mol.calc._label, mol.get_potential_energy()))
else:
print("Found error in input")
print(calc._error)
DftbPlus
Introduction
DftbPlus is a density-functional based tight-binding code using atom centered orbitals. This interface makes it
possible to use DftbPlus as a calculator in ASE. You need to register at DftbPlus site to download the code.
Additionally you need Slater-Koster files for the combination of atom types of your system. These can be obtained
at dftb.org.
Environment variables
Set environment variables in your configuration file (what is the directory for the Slater-Koster files and what is
the name of the executable):
bash:
$ DFTB_PREFIX=/my_disk/my_name/lib/Dftb+sk/mio-0-1/
$ DFTB_COMMAND=~/bin/DFTB+/dftb+_s081217.i686-linux
(an example)
(an example)
csh/tcsh:
$ setenv DFTB_PREFIX /my_disk/my_name/lib/Dftb+sk/mio-0-1/
$ setenv DFTB_COMMAND ~/bin/DFTB+/dftb+_s081217.i686-linux
(an example)
(an example)
The file geom.out.gen contains the input and output geometry and it will be updated during the dftb calculations.
If restart == None it is assumed that a new input file dftb_hsd.in will be written by ase using default keywords
and the ones given by the user.
If restart != None it is assumed that keywords are in file restart
All Keywords to the dftb calculator can be set by ase.
7.14. Calculators
125
Parameters
restart: str (default None) If restart == None it is assumed that a new input file dftb_hsd.in will
be written by ase using default keywords and the ones given by the user.
If restart != None it is assumed that keywords are in file restart
ignore_bad_restart_file: bool (default False) Ignore broken or missing restart file. By defauls, it is
an error if the restart file is missing or broken.
label: str (default dftb) Name used for all files. May contain a directory.
atoms: Atoms object (default None) Optional Atoms object to which the calculator will be attached. When restarting, atoms will get its positions and unit-cell updated from file.
kpts: (default None) Brillouin zone sampling:
(1,1,1): Gamma-point
(n1,n2,n3): Monkhorst-Pack grid
(n1,n2,n3,gamma): Shifted Monkhorst-Pack grid that includes
[(k11,k12,k13),(k21,k22,k23),...]: Explicit list in units of the reciprocal
lattice vectors
kpts=3.5: ~k-point density as in 3.5 ~k-points per 1 .
run_manyDftb_steps: bool (default False) If True the Dftb calculator is running many steps by its
own. If False all the relaxations/ molecular dynamis is done by ASE
Example: Geometry Optimization by ASE
from ase.calculators.dftb import Dftb
from ase.optimize import QuasiNewton
from ase.io import write
from ase.structure import molecule
test = molecule(H2O)
test.set_calculator(Dftb(label=h2o,
atoms=test,
Hamiltonian_MaxAngularMomentum_=,
Hamiltonian_MaxAngularMomentum_O="p",
Hamiltonian_MaxAngularMomentum_H="s",
))
dyn = QuasiNewton(test, trajectory=test.traj)
dyn.run(fmax=0.01)
write(test.final.xyz, test)
126
test = molecule(H2O)
test.set_calculator(Dftb(label=h2o,atoms=test,
run_manyDftb_steps = True,
Driver_=ConjugateGradient,
Driver_MaxForceComponent=1E-4,
Driver_MaxSteps=1000,
Hamiltonian_MaxAngularMomentum_ = ,
Hamiltonian_MaxAngularMomentum_O = "p",
Hamiltonian_MaxAngularMomentum_H = "s",
))
dyn = QuasiNewton(test, trajectory=test.traj)
dyn.run(fmax=100, steps=0)
test = read(geo_end.gen)
write(test.final.xyz, test)
This is unphysical because of at least two reasons - oxygen does not have spin here - the berendsen coupling is too
strong (0.01 here should be 0.0001) .. literalinclude:: dftb_ex3_make_2h2o.py
exciting
Introduction
exciting is a full-potential all-electron density-functional-theory (DFT) package based on the linearized augmented planewave (LAPW) method. It can be applied to all kinds of materials, irrespective of the atomic species
involved, and also allows for the investigation of the core region. The website is http://exciting-code.org/
The module depends on lxml http://lxml.de
There are two ways to construct the exciting calculator.
1. Using keyword arguments to specify groundstate attributes
2. Use paramdict to specify an input file structure with a data structure of dictionaries.
Constructor with Groundstate Keywords One is by giving parameters of the ground state in the constructor.
The possible attributes can be found at http://exciting-code.org/ref:groundstate
class ase.calculators.exciting.Exciting(bin=excitingser,
xctype=LDA_PW)
kpts=(4,
4,
4),
Parameter Dictionary When the paramdict keyword is used, the calculator translates the dictionary given
into the exciting XML file format. Note $EXCITINGROOT environmental variable should be set: details at
http://exciting-code.org/tutorials
import os
from ase import Atoms
from ase.calculators.exciting import Exciting
# test structure, not real
a = Atoms(N3O, [(0, 0, 0), (1, 0, 0), (0, 0, 1), (0.5, 0.5, 0.5)], pbc=True)
calculator = Exciting(
7.14. Calculators
127
dir=excitingtestfiles,
speciespath=os.environ[EXCITINGROOT]+/species,
paramdict={title:{text():N3O},
groundstate:{ngridk:1 2 3,tforce:true},
relax:{},
properties:{dos:{},
bandstructure:
{plot1d:{path:{steps:100,
point:
[{coord:0.75000
0.50000
0.25000, label:W},
{coord:0.50000
0.50000
0.50000, label:L},
{coord:0.00000
0.00000
0.00000, label:G},
{coord:0.50000
0.50000
0.00000, label:X},
{coord:0.75000
0.50000
0.25000, label:W},
{coord:0.75000
0.37500
0.37500, label:K}]
}}}}})
calculator.write(a)
The calculator constructure above is used to create this exciting input file:
The translation follows the following rules: String values are translated to attributes. Nested dictionaries are
translated to sub elements. A list of dictionaries is translated to a list of sub elements named after the key of which
the list is the value. The special key text() results in text content of the enclosing tag.
128
Sometimes it is necessary to specify a fixed muffin tin radius different from the default. The muffin tin radii can
be set by adding a custom array to the atoms object with the name rmt:
atoms.new_array(rmt, np.array([-1.0, -1.0, 2.3, 2.0] * Bohr))
Each entry corresponds to one atom. If the rmt value is negative, the default value is used. This array is correctly
updated if the atoms are added or removed.
Exciting Calculator Class
FHI-aims is a all-electron full-potential density functional theory code using a numeric local orbital basis set. This
interface provides all that should be required to run FHI-aims from within ASE.
Running the Calculator
7.14. Calculators
129
Two general options might come in useful to post process the output:
keyword
description
output_template
Base name for the output, in case the calculator is called multiple times within a single
script.
track_output True/False - if True all the output files will be kept, while the number of calls to the
calculator is encoded in the output file name.
List of keywords
This is a non-exclusive list of keywords for the control.in file that can be addresses from within ASE. The
meaning for these keywords is exactly the same as in FHI-aims, please refer to its manual for help on their use.
One thing that should be mentioned is that keywords with more than one option have been implemented as lists, eg.
k_grid=(12,12,12) or relativistic=(atomic_zora,scalar). In those cases, specifying a
single string containing all the options is also possible.
None of the keywords have any default within ASE,but do check the defaults set by FHI-aims. If there is a keyword
that you would like to set and that is not yet implemented here, it is trivial to add to the first few lines of the aims
calculator in the file ASE/ase/calculators/aims.py .
Describing the basic physics of the system:
keyword
xc
charge
spin
relativistic
use_dipole_correction
vdw_correction_hirshfeld
k_grid
type
str
float
str
list
bool
str
list
type
list
int
int
int
bool
list
list
list
Output options:
keyword
output_level
output
cubes
type
str
list
AimsCube
See below for a description of the volumetric cube file output interface AimsCube
Keywords for accuracy settings:
keyword
sc_accuracy_eev
sc_accuracy_etot
sc_accuracy_forces
sc_accuracy_rho
compute_forces
type
exp
exp
exp
exp
bool
keyword
charge_mix_param
prec_mix_param
spin_mix_param
KS_method
restart
restart_read_only
restart_write_only
preconditioner
mixer
empty_states
ini_linear_mixing
mixer_threshold
occupation_type
type
float
float
float
str
str
str
srt
list
str
int
int
list
list
Note:
Any argument can be changed after the initial construction of the
calculator, simply by setting it with the method
>>> calc.set( keyword=value )
The class
class ase.calculators.aims.AimsCube(origin=(0,0,0),edges=[(0.1,0.0,0.0),(0.0,0.1,0.0),(0.0,0.0,0.1)],points=(50,50,50)
describes an object that takes care of the volumetric output requests within FHI-aims. An object of this type can
be attached to the main Aims() object as an option.
The possible arguments for AimsCube are:
keyword
origin
edges
points
plots
type
list
3x3-array
list
list
The possible values for the entry of plots are discussed in detail in the FHI-aims manual, see below for an example.
Example
7.14. Calculators
131
sc_accuracy_rho=1e-6,
sc_accuracy_forces=1e-4,
cubes=water_cube)
water.set_calculator(calc)
dynamics = QuasiNewton(water,trajectory=square_water.traj)
dynamics.run(fmax=0.01)
FLEUR
Introduction
FLEUR is a density-functional theory code which uses the full potential linearized augmented plane-wave
(FLAPW) method. FLEUR can be applied to any element in the periodic table, and the code is well suited
especially to surfaces and magnetic materials.
Environment variables
In order to use FLEUR through ASE, two environment variables have to be set. FLEUR_INPGEN should point to
the simple input generator of FLEUR, and FLEUR to the actual executable. Note that FLEUR has different executables e.g. for cases with and without inversion symmetry, so the environment variable has to be set accordingly.
As an example, the variables could be set like:
$ export FLEUR_INPGEN=$HOME/fleur/v25/inpgen.x
$ export FLEUR=$HOME/fleur/v25/fleur.x
or:
$ export FLEUR="mpirun -np 32 $HOME/fleur/v25/fleur.x"
Currently, limited number of FLEUR parameters can be set via the ASE interface Below follows a list of supported
parameters
keyword
xc
kpts
convergence
width
kmax
mixer
maxiter
maxrelax
workdir
type
str
seq
dict
float
float
dict
int
int
str
default value
LDA
-point
{energy:
0.0001}
40
20
Current dir
description
XC-functional. Must be one of LDA, PBE, RPBE
k-point sampling
Convergence criteria (meV)
Width of Fermi smearing (eV)
Plane-wave cut-off (a.u.)
Mixing parameters imix, alpha, and spinf
Maximum number of SCF steps
Maximum number of relaxation steps
Working directory for the calculation
If the atoms object has non-zero magnetic moments, a spin-polarized calculation will be performed by default.
132
Utility functions
As only a subset of FLEUR parameters can currently be specified through ASE interface, the interface defines
some utility functions for cases where manual editing of the FLEUR input file inp is necessary.
FLEUR.write_inp(atoms)
Write the inp input file of FLEUR.
First, the information from Atoms is written to the simple input file and the actual input file inp is then
generated with the FLEUR input generator. The location of input generator is specified in the environment
variable FLEUR_INPGEN.
Finally, the inp file is modified according to the arguments of the FLEUR calculator object.
FLEUR.initialize_density(atoms)
Creates a new starting density.
FLEUR.calculate(atoms)
Converge a FLEUR calculation to self-consistency.
Input files should be generated before calling this function FLEUR performs always fixed number of SCF
steps. This function reduces the number of iterations gradually, however, a minimum of five SCF steps is
always performed.
FLEUR.relax(atoms)
Currently, user has to manually define relaxation parameters (atoms to relax, relaxation directions, etc.) in
inp file before calling this function.
Examples
Gromacs is a free classical molecular dynamics package. It is mainly used in modeling of biological systems. It
is part of the ubuntu-linux distribution. http://www.gromacs.org/
Warning:
1. Ase-Gromacs calculator works properly only with gromacs version 4.5.6 or a newer one. (fixed bug
related to .g96 format)
7.14. Calculators
133
Warning:
2. It only makes sense to use ase-gromacs for qm/mm or for testing. For pure MM production runs the
native gromacs is much much faster (at the moment ase-gromacs has formatted io using .g96 format
which is slow).
Gromacs Calculator
This ASE-interface is a preliminary one and it is VERY SLOW so do not use it for production runs. It is here
because of well have a QM/MM calculator which is using gromacs as the MM part.
For example: (setting for the MM part of a QM/MM run, parameter -nt 1 for serial run):
CALC_MM = Gromacs(doing_qmmm = True)
CALC_MM.set_own_params_runs(extra_mdrun_parameters, -nt 1 )
Here default values for MM input are:: define = -DFLEXIBLE, integrator = cg, nsteps = 10000, nstfout =
10, nstlog = 10, nstenergy = 10, nstlist = 10, ns_type = grid, pbc = xyz, rlist = 1.15, coulombtype
= PME-Switch, rcoulomb = 0.8, vdwtype = shift, rvdw = 0.8, rvdw_switch = 0.75, DispCorr =
Ener
The input values can be changed by::
CALC_MM.set_own_params( nsteps,99999 Number of steps)
The arguments for gromacs programs can be changed by::
CALC_MM.set_own_params_runs( extra_pdb2gmx_parameters,-ignh)
CALC_MM.set_own_params_runs( init_structure,1GM2.pdb)
CALC_MM.set_own_params_runs( extra_mdrun_parameters, -nt 1 )
CALC_MM.set_own_params_runs( extra_grompp_parameters, )
CALC_MM.set_own_params_runs( extra_editconf_parameters, )
CALC_MM.set_own_params_runs( extra_genbox_parameters, )
Parameters
The
description
of
the
parameters
http://www.gromacs.org/Documentation/Manual
can
be
found
in
the
Gromacs
manual:
GMXCMD the name of the main gromacs executable (usually mdrun). If GMXCMD is not set gromacs
test is not run, but in the calculator works using mdrun.
GMXCMD_PREF prefix for all gromacs commands (default )
134
THIS IS NOT A PROPER WAY TO SETUP YOUR MD SIMULATION. THIS IS JUST A DEMO THAT DOES
NOT CRASH. (the box size should be iterated by md-NTP, total charge should be 0).
Initial pdb coordinates (file his.pdb):
COMPND
REMARK
REMARK
HETATM
HETATM
HETATM
HETATM
HETATM
HETATM
HETATM
HETATM
HETATM
HETATM
HETATM
REMARK
HIS HISTIDINE
HIS Part of HIC-Up: http://xray.bmc.uu.se/hicup
HIS Extracted from PDB file pdb1wpu.ent
1 N
HIS 4234
0.999 -1.683 -0.097
2 CA HIS 4234
1.191 -0.222 -0.309
3 C
HIS 4234
2.641
0.213 -0.105
4 O
HIS 4234
3.529 -0.651 -0.222
5 CB HIS 4234
0.245
0.546
0.619
6 CG HIS 4234
-1.200
0.349
0.280
7 ND1 HIS 4234
-1.854 -0.849
0.470
8 CD2 HIS 4234
-2.095
1.176 -0.310
9 CE1 HIS 4234
-3.087 -0.752
0.006
10 NE2 HIS 4234
-3.258
0.467 -0.474
11 OXT HIS 4234
2.889
1.404
0.141
HIS ENDHET
1.00
1.00
1.00
1.00
1.00
1.00
1.00
1.00
1.00
1.00
1.00
20.00
20.00
20.00
20.00
20.00
20.00
20.00
20.00
20.00
20.00
20.00
7.14. Calculators
135
Jacapo is an ASE interface for Dacapo that is fully compatible with ASE. It replaces the old Dacapo interface
using Numeric python and ASE2. The code was originally developed by John Kitchin and detailed documentation
as well as many examples are available online:
http://gilgamesh.cheme.cmu.edu/doc/software/jacapo/index.html
Jacapo is included as an optional calculator in ASE and small differences to the above documentation may occur,
and the documentation is no longer maintained.
Jacapo calculator
The Jacapo interface is automatically installed with ase and can be imported using:
from ase.calculators.jacapo import Jacapo
type
str
str
object
float
float
str
nbands
ft
kpts
spinpol
fixmagmom
symmetry
stress
dipole
ados
stay_alive
debug
deletenc
int
float
list
boolean
str
boolean
boolean
boolean
dict
boolean
int
boolean
description
Output NetCDF file, or input file if nc already exists.
Output file. By default equal to nc.
ase atoms object
Planewave cutoff in eV
Density cutoff in eV
Exchange-correlation functional. One of
[PZ,VWN,PW91,PBE,RPBE,revPBE]
Number of bands
Fermi temperature
K-point grid, e.g. kpts = (2,2,1)
Turn on/off spin-polarization
Magnetic moment of the unit cell
Turn on/off symmetry reduction
Turn on/off stress calculation
Turn on/off dipole correction
Atom-projected density of states
Turn on/off stay alive
Set debug level (0=off, 10=extreme)
If the nc file exists, delete it (to ensure a fresh run). Default is False.
Example
136
pbc=True)
calc = Jacapo(Jacapo-test.nc,
pw=200,
nbands=2,
kpts=(1,1,1),
spinpol=False,
dipole=False,
symmetry=False,
ft=0.01)
atoms.set_calculator(calc)
print atoms.get_potential_energy()
write(Jacapo-test.traj, atoms)
Note that all calculator parameters should be set in the calculator definition itself. Do not attempt to use the
calc.set_* commands as they are intended to be internal to the calculator. Note also that Dacapo can only operate
with periodic boundary conditions, so be sure that pbc is set to True.
Restarting from an old calculation
If the file you specify to Jacapo with the nc keyword exists, Jacapo will assume you are attempting to restart
an existing calculation. If you do not want this behavior, turn the flag deletenc to True in your calculator
definition.
For example, it is possible to continue a geometry optimization with something like this:
calc = Jacapo(old.nc, stay_alive=True)
atoms = calc.get_atoms()
dyn = QuasiNewton(atoms, logfile=qn.log)
dyn.run(fmax=0.05)
Note, that the stay_alive flag is not stored in the .nc file and must be set when the calculator instance is created.
Atom-projected density of states
To find the atom-projected density of states with Jacapo, first specify the ados dictionary in your calculator definition, as in:
calc = Jacapo( ... ,
ados={energywindow: (-10., 5.),
energywidth: 0.2,
npoints: 250,
cutoff: 1.0})
After this is established, you can use the get_ados command to get the desired ADOS data. For example:
energies, dos = calc.get_ados(atoms=[0],
orbitals=[d],
cutoff=short,
spin=[0])
LAMMPS Calculators
LAMMPS (Large-scale Atomic/Molecular Massively Parallel Simulator) is a classical molecular dynamics code.
There are two calculators that interface to the LAMMPS molecular dynamics code that can be used to solve an
atoms model for energy, atom forces and cell stresses. They are:
7.14. Calculators
137
1. LAMMPSrun which interfaces to LAMMPS via writing a controlling input file that is then run automatically
through LAMMPS and the results read back in. These results are currently limited to total energy, atomic forces
and cell stress.
2. LAMMPSlib which uses the python interface that comes with LAMMPS, loads the LAMMPS program as a
python library. The LAMMPSlib calculator then creates a .lmp object which is a running LAMMPS subroutine,
so further commands can be sent to this object and executed until it is explicitly closed. Any additional variables
calculated by LAMMPS can also be extracted. Note however, any mistakes in the code sent to the LAMMPS
routine will cause python to terminate.
ASE is licensed as LGPL and LAMMPS is GPL which prohibits them from being linked together in a distribution
such as ASE. As a result, LAMMPSlib is not distributed with the ASE project but is available separately at
lammpslib . Further explanation of the licensing is constained in License.
It should not matter which code you use, but if you want access to more of LAMMPS internal variables or to
perform a more complicated simulation then use LAMMPSlib. It is important to know which code you are using
because when you make an error in the LAMMPS code, debugging the is difficult and different for both calculators.
Both of these interfaces are still experimental code and any problems should be reported to the ASE developers
mailing list.
LAMMPSrun
Introduction
LAMMPS (Large-scale Atomic/Molecular Massively Parallel Simulator) is a classical molecular dynamics code.
LAMMPS has potentials for soft materials (biomolecules, polymers) and solid-state materials (metals, semiconductors) and coarse-grained or mesoscopic systems. It can be used to model atoms or,
more generically, as a parallel particle simulator at the atomic, meso, or continuum scale.
This is LAMMPSrun ASE implementation of the interface to LAMMPS.
Environment variables
The environment variable LAMMPS_COMMAND should contain the path to the lammps binary, or more generally,
a command line possibly also including an MPI-launcher command. For example (in a Bourne-shell compatible
environment):
$ export LAMMPS_COMMAND=/path/to/lmp_binary
LAMMPS Calculator
The LAMMPS calculator first appeared in ASE version 3.5.0. At the time of the release of ASE 3.5.0, the
LAMMPS calculator is still in a fairly early stage of development (if you are missing some feature, consider
checking out the source code development tree or some more recent version of ASE).
class ase.calculators.LAMMPSrun.LAMMPS(..., parameters={}, files=[], ...)
Below follows a list with a selection of parameters
138
keyword
type default
value
files list[]
parameters
dict{}
description
Example
A simple example.
from ase import Atoms, Atom
from ase.calculators.lammpsrun import LAMMPS
a = [6.5, 6.5, 7.7]
d = 2.3608
NaCl = Atoms([Atom(Na, [0, 0, 0]),
Atom(Cl, [0, 0, d])],
cell=a, pbc=True)
calc = LAMMPS()
NaCl.set_calculator(calc)
print NaCl.get_stress()
There are some modules to facilitate the setup of an OPLS force field calculation, see ase.io.opls.
NWChem
NWChem is a computational chemistry code based on gaussian basis functions or plane-waves.
Environment variable
The default command to start NWChem is nwchem PREFIX.nw > PREFIX.out. You can change that by
setting the environment variable ASE_NWCHEM_COMMAND.
Example
Here is an example of how to calculate optimize the geometry of a water molecule using PBE:
$ asec H2O optimize -c nwchem -p xc=PBE
LBFGS:
0 16:17:29
-2064.914841
1.9673
LBFGS:
1 16:17:31
-2064.963074
0.9482
LBFGS:
2 16:17:32
-2064.976603
0.1425
LBFGS:
3 16:17:33
-2064.977216
0.0823
LBFGS:
4 16:17:35
-2064.977460
0.0010
$ ase-gui H2O.traj@-1 -tg "a(1,0,2),d(0,1)"
102.577881445 1.00806894632
7.14. Calculators
139
SIESTA
Introduction
SIESTA is a density-functional theory code for very large systems based on atomic orbital (LCAO) basis sets.
Environment variables
You need to write a script called run_siesta.py containing something like this:
import os
siesta = siesta_2.0
exitcode = os.system(%s < %s.fdf > %s.txt % (siesta, label, label))
SIESTA Calculator
The default parameters are very close to those that the SIESTA Fortran code uses. These are the exceptions:
class ase.calculators.siesta.Siesta(label=siesta, xc=LDA, pulay=5, mix=0.1)
Here is a detailed list of all the keywords for the calculator:
keyword
kpts
nbands
meshcutoff
basis
xc
pulay
mix
width
charge
label
type
list
int
float
str
str
int
float
float
float
str
default value
[1,1,1]
None
None
None
LDA
5
0.1
None
None
siesta
description
Monkhorst-Pack k-point sampling
Number of bands
Mesh cut-off energy in eV
Type of basis set (sz, dz, szp, dzp)
Exchange-correlation functional.
Number of old densities to use for Pulay mixing
Pulay mixing weight
Fermi-distribution width in eV
Total charge of the system
Name of the output file
The SIESTA code reads the input parameters for any calculation from a .fdf file. This means that you can set
parameters by manually setting entries in this input .fdf file. This is done by the syntax:
>>> calc.set_fdf(name_of_the_entry, value)
The complete list of the FDF entries can be found in the official SIESTA manual.
140
Customized basis-set
Standard basis sets can be set by the keyword basis directly in the Siesta calculator object. If a customized basis
is needed, it can be set as an FDF entry, as explained in the previous section.
As an example, we generate a triple-zeta triple-polarized (TZTP) basis for Au. Since the valence states are 6s and
5d, we will have 3 zeta orbitals for l=0 and 3 for l=2 plus 3 polarization orbitals for l=1. The basis can be defined
by
>>> value = ["""Au
2
>>>
0
3
P
>>>
0.00
0.00
>>>
>>>
2
3
>>>
0.00
0.00
split
3
0.00
0.00
0.00"""]
>>> calc.set_fdf(PAO.Basis,value=value)
The default basis set generation fails for Pt for some versions of Siesta. If this happens, you should specify the
basis set manually. This is exemplified below.
For Pt, using calc.set_fdf(PAO.EnergyShift, 0.1 * eV) is usually reasonable, and a single-zeta
polarized basis set can be specified by writing:
# Define SZP basis set for Pt
calc.set_fdf(PAO.Basis,
["""\
Pt
2
# Species label, number of l-shells
n=6 0 1 P
# n, l, Nzeta, Polarization, NzetaPol
0.
# 0.0 => default [6.982 \n 1.000]
n=5 2 1
# n, l, zeta
0."""])
# 0.0 => default [5.172 \n 1.000]
1.000]
1.000]
You can also reuse the basis set of a previous calculation, by copying the .ion files to the new location, and set the
User.Basis tag to True:
# Load basis from previous calc (*.ion files)
calc.set_fdf(User.Basis, True)
Warning: Specifying a basis set manually in any way will, for some obscure reason, make Siesta crash if you have
ghost atoms!
Pseudopotentials
Pseudopotential files in the .psf or .vps formats are needed. Pseudopotentials generated from the ABINIT
code and converted to the SIESTA format are available in the SIESTA website . A database of user contributed
pseudopotentials is also available there.
You can also find an on-line pseudopotential generator from the OCTOPUS code.
7.14. Calculators
141
Example
Here is an example of how to calculate the total energy for bulk Silicon, using a double-zeta basis generated by
specifying a given energy-shift:
#!/usr/bin/env python
from ase import *
a0 = 5.43
bulk = Atoms(Si2, [(0, 0, 0),
(0.25, 0.25, 0.25)],
pbc=True)
b = a0 / 2
bulk.set_cell([(0, b, b),
(b, 0, b),
(b, b, 0)], scale_atoms=True)
calc = Siesta(label=Si,
xc=PBE,
meshcutoff=200 * Ry,
basis=dz,
mix=0.01,
kpts=[10, 10, 10])
calc.set_fdf(PAO.EnergyShift, 0.01 * Ry)
bulk.set_calculator(calc)
e = bulk.get_potential_energy()
Here, the only input information on the basis set is, that it should be double-zeta (basis=dz) and that the confinement potential should result in an energy shift of 0.01 Rydberg (the PAO.EnergyShift fdf tag). Sometimes
it can be necessary to specify more information on the basis set. For example, the default basis set generation fails
for Pt for some versions of Siesta. To fix this, you must specify the basis set manually. Manual basis set specifications are described in Customized basis-set.
Restarting from an old Calculation
If you want to rerun an old SIESTA calculation, made using the ASE interface or not, you can set the fdf tag
UseSaveData to True. This is equivalent to setting both DM.UseSaveDM and MD.UseSaveXV to True, i.e.
it will reuse the the density matrix, and the atomic coordinates (and unit cell) of the previous calculation. Note
that the Siesta jobname (the label keyword in the ASE interface) must be identical to the jobname of the old
calculation.
TURBOMOLE
Introduction
TURBOMOLE is a density-functional or Hartree Fock code using atom centered orbitals. This interface makes it
possible to use TURBOMOLE as a calculator in ASE.
Environment variables
142
csh/tcsh:
$ setenv TURBODIR /my_disk/my_name/TURBOMOLE
$ set path=(${TURBODIR}/scripts $path)
$ set path=(${TURBODIR}/bin/sysname $path)
All usual turbomole input files generated by Turbomoles define [coord, control, basis, (auxbasis),
mos/alpha+beta] must be present in the current working directory.
Turbomole files are updated during the ASE-run.
Do not use internal coordinates, only cartesians are allowed.
Ase-Turbomole uses turbomole programs ridft and rdgrad if keyword $ricore is present in the Turbomoles
control file. Otherwise programs dscf and grad are used.
Example1: Single-point energy
to
calculate
proton
transfer
barrier
in
H3O2-:
VASP
Introduction
VASP is a density-functional theory code using pseudopotentials or the projector-augmented wave method and a
plane wave basis set. This interface makes it possible to use VASP as a calculator in ASE, and also to use ASE as
a post-processor for an already performed VASP calculation.
Environment variables
You need to write a script called run_vasp.py containing something like this:
import os
exitcode = os.system(vasp)
7.14. Calculators
143
VASP Calculator
type
bool
str
str
seq
bool
bool
str
float
float
int
str
int
float
int
default value
None
PW91
None
-point
None
None
description
Restart old calculation or use ASE for post-processing
XC-functional
Additional setup option
k-point sampling
-point centered k-point sampling
Use reciprocal units if k-points are specified explicitly
Accuracy of calculation
Kinetic energy cutoff
Convergence break condition for SC-loop.
Number of bands
Electronic minimization algorithm
Type of smearing
Width of smearing
Maximum number of SC-iterations
This would set the precision to Accurate and the break condition for the electronic SC-loop to 1E-5 eV.
Spin-polarized calculation
If the atoms object has non-zero magnetic moments, a spin-polarized calculation will be performed by default.
Here follows an example how to calculate the total magnetic moment of a sodium chloride molecule.
from ase import Atoms, Atom
from ase.calculators.vasp import Vasp
a = [6.5, 6.5, 7.7]
d = 2.3608
NaCl = Atoms([Atom(Na, [0, 0, 0], magmom=1.928),
Atom(Cl, [0, 0, d], magmom=0.75)],
cell=a)
calc = Vasp(prec = Accurate,
xc = PBE,
lreal = False)
NaCl.set_calculator(calc)
print NaCl.get_magnetic_moment()
In this example the initial magnetic moments are assigned to the atoms when defining the Atoms object. The calculator will detect that at least one of the atoms has a non-zero magnetic moment and a spin-polarized calculation
will automatically be performed. The ASE generated INCAR file will look like:
144
Note: It is also possible to manually tell the calculator to perform a spin-polarized calculation:
>>> calc.set(ispin=2)
This can be useful for continuation jobs, where the initial magnetic moment is read from the WAVECAR file.
To continue an old calculation which has been performed without the interface use the restart parameter when
constructing the calculator
>>> calc = Vasp(restart=True)
Then the calculator will read atomic positions from the CONTCAR file, physical quantities from the OUTCAR file,
k-points from the KPOINTS file and parameters from the INCAR file.
Note: Only Monkhorst-Pack and Gamma-centered k-point sampling are supported for restart at the moment.
Some INCAR parameters may not be implemented for restart yet. Please report any problems to the ASE mailing
list.
The restart parameter can be used , as the name suggest to continue a job from where a previous calculation
finished. Furthermore, it can be used to extract data from an already performed calculation. For example, to get the
total potential energy of the sodium chloride molecule in the previous section, without performing any additional
calculations, in the directory of the previous calculation do:
>>> calc = Vasp(restart=True)
>>> atoms = calc.get_atoms()
>>> atoms.get_potential_energy()
-4.7386889999999999
ase_qmmm_manyqm
Introduction
This an general interface to run QM/MM calculations with a ase-QM and ase-MM calculator. Currently QM can
be FHI-aims and MM can be Gromacs.
QM and MM region can be covalently bonded. In principle you can cut wherever you like, but other cutting
schemes are probably better than others. The standard recommendation is to cut only the C-C bonds.
There can be many QM regions embedded in the MM system.
Ase_qmmm_manyqm Calculator
145
Non-bonded interactions:
Generally energies and forces are treated by:
Within the same QM-QM: by QM calculator
MM-MM: by MM calculator
QM-MM: by MM using MM vdw parameters and QM charges.
Different QM-different QM: by MM using QM and MM charges and MM-vdw parameters
The Hirschfeld charges (or other atomic charges) on QM atoms are calculated by QM in a H terminated cluster in
vacuum. The charge of QM atom next to MM atom (edge-QM-atom) and its H neighbors are set as in the classical
force field.
The extra(missing) charge results from:
linkH atoms
The edge-QM atoms, and their singly bonded neighbors (typically -H or =O). These have their original
MM charges.
From the fact that the charge of the QM fraction is not usually an integer when using the original MM
charges.
The extra/missing charge is added equally to all QM atoms (not being linkH and not being edge-QMatom or its singly bonded neighbor) so that the total charge of the MM-fragment involving QM atoms
will be the same as in the original MM-description.
Vdw interactions are calculated by MM-gromacs for MM and MM-QM interactions. The QM-QM vdw interaction
s could be done by the FHI-aims if desired (by modifying the input for QM-FHI-aims input accordingly.
Bonded interactions:
E = E_qm(QM-H) + E_mm(ALL ATOMS), where
E_qm(QM-H): qm energy of H terminated QM cluster(s)
E_mm(ALL ATOMS): MM energy of all atoms, except for terms in which all MM-interacting atoms
are in the same QM region.
Forces do not act on link atoms but they are positioned by scaling. Forces on link atoms are given to their
QM and MM neighbors by chain rule. (see Top Curr Chem (2007) 268: 173290, especially pages 192194). At the beginning of a run, the optimal edge-qm-atom-linkH bond length(s) is (are) calculated by QM in
get_eq_qm_atom_link_h_distances or they are read from a file (this is determined by the argument link_info).
The covalent bonds between QM and MM are found automatically based on ase-covalent radii in neighbor search.
Link atoms are positioned automatically (according to .
Questions & Comments [email protected]
Interesting applications could be cases when we need two or more QM regions. For instance two redox centers in
a protein, cathode and anode of a fuel cell ... you name it!
Arguments
keyword
type default
value
nqm_regions
int
qm_calculators
list
mm_calculator
Calc
link_infostr byQM
146
description
Example
Generate the simulation box (cubic is not the most efficient one...)
>>> editconf -bt cubic -f 1GM2.gro -o 1GM2_box.gro -c -d 0.2
add to first lines to index.ndx (we define here 3 QM regions, indexing from 1):
[qm_ss]
18 19 20 21 139 140 141 142
[qm_thr]
28 29 30 31 32 33 34 35
[qm_ser]
64 65 66 67 68
2. Relax MM system by fixing QM atoms in their (crystallographic?) positions (see documentation for Gromacs MM calculator).
"""
An example for using gromacs calculator in ase.
Atom positions are relaxed.
If qm atoms are found in index file, they are kept fixed in the relaxation.
QM atoms are defined in index file (numbering from 1)
in sets containing QM or Qm or qm in their name.
A sample call:
./gromacs_example_mm_relax.py 1GM2_sol.gro
"""
from ase.calculators.gromacs import Gromacs
import sys
from ase.io import read
infile_name = sys.argv[1]
CALC_MM_RELAX = Gromacs(
init_structure_file=infile_name,
structure_file = gromacs_mm-relax.g96,
force_field=oplsaa,
7.14. Calculators
147
water_model=tip3p,
base_filename = gromacs_mm-relax,
doing_qmmm = False, freeze_qm = True,
index_filename = index.ndx,
extra_mdrun_parameters = -nt 1 ,
define = -DFLEXIBLE,
integrator = cg,
nsteps = 10000,
nstfout = 10,
nstlog = 10,
nstenergy = 10,
nstlist = 10,
ns_type = grid,
pbc = xyz,
rlist = 1.15,
coulombtype = PME-Switch,
rcoulomb = 0.8,
vdwtype = shift,
rvdw = 0.8,
rvdw_switch = 0.75,
DispCorr = Ener)
CALC_MM_RELAX.generate_topology_and_g96file()
CALC_MM_RELAX.generate_gromacs_run_file()
CALC_MM_RELAX.run()
./test_ase_qmmm_manyqm.py gromacs_mm-relax.g96
from
from
from
from
import sys
from ase.io.gromos import read_gromos
RUN_COMMAND = /home/mka/bin/aims.071711_6.serial.x
SPECIES_DIR = /home/mka/Programs/fhi-aims.071711_6/species_defaults/light/
LOG_FILE = open("ase-qm-mm-output.log","w")
sys.stdout = LOG_FILE
infile_name = sys.argv[1]
CALC_QM1 = Aims(charge = 0,
xc = pbe,
sc_accuracy_etot = 1e-5,
sc_accuracy_eev = 1e-2,
sc_accuracy_rho = 1e-5,
sc_accuracy_forces = 1e-3,
species_dir = SPECIES_DIR,
run_command = RUN_COMMAND)
CALC_QM1.set(output = hirshfeld)
CALC_QM2 = Aims(charge = 0,
xc = pbe,
sc_accuracy_etot = 1e-5,
sc_accuracy_eev = 1e-2,
sc_accuracy_rho = 1e-5,
sc_accuracy_forces = 1e-3,
148
species_dir = SPECIES_DIR,
run_command = RUN_COMMAND)
CALC_QM2.set(output = hirshfeld)
CALC_QM3 = Aims(charge = 0,
xc = pbe,
sc_accuracy_etot = 1e-5,
sc_accuracy_eev = 1e-2,
sc_accuracy_rho = 1e-5,
sc_accuracy_forces = 1e-3,
species_dir = SPECIES_DIR,
run_command = RUN_COMMAND)
CALC_QM3.set(output = hirshfeld)
CALC_MM = Gromacs(
init_structure_file = infile_name,
structure_file = gromacs_qm.g96, \
force_field = oplsaa,
water_model = tip3p,
base_filename = gromacs_qm,
doing_qmmm = True, freeze_qm = False,
index_filename = index.ndx,
define = -DFLEXIBLE,
integrator = md,
nsteps = 0,
nstfout = 1,
nstlog = 1,
nstenergy = 1,
nstlist = 1,
ns_type = grid,
pbc = xyz,
rlist = 1.15,
coulombtype = PME-Switch,
rcoulomb = 0.8,
vdwtype = shift,
rvdw = 0.8,
rvdw_switch = 0.75,
DispCorr = Ener)
CALC_MM.generate_topology_and_g96file()
CALC_MM.generate_gromacs_run_file()
CALC_QMMM = AseQmmmManyqm(nqm_regions = 3,
qm_calculators = [CALC_QM1, CALC_QM2, CALC_QM3],
mm_calculator = CALC_MM,
link_info = byQM)
#
link_info = byFILE)
SYSTEM = read_gromos(gromacs_qm.g96)
SYSTEM.set_calculator(CALC_QMMM)
DYN = BFGS(SYSTEM)
DYN.run(fmax = 0.05)
print(exiting fine)
LOG_FILE.close()
7.14.3 QMMM
For QMMM caculations, see ase.calculators.ase_qmmm_manyqm.
7.14. Calculators
149
150
get_magnetic_moment(atoms=None)
Return the total magnetic moment.
get_number_of_bands()
Return the number of bands.
get_number_of_grid_points()
Return the shape of arrays.
get_number_of_spins()
Return the number of spins in the calculation.
Spin-paired calculations: 1, spin-polarized calculation: 2.
get_occupation_numbers(kpt=0, spin=0)
Return occupation number array.
get_pseudo_density(spin=None, pad=True)
Return pseudo-density array.
If spin is not given, then the total density is returned. Otherwise, the spin up or down density is
returned (spin=0 or 1).
get_pseudo_wave_function(band=0, kpt=0, spin=0, broadcast=True, pad=True)
Return pseudo-wave-function array.
get_spin_polarized()
Is it a spin-polarized calculation?
get_wannier_localization_matrix(nbands, dirG, kpoint, nextkpoint, G_I, spin)
Calculate integrals for maximally localized Wannier functions.
get_xc_functional()
Return the XC-functional identifier.
LDA, PBE, ...
initial_wannier(initialwannier, kpointgrid, fixedstates, edf, spin, nbands)
Initial guess for the shape of wannier functions.
Use initial guess for wannier orbitals to determine rotation matrices U and C.
7.15 Constraints
When performing minimizations or dynamics one may wish to keep some degrees of freedom in the system fixed.
One way of doing this is by attaching constraint object(s) directly to the atoms object.
Important: setting constraints will freeze the corresponding atom positions. Changing such atom positions can be
achieved:
by directly setting the positions attribute (see example of setting Special attributes),
alternatively, by removing the constraints first:
del atoms.constraints
or:
atoms.set_constraint()
7.15. Constraints
151
In this example the distance between the atoms with indices 0 and 1 will be fixed in all following dynamics and/or
minimizations performed on the atoms object.
This constraint is useful for finding minimum energy barriers for reactions where the path can be described well
by a single bond length (see the Dissociation tutorial tutorial).
Important: If fixing multiple bond lengths, use the FixBondLengths class below, particularly if the same atom is
fixed to multiple partners.
Here the distances between atoms with indices 0 and 1 and atoms with indices 0 and 2 will be fixed. The constraint
is for the same purpose as the FixBondLength class.
152
Alternatively, this constraint can tether a single atom to a point in space, for example to prevent the top layer of
a slab from subliming during a high-temperature MD simulation. An example of tethering atom at index 3 to its
original position:
>>> c = Hookean(a1=3, a2=atoms[3].position, rt=0.94, k=2.)
>>> atoms.set_constraint(c)
Reasonable values of the threshold (rt) and spring constant (k) for some common bonds are below.
Bond
O-H
C-O
C-H
C=O
Pt sublimation
Cu sublimation
rt (Angstroms)
1.40
1.79
1.59
1.58
0.94
0.97
k (eV Angstrom^-2)
5
5
7
10
2
2
A third way this constraint can be applied is to apply a restorative force if an atom crosses a plane in space. For
example:
>>> c = Hookean(a1=3, a2=(0, 0, 1, -7), k=10.)
>>> atoms.set_constraint(c)
This will apply a restorative force on atom 3 in the downward direction of magnitude k * (atom.z - 7) if the atoms
vertical position exceeds 7 Angstroms. In other words, if the atom crosses to the (positive) normal side of the
plane, the force is applied and directed towards the plane. (The same plane with the normal direction pointing in
the -z direction would be given by (0, 0, -1, 7).)
For an example of use, see the Constrained minima hopping (global optimization) tutorial.
Note: In previous versions of ASE, this was known as the BondSpring constraint.
7.15. Constraints
153
This example defines a bond an angle and a dihedral angle constraint to be fixed at the same time.
When applying more than one constraint they are passed as a list in the set_constraint() method, and they
will be applied one after the other.
Important: If wanting to fix the length of more than one bond in the simulation, do not supply a list of
FixBondLength instances; instead, use a single instance of FixBondLengths.
154
A simple example:
import numpy as np
class MyConstraint:
"""Constrain an atom to move along a given direction only."""
def __init__(self, a, direction):
self.a = a
self.dir = direction / sqrt(np.dot(direction, direction))
def adjust_positions(self, oldpositions, newpositions):
step = newpositions[self.a] - oldpositions[self.a]
step = np.dot(step, self.dir)
newpositions[self.a] = oldpositions[self.a] + step * self.dir
def adjust_forces(self, positions, forces):
forces[self.a] = self.dir * np.dot(forces[self.a], self.dir)
A constraint can optionally have two additional methods, which will be ignored if missing:
ase.constraints.adjust_momenta(positions, momenta)
Adjust the momenta array inplace.
ase.constraints.adjust_potential_energy(positions, energy)
Provide the difference in the potential energy due to the constraint. (Note that inplace adjustment is not
possible for energy, which is a float.)
7.15. Constraints
155
In all three filters only the hydrogen atoms are made visible. When asking for the positions only the positions of
the hydrogen atoms are returned.
You should not attach this UnitCellFilter object to a trajectory. Instead, create a trajectory for the atoms,
and attach it to an optimizer like this:
>>>
>>>
>>>
>>>
>>>
>>>
atoms = Atoms(...)
ucf = UnitCellFilter(atoms)
qn = QuasiNewton(ucf)
traj = PickleTrajectory(TiO2.traj, w, atoms)
qn.attach(traj)
qn.run(fmax=0.05)
156
The optional second argument, mask, is a list of six booleans, indicating which of the six independent
components of the strain that are allowed to become non-zero. It defaults to [1,1,1,1,1,1].
Be sure to use the copy method (or similar) to create new instances of atoms within the list of images fed to the
NEB. Do not use something like [initial for i in range(3)], as it will only create references to the original atoms
object.
Notice the use of the interpolate() method to get a good initial guess for the path from A to B.
157
NEB.interpolate()
Interpolate path linearly from initial to final state.
Only the internal images (not the endpoints) need have calculators attached.
See Also:
ase.optimize: Information about energy minimization (optimization). Note that you cannot use the default
optimizer, BFGSLineSearch, with NEBs. (This is the optimizer imported when you import QuasiNewton.)
If you would like a quasi-newton optimizer, use BFGS instead.
ase.calculators: How to use calculators.
Tutorials:
Diffusion of gold atom on Al(100) surface (NEB)
Dissociation tutorial
Note: If there are M images and each image has N atoms, then the NEB object behaves like one big Atoms
object with M N atoms, so its get_positions() method will return a M N 3 array.
7.16.2 Trajectories
The code:
from ase.optimize import BFGS
optimizer = BFGS(neb, trajectory=A2B.traj)
will write all images to one file. The Trajectory object knows about NEB calculations, so it will write M images
with N atoms at every iteration and not one big configuration containing M N atoms.
The result of the latest iteration can now be analysed with this command: ase-gui A2B.traj@-5:.
For the example above, you can write the images to individual trajectory files like this:
for i in range(1, 4):
qn.attach(io.PickleTrajectory(A2B-%d.traj % i, w, images[i]))
7.16.3 Restarting
Restart the calculation like this:
images = io.read(A2B.traj@-5:)
158
Note: Quasi-Newton methods, such as BFGS, are not well suited for climbing image NEB calculations. FIRE
have been known to give good results, although convergence is slow.
Create the NEB object with NEB(images, parallel=True) and let the master processes write the images:
if rank % (size // n) == 0:
traj = io.PickleTrajectory(neb%d.traj % j, w, images[1 + j],
master=True)
optimizer.attach(traj)
159
160
7.19 Example
Simple example showing how to calculate the phonon dispersion for bulk aluminum using a 7x7x7 supercell
within effective medium theory:
161
from
from
from
from
162
7.19. Example
163
7.20 Thermochemistry
ASE contains a ase.thermochemistry module that lets the user derive commonly desired thermodynamic
quantities of molecules and crystalline solids from ASE output and some user-specified parameters. Three cases
are currently handled by this module: the ideal-gas limit (in which translational and rotational degrees of freedom
are taken into account), the harmonic limit (generally used for adsorbates, in which all degrees of freedom are
treated harmonically), and a crystalline solid model (in which a lattice of N atoms is treated as a system of
3N independent harmonic oscillators). The first two cases rely on good vibrational energies being fed to the
calculators, which can be calculated with the ase.vibrations module. Likewise, the crystalline solid model
depends on an accurate phonon density of states; this is readily calculated using the ase.phonons module.
Example
The IdealGasThermo class would generally be called after an energy optimization and a vibrational analysis.
The user needs to supply certain parameters if the entropy or free energy are desired, such as the geometry and
symmetry number. An example on the nitrogen molecule is:
from
from
from
from
from
atoms = molecule(N2)
atoms.set_calculator(EMT())
dyn = QuasiNewton(atoms)
dyn.run(fmax=0.01)
electronicenergy = atoms.get_potential_energy()
vib = Vibrations(atoms)
vib.run()
vib_energies = vib.get_energies()
thermo = IdealGasThermo(vib_energies=vib_energies,
electronicenergy=electronicenergy,
atoms=atoms,
geometry=linear,
symmetrynumber=2, spin=0)
G = thermo.get_gibbs_energy(temperature=298.15, pressure=101325.)
7.20. Thermochemistry
165
7.20.3 Crystals
In this model a crystalline solid is treated as a periodic system of independent harmonic oscillators. The
CrystalThermo class supports the calculation of internal energy (U ), entropy (S) and Helmholtz free energy
(F ), and has the interface listed below.
class ase.thermochemistry.CrystalThermo(phonon_DOS,
phonon_energies,
formula_units=None, electronicenergy=None)
Class for calculating thermodynamic properties of a crystalline solid in the approximation that a lattice of
N atoms behaves as a system of 3N independent harmonic oscillators.
Inputs:
phonon_DOS [list] a list of the phonon density of states, where each value represents the phonon DOS at
the vibrational energy value of the corresponding index in phonon_energies.
phonon_energies [list] a list of the range of vibrational energies (hbar*omega) over which the phonon density of states has been evaluated. This list should be the same length as phonon_DOS and integrating
phonon_DOS over phonon_energies should yield approximately 3N, where N is the number of atoms
per unit cell. If the first element of this list is zero-valued it will be deleted along with the first element
of phonon_DOS. Units of vibrational energies are eV.
electronicenergy [float] the electronic energy in eV (if electronicenergy is unspecified, then the methods
of this class can be interpreted as the phonon energy corrections.)
formula_units [int] the number of formula units per unit cell. If unspecified, the thermodynamic quantities
calculated will be listed on a per-unit-cell basis.
get_entropy(temperature, verbose=True)
Returns the entropy, in eV/K, of crystalline solid at a specified temperature (K).
166
get_helmholtz_energy(temperature, verbose=True)
Returns the Helmholtz free energy, in eV, of crystalline solid at a specified temperature (K).
get_internal_energy(temperature, verbose=True)
Returns the internal energy, in eV, of crystalline solid at a specified temperature (K).
Example
The CrystalThermo class will generally be called after an energy optimization and a phonon vibrational analysis of the crystal. An example for bulk gold is:
from
from
from
from
from
7.20. Thermochemistry
167
7.20.4 Background
Ideal gas. The conversion of electronic structure calculations to thermodynamic properties in the ideal-gas
limit is well documented; see, for example, Chapter 10 of Cramer, 2004. The key equations used in the
IdealGasThermo class are summarized here.
C.J. Cramer. Essentials of Computational Chemistry, Second Edition. Wiley, 2004.
The ideal-gas enthalpy is calculated from extrapolation of the energy at 0 K to the relevant temperature (for an
ideal gas, the enthalpy is not a function of pressure):
Z T
H(T ) = Eelec + EZPE +
CP dT
0
where the first two terms are the electronic energy and the zero-point energy, and the integral is over the constantpressure heat capacity. The heat capacity is separable into translational, rotational, vibrational, and electronic parts
(plus a term of kB to switch from constant-volume to constant-pressure):
CP = kB + CV ,trans + CV ,rot + CV ,vib + CV ,elec
The translational heat capacity is 3/2 kB for a 3-dimensional gas. The rotational heat capacity is 0 for a monatomic
species, kB for a linear molecule, and 3/2 kB for a nonlinear molecule. In this module, the electronic component
of the heat capacity is assumed to be 0. The vibrational heat capacity contains 3N 6 degrees of freedom for
nonlinear molecules and 3N 5 degrees of freedom for linear molecules (where N is the number of atoms). The
integrated form of the vibrational heat capacity is:
T
CV,vib dT =
0
vib
DOF
X
i
i
ei /kB T 1
P
P
P
P
where the translational, rotational, electronic, and vibrational components are calculated as below. (Note that
the translational component also includes components from the Stirling approximation, and that the vibrational
degrees of freedom are enumerated the same as in the above.)
( "
#
)
3/2
5
kB T
2M kB T
+
Strans = kB ln
h2
P
2
168
Srot
0 h
, if monatomic
i
IkB T
+
1
, if linear
kB ln 8h
2
=
2
3/2
+ 23
, if nonlinear
kB ln IA IB IC 8 hk2B T
Svib = kB
vib
DOF
X
"
i
i /kB T
ln 1 e
kB T ei /kB T 1
IA through IC are the three principle moments of inertia for a non-linear molecule. I is the degenerate moment of
inertia for a linear molecule. is the symmetry number of the molecule.
The ideal-gas Gibbs free energy is then just calculated from the combination of the enthalpy and entropy:
G(T, P ) = H(T ) T S(T, P )
Harmonic limit. The conversion of electronic structure calculation information into thermodynamic properties is
less established for adsorbates. However, the simplest approach often taken is to treat all 3N degrees of freedom
of the adsorbate harmonically since the adsorbate often has no real translational or rotational degrees of freedom.
This is the approach implemented in the HarmonicThermo class. Thus, the internal energy and entropy of the
adsorbate are calculated as
U (T ) = Eelec + EZPE +
harm
DOF
X
i
S = kB
harm
DOF
X
i
"
i
i
ei /kB T 1
ln 1 ei /kB T
kB T ei /kB T 1
In this case, the number of harmonic energies (i ) used in the summation is generally 3N , where N is the number
of atoms in the adsorbate.
Crystalline solid
The derivation of the partition function for a crystalline solid is fairly straight-forward and can be found, for
example, in Chapter 11 of McQuarrie, 2000.
D.A. McQuarrie. Statistical Mechanics. University Science Books, 2000.
The treatment implemented in the CrystalThermo class depends on introducing normal coordinates to the
entire crystal and treating each atom in the lattice as an independent harmonic oscillator. This yields the partition
function
!
1
3N
Y
e 2 h j
eEelec
Z=
hj
1
e
j=1
7.20. Thermochemistry
169
where j are the 3N vibrational frequencies, Eelec is the electronic energy of the crystalline solid, and = kB1T .
Now, taking the logarithm of the partition function and replacing the resulting sum with an integral (assuming that
the energy level spacing is essentially continuous) gives
Z
h
h
()d
ln Z = Eelec +
ln 1 e
+
2
0
Here () represents the degeneracy or phonon density of states as a function of vibrational frequency. Once
this function has been determined (i.e. using the ase.phonons module), it is a simple matter to calculate the
canonical ensemble thermodynamic quantities; namely the internal energy, the entropy and the Helmholtz free
energy.
ln Z
U (T ) =
N,V
Z
h
h
= Eelec +
+
()d
eh 1
2
0
U
+ kB ln Z
ZT
1
h
k
ln
1
e
()d
=
B
T eh 1
0
S(T ) =
F (T ) = U (T ) T S(T, P )
In addition to the methods included in the Vibrations class the InfraRed class introduces two new methods; get_spectrum() and write_spectra().
The summary(), get_energies(),
get_frequencies(), get_spectrum() and write_spectra() methods all take an optional method keyword. Use
method=Frederiksen to use the method described in:
T. Frederiksen, M. Paulsson, M. Brandbyge, A. P. Jauho: Inelastic transport theory from firstprinciples: methodology and applications for nanoscale devices, Phys. Rev. B 75, 205413
(2007)
170
This interface now also works for calculator siesta, (added get_dipole_moment for siesta).
Example:
>>> #!/usr/bin/env python
>>> from ase.io import read
>>> from ase.calculators.siesta import Siesta
>>> from ase.infrared import InfraRed
>>> bud = read(bud1.xyz)
>>> calc = Siesta(label=bud,
...
meshcutoff=250 * Ry,
171
...
...
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
basis=DZP,
kpts=[1, 1, 1])
calc.set_fdf(DM.MixingWeight, 0.08)
calc.set_fdf(DM.NumberPulay, 3)
calc.set_fdf(DM.NumberKick, 20)
calc.set_fdf(DM.KickMixingWeight, 0.15)
calc.set_fdf(SolutionMethod,
Diagon)
calc.set_fdf(MaxSCFIterations, 500)
calc.set_fdf(PAO.BasisType, split)
#50 meV = 0.003674931 * Ry
calc.set_fdf(PAO.EnergyShift, 0.003674931 * Ry )
calc.set_fdf(LatticeConstant, 1.000000 * Ang)
calc.set_fdf(WriteCoorXmol,
T)
>>> bud.set_calculator(calc)
>>> ir = InfraRed(bud)
>>> ir.run()
>>> ir.summary()
get_spectrum(start=800,
end=4000,
npts=None,
width=4,
type=Gaussian,
method=standard, direction=central, intensity_unit=(D/A)2/amu, normalize=False)
Get infrared spectrum.
The method returns wavenumbers in cm^-1 with corresponding absolute infrared intensity. Start and
end point, and width of the Gaussian/Lorentzian should be given in cm^-1. normalize=True ensures
the integral over the peaks to give the intensity.
write_spectra(out=ir-spectra.dat,
start=800,
end=4000,
npts=None,
width=10,
type=Gaussian,
method=standard,
direction=central,
intensity_unit=(D/A)2/amu, normalize=False)
Write out infrared spectrum to file.
First column is the wavenumber in cm^-1, the second column the absolute infrared intensities, and the
third column the absorbance scaled so that data runs from 1 to 0. Start and end point, and width of the
Gaussian/Lorentzian should be given in cm^-1.
A number of different algorithms can be used to perform molecular dynamics, with slightly different results.
172
step is only a little to large, the lack of energy conservation is most obvious in Velocity Verlet dynamics, where
energy should otherwise be conserved.
Experience has shown that 5 femtoseconds is a good choice for most metallic systems. Systems with light atoms
(e.g. hydrogen) and/or with strong bonds (carbon) will need a smaller time step.
All the dynamics objects documented here are sufficiently related to have the same optimal time step.
7.22.3 Logging
A logging mechanism is provided, printing time; total, potential and kinetic energy; and temperature (calculated
from the kinetic energy). It is enabled by giving the logfile argument when the dynamics object is created,
logfile may be an open file, a filename or the string - meaning standard output. Per default, a line is printed
for each timestep, specifying the loginterval argument will chance this to a more reasonable frequency.
The logging can be customized by explicitly attaching a MDLogger object to the dynamics:
from ase.md import MDLogger
dyn = VelocityVerlet(atoms, dt=2*ase.units.fs)
dyn.attach(MDLogger(dyn, atoms, md.log, header=False, stress=False,
peratom=True, mode="a"), interval=1000)
This example will skip the header line and write energies per atom instead of total energies. The parameters are
header: Print a header line defining the columns.
stress: Print the six components of the stress tensor.
peratom: Print energy per atom instead of total energy.
mode: If a, append to existing file, if w overwrite existing file.
Despite appearances, attaching a logger like this does not create a cyclic reference to the dynamics.
Note: If building your own logging class, be sure not to attach the dynamics object directly to the logging object.
Instead, create a weak reference using the proxy method of the weakref package. See the ase.md.MDLogger
source code for an example. (If this is not done, a cyclic reference may be created which can cause certain
calculators, such as Jacapo, to not terminate correctly.)
173
Both the friction and the temperature can be replaced with arrays giving per-atom values. This is mostly useful
for the friction, where one can choose a rather high friction near the boundaries, and set it to zero in the part of the
system where the phenomenon being studied is located.
Nos-Hoover dynamics
In Nos-Hoover dynamics, an extra term is added to the Hamiltonian representing the coupling to the heat bath.
From a pragmatic point of view one can regard Nos-Hoover dynamics as adding a friction term to Newtons
second law, but dynamically changing the friction coefficient to move the system towards the desired temperature.
Typically the friction coefficient will fluctuate around zero.
Nos-Hoover dynamics is not implemented as a separate class, but is a special case of NPT dynamics.
Berendsen NVT dynamics
class ase.md.nvtberendsen.NVTBerendsen(atoms, timestep, temperature, taut, fixcm)
174
In Berendsen NVT simulations the velocities are scaled to achieve the desired temperature. The speed of the
scaling is determined by the parameter taut.
This method does not result proper NVT sampling but it usually is sufficiently good in practise (with large taut).
For discussion see the gromacs manual at www.gromacs.org.
atoms: The list of atoms.
timestep: The time step.
temperature: The desired temperature, in Kelvin.
taut: Time constant for Berendsen temperature coupling.
fixcm: If True, the position and momentum of the center of mass is kept unperturbed. Default: True.
# Room temperature simulation (300K, 0.1 fs time step)
dyn = NVTBerendsen(atoms, 0.1 * units.fs, 300, taut=0.5*1000*units.fs)
175
NPT.initialize():
Estimates the dynamic variables for time=-1 to start the algorithm. This is automatically called before the
first timestep.
NPT.set_stress():
Set the external stress. Use with care. It is preferable to set the right value when creating the object.
NPT.set_mask():
Change the mask. Use with care, as you may freeze a fluctuation in the strain rate.
NPT.set_strainrate(eps):
Set the strain rate. eps must be an upper-triangular matrix. If you set a strain rate along a direction that is
masked out (see set_mask), the strain rate along that direction will be maintained constantly.
NPT.get_gibbs_free_energy():
Gibbs free energy is supposed to be preserved by this dynamics. This is mainly intended as a diagnostic
tool.
References:
[1] S. Melchionna, G. Ciccotti and B. L. Holian, Molecular Physics 78, p. 533 (1993).
[2] S. Melchionna, Physical Review E 61, p. 6165 (2000).
[3] B. L. Holian, A. J. De Groot, W. G. Hoover, and C. G. Hoover, Physical Review A 41, p. 4552 (1990).
[4] F. D. Di Tolla and M. Ronchetti, Physical Review E 48, p. 1726 (1993).
See Also:
The API documentation: md
Berendsen NPT dynamics
class ase.md.nptberendsen.NPTBerendsen(atoms, timestep, temperature, taut, fixcm, pressure,
taup, compressibility)
In Berendsen NPT simulations the velocities are scaled to achieve the desired temperature. The speed of the
scaling is determined by the parameter taut.
The atom positions and the simulation cell are scaled in order to achieve the desired pressure.
This method does not result proper NPT sampling but it usually is sufficiently good in practise (with large taut and
taup). For discussion see the gromacs manual at www.gromacs.org. or amber at ambermd.org
atoms: The list of atoms.
timestep: The time step.
temperature: The desired temperature, in Kelvin.
taut: Time constant for Berendsen temperature coupling.
fixcm: If True, the position and momentum of the center of mass is kept unperturbed. Default: True.
pressure: The desired pressure, in bar (1 bar = 1e5 Pa).
taup: Time constant for Berendsen pressure coupling.
compressibility: The compressibility of the material, water 4.57E-5 bar-1, in bar-1
# Room temperature simulation (300K, 0.1 fs time step, atmospheric pressure)
dyn = NPTBerendsen(atoms, timestep=0.1*units.fs, temperature=300,
taut=0.1*1000*units.fs, pressure = 1.01325,
taup=1.0*1000*units.fs, compressibility=4.57e-5)
176
Chadi-Cohen
Predefined sets of k-points:
ase.dft.kpoints.cc6_1x1
ase.dft.kpoints.cc12_2x3
ase.dft.kpoints.cc18_sq3xsq3
ase.dft.kpoints.cc18_1x1
ase.dft.kpoints.cc54_sq3xsq3
ase.dft.kpoints.cc54_1x1
ase.dft.kpoints.cc162_sq3xsq3
ase.dft.kpoints.cc162_1x1
Naming convention: cc18_sq3xsq3 is 18 k-points for a sq(3)xsq(3) cell.
Try this:
177
178
Return list of k-points, list of x-coordinates and list of x-coordinates of special points.
For examples of how to use the Wannier class, see the Wannier tutorial.
class ase.dft.wannier.Wannier(nwannier, calc, file=None, nbands=None, fixedenergy=None,
fixedstates=None, spin=0, initialwannier=random, seed=None,
verbose=False)
Maximally localized Wannier Functions
Find the set of maximally localized Wannier functions using the spread functional of Marzari and Vanderbilt
(PRB 56, 1997 page 12847).
7.23. Density Functional Theory
179
Required arguments:
nwannier: The number of Wannier functions you wish to construct. This must be at least
half the number of electrons in the system and at most equal to the number of bands in the
calculation.
calc: A converged DFT calculator class. If file arg. is not provided, the calculator must
provide the method get_wannier_localization_matrix, and contain the wavefunctions (save files with only the density is not enough). If the localization matrix is read
from file, this is not needed, unless get_function or write_cube is called.
Optional arguments:
nbands: Bands to include in localization. The number of bands considered by Wannier can
be smaller than the number of bands in the calculator. This is useful if the highest bands of
the DFT calculation are not well converged.
spin: The spin channel to be considered. The Wannier code treats each spin channel independently.
fixedenergy / fixedstates: Fixed part of Heilbert space. Determine the fixed part of
Hilbert space by either a maximal energy or a number of bands (possibly a list for multiple
k-points). Default is None meaning that the number of fixed states is equated to nwannier.
file: Read localization and rotation matrices from this file.
initialwannier: Initial guess for Wannier rotation matrix. Can be bloch to start from
the Bloch states, random to be randomized, or a list passed to calc.get_initial_wannier.
seed: Seed for random initialwannier.
verbose: True / False level of verbosity.
get_centers(scaled=False)
Calculate the Wannier centers
pos =
L / 2pi * phase(diag(Z))
get_function(index, repeat=None)
Get Wannier function on grid.
Returns an array with the funcion values of the indicated Wannier function on a grid with the size of
the repeated unit cell.
For a calculation using k-points the relevant unit cell for eg. visualization of the Wannier orbitals is
not the original unit cell, but rather a larger unit cell defined by repeating the original unit cell by the
number of k-points in each direction. Note that for a -point calculation the large unit cell coinsides
with the original unit cell. The large unitcell also defines the periodicity of the Wannier orbitals.
index can be either a single WF or a coordinate vector in terms of the WFs.
get_functional_value()
Calculate the value of the spread functional.
Tr[|ZI|^2]=sum(I)sum(n) w_i|Z_(i)_nn|^2,
diag(eps )
k
V
k
get_hamiltonian_kpoint(kpt_c)
Get Hamiltonian at some new arbitrary k-vector
180
_
H(k) = >_
R
ik.R
e
H(R)
-ik.R
e
H(k)
where R is the cell-distance (in units of the basis vectors of the small cell) and n,m are indices of the
Wannier functions.
get_pdos(w, energies, width)
Projected density of states (PDOS).
Returns the (PDOS) for Wannier function w. The calculation is performed over the energy grid specified in energies. The PDOS is produced as a sum of Gaussians centered at the points of the energy
grid and with the specified width.
get_radii()
Calculate the spread of the Wannier functions.
-- / L \ 2
2
radius**2 = - >
| --- |
ln |Z|
--d \ 2pi /
181
Placing only the l=2, m=-2 and m=-1 orbitals at atom no. 7 looks like this:
initialwannier = [[[7],2,-2,0.4],[[7],2,-1,0.4]]
I.e. if you do not specify the m quantum number all allowed values are used. Instead of placing an
orbital at an atom, you can place it at a specified position. For example the following:
initialwannier = [[[0.5,0.5,0.5],0,0.5]]
places an s orbital with radius 0.5 Angstroms at the position (0.5, 0.5, 0.5) in scaled coordinates of
the unit cell.
Note: For calculations using k-points, make sure that the -point is included in the k-point grid. The Wannier
module does not support k-point reduction by symmetry, so you must use the usesymm=False keyword in the
calc, and shift all k-points by a small amount (but not less than 2e-5 in) in e.g. the x direction, before performing
the calculation. If this is not done the symmetry program will still use time-reversal symmetry to reduce the
number of k-points by a factor 2. The shift can be performed like this:
from ase.dft.kpoints import monkhorst_pack
kpts = monkhorst_pack((15, 9, 9)) + [2e-5, 0, 0]
182
facilitated
by
the
use
of
More details
class ase.dft.dos.DOS(calc, width=0.1, window=None, npts=201)
Electronic Density Of States object.
calc: calculator object Any ASE compliant calculator object.
width: float Width of guassian smearing.
window: tuple of two float Use window=(emin, emax). If not specified, a window big enough to
hold all the eigenvalues will be used.
npts: int Number of points.
get_energies()
Return the array of energies used to sample the DOS. The energies are reported relative to the Fermi
level.
get_dos(spin=None)
Get array of DOS values.
The spin argument can be 0 or 1 (spin up or down) - if not specified, the total DOS is returned.
ase.dft.get_distribution_moment(x, y, order=0)
Return the moment of nth order of distribution.
1st and 2nd order moments of a band correspond to the bands center and width respectively.
For integration, the trapezoid rule is used.
183
0]
1]
[ 1 0]
[ 0 -1]
[ 0
[ 1
1]
0]
calculate_ldos(bias)
Calculate local density of states for given bias.
get_averaged_current(bias, z)
Calculate avarage current at height z.
Use this to get an idea of what current to use when scanning.
linescan(bias, current, p1, p2, npoints=50, z0=None)
Constant current line scan.
Example:
stm = STM(...)
z = ... # tip position
c = stm.get_averaged_current(-1.0, z)
stm.linescan(-1.0, c, (1.2, 0.0), (1.2, 3.0))
write(filename=stm.pckl)
Write local density of states to pickle file.
The algorithm is very well suited for large solid state physical systems, as well as large biomolecular systems.
The computational time depends only on the size of the 3D grid used to represent the electron density, and scales
linearly with the total number of grid points. As the accuracy of the method depends on the grid spacing, it is
recommended to check for convergence in this parameter (which should usually by smaller than the default value).
The program takes cube input files. It does not support units, and assumes atomic units for the density (Bohr^-3).
All ase dft calculators have a get_pseudo_density method, which can be used to get the density. A simple
python script for making a cube file, ready for the Bader program, could be:
>>> from ase import *
>>> density = calc.get_pseudo_density() * Bohr**3
>>> write(filename.cube, atoms, data=density)
Some calculators (e.g. gpaw) also have a method called get_all_electron_density, in which case this is
preferable to get_pseudo_density.
Note that it is strongly recommended to use version 0.26b or higher of the program, and the examples below refer
to this version.
Example: The water molecule
The following example shows how to do Bader analysis for a water molecule.
First do a ground state calculation, and save the density as a cube file:
from ase import *
from gpaw import *
atoms = molecule(H2O, cell=[7.5, 9, 9], calculator=GPAW(h=.17, xc=PBE))
atoms.center()
atoms.get_potential_energy()
rho = atoms.calc.get_all_electron_density(gridrefinement=4) * Bohr**3
write(water_density.cube, atoms, data=rho)
Then analyse the density cube file by running (use bader -h for a description of the possible options):
$ bader -p all_atom -p atom_index water_density.cube
This will produce a number of files. The ACF.dat file, contains a summary of the Bader analysis:
|
|
|
|
|
|
|
#
X
Y
Z
CHARGE
MIN DIST
----------------------------------------------------------------1
7.0865
8.5038
9.0672
9.1121
1.3250
2
7.0865
9.9461
7.9403
0.4440
0.2834
3
7.0865
7.0615
7.9403
0.4440
0.2834
----------------------------------------------------------------NUMBER OF ELECTRONS:
9.99999
Revealing that 0.56 electrons have been transferred from each Hydrogen atom to the Oxygen atom.
The BvAtxxxx.dat files, are cube files for each Bader volume, describing the density within that volume. (I.e. it is
just the original cube file, truncated to zero outside the domain of the specific Bader volume).
AtIndex.dat is a cube file with an integer value at each grid point, describing which Bader volume it belongs to.
The plot below shows the dividing surfaces of the Hydrogen Bader volumes. This was achieved by plotting a
contour surface of AtIndex.dat at an isovalue of 1.5.
185
You can attach the output charges from the bader program to the atoms for further processing:
from ase import *
from ase.io.bader import attach_charges
# define the molecule as above
atoms = molecule(H2O)
atoms.set_cell([7.5, 9, 9])
atoms.center()
# the next two lines are equivalent (only one needed)
attach_charges(atoms)
attach_charges(atoms, ACF.dat)
for atom in atoms:
print Atom, atom.symbol, Bader charge, atom.charge
...
...
There is a central region (blue atoms plus the molecule) connected to two semi-infinite leads constructed by
infinitely repeated principal layers (red atoms). The entire structure may be periodic in the transverse direction,
which can be effectively sampled using k-points (yellowish atoms).
186
The system is described by a Hamiltonian matrix which must be represented in terms of a localized basis set such
that each element of the Hamiltonian can be ascribed to either the left, central, or right region, or the coupling
between these.
The Hamiltonian can thus be decomposed as:
..
.
V
L
H=
VL
HL
VL
VL
HC
VR
VR
HR
VR
VR
..
.
where HL/R describes the left/right principal layer, and HC the central region. VL/R is the coupling between
principal layers, and from the principal layers into the central region. The central region must contain at least one
principal layer on each side, and more if the potential has not converged to its bulk value at this size. The central
region is assumed to be big enough that there is no direct coupling between the two leads. The principal layer
must be so big that there is only coupling between nearest neighbor layers.
Having defined HL/R , VL/R , and HC , the elastic transmission function can be determined using the Nonequilibrium Green Function (NEGF) method. This is achieved by the class: TransportCalculator (in
ase.transport.calculators) which makes no requirement on the origin of these five matrices.
class ase.transport.calculators.TransportCalculator(energies,
h,
h1,
h2,
s=None, s1=None, s2=None,
align_bf=False)
Determine transport properties of device sandwiched between semi-infinite leads using non-equillibrium
Green function methods.
energies is the energy grid on which the transport properties should be determined.
h1 (h2) is a matrix representation of the Hamiltonian of two principal layers of the left (right) lead, and the
coupling between such layers.
h is a matrix representation of the Hamiltonian of the scattering region. This must include at least on lead
principal layer on each side. The coupling in (out) of the scattering region is assumed to be identical to the
coupling between left (right) principal layers.
s, s1, and s2 are the overlap matrices corresponding to h, h1, and h2. Default is the identity operator.
If align_bf is True, the onsite elements of the Hamiltonians will be shifted to a common fermi level.
This module is stand-alone in the sense that it makes no requirement on the origin of these five matrices. They
can be model Hamiltonians or derived from different kinds of electronic structure codes.
For an example of how to use the ase.transport module, see the GPAW exercise on electron transport
187
ase.data.vdw_radii
All of these are lists that should be indexed with an atomic number:
>>> from ase.data import *
>>> atomic_names[92]
Uranium
>>> atomic_masses[2]
4.0026000000000002
ase.data.atomic_numbers
If you dont know the atomic number of some element, then you can look it up in the atomic_numbers
dictionary:
>>> atomic_numbers[Cu]
29
>>> covalent_radii[29]
1.1699999999999999
The covalent radii are taken from [Cordeo08]. The source of the van der Waals radii is given in vdw.py.
All molecular members of each database is conveniently contained in a list of strings (g1, g2, g3), ??? and one
can look up the experimental atomization energy for each molecule. This is extrapolated from experimental heats
of formation at room temperature, using calculated zero-point energies and thermal corrections.
Example:
>>> from ase.data.g2 import get_atomization_energy
>>> get_atomization_energy(H2O)
232.57990000000001
>>> from ase.units import kcal,mol
>>> get_atomization_energy(H2O)*kcal/mol
10.08562144637833
where the last line converts the experimental atomization energy of H2O from units of kcal/mol to eV.
The coupled-cluster interaction energies for the s22 and s26 systems are retrieved like this:
>>> from ase.data.s22 import s22, get_interaction_energy_s22
>>> get_interaction_energy_s22(s22[0])
-0.1375
188
in units of eV. For s22 these are not the original energies, but from more recent work where the same (large) basis
set was used for all complexes, yielding more accurate coupled-cluster interaction energies.
The s22x5 database expands on the original s22 data by introducing non-equilibrium geometries for each complex
(0.9, 1.0, 1.2, 1.5, and 2.0 times original intermolecular distance). However, these calculations were done in
accordance with the methods used in the original s22 work, and so is expected to inherit the same problems with
mixed basis set sizes. Assuming the interaction energy error due to this is the same in all 5 geometries for each
complex, the default s22x5 interaction energies are therefore corrected with the energy difference between original
and newer energies at the original separation.
Example:
>>> from ase.data.s22 import *
>>> sys1 = s22[0]
>>> sys1
Ammonia_dimer
>>> atoms1 = create_s22_system(sys1)
>>> sys2 = s22x5[0]
>>> sys2
Ammonia_dimer_0.9
>>> atoms2 = create_s22_system(sys2)
>>> sys3 = s22x5[1]
>>> sys3
Ammonia_dimer_1.0
>>> atoms3 = create_s22_system(sys3)
>>> get_interaction_energy_s22(sys1)
-0.1375
>>> get_interaction_energy_s22(sys2)
-0.1375
>>> get_interaction_energy_s22(sys3)
-0.1375
>>> get_interaction_energy_s22x5(sys2)
-0.10549743024963291
>>> get_interaction_energy_s22x5(sys3)
-0.1375
>>> get_interaction_energy_s22x5(sys3,correct_offset=False)
-0.1362
>>> get_interaction_energy_s22x5(sys1,dist=1.0)
-0.1375
>>> get_interaction_energy_s22x5(sys1,dist=0.9)
-0.10549743024963291
>>> get_interaction_energy_s22x5(sys1,dist=0.9,correct_offset=False)
-0.1045
>>> get_number_of_dimer_atoms(sys1)
[4, 4]
>>> get_s22x5_distance(sys2)
-0.25040236345454536
>>> get_s22x5_distance(sys3)
0.0
where sys1 is an s22 complex in the original geometry, while sys2 and sys3 are two different s22x5 geometries
of the exact same complex. It is seen that the interaction energies for an s22 system and its s22x5 equivalent
(indexed _1.0) does not necessarily match when the energy offset-correction is turned off. The last two functions
are convenience functions, giving the number of atoms in the two molecules constituting a dimer and the relative
intermolecular distance in a dimer (relative to the 1.0 separation, and in Angstrom), respectively.
189
The ase.io.trajectory module currently defines two kinds of Trajectory files, the PickleTrajectory and the
BundleTrajectory. PickleTrajectory is the recommended Trajectory format, BundleTrajectory is only intended for
large molecular dynamics simulations (large meaning millions of atoms).
In the future, other kinds of Trajectories may be defined, with similar Python interface but with different underlying
file formats.
7.26.1 PickleTrajectory
The PickleTrajectory has the interface
class ase.io.trajectory.PickleTrajectory(filename, mode=r, atoms=None,
ter=None, backup=True)
Reads/writes Atoms objects into a .traj file.
mas-
190
write(atoms=None)
Write the atoms to the file.
If the atoms argument is not given, the atoms object specified when creating the trajectory object is
used.
Note that there is apparently no methods for reading the trajectory. Reading is instead done by indexing the
trajectory, or by iterating over the trajectory: traj[0] and traj[-1] return the first and last Atoms object in
the trajectory.
Examples
Reading a configuration:
from ase.io.trajectory import PickleTrajectory
traj = PickleTrajectory("example.traj")
atoms = traj[-1]
7.26.2 BundleTrajectory
The BundleTrajectory has the interface
class ase.io.bundletrajectory.BundleTrajectory(filename, mode=r,
backup=True)
Reads and writes atoms into a .bundle directory.
atoms=None,
The BundleTrajectory is an alternative way of storing trajectories, intended for large-scale molecular dynamics simulations, where a single flat file becomes unwieldy. Instead, the data is stored in directory, a
bundle (the name bundle is inspired from bundles in Mac OS, which are really just directories the user is
supposed to think of as a single file-like unit).
Parameters:
filename: The name of the directory. Preferably ending in .bundle.
mode (optional): The file opening mode. r means open for reading, w for writing and a for appending.
Default: r. If opening in write mode, and the filename already exists, the old file is renamed to .bak
(any old .bak file is deleted), except if the existing file is empty.
atoms (optional): The atoms that will be written. Can only be specified in write or append mode. If not
specified, the atoms must be given as an argument to the .write() method instead.
backup=True: Use backup=False to disable renaming of an existing file.
close()
Closes the trajectory.
classmethod delete_bundle(filename)
Deletes a bundle.
191
static is_bundle(filename)
Check if a filename exists and is a BundleTrajectory.
static is_empty_bundle(filename)
Check if a filename is an empty bundle. Assumes that it is a bundle.
log(text)
Write to the log file in the bundle.
Logging is only possible in write/append mode.
This function is mainly for internal use, but can also be called by the user.
post_write_attach(function, interval=1, *args, **kwargs)
Attach a function to be called after writing ends.
function: The function or callable object to be called.
interval: How often the function is called. Default: every time (1).
All other arguments are stored, and passed to the function.
pre_write_attach(function, interval=1, *args, **kwargs)
Attach a function to be called before writing begins.
function: The function or callable object to be called.
interval: How often the function is called. Default: every time (1).
All other arguments are stored, and passed to the function.
read_extra_data(name, n=0)
Read extra data stored alongside the atoms.
Currently only used to read data stored by an NPT dynamics object. The data is not associated with
individual atoms.
select_data(data, value)
Selects if a given data type should be written.
Data can be written in every frame (specify True), in the first frame only (specify only) or not at
all (specify False). Not all data types support the only keyword, if not supported it is interpreted as
True.
The following data types are supported, the letter in parenthesis indicates the default:
positions (T), numbers (O), tags (O), masses (O), momenta (T), forces (T), energy (T), energies (F),
stress (F), magmoms (T)
If a given property is not present during the first write, it will be not be saved at all.
set_extra_data(name, source=None, once=False)
Adds extra data to be written.
Parameters: name: The name of the data.
source (optional): If specified, a callable object returning the data to be written. If not specified it is
instead assumed that the atoms contains the data as an array of the same name.
once (optional): If specified and True, the data will only be written to the first frame.
write(atoms=None)
Write the atoms to the file.
If the atoms argument is not given, the atoms object specified when creating the trajectory object is
used.
192
-1/3
t = V
taylor
A third order Taylor series expansion about the minimum volume
murnaghan
PRB 28, 5480 (1983)
birch
Intermetallic compounds: Principles and Practice,
Vol I: Principles. pages 195-210
birchmurnaghan
PRB 70, 224107
pouriertarantola
PRB 70, 224107
vinet
PRB 70, 224107
antonschmidt
Intermetallics 11, 23-32 (2003)
p3
A third order polynomial fit
Use:
eos = EquationOfState(volumes, energies, eos=sjeos)
v0, e0, B = eos.fit()
eos.plot()
See Also:
The Equation of state tutorial.
193
7.27.3 Phonons
http://phonopy.sourceforge.net/
build(atoms)
Build the list.
get_neighbors(a)
Return neighbors of atom number a.
A list of indices and offsets to neighboring atoms is returned. The positions of the neighbor atoms can
be calculated like this:
indices, offsets = nl.get_neighbors(42)
for i, offset in zip(indices, offsets):
print atoms.positions[i] + dot(offset, atoms.get_cell())
Notice that if get_neighbors(a) gives atom b as a neighbor, then get_neighbors(b) will not return a as
a neighbor - unless bothways=True was used.
update(atoms)
Make sure the list is up to date.
194
-0.762100000000000
0.522700000000000
-0.722900000000000
0.580900000000000
0.580900000000000
1.382000000000000
-1.581400000000000
-0.000000000000000
0.000000000000000
-0.000000000000000
0.887500000000000
-0.887500000000000
0.000000000000000
-0.000000000000000
1.522
1.229
1.090
1.090
80.0
35.0
70.0
JCC,7,(1986),230; AA
JCC,7,(1986),230; AA,CYT,GUA,THY,URA
changed from 331 bsd on NMA nmodes; AA, SUGARS
120.40
109.50
117.00
0.00000 6.02496E-01
-3
# cutoffs
C -CT 2.0
C -O 1.8
CT-HC 1.4
C -H1 1.4
C3-O1 1.8 # extra stuff, should not bother
195
which writes the LAMMPS input files lmp_atoms defining atoms, bonds, etc., and lmp_opls defining the
corresponding OPLS force field. A rudimentary lmp_in is also written.
196
has v3 keyword
has key abc with value H
both of the above
calculations done with NWChem
bandgap key has value between 2.2 and 3.0
10 or more atoms
less than 3 hydrogen atoms
specific id
not older than 1 hour
older than 1 year
integer identifier
number of atoms
potential energy
total charge
total magnetic moment
name of calculator
who did it
age of calculation (use s, m, h, d, w, M and y for second, minute, hour, day, week, month and year
respectively)
197
Also the ase-gui program can read from databases using the same syntax.
or
>>> import ase.db
>>> c = ase.db.connect(abc.db)
Lets do a calculation for a hydrogen molecule and write some results to a database:
>>> from ase import Atoms
>>> from ase.calculators.emt import EMT
>>> h2 = Atoms(H2, [(0, 0, 0), (0, 0, 0.7)])
>>> h2.calc = EMT()
>>> h2.get_forces()
array([[ 0.
, 0.
, -9.80290573],
[ 0.
, 0.
, 9.80290573]])
Write a row to the database with keyword molecule and a key-value pair (relaxed, False):
>>> c.write(h2, [molecule], relaxed=False)
1
The select() method will generate dictionaries that one can loop over. The dictionaries are special in the sense
that keys can be accessed as attributes also (d.relaxed == d[relaxed]).
Write the energy of an isolated hydrogen atom to the database:
198
>>> h = Atoms(H)
>>> h.calc = EMT()
>>> h.get_potential_energy()
3.21
>>> c.write(h)
3
0.
1.]]
199
More details
ase.db.core.connect(name,
type=extract_from_name,
use_lock_file=True)
Create connection to database.
create_indices=True,
reserve(*args, **kwargs)
Write empty row if not already present.
Usage:
id = conn.reserve(keyword1, keyword2, ...,
key1=value1, key2=value2, ...)
Write an empty row with the given keywords and key-value pairs and return the integer id. If such a
row already exists, dont write anything and return None.
get_atoms(selection=None,
**kwargs)
Get Atoms object.
attach_calculator=False,
add_additional_information=False,
200
201
202
203
204
CHAPTER
EIGHT
If you have many images, it will be easier to do it using the Python interpreter:
>>> from ase import *
>>> for n, image in enumerate(read(images.traj@:3)):
...
write(image%d.pov % n, image, run_povray=True, pause=False,
...
rotation=-90x,10z)
Here, we also:
run povray to generate png files
disable pausing between the images
set a rotation (choose View Rotate ... in ase-gui to select the best rotation angles)
Try:
>>> help(write)
8.2 General
8.2.1 Citation: how should I cite ASE?
If you find ASE useful in your research please cite:
S. R. Bahn and K. W. Jacobsen
An object-oriented scripting interface to a legacy electronic structure code
Comput. Sci. Eng., Vol. 4, 56-66, 2002
BibTex (doc/ASE.bib):
205
@Article{ISI:000175131400009,
Author = {S. R. Bahn and K. W. Jacobsen},
Title = {An object-oriented scripting interface to a legacy electronic structure code},
JournalFull = {COMPUTING IN SCIENCE \& ENGINEERING},
Year = {2002},
Volume = {4},
Number = {3},
Pages = {56-66},
Month = {MAY-JUN},
Abstract = {The authors have created an object-oriented scripting interface to a mature density fu
code. The interface gives users a high-level, flexible handle on the code without rewriting the
underlying number-crunching code. The authors also discuss the design issues and advantages of
homogeneous interfaces},
Publisher = {IEEE COMPUTER SOC},
Address = {10662 LOS VAQUEROS CIRCLE, PO BOX 3014, LOS ALAMITOS, CA 90720-1314 USA},
Type = {Article},
Language = {English},
Affiliation = {Bahn, SR (Reprint Author), Tech Univ Denmark, Dept Phys, CAMP, Bldg 307, DK-2800 Ly
Tech Univ Denmark, Dept Phys, CAMP, DK-2800 Lyngby, Denmark.},
ISSN = {1521-9615},
Keywords-Plus = {MULTISCALE SIMULATION; GOLD ATOMS},
Subject-Category = {Computer Science, Interdisciplinary Applications},
Author-Email = {[email protected] [email protected]},
Number-of-Cited-References = {19},
Journal-ISO = {Comput. Sci. Eng.},
Journal = {Comput. Sci. Eng.},
Doc-Delivery-Number = {543YL},
Unique-ID = {ISI:000175131400009},
DOI = {10.1109/5992.998641},
}
8.3 Download
Trying to checkout the code via SVN resulted:
[~]$ svn checkout "https://svn.fysik.dtu.dk/projects/ase/trunk"
svn: Unrecognized URL scheme https://svn.fysik.dtu.dk/projects/ase/trunk
This error is diplayed in case the library libsvn_ra_dav is missing on your system. The library is used by SVN,
but is not installed by default.
206
CHAPTER
NINE
GLOSSARY
API Application Programming Interface. Automatically generated documentation from docstrings in the source
code using Epydoc. See here.
ASE Atomic Simulation Environment.
Class XXX
Constructor XXX
Docstring XXX
DFT Density Functional Theory.
EMT Effective Medium Theory.
HF Hartree-Fock approximation XXX ...
Instance XXX
LAPW In the linearized augmented plane wave (LAPW) method the unit cell of the crystal is divided into two
different types of regions. The first one, called the muffin-tin region, consists of spheres centered around
the atoms, while the second one, called the interstitial region consists of the remaining part of the unit cell.
In the muffin-tin spheres the basis consists of atomic like functions to account for the rapid changes of the
wave function in this area, whereas in the interstitial region the basis functions are plane waves, since the
wave function changes only slowly at some distance from the atomic sites.
Namespace An abstract container of the current scopes variables.
ndarray NumPys n-dimensional array. See Numeric arrays in Python.
NumPy XXX See Numeric arrays in Python.
Method XXX
Python XXX What is Python?.
Scope An enclosing context where values and expressions are associated.
207
208
Chapter 9. Glossary
CHAPTER
TEN
MAILING LISTS
There is a mailing list for discussing ASE:
ase-users
The mailing lists below are of interest for active ASE developers only:
ase-developers
ase-svncheckins
or (mainly) dacapo / ASE-2 users / developers:
campos
campos-devel
209
210
CHAPTER
ELEVEN
LICENSE
Contents
License
Human-readable version
Legal version of the license
What happens when ASE Calculators are under another license?
11.3 What happens when ASE Calculators are under another license?
We are sometimes asked if it is problematic to use ASE together with calculators under other licenses, for example
GPL. It is clear that a program under the GPL can use a library under the LGPL, whereas a program under the
LGPL cannot be derived from (and link) a library under the GPL. Does this cause a problem if someone uses ASE
with a calculator such as GPAW licensed under the GPL? We do not think so, for the following reasons:
1. The LGPL and GPL do not limit how you use the codes, only how you distribute them.
211
2. ASE does not require any specific calculator to function, but many calculators require ASE to function,
supporting the interpretation that ASE is a library for the calculator.
3. Although ASE includes a few cases where it imports calculators such as GPAW and Asap, these can be
regarded as hooks helping ASE to support these calculators, ASE does not depend on these calculators
for its functionality.
4. The LGPL / GPL concept of derived work relies on the concept of linking which only makes sense
in compiled languages. It is generally agreed that it is unproblematic when an interpreted language uses
different modules under different licenses. See e.g. this statement by Fedora: Mere use of independent
modules in a true interpreted language environment (like Perl or Python) is not a situation where Fedora
is generally concerned about license compatibility, as long as those multiply licensed modules are not
compiled together into a single binary and there is no code copying between the two.
5. The actual executable doing the linkage is not ASE, but Python. However, nobody doubts that it is OK for
Python (which has a very permissible license) to load modules licensed under the GPL. Probably because
of point 1 above.
6. Point 5 is not valid when running parallel GPAW or Asap calculations. In these cases GPAW and Asap
provide specially built Python executables with the GPAW or Asap code built-in, i.e. derived work based on
Python but licensed under the GPL (or LGPL for Asap). In these cases it is absolutely clear that it is GPAW
or Asap loading ASE, not the other way around; so there are no problems.
212
CHAPTER
TWELVE
ASE DEVELOPMENT
As a developer, you should subscribe to all ASE related Mailing Lists.
213
214
The s22, s26 and s22x5 sets of van der Waals bonded dimers and complexes by the Hobza group.
The DBH24 set of gas-phase reaction barrier heights by the Truhlar group.
Implementation of the Dimer method.
Version 3.4.1
11 August 2010: tags/3.4.1.
Before you send the patch, please read our Coding Conventions and learn how to use pep8.py, pylint and epydoc:
Run pep8.py on your code
Using pylint to check your code
Run epydoc on your code
One of the current committers will look at the patch and give you some feedback. Maybe the patch is fine and the
committer will commit it to trunk. There could also be some more work to do like:
make it compatible with all supported pythons (see Installation requirements).
write more comments
fix docstrings
write a test
add some documentation
Once everyone is happy, the patch can be applied. This patch-feedback loop is not something we have invented to
prevent you from contributing - it should be viewed as an opportunity for you to learn how to write code that fits
into the ASE codebase.
After a couple of contributions, we will probably trust you enough to add you as a committer.
Committers
Here is the list of current committers:
user name
anpet
askhl
real name
Andrew Peterson
Ask Hjorth Larsen
andrew_peterson:brown,edu
asklarsen:gmail,com
Continued on next page
215
user name
bjork
dlandis
dulak
eojons
ehermes
gdonval
getri
grabow
hahansen
ivca
jakobb
jber
jblomqvist
jensj
jesperf
jesswe
jingzhe
jkitchin
jussie
kkaa
kleis
kwj
lassebv
markus
miwalter
moses
mvanin
pastewka
s032082
schenkst
schiotz
slabanja
strange
tjiang
tolsen
Former committers:
anro
carstenr
hanke
s042606
s052580
Anthony Goodrow
Carsten Rostgaard
Felix Hanke
Janosch Michael Rauba
Troels Kofoed Jacobsen
anro:fysik,dtu,dk
carstenr:fysik,dtu,dk
F,Hanke:liverpool,ac,uk
s042606:fysik,dtu,dk
s052580:fysik,dtu,dk
216
This retrieves the code tree from the subversion repository. Prepend PYTHONPATH and PATH environment
variables as described at Manual installation.
Updating the working copy of the code (in the directory ase-svn):
svn update
The status about the files which are not in version control can be surpassed with the -q flag, and the status
with respect to latest additions in server can be checked with the -u flag.
Committing the changes to the repository
Before sending the changes in the working copy to the repository, working copy should be updated. After
that, the changes can be send with:
svn commit -m "Message to describe the committed changes"
If the -m option is omitted and appropriate environment variable SVN_EDITOR is set, an editor is opened
for writing the log message.
Adding files or directories to version control:
svn add filename
If filename is directory, also all the files within the directory are added. Note that svn commit is
required before the new files are actually included in version control.
ASE documentation resides under doc directory, and is also under subversion control. See more at Writing
documentation.
We distinguish between scripts and code. In your own scripts, its OK to use:
from ase.all import *
217
The project shall follow the generic coding conventions as specified in the Style Guide for Python Code and
Docstring Conventions PEPs, summarized, clarified, and extended as follows:
4 spaces per indentation level. No hard tabs.
Very important: Read the Whitespace in Expressions and Statements section of PEP8.
Avoid introducing trailing whitespaces.
Try to use only 7-bit ASCII, no 8-bit strings.
No one-liner compound statements (i.e., no if x: return: use two lines & indentation), except for
degenerate class or method definitions (i.e., class X: pass is OK.).
Lines should be no more than 78 characters long.
Use StudlyCaps for class names.
Use lowercase or lowercase_with_underscores for function, method, and variable names. For short
names, maximum two words, joined lowercase may be used (e.g. tagname). For long names with three or
more words, or where its hard to parse the split between two words, use lowercase_with_underscores (e.g.,
note_explicit_target, explicit_target). If in doubt, use underscores.
Avoid lambda expressions, which are inherently difficult to understand. Named functions are preferable
and superior: theyre faster (no run-time compilation), and well-chosen names serve to document and aid
understanding.
Avoid functional constructs (filter, map, etc.). Use list comprehensions instead.
Avoid from __future__ import constructs. They are inappropriate for production code.
Use single quotes for string literals, and triple double quotes for docstrings. Double quotes are OK
for something like "dont".
Attention: Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the
number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent,
nor either indent thou two, excepting that thou then proceed to four. Tabs are right out.
Georg Brandl
General advice
Get rid of as many break and continue statements as possible.
Writing documentation in the code
Here is an example of how to write good docstrings:
https://github.com/numpy/numpy/blob/master/doc/example.py
Run pep8.py on your code
The pep8.py program is installed together with ASE tools/pep8.py. It will check the PEP8 conventions for you.
Try:
$ pep8.py --help
218
pylint_ase
Run epydoc on your code
Run:
$ epydoc --docformat restructuredtext --parse-only --show-imports -v dir
219
$ cd ~/ase/doc
$ sphinx-build . _build
Note: Make sure that you build the Sphinx documentation using the corresponding ASE version by setting the
environment variables $PYTHONPATH and $PATH.
Make your changes to the .rst files, run the sphinx-build command again, check the results and if things looks
ok, commit:
$
$
$
$
emacs index.rst
sphinx-build . _build
firefox _build/index.html
svn ci -m "..." index.rst
Extensions to Sphinx
We have a couple of extensions to Sphinx:
:mol:
Use :mol:CH_3OH to get CH3 OH.
:svn:
A role for creating a link to a file in SVN. If you write :svn:ase/atoms.py, you will get:
ase/atoms.py.
:trac:
A role for creating a link to a file in Trac. If you write :trac:ase/atoms.py, you will get:
ase/atoms.py.
:epydoc:
A role for creating a link to the API-documentation generated with epydoc.
:epydoc:ase.atoms.Atoms, you will get: Atoms.
If you write
:math:
This role is for inline LaTeX-style math. Example: :math:\sin(x_n^2) gives you sin(x2n ).
This role is actually the default for ASEs documentation, so you can leave out the :math: part like
here: \sin(x_n^2).
.. math::
Write displayed LaTeX-style math. Example:
.. math:: \frac{1}{1+x^2}
gives you:
1
1 + x2
220
Sphinx will run the script and generate the files that you can then use in your rst-file. Examples:
Equation of state. Source: doc/tutorials/eos/eos.py, doc/tutorials/eos/eos.rst
Finding lattice constants. Source: doc/tutorials/lattice_constant.py, doc/tutorials/lattice_constant.rst
reStructedText in emacs
For people using emacs, the reStructuredText extension is highly recommended. The intallation procedure is
described in the top of the file, but for most people, it is enough to place it in your emacs load-path (typically
.emacs.d/) and add the lines:
(add-to-list load-path "~/.emacs.d")
(require rst)
221
This will create doc/conf.py and doc/contents.rst. Both these files need to be edited further
(doc/conf.py may for example include options for sphinx.ext.pngmath)
class ase.calculators.calculator.Calculator(restart=None,
ignore_bad_restart_file=False, label=None,
atoms=None, **kwargs)
Base-class for all ASE calculators.
A calculator must raise NotImplementedError if asked for a property that it cant calculate. So, if calculation
of the stress tensor has not been implemented, get_stress(atoms) should raise NotImplementedError. This
can be achieved simply by not including the string stress in the list implemented_properties which is a class
member. These are the names of the standard properties: energy, forces, stress, dipole, charges,
magmom and magmoms.
Basic calculator implementation.
restart: str Prefix for restart file. May contain a directory. Default is None: dont restart.
ignore_bad_restart_file: bool Ignore broken or missing restart file. By default, it is an error if the restart
file is missing or broken.
label: str Name used for all files. May contain a directory.
atoms: Atoms object Optional Atoms object to which the calculator will be attached. When restarting,
atoms will get its positions and unit-cell updated from file.
implemented_properties = []
Properties calculator can handle (energy, forces, ...)
default_parameters = {}
Default parameters
set_label(label)
Set label and convert label to directory and prefix.
Examples:
label=abc: (directory=., prefix=abc)
label=dir1/abc: (directory=dir1, prefix=abc)
222
Calculators that must write results to files with fixed names can overwrite this method so that the
directory is set to all of label.
reset()
Clear all information from old calculation.
read(label)
Read atoms, parameters and calculated properties from output file.
Read result from self.label file. Raise ReadError if the file is not there. If the file is corrupted or
contains an error message from the calculation, a ReadError should also be raised. In case of succes,
these attributes must set:
atoms: Atoms object The state of the atoms from last calculation.
parameters: Parameters object The parameter dictionary.
results: dict Calculated properties like energy and forces.
The FileIOCalculator.read() method will typically read atoms and parameters and get the results dict
by calling the read_results() method.
set(**kwargs)
Set parameters like set(key1=value1, key2=value2, ...).
A dictionary containing the parameters that have been changed is returned.
Subclasses must implement a set() method that will look at the chaneged parameters and decide if a
call to reset() is needed. If the changed parameters are harmless, like a change in verbosity, then there
is no need to call reset().
The special keyword parameters can be used to read parameters from a file.
check_state(atoms, tol=1e-15)
Check for system changes since last calculation.
calculate(atoms=None, properties=[energy], system_changes=[positions, numbers, cell,
pbc, initial_charges, initial_magmoms])
Do the calculation.
properties: list of str List of what needs to be calculated. Can be any combination of energy,
forces, stress, dipole, charges, magmom and magmoms.
system_changes: list of str List of what has changed since last calculation. Can be any combination
of these five: positions, numbers, cell, pbc, initial_charges and initial_magmoms.
Subclasses need to implement this, but can ignore properties and system_changes if they want. Calculated properties should be inserted into results dictionary like shown in this dummy example:
self.results = {energy: 0.0,
forces: np.zeros((len(atoms), 3)),
stress: np.zeros(6),
dipole: np.zeros(3),
charges: np.zeros(len(atoms)),
magmom: 0.0,
magmoms: np.zeros(len(atoms))}
The subclass implementation should first call this implementation to set the atoms attribute.
calculate_numerical_forces(atoms, d=0.001)
Calculate numerical forces using finite difference.
All atoms will be displaced by +d and -d in all directions.
223
class ase.calculators.calculator.FileIOCalculator(restart=None,
ignore_bad_restart_file=False,
label=None, atoms=None, command=None, **kwargs)
Base class for calculators that write/read input/output files.
File-IO calculator.
command: str Command used to start calculation.
command = None
Command used to start calculation
write_input(atoms, properties=None, system_changes=None)
Write input file(s).
Call this method first in subclasses so that directories are created automatically.
read_results()
Read energy, forces, ... from output file(s).
224
225
Note that the tags_revision is put into the name of the tar file automatically. Make sure that you are
getting only tags_revision in the tar file name! Any changes to the source will be reflected as a mixed
or modified revision tag!
Put the tar file on webX (set it read-able for all):
scp dist/python-ase-3.1.0."tags_revision".tar.gz root@webX:/var/www/wiki/ase-files
Add a link on News and update the information on the Installation requirements page and the Release notes
page.
Add the new release on https://pypi.python.org/pypi/python-ase/:
under the edit menu increase the version number to 3.1.0
under the files menu add the tar file as File Type Source
Increase the version number in ase/version.py, and commit the change:
cd ~/ase
svn ci -m "Version 3.2.0"
226
Important: Unlike normally, the module __name__ will be set to __builtin__ when a test script is run
by the test suite.
12.1.10 Buildbot
buildbot is a continuous integration system. The server called buildmaster defines and schedules processes
of building and testing of software to be performed by so called builders on machines called buildslaves
(or buildbots). One buildslave can have several builders associated (for example a given operating system version buildslave performs testing of several software branches builders). One builder can also be associated with several buildslaves (several, identical machines running the same operating system), in which
case buildmaster will schedule the given builder to switch periodically between the buildslaves. At the
time of writing (2012) buildbot does not offer satisfactory security mechanisms, and due to clear text passwords
227
stored/transferred both on buildmaster and buildslaves external security measures like firewall, proxy,
ssh/stunnel should be used.
The sections below describe the configuration of buildmaster and buildslaves.
Configuration of buildmaster
The buildmaster should be running as unprivileged user (usually called buildmaster). The user and group
need to be created.
In order to install buildbot on RHEL6 system you need:
yum install python-twisted python-jinja2 python-tempita
wget https://downloads.sourceforge.net/project/sqlalchemy/sqlalchemy/0.7.9/SQLAlchemy-0.7.9.tar.gz
wget http://sqlalchemy-migrate.googlecode.com/files/sqlalchemy-migrate-0.7.2.tar.gz
It is sufficient to unpack the files and set PYTHONPATH, and PATH accordingly. Buildbot may need to
be patched for twisted compatibility http://www.npcglib.org/~stathis/blog/2012/10/20/bug-buildbot-dies-withexceptions-importerror-cannot-import-name-noresource/
Proceed with buildbot configuration:
create the master:
buildbot create-master --relocatable python-ase
consider setting up a crontab which starts buildmaster after the server reboot (this solution is not reliable, deploy rather init scripts - see below):
# run every 5 minutes
*/5 * * * * sh ~/python-ase-restart.sh
228
python-ase buildmaster
345 98 02
python-ase buildmaster
# LSB init-info
### BEGIN INIT INFO
# Provides:
# Required-Start:
# Required-Stop:
# Default-Start:
# Default-Stop:
# Short-Description:
### END INIT INFO
python-ase
$network
$network
2 3 4 5
0 1 6
python-ase buildmaster
start() {
echo -n $"Starting python-ase buildmaster: "
dostatus > /dev/null 2>&1
if [ $RETVAL -eq 0 ]
then
echo -n $"python-ase buildmaster already running"
log_failure_msg
RETVAL=1
return
fi
#su - $RUN_AS -s /bin/sh -c "exec nohup /bin/sh $PYTHON_ASE_HOME/../python-ase-start.
# dont produce log
su - $RUN_AS -s /bin/sh -c "exec nohup /bin/sh $PYTHON_ASE_HOME/../python-ase-start.s
RETVAL=$?
if [ $RETVAL -eq 0 ]
then
sleep 5
su - $RUN_AS -s /bin/sh -c "cat $PYTHON_ASE_HOME/twistd.pid > $PIDFILE"
su - $RUN_AS -s /bin/sh -c "touch $LOCKFILE"
log_success_msg
else
log_failure_msg
fi
return $RETVAL
}
stop() {
echo -n $"Shutting down python-ase buildmaster: "
kill $(su - $RUN_AS -s /bin/sh -c "cat $PIDFILE 2>/dev/null") > /dev/null 2>&1
RETVAL=$?
sleep 5
if [ $RETVAL -eq 0 ]
then
229
dostatus() {
kill -0 $(cat $PIDFILE 2>/dev/null) > /dev/null 2>&1
RETVAL=$?
if [ $RETVAL -eq 0 ]
then
echo "python-ase buildmaster (pid $(cat $PIDFILE 2>/dev/null)) is running..."
else
if [ -f $PIDFILE ]
then
echo "python-ase buildmaster dead but pid file exists"
RETVAL=1
return
fi
if [ -f $LOCKFILE ]
then
echo "python-ase buildmaster dead but subsys locked"
RETVAL=2
return
fi
echo "python-ase buildmaster is stopped"
RETVAL=3
fi
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
dostatus
;;
restart|reload)
restart
;;
condrestart)
condrestart
;;
*)
echo $"Usage: $0 {start|stop|status|restart|reload|condrestart}"
exit 1
esac
230
exit $RETVAL
started with:
service python-ase-buildmaster start
231
Installation
python-ase-fedora+18+x86_64+gcc+2.7-start.sh simply exports the necessary environment variables (if needed) and starts buildslave (use the full path), e.g.:
#!/bin/sh
bot=/home/buildslave-username/python-ase-fedora+18+x86_64+gcc+2.7
buildslave start $bot
Choose User and Group under which buildslave will be running. The service is started with:
systemctl start python-ase-fedora-18-x86_64-gcc-2.7.service
then:
easy_install --install-dir=$HOME/buildbot-slave-el5 zope.interface==3.6.7
easy_install --install-dir=$HOME/buildbot-slave-el5 twisted==9.0.0 # ignore errors
easy_install --install-dir=$HOME/buildbot-slave-el5 buildbot-slave
232
4. create a local (domain computer-name) user that will run the buildbot service:
control panel->administrative tools->computer management->local users and groups->users->new
Click the created user: member of: administrators->check names
7. start the service (for the moment it does not start any buildslave, because they are not configured yet):
Start->Control Panel> Administrative Tools->Services->Buildbot (Start)
There are additional steps mentioned in the buildbot wiki, but it seems just to work on Windows 7.
8. run regedit as administrator (type regedit on the command line) and add directories parameter of the
String Value type, containing paths to all your buildslave instances (they will be configured in the
Configuration section below):
9. configure buildslave instance as described in the Configuration section below and start the service again
(point 7.). Test that buildslave comes online, and verify that the service starts after reboot.
233
Configuration
After having installed the buildbot create a name which will identify your buildslave. Obtain the first part of
the name for your buildslave by running doc/development/master.cfg:
python master.cfg
ASE_BB_PORT is the port ASE buildbot uses for communication with the buildslave. You will have to tell
us the name and password of your buildslave. Please contact ase-developers list Mailing Lists, but dont send
the name and password there!
Edit the python-ase-redhat+6+x86_64+gcc+2.6/info/{admin,info} files:
buildslave configuration relevant for the builder process in the info file.
describe your
Note that before starting the slave you need to perform an temporary svn checkout of ASE in order to accept the
certificate permanently.
Start the buildslave with:
buildslave start python-ase-redhat+6+x86_64+gcc+2.6
Dont forget to configure a crontab job or a service as described in the previous sections.
By default all slaves run the continuous integration for the trunk. If you prefer your buildslave works also on
one of the branches, write this in the email to ase-developers Mailing Lists.
234
#: ../energyforces.py:61
msgid "Calculate potential energy and the force on all atoms"
msgstr "Beregn potentiel energi og krfter p alle atomer"
Your editor may wholly or partially hide some of the difficult formatting syntax. This next example shows a more
syntactically complex case in case you need it:
#: ../calculator.py:107
msgid ""
"GPAW implements Density Functional Theory using a\n"
"<b>G</b>rid-based real-space representation of the wave\n"
"functions, and the <b>P</b>rojector <b>A</b>ugmented <b>W</b>ave\n"
"method for handling the core regions. \n"
msgstr ""
"GPAW implementerer tthedsfunktionalteori med en <b>G</b>itterbaseret\n"
"reprsentation af blgefunktioner i det reelle rum, samt\n"
"<b>P</b>rojector <b>A</b>ugmented <b>W</b>ave-metoden til behandling\n"
"af regionen omkring atomkerner. \n"
If you are maintaining an existing translation, there may be some fuzzy messages. These are translations that
were written previously but now need to be reviewed, maybe because the original string has been slightly modified.
Edit them as appropriate and remove the fuzzy flag.
There will be a few special constructs such as string substitution codes %(number)d or %s. These should remain
unchanged in the translation as they are replaced by numbers or text at runtime. An underscore like in msgid
"_File" indicates that F is a shortcut key. Conflicting shortcut keys are not a big problem, but avoid them if
you see them. Finally, some messages may have a lot of whitespace in them. This is due to bad programming
style; just try to get approximately the same spacing in your translation.
Already after writing a few translations, you can check that the translation works as expected by following the
instructions in the next section.
Check and commit your translation
You can check the syntax by running msgfmt -cv ag.po. This will report any syntax errors.
You can test your translation in ase-gui directly. First issue the command make in ase/gui/po,
then reinstall ASE using the usual procedure. The translations will then be in the newly installed ASE. If
you translate into the same language as your computers locale, you should see the translations when you
start ase-gui normally. If you translate ASE into another language, then run LANG=ll_LL.UTF-8
ase-gui. On some operating systems you may need to run LANGUAGE=ll_LL.UTF-8 ase-gui
instead.
Depending on your operating system, you may need to install gettext or locales.
Send the partially or completely translated po-file to the developers mailing list and ask to have it committed. In
fact, we will be quite thrilled if you send an e-mail even before you start, and be sure to send one whenever you
have questions.
Note: Certain uncommon languages such as Lojban, Anglo-Saxon or Klingon may not be compatible with our
current build system. Please let us know if you want to translate ASE into such languages.
Maintaining translations
Messages will once in a while be added or changed in the ASE. Running make in ase/gui/po automatically
synchronizes all templates with the messages in the current source tree while maximally reusing the existing
translations. Some strings may be marked fuzzy, indicating that they need review by translators (this happens
e.g. if an English message is changed only slightly). One can then update the few fuzzy or untranslated messages.
The obvious time to do this is shortly before a new stable release.
235
If you are a committer, please run make before committing and briefly check by running the translated ase-gui
that nothing is obviously horrible.
12.1.12 To do
Check our issue tracker.
Documentation
Put example of Verlet dynamics in ase/md
talk about writing files - pos, py and pckl
Write more about the parameters of the supported elements of the EMT calculator.
Code
Could the directions argument of ase.lattice.FaceCenteredCubic etc. have default values?
When a calculator calculates the energy, forces, stress tensor, total magnetic moment, atomic magnetic moments
or dipole moment, it should store a copy of the system (atomic numbers, atomic positions, unit cell and boundary
conditions). When asked again, it should return the value already calculated if the system hasnt been changed.
If calculational parameters such as plane wave cutoff or XC-functional has been changed the calculator should
throw away old calculated values.
236
Standards parameters
The standard keywords that all calculators must use (if they make sense) are: xc, kpts, smearing, charge
and nbands. Each calculator will have its own default values for these parameters see recommendations
below. In addition, calculators will typically have many other parameters. The units are eV and .
Initial magnetic moments are taken from the Atoms object.
xc It is recommended that LDA and PBE are valid options.
kpts
(1,1,1): Gamma-point
(n1,n2,n3): Monkhorst-Pack grid
(n1,n2,n3,gamma): Shifted Monkhorst-Pack grid that includes
[(k11,k12,k13),(k21,k22,k23),...]: Explicit list in units of the reciprocal
lattice vectors
kpts=3.5: ~k-point density as in 3.5 ~k-points per 1
smearing The smearing parameter must be given as a tuple:
(Fermi-Dirac, width)
(Gaussian, width)
(Methfessel-Paxton, width, n), where n is the order (n = 0 is the same as
Gaussian)
Lower-case strings are also allowed. The width parameter used for the chosen smearing
method is in eV units.
charge Charge of the system in units of |e| (charge=1 means one electron has been removed).
nbands Each band can be occupied by two electrons.
ABC calculator example
A calculator should be able to prefix all output files with a given label or run the calculation in a directory with a
specified name. This is handled by the label argument. There are three possibilities:
Name of a file containing all results of a calculation (possibly containing a directory).
A prefix used for several files containing results. The label may have both a directory part and a prefix part
like LDA/mol1.
Name of a directory containing result files with fixed names.
Each calculator can decide what the default value is: None for no output, - for standard output or something
else.
If the restart argument is given, atomic configuration, input parameters and results will be read from a previous
calculation from the file(s) pointed to by the restart argument. It is an error if those files dont exist and are
corrupted. This error can be ignored bu using ignore_bad_restart=True.
The atoms argument is discussed below. All additional parameters are given as keyword arguments.
Example: Do a calculation with ABC calculator and write results to si.abc:
237
If we do:
>>> atoms = ABC.read_atoms(si.abc)
>>> atoms.rattle()
# change positions and/or
>>> atoms.calc.set(xc=PBE) # change a calculator-parameter
>>> atoms.get_potential_energy()
-0.7
This will automatically attach the calculator to the atoms and the atoms will be updated form the file. If you
add ignore_bad_restart=True, you will be able to use the same script to do the initial calculation where
si.abc does not exist and following calculations where atoms may have been moved arround by an optimization
algorithm.
The command used to start the ABC code can be given in an environment variable called ASE_ABC_COMMAND
or as a command keyword. The command can look like this:
mpiexec abc PREFIX.input > PREFIX.output
or like this:
~/bin/start_abc.py PREFIX
238
description
ASEs GUI
Translate old ASE-2 code to ASE-3 style
Run tests
First attempt to create a command that can do everything
Second attempt
Wrap atoms outside simulation box to inside box
Write information about trajectory file
description
ASEs GUI
Write information about files
Run tests
Build simple molecule or bulk structure
Run calculations with ASEs calculators
Put stuff into or query database
Comments
ag:
Renamed to ase-gui.
ASE2ase:
Removed no longer needed.
testase:
Renamed to ase-test. Alternative:
python setup.py test
instead.
trajectoryinfo:
Replaced by new more general command ase-info that can pull out information from anything that
ASE can read.
12.1. Development topics
239
Naming convention
Any suggestions for better names or are the proposed ones OK? The good thing about using ase-something for
all is that it is consistent and if you know one command, you will maybe discover the other ones when you do
tab-completion.
Implementation details
Should we use the very nice argparse module, which is the future but only available in Python 2.7, or
should we stick with the old and deprecated optparse module?
and type a good password twice. The encrypted password will be printed on the screen.
Alternatively, you can use:
openssl passwd -apr1
240
CHAPTER
THIRTEEN
BUGS!
If you find a bug in the ASE software, please report it to the developers so it can be fixed. We need that feedback
from the community to maintain the quality of the code.
241
242
CHAPTER
FOURTEEN
The new ASE can actually read old NetCDF trajectory files, so this would be simpler:
from ase import *
a = read(a.nc)
Note:
Reading old NetCDF files in the new ASE, works even without having the libnetcdf and
Scientific.IO.NetCDF libraries installed.
Check that the differences look OK. The conversion tool isnt clever enough to get everything right, so you will
have to do some conversion manually also. If you have any problems doing this, then you should not hesitate to
contact the campos-devel mailing list (see Mailing Lists) and ask for help.
243
244
BIBLIOGRAPHY
[Alfe] D. Alfe, PHON: A program to calculate phonons using the small displacement method, Comput. Phys.
Commun. 180, 2622 (2009)
[Wang] Y. Wang et al., A mixed-space approach to first-principles calculations of phonon frequencies for polar
materials, J. Phys.: Cond. Matter 22, 202201 (2010)
[MonkhorstPack] Hendrik J. Monkhorst and James D. Pack: Special points for Brillouin-zone integrations, Phys.
Rev. B 13, 51885192 (1976)
[Bader] R. F. W. Bader. Atoms in Molecules: A Quantum Theory. Oxford University Press, New York, 1990.
[Tang] W. Tang, E. Sanville, G. Henkelman. A grid-based Bader analysis algorithm without lattice bias. J. Phys.:
Compute Mater. 21, 084204 (2009).
[Cordeo08] Covalent radii revisited, Beatriz Cordero, Vernica Gmez, Ana E. Platero-Prats, Marc Revs,
Jorge Echeverra, Eduard Cremades, Flavia Barragn and Santiago Alvarez, Dalton Trans., 2008, 2832-2838
DOI:10.1039/B801115J
245
246
Bibliography
a
ase, 54
ase.atom, 67
ase.atoms, 55
ase.calculators, 113
ase.calculators.abinit, 120
ase.calculators.aims, 129
ase.calculators.ase_qmmm_manyqm, 145
ase.calculators.castep, 121
ase.calculators.dftb, 125
ase.calculators.eam, 116
ase.calculators.emt, 120
ase.calculators.exciting, 127
ase.calculators.fleur, 132
ase.calculators.gromacs, 133
ase.calculators.jacapo, 135
ase.calculators.lammps, 137
ase.calculators.LAMMPSrun, 138
ase.calculators.nwchem, 139
ase.calculators.siesta, 139
ase.calculators.turbomole, 142
ase.calculators.vasp, 143
ase.constraints, 151
ase.data, 187
ase.db, 196
ase.db.core, 198
ase.dft, 176
ase.dft.dos, 182
ase.dft.kpoints, 177
ase.dft.wannier, 179
ase.dimer, 201
ase.gui, 75
ase.infrared, 170
ase.io, 69
ase.io.opls, 194
ase.io.trajectory, 189
ase.lattice, 97
ase.lattice.spacegroup, 29
ase.lattice.surface, 88
ase.md, 172
ase.md.langevin, 174
ase.md.npt, 175
ase.md.nptberendsen, 176
ase.md.nvtberendsen, 174
ase.md.verlet, 174
ase.neb, 157
ase.optimize, 101
ase.optimize.basin, 105
ase.optimize.bfgslinesearch, 104
ase.optimize.fire, 103
ase.optimize.lbfgs, 103
ase.optimize.mdmin, 103
ase.optimize.qn, 102
ase.optimize.sciopt, 104
ase.parallel, 106
ase.phonons, 161
ase.structure, 86
ase.test, 226
ase.thermochemistry, 163
ase.transport, 186
ase.units, 68
ase.utils, 193
ase.vibrations, 159
ase.visualize, 106
ase.visualize.vtk, 107
b
basics, 75
c
calculate, 82
e
edit, 78
s
setup, 81
t
tools, 79
v
view, 78
vtk, 111
247
248
INDEX
Symbols
ase.transport.calculators.TransportCalculator (class in
ase.transport), 187
ase.units (module), 68
ase.utils (module), 193
ase.vibrations (module), 159
ase.visualize (module), 106
ase.visualize.vtk (module), 107
ASE2ase, 243
ASE_ABC_COMMAND, 115, 238
ASE_NWCHEM_COMMAND, 139
assert() (in module ase.test), 227
Atom (class in ase.atom), 67
atomic_masses (in module ase.data), 187
atomic_names (in module ase.data), 187
atomic_numbers (in module ase.data), 188
Atoms (class in ase.atoms), 60
B
basics (module), 75
bcc100() (in module ase.lattice.surface), 89
bcc110() (in module ase.lattice.surface), 90
bcc111() (in module ase.lattice.surface), 90
build()
(ase.calculators.neighborlist.NeighborList
method), 194
Bulk modulus, 193
bulk() (in module ase.lattice), 86
BundleTrajectory (class in ase.io.bundletrajectory), 191
close()
(ase.io.bundletrajectory.BundleTrajectory
method), 191
close() (ase.io.trajectory.PickleTrajectory method), 190
command (ase.calculators.calculator.FileIOCalculator
attribute), 224
connect() (in module ase.db.core), 200
constraints (ase.atoms.Atoms attribute), 61
Constructor, 207
copy() (ase.atoms.Atoms method), 61
covalent_radii (in module ase.data), 187
cpk_colors (in module ase.data), 187
CrystalThermo (class in ase.thermochemistry), 166
D
Database (class in ase.db.core), 200
default_parameters (ase.calculators.calculator.Calculator
attribute), 222
delete() (ase.db.core.Database method), 201
delete_bundle() (ase.io.bundletrajectory.BundleTrajectory
class method), 191
DFT, 207
DFTCalculator (class in ase.calculators.interface), 150
diamond100() (in module ase.lattice.surface), 89
diamond111() (in module ase.lattice.surface), 91
DimerControl (class in ase.dimer), 202
DimerEigenmodeSearch (class in ase.dimer), 203
Docstring, 207
DOS (class in ase.dft.dos), 183
E
calc (ase.atoms.Atoms attribute), 61
edit (module), 78
calculate (module), 82
calculate()
(ase.calculators.calculator.Calculator edit() (ase.atoms.Atoms method), 61
EMT, 207
method), 223
calculate() (ase.calculators.fleur.FLEUR method), 133 EMT (class in ase.calculators.emt), 120
environment variable
calculate_ldos() (ase.dft.stm.STM method), 184
$HOME, 11
calculate_numerical_forces()
$PATH, 220
(ase.calculators.calculator.Calculator
$PYTHONPATH, 220
method), 223
ABINIT_PP_PATH, 120
calculation_required() (ase.calculators.interface.Calculator
ASE_ABC_COMMAND, 115, 238
method), 150
ASE_ABINIT_COMMAND, 120
Calculator (class in ase.calculators.calculator), 222
ASE_NWCHEM_COMMAND, 139
Calculator (class in ase.calculators.interface), 150
FLEUR, 132
Castep (class in ase.calculators.castep), 121
FLEUR_INPGEN, 132
cc12_2x3 (in module ase.dft.kpoints), 177
HOME, 15
cc162_1x1 (in module ase.dft.kpoints), 177
LAMMPS_COMMAND, 138
cc162_sq3xsq3 (in module ase.dft.kpoints), 177
PATH, 15, 217, 228
cc18_1x1 (in module ase.dft.kpoints), 177
PYTHONPATH, 15, 20, 217, 228
cc18_sq3xsq3 (in module ase.dft.kpoints), 177
PYTHONSTARTUP, 18
cc54_1x1 (in module ase.dft.kpoints), 177
SIESTA_PP_PATH, 140
cc54_sq3xsq3 (in module ase.dft.kpoints), 177
SIESTA_SCRIPT, 140
cc6_1x1 (in module ase.dft.kpoints), 177
SVN_EDITOR, 217
cell (ase.atoms.Atoms attribute), 61
VASP_PP_PATH, 143
center() (ase.atoms.Atoms method), 61
VASP_SCRIPT, 143
check_state()
(ase.calculators.calculator.Calculator
EquationOfState
(class in ase.utils.eos), 193
method), 223
Exciting (class in ase.calculators.exciting), 127, 129
chemical_symbols (in module ase.data), 187
extend() (ase.atoms.Atoms method), 61
Class, 207
250
Index
get_entropy()
(ase.thermochemistry.CrystalThermo
method),
166
fcc100() (in module ase.lattice.surface), 89
get_entropy()
(ase.thermochemistry.HarmonicThermo
fcc110() (in module ase.lattice.surface), 89
method), 166
fcc111() (in module ase.lattice.surface), 90
get_entropy()
(ase.thermochemistry.IdealGasThermo
fcc211() (in module ase.lattice.surface), 90
method),
164
FieldPlotter (class in ase.visualize.fieldplotter), 110
get_fermi_level()
(ase.calculators.interface.DFTCalculator
FileIOCalculator (class in ase.calculators.calculator),
method), 150
224
get_forces()
(ase.atoms.Atoms method), 62
Filter (class in ase.constraints), 155
get_forces()
(ase.calculators.interface.Calculator
FixAtoms (class in ase.constraints), 152
method),
150
FixBondLength (class in ase.constraints), 152
get_free_energy()
(ase.thermochemistry.HarmonicThermo
FixBondLengths (class in ase.constraints), 152
method), 166
FixedLine (class in ase.constraints), 152
get_free_energy()
(ase.thermochemistry.IdealGasThermo
FixedMode (class in ase.constraints), 153
method),
164
FixedPlane (class in ase.constraints), 153
get_frequencies()
(ase.vibrations.Vibrations
method),
FixInternals (class in ase.constraints), 154
160
FLEUR, 132
get_function() (ase.dft.wannier.Wannier method), 180
FLEUR_INPGEN, 132
get_functional_value()
(ase.dft.wannier.Wannier
fold() (ase.vibrations.Vibrations method), 160
method), 180
get_gibbs_energy() (ase.thermochemistry.HarmonicThermo
G
method), 166
get() (ase.db.core.Database method), 200
get_gibbs_energy() (ase.thermochemistry.IdealGasThermo
get_actor() (ase.visualize.vtk.module.vtkGlyphModule
method), 164
method), 113
get_hamiltonian() (ase.dft.wannier.Wannier method),
get_angle() (ase.atoms.Atoms method), 61
180
get_angular_momentum() (ase.atoms.Atoms method),
get_hamiltonian_kpoint()
(ase.dft.wannier.Wannier
62
method), 180
get_array() (ase.atoms.Atoms method), 62
get_helmholtz_energy()
get_atomic_numbers() (ase.atoms.Atoms method), 62
(ase.thermochemistry.CrystalThermo
get_atoms() (ase.db.core.Database method), 200
method), 166
get_averaged_current() (ase.dft.stm.STM method), 184
get_hopping() (ase.dft.wannier.Wannier method), 181
get_bandpath() (in module ase.dft.kpoints), 178
get_ibz_k_points() (ase.calculators.interface.DFTCalculator
get_bz_k_points() (ase.calculators.interface.DFTCalculator
method), 150
method), 150
get_initial_charges() (ase.atoms.Atoms method), 63
get_calculation_done() (ase.atoms.Atoms method), 62
get_initial_magnetic_moments()
(ase.atoms.Atoms
get_calculator() (ase.atoms.Atoms method), 62
method), 63
get_cell() (ase.atoms.Atoms method), 62
get_internal_energy() (ase.thermochemistry.CrystalThermo
get_celldisp() (ase.atoms.Atoms method), 62
method), 167
get_center_of_mass() (ase.atoms.Atoms method), 62
get_internal_energy() (ase.thermochemistry.HarmonicThermo
get_centers() (ase.dft.wannier.Wannier method), 180
method), 166
get_charges() (ase.atoms.Atoms method), 62
get_isotropic_pressure() (ase.atoms.Atoms method), 63
get_chemical_formula() (ase.atoms.Atoms method), 62
get_k_point_weights() (ase.calculators.interface.DFTCalculator
get_chemical_symbols() (ase.atoms.Atoms method),
method), 150
62
get_kinetic_energy() (ase.atoms.Atoms method), 63
get_dihedral() (ase.atoms.Atoms method), 62
get_magnetic_moment() (ase.atoms.Atoms method),
get_dipole_moment() (ase.atoms.Atoms method), 62
63
get_distance() (ase.atoms.Atoms method), 62
get_magnetic_moment()
get_distribution_moment() (in module ase.dft), 183
(ase.calculators.interface.DFTCalculator
get_dos() (ase.dft.dos.DOS method), 183
method), 150
get_effective_potential()
get_magnetic_moments() (ase.atoms.Atoms method),
(ase.calculators.interface.DFTCalculator
63
method), 150
get_masses() (ase.atoms.Atoms method), 63
get_eigenvalues() (ase.calculators.interface.DFTCalculator
get_mode() (ase.vibrations.Vibrations method), 160
method), 150
get_momenta() (ase.atoms.Atoms method), 63
get_energies() (ase.dft.dos.DOS method), 183
get_moments_of_inertia() (ase.atoms.Atoms method),
get_energies() (ase.vibrations.Vibrations method), 160
63
get_enthalpy() (ase.thermochemistry.IdealGasThermo
get_monkhorst_pack_size_and_offset() (in module
method), 164
Index
251
ase.dft.kpoints), 177
has() (ase.atoms.Atoms method), 64
get_neighbors() (ase.calculators.neighborlist.NeighborListhcp0001() (in module ase.lattice.surface), 91
method), 194
hcp10m10() (in module ase.lattice.surface), 89
get_number_of_atoms() (ase.atoms.Atoms method), 63 HF, 207
get_number_of_bands()
HOME, 15
(ase.calculators.interface.DFTCalculator
I
method), 151
get_number_of_grid_points()
IdealGasThermo (class in ase.thermochemistry), 164
(ase.calculators.interface.DFTCalculator
implemented_properties
method), 151
(ase.calculators.calculator.Calculator
atget_number_of_spins()
tribute), 222
(ase.calculators.interface.DFTCalculator
InfraRed (class in ase.infrared), 170
method), 151
initial_wannier() (ase.calculators.interface.DFTCalculator
get_occupation_numbers()
method), 151
(ase.calculators.interface.DFTCalculator
initialize() (ase.dft.wannier.Wannier method), 181
method), 151
initialize_density()
(ase.calculators.fleur.FLEUR
get_pbc() (ase.atoms.Atoms method), 63
method), 133
get_pdos() (ase.dft.wannier.Wannier method), 181
Instance, 207
get_points() (ase.visualize.vtk.grid.vtkAtomicPositions interpolate() (ase.neb.NEB method), 157
method), 113
is_bundle() (ase.io.bundletrajectory.BundleTrajectory
get_positions() (ase.atoms.Atoms method), 63
static method), 191
get_potential_energies() (ase.atoms.Atoms method), 63 is_empty_bundle() (ase.io.bundletrajectory.BundleTrajectory
get_potential_energy() (ase.atoms.Atoms method), 63
static method), 192
get_potential_energy() (ase.calculators.interface.Calculator
J
method), 150
get_pseudo_density() (ase.calculators.interface.DFTCalculator
Jacapo (class in ase.calculators.jacapo), 136
method), 151
get_pseudo_wave_function()
L
(ase.calculators.interface.DFTCalculator
LAMMPS (class in ase.calculators.LAMMPSrun), 138
method), 151
LAMMPS_COMMAND, 138
get_radii() (ase.dft.wannier.Wannier method), 181
Langevin (class in ase.md.langevin), 174
get_reciprocal_cell() (ase.atoms.Atoms method), 63
LAPW, 207
get_scaled_positions() (ase.atoms.Atoms method), 63
linescan() (ase.dft.stm.STM method), 184
get_spectrum() (ase.infrared.InfraRed method), 172
localize() (ase.dft.wannier.Wannier method), 181
get_spin_polarized() (ase.calculators.interface.DFTCalculator
log()
(ase.io.bundletrajectory.BundleTrajectory
method), 151
method), 192
get_stress() (ase.atoms.Atoms method), 64
log() (ase.visualize.fieldplotter.FieldPlotter method),
get_stress()
(ase.calculators.interface.Calculator
110
method), 150
log() (ase.visualize.primiplotter.PrimiPlotter method),
get_stresses() (ase.atoms.Atoms method), 64
109
get_tags() (ase.atoms.Atoms method), 64
get_temperature() (ase.atoms.Atoms method), 64
M
get_total_energy() (ase.atoms.Atoms method), 64
max_spread() (ase.dft.wannier.Wannier method), 181
get_unstructured_grid()
Method, 207
(ase.visualize.vtk.grid.vtkAtomicPositions
MinModeAtoms (class in ase.dimer), 203
method), 113
MinModeTranslate (class in ase.dimer), 203
get_velocities() (ase.atoms.Atoms method), 64
molecule() (in module ase.structure), 86
get_volume() (ase.atoms.Atoms method), 64
monkhorst_pack() (in module ase.dft.kpoints), 177
get_wannier_localization_matrix()
(ase.calculators.interface.DFTCalculator
N
method), 151
Namespace, 207
get_xc_functional() (ase.calculators.interface.DFTCalculator
nanotube() (in module ase.structure), 87
method), 151
ndarray, 207
graphene_nanoribbon() (in module ase.structure), 88
NEB (class in ase.neb), 157
gui, 75
NeighborList (class in ase.calculators.neighborlist), 194
new_array() (ase.atoms.Atoms method), 64
H
NPT (class in ase.md.npt), 175
HarmonicThermo (class in ase.thermochemistry), 166
NPTBerendsen (class in ase.md.nptberendsen), 176
252
Index
Scope, 207
select() (ase.db.core.Database method), 201
select_data() (ase.io.bundletrajectory.BundleTrajectory
method), 192
O
set() (ase.calculators.calculator.Calculator method),
223
open() (ase.io.trajectory.PickleTrajectory method), 190
set() (in module ase.calculators), 116
set_actor() (ase.visualize.vtk.module.vtkGlyphModule
P
method), 113
paropen() (in module ase.parallel), 106
set_angle()
(ase.atoms.Atoms method), 65
parprint() (in module ase.parallel), 106
set_array()
(ase.atoms.Atoms
method), 65
PATH, 15, 217, 228
set_atomic_numbers()
(ase.atoms.Atoms
method), 65
pbc (ase.atoms.Atoms attribute), 64
set_atoms()
(ase.io.trajectory.PickleTrajectory
PickleTrajectory (class in ase.io.trajectory), 190
method), 190
plot() (ase.visualize.fieldplotter.FieldPlotter method),
set_background()
(ase.visualize.fieldplotter.FieldPlotter
110
method),
110
plot() (ase.visualize.primiplotter.PrimiPlotter method),
set_background_color()
109
(ase.visualize.fieldplotter.FieldPlotter
pop() (ase.atoms.Atoms method), 64
method), 110
positions (ase.atoms.Atoms attribute), 64
set_black_white_colors()
post_write_attach() (ase.io.bundletrajectory.BundleTrajectory
(ase.visualize.fieldplotter.FieldPlotter
method), 192
method), 110
post_write_attach() (ase.io.trajectory.PickleTrajectory
set_calculator()
(ase.atoms.Atoms method), 65
method), 190
set_cell()
(ase.atoms.Atoms
method), 65
pre_write_attach() (ase.io.bundletrajectory.BundleTrajectory
set_charges()
(ase.atoms.Atoms
method), 66
method), 192
set_chemical_symbols()
(ase.atoms.Atoms
method), 66
pre_write_attach() (ase.io.trajectory.PickleTrajectory
set_color_function()
(ase.visualize.fieldplotter.FieldPlotter
method), 190
method), 110
PrimiPlotter (class in ase.visualize.primiplotter), 107
set_color_function()
(ase.visualize.primiplotter.PrimiPlotter
Python, 207
method),
109
PYTHONPATH, 15, 20, 217, 228
set_colors()
(ase.visualize.primiplotter.PrimiPlotter
PYTHONSTARTUP, 18
method), 109
set_constraint() (ase.atoms.Atoms method), 66
R
set_data_range() (ase.visualize.fieldplotter.FieldPlotter
rattle() (ase.atoms.Atoms method), 64
method), 110
read() (ase.calculators.calculator.Calculator method),
set_dihedral()
(ase.atoms.Atoms method), 66
223
set_dimensions()
(ase.visualize.fieldplotter.FieldPlotter
read() (in module ase.io), 69
method),
111
read_cube_data() (in module ase.io), 73
set_dimensions()
(ase.visualize.primiplotter.PrimiPlotter
read_extra_data() (ase.io.bundletrajectory.BundleTrajectory
method), 109
method), 192
set_distance()
(ase.atoms.Atoms method), 66
read_results() (ase.calculators.calculator.FileIOCalculator
set_extra_data()
(ase.io.bundletrajectory.BundleTrajectory
method), 224
method),
192
reference_states (in module ase.data), 187
set_initial_charges()
(ase.atoms.Atoms method), 66
relax() (ase.calculators.fleur.FLEUR method), 133
set_initial_magnetic_moments()
(ase.atoms.Atoms
repeat() (ase.atoms.Atoms method), 64
method),
66
reserve() (ase.db.core.Database method), 200
reset() (ase.calculators.calculator.Calculator method), set_invisibility_function()
(ase.visualize.fieldplotter.FieldPlotter
223
method), 111
rotate() (ase.atoms.Atoms method), 64
set_invisibility_function()
rotate_dihedral() (ase.atoms.Atoms method), 65
(ase.visualize.primiplotter.PrimiPlotter
rotate_euler() (ase.atoms.Atoms method), 65
method), 109
run() (ase.vibrations.Vibrations method), 160
set_invisible() (ase.visualize.fieldplotter.FieldPlotter
method), 111
S
set_invisible() (ase.visualize.primiplotter.PrimiPlotter
save() (ase.dft.wannier.Wannier method), 181
method), 109
scan() (ase.dft.stm.STM method), 184
set_label()
(ase.calculators.calculator.Calculator
SciPyFminBFGS (class in ase.optimize.sciopt), 104
method), 222
SciPyFminCG (class in ase.optimize.sciopt), 104
numbers (ase.atoms.Atoms attribute), 64
NumPy, 207
NVTBerendsen (class in ase.md.nvtberendsen), 174
Index
253
set_log()
(ase.visualize.fieldplotter.FieldPlotter update()
(ase.visualize.fieldplotter.FieldPlotter
method), 111
method), 111
set_log()
(ase.visualize.primiplotter.PrimiPlotter update()
(ase.visualize.primiplotter.PrimiPlotter
method), 109
method), 110
set_masses() (ase.atoms.Atoms method), 66
V
set_momenta() (ase.atoms.Atoms method), 66
set_output()
(ase.visualize.fieldplotter.FieldPlotter Vasp (class in ase.calculators.vasp), 144
method), 111
VASP_PP_PATH, 143
set_output()
(ase.visualize.primiplotter.PrimiPlotter VASP_SCRIPT, 143
method), 109
vdw_radii (in module ase.data), 187
set_pbc() (ase.atoms.Atoms method), 66
VelocityVerlet (class in ase.md.verlet), 174
set_plot_plane() (ase.visualize.fieldplotter.FieldPlotter Vibrations (class in ase.vibrations), 159
method), 111
view (module), 78
set_positions() (ase.atoms.Atoms method), 66
view() (in module ase.visualize), 106
set_property() (ase.visualize.vtk.module.vtkGlyphModulevtk, 111
method), 113
vtk (module), 111
set_radii()
(ase.visualize.fieldplotter.FieldPlotter vtkAtomicPositions (class in ase.visualize.vtk.grid),
method), 111
112
set_radii()
(ase.visualize.primiplotter.PrimiPlotter vtkAtoms (class in ase.visualize.vtk.atoms), 111
method), 109
vtkGlyphModule (class in ase.visualize.vtk.module),
set_red_yellow_colors()
113
(ase.visualize.fieldplotter.FieldPlotter
W
method), 111
set_rotation()
(ase.visualize.fieldplotter.FieldPlotter Wannier (class in ase.dft.wannier), 179
method), 111
write() (ase.atoms.Atoms method), 67
set_rotation() (ase.visualize.primiplotter.PrimiPlotter write() (ase.db.core.Database method), 200
method), 109
write() (ase.dft.stm.STM method), 184
set_scaled_positions() (ase.atoms.Atoms method), 66
write()
(ase.io.bundletrajectory.BundleTrajectory
set_tags() (ase.atoms.Atoms method), 66
method), 192
set_velocities() (ase.atoms.Atoms method), 66
write() (ase.io.trajectory.PickleTrajectory method), 190
setup (module), 81
write() (in module ase.io), 71
Siesta (class in ase.calculators.siesta), 140
write_cube() (ase.dft.wannier.Wannier method), 181
SIESTA_PP_PATH, 140
write_dos() (ase.vibrations.Vibrations method), 161
SIESTA_SCRIPT, 140
write_inp() (ase.calculators.fleur.FLEUR method), 133
STM (class in ase.dft.stm), 184
write_input() (ase.calculators.calculator.FileIOCalculator
StrainFilter (class in ase.constraints), 156
method), 224
summary() (ase.vibrations.Vibrations method), 161
write_jmol() (ase.vibrations.Vibrations method), 161
surface() (in module ase.lattice.surface), 93
write_mode() (ase.vibrations.Vibrations method), 161
SVN_EDITOR, 217
write_spectra() (ase.infrared.InfraRed method), 172
T
test, 15
test.test() (in module ase.test), 226
testase, 226
tools (module), 79
translate() (ase.atoms.Atoms method), 67
translate() (ase.dft.wannier.Wannier method), 181
translate_all_to_cell()
(ase.dft.wannier.Wannier
method), 181
translate_to_cell() (ase.dft.wannier.Wannier method),
181
U
UnitCellFilter (class in ase.constraints), 156
update()
(ase.calculators.neighborlist.NeighborList
method), 194
update() (ase.db.core.Database method), 201
254
Index