dfpt Package

dpft Package

This subpackage provides objects and functions for the analysis of DFPT calculations.

anaddbnc Module

AnaddbNcFile provides a high-level interface to the data stored in the anaddb.nc file.

class abipy.dfpt.anaddbnc.AnaddbNcFile(filepath)[source]

Bases: abipy.core.mixins.AbinitNcFile, abipy.core.mixins.Has_Structure, abipy.core.mixins.NotebookWriter

AnaddbNcFile provides a high-level interface to the data stored in the anaddb.nc file. This object is usually instanciated with abiopen(“anaddb.nc”).

structure[source]

abipy.core.structure.Structure object.

epsinf[source]

Macroscopic dielectric tensor. None if the file does not contain this information.

becs[source]

Born effective charges. None if the file does not contain this inf

ifc[source]

InteratomicForceConstants object with the interatomic force constants calculated by anaddb. None, if the netcdf file does not contain the IFCs.

Inheritance Diagram

Inheritance diagram of AnaddbNcFile
classmethod from_file(filepath)[source]

Initialize the object from file.

close()[source]

Close the file.

structure()[source]

Returns the abipy.core.structure.Structure object.

params()[source]

OrderedDict with the convergence parameters Used to construct pandas.DataFrame.

to_string(verbose=0)[source]

String representation

Parameters

verbose – verbosity level.

epsinf()[source]

Macroscopic electronic abipy.tools.tensors.DielectricTensor in Cartesian coordinates (a.k.a. epsilon_infinity) None if the file does not contain this information.

property emacro
eps0()[source]

Relaxed ion macroscopic abipy.tools.tensors.DielectricTensor in Cartesian coordinates (a.k.a. epsilon_zero) None if the file does not contain this information.

property emacro_rlx
becs()[source]

Born effective charges. None if the file does not contain this information.

ifc()[source]

The interatomic force constants calculated by anaddb. The following anaddb variables should be used in the run: ifcflag, natifc, atifc, ifcout. Return None, if the netcdf file does not contain the IFCs,

dchide()[source]

Non-linear optical susceptibility tensor. Returns a NLOpticalSusceptibilityTensor or None if the file does not contain this information.

dchidt()[source]

First-order change in the linear dielectric susceptibility. Returns a list of lists of 3x3 Tensor object with shape (number of atoms, 3). The [i][j] element of the list contains the Tensor representing the change due to the displacement of the ith atom in the jth direction. None if the file does not contain this information.

oscillator_strength()[source]

A complex numpy.ndarray containing the oscillator strengths with shape [number of phonon modes, 3, 3], in a.u. (1 a.u.=253.2638413 m3/s2). None if the file does not contain this information.

has_elastic_data()[source]

True if elastic tensors have been computed.

has_piezoelectric_data()[source]

True if piezoelectric tensors have been computed.

elastic_data()[source]

Container with the different (piezo)elastic tensors computed by anaddb. stored in pymatgen tensor objects.

amu()[source]

Dictionary with atomic_number as keys and the atomic massu units as values.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user. Used in abiview.py to get a quick look at the results.

write_notebook(nbpath=None)[source]

Write an jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

class abipy.dfpt.anaddbnc.AnaddbNcRobot(*args)[source]

Bases: abipy.abio.robots.Robot

This robot analyzes the results contained in multiple anaddb.nc files.

Inheritance Diagram

Inheritance diagram of AnaddbNcRobot
EXT = 'anaddb'
property has_elastic_data
get_dataframe()[source]
get_elastic_dataframe(with_geo=True, abspath=False, with_params=False, funcs=None, **kwargs)[source]

Return a pandas.DataFrame with properties derived from the elastic tensor and an associated structure. Filename is used as index.

Parameters
  • with_geo – True if structure info should be added to the dataframe

  • abspath – True if paths in index should be absolute. Default: Relative to getcwd().

  • with_params – False to exclude calculation parameters from the dataframe.

kwargs:
attrs:

List of additional attributes of the abipy.electrons.gsr.GsrFile to add to the DataFrame.

funcs: Function or list of functions to execute to add more data to the DataFrame.

Each function receives a abipy.electrons.gsr.GsrFile object and returns a tuple (key, value) where key is a string with the name of column and value is the value to be inserted.

plot_elastic_properties(fontsize=10, **kwargs)[source]
Parameters

fontsize – legend and label fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user. Used in abiview.py to get a quick look at the results.

write_notebook(nbpath=None)[source]

Write a jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

converters Module

Converters between abinit/abipy format and other external tools. Some portions of the code have been imported from the ConvertDDB.py script developed by Hu Xe, Eric Bousquet and Aldo Romero.

abipy.dfpt.converters.abinit_to_phonopy(anaddbnc, supercell_matrix, symmetrize_tensors=False, output_dir_path=None, prefix_outfiles='', symprec=1e-05, set_masses=False)[source]

Converts the interatomic force constants(IFC), born effective charges(BEC) and dielectric tensor obtained from anaddb to the phonopy format. Optionally writes the standard phonopy files to a selected directory: FORCE_CONSTANTS, BORN (if BECs are available) POSCAR of the unit cell, POSCAR of the supercell.

The conversion is performed taking the IFC in the Wigner–Seitz supercell with weights as produced by anaddb and reorganizes them in a standard supercell multiple of the unit cell. Operations are vectorized using numpy. This may lead to the allocation of large arrays in case of very large supercells.

Performs a check to verify if the two codes identify the same symmetries and it gives a warning in case of failure. Mismatching symmetries may lead to incorrect conversions.

Parameters
  • anaddbnc – an instance of AnaddbNcFile. Should contain the output of the IFC analysis, the BEC and the dielectric tensor.

  • supercell_matrix – the supercell matrix used for phonopy. Any choice is acceptable, however the best agreement between the abinit and phonopy results is obtained if this is set to a diagonal matrix with on the diagonal the ngqpt used to generate the anaddb.nc.

  • symmetrize_tensors – if True the tensors will be symmetrized in the Phonopy object and in the output files. This will apply to IFC, BEC and dielectric tensor.

  • output_dir_path – a path to a directory where the phonopy files will be created

  • prefix_outfiles – a string that will be added as a prefix to the name of the written files

  • symprec – distance tolerance in Cartesian coordinates to find crystal symmetry in phonopy. It might be that the value should be tuned so that it leads to the the same symmetries as in the abinit calculation.

  • set_masses – if True the atomic masses used by abinit will be added to the PhonopyAtoms and will be present in the returned Phonopy object. This should improve compatibility among abinit and phonopy results if frequencies needs to be calculated.

Returns

An instance of a Phonopy object that contains the IFC, BEC and dieletric tensor data.

abipy.dfpt.converters.phonopy_to_abinit(unit_cell, supercell_matrix, out_ddb_path, ngqpt=None, qpt_list=None, force_constants=None, force_sets=None, born=None, primitive_matrix='auto', symprec=1e-05, tolsym=None, supercell=None, calculator=None, manager=None, workdir=None, pseudos=None, verbose=False)[source]

Converts the data from phonopy to an abinit DDB file. The data can be provided in form of arrays or paths to the phonopy files that should be parsed. The minimal input should contains the FORCE_CONSTANTS or FORCE_SETS. If BORN is present the Born effective charges (BEC) and dielectric tensor will also be added to the DDB.

The best agreement is obtained with supercell_matrix and ngqpt being equivalent (i.e. supercell_matrix a diagonal matrix with ngqpt as diagonal elements). Non diagonal supercell_matrix are allowed as well, but the information encoded in the DDB will be the result of an interpolation done through phonopy.

Phonopy is used to convert the IFC to the dynamical matrix. However, in order to determine the list of q-points in the irreducible Brillouin zone and to prepare the base for the final DDB file, abinit will be called for a very short and inexpensive run.

Performs a check to verify if the two codes identify the same symmetries and it gives a warning in case of failure. Mismatching symmetries may lead to incorrect conversions.

Parameters
  • unit_cell – a abipy.core.structure.Structure object that identifies the unit cell used for the phonopy calculation.

  • supercell_matrix – a 3x3 array representing the supercell matrix used to generated the forces with phonopy.

  • out_ddb_path – a full path to the file where the new DDB will be written

  • ngqpt – a list of 3 elements indicating the grid of q points that will be used in the DDB.

  • qpt_list – alternatively to ngqpt an explicit list of q-points can be provided here. At least one among ngqpt and qpt_list should be defined.

  • force_constants – an array with shape (num atoms unit cell, num atoms supercell, 3, 3) containing the force constants. Alternatively a string with the path to the FORCE_CONSTANTS file. This or force_set should be defined. If both given this has precedence.

  • force_sets – a dictionary obtained from the force sets generated with phonopy. Alternatively a string with the path to the FORCE_SETS file. This or force_constants should be defined.

  • born – a dictionary with “dielectric” and “born” keywords as obtained from the nac_params in phonopy. Alternatively a string with the path to the BORN file. Notice that the “factor” attribute is not taken into account, so the values should be in default phonopy units.

  • primitive_matrix – a 3x3 array with the primitive matrix passed to Phonopy. “auto” will use spglib to try to determine it automatically. If the DDB file should contain the actual unit cell this should be the identity matrix.

  • symprec – distance tolerance in Cartesian coordinates to find crystal symmetry in phonopy. It might be that the value should be tuned so that it leads to the the same symmetries as in the abinit calculation.

  • tolsym – Gives the tolerance to identify symmetries in abinit. See abinit documentation for more details.

  • supercell – if given it should represent the supercell used to get the force constants, without any perturbation. It will be used to match it to the phonopy supercell and sort the IFC in the correct order.

  • calculator – a string with the name of the calculator. Will be used to set the conversion factor for the force constants coming from phonopy.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • pseudos – List of filenames or list of pymatgen.io.abinit.pseudos.Pseudo objects or pymatgen.io.abinit.pseudos.PseudoTable object. It will be used by abinit to generate the base DDB file. If None the abipy.data.hgh_pseudos.HGH_TABLE table will be used.

  • verbose – verbosity level. Set it to a value > 0 to get more information

  • workdir – path to the directory where the abinit calculation will be executed.

Returns

a DdbFile instance of the file written in out_ddb_path.

abipy.dfpt.converters.generate_born_deriv(born, zion, structure)[source]

Helper function to generate the portion of the derivatives in the DDB that are related to the Born effective charges and dielectric tensor, starting from the data available in phonopy format.

Parameters
  • born – a dictionary with “dielectric” and “born” keywords as obtained from the nac_params in phonopy.

  • zion – the ionic charge of each atom in the system. It should be in the same order as the one present in the header of the DDB.

  • structure – a pymatgen abipy.core.structure.Structure of the unit cell.

Returns

a complex numpy array with shape (len(structure)+2, 3, len(structure)+2, 3). Only the parts relative to the BECs and dielectric tensors will be filled.

abipy.dfpt.converters.get_dm(phonon, qpt_list, structure)[source]

Helper function to generate the dynamical matrix in the abinit conventions for a list of q-points from a Phonopy object.

Parameters
  • phonon – a Phonopy object with force constants.

  • qpt_list – a list of fractional coordinates of q-points for which the dynamical matrix should be generated.

  • structure – a pymatgen abipy.core.structure.Structure of the primitive cell.

Returns

a list of arrays with the dynamical matrices of the selected q-points.

abipy.dfpt.converters.add_data_ddb(ddb, dm_list, qpt_list, born_data)[source]

Helper function to add the blocks for the dynamical matrix and BECs to a DdbFile object.

Parameters
  • ddb – a DdbFile object to be modified.

  • dm_list – the list of dynamical matrices to be added.

  • qpt_list – the list of q-points corresponding to dm_list.

  • born_data – the data corresponding to BECs and dielectric tensor. If None these part will not be set in the DDB.

abipy.dfpt.converters.tdep_to_abinit(unit_cell, fc_path, supercell_matrix, supercell, out_ddb_path, ngqpt=None, qpt_list=None, primitive_matrix='auto', lotosplitting_path=None, symprec=1e-05, tolsym=None, manager=None, workdir=None, pseudos=None, verbose=False)[source]

Converts the files produced by TDEP to an abinit DDB file. If the lotosplitting file is provided the BEC and dielectric tensor will also be added to the DDB.

The conversion is performed by first extracting the force constants in phonopy format and then using phonopy_to_abinit_py to generate the DDB file. See the phonopy_to_abinit_py docstring for further details about the second step of the conversion. Notice that the supercell used by TDEP should be provided in order to properly sort the IFC to match the order required by phonopy.

Parameters
  • unit_cell – a abipy.core.structure.Structure object that identifies the unit cell used for the TDEP calculation.

  • fc_path – the path to the forceconstants file produced by TDEP.

  • supercell_matrix – a 3x3 array representing the supercell matrix used to generated the forces with TDEP.

  • supercell – the supercell used by TDEP to get the force constants, without any perturbation (usually named with extension ssposcar). It will be used to match it to the phonopy supercell and sort the IFC in the correct order.

  • out_ddb_path – a full path to the file where the new DDB will be written

  • ngqpt – a list of 3 elements indicating the grid of q points that will be used in the DDB.

  • qpt_list – alternatively to ngqpt an explicit list of q-points can be provided here. At least one among ngqpt and qpt_list should be defined.

  • primitive_matrix – a 3x3 array with the primitive matrix passed to Phonopy. “auto” will use spglib to try to determine it automatically. If the DDB file should contain the actual unit cell this should be the identity matrix.

  • lotosplitting_path – path to the lotosplitting file produced by TDEP. If None no BEC contribution will be set to the DDB.

  • symprec – distance tolerance in Cartesian coordinates to find crystal symmetry in phonopy. It might be that the value should be tuned so that it leads to the the same symmetries as in the abinit calculation.

  • tolsym – Gives the tolerance to identify symmetries in abinit. See abinit documentation for more details.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • pseudos – List of filenames or list of pymatgen.io.abinit.pseudos.Pseudo objects or pymatgen.io.abinit.pseudos.PseudoTable object. It will be used by abinit to generate the base DDB file. If None the abipy.data.hgh_pseudos.HGH_TABLE table will be used.

  • verbose – verbosity level. Set it to a value > 0 to get more information

  • workdir – path to the directory where the abinit calculation will be executed.

Returns

a DdbFile instance of the file written in out_ddb_path.

abipy.dfpt.converters.parse_tdep_fc(fc_path, unit_cell, supercell)[source]

Parses a forceconstants file produced by TDEP an converts it to an array in the phonopy format.

Parameters
  • fc_path – path to the forceconstants file

  • unit_cell – a abipy.core.structure.Structure object with the unit cell used for the calculation in TDEP.

  • supercell – the supercell used for the calculation in TDEP.

Returns

a comple numpy array with shape (len(unit_cell), len(supercell), 3, 3)

abipy.dfpt.converters.parse_tdep_lotosplitting(filepath)[source]

Parses the lotosplitting file produced by TDEP and transforms them in the phonopy format for Born effective charges and dielectric tensor.

Parameters

filepath – path to the lotosplitting file.

Returns

a tuple with dielectric tensor and Born effective charges.

abipy.dfpt.converters.write_tdep_lotosplitting(eps, born, filepath='infile.lotosplitting', fmt='%14.10f')[source]

Writes an lotosplitting file starting from arrays containing dielectric tensor and Born effective charges.

Parameters
  • eps – a 3x3 array with the dielectric tensor.

  • born – an array with the Born effective charges.

  • filepath – the path where the lotosplitting file should be written.

  • fmt – the format for the float numbers.

abipy.dfpt.converters.born_to_lotosplitting(born, lotosplitting_path='infile.lotosplitting')[source]

Converted of a file from the BORN file produced from phonopy to the lotosplitting file used by TDEP.

Parameters
  • born – a dictionary with “dielectric” and “born” keywords as obtained from the nac_params in phonopy. Notice that the “factor” attribute is not taken into account, so the values should be in default phonopy units.

  • lotosplitting_path – the path where the lotosplitting file should be written.

abipy.dfpt.converters.write_BORN(primitive, borns, epsilon, filename='BORN', symmetrize_tensors=False)[source]

Helper function imported from phonopy.file_IO. Contrarily to the original, it does not symmetrize the tensor.

abipy.dfpt.converters.get_BORN_lines(unitcell, borns, epsilon, factor=None, primitive_matrix=None, supercell_matrix=None, symprec=1e-05, symmetrize_tensors=False)[source]

Helper function imported from phonopy.file_IO that exposes the option of not symmetrizing the tensor.

ddb Module

Python API for the DDB file containing the derivatives of the total Energy wrt different perturbations.

exception abipy.dfpt.ddb.DdbError[source]

Bases: Exception

Error class raised by DDB.

exception abipy.dfpt.ddb.AnaddbError(*args, **kwargs)[source]

Bases: abipy.dfpt.ddb.DdbError

Exceptions raised when we try to execute abipy.flowtk.tasks.AnaddbTask in the abipy.dfpt.ddb.DdbFile methods

An AnaddbError has a reference to the task and to the EventsReport that contains the error messages of the run.

class abipy.dfpt.ddb.DdbFile(filepath)[source]

Bases: abipy.core.mixins.TextFile, abipy.core.mixins.Has_Structure, abipy.core.mixins.NotebookWriter

This object provides an interface to the DDB file produced by ABINIT as well as methods to compute phonon band structures, phonon DOS, thermodynamic properties etc.

About the indices (idir, ipert) used by Abinit (Fortran notation):

  • idir in [1, 2, 3] gives the direction (usually reduced direction, cart for strain)

  • ipert in [1, 2, …, mpert] where mpert = natom + 6

    • ipert in [1, …, natom] corresponds to atomic perturbations (reduced directions)

    • ipert = natom + 1 corresponds d/dk (reduced directions)

    • ipert = natom + 2 corresponds the electric field

    • ipert = natom + 3 corresponds the uniaxial stress (Cartesian directions)

    • ipert = natom + 4 corresponds the shear stress. (Cartesian directions)

Inheritance

Inheritance diagram of DdbFile
Error

alias of abipy.dfpt.ddb.DdbError

exception AnaddbError(*args, **kwargs)

Bases: abipy.dfpt.ddb.DdbError

Exceptions raised when we try to execute abipy.flowtk.tasks.AnaddbTask in the abipy.dfpt.ddb.DdbFile methods

An AnaddbError has a reference to the task and to the EventsReport that contains the error messages of the run.

classmethod from_file(filepath)[source]

Needed for the TextFile abstract interface.

classmethod from_string(string)[source]

Build object from string using temporary file.

classmethod from_mpid(material_id, api_key=None, endpoint=None)[source]

Fetch DDB file corresponding to a materials project material_id, save it to temporary file and return new DdbFile object.

Raises: MPRestError if DDB file is not available

Parameters
  • material_id (str) – Materials Project material_id (e.g., mp-1234).

  • api_key (str) – A String API key for accessing the MaterialsProject REST interface. If None, the code will check if there is a PMG_MAPI_KEY in your .pmgrc.yaml.

  • endpoint (str) – Url of endpoint to access the MaterialsProject REST interface. Defaults to the standard Materials Project REST address

classmethod as_ddb(obj)[source]

Return an instance of abipy.dfpt.ddb.DdbFile from a generic object obj. Accepts: DdbFile or filepath

to_string(verbose=0)[source]

String representation.

get_string()[source]

Return string with DDB content.

property structure

abipy.core.structure.Structure object.

property natom

Number of atoms in structure.

property version

DDB Version number (integer).

property header

Dictionary with the values reported in the header section. Use e.g. ddb.header.ecut to access its values

computed_dynmat()[source]

OrderedDict mapping q-point object to –> pandas Dataframe. The pandas.DataFrame contains the columns: “idir1”, “ipert1”, “idir2”, “ipert2”, “cvalue” and (idir1, ipert1, idir2, ipert2) as index.

Note

The indices follow the Abinit (Fortran) notation so they start at 1.

blocks()[source]

DDB blocks. List of dictionaries, Each dictionary contains the following keys. “qpt” with the reduced coordinates of the q-point. “data” that is a list of strings with the entries of the dynamical matrix for this q-point.

property qpoints

abipy.core.kpoints.KpointList object with the list of q-points in reduced coordinates.

has_qpoint(qpoint)[source]

True if the DDB file contains this q-point.

qindex(qpoint)[source]

The index of the q-point in the internal list of q-points. Accepts: abipy.core.kpoints.Kpoint instance or integer.

guessed_ngqpt()[source]

Guess for the q-mesh divisions (ngqpt) inferred from the list of q-points found in the DDB file.

Warning

The mesh may not be correct if the DDB file contains points belonging to different meshes and/or the Q-mesh is shifted.

params()[source]

OrderedDict with parameters that might be subject to convergence studies.

total_energy()[source]

Total energy in eV. None if not available.

cart_forces()[source]

Cartesian forces in eV / Ang None if not available i.e. if the GS DDB has not been merged.

cart_stress_tensor()[source]

