# pymatgen.io.vasp.outputs module¶

Classes for reading/manipulating/writing VASP ouput files.

class BSVasprun(filename, parse_projected_eigen=False, parse_potcar_file=False, occu_tol=1e-08)[source]

A highly optimized version of Vasprun that parses only eigenvalues for bandstructures. All other properties like structures, parameters, etc. are ignored.

Parameters
• filename (str) – Filename to parse

• parse_projected_eigen (bool) – Whether to parse the projected eigenvalues. Defaults to False. Set to True to obtain projected eigenvalues. Note that this can take an extreme amount of time and memory. So use this wisely.

• parse_potcar_file (bool/str) –

Whether to parse the potcar file to read the potcar hashes for the potcar_spec attribute. Defaults to True, where no hashes will be determined and the potcar_spec dictionaries will read {“symbol”: ElSymbol, “hash”: None}. By Default, looks in the same directory as the vasprun.xml, with same extensions as

Vasprun.xml. If a string is provided, looks at that filepath.

• occu_tol (float) – Sets the minimum tol for the determination of the vbm and cbm. Usually the default of 1e-8 works well enough, but there may be pathological cases.

as_dict()[source]

Json-serializable dict representation.

class Chgcar(poscar, data, data_aug=None)[source]

Simple object for reading a CHGCAR file.

Parameters
• poscar (Poscar) – Poscar object containing structure.

• data – Actual data.

static from_file(filename)[source]

Parameters

filename – Filename

Returns

Chgcar

property net_magnetization[source]

Net magnetization from Chgcar

Type

return

class Dynmat(filename)[source]

Bases: object

Object for reading a DYNMAT file.

data[source]

A nested dict containing the DYNMAT data of the form:: [atom <int>][disp <int>][‘dispvec’] =

displacement vector (part of first line in dynmat block, e.g. “0.01 0 0”)

[atom <int>][disp <int>][‘dynmat’] =

<list> list of dynmat lines for this atom and this displacement

Authors: Patrick Huck

Parameters

filename – Name of file containing DYNMAT

get_phonon_frequencies()[source]

calculate phonon frequencies

property masses[source]

returns the list of atomic masses

property natoms[source]

returns the number of atoms

property ndisps[source]

returns the number of displacements

property nspecs[source]

returns the number of species

class Eigenval(filename, occu_tol=1e-08)[source]

Bases: object

filename[source]

string containing input filename

occu_tol[source]

tolerance for determining occupation in band properties

ispin[source]

spin polarization tag (int)

nelect[source]

number of electrons

nkpt[source]

number of kpoints

nbands[source]

number of bands

kpoints[source]

list of kpoints

kpoints_weights[source]

weights of each kpoint in the BZ, should sum to 1.

eigenvalues[source]

Eigenvalues as a dict of {(spin): np.ndarray(shape=(nkpt, nbands, 2))}. This representation is based on actual ordering in VASP and is meant as an intermediate representation to be converted into proper objects. The kpoint index is 0-based (unlike the 1-based indexing in VASP).

Reads input from filename to construct Eigenval object

Parameters
• filename (str) – filename of EIGENVAL to read in

• occu_tol (float) – tolerance for determining band gap

Returns

a pymatgen.io.vasp.outputs.Eigenval object

property eigenvalue_band_properties[source]

Band properties from the eigenvalues as a tuple, (band gap, cbm, vbm, is_band_gap_direct).

class Elfcar(poscar, data)[source]

Read an ELFCAR file which contains the Electron Localization Function (ELF) as calculated by VASP.

For ELF, “total” key refers to Spin.up, and “diff” refers to Spin.down.

This also contains information on the kinetic energy density.

Parameters
• poscar (Poscar) – Poscar object containing structure.

• data – Actual data.

classmethod from_file(filename)[source]

Parameters

filename – Filename

Returns

Elfcar

get_alpha()[source]

Get the parameter alpha where ELF = 1/(1+alpha^2).

class Locpot(poscar, data)[source]

Simple object for reading a LOCPOT file.

Parameters
• poscar (Poscar) – Poscar object containing structure.

• data – Actual data.

static from_file(filename)[source]

Parameters

filename – Filename

Returns

Locpot

class Oszicar(filename)[source]

Bases: object

A basic parser for an OSZICAR output from VASP. In general, while the OSZICAR is useful for a quick look at the output from a VASP run, we recommend that you use the Vasprun parser instead, which gives far richer information about a run.

electronic_steps[source]

