12.2. anphon (phonon properties)#
Warning
The anphon Python API is experimental in version 2.0. It is tested
against the command-line program, but its interface may still change in
later releases; see API stability.
Overview#
The Python package anphon runs anphon inside the Python process. A run goes
through the same code path as the command-line program (anphon file.in):
the input is ordinary anphon input text, parsed by anphon itself, and the
results are the usual output files. The package adds three conveniences on top:
anphon.runwrites the input file from Python dictionaries (or takes an existing input file) and runs it;anphon.Resultlocates the output files and reads the HDF5 results (PREFIX.kappa.h5,PREFIX.scph.h5,PREFIX.qha.h5, …) into nested dictionaries;anphon.Phononreturns harmonic phonon frequencies and eigenvectors at arbitrary \(q\) points as NumPy arrays.
Everything is file based: the inputs are files (force constants, BORNINFO,
…), and the results are read back from the files anphon writes.
One Python distribution, alamode-python, provides both packages,
alm and anphon (see Python API).
Installation#
The anphon package is built by the same command as alm
(see Installation):
% cd python
% pip install .
On top of the alm requirements, the anphon module needs an MPI library
at build and run time, and h5py at run time (installed by pip as a dependency).
The conda environment file etc/alamode-environment.yml and the
pixi route already provide OpenMPI, HDF5, and h5py.
If CMake cannot find MPI, the configure step fails with a message. To build only
almon a machine without MPI, pass:% pip install . -C cmake.define.ALAMODE_PYTHON_ANPHON=OFF
The build compiles the anphon sources. Set
CMAKE_BUILD_PARALLEL_LEVELto bound the number of parallel compile jobs, e.g.CMAKE_BUILD_PARALLEL_LEVEL=4 pip install ..
Verify the installation with:
import alm, anphon
print(anphon.__version__) # same as alm.__version__ and `pip show alamode-python`
After an ALM-only build (ALAMODE_PYTHON_ANPHON=OFF), only import alm
works.
Running anphon: anphon.run#
anphon.run has two forms. With an existing input file, it runs the file as
the command anphon si.in would:
import anphon
r = anphon.run("si.in") # outputs in the current directory
r = anphon.run("si.in", workdir="run1") # outputs in run1/
With keyword arguments, one per input section, it writes the input file
<workdir>/<PREFIX>.in and runs it:
r = anphon.run(
general=dict(PREFIX="si", MODE="phonons", FCSFILE="si222.xml"),
cell=dict(a=10.263, lattice=[[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]]),
kpoint=dict(KPMODE=2, mesh=[20, 20, 20]),
workdir="dos",
)
The input tags are those of the command-line program (ANPHON: Anharmonic phonon calculator). The section values are turned into input text as follows:
A
dict(general,scph,kappa,analysis, …) becomes oneKEY = valueline per entry. Keys are written in upper case, lists and arrays are joined by spaces (KD=["Ba", "Ti", "O"]givesKD = Ba Ti O),True/Falsebecome1/0, and entries whose value isNoneare dropped. A value that contains a newline,;,#, or=, or a non-finite number, raisesValueError.cellisdict(a=<factor>, lattice=<3x3>), as in the&cellfield: the rows oflattice(dimensionless) multiplied bya(in bohr, default 1.0) are the lattice vectors \(\boldsymbol{a}_1, \boldsymbol{a}_2, \boldsymbol{a}_3\) in bohr. Alternatively, givelatticein bohr and leavea = 1. A bare 3x3 array is accepted as the lattice witha = 1.kpointis a dict withKPMODEandKPMODE=0:qpoints=[[qx, qy, qz], ...];KPMODE=1:path=[("G", [0, 0, 0], "X", [0.5, 0.5, 0], 51), ...], one(label1, q1, label2, q2, npoints)tuple per line segment;KPMODE=2:mesh=[n1, n2, n3];any mode:
lines=[...], the lines after theKPMODEline, verbatim.
KPMODE, the mesh, and the numbers of points must be integers (4.0is accepted,4.5orTrueraiseValueError).Any other non-dict value (e.g. a 3x3 matrix for
strain) is written one line per row.A
stris written verbatim as the body of the section. This is the escape hatch for anything the rules above do not cover.
Only the form is checked in Python; the content is validated by anphon’s input
parser, whose errors raise RuntimeError (see Errors).
Passing both an input file and sections raises TypeError, and a missing
general section or PREFIX raises ValueError.
anphon.format_input(**sections) returns the generated text without running
anything, which is useful to check it:
print(anphon.format_input(general=dict(PREFIX="si", MODE="phonons", FCSFILE="si.xml"),
kpoint=dict(KPMODE=2, mesh=[8, 8, 8])))
&general
PREFIX = si
MODE = phonons
FCSFILE = si.xml
/
&kpoint
2
8 8 8
/
workdir (default: the current directory) is created if it does not exist.
anphon runs inside it, so relative file names in the input (FCSFILE,
BORNINFO, …) are relative to workdir, as are all outputs. The
current directory of the Python process is restored when the run ends, also
after an error. Use absolute paths when in doubt.
anphon prints its usual log to standard output. Set VERBOSITY = 0 in
general to make it shorter; a run from Python then also omits the banner
and the start and finish lines. The log is written by C++, so when the output
is redirected to a file, it can interleave out of order with text printed by
Python.
Results: anphon.Result#
run returns a Result with the attributes workdir (absolute path)
and prefix:
r.path(".bands")returnsworkdir / (prefix + ".bands");r.files()lists the files<prefix>.*inworkdir(including the input file<prefix>.inwritten byrun);r.h5(kind)readsPREFIX.<kind>.h5into a nested dictionary, e.g.r.h5("kappa"),r.h5("scph"), orr.h5("qha")(FileNotFoundErrorif the file does not exist). It returns the raw file contents.
The text outputs (.bands, .dos, …) are read with the usual tools,
e.g. numpy.loadtxt(r.path(".bands")).
r.h5 uses anphon.read_h5(path), which works for any HDF5 file:
groups become dicts, datasets NumPy arrays (scalars as NumPy scalars);
strings are decoded to
str(string arrays become lists ofstr);an attribute of a group is stored in that group’s dict under
"@name", and an attribute of a dataset under"dataset@name"next to the dataset.
For example, for a MODE = kappa run:
k = r.h5("kappa")
k["@schema"] # 'alamode:kappa_result'
T = k["metadata"]["temperatures"] # K
kap = k["kappa"]["kappa_peierls"] # shape (nT, 3, 3)
k["kappa"]["kappa_peierls@unit"] # 'W/mK'
The layouts of the files are described in HDF5 files (Thermal conductivity (PREFIX.kappa.h5), SCPH and QHA results (PREFIX.scph.h5, PREFIX.qha.h5)).
Phonons at arbitrary q: anphon.Phonon#
Phonon returns harmonic frequencies and eigenvectors as arrays:
ph = anphon.Phonon("si222_harmonic.h5")
q = [[0, 0, 0], [0.5, 0.5, 0], [0.5, 0.5, 0.5]]
w = ph.frequencies(q)
w, evec = ph.frequencies(q, eigenvectors=True)
Phonon(fcsfile, *, cell=None, kd=None, borninfo=None, nonanalytic=0, general=None)takes the settings. They are validated, and the files are loaded, at construction or at the first calculation.cellhas the form described forrun. An HDF5 force-constant file written by ALM 2.0 carries the primitive cell, socellandkdare not needed; an XML file does not, socell=must be given. Other&generaltags (MASS,TOLERANCE,VERBOSITY, …) go in the dictgeneral.VERBOSITYdefaults to 0 here, soPhononprints only warnings; setVERBOSITY=1to see the anphon log. The tagsPREFIX,MODE,FCSFILE,BORNINFO,NONANALYTIC,FILE_FORMAT, andKDare set byPhononitself (or through its arguments) and raiseValueErroringeneral, in any letter case.Phononkeeps its own copy of the settings, so changing the dicts passed to it afterwards has no effect.frequencies(q, eigenvectors=False)takes \(q\) points in fractional coordinates of the reciprocal primitive lattice (shape(nq, 3)or(3,); other shapes raiseValueError) and returns the frequencies in cm-1 with shape(nq, nmodes),nmodes = 3 * natomsof the primitive cell. Imaginary modes come out as negative numbers. Witheigenvectors=Trueit also returns the complex eigenvectors of the dynamical matrix with shape(nq, nmodes, nmodes), laid out asevec[iq, imode, 3 * iatom + ixyz](axis 1 is the mode).Each call runs anphon (
MODE = phonons,KPMODE = 0) in a temporary directory, which is removed afterwards. Ask for all \(q\) points in one call rather than one call per point.Phononis serial only: it raisesRuntimeErrorwhen MPI runs with more than one process.
Note
Non-analytic correction at \(\Gamma\). With nonanalytic > 0,
the direction of \(q\) used by the non-analytic term is obtained by
shifting each fractional component of \(q\) by the nearest integer
(\(q_i - \mathrm{nint}(q_i)\)) and converting the result to Cartesian
coordinates. At \(\Gamma\) and at every
reciprocal-lattice point ([0, 0, 0], [1, 0, 0], …), this direction
is zero and the non-analytic term vanishes, so there is no LO-TO splitting
exactly at these points. To get the LO frequencies for a given direction,
use a small \(q\) along it (e.g. [1e-4, 0, 0]), or run a band
structure (KPMODE = 1) with run, which takes the direction of the
path.
Errors#
In a serial run, errors while
runprepares the input in Python raise ordinary Python exceptions:TypeErrorfor an input file plus sections,ValueErrorfor a missinggeneralsection orPREFIXor a bad value, andOSErrorfrom the filesystem.In a serial run, errors that anphon reports (invalid input, a missing or broken file, …) raise
RuntimeErrorwith anphon’s error message. The message is also printed to the log first. The process stays usable: the current directory is restored, and the next run starts from a clean state.Errors raised inside an OpenMP parallel region, and out-of-memory errors, still terminate the process, as in the command-line program.
Under MPI with more than one process, errors in
runabort all ranks (MPI_Abort): both an error whilerunprepares the input in Python, even on one rank only, and a failure inside the collective anphon run. This avoids a deadlock in which the other ranks wait forever. Errors outside a run still raise locally:format_inputandread_h5errors, the errors ofPhonon(TypeErrororValueErrorfor its arguments,RuntimeErrorbecause it is serial only), and theRuntimeErrorfor a call from a thread other than the main thread, which is raised before the run starts.
MPI#
anphon is parallelized with MPI and OpenMP, and the Python interface runs under MPI as the command-line program does:
% mpirun -np 4 python script.py
Importing
anphoninitializes MPI (MPI_THREAD_FUNNELED) unless it is already initialized, e.g. bympi4py. Initialization is collective, so in that case all ranks must importanphon(an import on rank 0 only can hang). Both orders ofimport mpi4py/import anphonwork. MPI that is already initialized must provide at leastMPI_THREAD_FUNNELED; otherwise the import raisesImportError. MPI is finalized at exit only ifanphoninitialized it.mpi4pyand the anphon module must be built against the same MPI library.Every
runcall is collective overMPI_COMM_WORLD: all ranks must call it with the same arguments. Rank 0 writes the outputs, and every rank returns only after they are complete, so all ranks can read them afterwards.Import
anphonand callrunfrom the main Python thread only (other threads getImportError/RuntimeError). Python threads keep running during a run, but cannot start another one.
Note
Reproducibility. OpenMP reductions can make the results of two runs
differ in the last bit, as for the command-line program. With
OMP_NUM_THREADS=1, the results are numerically identical to those of
the command-line program with the same build and settings (all datasets
equal); only the metadata attributes created_date,
alamode_git_commit, and alamode_version differ.
Example: silicon#
The following script uses the silicon force constants shipped in
example/Si. Copy them to a working directory first:
% cp example/Si/anharm_IFCs/1_harmonic/reference/si222_harmonic.xml .
% cp example/Si/anharm_IFCs/2_generate_config/si222_harmonic.h5 .
% cp example/Si/reference/si222_cubic.h5 .
It computes the phonon dispersion, the lattice thermal conductivity in the relaxation-time approximation (on a coarse \(4\times4\times4\) mesh, which takes a few seconds), and the frequencies at \(\Gamma\), X, and L.
import os
import numpy as np
import anphon
here = os.getcwd()
fcc = [[0.0, 0.5, 0.5],
[0.5, 0.0, 0.5],
[0.5, 0.5, 0.0]]
# 1. phonon dispersion along G-X-G-L
bands = anphon.run(
general=dict(PREFIX="si", MODE="phonons", VERBOSITY=0,
FCSFILE=os.path.join(here, "si222_harmonic.xml")),
cell=dict(a=10.2631026, lattice=fcc),
kpoint=dict(KPMODE=1, path=[
("G", [0, 0, 0], "X", [0.5, 0.5, 0], 51),
("X", [0.5, 0.5, 1], "G", [0, 0, 0], 51),
("G", [0, 0, 0], "L", [0.5, 0.5, 0.5], 51),
]),
workdir="bands",
)
print(bands.files()) # ['si.bands', 'si.in']
b = np.loadtxt(bands.path(".bands")) # (153, 7): path coordinate, 6 branches
# 2. thermal conductivity (RTA)
res = anphon.run(
general=dict(PREFIX="si", MODE="kappa", VERBOSITY=0,
FCSFILE=os.path.join(here, "si222_cubic.h5"),
TMIN=100, TMAX=500, DT=100),
kpoint=dict(KPMODE=2, mesh=[4, 4, 4]),
kappa=dict(SOLVER="RTA"),
workdir="kappa",
)
k = res.h5("kappa")
for T, kap in zip(k["metadata"]["temperatures"], k["kappa"]["kappa_peierls"]):
print(f"{T:5.0f} K {kap[0, 0]:8.2f} W/mK")
# 3. frequencies at Gamma, X, and L (the .h5 file carries the primitive cell)
ph = anphon.Phonon("si222_harmonic.h5")
w, evec = ph.frequencies([[0, 0, 0], [0.5, 0.5, 0], [0.5, 0.5, 0.5]],
eigenvectors=True)
print(np.round(w, 2)) # cm^-1, shape (3, 6)
print(evec.shape) # (3, 6, 6)
# the same with the XML file, which needs the cell
ph_xml = anphon.Phonon("si222_harmonic.xml", cell=dict(a=10.2631026, lattice=fcc))
The frequencies printed in step 3 are:
[[ 0. 0. 0. 509.62 509.62 509.62]
[134.17 134.17 405.55 405.55 458.65 458.65]
[103.5 103.5 368.81 410.16 486.47 486.47]]
The coarse mesh of step 2 gives a thermal conductivity far from convergence
(34 W/mK at 300 K, against 104 W/mK on the \(10\times10\times10\) mesh of
example/Si/reference/si222_kappa.in); use a denser mesh for real
calculations.
Limitations#
The following are not available in this version:
in-memory input of force constants and structures: force constants from
almgo through a file (ALM.save_fc), which is then passed asFCSFILE;a persistent
Phononobject: eachfrequenciescall runs anphon anew;sub-communicators: runs always use
MPI_COMM_WORLD.
API stability#
Intended to stay stable in 2.x:
run(the file runner) and its documented arguments;Result.workdir,Result.prefix,Result.path(), andResult.files();format_input;__version__; the unit and shape conventions ofPhonon.frequencies(cm-1, fractional \(q\), shape(nq, nmodes),evec[iq, imode, 3 * iatom + ixyz]).Provisional (may change in a 2.x minor release, with release notes):
Phonon(its implementation and any further arguments);Result.h5andread_h5, whose content is the raw file schema, versioned separately in HDF5 files.Deprecation rule: a stable name is not removed or changed incompatibly in 2.x. A deprecation warns for at least one minor release before the removal in a major release.
API reference#
anphon.run(input=None, *, workdir=None, **sections)Run anphon on the input file
input, or on the input generated fromsections, insideworkdir. Returns aResult. Collective under MPI. The keyword-only argument names (workdir, and future ones such ascomm) are reserved; all other keywords are input sections.anphon.format_input(**sections)Return the input text that
runwould write forsections.anphon.Result(workdir, prefix)Outputs of a run. Attributes
workdir,prefix; methodspath(suffix),files(),h5(kind).anphon.read_h5(path)Read an HDF5 file into a nested dict (
"@name"and"dataset@name"keys for attributes).anphon.Phonon(fcsfile, *, cell=None, kd=None, borninfo=None, nonanalytic=0, general=None)Harmonic phonons from a force-constant file. Method
frequencies(qpoints_frac, eigenvectors=False). Serial only.anphon.__version__Version of the
alamode-pythondistribution.
The low-level binding underneath run is private.
See also#
ANPHON: Anharmonic phonon calculator — the anphon command-line program and its input tags.
alm (force constants) — the ALM Python interface, which writes the force-constant files used here.
HDF5 files — layouts of the HDF5 files read by
Result.Silicon with Python — a tutorial that uses
run,Phonon, andResult.h5on silicon.