abipy.tools.tensors.Stress tensor in cartesian coordinates (GPa units). None if not available.

has_lo_to_data(select='at_least_one')[source]

True if the DDB file contains the data required to compute the LO-TO splitting.

has_at_least_one_atomic_perturbation(qpt=None)[source]

True if the DDB file contains info on (at least one) atomic perturbation. If the coordinates of a q point are provided only the specified qpt will be considered.

has_epsinf_terms(select='at_least_one')[source]

True if the DDB file contains info on the electric-field perturbation.

Parameters

select – Possible values in [“at_least_one”, “at_least_one_diagoterm”, “all”] If select == “at_least_one”, we check if there’s at least one entry associated to the electric field and we assume that anaddb will be able to reconstruct the full tensor by symmetry. “at_least_one_diagoterm” is similar but it only checks for the presence of one diagonal term. If select == “all”, all tensor components must be present in the DDB file.

has_emacro_terms(**kwargs)
has_bec_terms(select='at_least_one')[source]

True if the DDB file contains info on the Born effective charges.

Parameters

select – Possible values in [“at_least_one”, “all”] By default, we check if there’s at least one entry associated to atomic displacement and electric field and we assume that anaddb will be able to reconstruct the full tensor by symmetry. If select == “all”, all bec components must be present in the DDB file.

has_strain_terms(select='all')[source]

True if the DDB file contains info on the (clamped-ion) strain perturbation (i.e. 2nd order derivatives wrt strain)

Parameters

select – Possible values in [“at_least_one”, “all”] If select == “at_least_one”, we check if there’s at least one entry associated to the strain. and we assume that anaddb will be able to reconstruct the full tensor by symmetry. If select == “all”, all tensor components must be present in the DDB file.

Note

As anaddb is not yet able to reconstruct the strain terms by symmetry, the default value for select is “all”

has_internalstrain_terms(select='all')[source]

True if the DDB file contains internal strain terms i.e “off-diagonal” 2nd order derivatives wrt (strain, atomic displacement)

Parameters

select – Possible values in [“at_least_one”, “all”] If select == “at_least_one”, we check if there’s at least one entry associated to the strain. and we assume that anaddb will be able to reconstruct the full tensor by symmetry. If select == “all”, all tensor components must be present in the DDB file.

Note

As anaddb is not yet able to reconstruct the strain terms by symmetry, the default value for select is “all”

has_piezoelectric_terms(select='all')[source]

True if the DDB file contains piezoelectric terms i.e “off-diagonal” 2nd order derivatives wrt (electric_field, strain)

Parameters

select – Possible values in [“at_least_one”, “all”] If select == “at_least_one”, we check if there’s at least one entry associated to the strain. and we assume that anaddb will be able to reconstruct the full tensor by symmetry. If select == “all”, all tensor components must be present in the DDB file.

Note

As anaddb is not yet able to reconstruct the (strain, electric) terms by symmetry, the default value for select is “all”

view_phononwebsite(browser=None, verbose=0, dryrun=False, **kwargs)[source]

Invoke anaddb to compute phonon bands. Produce JSON file that can be parsed from the phononwebsite and open it in browser.

Parameters
  • browser – Open webpage in browser. Use default $BROWSER if None.

  • verbose – Verbosity level

  • dryrun – Activate dryrun mode for unit testing purposes.

  • kwargs – Passed to anaget_phbst_and_phdos_files.

Return: Exit status

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

anaget_phmodes_at_qpoint(qpoint=None, asr=2, chneut=1, dipdip=1, workdir=None, mpi_procs=1, manager=None, verbose=0, lo_to_splitting=False, spell_check=True, directions=None, anaddb_kwargs=None, return_input=False)[source]

Execute anaddb to compute phonon modes at the given q-point. Non analytical contribution can be added if qpoint is Gamma and required elements are present in the DDB.

Parameters
  • qpoint – Reduced coordinates of the qpoint where phonon modes are computed.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • workdir – Working directory. If None, a temporary directory is created.

  • mpi_procs – Number of MPI processes to use.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • verbose – verbosity level. Set it to a value > 0 to get more information.

  • lo_to_splitting – Allowed values are [True, False, “automatic”]. Defaults to False If True the LO-TO splitting will be calculated if qpoint == Gamma and the non_anal_directions non_anal_phfreqs attributes will be addeded to the phonon band structure. “automatic” activates LO-TO if the DDB file contains the dielectric tensor and Born effective charges.

  • directions – list of 3D directions along which the LO-TO splitting will be calculated. If None the three cartesian direction will be used.

  • anaddb_kwargs – additional kwargs for anaddb.

  • return_input – True if abipy.abio.inputs.AnaddbInput object should be returned as 2nd argument

Return: abipy.dfpt.phonons.PhononBands object.

anaget_phmodes_at_qpoints(qpoints=None, asr=2, chneut=1, dipdip=1, ifcflag=0, ngqpt=None, workdir=None, mpi_procs=1, manager=None, verbose=0, lo_to_splitting=False, spell_check=True, directions=None, anaddb_kwargs=None, return_input=False)[source]

Execute anaddb to compute phonon modes at the given list of q-points. Non analytical contribution can be added if Gamma belongs to the list and required elements are present in the DDB. If the list of q-points contains points that are not present in the DDB the values will be interpolated and ifcflag should be set to 1.

Parameters
  • qpoints – Reduced coordinates of a list of qpoints where phonon modes are computed.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • ifcflag – Anaddb input variable. See official documentation.

  • ngqpt – Number of divisions for the q-mesh in the DDB file. Auto-detected if None (default).

  • workdir – Working directory. If None, a temporary directory is created.

  • mpi_procs – Number of MPI processes to use.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • verbose – verbosity level. Set it to a value > 0 to get more information.

  • lo_to_splitting – Allowed values are [True, False, “automatic”]. Defaults to False If True the LO-TO splitting will be calculated if qpoint == Gamma and the non_anal_directions non_anal_phfreqs attributes will be addeded to the phonon band structure. “automatic” activates LO-TO if the DDB file contains the dielectric tensor and Born effective charges.

  • directions – list of 3D directions along which the LO-TO splitting will be calculated. If None the three cartesian direction will be used.

  • anaddb_kwargs – additional kwargs for anaddb.

  • return_input – True if abipy.abio.inputs.AnaddbInput object should be returned as 2nd argument

Return: abipy.dfpt.phonons.PhononBands object.

anaget_phbst_and_phdos_files(nqsmall=10, qppa=None, ndivsm=20, line_density=None, asr=2, chneut=1, dipdip=1, dos_method='tetra', lo_to_splitting='automatic', ngqpt=None, qptbounds=None, anaddb_kwargs=None, verbose=0, spell_check=True, mpi_procs=1, workdir=None, manager=None, return_input=False)[source]

Execute anaddb to compute the phonon band structure and the phonon DOS. Return contex manager that closes the files automatically.

Important

Use:

with ddb.anaget_phbst_and_phdos_files(…) as g:

phbst_file, phdos_file = g[0], g[0]

to ensure the netcdf files are closed instead of:

phbst_file, phdos_file = ddb.anaget_phbst_and_phdos_files(…)

Parameters
  • nqsmall – Defines the homogeneous q-mesh used for the DOS. Gives the number of divisions used to sample the smallest lattice vector. If 0, DOS is not computed and (phbst, None) is returned.

  • qppa – Defines the homogeneous q-mesh used for the DOS in units of q-points per reciproval atom. Overrides nqsmall.

  • ndivsm – Number of division used for the smallest segment of the q-path.

  • line_density – Defines the a density of k-points per reciprocal atom to plot the phonon dispersion. Overrides ndivsm.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • dos_method – Technique for DOS computation in Possible choices: “tetra”, “gaussian” or “gaussian:0.001 eV”. In the later case, the value 0.001 eV is used as gaussian broadening.

  • lo_to_splitting – Allowed values are [True, False, “automatic”]. Defaults to “automatic” If True the LO-TO splitting will be calculated and the non_anal_directions and the non_anal_phfreqs attributes will be addeded to the phonon band structure. “automatic” activates LO-TO if the DDB file contains the dielectric tensor and Born effective charges.

  • ngqpt – Number of divisions for the q-mesh in the DDB file. Auto-detected if None (default).

  • qptbounds – Boundaries of the path. If None, the path is generated from an internal database depending on the input structure.

  • anaddb_kwargs – additional kwargs for anaddb.

  • verbose – verbosity level. Set it to a value > 0 to get more information.

  • mpi_procs – Number of MPI processes to use.

  • workdir – Working directory. If None, a temporary directory is created.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file.

  • return_input – True if abipy.abio.inputs.AnaddbInput object should be attached to the Context manager.

Returns: Context manager with two files:

abipy.dfpt.phonons.PhbstFile with the phonon band structure. abipy.dfpt.phonons.PhdosFile with the the phonon DOS.

get_coarse(ngqpt_coarse, filepath=None)[source]

Get a version of this file on a coarse mesh

Parameters
  • ngqpt_coarse – list of ngqpt indexes that must be a sub-mesh of the original ngqpt

  • filepath – Filename for coarse DDB. If None, temporary filename is used.

Return: abipy.dfpt.ddb.DdbFile on coarse mesh.

anacompare_asr(asr_list=(0, 2), chneut_list=(1), dipdip=1, lo_to_splitting='automatic', nqsmall=10, ndivsm=20, dos_method='tetra', ngqpt=None, verbose=0, mpi_procs=1)[source]

Invoke anaddb to compute the phonon band structure and the phonon DOS with different values of the asr input variable (acoustic sum rule treatment). Build and return abipy.dfpt.phonons.PhononBandsPlotter object.

Parameters
  • asr_list – List of asr values to test.

  • chneut_list – List of chneut values to test (used by anaddb only if dipdip == 1).

  • dipdip – 1 to activate treatment of dipole-dipole interaction (requires BECS and dielectric tensor).

  • lo_to_splitting – Allowed values are [True, False, “automatic”]. Defaults to “automatic” If True the LO-TO splitting will be calculated if qpoint == Gamma and the non_anal_directions non_anal_phfreqs attributes will be addeded to the phonon band structure. “automatic” activates LO-TO if the DDB file contains the dielectric tensor and Born effective charges.

  • nqsmall – Defines the q-mesh for the phonon DOS in terms of the number of divisions to be used to sample the smallest reciprocal lattice vector. 0 to disable DOS computation.

  • ndivsm – Number of division used for the smallest segment of the q-path

  • dos_method – Technique for DOS computation in Possible choices: “tetra”, “gaussian” or “gaussian:0.001 eV”. In the later case, the value 0.001 eV is used as gaussian broadening

  • ngqpt – Number of divisions for the ab-initio q-mesh in the DDB file. Auto-detected if None (default)

  • verbose – Verbosity level.

  • mpi_procs – Number of MPI processes used by anaddb.

Returns

abipy.dfpt.phonons.PhononBandsPlotter object.

Client code can use plotter.combiplot() or plotter.gridplot() to visualize the results.

anacompare_dipdip(chneut_list=(1), asr=2, lo_to_splitting='automatic', nqsmall=10, ndivsm=20, dos_method='tetra', ngqpt=None, verbose=0, mpi_procs=1)[source]

Invoke anaddb to compute the phonon band structure and the phonon DOS with different values of the dipdip input variable (dipole-dipole treatment). Build and return abipy.dfpt.phonons.PhononDosPlotter object.

Parameters
  • chneut_list – List of chneut values to test (used for dipdip == 1).

  • asr_list – Variable for acoustic sum rule treatment.

  • lo_to_splitting – Allowed values are [True, False, “automatic”]. Defaults to “automatic” If True the LO-TO splitting will be calculated if qpoint == Gamma and the non_anal_directions non_anal_phfreqs attributes will be addeded to the phonon band structure. “automatic” activates LO-TO if the DDB file contains the dielectric tensor and Born effective charges.

  • nqsmall – Defines the q-mesh for the phonon DOS in terms of the number of divisions to be used to sample the smallest reciprocal lattice vector. 0 to disable DOS computation.

  • ndivsm – Number of division used for the smallest segment of the q-path

  • dos_method – Technique for DOS computation in Possible choices: “tetra”, “gaussian” or “gaussian:0.001 eV”. In the later case, the value 0.001 eV is used as gaussian broadening

  • ngqpt – Number of divisions for the ab-initio q-mesh in the DDB file. Auto-detected if None (default)

  • verbose – Verbosity level.

  • mpi_procs – Number of MPI processes used by anaddb.

Returns

abipy.dfpt.phonons.PhononDosPlotter object.

Client code can use plotter.combiplot() or plotter.gridplot() to visualize the results.

anacompare_phdos(nqsmalls, asr=2, chneut=1, dipdip=1, dos_method='tetra', ngqpt=None, verbose=0, num_cpus=1, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]

Invoke Anaddb to compute Phonon DOS with different q-meshes. The ab-initio dynamical matrix reported in the DDB file will be Fourier-interpolated on the list of q-meshes specified by nqsmalls. Useful to perform convergence studies.

Parameters
  • nqsmalls – List of integers defining the q-mesh for the DOS. Each integer gives the number of divisions to be used to sample the smallest reciprocal lattice vector.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • dos_method – Technique for DOS computation in Possible choices: “tetra”, “gaussian” or “gaussian:0.001 eV”. In the later case, the value 0.001 eV is used as gaussian broadening

  • ngqpt – Number of divisions for the ab-initio q-mesh in the DDB file. Auto-detected if None (default)

  • verbose – Verbosity level.

  • num_cpus – Number of CPUs (threads) used to parallellize the calculation of the DOSes. Autodetected if None.

  • stream – File-like object used for printing.

Returns

namedtuple with the following attributes:

phdoses: List of |PhononDos| objects
plotter: |PhononDosPlotter| object.
    Client code can use ``plotter.gridplot()`` to visualize the results.

anacompare_rifcsph(rifcsph_list, asr=2, chneut=1, dipdip=1, lo_to_splitting='automatic', ndivsm=20, ngqpt=None, verbose=0, mpi_procs=1)[source]

Invoke anaddb to compute the phonon band structure and the phonon DOS with different values of the asr input variable (acoustic sum rule treatment). Build and return abipy.dfpt.phonons.PhononBandsPlotter object.

Parameters
  • rifcsph_list – List of rifcsph to analyze.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • dipdip – 1 to activate treatment of dipole-dipole interaction (requires BECS and dielectric tensor).

  • lo_to_splitting – Allowed values are [True, False, “automatic”]. Defaults to “automatic” If True the LO-TO splitting will be calculated if qpoint == Gamma and the non_anal_directions non_anal_phfreqs attributes will be addeded to the phonon band structure. “automatic” activates LO-TO if the DDB file contains the dielectric tensor and Born effective charges.

  • ndivsm – Number of division used for the smallest segment of the q-path

  • ngqpt – Number of divisions for the ab-initio q-mesh in the DDB file. Auto-detected if None (default)

  • verbose – Verbosity level.

  • mpi_procs – Number of MPI processes used by anaddb.

Returns

abipy.dfpt.phonons.PhononBandsPlotter object.

Client code can use plotter.combiplot() or plotter.gridplot() to visualize the results.

anaget_epsinf_and_becs(chneut=1, mpi_procs=1, workdir=None, manager=None, verbose=0)[source]

Call anaddb to compute the macroscopic electronic dielectric tensor (e_inf) and the Born effective charges in Cartesian coordinates.

Parameters
  • chneut – Anaddb input variable. See official documentation.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • mpi_procs – Number of MPI processes to use.

  • verbose – verbosity level. Set it to a value > 0 to get more information

Return: namedtuple with the following attributes::

epsinf: abipy.tools.tensors.DielectricTensor object. becs: Becs objects.

anaget_emacro_and_becs(**kwargs)
anaget_ifc(ifcout=None, asr=2, chneut=1, dipdip=1, ngqpt=None, mpi_procs=1, workdir=None, manager=None, verbose=0, anaddb_kwargs=None)[source]

Execute anaddb to compute the interatomic forces.

Parameters
  • ifcout – Number of neighbouring atoms for which the ifc’s will be output. If None all the atoms in the big box.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • ngqpt – Number of divisions for the q-mesh in the DDB file. Auto-detected if None (default)

  • mpi_procs – Number of MPI processes to use.

  • workdir – Working directory. If None, a temporary directory is created.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • verbose – verbosity level. Set it to a value > 0 to get more information

  • anaddb_kwargs – additional kwargs for anaddb

Returns

InteratomicForceConstants with the calculated ifc.

anaget_phonopy_ifc(ngqpt=None, supercell_matrix=None, asr=0, chneut=0, dipdip=0, manager=None, workdir=None, mpi_procs=1, symmetrize_tensors=False, output_dir_path=None, prefix_outfiles='', symprec=1e-05, set_masses=False, verbose=0)[source]

Runs anaddb to get the interatomic force constants(IFC), born effective charges(BEC) and dielectric tensor obtained and converts them to the phonopy format. Optionally writes the standard phonopy files to a selected directory: FORCE_CONSTANTS, BORN (if BECs are available) POSCAR of the unit cell, POSCAR of the supercell.

Parameters
  • ngqpt – the ngqpt used to generate the anaddbnc. Will be used to determine the (diagonal) supercell matrix in phonopy. A smaller value can be used, but some information will be lost and inconsistencies in the convertion may occour.

  • supercell_matrix – the supercell matrix used for phonopy. if None it will be set to a diagonal matrix with ngqpt on the diagonal. This should provide the best agreement between the anaddb and phonopy results.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • workdir – Working directory. If None, a temporary directory is created.

  • mpi_procs – Number of MPI processes to use.

  • symmetrize_tensors – if True the tensors will be symmetrized in the Phonopy object and in the output files. This will apply to IFC, BEC and dielectric tensor.

  • output_dir_path – a path to a directory where the phonopy files will be created

  • prefix_outfiles – a string that will be added as a prefix to the name of the written files

  • symprec – distance tolerance in Cartesian coordinates to find crystal symmetry in phonopy. It might be that the value should be tuned so that it leads to the the same symmetries as in the abinit calculation.

  • set_masses – if True the atomic masses used by abinit will be added to the PhonopyAtoms and will be present in the returned Phonopy object. This should improve compatibility among abinit and phonopy results if frequencies needs to be calculated.

  • verbose – verbosity level. Set it to a value > 0 to get more information

Returns

An instance of a Phonopy object that contains the IFC, BEC and dieletric tensor data.

anaget_interpolated_ddb(qpt_list, asr=2, chneut=1, dipdip=1, ngqpt=None, workdir=None, manager=None, mpi_procs=1, verbose=0, anaddb_kwargs=None)[source]

Runs anaddb to generate an interpolated DDB file on a list of qpt.

Parameters
  • qpt_list – list of fractional coordinates of qpoints where the ddb should be interpolated.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • ngqpt – Number of divisions for the q-mesh in the DDB file. Auto-detected if None (default).

  • workdir – Working directory. If None, a temporary directory is created.

  • mpi_procs – Number of MPI processes to use.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • verbose – verbosity level. Set it to a value > 0 to get more information.

  • anaddb_kwargs – additional kwargs for anaddb.

anaget_dielectric_tensor_generator(asr=2, chneut=1, dipdip=1, workdir=None, mpi_procs=1, manager=None, verbose=0, anaddb_kwargs=None, return_input=False)[source]

Execute anaddb to extract the quantities necessary to create a abipy.dfpt.ddb.DielectricTensorGenerator. Requires phonon perturbations at Gamma and static electric field perturbations.

Parameters
  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • workdir – Working directory. If None, a temporary directory is created.

  • mpi_procs – Number of MPI processes to use.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • verbose – verbosity level. Set it to a value > 0 to get more information

  • anaddb_kwargs – additional kwargs for anaddb

  • return_input – True if abipy.abio.inputs.AnaddbInput object should be returned as 2nd argument

Return: abipy.dfpt.ddb.DielectricTensorGenerator object.

anaget_elastic(relaxed_ion='automatic', piezo='automatic', dde=False, stress_correction=False, asr=2, chneut=1, mpi_procs=1, workdir=None, manager=None, verbose=0, retpath=False)[source]

Call anaddb to compute elastic and piezoelectric tensors. Require DDB with strain terms.

By default, this method sets the anaddb input variables automatically by looking at the 2nd-order derivatives available in the DDB file. This behaviour can be changed by setting explicitly the value of: relaxed_ion and piezo.

Parameters
  • relaxed_ion – Activate computation of relaxed-ion tensors. Allowed values are [True, False, “automatic”]. Defaults to “automatic”. In “automatic” mode, relaxed-ion tensors are automatically computed if internal strain terms and phonons at Gamma are present in the DDB.

  • piezo – Activate computation of piezoelectric tensors. Allowed values are [True, False, “automatic”]. Defaults to “automatic”. In “automatic” mode, piezoelectric tensors are automatically computed if piezoelectric terms are present in the DDB. NB: relaxed-ion piezoelectric requires the activation of relaxed_ion.

  • dde – if True, dielectric tensors will be calculated.

  • stress_correction – Calculate the relaxed ion elastic tensors, considering the stress left inside cell. The DDB must contain the stress tensor.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • mpi_procs – Number of MPI processes to use.

  • workdir – Working directory. If None, a temporary directory is created.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • verbose – verbosity level. Set it to a value > 0 to get more information

  • retpath – True to return path to anaddb.nc file.