All electronic steps as a list of list of dict. e.g., [[{“rms”: 160.0, “E”: 4507.24605593, “dE”: 4507.2, “N”: 1, “deps”: -17777.0, “ncg”: 16576}, …], [….] where electronic_steps[index] refers the list of electronic steps in one ionic_step, electronic_steps[index][subindex] refers to a particular electronic step at subindex in ionic step at index. The dict of properties depends on the type of VASP run, but in general, “E”, “dE” and “rms” should be present in almost all runs.

ionic_steps:

All ionic_steps as a list of dict, e.g., [{“dE”: -526.36, “E0”: -526.36024, “mag”: 0.0, “F”: -526.36024}, …] This is the typical output from VASP at the end of each ionic step.

Parameters

filename (str) – Filename of file to parse

property all_energies[source]

Compilation of all energies from all electronic steps and ionic steps as a tuple of list of energies, e.g., ((4507.24605593, 143.824705755, -512.073149912, …), …)

as_dict()[source]
Returns

MSONable dict

property final_energy[source]
class Outcar(filename)[source]

Bases: object

Parser for data in OUTCAR that is not available in Vasprun.xml

Note, this class works a bit differently than most of the other VaspObjects, since the OUTCAR can be very different depending on which “type of run” performed.

Creating the OUTCAR class with a filename reads “regular parameters” that are always present.

magnetization[source]

Magnetization on each ion as a tuple of dict, e.g., ({“d”: 0.0, “p”: 0.003, “s”: 0.002, “tot”: 0.005}, … ) Note that this data is not always present. LORBIT must be set to some other value than the default.

chemical_shielding[source]

chemical shielding on each ion as a dictionary with core and valence contributions

unsym_cs_tensor[source]

Unsymmetrized chemical shielding tensor matrixes on each ion as a list. e.g., [[[sigma11, sigma12, sigma13],

[sigma21, sigma22, sigma23], [sigma31, sigma32, sigma33]], …

[[sigma11, sigma12, sigma13],

[sigma21, sigma22, sigma23], [sigma31, sigma32, sigma33]]]

cs_g0_contribution[source]

G=0 contribution to chemical shielding. 2D rank 3 matrix

cs_core_contribution[source]

Core contribution to chemical shielding. dict. e.g., {‘Mg’: -412.8, ‘C’: -200.5, ‘O’: -271.1}

efg[source]

Electric Field Gradient (EFG) tensor on each ion as a tuple of dict, e.g., ({“cq”: 0.1, “eta”, 0.2, “nuclear_quadrupole_moment”: 0.3},

{“cq”: 0.7, “eta”, 0.8, “nuclear_quadrupole_moment”: 0.9}, …)

charge[source]

Charge on each ion as a tuple of dict, e.g., ({“p”: 0.154, “s”: 0.078, “d”: 0.0, “tot”: 0.232}, …) Note that this data is not always present. LORBIT must be set to some other value than the default.

is_stopped[source]

True if OUTCAR is from a stopped run (using STOPCAR, see Vasp Manual).

run_stats[source]

Various useful run stats as a dict including “System time (sec)”, “Total CPU time used (sec)”, “Elapsed time (sec)”, “Maximum memory used (kb)”, “Average memory used (kb)”, “User time (sec)”.

elastic_tensor[source]
Total elastic moduli (Kbar) is given in a 6x6 array matrix.
drift[source]
Total drift for each step in eV/Atom
ngf[source]
Dimensions for the Augementation grid
..attribute: final_energy_contribs

Individual contributions to the total final energy as a dictionary. Include contirbutions from keys, e.g.: {‘DENC’: -505778.5184347, ‘EATOM’: 15561.06492564, ‘EBANDS’: -804.53201231, ‘EENTRO’: -0.08932659, ‘EXHF’: 0.0, ‘Ediel_sol’: 0.0, ‘PAW double counting’: 664.6726974100002, ‘PSCENC’: 742.48691646, ‘TEWEN’: 489742.86847338, ‘XCENC’: -169.64189814}

See the documentation of those methods for more documentation.

Authors: Rickard Armiento, Shyue Ping Ong

Parameters

filename (str) – OUTCAR filename to parse.

as_dict()[source]
Returns

MSONAble dict.

property frequencies[source]
read_avg_core_poten()[source]

Read the core potential at each ionic step.

Returns

A list for each ionic step containing a list of the average core potentials for each atom: [[avg core pot]].

Example

The average core potential of the 2nd atom of the structure at the last ionic step is: [-1][1]

read_chemical_shielding()[source]

Parse the NMR chemical shieldings data. Only the second part “absolute, valence and core” will be parsed. And only the three right most field (ISO_SHIELDING, SPAN, SKEW) will be retrieved.

Returns

List of chemical shieldings in the order of atoms from the OUTCAR. Maryland notation is adopted.

read_core_state_eigen()[source]

Read the core state eigenenergies at each ionic step.

Returns

[core state eig]}]. The core state eigenenergie list for each AO is over all ionic step.

Return type