Returns

abipy.dfpt.elastic.ElasticData object if retpath is None else absolute path to anaddb.nc file.

anaget_raman(asr=2, chneut=1, ramansr=1, alphon=1, workdir=None, mpi_procs=1, manager=None, verbose=0, directions=None, anaddb_kwargs=None)[source]

Execute anaddb to compute the Raman spectrum

Parameters
  • qpoint – Reduced coordinates of the qpoint where phonon modes are computed.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • ramansr – Anaddb input variable. See official documentation.

  • alphon – Anaddb input variable. See official documentation.

  • workdir – Working directory. If None, a temporary directory is created.

  • mpi_procs – Number of MPI processes to use.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • verbose – verbosity level. Set it to a value > 0 to get more information.

  • directions – list of 3D directions along which the non analytical contribution will be calculated. If None the three cartesian direction will be used.

  • anaddb_kwargs – additional kwargs for anaddb.

Return: |Raman| object.

write(filepath, filter_blocks=None)[source]

Writes the DDB file in filepath. Requires the blocks data. Only the information stored in self.header.lines and in self.blocks will be used to produce the file

get_block_for_qpoint(qpt)[source]

Extracts the block data for the selected qpoint. Returns a list of lines containing the block information

replace_block_for_qpoint(qpt, data)[source]

Change the block data for the selected qpoint. Object is modified in-place. Data should be a list of strings representing the whole data block. Note that the DDB file should be written and reopened in order to call methods that run anaddb.

Returns

True if qpt has been found and data has been replaced.

insert_block(data, replace=True)[source]

Inserts a block in the list. Can replace a block if already present.

Parameters
  • data – a dictionary with keys “dord” (the order of the perturbation), “qpt” (the fractional coordinates of the qpoint if dord=2), “qpt3” (the fractional coordinates of the qpoints if dord=3), “data” (the lines of the block of data).

  • replace – if True and an equivalent block is already present it will be replaced, otherwise the block will not be inserted.

Returns

True if the block was inserted.

Return type

bool

remove_block(dord, qpt=None, qpt3=None)[source]

Removes one block from the list of blocks in the ddb :param dord: the order of the perturbation (from 0 to 3). :param qpt: the fractional coordinates of the q point of the block to be

removed. Should be present if dord=2.

Parameters

qpt3 – a 3x3 matrix with the coordinates for the third order perturbations. Should be present in dord=3.

Returns

True if a matching block was found and removed.

Return type

bool

get_2nd_ord_dict()[source]

Generates an ordered dictionary with the second order derivative of the form {qpt: {(idir1, ipert1, idir2, ipert2): complex value}}.

Returns

a dictionary with all the elements of a dynamical matrix

Return type

OrderedDict

set_2nd_ord_data(data, replace=True)[source]

Insert the blocks corresponding to the data provided for the second order perturbations.

Parameters
  • data – a dict of the form {qpt: {(idir1, ipert1, idir2, ipert2): complex value}}.

  • replace – if True and an equivalent block is already present it will be replaced, otherwise the block will not be inserted.

get_panel()[source]

Build panel with widgets to interact with the abipy.dfpt.ddb.DdbFile either in a notebook or in panel app.

write_notebook(nbpath=None)[source]

Write an jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

class abipy.dfpt.ddb.Becs(becs_arr, structure, chneut, order='c')[source]

Bases: abipy.core.mixins.Has_Structure, monty.json.MSONable

This object stores the Born effective charges and provides simple tools for data analysis.

as_dict()[source]

Return dictionary with JSON serialization in MSONable format.

property structure

abipy.core.structure.Structure object.

to_string(verbose=0)[source]

String representation.

property sumrule

[3, 3] matrix with Born effective charge neutrality sum-rule.

get_voigt_dataframe(view='inequivalent', tol=0.001, select_symbols=None, decimals=5, verbose=0)[source]

Return pandas.DataFrame with Voigt indices as columns and natom rows.

Parameters
  • view – “inequivalent” to show only inequivalent atoms. “all” for all sites.

  • tol – Entries are set to zero below this value

  • select_symbols – String or list of strings with chemical symbols. Used to select only atoms of this type.

  • decimals – Number of decimal places to round to. If decimals is negative, it specifies the number of positions to the left of the decimal point.

  • verbose – Verbosity level.

check_site_symmetries(verbose=0)[source]

Check site symmetries of the Born effective charges. Print output to terminal. Return: max_err

class abipy.dfpt.ddb.DielectricTensorGenerator(phfreqs, oscillator_strength, eps0, epsinf, structure)[source]

Bases: abipy.core.mixins.Has_Structure

Object used to generate frequency dependent dielectric tensors as obtained from DFPT calculations. The values are calculated on the fly based on the phonon frequencies at gamma and oscillator strengths. The first three frequencies would be considered as acoustic modes and ignored in the calculation. No checks would be performed.

See the definitions Eq.(53-54) in [Gonze1997] PRB55, 10355 (1997).

classmethod from_files(phbst_filepath, anaddbnc_filepath)[source]

Generates the object from the files that contain the phonon frequencies, oscillator strength and static dielectric tensor, i.e. the PHBST.nc and anaddb.nc netcdf files, respectively.

classmethod from_objects(phbands, anaddbnc)[source]

Generates the object from the objects abipy.dfpt.phonons.PhononBands object and AnaddbNcFile

property structure

abipy.core.structure.Structure object.

to_string(verbose=0)[source]

String representation with verbosity level verbose.

get_oscillator_dataframe(reim='all', tol=1e-06)[source]

Return pandas.DataFrame with oscillator matrix elements.

Parameters
  • reim – “re” for real part, “im” for imaginary part, “all” for both.

  • tol – Entries are set to zero below this value

tensor_at_frequency(w, gamma_ev=0.0001, units='eV')[source]

Returns a abipy.tools.tensors.DielectricTensor object representing the dielectric tensor in atomic units at the specified frequency w. Eq.(53-54) in PRB55, 10355 (1997).

Parameters
  • w – Frequency.

  • gamma_ev – Phonon damping factor in eV (full width). Poles are shifted by phfreq * gamma_ev. Accept scalar or [nfreq] array.

  • units – string specifying the units used for phonon frequencies. Possible values in

  • ("eV"

  • "meV"

  • "Ha"

  • "cm-1"

  • Case-insensitive. ("Thz")) –

plot(w_min=0, w_max=None, gamma_ev=0.0001, num=500, component='diag', reim='reim', units='eV', with_phfreqs=True, ax=None, fontsize=12, **kwargs)[source]

Plots the selected components of the dielectric tensor as a function of frequency.

Parameters
  • w_min – minimum frequency in units units.

  • w_max – maximum frequency. If None it will be set to the value of the maximum frequency + 5*gamma_ev.

  • gamma_ev – Phonon damping factor in eV (full width). Poles are shifted by phfreq * gamma_ev. Accept scalar or [nfreq] array.

  • num – number of values of the frequencies between w_min and w_max.

  • component

    determine which components of the tensor will be displayed. Can be a list/tuple of two elements, indicating the indices [i, j] of the desired component or a string among:

    • ’diag_av’ to plot the average of the components on the diagonal

    • ’diag’ to plot the elements on diagonal

    • ’all’ to plot all the components in the upper triangle.

    • ’offdiag’ to plot the off-diagonal components in the upper triangle.

  • reim – a string with “re” will plot the real part, with “im” selects the imaginary part.

  • units – string specifying the units used for phonon frequencies. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • with_phfreqs – True to show phonon frequencies with dots.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • fontsize – Legend and label fontsize.

Return: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_vs_w(w_min=0, w_max=None, gamma_ev=0.0001, num=500, component='diag', reim='reim', units='eV', with_phfreqs=True, ax=None, fontsize=12, **kwargs)

Plots the selected components of the dielectric tensor as a function of frequency.

Parameters
  • w_min – minimum frequency in units units.

  • w_max – maximum frequency. If None it will be set to the value of the maximum frequency + 5*gamma_ev.

  • gamma_ev – Phonon damping factor in eV (full width). Poles are shifted by phfreq * gamma_ev. Accept scalar or [nfreq] array.

  • num – number of values of the frequencies between w_min and w_max.

  • component

    determine which components of the tensor will be displayed. Can be a list/tuple of two elements, indicating the indices [i, j] of the desired component or a string among:

    • ’diag_av’ to plot the average of the components on the diagonal

    • ’diag’ to plot the elements on diagonal

    • ’all’ to plot all the components in the upper triangle.

    • ’offdiag’ to plot the off-diagonal components in the upper triangle.

  • reim – a string with “re” will plot the real part, with “im” selects the imaginary part.

  • units – string specifying the units used for phonon frequencies. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • with_phfreqs – True to show phonon frequencies with dots.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • fontsize – Legend and label fontsize.

Return: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_all(**kwargs)[source]

Plot diagonal and off-diagonal elements of the dielectric tensor as a function of frequency. Both real and imag part are show. Accepts all arguments of plot method with the exception of: component and reim.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_e0w_qdirs(qdirs=None, w_min=0, w_max=None, gamma_ev=0.0001, num=500, reim='reim', func='direct', units='eV', with_phfreqs=True, ax=None, fontsize=12, **kwargs)[source]

Plots the dielectric tensor and/or -epsinf_q**2 / epsilon_q along a set of specified directions. With epsilon_q as defined in eq. (56) in [Gonze1997] PRB55, 10355 (1997).

Parameters
  • qdirs – a list of directions along which to plot the dielectric tensor. They will be normalized internally. If None the three cartesian directions will be shown.

  • w_min – minimum frequency in units units.

  • w_max – maximum frequency. If None it will be set to the value of the maximum frequency + 5*gamma_ev.

  • gamma_ev – Phonon damping factor in eV (full width). Poles are shifted by phfreq * gamma_ev. Accept scalar or [nfreq] array.

  • num – number of values of the frequencies between w_min and w_max.

  • reim – a string with “re” will plot the real part, with “im” selects the imaginary part.

  • func – determines which functional form will be plot. Can be: * “direct”: plot of epsilon_q * “inverse”: plot of -epsinf_q**2 / epsilon_q * “both”: both plots.

  • units – string specifying the units used for phonon frequencies. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • with_phfreqs – True to show phonon frequencies with dots.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • fontsize – Legend and label fontsize.

Return: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

reflectivity(qdir, w, gamma_ev=0.0001, units='eV')[source]

Calculates the reflectivity from the dielectric tensor along the specified direction according to eq. (58) in [Gonze1997] PRB55, 10355 (1997).

Parameters
  • qdir – a list with three components defining the direction. It will be normalized internally.

  • w – frequency.

  • gamma_ev – Phonon damping factor in eV (full width). Poles are shifted by phfreq * gamma_ev. Accept scalar or [nfreq] array.

  • units – string specifying the units used for phonon frequencies. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

Returns

the value of the reflectivity.

plot_reflectivity(qdirs=None, w_min=0, w_max=None, gamma_ev=0.0001, num=500, units='eV', with_phfreqs=True, ax=None, fontsize=12, **kwargs)[source]

Plots the reflectivity from the dielectric tensor along the specified directions, according to eq. (58) in [Gonze1997] PRB55, 10355 (1997).

Parameters
  • qdirs – a list of directions along which to plot the dielectric tensor. They will be normalized internally. If None the three cartesian directions will be shown.

  • w_min – minimum frequency in units units.

  • w_max – maximum frequency. If None it will be set to the value of the maximum frequency + 5*gamma_ev.

  • gamma_ev – Phonon damping factor in eV (full width). Poles are shifted by phfreq * gamma_ev. Accept scalar or [nfreq] array.

  • num – number of values of the frequencies between w_min and w_max.

  • units – string specifying the units used for phonon frequencies. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • with_phfreqs – True to show phonon frequencies with dots.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • fontsize – Legend and label fontsize.

Return: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

class abipy.dfpt.ddb.DdbRobot(*args)[source]

Bases: abipy.abio.robots.Robot

This robot analyzes the results contained in multiple DDB files.

Inheritance Diagram

Inheritance diagram of DdbRobot
EXT = 'DDB'
classmethod class_handles_filename(filename)[source]

Exclude DDB.nc files. Override base class.

classmethod from_mpid_list(mpid_list, api_key=None, endpoint=None)[source]

Build a DdbRobot from list of materials-project ids.

Parameters
  • mpid_list – List of Materials Project material_ids (e.g., [“mp-1234”, “mp-1245”]).

  • api_key (str) – A String API key for accessing the MaterialsProject REST interface. If None, the code will check if there is a PMG_MAPI_KEY in your .pmgrc.yaml.

  • endpoint (str) – Url of endpoint to access the MaterialsProject REST interface. Defaults to the standard Materials Project REST address

get_dataframe_at_qpoint(qpoint=None, units='eV', asr=2, chneut=1, dipdip=1, with_geo=True, with_spglib=True, abspath=False, funcs=None)[source]

Call anaddb to compute the phonon frequencies at a single q-point using the DDB files treated by the robot and the given anaddb input arguments. LO-TO splitting is not included. Build and return a pandas.DataFrame with results

Parameters
  • qpoint – Reduced coordinates of the qpoint where phonon modes are computed

  • units – string specifying the units used for ph frequencies. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • with_geo – True if structure info should be added to the dataframe

  • with_spglib – True to compute spglib space group and add it to the DataFrame.

  • abspath – True if paths in index should be absolute. Default: Relative to getcwd().

  • funcs – Function or list of functions to execute to add more data to the DataFrame. Each function receives a abipy.dfpt.ddb.DdbFile object and returns a tuple (key, value) where key is a string with the name of column and value is the value to be inserted.

Return: pandas.DataFrame

anaget_phonon_plotters(**kwargs)[source]

Invoke anaddb to compute phonon bands and DOS using the arguments passed via **kwargs. Collect results and return namedtuple with the following attributes:

phbands_plotter: abipy.dfpt.phonons.PhononBandsPlotter object. phdos_plotter: abipy.dfpt.phonons.PhononDosPlotter object.

anacompare_elastic(ddb_header_keys=None, with_structure=True, with_spglib=True, with_path=False, manager=None, verbose=0, **kwargs)[source]

Compute elastic and piezoelectric properties for all DDBs in the robot and build DataFrame.

Parameters
  • ddb_header_keys – List of keywords in the header of the DDB file whose value will be added to the Dataframe.

  • with_structure – True to add structure parameters to the DataFrame.

  • with_spglib – True to compute spglib space group and add it to the DataFrame.

  • with_path – True to add DDB path to dataframe

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file

  • verbose – verbosity level. Set it to a value > 0 to get more information

  • kwargs – Keyword arguments passed to ddb.anaget_elastic.

Return: DataFrame and list of ElastData objects.

anacompare_becs(ddb_header_keys=None, chneut=1, tol=0.001, with_path=False, verbose=0)[source]

Compute Born effective charges for all DDBs in the robot and build DataFrame. with Voigt indices as columns + metadata. Useful for convergence studies.

Parameters
  • ddb_header_keys – List of keywords in the header of the DDB file whose value will be added to the Dataframe.

  • chneut – Anaddb input variable. See official documentation.

  • tol – Elements below this value are set to zero.

  • with_path – True to add DDB path to dataframe

  • verbose – verbosity level. Set it to a value > 0 to get more information

Return: namedtuple with the following attributes:

df: DataFrame with Voigt as columns.
becs_list: list of Becs objects.
anacompare_epsinf(ddb_header_keys=None, chneut=1, tol=0.001, with_path=False, verbose=0)[source]

Compute (eps^inf) electronic dielectric tensor for all DDBs in the robot and build DataFrame. with Voigt indices as columns + metadata. Useful for convergence studies.

Parameters
  • ddb_header_keys – List of keywords in the header of the DDB file whose value will be added to the Dataframe.

  • chneut – Anaddb input variable. See official documentation.

  • tol – Elements below this value are set to zero.

  • with_path – True to add DDB path to dataframe

  • verbose – verbosity level. Set it to a value > 0 to get more information

Return: namedtuple with the following attributes:

df: DataFrame with Voigt indices as columns.
epsinf_list: List of |DielectricTensor| objects with eps^{inf}
anacompare_eps0(ddb_header_keys=None, asr=2, chneut=1, tol=0.001, with_path=False, verbose=0)[source]

Compute (eps^0) dielectric tensor for all DDBs in the robot and build DataFrame. with Voigt indices as columns + metadata. Useful for convergence studies.

Parameters
  • ddb_header_keys – List of keywords in the header of the DDB file whose value will be added to the Dataframe.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • tol – Elements below this value are set to zero.

  • with_path – True to add DDB path to dataframe

  • verbose – verbosity level. Set it to a value > 0 to get more information

Return: namedtuple with the following attributes:

df: DataFrame with Voigt as columns.
eps0_list: List of |DielectricTensor| objects with eps^0.
dgen_list: List of DielectricTensorGenerator.
yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

write_notebook(nbpath=None)[source]

Write a jupyter notebook to nbpath. If nbpath is None, a temporary file in the current working directory is created. Return path to the notebook.

abipy.dfpt.ddb.get_2nd_ord_block_string(qpt, data)[source]

Helper function providing the lines required in a DDB file for a given q point and second order derivatives.

Parameters
  • qpt – the fractional coordinates of the q point.

  • data – a dictionary of the form {qpt: {(idir1, ipert1, idir2, ipert2): complex value}} with the data that should be given in the string.

Returns

the lines that can be added to the DDB file.

Return type

list of str

elastic Module

Objects to analyze elastic and piezoelectric tensors computed by anaddb.

class abipy.dfpt.elastic.MyElasticTensor(input_array, tol=0.0001)[source]

Bases: pymatgen.analysis.elasticity.elastic.ElasticTensor

get_voigt_dataframe(tol=1e-05)[source]

Return pandas.DataFrame with Voigt indices as colums (C-indexing starting from 0). Useful to analyze the converge of individual elements of the tensor(s) Elements below tol are set to zero.

class abipy.dfpt.elastic.MyPiezoTensor(input_array, tol=0.001)[source]

Bases: pymatgen.analysis.piezo.PiezoTensor

get_voigt_dataframe(tol=1e-05)[source]

Return pandas.DataFrame with Voigt indices as colums (C-indexing starting from 0). Useful to analyze the converge of individual elements of the tensor(s) Elements below tol are set to zero.

class abipy.dfpt.elastic.ElasticData(structure, params, elastic_clamped=None, elastic_relaxed=None, elastic_stress_corr=None, elastic_relaxed_fixed_D=None, piezo_clamped=None, piezo_relaxed=None, d_piezo_relaxed=None, g_piezo_relaxed=None, h_piezo_relaxed=None)[source]

Bases: abipy.core.mixins.Has_Structure, monty.json.MSONable

Container with the different elastic and piezoelectric tensors computed by anaddb. Data is stored in pymatgen tensor objects.

Provides methods to analyze/tabulate data Se also http://progs.coudert.name/elate/mp?query=mp-2172 for a web interface.

ALL_ELASTIC_TENSOR_NAMES = ('elastic_relaxed', 'elastic_clamped', 'elastic_stress_corr', 'elastic_relaxed_fixed_D')
ALL_PIEZOELECTRIC_TENSOR_NAMES = ('piezo_relaxed', 'piezo_clamped', 'd_piezo_relaxed', 'g_piezo_relaxed', 'h_piezo_relaxed')
ALL_TENSOR_NAMES = ('elastic_relaxed', 'elastic_clamped', 'elastic_stress_corr', 'elastic_relaxed_fixed_D', 'piezo_relaxed', 'piezo_clamped', 'd_piezo_relaxed', 'g_piezo_relaxed', 'h_piezo_relaxed')
TYPE2NAMES = {'all': ('elastic_relaxed', 'elastic_clamped', 'elastic_stress_corr', 'elastic_relaxed_fixed_D', 'piezo_relaxed', 'piezo_clamped', 'd_piezo_relaxed', 'g_piezo_relaxed', 'h_piezo_relaxed'), 'elastic': ('elastic_relaxed', 'elastic_clamped', 'elastic_stress_corr', 'elastic_relaxed_fixed_D'), 'piezoelectric': ('piezo_relaxed', 'piezo_clamped', 'd_piezo_relaxed', 'g_piezo_relaxed', 'h_piezo_relaxed')}
TENSOR_META = {'d_piezo_relaxed': {'info': 'relaxed-ion piezoelectric d tensor in Voigt notation (shape: (3, 6))', 'latex': '${d}$', 'units': 'pc/m^2'}, 'elastic_clamped': {'info': 'clamped-ion elastic tensor in Voigt notation (shape: (6, 6))', 'latex': '${\\xoverline(C)}$', 'units': 'GPa'}, 'elastic_relaxed': {'info': 'relaxed-ion elastic tensor in Voigt notation (shape: (6, 6))', 'latex': '${C}$', 'units': 'GPa'}, 'elastic_relaxed_fixed_D': {'info': 'relaxed-ion elastic tensor at fixed displacement field in Voigt notation (shape: (6, 6))', 'latex': '$C^{(D)}$', 'units': 'GPa'}, 'elastic_stress_corr': {'info': 'relaxed-ion elastic tensor considering the stress left inside cell in Voigt notation (shape: (6, 6))', 'latex': '${C^{\\sigma}}$', 'units': 'GPa'}, 'g_piezo_relaxed': {'info': 'relaxed-ion piezoelectric g tensor in Voigt notation (shape: (3, 6))', 'latex': '${g}$', 'units': 'm^2/c'}, 'h_piezo_relaxed': {'info': 'relaxed-ion piezoelectric h tensor in Voigt notation (shape: (3, 6))', 'latex': '${h}$', 'units': 'GN/c'}, 'piezo_clamped': {'info': 'clamped-ion piezoelectric tensor in Voigt notation (shape: (3, 6))', 'latex': '${\\xoverline(e)}$', 'units': 'c/m^2'}, 'piezo_relaxed': {'info': 'relaxed-ion piezoelectric tensor in Voigt notation (shape: (3, 6))', 'latex': '${e}$', 'units': 'c/m^2'}}
property structure

abipy.core.structure.Structure object.

classmethod from_file(path)[source]

Builds the object from an anaddb.nc file

classmethod from_ncreader(reader)[source]

Builds the object from a ETSF_Reader

to_string(verbose=0)[source]

String represention with verbosity level verbose.

get_tensor(tensor_name, tol=None)[source]

Return tensor from its name tensor_name. Set to zero all entries below tol if tol is not None.

name_tensor_list(tensor_names=None, tensor_type='all', tol=None)[source]

List of (name, tensor) tuples. Only tensors stored in the object are returned.

Parameters
  • tensor_names – List of tensor names to select. None means all.

  • tensor_type – Select tensors by type. Must be in [“all”, “elastic”, “piezoelectric”].

  • tol – Set to zero all all entries below this threshold

fit_to_structure(structure=None, symprec=0.1)[source]

Return new ElasticData object with tensors that are invariant with respect to symmetry operations corresponding to structure.

Parameters
  • structureabipy.core.structure.Structure from which to generate symmetry operations If None, the internal structure is used.

  • symprec (float) – symmetry tolerance for the Spacegroup Analyzer used to generate the symmetry operations

convert_to_ieee(structure=None, initial_fit=True, refine_rotation=True)[source]

Return new set of tensors in IEEE format according to the 1987 IEEE standards.

Parameters
  • structure – A abipy.core.structure.Structure structure associated with the tensor to be converted to the IEEE standard If None, the internal structure is used

  • initial_fit (bool) – flag to indicate whether initial tensor is fit to the symmetry of the structure. Defaults to true. Note that if false, inconsistent results may be obtained due to symmetrically equivalent, but distinct transformations being used in different versions of spglib.

  • refine_rotation (bool) – whether to refine the rotation produced by the ieee transform generator, default True

get_elastic_tensor_dataframe(tensor_name='elastic_relaxed', tol=0.001)[source]
Parameters
  • tensor_name

  • tol – set to zero all entries below this threshold.

get_piezoelectric_tensor_dataframe(tensor_name='piezo_relaxed', tol=1e-05)[source]
Parameters
  • tensor_name

  • tol – set to zero all entries below this threshold.

get_elastic_voigt_dataframe(voigt_as_index=True, tol=None)[source]
get_piezo_voigt_dataframe(voigt_as_index=True, tol=None)[source]
get_voigt_dataframe(tensor_names, voigt_as_index=True, tol=None)[source]

Return pandas.DataFrame with Voigt indices as colums (C-indexing starting from 0). Useful to analyze the converge of individual elements of the tensor(s)

Parameters
  • tensor_names – List of tensor names.

  • tol – Set to zero all all entries below a certain threshold

get_elastic_properties_dataframe(tensor_names='all', properties_as_index=False, include_base_props=True, ignore_errors=False, fit_to_structure=False, symprec=0.1)[source]

Return a pandas.DataFrame with properties derived from the elastic tensor and the associated structure

Parameters
  • ["elastic_relaxed" (tensor_names=) –

  • "elastic_clamped"

  • "elastic_stress_corr"

  • "elastic_relaxed_fixed_D"]

  • properties_as_index

  • include_base_props (bool) – whether to include base properties, like k_vrh, etc.

  • ignore_errors (bool) – if set to true, will set problem properties that depend on a physical tensor to None, defaults to False

  • fit_to_structure (bool) – If True, properties are computed with the orginal tensors and symmetrized tensors. An additional column fit_to_structure is added to the dataframe.

  • symprec (float) – symmetry tolerance for the Spacegroup Analyzer used to generate the symmetry operations if fit_to_structure

frozen_phonons Module

Objects to run and analyze the frozen phonons generated from displacements of atoms

abipy.dfpt.frozen_phonons.quadratic_fit_function(xx, aa, bb)[source]

Simple quadratic function used as a default for the fitting.

Parameters
  • xx – the variable

  • aa – the coefficient of the quadratic term

  • bb – the constant term

class abipy.dfpt.frozen_phonons.FrozenPhonon(original_structure, original_displ_cart, structures, normalized_displ_cart, etas, qpt_frac_coords, scale_matrix, energies=None)[source]

Bases: object

Class defining a set of structures with displaced atoms. Provides methods to generate, interpolate and plot the data.

property energies

Energies in eV corresponding to the the structures.

property qpt_cart_coords

The cartesian coordinates of the qpoint.

property n_displ

Number of displacements.

ieta0()[source]

The index corresponding to the structure with no displacements.

classmethod from_phbands(phbands, qpt_frac_coords, imode, etas, scale_matrix=None, max_supercell=None)[source]

Create an instace of FrozenPhonon using the eigendisplacements from a abipy.dfpt.phonons.PhononBands

Parameters
  • phbands – a abipy.dfpt.phonons.PhononBands instance.

  • qpt_frac_coords – q vector in reduced coordinate in reciprocal space or index of the qpoint.

  • imode – index of the mode.

  • etas – list of amplitudes of the displacement to be applied to the system. Will correspond to the largest displacement of one atom in Angstrom.

  • scale_matrix – the scaling matrix of the supercell. If None a scaling matrix suitable for the qpoint will be determined.

  • max_supercell – mandatory if scale_matrix is None, ignored otherwise. Defines the largest supercell in the search for a scaling matrix suitable for the q point.

Returns

A FrozenPhonon.

mass_factor()[source]

The factor accounting for the different masses and displacement of each atom

fit_to_frequency(fit_function=None, units='eV', min_fit_eta=None, max_fit_eta=None)[source]

Uses the energies and the displacements to calculate the phonon frequency corresponding to the quadratic term of the fit. The fit is performed with scipy.optimize.curve_fit based on the function given in input and can also be limited number to a subset of the values of the displacements.

Parameters
  • fit_function – a function that will be used to fit the data. The first parameter should be the coefficient of the quadratic term. If None a simple quadratic fit will be used.

  • units – units of the output frequency. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • min_fit_eta – if not None represents minimum value allowed for the (signed) eta to be used in the fit.

  • max_fit_eta – if not None represents maximum value allowed for the (signed) eta to be used in the fit.

Returns

the values of the frequency extracted from the fit, ‘fit_params’: the parameters obtained from the fit, ‘cov’: the estimated covariance of fit_params (see scipy.optimize.curve_fit documentation for more details).

Return type

A namedtuple with ‘freq’

plot_fit_energies(fit_function=None, min_fit_eta=None, max_fit_eta=None, freq=None, ax=None, **kwargs)[source]

Fits the displacements etas to the energies. See fit_to_frequency() for more details.

Parameters
  • fit_function – a function that will be used to fit the data. The first parameter should be the coefficient of the quadratic term. If None a simple quadratic fit will be used.

  • min_fit_eta – if not None represents minimum value allowed for the (signed) eta to be used in the fit.

  • max_fit_eta – if not None represents maximum value allowed for the (signed) eta to be used in the fit.

  • freq – if not None the quadratic function with this frequency as a coefficient will be added to the plot. freq in eV. Requires the 0 displacement to be present in the list of etas.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

Returns

matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_anharmonic_contribution(freq, relative=False, ax=None, **kwargs)[source]

Plots the the absolute relative difference between the energies extracted from the frequency as quadratic coefficient and the calculated energies, giving an estimate of the anharmonic contribution Requires the 0 displacement to be present in the list of etas.

Parameters
  • freq – phonon frequncy in eV

  • relative – if True the plot will represent the relative difference with respect to the expected value obtained from the frequency, rather than the absolute difference.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

Returns

matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

gruneisen Module

Objects to analyze the results stored in the GRUNS.nc file produced by anaddb.

class abipy.dfpt.gruneisen.GrunsNcFile(filepath)[source]

Bases: abipy.core.mixins.AbinitNcFile, abipy.core.mixins.Has_Structure, abipy.core.mixins.NotebookWriter

This object provides an interface to the GRUNS.nc file produced by abinit. This file contains Grunesein parameters computed via finite difference.

Usage example:

with GrunsNcFile("foo_GRUNS.nc") as ncfile:
    print(ncfile)

Inheritance Diagram

Inheritance diagram of GrunsNcFile
classmethod from_file(filepath)[source]

Initialize the object from a netcdf file

close()[source]

Close file.

params()[source]

OrderedDict with parameters that might be subject to convergence studies.

to_string(verbose=0)[source]

String representation.

property structure

abipy.core.structure.Structure corresponding to the central point V0.

property iv0
doses()[source]

Dictionary with the phonon doses.

wvols_qibz()[source]

Phonon frequencies on regular grid for the different volumes in eV

qibz()[source]

q-points in the irreducible brillouin zone

gvals_qibz()[source]

Gruneisen parameters in the irreducible brillouin zone

phbands_qpath_vol()[source]

List of abipy.dfpt.phonons.PhononBands objects corresponding to the different volumes.

structures()[source]

List of structures

volumes()[source]

List of volumes

phdispl_cart_qibz()[source]

Eigendisplacements for the modes on the qibz

property nvols

Number of volumes

amu_symbol()[source]

Atomic mass units

to_dataframe()[source]

Return a pandas.DataFrame with the following columns:

[‘qidx’, ‘mode’, ‘freq’, ‘qpoint’]

where:

Column

Meaning

qidx

q-point index.

mode

phonon branch index.

grun

Gruneisen parameter.

groupv

Group velocity.

freq

Phonon frequency in eV.

plot_doses(xlims=None, dos_names='all', with_idos=True, **kwargs)[source]

Plot the different DOSes stored in the GRUNS.nc file.

Parameters
  • xlims – Set the data limits for the x-axis in eV. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • dos_names – List of strings defining the DOSes to plot. Use “all” to plot all DOSes available.

  • with_idos – True to display integrated doses.

Return: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

get_plotter()[source]

Return an instance of abipy.dfpt.phonons.PhononBandsPlotter that can be use to plot multiple phonon bands or animate the bands

plot_phbands_with_gruns(fill_with='gruns', gamma_fact=1, alpha=0.6, with_doses='all', units='eV', ylims=None, match_bands=False, qlabels=None, branch_range=None, **kwargs)[source]

Plot the phonon bands corresponding to V0 (the central point) with markers showing the value and the sign of the Grunesein parameters.

Parameters
  • fill_with – Define the quantity used to plot stripes. “gruns” for Grunesein parameters, “gruns_fd” for Grunesein parameters calculated with finite differences, “groupv” for phonon group velocities.

  • gamma_fact – Scaling factor for Grunesein parameters. Up triangle for positive values, down triangles for negative values.

  • alpha – The alpha blending value for the markers between 0 (transparent) and 1 (opaque).

  • with_doses – “all” to plot all DOSes available, None to disable DOS plotting, else list of strings with the name of the DOSes to plot.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • ylims – Set the data limits for the y-axis in eV. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • match_bands – if True tries to follow the band along the path based on the scalar product of the eigenvectors.

  • qlabels – dictionary whose keys are tuples with the reduced coordinates of the q-points. The values are the labels. e.g. qlabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}.

  • branch_range – Tuple specifying the minimum and maximum branch index to plot (default: all branches are plotted).

Returns: matplotlib.figure.Figure.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_gruns_scatter(values='gruns', ax=None, units='eV', cmap='rainbow', **kwargs)[source]

A scatter plot of the values of the Gruneisen parameters or group velocities as a function of the phonon frequencies.

Parameters
  • values – Define the plotted quantity. “gruns” for Grunesein parameters, “gruns_fd” for Grunesein parameters calculated with finite differences, “groupv” for phonon group velocities.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • units – Units for phonon frequencies. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • cmap – matplotlib colormap. If not None, points are colored according to the branch index.

  • **kwargs – kwargs passed to the matplotlib function ‘scatter’. Size defaults to 10.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

split_gruns()[source]

Splits the values of the gruneisen along a path like for the phonon bands

split_dwdq()[source]

Splits the values of the group velocities along a path like for the phonon bands

plot_gruns_bs(values='gruns', ax=None, branch_range=None, qlabels=None, match_bands=False, **kwargs)[source]

A plot of the values of the Gruneisen parameters or group velocities along the high symmetry path. By default only the calculated points will be displayed. If lines are required set a positive value for lw and match_bands=True to obtained reasonable paths.

Parameters
  • values – Define the plotted quantity. “gruns” for Grunesein parameters, “gruns_fd” for Grunesein parameters calculated with finite differences, “groupv” for phonon group velocities.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • branch_range – Tuple specifying the minimum and maximum branch index to plot (default: all branches are plotted).

  • qlabels – dictionary whose keys are tuples with the reduced coordinates of the q-points. The values are the labels. e.g. qlabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}.

  • match_bands – if True the bands will be matched based on the scalar product between the eigenvectors.

  • **kwargs – kwargs passed to the matplotlib function ‘plot’. Marker size defaults to 4, line width to 0, marker to ‘o’, color to black.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user. Used in abiview.py to get a quick look at the results.

write_notebook(nbpath=None)[source]

Write a jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

property phdos

The abipy.dfpt.phonons.PhononDos corresponding to iv0, if present in the file, None otherwise.

average_gruneisen(t=None, squared=True, limit_frequencies=None)[source]

Calculates the average of the Gruneisen based on the values on the regular grid. If squared is True the average will use the squared value of the Gruneisen and a squared root is performed on the final result. Values associated to negative frequencies will be ignored. See Scripta Materialia 129, 88 for definitions.

Parameters
  • t – the temperature at which the average Gruneisen will be evaluated. If None the acoustic Debye temperature is used (see acoustic_debye_temp).

  • squared – if True the average is performed on the squared values of the Gruenisen.

  • limit_frequencies – if None (default) no limit on the frequencies will be applied. Possible values are “debye” (only modes with frequencies lower than the acoustic Debye temperature) and “acoustic” (only the acoustic modes, i.e. the first three modes).

Returns

The average Gruneisen parameter

thermal_conductivity_slack(squared=True, limit_frequencies=None, theta_d=None, t=None)[source]

Calculates the thermal conductivity at the acoustic Debye temperature wit the Slack formula, using the average Gruneisen.

Parameters
  • squared – if True the average is performed on the squared values of the Gruenisen

  • limit_frequencies – if None (default) no limit on the frequencies will be applied. Possible values are “debye” (only modes with frequencies lower than the acoustic Debye temperature) and “acoustic” (only the acoustic modes, i.e. the first three modes).

  • theta_d – the temperature used to estimate the average of the Gruneisen used in the Slack formula. If None the the acoustic Debye temperature is used (see acoustic_debye_temp). Will also be considered as the Debye temperature in the Slack formula.

  • t – temperature at which the thermal conductivity is estimated. If None the value at the calculated acoustic Debye temperature is given. The value is obtained as a simple rescaling of the value at the Debye temperature.

Returns: The value of the thermal conductivity in W/(m*K)

property debye_temp

Debye temperature in K obtained from the phonon DOS

property acoustic_debye_temp

Acoustic Debye temperature in K, i.e. the Debye temperature divided by nsites**(1/3). Obtained from the phonon DOS

classmethod from_ddb_list(ddb_list, nqsmall=10, qppa=None, ndivsm=20, line_density=None, asr=2, chneut=1, dipdip=1, dos_method='tetra', lo_to_splitting='automatic', ngqpt=None, qptbounds=None, anaddb_kwargs=None, verbose=0, mpi_procs=1, workdir=None, manager=None)[source]

Execute anaddb to compute generate the object from a list of ddbs.

Parameters
  • ddb_list – A list with the paths to the ddb_files at different volumes. There should be an odd number of DDB files and the volume increment must be constant. The DDB files will be ordered according to the volume of the unit cell and the middle one will be considered as the DDB at the relaxed volume.

  • nqsmall – Defines the homogeneous q-mesh used for the DOS. Gives the number of divisions used to sample the smallest lattice vector. If 0, DOS is not computed and (phbst, None) is returned.

  • qppa – Defines the homogeneous q-mesh used for the DOS in units of q-points per reciprocal atom. Overrides nqsmall.

  • ndivsm – Number of division used for the smallest segment of the q-path.

  • line_density – Defines the a density of k-points per reciprocal atom to plot the phonon dispersion. Overrides ndivsm.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • dos_method – Technique for DOS computation in Possible choices: “tetra”, “gaussian” or “gaussian:0.001 eV”. In the later case, the value 0.001 eV is used as gaussian broadening.

  • lo_to_splitting – Allowed values are [True, False, “automatic”]. Defaults to “automatic” If True the LO-TO splitting will be calculated and the non_anal_directions and the non_anal_phfreqs attributes will be addeded to the phonon band structure. “automatic” activates LO-TO if the DDB file contains the dielectric tensor and Born effective charges.

  • ngqpt – Number of divisions for the q-mesh in the DDB file. Auto-detected if None (default).

  • qptbounds – Boundaries of the path. If None, the path is generated from an internal database depending on the input structure.

  • anaddb_kwargs – additional kwargs for anaddb.

  • verbose – verbosity level. Set it to a value > 0 to get more information.

  • mpi_procs – Number of MPI processes to use.

  • workdir – Working directory. If None, a temporary directory is created.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file.

Returns: A GrunsNcFile object.

grun_vals_finite_differences(match_eigv=True)[source]

Gruneisen parameters along the high symmetry path calculated with finite differences.

split_gruns_finite_differences(match_eigv=True)[source]

Splits the values of the finite differences gruneisen along a path like for the phonon bands

gvals_qibz_finite_differences(match_eigv=True)[source]

Gruneisen parameters in the irreducible brillouin zone calculated with finite differences.

class abipy.dfpt.gruneisen.GrunsReader(filepath)[source]

Bases: abipy.iotools.ETSF_Reader

This object reads the results stored in the GRUNS.nc file produced by ABINIT. It provides helper functions to access the most important quantities.

Inheritance Diagram

Inheritance diagram of GrunsReader
read_doses()[source]

Return a monty.collections.AttrDict with the DOSes available in the file. Empty dict if DOSes are not available.

read_phbands_on_qpath()[source]

Return a list of abipy.dfpt.phonons.PhononBands computed at the different volumes. The iv0 entry corresponds to the central point used to compute Grunesein parameters with finite differences. This object stores the Grunesein parameters in grun_vals.

read_amuz_dict()[source]

Dictionary that associates the atomic number to the values of the atomic mass units used for the calculation.

read_structures()[source]

Resturns a list of structures at the different volumes

abipy.dfpt.gruneisen.calculate_gruns_finite_differences(phfreqs, eig, iv0, volume, dv)[source]

Calculates the Gruneisen parameters from finite differences on the phonon frequencies. Uses the eigenvectors to match the frequencies at different volumes.

Parameters
  • phfreqs – numpy array with the phonon frequencies at different volumes. Shape (nvols, nqpts, 3*natoms)

  • eig – numpy array with the phonon eigenvectors at the different volumes. Shape (nvols, nqpts, 3*natoms, 3*natoms) If None simple ordering will be used.

  • iv0 – index of the 0 volume.

  • volume – volume of the structure at the central volume.

  • dv – volume variation.

Returns

A numpy array with the gruneisen parameters. Shape (nqpts, 3*natoms)

abipy.dfpt.gruneisen.thermal_conductivity_slack(average_mass, volume, mean_g, theta_d, t=None)[source]

Generic function for the calculation of the thermal conductivity at the acoustic Debye temperature with the Slack formula, based on the quantities that can be calculated. Can be used to calculate the thermal conductivity with different definitions of the Gruneisen parameters or of the Debye temperature.