A list of dict over the atom such as [{“AO”

Example

The core state eigenenergie of the 2s AO of the 6th atom of the structure at the last ionic step is [5][“2s”][-1]

read_corrections(reverse=True, terminate_on_match=True)[source]

Parameters
• reverse – Whether to start from end of OUTCAR.

• terminate_on_match – Whether to terminate once match is found.

read_cs_core_contribution()[source]

Parse the core contribution of NMR chemical shielding.

Returns: G0 contribution matrix as list of list.

read_cs_g0_contribution()[source]

Parse the G0 contribution of NMR chemical shielding.

Returns

G0 contribution matrix as list of list.

read_cs_raw_symmetrized_tensors()[source]

Parse the matrix form of NMR tensor before corrected to table.

Returns

nsymmetrized tensors list in the order of atoms.

read_elastic_tensor()[source]

Parse the elastic tensor data.

Returns

6x6 array corresponding to the elastic tensor from the OUTCAR.

read_electrostatic_potential()[source]

Parses the eletrostatic potential for the last ionic step

read_fermi_contact_shift()[source]

output example: Fermi contact (isotropic) hyperfine coupling parameter (MHz) ————————————————————- ion A_pw A_1PS A_1AE A_1c A_tot ————————————————————-

1 -0.002 -0.002 -0.051 0.000 -0.052 2 -0.002 -0.002 -0.051 0.000 -0.052 3 0.056 0.056 0.321 -0.048 0.321

, which corresponds to [[-0.002, -0.002, -0.051, 0.0, -0.052],

[-0.002, -0.002, -0.051, 0.0, -0.052], [0.056, 0.056, 0.321, -0.048, 0.321]] from ‘fch’ data

read_freq_dielectric()[source]

Parses the frequency dependent dielectric function (obtained with LOPTICS). Frequencies (in eV) are in self.frequencies, and dielectric tensor function is given as self.dielectric_tensor_function.

read_igpar()[source]
Renders accessible:

er_ev = e<r>_ev (dictionary with Spin.up/Spin.down as keys) er_bp = e<r>_bp (dictionary with Spin.up/Spin.down as keys) er_ev_tot = spin up + spin down summed er_bp_tot = spin up + spin down summed p_elc = spin up + spin down summed p_ion = spin up + spin down summed

(See VASP section “LBERRY, IGPAR, NPPSTR, DIPOL tags” for info on what these are).

read_internal_strain_tensor()[source]
Reads the internal strain tensor and populates self.internal_strain_tensor with an array of voigt notation

tensors for each site.

read_lcalcpol()[source]

# TODO: Document the actual variables.

read_lepsilon()[source]

# TODO: Document the actual variables.

read_lepsilon_ionic()[source]

Reads an LEPSILON run, the ionic component.

# TODO: Document the actual variables.

read_neb(reverse=True, terminate_on_match=True)[source]

Reads NEB data. This only works with OUTCARs from both normal VASP NEB calculations or from the CI NEB method implemented by Henkelman et al.

Parameters
• reverse (bool) – Read files in reverse. Defaults to false. Useful for large files, esp OUTCARs, especially when used with terminate_on_match. Defaults to True here since we usually want only the final value.

• terminate_on_match (bool) – Whether to terminate when there is at least one match in each key in pattern. Defaults to True here since we usually want only the final value.

Renders accessible:

tangent_force - Final tangent force. energy - Final energy. These can be accessed under Outcar.data[key]

read_nmr_efg()[source]

Parse the NMR Electric Field Gradient interpretted values.

Returns

Electric Field Gradient tensors as a list of dict in the order of atoms from OUTCAR. Each dict key/value pair corresponds to a component of the tensors.

read_nmr_efg_tensor()[source]

Parses the NMR Electric Field Gradient Raw Tensors

Returns

A list of Electric Field Gradient Tensors in the order of Atoms from OUTCAR

read_onsite_density_matrices()[source]

Parse the onsite density matrices, returns list with index corresponding to atom index in Structure.

read_pattern(patterns, reverse=False, terminate_on_match=False, postprocess=<class 'str'>)[source]

General pattern reading. Uses monty’s regrep method. Takes the same arguments.

Parameters
• patterns (dict) – A dict of patterns, e.g., {“energy”: r”energy$$sigma->0$$\s+=\s+([\d-.]+)”}.

• reverse (bool) – Read files in reverse. Defaults to false. Useful for large files, esp OUTCARs, especially when used with terminate_on_match.

• terminate_on_match (bool) – Whether to terminate when there is at least one match in each key in pattern.

• postprocess (callable) – A post processing function to convert all matches. Defaults to str, i.e., no change.

Renders accessible:

Any attribute in patterns. For example, {“energy”: r”energy$$sigma->0$$\s+=\s+([\d-.]+)”} will set the value of self.data[“energy”] = [[-1234], [-3453], …], to the results from regex and postprocess. Note that the returned values are lists of lists, because you can grep multiple items on one line.

read_piezo_tensor()[source]

Parse the piezo tensor data

read_pseudo_zval()[source]

Create pseudopotential ZVAL dictionary.

read_table_pattern(header_pattern, row_pattern, footer_pattern, postprocess=<class 'str'>, attribute_name=None, last_one_only=True)[source]

Parse table-like data. A table composes of three parts: header, main body, footer. All the data matches “row pattern” in the main body will be returned.

Parameters
• header_pattern (str) – The regular expression pattern matches the table header. This pattern should match all the text immediately before the main body of the table. For multiple sections table match the text until the section of interest. MULTILINE and DOTALL options are enforced, as a result, the “.” meta-character will also match “n” in this section.

• row_pattern (str) – The regular expression matches a single line in the table. Capture interested field using regular expression groups.

• footer_pattern (str) – The regular expression matches the end of the table. E.g. a long dash line.

• postprocess (callable) – A post processing function to convert all matches. Defaults to str, i.e., no change.

• attribute_name (str) – Name of this table. If present the parsed data will be attached to “data. e.g. self.data[“efg”] = […]

• last_one_only (bool) – All the tables will be parsed, if this option is set to True, only the last table will be returned. The enclosing list will be removed. i.e. Only a single table will be returned. Default to be True.

Returns

List of tables. 1) A table is a list of rows. 2) A row if either a list of attribute values in case the the capturing group is defined without name in row_pattern, or a dict in case that named capturing groups are defined by row_pattern.

class Procar(filename)[source]

Bases: object

Object for reading a PROCAR file.

data[source]

The PROCAR data of the form below. It should VASP uses 1-based indexing, but all indices are converted to 0-based here.:

{
spin: nd.array accessed with (k-point index, band index,
ion index, orbital index)
}

weights[source]

The weights associated with each k-point as an nd.array of lenght nkpoints.

..attribute:: phase_factors

Phase factors, where present (e.g. LORBIT = 12). A dict of the form: {

spin: complex nd.array accessed with (k-point index, band index,

ion index, orbital index)

}