Parameters
  • average_mass – average mass in atomic units of the atoms of the system.

  • volume – volume of the unit cell.

  • mean_g – the mean of the Gruneisen parameters.

  • theta_d – the Debye temperature in the Slack formula.

  • t – temperature at which the thermal conductivity is estimated. If None theta_d is used. The value is obtained as a simple rescaling of the value at the Debye temperature.

Returns

The value of the thermal conductivity in W/(m*K)

ifc Module

The interatomic force constants calculated by anaddb.

class abipy.dfpt.ifc.InteratomicForceConstants(structure, atoms_indices, neighbours_indices, ifc_cart_coord, ifc_cart_coord_short_range, local_vectors, distances, atoms_cart_coord, ifc_weights)[source]

Bases: abipy.core.mixins.Has_Structure

The interatomic force constants calculated by anaddb. Read from anaddb.nc

property number_of_atoms

Number of atoms is structure.

classmethod from_file(filepath)[source]

Create the object from a netcdf file.

property structure

abipy.core.structure.Structure object.

to_string(verbose=0)[source]

String representation.

property number_of_neighbours

Number of neighbouring atoms for which the ifc are present. ifcout in anaddb.

ifc_cart_coord_ewald()[source]

Ewald part of the ifcs in cartesian coordinates

ifc_local_coord()[source]

Ifcs in local coordinates

ifc_local_coord_short_range()[source]

Short range part of the ifcs in cartesian coordinates

ifc_local_coord_ewald()[source]

Ewald part of the ifcs in local coordinates

get_ifc_cartesian(atom_indices=None, atom_element=None, neighbour_element=None, min_dist=None, max_dist=None)[source]

Filters the IFCs in cartesian coordinates All the arguments are optional. If None the filter will not be applied. Returns two arrays containing the distances and the corresponding filtered ifcs.

Parameters
  • atom_indices – a list of atom indices in the structure. Only neighbours of these atoms will be considered.

  • atom_element – symbol of an element in the structure. Only neighbours of these atoms will be considered.

  • neighbour_element – symbol of an element in the structure. Only neighbours of this specie will be considered.

  • min_dist – minimum distance between atoms and neighbours.

  • max_dist – maximum distance between atoms and neighbours.

get_ifc_local(atom_indices=None, atom_element=None, neighbour_element=None, min_dist=None, max_dist=None)[source]

Filters the IFCs in local coordinates All the arguments are optional. If None the filter will not be applied. Returns two arrays containing the distances and the corresponding filtered ifcs.

Parameters
  • atom_indices – a list of atom indices in the structure. Only neighbours of these atoms will be considered.

  • atom_element – symbol of an element in the structure. Only neighbours of these atoms will be considered.

  • neighbour_element – symbol of an element in the structure. Only neighbours of this specie will be considered.

  • min_dist – minimum distance between atoms and neighbours.

  • max_dist – maximum distance between atoms and neighbours.

get_plot_ifc(ifc, atom_indices=None, atom_element=None, neighbour_element=None, min_dist=None, max_dist=None, ax=None, **kwargs)[source]

Plots the specified ifcs, filtered according to the optional arguments. An array with shape number_of_atoms*number_of_neighbours, so only one of the components of the ifc matrix can be plotted at a time.

Parameters
  • ifc – an array with shape number_of_atoms * number_of_neighbours of the ifc that should be plotted

  • atom_indices – a list of atom indices in the structure. Only neighbours of these atoms will be considered.

  • atom_element – symbol of an element in the structure. Only neighbours of these atoms will be considered.

  • neighbour_element – symbol of an element in the structure. Only neighbours of this specie will be considered.

  • min_dist – minimum distance between atoms and neighbours.

  • max_dist – maximum distance between atoms and neighbours.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • kwargs – kwargs passed to the matplotlib function ‘plot’. Color defaults to blue, symbol to ‘o’ and lw to 0

Returns: matplotlib.figure.Figure

plot_longitudinal_ifc(atom_indices=None, atom_element=None, neighbour_element=None, min_dist=None, max_dist=None, ax=None, **kwargs)[source]

Plots the total longitudinal ifcs in local coordinates, filtered according to the optional arguments.

Parameters
  • atom_indices – a list of atom indices in the structure. Only neighbours of these atoms will be considered.

  • atom_element – symbol of an element in the structure. Only neighbours of these atoms will be considered.

  • neighbour_element – symbol of an element in the structure. Only neighbours of this specie will be considered.

  • min_dist – minimum distance between atoms and neighbours.

  • max_dist – maximum distance between atoms and neighbours.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • kwargs – kwargs passed to the matplotlib function ‘plot’. Color defaults to blue, symbol to ‘o’ and lw to 0

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_longitudinal_ifc_short_range(atom_indices=None, atom_element=None, neighbour_element=None, min_dist=None, max_dist=None, ax=None, **kwargs)[source]

Plots the short range longitudinal ifcs in local coordinates, filtered according to the optional arguments.

Parameters
  • atom_indices – a list of atom indices in the structure. Only neighbours of these atoms will be considered.

  • atom_element – symbol of an element in the structure. Only neighbours of these atoms will be considered.

  • neighbour_element – symbol of an element in the structure. Only neighbours of this specie will be considered.

  • min_dist – minimum distance between atoms and neighbours.

  • max_dist – maximum distance between atoms and neighbours.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • kwargs – kwargs passed to the matplotlib function ‘plot’. Color defaults to blue, symbol to ‘o’ and lw to 0

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_longitudinal_ifc_ewald(atom_indices=None, atom_element=None, neighbour_element=None, min_dist=None, max_dist=None, ax=None, **kwargs)[source]

Plots the Ewald part of the ifcs in local coordinates, filtered according to the optional arguments.

Parameters
  • atom_indices – a list of atom indices in the structure. Only neighbours of these atoms will be considered.

  • atom_element – symbol of an element in the structure. Only neighbours of these atoms will be considered.

  • neighbour_element – symbol of an element in the structure. Only neighbours of this specie will be considered.

  • min_dist – minimum distance between atoms and neighbours.

  • max_dist – maximum distance between atoms and neighbours.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • kwargs – kwargs passed to the matplotlib function ‘plot’. Color defaults to blue, symbol to ‘o’ and lw to 0

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

msqdos Module

Objects related to the computation of Debye-Waller tensors from the generalized phonon DOS.

class abipy.dfpt.msqdos.MsqDos(structure, wmesh, values, amu_symbol)[source]

Bases: abipy.core.mixins.Has_Structure

This object stores the generalized phonon DOS in CARTESIAN coords. This DOS-like quantity allows one to calculate Debye Waller factors as a function of Temperature by integration with 1/omega and the Bose-Einstein factor. This object is usually instanciated via the read_msq_dos method of the PhdosReader and stored as attribute of the PhdosFile instance.

See [Lee1995] for the further details about the internal implementation and [Trueblood1996] for the different conventions used by crystallographers.

See also http://atztogo.github.io/phonopy/formulation.html#thermal-displacement

ALL_COMPS = {'trace': <abipy.dfpt.msqdos._Component object>, 'xx': <abipy.dfpt.msqdos._Component object>, 'xy': <abipy.dfpt.msqdos._Component object>, 'xz': <abipy.dfpt.msqdos._Component object>, 'yy': <abipy.dfpt.msqdos._Component object>, 'yz': <abipy.dfpt.msqdos._Component object>, 'zz': <abipy.dfpt.msqdos._Component object>}
property structure

abipy.core.structure.Structure object.

to_string(verbose=0)[source]

Human-readable string with useful information on the object.

Parameters

verbose – Verbosity level.

get_json_doc(tstart=0, tstop=600, num=11)[source]

Return dictionary with results. Used by emmet builder.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate.

get_msq_tmesh(tmesh, iatom_list=None, what_list=('displ', 'vel'))[source]

Compute mean square displacement for each atom in iatom_list as a function of T. in Cartesian coordinates and atomic-units.

Parameters
  • tmesh – array-like with temperatures in Kelvin.

  • iatom_list – List of atom sites to compute. None if all aomts are wanted.

  • what_list – “displ” for displacement, “vel” for velocity tensor.

Returns

namedtuple with (tmesh=tmesh, displ=msq_d, vel=msq_v)

msq_d = np.empty((natom, 3, 3, nt))

convert_ucart(ucart_mat, fmt)[source]

Convert the U tensor from Cartesian coordinates to format fmt Return new tensor. See also [Grosse-Kunstleve2002].

Parameters
  • ucart_mat – (natom,3,3) array with tensor in Cartesian coords.

  • fmt – Output format. Available options: “cif”, “ustar”, “beta”, “cartesian”

Return: (natom, 3, 3) tensor.

get_dataframe(temp=300, fmt='cartesian', view='inequivalent', what='displ', decimals=4, select_symbols=None, verbose=0)[source]

Return pandas.DataFrame with cartesian tensor components as columns and (inequivalent) sites along the rows.

Parameters
  • temp – Temperature in Kelvin.

  • fmt – “cartesian” for elements in Cartesian coordinates, “cif” for results in reduced coordinates

  • view – “inequivalent” to show only inequivalent atoms. “all” for all sites.

  • what – “displ” for displament, “vel” for velocity.

  • decimals – Number of decimal places to round to. If decimals is negative, it specifies the number of positions to the left of the decimal point.

  • select_symbols – String or list of strings with chemical symbols. Used to select only atoms of this type.

  • verbose – Verbosity level.

Return: pandas.DataFrame

write_cif_file(filepath, temp=300, symprec=None)[source]

Write CIF file with structure and anisotropic U tensor in CIF format.

Parameters
  • filepath – Name of CIF file. If None, a temporary filepath is created.

  • temp – Temperature in Kelvin (used to compute U).

  • symprec (float) – If not none, finds the symmetry of the structure and writes the cif with symmetry information. Passes symprec to the SpacegroupAnalyzer

Return: Filepath

vesta_open(temp=300)[source]

Visualize termal displacement ellipsoids at temperature temp (Kelvin) with Vesta application.

get_cif_string(temp=300, symprec=None)[source]

Return string with structure and anisotropic U tensor in CIF format at temperature temp in Kelvin

Parameters

symprec (float) – If not none, finds the symmetry of the structure and writes the cif with symmetry information. Passes symprec to the SpacegroupAnalyzer

check_site_symmetries(temp=300, verbose=0)[source]

Check site symmetries of the displacement tensor at temperature temp in Kelvin. Return maximum error.

plot(components='upper', view='inequivalent', units='eV', select_symbols=None, xlims=None, ylims=None, sharey=False, fontsize=8, verbose=0, **kwargs)[source]

Plot the generalized phonon DOS g_ij(omega, atom) for each atom in the unit cell. One subplot per atom. Each subplot shows the 9 independent components of the symmetric tensor. as a function of frequency. By default, only “inequivalent” atoms are shown.

Parameters
  • view – “inequivalent” to show only inequivalent atoms. “all” for all sites.

  • components – List of cartesian tensor components to plot e.g. [“xx”, “xy”]. “all” for all components. “upper” for the upper triangle, “diag” for diagonal elements.

  • units – Units energy axis. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • select_symbols – String or list of strings with chemical symbols. Used to select only atoms of this type.

  • xlims – Set the data limits for the x-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used.

  • ylims – Set the data limits for the y-axis.

  • sharey – True if y-axis should be shared.

  • fontsize – Legend and title fontsize.

  • verbose – Verbosity level.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_tensor(tstart=0, tstop=600, num=50, components='all', what='displ', view='inequivalent', select_symbols=None, colormap='jet', xlims=None, ylims=None, fontsize=10, verbose=0, **kwargs)[source]

Plot tensor(T) for each atom in the unit cell. One subplot for each component, each subplot show all inequivalent sites. By default, only “inequivalent” atoms are shown.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate.

  • components – “all” for all components. “diag” for diagonal elements, “offdiag” for off-diagonal terms only.

  • what – “displ” for displament, “vel” for velocity.

  • view – “inequivalent” to show only inequivalent atoms. “all” for all sites.

  • select_symbols – String or list of strings with chemical symbols. Used to select only atoms of this type.

  • colormap – matplotlib colormap.

  • xlims – Set the data limits for the x-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used.

  • ylims – Set the data limits for the y-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • fontsize – Legend and title fontsize.

  • verbose – Verbosity level.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_uiso(tstart=0, tstop=600, num=50, what='displ', view='inequivalent', select_symbols=None, colormap='jet', xlims=None, ylims=None, sharey=False, fontsize=10, verbose=0, **kwargs)[source]

Plot phonon PJDOS for each atom in the unit cell. One subplot for each component, each subplot show all inequivalent sites. By default, only “inequivalent” atoms are shown.

comparison of Ueq values, which are calculated as the mean of the diagonal elements of the harmonic ADP tensor, (d) comparison of the ADP anisotropy factor, which is defined as the ratio between maximum Uii and minimum Uii values. A ratio of 1 would correspond to an isotropic displacement.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate.

  • components – “all” for all components. “diag” for diagonal elements, “offdiag” for off-diagonal terms only.

  • what – “displ” for displament, “vel” for velocity.

  • view – “inequivalent” to show only inequivalent atoms. “all” for all sites.

  • select_symbols – String or list of strings with chemical symbols. Used to select only atoms of this type.

  • colormap – matplotlib colormap.

  • xlims – Set the data limits for the x-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used.

  • ylims – Set the data limits for the y-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • sharey – True if y-axis should be shared.

  • fontsize – Legend and title fontsize.

  • verbose – Verbosity level.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

phonons Module

class abipy.dfpt.phonons.PhononBands(structure, qpoints, phfreqs, phdispl_cart, non_anal_ph=None, amu=None, epsinf=None, zcart=None, linewidths=None)[source]

Bases: object

Container object storing the phonon band structure.

Note

Frequencies are in eV. Cartesian displacements are in Angstrom.

classmethod from_file(filepath)[source]

Create the object from a netcdf file.

classmethod as_phbands(obj)[source]

Return an instance of abipy.dfpt.phonons.PhononBands from a generic object obj. Supports:

  • instances of cls

  • files (string) that can be open with abiopen and that provide a phbands attribute.

  • objects providing a phbands attribute.

static phfactor_ev2units(units)[source]

Return conversion factor eV –> units (case-insensitive)

read_non_anal_from_file(filepath)[source]

Reads the non analytical directions, frequencies and displacements from the anaddb.nc file specified and adds them to the object.

property nqpt

An alias for num_qpoints.

to_string(title=None, with_structure=True, with_qpoints=False, verbose=0)[source]

Human-readable string with useful information such as structure, q-points, …

Parameters
  • with_structure – False if structural info should not be displayed.

  • with_qpoints – False if q-point info shoud not be displayed.

  • verbose – Verbosity level.

property displ_shape

The shape of phdispl_cart.

property minfreq

Minimum phonon frequency.

property maxfreq

Maximum phonon frequency in eV.

get_minfreq_mode(mode=None)[source]

Compute the minimum of the frequencies.

get_maxfreq_mode(mode=None)[source]

Compute the minimum of the frequencies.

property shape

Shape of the array with the eigenvalues.

property linewidths

linewidths in eV. numpy.ndarray with shape [nqpt, num_branches].

property has_linewidths

True if bands with linewidths.

dyn_mat_eigenvect()[source]

[nqpt, 3*natom, 3*natom] array with the orthonormal eigenvectors of the dynamical matrix. in Cartesian coordinates.

property non_anal_directions

Cartesian directions along which the non analytical frequencies and displacements are available

property non_anal_phfreqs

Phonon frequencies with non analytical contribution in eV along non_anal_directions

property non_anal_phdispl_cart

Displacement in Cartesian coordinates with non analytical contribution along non_anal_directions

property non_anal_dyn_mat_eigenvect

Eigenvalues of the dynamical matrix with non analytical contribution along non_anal_directions.

to_xmgrace(filepath, units='meV')[source]

Write xmgrace file with phonon band structure energies and labels for high-symmetry q-points.

Parameters
  • filepath – String with filename or stream.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

qindex(qpoint)[source]

Returns the index of the qpoint. Accepts integer or reduced coordinates.

qindex_qpoint(qpoint, is_non_analytical_direction=False)[source]

Returns (qindex, qpoint) from an integer or a qpoint.

Parameters
  • qpoint – integer, vector of reduced coordinates or abipy.core.kpoints.Kpoint object.

  • is_non_analytical_direction – True if qpoint should be interpreted as a fractional direction for q –> 0 In this case qindex refers to the index of the direction in the NonAnalyticalPh object.

get_unstable_modes(below_mev=- 5.0)[source]

Return a list of PhononMode objects with the unstable modes. A mode is unstable if its frequency is < below_mev. Output list is sorted and modes with lowest frequency come first.

get_dict4pandas(with_spglib=True)[source]

Return a OrderedDict with the most important parameters:

  • Chemical formula and number of atoms.

  • Lattice lengths, angles and volume.

  • The spacegroup number computed by Abinit (set to None if not available).

  • The spacegroup number and symbol computed by spglib (set to None not with_spglib).

Useful to construct pandas DataFrames

Parameters

with_spglib – If True, spglib is invoked to get the spacegroup symbol and number

get_phdos(method='gaussian', step=0.0001, width=0.0004)[source]

Compute the phonon DOS on a linear mesh.

Parameters
  • method – String defining the method

  • step – Energy step (eV) of the linear mesh.

  • width – Standard deviation (eV) of the gaussian.

Returns

abipy.dfpt.phonons.PhononDos object.

Warning

Requires a homogeneous sampling of the Brillouin zone.

create_xyz_vib(iqpt, filename, pre_factor=200, do_real=True, scale_matrix=None, max_supercell=None)[source]

Create vibration XYZ file for visualization of phonons.

Parameters
  • iqpt – index of qpoint.

  • filename – name of the XYZ file that will be created.

  • pre_factor – Multiplication factor of the displacements.

  • do_real – True if we want only real part of the displacement, False means imaginary part.

  • scale_matrix – Scaling matrix of the supercell.

  • max_supercell – Maximum size of the supercell with respect to primitive cell.

create_ascii_vib(iqpts, filename, pre_factor=1)[source]

Create vibration ascii file for visualization of phonons. This format can be read with v_sim or ascii-phonons.

Parameters
  • iqpts – an index or a list of indices of the qpoints in self. Note that at present only V_sim supports an ascii file with multiple qpoints.

  • filename – name of the ascii file that will be created.

  • pre_factor – Multiplication factor of the displacements.

view_phononwebsite(browser=None, verbose=0, dryrun=False, **kwargs)[source]

Produce JSON file that can be parsed from the phononwebsite and open it in browser.

Parameters
  • browser – Open webpage in browser. Use default $BROWSER if None.

  • verbose – Verbosity level

  • dryrun – Activate dryrun mode for unit testing purposes.

  • kwargs – Passed to create_phononwebsite_json method

Return: Exit status

create_phononwebsite_json(filename, name=None, repetitions=None, highsym_qpts=None, match_bands=True, highsym_qpts_mode='std', indent=2)[source]

Writes a JSON file that can be parsed from the phononwebsite.

Parameters
  • filename – name of the json file that will be created

  • name – name associated with the data.

  • repetitions – number of repetitions of the cell. List of three integers. Defaults to [3,3,3].

  • highsym_qpts – list of tuples. The first element of each tuple should be a list with the coordinates of a high symmetry point, the second element of the tuple should be its label.

  • match_bands – if True tries to follow the band along the path based on the scalar product of the eigenvectors.

  • highsym_qpts_mode – if highsym_qpts is None, high symmetry q-points can be automatically determined. Accepts the following values: ‘split’ will split the path based on points where the path changes direction in the Brillouin zone. Similar to what is done in phononwebsite. Only Gamma will be labeled. ‘std’ uses the standard generation procedure for points and labels used in PhononBands. None does not set any point.

  • indent – Indentation level, passed to json.dump

make_isodistort_ph_dir(qpoint, select_modes=None, eta=1, workdir=None)[source]

Compute ph-freqs for given q-point (default: Gamma), produce CIF files for unperturbed and distorded structure that can be used with ISODISTORT (https://stokes.byu.edu/iso/isodistort.php) to analyze the symmetry of phonon modes. See README.me file produced in output directory.

Parameters
  • qpoint

  • wordir

  • select_modes

  • eta – Amplitude of the displacement to be applied to the system. Will correspond to the largest displacement of one atom in Angstrom.

  • scale_matrix – the scaling matrix of the supercell. If None a scaling matrix suitable for the qpoint will be determined.

  • max_supercell – mandatory if scale_matrix is None, ignored otherwise. Defines the largest supercell in the search for a scaling matrix suitable for the q point.

decorate_ax(ax, units='eV', **kwargs)[source]

Add q-labels, title and unit name to axis ax. Use units=”” to add k-labels without unit name.

Parameters
  • title

  • fontsize

  • qlabels

  • qlabel_size

plot(ax=None, units='eV', qlabels=None, branch_range=None, match_bands=False, temp=None, fontsize=12, **kwargs)[source]

Plot the phonon band structure.

Parameters
  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • qlabels – dictionary whose keys are tuples with the reduced coordinates of the q-points. The values are the labels. e.g. qlabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}.

  • branch_range – Tuple specifying the minimum and maximum branch index to plot (default: all branches are plotted).

  • match_bands – if True the bands will be matched based on the scalar product between the eigenvectors.

  • temp – Temperature in Kelvin. If not None, a scatter plot with the Bose-Einstein occupation factor at temperature temp is added.

  • fontsize – Legend and title fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_ax(ax, branch, units='eV', match_bands=False, **kwargs)[source]

Plots the frequencies for the given branches indices as a function of the q-index on axis ax. If branch is None, all phonon branches are plotted.

Return: The list of matplotlib lines added.

plot_colored_matched(ax=None, units='eV', qlabels=None, branch_range=None, colormap='rainbow', max_colors=None, **kwargs)[source]

Plot the phonon band structure with different colors for each line.

Parameters
  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • qlabels – dictionary whose keys are tuples with the reduced coordinates of the q-points. The values are the labels. e.g. qlabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}.

  • branch_range – Tuple specifying the minimum and maximum branch_i index to plot (default: all branches are plotted).

  • colormap – matplotlib colormap to determine the colors available. The colors will be chosen not in a sequential order to avoid difficulties in distinguishing the lines. http://matplotlib.sourceforge.net/examples/pylab_examples/show_colormaps.html

  • max_colors – maximum number of colors to be used. If max_colors < num_braches the colors will be reapeated. It useful to better distinguish close bands when the number of branch is large.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_lt_character(units='eV', qlabels=None, ax=None, xlims=None, ylims=None, colormap='jet', fontsize=12, **kwargs)[source]

Plot the phonon band structure with colored lines. The color of the lines indicates the degree to which the mode is longitudinal: Red corresponds to longitudinal modes and black to purely transverse modes.

Parameters
  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • units – Units for plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • qlabels – dictionary whose keys are tuples with the reduced coordinates of the q-points. The values are the labels. e.g. qlabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}.

  • xlims – Set the data limits for the x-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used.

  • ylims – y-axis limits.

  • colormap – Matplotlib colormap.

  • fontsize – legend and title fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

property split_qpoints
property split_phfreqs
property split_phdispl_cart
property split_matched_indices

A list of numpy arrays containing the indices in which each band should be sorted in order to match the scalar product of the eigenvectors. The shape is the same as that of split_phfreqs. Lazy property.

plot_fatbands(use_eigvec=True, units='eV', colormap='jet', phdos_file=None, alpha=0.6, max_stripe_width_mev=5.0, width_ratios=(2, 1), qlabels=None, ylims=None, fontsize=12, **kwargs)[source]

Plot phonon fatbands and, optionally, atom-projected phonon DOSes. The width of the band is given by ||v_{type}|| where v is the (complex) phonon displacement (eigenvector) in cartesian coordinates and v_{type} selects only the terms associated to the atomic type.

Parameters
  • use_eigvec – True if the width of the phonon branch should be computed from the eigenvectors. False to use phonon displacements. Note that the PHDOS is always decomposed in terms of (orthonormal) eigenvectors.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • colormap – Have a look at the colormaps here and decide which one you like: http://matplotlib.sourceforge.net/examples/pylab_examples/show_colormaps.html

  • phdos_file – Used to activate fatbands + PJDOS plot. Accept string with path of PHDOS.nc file or abipy.dfpt.phonons.PhdosFile object.

  • alpha – The alpha blending value, between 0 (transparent) and 1 (opaque)

  • max_stripe_width_mev – The maximum width of the stripe in meV. Will be rescaled according to units.

  • width_ratios – Ratio between the width of the fatbands plots and the DOS plots. Used if phdos_file is not None

  • ylims – Set the data limits for the y-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • qlabels – dictionary whose keys are tuples with the reduced coordinates of the q-points. The values are the labels. e.g. qlabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}.

  • fontsize – Legend and title fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_with_phdos(phdos, units='eV', qlabels=None, ax_list=None, width_ratios=(2, 1), **kwargs)[source]

Plot the phonon band structure with the phonon DOS.

Parameters
  • phdos – An instance of abipy.dfpt.phonons.PhononDos or a netcdf file providing a PhononDos object.

  • units – Units for plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • qlabels – dictionary whose keys are tuples with the reduced coordinates of the q-points. The values are the labels e.g. qlabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}.

  • ax_list – The axes for the bandstructure plot and the DOS plot. If ax_list is None, a new figure is created and the two axes are automatically generated.

  • width_ratios – Ratio between the width of the bands plots and the DOS plots. Used if ax_list is None

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_phdispl(qpoint, cart_dir=None, use_reduced_coords=False, ax=None, units='eV', is_non_analytical_direction=False, use_eigvec=False, colormap='viridis', hatches='default', atoms_index=None, labels_groups=None, normalize=True, use_sqrt=False, fontsize=12, branches=None, format_w='%.3f', **kwargs)[source]

Plot vertical bars with the contribution of the different atoms or atomic types to all the phonon modes at a given qpoint. The contribution is given by ||v_{type}|| where v is the (complex) phonon displacement (eigenvector) in cartesian coordinates and v_{type} selects only the terms associated to the atomic type. Options allow to specify which atoms should be taken into account and how should be reparted.

Parameters
  • qpoint – integer, vector of reduced coordinates or abipy.core.kpoints.Kpoint object.

  • cart_dir – “x”, “y”, or “z” to select a particular Cartesian directions. or combinations separated by “+”. Example: “x+y”. None if no projection is wanted.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • units – Units for phonon frequencies. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • is_non_analytical_direction – If True, the qpoint is interpreted as a direction in q-space and the phonon (displacements/eigenvectors) for q –> 0 along this direction are used. Requires band structure with NonAnalyticalPh object.

  • use_eigvec – True if eigenvectors should be used instead of displacements (eigenvectors are orthonormal, unlike diplacements)

  • colormap – Matplotlib colormap used for atom type.

  • hatches – List of strings with matplotlib hatching patterns. None or empty list to disable hatching.

  • fontsize – Legend and title fontsize.

  • normalize – if True divides by the square norm of the total eigenvector

  • use_sqrt – if True the square root of the sum of the components will be taken

  • use_reduced_coords – if True coordinates will be converted to reduced coordinates. So the values will be fraction of a,b,c rather than x,y,z.

  • atoms_index – list of lists. Each list contains the indices of atoms in the structure that will be summed on a separate group. if None all the atoms will be considered and grouped by type.

  • labels_groups – If atoms_index is not None will provide the labels for each of the group in atoms_index. Should have the same length of atoms_index or be None. If None automatic labelling will be used.

  • branches – list of indices for the modes that should be represented. If None all the modes will be shown.

  • format_w – string used to format the values of the frequency. Default “%.3f”.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_phdispl_cartdirs(qpoint, cart_dirs=('x', 'y', 'z'), units='eV', is_non_analytical_direction=False, use_eigvec=False, colormap='viridis', hatches='default', atoms_index=None, labels_groups=None, normalize=True, use_sqrt=False, fontsize=8, branches=None, format_w='%.3f', **kwargs)[source]

Plot three panels. Each panel shows vertical bars with the contribution of the different atomic types to all the phonon displacements at the given qpoint along on the Cartesian directions in cart_dirs.

Parameters
  • qpoint – integer, vector of reduced coordinates or abipy.core.kpoints.Kpoint object.

  • cart_dirs – List of strings defining the Cartesian directions. “x”, “y”, or “z” to select a particular Cartesian directions. or combinations separated by “+”. Example: “x+y”.

  • units – Units for phonon frequencies. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • is_non_analytical_direction – If True, the qpoint is interpreted as a direction in q-space and the phonon (displacements/eigenvectors) for q –> 0 along this direction are used. Requires band structure with NonAnalyticalPh object.

  • use_eigvec – True if eigenvectors should be used instead of displacements (eigenvectors are orthonormal, unlike diplacements)

  • colormap – Matplotlib colormap used for atom type.

  • hatches – List of strings with matplotlib hatching patterns. None or empty list to disable hatching.

  • fontsize – Legend and title fontsize.

  • normalize – if True divides by the square norm of the total eigenvector

  • use_sqrt – if True the square root of the sum of the components will be taken fraction of a,b,c rather than x,y,z.

  • atoms_index – list of lists. Each list contains the indices of atoms in the structure that will be summed on a separate group. if None all the atoms will be considered and grouped by type.

  • labels_groups – If atoms_index is not None will provide the labels for each of the group in atoms_index. Should have the same length of atoms_index or be None. If None automatic labelling will be used.

  • branches – list of indices for the modes that should be represented. If None all the modes will be shown.

  • format_w – string used to format the values of the frequency. Default “%.3f”.

See plot_phdispl for the meaning of the other arguments.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

get_dataframe()[source]

Return a pandas.DataFrame with the following columns:

[‘qidx’, ‘mode’, ‘freq’, ‘qpoint’]

where:

Column

Meaning

qidx

q-point index.

mode

phonon branch index.

freq

Phonon frequency in eV.

qpoint

abipy.core.kpoints.Kpoint object

boxplot(ax=None, units='eV', mode_range=None, swarm=False, **kwargs)[source]

Use seaborn to draw a box plot to show distributions of eigenvalues with respect to the mode index.

Parameters
  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • mode_range – Only modes such as mode_range[0] <= mode_index < mode_range[1] are included in the plot.

  • swarm – True to show the datapoints on top of the boxes

  • kwargs – Keyword arguments passed to seaborn boxplot.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

to_pymatgen(qlabels=None)[source]

Creates a pymatgen PhononBandStructureSymmLine object.

Parameters

qlabels – dictionary whose keys are tuples with the reduced coordinates of the q-points. The values are the labels e.g. qlabels = {(0.0,0.0,0.0):"$\Gamma$", (0.5,0,0):"L"}. If None labels will be determined automatically.

classmethod from_pmg_bs(pmg_bs, structure=None)[source]

Creates an instance of the object from a PhononBandStructureSymmLine object.

Parameters
  • pmg_bs – the instance of PhononBandStructureSymmLine.

  • structure – a abipy.core.structure.Structure object. Should be present if the structure attribute is not set in pmg_bs.

acoustic_indices(qpoint, threshold=0.95, raise_on_no_indices=True)[source]

Extract the indices of the three acoustic modes for a qpoint. Acoustic modes could be reasonably identified for Gamma and points close to Gamma.

Parameters
  • qpoint – the qpoint. Accepts integer or reduced coordinates

  • threshold – fractional value allowed for the matching of the displacements to identify acoustic modes.

  • raise_on_no_indices – if True a RuntimeError will be raised if the acoustic mode will not be correctly identified. If False [0, 1, 2] will be returned.

asr_breaking(units='eV', threshold=0.95, raise_on_no_indices=True)[source]

Calculates the breaking of the acoustic sum rule. Requires the presence of Gamma.

Parameters
  • units – Units for the output. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • threshold – fractional value allowed for the matching of the displacements to identify acoustic modes.

  • raise_on_no_indices – if True a RuntimeError will be raised if the acoustic mode will not be correctly identified

Returns

the three breaking of the acoustic modes the maximum breaking with sign the absolute value of the maximum breaking

Return type

A namedtuple with

get_frozen_phonons(qpoint, nmode, eta=1, scale_matrix=None, max_supercell=None)[source]

Creates a supercell with displaced atoms for the specified q-point and mode.

Parameters
  • qpoint – q vector in reduced coordinate in reciprocal space or index of the qpoint.

  • nmode – number of the mode.

  • eta – pre-factor multiplying the displacement. Gives the value in Angstrom of the largest displacement.

  • scale_matrix – the scaling matrix of the supercell. If None a scaling matrix suitable for the qpoint will be determined.

  • max_supercell – mandatory if scale_matrix is None, ignored otherwise. Defines the largest supercell in the search for a scaling matrix suitable for the q point.

Returns

A namedtuple with a Structure with the displaced atoms, a numpy array containing the displacements applied to each atom and the scale matrix used to generate the supercell.

get_longitudinal_fraction(qpoint, idir=None)[source]

Calculates “longitudinal” fraction of the eigendisplacements.

Parameters
  • qpoint – q vector in reduced coordinate in reciprocal space or index of the qpoint.

  • idir – an integer with the index of the non analytical direction if qpoint is gamma. If None all will be given.

Returns

A numpy array with the longitudinal fractions for each mode of the specified q point. If qpoint is gamma and idir is None it will be a numpy array with all the non analytical directions.

plot_longitudinal_fraction(qpoint, idir=None, ax_list=None, units='eV', branches=None, format_w='%.3f', fontsize=10, **kwargs)[source]

Plots an histogram “longitudinal” fraction of the eigendisplacements.

Parameters
  • qpoint – q vector in reduced coordinate in reciprocal space or index of the qpoint.

  • idir – an integer with the index of the non analytical direction if qpoint is gamma. If None all will be plot.

  • ax_list – The axes for the plot. If ax_list is None, a new figure is created and the axes are automatically generated.

  • units – Units for the output. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • branches – list of indices for the modes that should be represented. If None all the modes will be shown.

  • format_w – string used to format the values of the frequency. Default “%.3f”.

  • fontsize – Labels and title fontsize.

Returns

matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_longitudinal_fatbands(ax=None, units='eV', qlabels=None, branch_range=None, match_bands=False, sum_degenerate=False, factor=1, **kwargs)[source]

Plot the phonon band structure with width representing the longitudinal fraction of the fatbands.

Parameters
  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • qlabels – dictionary whose keys are tuples with the reduced coordinates of the q-points. The values are the labels. e.g. qlabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}.

  • branch_range – Tuple specifying the minimum and maximum branch index to plot (default: all branches are plotted).

  • match_bands – if True the bands will be matched based on the scalar product between the eigenvectors.

  • sum_degenerate – if True modes with similar frequencies will be considered as degenerated and their contributions will be summed (squared sum). Notice that this may end up summing contributions from modes that are just accidentally degenerated.

  • factor – a float that will used to scale the width of the fatbands.

Returns

matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_qpt_distance(qpt_list=None, ngqpt=None, shiftq=(0, 0, 0), plot_distances=False, units='eV', qlabels=None, branch_range=None, colormap='viridis_r', match_bands=False, log_scale=False, **kwargs)[source]

Plot the phonon band structure coloring the point according to the minimum distance of the qpoints of the path from a list of qpoints. This can be for example defined as the q-points effectively calculated in DFPT. Optionally plot the explicit values.

Parameters
  • qpt_list – list of fractional coordinates or KpointList of the qpoints from which the minimum distance will be calculated.

  • ngqpt – the division of a regular grid of qpoints. Used to automatically fill in the qpt_list based on abipy.core.kpoints.kmesh_from_mpdivs.

  • shiftq – the shifts of a regular grid of qpoints. Used to automatically fill in the qpt_list based on abipy.core.kpoints.kmesh_from_mpdivs.

  • plot_distances – if True a second plot will be added with the explicit values of the distances.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • qlabels – dictionary whose keys are tuples with the reduced coordinates of the q-points. The values are the labels. e.g. qlabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}.

  • branch_range – Tuple specifying the minimum and maximum branch_i index to plot (default: all branches are plotted).

  • colormap – matplotlib colormap to determine the colors available. http://matplotlib.sourceforge.net/examples/pylab_examples/show_colormaps.html

  • match_bands – if True the bands will be matched based on the scalar product between the eigenvectors.

  • log_scale – if True the values will be plotted in a log scale.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

class abipy.dfpt.phonons.PhononBandsPlotter(key_phbands=None, key_phdos=None, phdos_kwargs=None)[source]

Bases: abipy.core.mixins.NotebookWriter

Class for plotting phonon band structure and DOSes. Supports plots on the same graph or separated plots.

Usage example:

plotter = PhononBandsPlotter()
plotter.add_phbands("foo bands", "foo_PHBST.nc")
plotter.add_phbands("bar bands", "bar_PHBST.nc")
plotter.gridplot()
add_plotter(other)[source]

Merge two plotters, return new plotter.

to_string(func=<class 'str'>, verbose=0)[source]

String representation.

has_same_formula()[source]

True of plotter contains structures with same chemical formula.

get_phbands_frame(with_spglib=True)[source]

Build a pandas.DataFrame with the most important results available in the band structures.

property phbands_dict

Dictionary with the mapping label –> phbands.

property bands_dict

Dictionary with the mapping label –> phbands.

property phdoses_dict

Dictionary with the mapping label –> phdos.

property phbands_list

“List of abipy.dfpt.phonons.PhononBands objects.

property phdoses_list

“List of abipy.dfpt.phonons.PhononDos.

iter_lineopt()[source]

Generates matplotlib linestyles.

add_phbands(label, bands, phdos=None, dos=None, phdos_kwargs=None)[source]

Adds a band structure for plotting.

Parameters
combiplot(qlabels=None, units='eV', ylims=None, width_ratios=(2, 1), fontsize=8, linestyle_dict=None, **kwargs)[source]

Plot the band structure and the DOS on the same figure. Use gridplot to plot band structures on different figures.

Parameters
  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • qlabels – dictionary whose keys are tuples with the reduced coordinates of the k-points. The values are the labels e.g. klabels = {(0.0,0.0,0.0): "$\Gamma$", (0.5,0,0): "L"}.

  • ylims – Set the data limits for the y-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • width_ratios – Ratio between the width of the phonon bands plots and the DOS plots. Used if plotter has DOSes.

  • fontsize – fontsize for titles and legend.

  • linestyle_dict – Dictionary mapping labels to matplotlib linestyle options.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot(*args, **kwargs)[source]

An alias for combiplot.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

gridplot(with_dos=True, units='eV', fontsize=8, **kwargs)[source]

Plot multiple phonon bandstructures and optionally DOSes on a grid.

Parameters
  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • with_dos – True to plot phonon DOS (if available).

  • fontsize – legend and title fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

gridplot_with_hue(hue, with_dos=False, units='eV', width_ratios=(2, 1), ylims=None, fontsize=8, **kwargs)[source]

Plot multiple phonon bandstructures and optionally DOSes on a grid. Group results by hue.

Example

plotter.gridplot_with_hue(“tsmear”)

Parameters
  • hue – Variable that define subsets of the phonon bands, which will be drawn on separate plots. Accepts callable or string If string, it’s assumed that the phbands has an attribute with the same name and getattr is invoked. Dot notation is also supported e.g. hue=”structure.formula” –> abifile.structure.formula If callable, the output of hue(phbands) is used.

  • with_dos – True to plot phonon DOS (if available).

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • width_ratios – Ratio between the width of the fatbands plots and the DOS plots. Used if plotter has PH DOSes is not None

  • ylims – Set the data limits for the y-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • fontsize – legend and title fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

boxplot(mode_range=None, units='eV', swarm=False, **kwargs)[source]

Use seaborn to draw a box plot to show distributions of eigenvalues with respect to the band index. Band structures are drawn on different subplots.

Parameters
  • mode_range – Only bands such as mode_range[0] <= nu_index < mode_range[1] are included in the plot.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • swarm – True to show the datapoints on top of the boxes

  • kwargs – Keywork arguments passed to seaborn boxplot.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

combiboxplot(mode_range=None, units='eV', swarm=False, ax=None, **kwargs)[source]

Use seaborn to draw a box plot comparing the distributions of the frequencies. Phonon Band structures are drawn on the same plot.

Parameters
  • mode_range – Only bands such as mode_range[0] <= nu_index < mode_range[1] are included in the plot.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • swarm – True to show the datapoints on top of the boxes

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • kwargs – Keyword arguments passed to seaborn boxplot.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_phdispl(qpoint, **kwargs)[source]

Plot vertical bars with the contribution of the different atomic types to the phonon displacements at a given q-point. One panel for all abipy.dfpt.phonons.PhononBands stored in the plotter.

Parameters
  • qpoint – integer, vector of reduced coordinates or abipy.core.kpoints.Kpoint object.

  • kwargs – keyword arguments passed to phbands.plot_phdispl

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

animate(interval=500, savefile=None, units='eV', width_ratios=(2, 1), show=True)[source]

Use matplotlib to animate a list of band structure plots (with or without DOS).

Parameters
  • interval – draws a new frame every interval milliseconds.

  • savefile – Use e.g. ‘myanimation.mp4’ to save the animation in mp4 format.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • width_ratios – Ratio between the band structure plot and the dos plot. Used when there are DOS stored in the plotter.

  • show – True if the animation should be shown immediately.

Returns: Animation object.

Note

It would be nice to animate the title of the plot, unfortunately this feature is not available in the present version of matplotlib. See: http://stackoverflow.com/questions/17558096/animated-title-in-matplotlib

ipw_select_plot()[source]

Return an ipython widget with controllers to select the plot.

get_panel()[source]