..attribute:: nbands

Number of bands

..attribute:: nkpoints

Number of k-points

..attribute:: nions

Number of ions

Parameters

filename – Name of file containing PROCAR.

get_occupation(atom_index, orbital)[source]

Returns the occupation for a particular orbital of a particular atom.

Parameters
• atom_num (int) – Index of atom in the PROCAR. It should be noted that VASP uses 1-based indexing for atoms, but this is converted to 0-based indexing in this parser to be consistent with representation of structures in pymatgen.

• orbital (str) – An orbital. If it is a single character, e.g., s, p, d or f, the sum of all s-type, p-type, d-type or f-type orbitals occupations are returned respectively. If it is a specific orbital, e.g., px, dxy, etc., only the occupation of that orbital is returned.

Returns

Sum occupation of orbital of atom.

get_projection_on_elements(structure)[source]

Method returning a dictionary of projections on elements.

Parameters

structure (Structure) – Input structure.

Returns

[k index][b index][{Element:values}]]

Return type

a dictionary in the {Spin.up

exception UnconvergedVASPWarning[source]

Bases: Warning

Warning for unconverged vasp run.

exception VaspParserError[source]

Bases: Exception

Exception class for VASP parsing.

class Vasprun(filename, ionic_step_skip=None, ionic_step_offset=0, parse_dos=True, parse_eigen=True, parse_projected_eigen=False, parse_potcar_file=True, occu_tol=1e-08, exception_on_bad_xml=True)[source]

Bases: monty.json.MSONable

Vastly improved cElementTree-based parser for vasprun.xml files. Uses iterparse to support incremental parsing of large files. Speedup over Dom is at least 2x for smallish files (~1Mb) to orders of magnitude for larger files (~10Mb).

Vasp results

ionic_steps[source]

All ionic steps in the run as a list of {“structure”: structure at end of run, “electronic_steps”: {All electronic step data in vasprun file}, “stresses”: stress matrix}

tdos[source]

Total dos calculated at the end of run.

idos[source]

Integrated dos calculated at the end of run.

pdos[source]

List of list of PDos objects. Access as pdos[atomindex][orbitalindex]

efermi[source]

Fermi energy

eigenvalues[source]

Available only if parse_eigen=True. Final eigenvalues as a dict of {(spin, kpoint index):[[eigenvalue, occu]]}. This representation is based on actual ordering in VASP and is meant as an intermediate representation to be converted into proper objects. The kpoint index is 0-based (unlike the 1-based indexing in VASP).

projected_eigenvalues[source]

Final projected eigenvalues as a dict of {spin: nd-array}. To access a particular value, you need to do Vasprun.projected_eigenvalues[spin][kpoint index][band index][atom index][orbital_index] This representation is based on actual ordering in VASP and is meant as an intermediate representation to be converted into proper objects. The kpoint, band and atom indices are 0-based (unlike the 1-based indexing in VASP).

other_dielectric[source]

Dictionary, with the tag comment as key, containing other variants of the real and imaginary part of the dielectric constant (e.g., computed by RPA) in function of the energy (frequency). Optical properties (e.g. absorption coefficient) can be obtained through this. The data is given as a tuple of 3 values containing each of them the energy, the real part tensor, and the imaginary part tensor ([energies],[[real_partxx,real_partyy,real_partzz,real_partxy, real_partyz,real_partxz]],[[imag_partxx,imag_partyy,imag_partzz, imag_partxy, imag_partyz, imag_partxz]])

nionic_steps[source]

The total number of ionic steps. This number is always equal to the total number of steps in the actual run even if ionic_step_skip is used.

force_constants[source]

Force constants computed in phonon DFPT run(IBRION = 8). The data is a 4D numpy array of shape (natoms, natoms, 3, 3).

normalmode_eigenvals[source]

Normal mode frequencies. 1D numpy array of size 3*natoms.

normalmode_eigenvecs[source]

Normal mode eigen vectors. 3D numpy array of shape (3*natoms, natoms, 3).

Vasp inputs

incar[source]

Incar object for parameters specified in INCAR file.

parameters[source]

Incar object with parameters that vasp actually used, including all defaults.

kpoints[source]

Kpoints object for KPOINTS specified in run.

actual_kpoints[source]

List of actual kpoints, e.g., [[0.25, 0.125, 0.08333333], [-0.25, 0.125, 0.08333333], [0.25, 0.375, 0.08333333], ….]

actual_kpoints_weights[source]

List of kpoint weights, E.g., [0.04166667, 0.04166667, 0.04166667, 0.04166667, 0.04166667, ….]

atomic_symbols[source]

List of atomic symbols, e.g., [“Li”, “Fe”, “Fe”, “P”, “P”, “P”]

potcar_symbols[source]

List of POTCAR symbols. e.g., [“PAW_PBE Li 17Jan2003”, “PAW_PBE Fe 06Sep2000”, ..]

Author: Shyue Ping Ong

Parameters
• filename (str) – Filename to parse

• ionic_step_skip (int) – If ionic_step_skip is a number > 1, only every ionic_step_skip ionic steps will be read for structure and energies. This is very useful if you are parsing very large vasprun.xml files and you are not interested in every single ionic step. Note that the final energies may not be the actual final energy in the vasprun.

• ionic_step_offset (int) – Used together with ionic_step_skip. If set, the first ionic step read will be offset by the amount of ionic_step_offset. For example, if you want to start reading every 10th structure but only from the 3rd structure onwards, set ionic_step_skip to 10 and ionic_step_offset to 3. Main use case is when doing statistical structure analysis with extremely long time scale multiple VASP calculations of varying numbers of steps.

• parse_dos (bool) – Whether to parse the dos. Defaults to True. Set to False to shave off significant time from the parsing if you are not interested in getting those data.

• parse_eigen (bool) – Whether to parse the eigenvalues. Defaults to True. Set to False to shave off significant time from the parsing if you are not interested in getting those data.

• parse_projected_eigen (bool) – Whether to parse the projected eigenvalues. Defaults to False. Set to True to obtain projected eigenvalues. Note that this can take an extreme amount of time and memory. So use this wisely.

• parse_potcar_file (bool/str) –

Whether to parse the potcar file to read the potcar hashes for the potcar_spec attribute. Defaults to True, where no hashes will be determined and the potcar_spec dictionaries will read {“symbol”: ElSymbol, “hash”: None}. By Default, looks in the same directory as the vasprun.xml, with same extensions as

Vasprun.xml. If a string is provided, looks at that filepath.

• occu_tol (float) – Sets the minimum tol for the determination of the vbm and cbm. Usually the default of 1e-8 works well enough, but there may be pathological cases.

• exception_on_bad_xml (bool) – Whether to throw a ParseException if a malformed XML is detected. Default to True, which ensures only proper vasprun.xml are parsed. You can set to False if you want partial results (e.g., if you are monitoring a calculation during a run), but use the results with care. A warning is issued.

as_dict()[source]

Json-serializable dict representation.

property complete_dos[source]

A complete dos object which incorporates the total dos and all projected dos.

property converged[source]

Returns: True if a relaxation run is converged both ionically and electronically.

property converged_electronic[source]

Returns: True if electronic step convergence has been reached in the final ionic step

property converged_ionic[source]

Returns: True if ionic step convergence has been reached, i.e. that vasp exited before reaching the max ionic steps for a relaxation run

property dielectric[source]

Returns: The real and imaginary part of the dielectric constant (e.g., computed by RPA) in function of the energy (frequency). Optical properties (e.g. absorption coefficient) can be obtained through this. The data is given as a tuple of 3 values containing each of them the energy, the real part tensor, and the imaginary part tensor ([energies],[[real_partxx,real_partyy,real_partzz,real_partxy, real_partyz,real_partxz]],[[imag_partxx,imag_partyy,imag_partzz, imag_partxy, imag_partyz, imag_partxz]])

property eigenvalue_band_properties[source]

Band properties from the eigenvalues as a tuple, (band gap, cbm, vbm, is_band_gap_direct).

property epsilon_ionic[source]

Property only available for DFPT calculations and when IBRION=5, 6, 7 or 8.

Returns

The ionic part of the static dielectric constant. Present when it’s a DFPT run (LEPSILON=TRUE) and IBRION=5, 6, 7 or 8

property epsilon_static[source]

Property only available for DFPT calculations.

Returns

The static part of the dielectric constant. Present when it’s a DFPT run (LEPSILON=TRUE)

property epsilon_static_wolfe[source]

Property only available for DFPT calculations.

Returns

The static part of the dielectric constant without any local field effects. Present when it’s a DFPT run (LEPSILON=TRUE)

property final_energy[source]
get_band_structure(kpoints_filename=None, efermi=None, line_mode=False, force_hybrid_mode=False)[source]

Returns the band structure as a BandStructure object

Parameters
• kpoints_filename (str) – Full path of the KPOINTS file from which the band structure is generated. If none is provided, the code will try to intelligently determine the appropriate KPOINTS file by substituting the filename of the vasprun.xml with KPOINTS. The latter is the default behavior.

• efermi (float) – If you want to specify manually the fermi energy this is where you should do it. By default, the None value means the code will get it from the vasprun.

• line_mode (bool) – Force the band structure to be considered as a run along symmetry lines.

• force_hybrid_mode (bool) – Makes it possible to read in self-consistent band structure calculations for every type of functional

Returns

a BandStructure object (or more specifically a BandStructureSymmLine object if the run is detected to be a run along symmetry lines)

Two types of runs along symmetry lines are accepted: non-sc with Line-Mode in the KPOINT file or hybrid, self-consistent with a uniform grid+a few kpoints along symmetry lines (explicit KPOINTS file) (it’s not possible to run a non-sc band structure with hybrid functionals). The explicit KPOINTS file needs to have data on the kpoint label as commentary.

get_computed_entry(inc_structure=True, parameters=None, data=None)[source]

Returns a ComputedStructureEntry from the vasprun.

Parameters
• inc_structure (bool) – Set to True if you want ComputedStructureEntries to be returned instead of ComputedEntries.

• parameters (list) – Input parameters to include. It has to be one of the properties supported by the Vasprun object. If parameters is None, a default set of parameters that are necessary for typical post-processing will be set.

• data (list) – Output data to include. Has to be one of the properties supported by the Vasprun object.

Returns

ComputedStructureEntry/ComputedEntry

get_potcars(path)[source]
Parameters

path – Path to search for POTCARs

Returns

Potcar from path.

property hubbards[source]

Hubbard U values used if a vasprun is a GGA+U run. {} otherwise.

property is_hubbard[source]

True if run is a DFT+U run.

property is_spin[source]

True if run is spin-polarized.

property optical_absorption_coeff[source]

Calculate the optical absorption coefficient from the dielectric constants. Note that this method is only implemented for optical properties calculated with GGA and BSE. Returns: optical absorption coefficient in list

property run_type[source]

Returns the run type. Currently supports LDA, GGA, vdW-DF and HF calcs.

TODO: Fix for other functional types like PW91, other vdW types, etc.

property structures[source]

Returns: List of Structure objects for the structure at each ionic step.

update_charge_from_potcar(path)[source]

Sets the charge of a structure based on the POTCARs found.

Parameters

path – Path to search for POTCARs

update_potcar_spec(path)[source]
Parameters

path – Path to search for POTCARs

Returns

Potcar spec from path.

class VolumetricData(structure, data, distance_matrix=None, data_aug=None)[source]

Bases: monty.json.MSONable

Simple volumetric object for reading LOCPOT and CHGCAR type files.

structure[source]

Structure associated with the Volumetric Data object

..attribute:: is_spin_polarized

True if run is spin polarized

..attribute:: dim

Tuple of dimensions of volumetric grid in each direction (nx, ny, nz).

..attribute:: data

Actual data as a dict of {string: np.array}. The string are “total” and “diff”, in accordance to the output format of vasp LOCPOT and CHGCAR files where the total spin density is written first, followed by the difference spin density.

ngridpts[source]

Total number of grid points in volumetric data.

Typically, this constructor is not used directly and the static from_file constructor is used. This constructor is designed to allow summation and other operations between VolumetricData objects.

Parameters
• structure – Structure associated with the volumetric data

• data – Actual volumetric data.

• data_aug – Any extra information associated with volumetric data (typically augmentation charges)

• distance_matrix – A pre-computed distance matrix if available. Useful so pass distance_matrices between sums, shortcircuiting an otherwise expensive operation.

copy()[source]
Returns

Copy of Volumetric object

classmethod from_hdf5(filename)[source]

Parameters

filename – Filename

Returns

VolumetricData

get_average_along_axis(ind)[source]

Get the averaged total of the volumetric data a certain axis direction. For example, useful for visualizing Hartree Potentials from a LOCPOT file.

Parameters

ind (int) – Index of axis.

Returns

Average total along axis

get_axis_grid(ind)[source]

Returns the grid for a particular axis.

Parameters

ind (int) – Axis index.

get_integrated_diff(ind, radius, nbins=1)[source]

Get integrated difference of atom index ind up to radius. This can be an extremely computationally intensive process, depending on how many grid points are in the VolumetricData.

Parameters
• ind (int) – Index of atom.

• nbins (int) – Number of bins. Defaults to 1. This allows one to obtain the charge integration up to a list of the cumulative charge integration values for radii for [radius/nbins, 2 * radius/nbins, ….].

Returns

Differential integrated charge as a np array of [[radius, value], …]. Format is for ease of plotting. E.g., plt.plot(data[:,0], data[:,1])

linear_add(other, scale_factor=1.0)[source]

Method to do a linear sum of volumetric objects. Used by + and - operators as well. Returns a VolumetricData object containing the linear sum.

Parameters
• other (VolumetricData) – Another VolumetricData object

• scale_factor (float) – Factor to scale the other data by.

Returns

VolumetricData corresponding to self + scale_factor * other.

static parse_file(filename)[source]

Convenience method to parse a generic volumetric data file in the vasp like format. Used by subclasses for parsing file.

Parameters

filename (str) – Path of file to parse

Returns

(poscar, data)

property spin_data[source]

data}. Essentially, this provides the actual Spin.up and Spin.down data instead of the total and diff. Note that by definition, a non-spin-polarized run would have Spin.up data == Spin.down data.

Type

The data decomposed into actual spin data as {spin

to_hdf5(filename)[source]

Writes the VolumetricData to a HDF5 format, which is a highly optimized format for reading storing large data. The mapping of the VolumetricData to this file format is as follows:

VolumetricData.data -> f[“vdata”] VolumetricData.structure ->

f[“Z”]: Sequence of atomic numbers f[“fcoords”]: Fractional coords f[“lattice”]: Lattice in the pymatgen.core.lattice.Lattice matrix

format

f.attrs[“structure_json”]: String of json representation

Parameters

filename (str) – Filename to output to.

write_file(file_name, vasp4_compatible=False)[source]

Write the VolumetricData object to a vasp compatible file.

Parameters
• file_name (str) – Path to a file

• vasp4_compatible (bool) – True if the format is vasp4 compatible

class Wavecar(filename='WAVECAR', verbose=False, precision='normal')[source]

Bases: object

This is a class that contains the (pseudo-) wavefunctions from VASP.

Coefficients are read from the given WAVECAR file and the corresponding G-vectors are generated using the algorithm developed in WaveTrans (see acknowledgments below). To understand how the wavefunctions are evaluated, please see the evaluate_wavefunc docstring.

It should be noted that the pseudopotential augmentation is not included in the WAVECAR file. As a result, some caution should be exercised when deriving value from this information.

The usefulness of this class is to allow the user to do projections or band unfolding style manipulations of the wavefunction. An example of this can be seen in the work of Shen et al. 2017 (https://doi.org/10.1103/PhysRevMaterials.1.065001).

filename[source]

String of the input file (usually WAVECAR)

nk[source]

Number of k-points from the WAVECAR

nb[source]

Number of bands per k-point

encut[source]

Energy cutoff (used to define G_{cut})

efermi[source]

Fermi energy

a[source]

Primitive lattice vectors of the cell (e.g. a_1 = self.a[0, :])

b[source]

Reciprocal lattice vectors of the cell (e.g. b_1 = self.b[0, :])

vol[source]

The volume of the unit cell in real space

kpoints[source]

The list of k-points read from the WAVECAR file

band_energy[source]

The list of band eigenenergies (and corresponding occupancies) for each kpoint, where the first index corresponds to the index of the k-point (e.g. self.band_energy[kp])

Gpoints[source]

The list of generated G-points for each k-point (a double list), which are used with the coefficients for each k-point and band to recreate the wavefunction (e.g. self.Gpoints[kp] is the list of G-points for k-point kp). The G-points depend on the k-point and reciprocal lattice and therefore are identical for each band at the same k-point. Each G-point is represented by integer multipliers (e.g. assuming Gpoints[kp][n] == [n_1, n_2, n_3], then G_n = n_1*b_1 + n_2*b_2 + n_3*b_3)

coeffs[source]

The list of coefficients for each k-point and band for reconstructing the wavefunction. For non-spin-polarized, the first index corresponds to the kpoint and the second corresponds to the band (e.g. self.coeffs[kp][b] corresponds to k-point kp and band b). For spin-polarized calculations, the first index is for the spin.

Acknowledgments:

This code is based upon the Fortran program, WaveTrans, written by R. M. Feenstra and M. Widom from the Dept. of Physics at Carnegie Mellon University. To see the original work, please visit: https://www.andrew.cmu.edu/user/feenstra/wavetrans/

Author: Mark Turiansky

Information is extracted from the given WAVECAR

Parameters
• filename (str) – input file (default: WAVECAR)

• verbose (bool) – determines whether processing information is shown

• precision (str) – determines how fine the fft mesh is (normal or accurate), only the first letter matters

evaluate_wavefunc(kpoint, band, r, spin=0)[source]

Evaluates the wavefunction for a given position, r.

The wavefunction is given by the k-point and band. It is evaluated at the given position by summing over the components. Formally,

psi_n^k (r) = sum_{i=1}^N c_i^{n,k} exp (i (k + G_i^{n,k}) cdot r)

where psi_n^k is the wavefunction for the nth band at k-point k, N is the number of plane waves, c_i^{n,k} is the ith coefficient that corresponds to the nth band and k-point k, and G_i^{n,k} is the ith G-point corresponding to k-point k.

NOTE: This function is very slow; a discrete fourier transform is the preferred method of evaluation (see Wavecar.fft_mesh).

Parameters
• kpoint (int) – the index of the kpoint where the wavefunction will be evaluated

• band (int) – the index of the band where the wavefunction will be evaluated

• r (np.array) – the position where the wavefunction will be evaluated

• spin (int) – spin index for the desired wavefunction (only for ISPIN = 2, default = 0)

Returns

a complex value corresponding to the evaluation of the wavefunction

fft_mesh(kpoint, band, spin=0, shift=True)[source]

Places the coefficients of a wavefunction onto an fft mesh.

Once the mesh has been obtained, a discrete fourier transform can be used to obtain real-space evaluation of the wavefunction. The output of this function can be passed directly to numpy’s fft function. For .. rubric:: Example

mesh = Wavecar(‘WAVECAR’).fft_mesh(kpoint, band) evals = np.fft.ifftn(mesh)

Parameters
• kpoint (int) – the index of the kpoint where the wavefunction will be evaluated

• band (int) – the index of the band where the wavefunction will be evaluated

• spin (int) – the spin of the wavefunction for the desired wavefunction (only for ISPIN = 2, default = 0)

• shift (bool) – determines if the zero frequency coefficient is placed at index (0, 0, 0) or centered

Returns

a numpy ndarray representing the 3D mesh of coefficients

get_parchg(poscar, kpoint, band, spin=None, phase=False, scale=2)[source]

Generates a Chgcar object, which is the charge density of the specified wavefunction.

This function generates a Chgcar object with the charge density of the wavefunction specified by band and kpoint (and spin, if the WAVECAR corresponds to a spin-polarized calculation). The phase tag is a feature that is not present in VASP. For a real wavefunction, the phase tag being turned on means that the charge density is multiplied by the sign of the wavefunction at that point in space. A warning is generated if the phase tag is on and the chosen kpoint is not Gamma.

Note: Augmentation from the PAWs is NOT included in this function. The maximal charge density will differ from the PARCHG from VASP, but the qualitative shape of the charge density will match.

Parameters
• poscar (pymatgen.io.vasp.inputs.Poscar) – Poscar object that has the structure associated with the WAVECAR file

• kpoint (int) – the index of the kpoint for the wavefunction

• band (int) – the index of the band for the wavefunction

• spin (int) – optional argument to specify the spin. If the Wavecar has ISPIN = 2, spin is None generates a Chgcar with total spin and magnetization, and spin == {0, 1} specifies just the spin up or down component.

• phase (bool) – flag to determine if the charge density is multiplied by the sign of the wavefunction. Only valid for real wavefunctions.

• scale (int) – scaling for the FFT grid. The default value of 2 is at least as fine as the VASP default.

Returns

a pymatgen.io.vasp.outputs.Chgcar object

class Waveder(filename, gamma_only=False)[source]

Bases: object

Class for reading a WAVEDER file. The LOPTICS tag produces a WAVEDER file. The WAVEDER contains the derivative of the orbitals with respect to k. Author: Kamal Choudhary, NIST

Parameters

filename – Name of file containing WAVEDER.

property cder_data[source]

Returns the orbital derivative between states

get_orbital_derivative_between_states(band_i, band_j, kpoint, spin, cart_dir)[source]

Method returning a value between bands band_i and band_j for k-point index, spin-channel and cartesian direction. :param band_i: Index of band i :type band_i: Integer :param band_j: Index of band j :type band_j: Integer :param kpoint: Index of k-point :type kpoint: Integer :param spin: Index of spin-channel (0 or 1) :type spin: Integer :param cart_dir: Index of cartesian direction (0,1,2) :type cart_dir: Integer

Returns

a float value

property nbands[source]

Returns the number of bands in the calculation

property nelect[source]

Returns the number of electrons in the calculation

property nkpoints[source]

Returns the number of k-points in the calculation

class Wavederf(filename)[source]

Bases: object

Object for reading a WAVEDERF file.

Note: This file is only produced when LOPTICS is true AND vasp has been recompiled after uncommenting the line that calls WRT_CDER_BETWEEN_STATES_FORMATTED in linear_optics.F

data[source]

A numpy array containing the WAVEDERF data of the form below. It should be noted that VASP uses 1-based indexing for bands, but this is converted to 0-based numpy array indexing.

For each kpoint (in the same order as in IBZKPT), and for each pair of bands:

[ #kpoint index
[ #band 1 index
[ #band 2 index

[cdum_x_real, cdum_x_imag, cdum_y_real, cdum_y_imag, cdum_z_real, cdum_z_imag]

]

]

]

This structure follows the file format. Numpy array methods can be used to fetch data in a more useful way (e.g., get matrix elements between wo specific bands at each kpoint, fetch x/y/z components, real/imaginary parts, abs/phase, etc. )

Author: Miguel Dias Costa

Parameters

filename – Name of file containing WAVEDERF.

get_elements_between_bands(band_i, band_j)[source]

Method returning a numpy array with elements

[cdum_x_real, cdum_x_imag, cdum_y_real, cdum_y_imag, cdum_z_real, cdum_z_imag]

between bands band_i and band_j (vasp 1-based indexing) for all kpoints.

Parameters
• band_i (Integer) – Index of band i

• band_j (Integer) – Index of band j

Returns

a numpy list of elements for each kpoint

property nb_bands[source]

returns the number of bands in the band structure

property nb_kpoints[source]

Returns the number of k-points in the band structure calculation

class Xdatcar(filename, ionicstep_start=1, ionicstep_end=None, comment=None)[source]

Bases: object

Class representing an XDATCAR file. Only tested with VASP 5.x files.

structures[source]

List of structures parsed from XDATCAR.

comment[source]

Optional comment string.

Authors: Ram Balachandran

Init a Xdatcar.

Parameters
• filename (str) – Filename of input XDATCAR file.

• ionicstep_start (int) – Starting number of ionic step.

• ionicstep_end (int) – Ending number of ionic step.

concatenate(filename, ionicstep_start=1, ionicstep_end=None)[source]

Concatenate structures in file to Xdatcar.

Parameters
• filename (str) – Filename of XDATCAR file to be concatenated.

• ionicstep_start (int) – Starting number of ionic step.

• ionicstep_end (int) – Ending number of ionic step.

TODO(rambalachandran):

Requires a check to ensure if the new concatenating file has the same lattice structure and atoms as the Xdatcar class.

get_string(ionicstep_start=1, ionicstep_end=None, significant_figures=8)[source]

Write Xdatcar class to a string.

Parameters
• ionicstep_start (int) – Starting number of ionic step.

• ionicstep_end (int) – Ending number of ionic step.

• significant_figures (int) – Number of significant figures.

property natoms[source]

Sequence of number of sites of each type associated with the Poscar. Similar to 7th line in vasp 5+ Xdatcar.

property site_symbols[source]

Sequence of symbols associated with the Xdatcar. Similar to 6th line in vasp 5+ Xdatcar.

write_file(filename, **kwargs)[source]

Write Xdatcar class into a file.

Parameters
• filename (str) – Filename of output XDATCAR file.

• supported kwargs are the same as those for the (The) –

• method and are passed through directly. (Xdatcar.get_string) –

get_adjusted_fermi_level(efermi, cbm, band_structure)[source]

When running a band structure computations the fermi level needs to be take from the static run that gave the charge density used for the non-self consistent band structure run. Sometimes this fermi level is however a little too low because of the mismatch between the uniform grid used in the static run and the band structure k-points (e.g., the VBM is on Gamma and the Gamma point is not in the uniform mesh). Here we use a procedure consisting in looking for energy levels higher than the static fermi level (but lower than the LUMO) if any of these levels make the band structure appears insulating and not metallic anymore, we keep this adjusted fermi level. This procedure has shown to detect correctly most insulators.

Parameters
• efermi (float) – Fermi energy of the static run

• cbm (float) – Conduction band minimum of the static run

• run_bandstructure – a band_structure object

Returns

get_band_structure_from_vasp_multiple_branches(dir_name, efermi=None, projections=False)[source]

This method is used to get band structure info from a VASP directory. It takes into account that the run can be divided in several branches named “branch_x”. If the run has not been divided in branches the method will turn to parsing vasprun.xml directly.

The method returns None is there”s a parsing error

Parameters
• dir_name – Directory containing all bandstructure runs.

• efermi – Efermi for bandstructure.

• projections – True if you want to get the data on site projections if any. Note that this is sometimes very large

Returns

A BandStructure Object