Return tabs with widgets to interact with the abipy.dfpt.phonons.PhononBandsPlotter file.

write_notebook(nbpath=None)[source]

Write a jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

class abipy.dfpt.phonons.PhbstFile(filepath)[source]

Bases: abipy.core.mixins.AbinitNcFile, abipy.core.mixins.Has_Structure, abipy.core.mixins.Has_PhononBands, abipy.core.mixins.NotebookWriter

Object used to access data stored in the PHBST.nc file produced by ABINIT.

Inheritance Diagram

Inheritance diagram of PhbstFile
to_string(verbose=0)[source]

String representation

Parameters

verbose – verbosity level.

property structure

abipy.core.structure.Structure object

property qpoints

List of q-point objects.

property phbands

abipy.dfpt.phonons.PhononBands object

close()[source]

Close the file.

params()[source]

OrderedDict with parameters that might be subject to convergence studies.

qindex(qpoint)[source]

Returns the index of the qpoint in the PhbstFile. Accepts integer, vector with reduced coordinates or abipy.core.kpoints.Kpoint.

qindex_qpoint(qpoint, is_non_analytical_direction=False)[source]

Returns (qindex, qpoint). Accepts integer, vector with reduced coordinates or abipy.core.kpoints.Kpoint.

get_phframe(qpoint, with_structure=True)[source]

Return a pandas.DataFrame with the phonon frequencies at the given q-point and information on the crystal structure (used for convergence studies).

Parameters
  • qpoint – integer, vector of reduced coordinates or abipy.core.kpoints.Kpoint object.

  • with_structure – True to add structural parameters.

get_phmode(qpoint, branch)[source]

Returns the PhononMode with the given qpoint and branch nu.

Parameters
  • qpoint – Either a vector with the reduced components of the q-point or an integer giving the sequential index (C-convention).

  • branch – branch index (C-convention)

Returns

PhononMode instance.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

write_notebook(nbpath=None)[source]

Write an jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

class abipy.dfpt.phonons.PhononDos(mesh, values)[source]

Bases: abipy.core.func1d.Function1D

This object stores the phonon density of states. An instance of PhononDos has a mesh (numpy array with the points of the mesh) and another numpy array, values, with the DOS on the mesh.

Note

mesh is given in eV, values are in states/eV.

classmethod as_phdos(obj, phdos_kwargs=None)[source]

Return an instance of abipy.dfpt.phonons.PhononDos from a generic obj. Supports:

- instances of cls
- files (string) that can be open with abiopen and that provide one of the following attributes: [`phdos`, `phbands`]
- instances of |PhononBands|.
- objects providing a ``phbands`` attribute.
Parameters
  • phdos_kwargs – optional dictionary with the options passed to get_phdos to compute the phonon DOS.

  • when obj is not already an instance of cls or when we have to compute the DOS from obj. (Used) –

iw0()[source]

Index of the first point in the mesh whose value is >= 0

idos()[source]

Integrated DOS.

zero_point_energy()[source]

Zero point energy in eV per unit cell.

plot_dos_idos(ax, what='d', exchange_xy=False, units='eV', **kwargs)[source]

Helper function to plot DOS/IDOS on the axis ax.

Parameters
  • axmatplotlib.axes.Axes

  • what – string selecting the quantity to plot: “d” for DOS, “i” for IDOS. chars can be concatenated hence what=”id” plots both IDOS and DOS. (default “d”).

  • exchange_xy – True to exchange axis

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • kwargs – Options passed to matplotlib plot method.

Returns

list of lines added to the plot.

plot(units='eV', **kwargs)[source]

Plot Phonon DOS and IDOS on two distict plots.

Parameters
  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • kwargs – Keyword arguments passed to matplotlib.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

get_internal_energy(tstart=5, tstop=300, num=50)[source]

Returns the internal energy, in eV, in the harmonic approximation for different temperatures Zero point energy is included.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num (int) – optional Number of samples to generate. Default is 50.

Return: abipy.core.func1d.Function1D object with U(T) + ZPE.

get_entropy(tstart=5, tstop=300, num=50)[source]

Returns the entropy, in eV/K, in the harmonic approximation for different temperatures

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num (int) – optional Number of samples to generate. Default is 50.

Return: abipy.core.func1d.Function1D object with S(T).

get_free_energy(tstart=5, tstop=300, num=50)[source]

Returns the free energy, in eV, in the harmonic approximation for different temperatures Zero point energy is included.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num (int) – optional Number of samples to generate. Default is 50.

Return: abipy.core.func1d.Function1D object with F(T) = U(T) + ZPE - T x S(T)

get_cv(tstart=5, tstop=300, num=50)[source]

Returns the constant-volume specific heat, in eV/K, in the harmonic approximation for different temperatures

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num (int) – optional Number of samples to generate. Default is 50.

Return: abipy.core.func1d.Function1D object with C_v(T).

plot_harmonic_thermo(tstart=5, tstop=300, num=50, units='eV', formula_units=None, quantities=None, fontsize=8, **kwargs)[source]

Plot thermodynamic properties from the phonon DOSes within the harmonic approximation.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 50.

  • quantities – List of strings specifying the thermodynamic quantities to plot. Possible values: [“internal_energy”, “free_energy”, “entropy”, “c_v”]. None means all.

  • units – eV for energies in ev/unit_cell, Jmol for results in J/mole.

  • formula_units – the number of formula units per unit cell. If unspecified, the thermodynamic quantities will be given on a per-unit-cell basis.

  • fontsize – Legend and title fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

to_pymatgen()[source]

Creates a pymatgen PmgPhononDos object

property debye_temp

Debye temperature in K.

get_acoustic_debye_temp(nsites)[source]

Acoustic Debye temperature in K, i.e. the Debye temperature divided by nsites**(1/3).

Parameters

nsites – the number of sites in the cell.

class abipy.dfpt.phonons.PhononDosPlotter(key_phdos=None, phdos_kwargs=None)[source]

Bases: abipy.core.mixins.NotebookWriter

Class for plotting multiple phonon DOSes.

Usage example:

plotter = PhononDosPlotter()
plotter.add_phdos("foo dos", "foo.nc")
plotter.add_phdos("bar dos", "bar.nc")
plotter.gridplot()
property phdos_list

List of phonon DOSes

add_phdos(label, phdos, phdos_kwargs=None)[source]

Adds a DOS for plotting.

Parameters
  • label – label for the phonon DOS. Must be unique.

  • phdosabipy.dfpt.phonons.PhononDos object.

  • phdos_kwargs – optional dictionary with the options passed to get_phdos to compute the phonon DOS. Used when phdos is not already an instance of cls or when we have to compute the DOS from obj.

combiplot(ax=None, units='eV', xlims=None, ylims=None, fontsize=8, **kwargs)[source]

Plot DOSes on the same figure. Use gridplot to plot DOSes on different figures.

Parameters
  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • xlims – Set the data limits for the x-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • ylims – y-axis limits.

  • fontsize – Legend and title fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot(**kwargs)[source]

An alias for combiplot.

gridplot(units='eV', xlims=None, ylims=None, fontsize=8, **kwargs)[source]

Plot multiple DOSes on a grid.

Parameters
  • units – eV for energies in ev/unit_cell, Jmol for results in J/mole.

  • xlims – Set the data limits for the x-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • fontsize – Legend and title fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_harmonic_thermo(tstart=5, tstop=300, num=50, units='eV', formula_units=1, quantities='all', fontsize=8, **kwargs)[source]

Plot thermodynamic properties from the phonon DOS within the harmonic approximation.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 50.

  • units – eV for energies in ev/unit_cell, Jmol for results in J/mole.

  • formula_units – the number of formula units per unit cell. If unspecified, the thermodynamic quantities will be given on a per-unit-cell basis.

  • quantities – List of strings specifying the thermodynamic quantities to plot. Possible values in [“internal_energy”, “free_energy”, “entropy”, “c_v”].

  • fontsize – Legend and title fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

ipw_select_plot()[source]

Return an ipython widget with controllers to select the plot.

ipw_harmonic_thermo()[source]

Return an ipython widget with controllers to plot thermodynamic properties from the phonon DOS within the harmonic approximation.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

write_notebook(nbpath=None)[source]

Write an jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

class abipy.dfpt.phonons.PhdosReader(path)[source]

Bases: abipy.iotools.ETSF_Reader

This object reads data from the PHDOS.nc file produced by anaddb.

Note

Frequencies are in eV, DOSes are in states/eV.

structure()[source]

abipy.core.structure.Structure object.

wmesh()[source]

The frequency mesh for the PH-DOS in eV.

read_pjdos_type()[source]

[ntypat, nomega] array with Phonon DOS projected over atom types.

read_pjdos_atdir()[source]

Return [natom, three, nomega] array with Phonon DOS projected over atoms and cartesian directions.

read_phdos()[source]

Return abipy.dfpt.phonons.PhononDos object with the total phonon DOS

read_pjdos_symbol_xyz_dict()[source]

Return OrderedDict mapping element symbol –> [3, nomega] array with the the phonon DOSes summed over atom-types and decomposed along the three cartesian directions.

read_pjdos_symbol_dict()[source]

Ordered dictionary mapping element symbol –> abipy.dfpt.phonons.PhononDos where PhononDos is the contribution to the total DOS summed over atoms with chemical symbol symbol.

read_msq_dos()[source]

Read generalized DOS with MSQ displacement tensor in cartesian coords.

Return: abipy.dfpt.msqdos.MsqDos object.

class abipy.dfpt.phonons.PhdosFile(filepath)[source]

Bases: abipy.core.mixins.AbinitNcFile, abipy.core.mixins.Has_Structure, abipy.core.mixins.NotebookWriter

Container object storing the different DOSes stored in the PHDOS.nc file produced by anaddb. Provides helper function to visualize/extract data.

Inheritance Diagram

Inheritance diagram of PhdosFile
close()[source]

Close the file.

params()[source]

OrderedDict with the convergence parameters Used to construct pandas.DataFrame.

to_string(verbose=0)[source]

Human-readable string with useful information such as structure…

Parameters

verbose – Verbosity level.

structure()[source]

abipy.core.structure.Structure object.

phdos()[source]

abipy.dfpt.phonons.PhononDos object.

pjdos_symbol()[source]

Ordered dictionary mapping element symbol –> PhononDos where PhononDos is the contribution to the total DOS summed over atoms with chemical symbol symbol.

msqd_dos()[source]

abipy.dfpt.msqdos.MsqDos object with Mean square displacement tensor in cartesian coords. Allows one to calculate Debye Waller factors by integration with 1/omega and the Bose-Einstein factor.

plot_pjdos_type(units='eV', stacked=True, colormap='jet', alpha=0.7, exchange_xy=False, ax=None, xlims=None, ylims=None, fontsize=12, **kwargs)[source]

Plot type-projected phonon DOS.

Parameters
  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • stacked – True if DOS partial contributions should be stacked on top of each other.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • colormap – Have a look at the colormaps here and decide which one you’d like:

  • alpha – The alpha blending value, between 0 (transparent) and 1 (opaque).

  • exchange_xy – True to exchange x-y axis.

  • xlims – Set the data limits for the x-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used.

  • ylims – y-axis limits.

  • fontsize – legend and title fontsize.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_pjdos_cartdirs_type(units='eV', stacked=True, colormap='jet', alpha=0.7, xlims=None, ylims=None, ax_list=None, fontsize=8, **kwargs)[source]

Plot type-projected phonon DOS decomposed along the three cartesian directions. Three rows for each cartesian direction. Each row shows the contribution of each atomic type + Total Phonon DOS.

Parameters
  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • stacked – True if DOS partial contributions should be stacked on top of each other.

  • colormap

    Have a look at the colormaps here and decide which one you’d like:

  • alpha – The alpha blending value, between 0 (transparent) and 1 (opaque)

  • xlims – Set the data limits for the x-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • ylims – y-axis limits.

  • ax_list – List of matplotlib.axes.Axes or None if a new figure should be created.

  • fontsize – Legend and label fontsize.

Returns: matplotlib.figure.Figure.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_pjdos_cartdirs_site(view='inequivalent', units='eV', stacked=True, colormap='jet', alpha=0.7, xlims=None, ylims=None, ax_list=None, fontsize=8, verbose=0, **kwargs)[source]

Plot phonon PJDOS for each atom in the unit cell. By default, only “inequivalent” atoms are shown.

Parameters
  • view – “inequivalent” to show only inequivalent atoms. “all” for all sites.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • stacked – True if DOS partial contributions should be stacked on top of each other.

  • colormap – matplotlib colormap.

  • alpha – The alpha blending value, between 0 (transparent) and 1 (opaque)

  • xlims – Set the data limits for the x-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used.

  • ylims – Set the data limits for the y-axis. Accept tuple e.g. (left, right) or scalar e.g. left. If left (right) is None, default values are used

  • ax_list – List of matplotlib.axes.Axes or None if a new figure should be created.

  • fontsize – Legend and title fontsize.

  • verbose – Verbosity level.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user. Used in abiview.py to get a quick look at the results.

write_notebook(nbpath=None)[source]

Write a jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.

to_pymatgen()[source]

Creates a pymatgen PmgCompletePhononDos object.

phtk Module

Phonon Toolkit: This module gathers low-level tools to operate on phonons.

abipy.dfpt.phtk.get_dyn_mat_eigenvec(phdispl, structure, amu=None, amu_symbol=None)[source]

Converts the phonon displacements to the orthonormal eigenvectors of the dynamical matrix. Small discrepancies with the original values may be expected due to the different values of the atomic masses in abinit and pymatgen.

Note

These eigenvectors are orthonormalized and should be very close to the ones computed by Abinit in a.u. Note, however, that the output vectors are given in atomic units so dividing then by the sqrt(Mass) won’t give the dipl_cart used in PhononBands that are in Angstrom.

Parameters
  • phdispl – a numpy array containing the displacements in cartesian coordinates. The last index should have size 3*(num atoms), but the rest of the shape is arbitrary. If qpts is not None the first dimension should match the q points.

  • structureabipy.core.structure.Structure object.

  • amu – dictionary that associates the atomic numbers present in the structure to the values of the atomic mass units used for the calculation. Incompatible with amu_sumbol. If None and amu_symbol is None, values from pymatgen will be used. Note that this will almost always lead to inaccuracies in the conversion.

  • amu_symbol – dictionary that associates the symbol present in the structure to the values of the atomic mass units used for the calculation. Incompatible with amu. If None and amu_symbol is None, values from pymatgen will be used. that this will almost always lead to inaccuracies in the conversion.

Returns

A numpy.ndarray of the same shape as phdispl containing the eigenvectors of the dynamical matrix

abipy.dfpt.phtk.match_eigenvectors(v1, v2)[source]

Given two list of vectors, returns the pair matching based on the complex scalar product. Returns the indices of the second list that match the vectors of the first list in ascending order.

class abipy.dfpt.phtk.NonAnalyticalPh(structure, directions, phfreqs, phdispl_cart, amu=None)[source]

Bases: abipy.core.mixins.Has_Structure

Phonon data at gamma including non analytical contributions Read from anaddb.nc

classmethod from_file(filepath)[source]

Reads the non analytical directions, frequencies and displacements from the anaddb.nc file specified. Non existence of displacements is accepted for compatibility with abinit 8.0.6 Raises an error if the other values are not present in anaddb.nc.

dyn_mat_eigenvect()[source]

[ndirection, 3*natom, 3*natom] array with the orthonormal eigenvectors of the dynamical matrix. in Cartesian coordinates.

property structure

abipy.core.structure.Structure object.

index_direction(direction, cartesian=False)[source]

Returns: the index of direction. Raises: ValueError if not found.

Parameters
  • direction – a 3 element list indicating the direction. Can be a generic vector

  • cartesian – if True the direction are already in cartesian coordinates, if False it will be converted to match the internal description of the directions.

has_direction(direction, cartesian=False)[source]

Checks if the input direction is among those available.

Parameters
  • direction – a 3 element list indicating the direction. Can be a generic vector

  • cartesian – if True the direction are already in cartesian coordinates, if False it will be converted to match the internal description of the directions.

abipy.dfpt.phtk.open_file_phononwebsite(filename, port=8000, website='http://henriquemiranda.github.io/phononwebsite', host='localhost', browser=None)[source]

Take a file, detect the type and open it on the phonon website Based on a similar function in <https://github.com/henriquemiranda/phononwebsite/phononweb.py>

Parameters
  • filename – file with phonon data in phononwebsite format.

  • port – Initial port.

  • website – Website URL

  • host – localhost name.

  • browser – Open webpage in browser. Use default if $BROWSER if None.

qha Module

class abipy.dfpt.qha.AbstractQHA(structures, energies, eos_name='vinet', pressure=0)[source]

Bases: object

Abstract class for the quasi-harmonic approximation analysis. Provides some basic methods and plotting utils, plus a converter to write input files for phonopy-qha or to generate an instance of phonopy.qha.QHA. These can be used to obtain other quantities and plots. Does not include electronic entropic contributions for metals.

fit_energies(tstart=0, tstop=800, num=100)[source]

Performs a fit of the energies as a function of the volume at different temperatures.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

Returns

namedtuple with the following attributes:

tot_en: numpy array with shape (nvols, num) with the energies used for the fit
fits: list of subclasses of pymatgen.analysis.eos.EOSBase, depending on the type of
    eos chosen. Contains the fit for the energies at the different temperatures.
min_en: numpy array with the minimum energies for the list of temperatures
min_vol: numpy array with the minimum volumes for the list of temperatures
temp: numpy array with the temperatures considered

abstract get_vib_free_energies(tstart=0, tstop=800, num=100)[source]

Generates the vibrational free energy corresponding to all the structures.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

Returns

A numpy array of num values of the vibrational contribution to the free energy

abstract get_thermodynamic_properties(tstart=0, tstop=800, num=100)[source]

Generates all the thermodynamic properties corresponding to all the volumes.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

Returns

tmesh: numpy array with the list of temperatures. Shape (num). cv: constant-volume specific heat, in eV/K. Shape (nvols, num). free_energy: free energy, in eV. Shape (nvols, num). entropy: entropy, in eV/K. Shape (nvols, num). zpe: zero point energy in eV. Shape (nvols).

Return type

namedtuple with the following attributes for all the volumes

property nvols

Number of volumes

property natoms

Number of atoms in the unit cell.

set_eos(eos_name)[source]

Set the EOS model used for the fit.

Parameters

eos_name – string indicating the expression used to fit the energies. See pymatgen.analysis.eos.EOS.

plot_energies(tstart=0, tstop=800, num=10, ax=None, **kwargs)[source]

Plots the energies as a function of volume at different temperatures.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 10.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

get_thermal_expansion_coeff(tstart=0, tstop=800, num=100)[source]

Calculates the thermal expansion coefficient as a function of temperature, using finite difference on the fitted values of the volume as a function of temperature.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

Returns: abipy.core.func1d.Function1D

plot_thermal_expansion_coeff(tstart=0, tstop=800, num=100, ax=None, **kwargs)[source]

Plots the thermal expansion coefficient as a function of the temperature.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_vol_vs_t(tstart=0, tstop=800, num=100, ax=None, **kwargs)[source]

Plot the volume as a function of the temperature.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_phbs(phbands, temperatures=None, t_max=1000, colormap='plasma', **kwargs)[source]

Given a list of abipy.dfpt.phonons.PhononBands plots the band structures with a color depending on the temperature using a abipy.dfpt.phonons.PhononBandsPlotter. If temperatures are not given they will be deduced inverting the dependence of volume with respect to the temperature. If a unique volume could not be identified an error will be raised.

Parameters
  • phbands – list of abipy.dfpt.phonons.PhononBands objects.

  • temperatures – list of temperatures.

  • t_max – maximum temperature considered for plotting.

  • colormap – matplotlib color map.

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

get_vol_at_t(t)[source]

Calculates the volume corresponding to a specific temperature.

Parameters

t – temperature in K

Returns

The volume

get_t_for_vols(vols, t_max=1000)[source]

Find the temperatures corresponding to a specific volume. The search is performed interpolating the V(T) dependence with a spline and finding the roots with of V(t) - v. It may return more than one temperature for a volume in case of non monotonic behavior.

Parameters
  • vols – list of volumes

  • t_max – maximum temperature considered for the fit

Returns

A list of lists of temperatures. For each volume more than one temperature can be identified.

write_phonopy_qha_inputs(tstart=0, tstop=2100, num=211, path=None)[source]

Writes nvols thermal_properties-i.yaml files that can be used as inputs for phonopy-qha. Notice that phonopy apparently requires the value of the 300 K temperature to be present in the list. Choose the values of tstart, tstop and num to satisfy this condition.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 211.

  • path – a path to a folder where the files will be stored

get_phonopy_qha(tstart=0, tstop=2100, num=211, eos='vinet', t_max=None, energy_plot_factor=None)[source]

Creates an instance of phonopy.qha.QHA that can be used generate further plots and output data. The object is returned right after the construction. The “run()” method should be executed before getting results and plots. Notice that phonopy apparently requires the value of the 300 K temperature to be present in the list. Choose the values of tstart, tstop and num to satisfy this condition.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 211.

  • eos – the expression used to fit the energies in phonopy. Possible values are “vinet”, “murnaghan” and “birch_murnaghan”. Passed to phonopy’s QHA.

  • t_max – maximum temperature. Passed to phonopy’s QHA.

  • energy_plot_factor – factor multiplying the energies. Passed to phonopy’s QHA.

Returns

An instance of phonopy.qha.QHA

class abipy.dfpt.qha.QHA(structures, doses, energies, eos_name='vinet', pressure=0)[source]

Bases: abipy.dfpt.qha.AbstractQHA

Object to extract results in the quasi-harmonic approximation from electronic and phonon calculations at different volumes. Provides some basic methods and plotting utils, plus a converter to write input files for phonopy-qha or to generate an instance of phonopy.qha.QHA. These can be used to obtain other quantities and plots. Does not include electronic entropic contributions for metals.

Inheritance Diagram

Inheritance diagram of QHA
classmethod from_files(gsr_paths, phdos_paths)[source]

Creates an instance of QHA from a list of GSR files and a list of PHDOS.nc files. The list should have the same size and the volumes should match.

Parameters
  • gsr_paths – list of paths to GSR files.

  • phdos_paths – list of paths to PHDOS.nc files.

Returns: A new instance of QHA

get_vib_free_energies(tstart=0, tstop=800, num=100)[source]

Generates the vibrational free energy from the phonon DOS.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

Returns

A numpy array of num values of the vibrational contribution to the free energy

get_thermodynamic_properties(tstart=0, tstop=800, num=100)[source]

Generates all the thermodynamic properties corresponding to all the volumes using the phonon DOS.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

Returns

tmesh: numpy array with the list of temperatures. Shape (num). cv: constant-volume specific heat, in eV/K. Shape (nvols, num). free_energy: free energy, in eV. Shape (nvols, num). entropy: entropy, in eV/K. Shape (nvols, num). zpe: zero point energy in eV. Shape (nvols).

Return type

namedtuple with the following attributes for all the volumes

class abipy.dfpt.qha.QHA3PF(structures, doses, energies, ind_doses, eos_name='vinet', pressure=0, fit_degree=2)[source]

Bases: abipy.dfpt.qha.AbstractQHA

Object to extract results in the quasi-harmonic approximation from several electronic energies at different volumes and three phonon calculations. Provides some basic methods and plotting utils, plus a converter to write input files for phonopy-qha or to generate an instance of phonopy.qha.QHA. These can be used to obtain other quantities and plots. Does not include electronic entropic contributions for metals.

Inheritance Diagram

Inheritance diagram of QHA3PF
classmethod from_files(gsr_paths, phdos_paths, ind_doses)[source]

Creates an instance of QHA from a list of GSR files and a list of PHDOS.nc files. The list should have the same size and the volumes should match.

Parameters
  • gsr_paths – list of paths to GSR files.

  • phdos_paths – list of paths to three PHDOS.nc files.

  • ind_doses – list of three values indicating, for each of the three doses, the index of the corresponding gsr_file in “gsr_paths”.

Returns: A new instance of QHA

get_thermodynamic_properties(tstart=0, tstop=800, num=100)[source]

Generates all the thermodynamic properties corresponding to all the volumes using the phonon DOS.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

Returns

tmesh: numpy array with the list of temperatures. Shape (num). cv: constant-volume specific heat, in eV/K. Shape (nvols, num). free_energy: free energy, in eV. Shape (nvols, num). entropy: entropy, in eV/K. Shape (nvols, num). zpe: zero point energy in eV. Shape (nvols).

Return type

namedtuple with the following attributes for all the volumes

get_vib_free_energies(tstart=0, tstop=800, num=100)[source]

Generates the vibrational free energy corresponding to all the structures, either from the phonon DOS or from a fit of the known values.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

Returns

A numpy array of num values of the vibrational contribution to the free energy

class abipy.dfpt.qha.QHA3P(structures, gruns, energies, ind_grun, eos_name='vinet', pressure=0)[source]

Bases: abipy.dfpt.qha.AbstractQHA

Object to extract results in the quasi-harmonic approximation from several electronic energies at different volumes and three phonon calculations. Provides some basic methods and plotting utils, plus a converter to write input files for phonopy-qha or to generate an instance of phonopy.qha.QHA. These can be used to obtain other quantities and plots. Does not include electronic entropic contributions for metals.

Inheritance Diagram

Inheritance diagram of QHA3P
classmethod from_files(gsr_paths, grun_file_path, ind_doses)[source]

Creates an instance of QHA from a list of GSR files and a list PHDOS.nc files. The list should have the same size and the volumes should match.

Parameters
  • gsr_paths – list of paths to GSR files.

  • phdos_paths – list of paths to three PHDOS.nc files.

  • ind_doses – list of three values indicating, for each of the three doses, the index of the corresponding gsr_file in “gsr_paths”.

Returns

A new instance of QHA

close()[source]

Close files.

get_thermodynamic_properties(tstart=0, tstop=800, num=100)[source]

Generates the thermodynamic properties corresponding to all the structures, either from the phonon frequencies or from a fit of the know values.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

Returns

tmesh: numpy array with the list of temperatures. Shape (num). cv: constant-volume specific heat, in eV/K. Shape (nvols, num). free_energy: free energy, in eV. Shape (nvols, num). entropy: entropy, in eV/K. Shape (nvols, num). zpe: zero point energy in eV. Shape (nvols).

Return type

namedtuple with the following attributes for all the volumes

fitted_frequencies()[source]

A numpy array with size (nvols, nqpts_ibz, 3*natoms) containing the phonon frequencies for all the volumes, either from the original phonon calculations or fitted

get_vib_free_energies(tstart=0, tstop=800, num=100)[source]

Generates the vibrational free energy corresponding to all the structures, either from the phonon DOS or from a fit of the know values.

Parameters
  • tstart – The starting value (in Kelvin) of the temperature mesh.

  • tstop – The end value (in Kelvin) of the mesh.

  • num – int, optional Number of samples to generate. Default is 100.

Returns

A numpy array of num values of the vibrational contribution to the free energy

abipy.dfpt.qha.get_free_energy(w, weights, t)[source]

Calculates the free energy in eV from the phonon frequencies on a regular grid.

Parameters
  • w – the phonon frequencies

  • weights – the weights of the q-points

  • t – the temperature

abipy.dfpt.qha.get_cv(w, weights, t)[source]

Calculates the constant-volume specific heat in eV/K from the phonon frequencies on a regular grid.

Parameters
  • w – the phonon frequencies

  • weights – the weights of the q-points

  • t – the temperature

abipy.dfpt.qha.get_zero_point_energy(w, weights)[source]

Calculates the zero point energy in eV from the phonon frequencies on a regular grid.

Parameters
  • w – the phonon frequencies

  • weights – the weights of the q-points

abipy.dfpt.qha.get_entropy(w, weights, t)[source]

Calculates the entropy in eV/K from the phonon frequencies on a regular grid.

Parameters
  • w – the phonon frequencies

  • weights – the weights of the q-points

  • t – the temperature

class abipy.dfpt.qha.AbstractQmeshAnalyzer[source]

Bases: object

Abstract class for the analysis of the convergence wrt to the q-mesh used to compute the phonon DOS. Relies on abstract methods implemented in AbstractQHA.

fontsize = 8
colormap = 'viridis'
set_eos(eos_name)[source]

Set the EOS model used for the fit.

Parameters

eos_name – string indicating the expression used to fit the energies. See pymatgen.analysis.eos.EOS.

plot_energies(**kwargs)[source]

Plots the energies as a function of volume at different temperatures. kwargs are propagated to the analogous method of QHA.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_thermal_expansion_coeff(**kwargs)[source]

Plots the thermal expansion coefficient as a function of the temperature. kwargs are propagated to the analogous method of QHA.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot_vol_vs_t(**kwargs)[source]

Plot the volume as a function of the temperature. kwargs are propagated to the analogous method of QHA.

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

class abipy.dfpt.qha.QHAQmeshAnalyzer(gsr_paths, ddb_paths)[source]

Bases: abipy.dfpt.qha.AbstractQmeshAnalyzer

run_qlist(nqsmall_list, **kwargs)[source]

raman Module

class abipy.dfpt.raman.PowderIntensity(paral, perp, tot)

Bases: tuple

paral

Alias for field number 0

perp

Alias for field number 1

tot

Alias for field number 2

class abipy.dfpt.raman.Raman(susceptibility, phfreqs, non_anal_susceptibility=None, non_anal_phfreqs=None, non_anal_directions=None)[source]

Bases: object

An object that allows to obtain the Raman intensities based on the calculated susceptibilities. The expressions used to extract the different values of the Raman intensities can be found for example in PRB 71, 214307, Physics of the Earth and Planetary Interiors 174, 113 or PRB 71, 125107.

classmethod from_file(filepath)[source]

Create the object from an anaddb.nc netcdf file.

Parameters

filepath – path to the netcdf file.

Returns

An instance of Raman.

get_modes_intensities(temp, laser_freq, non_anal_dir=None, relative=False, units='eV', pol_in=None, pol_out=None)[source]

Calculates the Raman intensities for each mode in arbitrary units. It is possible to use the susceptibilities from the transverse modes only or to specify one of the directions with non analytical contributions. By default it returns an array with shape (n modes, 3, 3) where each component of the 3x3 matrix are those with different incoming (the first index) and outgoing (the second index) polarization. These are along the components along the standard axes (e.g. “xx” or “yz” components). If pol_in and pol_out an array with shape (n modes) is returned corresponding to the selected polarizations.

Parameters
  • temp – temperature in K.

  • laser_freq – frequency of the incident laser. The units are determined the “units” argument.

  • non_anal_dir – index of the direction along which the non analytical contribution has been calculated. Corresponds to the indices in the non_anal_directions attribute.

  • relative – if True the intensities will be rescaled so that the largest value is 1.

  • units – the units in which the input and the output frequencies will be given. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”)

  • pol_in – the polarization of the incoming photon. If not None can be either either a string with one of the cartesian components i.e. “x”, “y”, “z” or an array with 3 elements representing the polarization direction. If not None pol_out can not be None.

  • pol_out – the polarization of the outgoing photon. If not None can be either either a string with one of the cartesian components i.e. “x”, “y”, “z” or an array with 3 elements representing the polarization direction. If not None pol_in can not be None.

Returns

An array with the Raman intensities. If pol_in==pol_out==None has shape (n modes, 3, 3) with all the components. Otherwise an array with size (n modes) with the intensities of the selected polarizations.

get_lorentz_intensity(temp, laser_freq, width, non_anal_dir=None, min_freq=None, max_freq=None, num=1000, relative=False, units='eV', pol_in=None, pol_out=None)[source]

Calculates the broadened Raman intensities in arbitrary units for frequencies in an interval. It is possible to use the susceptibilities from the transverse modes only or to specify one of the directions with non analytical contributions. By default it returns a 3x3 matrix where each component is a Function1D object with the Raman intensities with different incoming (the first index) and outgoing (the second index) polarization. These are along the components along the standard axes (e.g. “xx” or “yz” components). If pol_in and pol_out a single Function1D is returned corresponding to the selected polarizations.

Parameters
  • temp – temperature in K.

  • laser_freq – frequency of the incident laser. The units are determined the “units” argument.

  • width – the width of the Lorentz distribution. The units are determined the “units” argument.

  • non_anal_dir – index of the direction along which the non analytical contribution has been calculated. Corresponds to the indices in the non_anal_directions attribute.

  • min_freq – minimum frequency considered. If None it will be given by the minimum frequency with non zero intensities minus 10 times the width of the distribution. If given the units are determined by the “units” argument.

  • max_freq – maximum frequency considered. If None it will be given by the maximum frequency with non zero intensities plus 10 times the width of the distribution. If given the units are determined by the “units” argument.

  • num – number of frequencies in the interval (min_freq, max_freq).

  • relative – if True the intensities will be rescaled so that the largest value is 1.

  • units – the units in which the input and the output frequencies will be given. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”)

  • pol_in – the polarization of the incoming photon. If not None can be either either a string with one of the cartesian components i.e. “x”, “y”, “z” or an array with 3 elements representing the polarization direction. If not None pol_out can not be None.

  • pol_out – the polarization of the outgoing photon. If not None can be either either a string with one of the cartesian components i.e. “x”, “y”, “z” or an array with 3 elements representing the polarization direction. If not None pol_in can not be None.

Returns

If pol_in==pol_out==None a 3x3 list with a Function1D corresponding to the different components of the intensities. Otherwise a single Function1D with the intensities of the selected polarizations. Each Function1D has “num” points.

get_powder_intensity(temp, laser_freq, non_anal_dir=None, relative=False, units='eV')[source]

Calculates the Raman intensities in arbitrary units for each mode integrated over all possible orientation to reproduce the powder measurements. It is possible to use the susceptibilities from transverse modes only or to specify one of the directions with non analytical contributions.

Parameters
  • temp – temperature in K.

  • laser_freq – frequency of the incident laser. The units are determined the “units” argument.

  • non_anal_dir – index of the direction along which the non analytical contribution has been calculated. Corresponds to the indices in the non_anal_directions attribute.

  • relative – if True the intensities will be rescaled so that the largest value of the total intensity is 1.

  • units – the units in which the input and the output frequencies will be given. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”)

Returns

A PowderIntensity with the parallel, perpendicular and total components of the powder intensities. Each one is an array with length n modes.

get_powder_lorentz_intensity(temp, laser_freq, width, non_anal_dir=None, min_freq=None, max_freq=None, num=1000, relative=False, units='eV')[source]

Calculates the broadened Raman intensities in arbitrary units integrated over all possible orientation to reproduce the powder measurements for frequencies in an interval. It is possible to use the susceptibilities from the transverse modes only or to specify one of the directions with non analytical contributions.

Parameters
  • temp – temperature in K.

  • laser_freq – frequency of the incident laser. The units are determined the “units” argument.

  • width – the width of the Lorentz distribution. The units are determined the “units” argument.

  • non_anal_dir – index of the direction along which the non analytical contribution has been calculated. Corresponds to the indices in the non_anal_directions attribute.

  • min_freq – minimum frequency considered. If None it will be given by the minimum frequency with non zero intensities minus 10 times the width of the distribution. If given the units are determined by the “units” argument.

  • max_freq – maximum frequency considered. If None it will be given by the maximum frequency with non zero intensities plus 10 times the width of the distribution. If given the units are determined by the “units” argument.

  • num – number of frequencies in the interval (min_freq, max_freq).

  • relative – if True the intensities will be rescaled so that the largest value of the total intensity is 1.

  • units – the units in which the input and the output frequencies will be given. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”)

Returns

A PowderIntensity with the parallel, perpendicular and total components of the powder intensities. Each one is a Function1D with “num” points.

plot_intensity(temp, laser_freq, width, value, non_anal_dir=None, min_freq=None, max_freq=None, num=1000, relative=False, units='eV', ax=None, plot_phfreqs=False, **kwargs)[source]

Plot one representation of the broadened Raman intensities.

Parameters
  • temp – temperature in K.

  • laser_freq – frequency of the incident laser. The units are determined the “units” argument.

  • width – the width of the Lorentz distribution. The units are determined the “units” argument. If None or 0 a plot of only the frequencies for each mode will be given.

  • value – a string describing the value that should be plotted. Can be “powder” or a string of the type “xz” with the polarization of the incoming and outgoing phonon. All the combinations of “x”, “y” and “z” are accepted.

  • non_anal_dir – index of the direction along which the non analytical contribution has been calculated. Corresponds to the indices in the non_anal_directions attribute.

  • min_freq – minimum frequency considered. If None it will be given by the minimum frequency with non zero intensities minus 10 times the width of the distribution. If given the units are determined by the “units” argument.

  • max_freq – maximum frequency considered. If None it will be given by the maximum frequency with non zero intensities plus 10 times the width of the distribution. If given the units are determined by the “units” argument.

  • num – number of frequencies in the interval (min_freq, max_freq).

  • relative – if True the intensities will be rescaled so that the largest value of the total intensity is 1.

  • units – the units in which the input and the output frequencies will be given. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”)

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • plot_phfreqs – if True vertical dashed lines are added to the figure for all the phonon modes.

  • **kwargs – arguments passed to the plot function.

Returns

matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

vsound Module

Tools to compute speed of sound.

class abipy.dfpt.vsound.SoundVelocity(directions, sound_velocities, mode_types, structure, labels=None, phfreqs=None, qpts=None)[source]

Bases: abipy.core.mixins.Has_Structure, abipy.core.mixins.NotebookWriter

Compute the speed of sound by fitting phonon frequencies along selected directions by linear least-squares fit.

property structure

abipy.core.structure.Structure object

property n_directions

Number of directions.

classmethod from_ddb(ddb_path, directions=None, labels=None, num_points=20, qpt_norm=0.1, ignore_neg_freqs=True, asr=2, chneut=1, dipdip=1, ngqpt=None, spell_check=True, anaddb_kwargs=None, verbose=0, mpi_procs=1, workdir=None, manager=None)[source]

Creates and instance of the object. Runs anaddb along the specified directions or the standard directions in the standard paths given in [Setyawan2010]. The values of the speed of sound will be calculated as the slope of the linear fits along each direction.

Parameters
  • ddb_path (str) – path to the ddb file.

  • directions (list) – list of qpoints identifying the directions for the calculation of the speed of sound. In fractional coordinates.

  • labels (list) – list of string with the name of the directions.

  • num_points (int) – number of points calculated along each direction and used to fit the speed of sound.

  • qpt_norm (float) – Norm of the largest point in fractional coordinates for each of the directions considered.

  • ignore_neg_freqs (bool) – if True points with negative frequencies will not be considered in the fit, in order to ignore inaccuracies in the long range behavior.

  • asr – Anaddb input variable. See official documentation.

  • chneut – Anaddb input variable. See official documentation.

  • dipdip – Anaddb input variable. See official documentation.

  • ngqpt – Number of divisions for the q-mesh in the DDB file. Auto-detected if None (default).

  • anaddb_kwargs – additional kwargs for anaddb.

  • verbose – verbosity level. Set it to a value > 0 to get more information.

  • mpi_procs – Number of MPI processes to use.

  • workdir – Working directory. If None, a temporary directory is created.

  • managerabipy.flowtk.tasks.TaskManager object. If None, the object is initialized from the configuration file.

Returns: an instance of SoundVelocity

classmethod from_phbst(phbst_path, ignore_neg_freqs=True, labels=None)[source]

Creates an instance of the object starting interpolating the acoustic frequencies from a PHBST netcdf file. The file should contain a series of directions starting from gamma and with the same number of points for each direction, as the one produced in the from_ddb method.

Parameters
  • phbst_path – path to the PHBST netcdf file.

  • ignore_neg_freqs (bool) – if True points with negative frequencies will not be considered in the fit, in order to ignore inaccuracies in the long range behavior.

  • labels (list) – list of string with the name of the directions.

Returns: an instance of SoundVelocity

get_dataframe()[source]

Return a pandas.DataFrame with the data of the speed of sound.

plot_fit_freqs_dir(idir, ax=None, units='eV', fontsize=8, **kwargs)[source]

Plots the phonon frequencies, if available, along the specified direction. The line representing the fitted value will be shown as well.

Parameters
  • idir – index of the direction.

  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • fontsize – fontsize for legends and titles

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

plot(units='eV', fontsize=8, **kwargs)[source]

Plots the phonon frequencies, if available, along all the directions. The lines representing the fitted values will be shown as well.

Parameters
  • axmatplotlib.axes.Axes or None if a new figure should be created.

  • units – Units for phonon plots. Possible values in (“eV”, “meV”, “Ha”, “cm-1”, “Thz”). Case-insensitive.

  • fontsize – fontsize for legends and titles

Returns: matplotlib.figure.Figure

Keyword arguments controlling the display of the figure:

kwargs

Meaning

title

Title of the plot (Default: None).

show

True to show the figure (default: True).

savefig

“abc.png” or “abc.eps” to save the figure to a file.

size_kwargs

Dictionary with options passed to fig.set_size_inches e.g. size_kwargs=dict(w=3, h=4)

tight_layout

True to call fig.tight_layout (default: False)

ax_grid

True (False) to add (remove) grid from all axes in fig. Default: None i.e. fig is left unchanged.

ax_annotate

Add labels to subplots e.g. (a), (b). Default: False

fig_close

Close figure. Default: False.

yield_figs(**kwargs)[source]

This function generates a predefined list of matplotlib figures with minimal input from the user.

write_notebook(nbpath=None)[source]

Write an jupyter notebook to nbpath. If nbpath is None, a temporay file in the current working directory is created. Return path to the notebook.