API Reference

Core

Common routines used across the sub-libraries.

groupby_cmp(lst, cmp_eq, title_function=None)[source]

Group elements of a list by pairwise comparison.

Groups consecutive elements using a caller-supplied equality function.

Parameters:
  • lst – List of elements to group.

  • cmp_eq – Function that takes two elements and returns True if they should belong to the same group.

  • title_function – Optional function that takes an element and returns a string used in log messages. When None, “??” is logged.

Returns:

List of grouped lists. Each sublist contains elements that are pairwise equivalent according to cmp_eq.

Return type:

list[list]

Extension for pymatgen.core.structure.

class IMDStructure(lattice, species, coords, charge=None, validate_proximity=False, to_unit_cell=False, coords_are_cartesian=False, site_properties=None, labels=None, properties=None)[source]

Bases: Structure

IMDGroup variant of pymatgen Structure.

Adds the ability to read and write ATAT str.out files and handle vacancies (Vac) as dummy species X.

Create a periodic structure.

Parameters:
  • lattice (ArrayLike | Lattice) – The lattice, either as a pymatgen.core.Lattice or simply as any 2D array. Each row should correspond to a lattice vector. e.g. [[10,0,0], [20,10,0], [0,0,30]] specifies a lattice with lattice vectors [10,0,0], [20,10,0] and [0,0,30].

  • species (Sequence[CompositionLike]) –

    List of species on each site. Can take in flexible input, including:

    1. A sequence of element / species specified either as string symbols, e.g. [“Li”, “Fe2+”, “P”, …] or atomic numbers, e.g. (3, 56, …) or actual Element or Species objects.

    2. List of dict of elements/species and occupancies, e.g. [{“Fe” : 0.5, “Mn”:0.5}, …]. This allows the setup of disordered structures.

  • coords (Nx3 array) – Array of fractional/cartesian coordinates of each species.

  • charge (float) – Overall charge of the structure. Defaults to behavior in SiteCollection where total charge is the sum of the oxidation states.

  • validate_proximity (bool) – Whether to check if there are sites that are less than 0.01 Ang apart. Defaults to False.

  • to_unit_cell (bool) – Whether to map all sites into the unit cell, i.e., fractional coords between 0 and 1. Defaults to False.

  • coords_are_cartesian (bool) – Set to True if you are providing coordinates in Cartesian coordinates. Defaults to False.

  • site_properties (dict) – Properties associated with the sites as a dict of sequences, e.g. {“magmom”:[5,5,5,5]}. The sequences have to be the same length as the atomic species and fractional_coords. Defaults to None for no properties.

  • labels (list[str]) – Labels associated with the sites as a list of strings, e.g. [‘Li1’, ‘Li2’]. Must have the same length as the species and fractional coords. Defaults to None for no labels.

  • properties (dict) – Properties associated with the whole structure. Will be serialized when writing the structure to JSON or YAML but is lost when converting to other formats.

classmethod from_file(filename, primitive=False, sort=False, merge_tol=0.0, **kwargs)[source]

Read a structure from a file. Support everything from pymatgen.Structure and also ATAT’s structures. ATAT’s structures will contain vacancies (Vac) as dummy X species.

Parameters:
  • filename (PathLike) – The file to read.

  • primitive (bool) – Whether to convert to a primitive cell. Defaults to False.

  • sort (bool) – Whether to sort sites. Default to False.

  • merge_tol (float) – If this is some positive number, sites that are within merge_tol from each other will be merged. Usually 0.01 should be enough to deal with common numerical issues.

  • kwargs – Passthrough to relevant reader. E.g. if the file has CIF format, the kwargs will be passed through to CifParser.

Returns:

Structure.

Return type:

Self

classmethod from_structure(structure)[source]

Create an IMDStructure from an existing pymatgen Structure.

Parameters:

structure (Structure) – Structure to convert.

Returns:

Copy of structure as an IMDStructure.

Return type:

IMDStructure

to(filename='', fmt='', **kwargs)[source]

Output the structure to a file or string. In addition to what pymatgen provides, write “str.out” file suitable for ATAT, replacing X0+ species with Vac and dropping occupancies. This corresponds to fmt=”atat”.

Parameters:
  • filename (PathLike) – If provided, output will be written to a file. If fmt is not specified, the format is determined from the filename. Defaults is None, i.e. string output.

  • fmt (str) – Format to output to. Defaults to JSON unless filename is provided. If fmt is specifies, it overrides whatever the filename is. Options include “cif”, “poscar”, “cssr”, “json”, “xsf”, “mcsqs”, “prismatic”, “yaml”, “yml”, “fleur-inpgen”, “pwmat”, “aims”. Non-case sensitive.

  • **kwargs – Kwargs passthru to relevant methods. e.g. This allows the passing of parameters like symprec to the CifWriter.__init__ method for generation of symmetric CIFs.

Returns:

String representation of molecule in given format. If a filename

is provided, the same string is written to the file.

Return type:

str

to_file(filename='', fmt='')[source]

A more intuitive alias for .to().

Parameters:

filename (str)

Return type:

str | None

exception StructureDuplicateWarning[source]

Bases: UserWarning

Warning emitted when duplicate input structures are detected.

get_matched_structure(reference_struct, target_struct, pbc=True, match_species=True)[source]

Rearrange sites in target_struct to best match reference_struct.

Returns a modified target_struct with sites reordered so that reference_struct[idx] is close to the returned structure’s [idx] and they share the same species. Extra sites (beyond the reference length) are appended at the end.

Parameters:
  • reference_struct (Structure) – The reference structure to match against.

  • target_struct (Structure) – The target structure to reorder. Must have the same lattice and contain reference_struct sites as a subset.

  • pbc (bool) – When True (default), use periodic boundary conditions for distance calculations.

  • match_species (bool) – When False, ignore species when matching sites.

Returns:

Reordered target structure with one-to-one site correspondence to reference_struct.

Return type:

Structure

Raises:

ValueError – If target_struct has too few sites or the lattices differ, or if matching fails.

get_supercell_size(structure)[source]

Determine supercell dimensions relative to the primitive cell.

Parameters:

structure – Supercell structure.

Returns:

(A, B, C) factors such that the input is an A x B x C supercell of its primitive.

Return type:

tuple[int, int, int]

merge_structures(structs, tol=0.01)[source]

Merge multiple structures into a single Structure.

All structures must share the same lattice. Sites are merged with the given tolerance.

Parameters:
  • structs (list[Structure]) – List of structures to merge. Must be non-empty.

  • tol (float) – Tolerance in Angstrom for merging sites (passed to Structure.merge_sites).

Returns:

A new structure containing merged sites from all inputs.

Return type:

Structure

reduce_supercell(structure)[source]

Return the primitive cell of a supercell structure.

Constrains alpha, beta, and gamma angles during reduction.

Parameters:

structure – Input structure (possibly a supercell).

Returns:

Primitive cell. The input is not modified.

Return type:

Structure

structure_diff(structure1, structure2, tol=0.1, match_first=True, match_species=True)[source]

Compute translation vectors between two similar structures.

Both structures must have the same number of sites and species. Each vector in the result connects corresponding sites. Displacements below tol Angstrom are zeroed.

Parameters:
  • structure1 (Structure) – First structure.

  • structure2 (Structure) – Second structure.

  • tol (float) – Displacements below this threshold (Angstrom) are set to the zero vector.

  • match_first (bool) – When True (default), call get_matched_structure() before computing vectors.

  • match_species (bool) – When False and match_first is True, ignore species during structure matching.

Returns:

List of 3D cartesian displacement vectors, one per site.

Return type:

list[np.ndarray]

structure_distance(structure1, structure2, tol=0.1, match_first=True, max_dist=None, norm=False, match_species=True)[source]

Compute distance between two similar structures.

The distance is the square root of the sum of squared distances between corresponding sites. Displacements below tol Angstrom do not contribute.

When the structures have similar but not identical lattices, fractional site positions of structure2 are mapped onto the lattice vectors of structure1.

Parameters:
  • structure1 (Structure) – First structure.

  • structure2 (Structure) – Second structure.

  • tol (float) – Displacement threshold below which contributions are ignored (Angstrom).

  • match_first – When True (default), call get_matched_structure() before computing distances.

  • match_species (bool) – When False and match_first is True, ignore species during matching.

  • max_dist – When set, return early if the accumulating distance exceeds this value.

  • norm – When True, divide the result by the count of sites displaced above threshold.

Returns:

Structure distance.

Return type:

float

structure_interpolate2(structure1, structure2, nimages=10, frac_tol=0.5, center=0.5, match_first=True, **kwargs)[source]

Interpolate between structures, avoiding atom collisions.

Like Structure.interpolate, but ensures no atoms in the interpolated images are too close. “Too close” means less than frac_tol * (radius1 + radius2).

Parameters:
  • structure1 (Structure) – Starting structure.

  • structure2 (Structure) – Ending structure.

  • nimages (int) – Number of interpolated images (excludes endpoints).

  • frac_tol (float) – Proximity tolerance as a fraction of atomic radii sum. Use 0 to skip validity checks.

  • center (bool | float) – When True or a float, align geometric centers of mass before interpolation. When a float, only align if the center-to-center distance is below that value.

  • match_first (bool) – When True (default), call get_matched_structure() before interpolation.

  • **kwargs – Forwarded to Structure.interpolate.

Returns:

Interpolated structures, possibly with adjusted spacing to avoid collisions.

Return type:

list[Structure]

structure_is_valid2(structure, frac_tol=0.5)[source]

Check whether a structure contains no atoms that are too close.

Atoms are considered too close when the distance between them is less than frac_tol * (atomic_radius1 + atomic_radius2).

Parameters:
  • structure (Structure) – Structure to validate.

  • frac_tol (float) – Threshold multiplier for the sum of atomic radii.

Returns:

True if all pairwise distances are above threshold.

Return type:

bool

structure_matches(struct, known_structs, cmp_fun=None, warn=False, multithread=False)[source]

Check whether a structure is equivalent to any in a known list.

Parameters:
  • struct (Structure) – Structure to test.

  • known_structs (list[Structure | None]) – List of known structures. None entries are skipped.

  • cmp_fun – Callable that takes two structures and returns True if they match. Defaults to StructureMatcher(attempt_supercell=True, scale=False).fit.

  • warn – When True, emit StructureDuplicateWarning on match.

  • multithread – When True, use cpu_count - 1 workers. When an integer, use that many workers (capped at available CPUs).

Returns:

True if a match is found, False otherwise.

Return type:

bool

structure_perturb(structure, distance, min_distance=None, frac_tol=0.5)[source]

Perturb sites randomly while respecting selective dynamics.

Unlike pymatgen.core.Structure.perturb, this function honours selective_dynamics site properties and ensures the perturbed structure has no sites that are too close.

Parameters:
  • structure (Structure) – Structure to perturb. Modified in place.

  • distance (float) – Maximum perturbation amplitude in Angstrom.

  • min_distance (float | None) – When set, each perturbation is drawn uniformly from [min_distance, distance].

  • frac_tol (float) – Proximity tolerance as a fraction of atomic radii sum.

Returns:

The perturbed structure (same object).

Return type:

Structure

Raises:

ValueError – If a valid perturbation cannot be found after 100 attempts.

structure_remove_duplicates(structs, cmp_fun=None, warn=False, multithread=False)[source]

Remove duplicate structures from a list, preserving order.

Uses structure_matches() to test each structure against previously kept structures. The first occurrence of each unique structure is kept; subsequent duplicates are replaced with None.

Parameters:
  • structs (list[Structure | None]) – List of structures to deduplicate.

  • cmp_fun – Comparison function passed to structure_matches(). Defaults to None, which uses StructureMatcher(attempt_supercell=True, scale=False).fit.

  • warn – When True, emit StructureDuplicateWarning for each duplicate found.

  • multithread – When True, use cpu_count - 1 workers. When an integer, use that many workers (capped at available CPUs).

Returns:

Input list with duplicates replaced by None, preserving order.

Return type:

list[Structure | None]

structure_strain(structure1, structure2)[source]

Compute the engineering strain to deform structure1 into structure2.

Parameters:
  • structure1 (Structure) – Initial structure.

  • structure2 (Structure) – Deformed structure.

Returns:

3x3 symmetric strain tensor.

Return type:

np.ndarray

I/O

This module implements abstraction over Vasp input/output directory.

class IMDGVaspDir(dirname, exclude_patterns=None)[source]

Bases: Mapping, MSONable

Dictionary-like access to all files in a VASP calculation directory.

Files are lazily parsed to minimise initialisation cost. Example:

d = IMDGVaspDir(".")
print(d["INCAR"]["NELM"])
print(d["vasprun.xml"].parameters)

Call refresh() to re-read the directory after files change.

Cached parsing results are stored in LMDB to speed up repeated access in HPC workflows.

Properties that require parsing multiple files:

  • final_energy, final_energy_reliable

  • initial_structure, structure

  • total_magnetization

  • converged, converged_ionic, converged_electronic, converged_sequence, converged_manual

  • nebp (whether directory is a NEB calculation)

  • neb_dirs (list of NEB subdirectories, if any)

  • mtime (latest modification time across all files)

  • prev_dirs (chain of previous gorun_* runs)

Initialise from a directory path.

Parameters:
  • dirname (str | Path) – Path to the VASP calculation directory.

  • exclude_patterns (Iterable[str] | None) – Extra glob patterns for files to skip during directory scanning. These are added to the class-level EXCLUDE_PATTERNS. For example, ["*.log"] excludes imdg.log (already in the class default) as well as any other *.log file.

CACHE_VERSION: ClassVar[int] = 1
EXCLUDE_PATTERNS: ClassVar[frozenset[str]] = frozenset({'imdg.log'})
FILE_MAPPINGS: ClassVar = {'CHGCAR': <class 'pymatgen.io.vasp.outputs.Chgcar'>, 'CONTCAR': <class 'pymatgen.io.vasp.inputs.Poscar'>, 'ELFCAR': <class 'pymatgen.io.vasp.outputs.Elfcar'>, 'INCAR': <class 'IMDgroup.pymatgen.io.vasp.inputs.Incar'>, 'KPOINTS': <class 'pymatgen.io.vasp.inputs.Kpoints'>, 'LOCPOT': <class 'pymatgen.io.vasp.outputs.Locpot'>, 'OSZICAR': <class 'pymatgen.io.vasp.outputs.Oszicar'>, 'OUTCAR': <class 'IMDgroup.pymatgen.io.vasp.outputs.Outcar'>, 'POSCAR': <class 'pymatgen.io.vasp.inputs.Poscar'>, 'POTCAR': <class 'pymatgen.io.vasp.inputs.Potcar'>, 'PROCAR': <class 'pymatgen.io.vasp.outputs.Procar'>, 'WAVEDER': <class 'pymatgen.io.vasp.outputs.Waveder'>, 'WSWQ': <class 'pymatgen.io.vasp.outputs.WSWQ'>, 'slurm.+': <class 'IMDgroup.pymatgen.io.vasp.outputs.Vasplog'>, 'stdout.*': <class 'IMDgroup.pymatgen.io.vasp.outputs.Vasplog'>, 'vasp\\.out.*': <class 'IMDgroup.pymatgen.io.vasp.outputs.Vasplog'>, 'vasprun\\.xml(\\.gz)?': <class 'IMDgroup.pymatgen.io.vasp.outputs.Vasprun'>}
TIMEOUT = 120
__init__(dirname, exclude_patterns=None)[source]

Initialise from a directory path.

Parameters:
  • dirname (str | Path) – Path to the VASP calculation directory.

  • exclude_patterns (Iterable[str] | None) – Extra glob patterns for files to skip during directory scanning. These are added to the class-level EXCLUDE_PATTERNS. For example, ["*.log"] excludes imdg.log (already in the class default) as well as any other *.log file.

Return type:

None

check_displacements()[source]

Check whether atomic displacements are below a safe threshold.

Warns and returns False when the maximum displacement exceeds twice the average bond length.

Returns:

True if displacements are acceptable.

Return type:

bool

check_framework_symmetry(framework_elements=None, symprec=0.1, max_rms_threshold=0.5)[source]

Check whether the framework symmetry is preserved.

Reduces false positives from mobile atoms breaking symmetry.

Parameters:
  • framework_elements – List of element symbols for the framework. Defaults to the most common element.

  • symprec – Symmetry tolerance for space group detection.

  • max_rms_threshold – Maximum RMS displacement threshold in Angstrom.

Returns:

True if framework symmetry is preserved.

Return type:

bool

property converged: bool

Overall convergence status.

Returns True only when the run is electronically and ionically converged, the convergence sequence is complete, and no UNCONVERGED marker file is present. For NEB runs, all images must be converged.

property converged_electronic: bool

Whether electronic convergence was reached.

property converged_ionic: bool

Whether ionic convergence was reached.

Also checks framework symmetry and displacements.

property converged_manual: bool

Whether the directory is explicitly marked as converged.

Returns False when an UNCONVERGED file is present.

property converged_sequence: bool

Whether the multi-step convergence sequence is complete.

Returns False when INCAR.[0-9]+ files remain (signalling that further convergence steps are pending).

property final_energy: float

Final energy computed in current Vasp outputs.

property final_energy_reliable: str | float

Like final_energy, but with a reliability check.

Returns:

The final energy when judged reliable. str: "unreliable" when energy may be inaccurate (e.g. volume relaxation). str: "unconverged" when the run has not converged.

Return type:

float

classmethod flush_cache()[source]

Write all pending cache entries to LMDB.

On write failure (including timeout), pending entries are restored so they can be retried on the next flush.

Return type:

None

property initial_structure: Structure

Initial structure of the calculation.

Follows the chain of prev_dirs to find the earliest initial structure if previous runs exist.

logs()[source]

Parse VASP log files in this directory through the file cache.

Discovers log files via Vasplog.vasp_log_files() and parses each through __getitem__(), so parsed warnings and progress are cached alongside the other files. Returns Vasplog instances for slurm/stdout/vasp.out logs and an Outcar when OUTCAR is the only log file.

Returns:

Parsed log objects, skipping files that fail to parse.

Return type:

list

max_force(include_constrained=False)[source]

Maximum residual force magnitude from the OUTCAR.

When include_constrained is False (default), force components in directions constrained by selective dynamics are ignored, so fixed atoms do not dominate the reported force. Constraints are read from the POSCAR, with CONTCAR as a fallback.

Parameters:

include_constrained (bool) – When True, include all force components regardless of selective dynamics.

Returns:

Maximum force in eV/Angstrom, or None when the OUTCAR forces are unavailable or no unconstrained force components remain.

Return type:

float | None

mtime()[source]

Latest modification time across all relevant files.

Considers NEB subdirectories and previous-run directories.

Return type:

float

neb_dirs(include_ends=True)[source]

List of NEB image subdirectories.

Parameters:

include_ends – When False, exclude the first and last images.

Returns:

NEB subdirectories, or None if this is not a NEB run.

Return type:

list[IMDGVaspDir] | None

property nebp: bool

Whether this directory contains a NEB-like calculation.

Detected by the presence of IMAGES in the INCAR.

prev_dirs()[source]

List of previous VASP runs in the chain.

Previous runs are assumed to reside in gorun_* subdirectories containing a POSCAR.

Returns:

Sorted list of previous-run directories, or None.

Return type:

list[IMDGVaspDir] | None

static read_vaspdirs(rootpath, path_filter=None)[source]

Recursively scan directories for VASP calculations.

Parameters:
  • rootpath (Path | str | list[Path | str]) – Root directory or list of directories to scan.

  • path_filter – Optional callable that returns True for paths to include.

Returns:

Mapping of {path: IMDGVaspDir}.

Return type:

dict[str, IMDGVaspDir]

refresh()[source]

Reload cached data from disk or re-parse if files changed.

reset()[source]

Reset all loaded files and re-scan the directory.

Clears cached parsed files, previous-run references, and NEB subdirectory references. Files matching EXCLUDE_PATTERNS or extra patterns from the constructor are skipped.

property structure: Structure

Last known structure (CONTCAR if present, else final from vasprun).

property total_magnetization: float | None

Total magnetization from OSZICAR, or None if unavailable.

property warnings: VaspWarnings

Structured warnings for this directory.

Aggregates log-file warnings (Vasplog/Outcar), Vasprun accuracy checks, and directory-level checks (energy reliability, displacements, framework symmetry). The container is cached and replayed on subsequent loads.

Returns:

Name-keyed warning records.

Return type:

VaspWarnings

exception TimeoutException[source]

Bases: Exception

Raised when a VASP directory read operation times out.

timeout_handler(signum, frame)[source]

Signal handler that raises TimeoutException.

Parameters:
  • signum – Signal number.

  • frame – Current stack frame.

Raises:

TimeoutException – Always raised.

This module implements IMD group-specific extensions to pymatgen.io.vasp.inputs module.

class Incar(params=None)[source]

Bases: Incar

Modified version of pymatgen’s Incar class.

Extensions:

  1. Readable constants for INCAR values (ISIF_*, IBRION_*).

  2. Warning when IBRION=-1 and NSW>0 (useless combination).

  3. Methods to retrieve standard setting combinations.

Clean up params and create an Incar object.

Parameters:

params (dict) – INCAR parameters as a dictionary.

Warning

BadIncarWarning: If there are duplicate in keys (case insensitive).

IBRION_IONIC_RELAX_CGA = 2
IBRION_IONIC_RELAX_DAMPED_MD = 3
IBRION_IONIC_RELAX_FORCE_FAST = 1
IBRION_IONIC_RELAX_values = [1, 2, 3]
IBRION_MD = 0
IBRION_NONE = -1
IFIX_FIX_POS_VOL = 5
ISIF_FIX_NONE = 3
ISIF_FIX_POS = 6
ISIF_FIX_POS_SHAPE = 7
ISIF_FIX_SHAPE = 8
ISIF_FIX_SHAPE_VOL = 2
ISIF_FIX_SHAPE_VOL_FAST = 0
ISIF_FIX_SHAPE_VOL_TRACE = 1
ISIF_FIX_VOL = 4
ISIF_RELAX_POS = 2
ISIF_RELAX_POS_FAST = 0
ISIF_RELAX_POS_SHAPE = 4
ISIF_RELAX_POS_SHAPE_VOL = 3
ISIF_RELAX_POS_TRACE = 1
ISIF_RELAX_POS_VOL = 8
ISIF_RELAX_SHAPE = 5
ISIF_RELAX_SHAPE_VOL = 6
ISIF_RELAX_VOL = 7
static get_recipe(setup, name)[source]

Retrieve INCAR settings for a given setup and name.

Parameters:
  • setup (str) – "functional" to retrieve functional settings.

  • name (str) – Functional name. Supported values: PBE, PBEsol, PBE+D2, PBE+TS, vdW-DF, vdW-DF2, optB88-vdW, optB86b-vdW.

Returns:

INCAR parameter dictionary.

Return type:

dict

Raises:
static group_incars(incars, ignore_fields=['SYSTEM', 'NELM', 'NELMIN', 'ALGO', 'SYMPREC'])[source]

Group similar INCARs together.

Differences in ignore_fields are not considered when comparing INCARs.

Parameters:
  • incars – List of Incar objects.

  • ignore_fields – INCAR keys to ignore when grouping.

Returns:

(common_incar, groups) where common_incar is an Incar with parameters shared by all groups, and groups is a list of lists of Incar objects.

Return type:

tuple

image_dir_names(include_ends=True)[source]

Return directory names for NEB images.

Parameters:

include_ends (bool) – When False, exclude the first (00) and last image directories.

Returns:

Sorted list of directory names, or None when IMAGES is not set in the INCAR.

Return type:

list[str] | None

This module implements extensions to pymatgen.io.vasp.outputs module.

class Outcar(filename)[source]

Bases: VasplogMixin, Outcar

Modified version of pymatgen’s Outcar that stores all fields.

Initialize an Outcar.

Parameters:

filename (PathLike) – OUTCAR file to parse.

as_dict()[source]

MSONable dict.

Return type:

dict

property file: Path

Path to the OUTCAR file (uniform with Vasplog).

property final_forces: ndarray | None

Force vectors from the final ionic step.

Parses the last TOTAL-FORCE table from the OUTCAR and returns one force vector per atom.

Returns:

Array of shape (n_atoms, 3) with forces in eV/Angstrom, or None when the table is missing or cannot be parsed.

Return type:

np.ndarray | None

class Vasplog(filename)[source]

Bases: VasplogMixin, MSONable

Parser for VASP log files (slurm output, stdout, OUTCAR).

Extracts warnings and progress messages from VASP output using configurable regex patterns. The parsed log file path is stored in file.

Initialize parser from a log file.

Parameters:

filename (str | Path) – Path to the log file to parse.

__init__(filename)[source]

Initialize parser from a log file.

Parameters:

filename (str | Path) – Path to the log file to parse.

Return type:

None

class VasplogMixin[source]

Bases: object

Shared log-parsing logic for VASP log files and OUTCAR.

Builds a deduplicated line index (self.lines and self.line_counts) and exposes regex-driven warning/progress extraction. Subclasses supply the raw log lines via _raw_log_lines(): Vasplog reads them from a file, Outcar reuses the text already slurped by pymatgen.

MAX_SIZE = 10000000
VASP_LOG_FILES = ['slurm.+', 'stdout', 'OUTCAR', 'vasp.out']
VASP_PROGRESS = {'00SCF': ['DAV:.+'], '01relax': ['step:.+harm=.+dis=.+next Energy=.+dE=.+', 'opt step +=.+harmonic.+distance.+', 'next E +=.+d E +=.+', 'BRION:.+', 'g.Force. *= .+g.Stress.=.+']}
VASP_WARNINGS = {'__context': {'kpoints_parser': 3, 'mag_init': 1, 'vasp_runtime_error': 2, 'zbrent': 2}, '__exclude': [' *kinetic energy error for atom=.+'], '__extra_message': {'brions': ['The system may be oscilating. Consider smaller POTIM or changing to IBRION=2 or 3'], 'brmix': ['This is expected to happen once in charged systems'], 'dentet': ['This error can occur in metallic systems where band occupancy cannot be uniquely solved.  Or when KPOINTS are pointing to the same band (e.g. in 1D structures).'], 'slurm_error': ['VASP crashed.  Possible causes: time limit exceeded, not enough memory, VASP bug, cluster problem'], 'subspacematrix': ['As long as converged, should not affect final energy']}, 'algo_tet': ['ALGO=A and IALGO=5X tend to fail'], 'amin': ['One of the lattice vectors is very long (>50 A), but AMIN'], 'auto_nbands': ['The number of bands has been changed'], 'bravais': ['Inconsistent Bravais lattice'], 'brions': ['BRIONS problems: POTIM should be increased'], 'brmix': ['BRMIX: very serious problems'], 'canceled': ['JOB [0-9]+ ON [0-9a-z]+ CANCELLED AT'], 'coef': ['while reading plane', 'while reading WAVECAR'], 'dentet': ['DENTET'], 'dfpt_ncore': ['PEAD routines do not work for NCORE', 'remove the tag NPAR from the INCAR file'], 'edddav': ['Error EDDDAV: Call to ZHEGV failed'], 'eddiag': ['ERROR in EDDIAG: call to ZHEEV/ZHEEVX/DSYEV/DSYEVX failed'], 'eddrmm': ['WARNING in EDDRMM: call to ZHEGV failed'], 'electron_convergance': ['The electronic self-consistency was not achieved in the given'], 'elf_kpar': ['ELF: KPAR>1 not implemented'], 'elf_ncl': ['WARNING: ELF not implemented for non collinear case'], 'fexcf': ['ERROR FEXCF: supplied exchange-correlation table'], 'fortran_runtime_error': ['Fortran runtime error'], 'grad_not_orth': ['EDWAV: internal error, the gradient is not orthogonal'], 'hnform': ['HNFORM: k-point generating'], 'ibzkpt': ['IBZKPT: unable to construct a generating k-lattice suitable for use'], 'incorrect_shift': ['Could not get correct shifts'], 'inv_rot_mat': ['rotation matrix was not found (increase SYMPREC)'], 'kpoints_parser': ['Error reading KPOINTS file'], 'ksymm': ['Fatal error detecting k-mesh', 'Fatal error: unable to match k-point'], 'nbands_not_sufficient': ['number of bands is not sufficient'], 'nicht_konv': ['ERROR: SBESSELITER : nicht konvergent'], 'pdsyevx': ['ERROR in subspace rotation PDSYEVX'], 'point_group': ['group operation missing'], 'posmap': ['POSMAP'], 'pricel': ['internal error in subroutine PRICEL'], 'pricelv': ['PRICELV: current lattice and primitive lattice are incommensurate'], 'pssyevx': ['ERROR in subspace rotation PSSYEVX'], 'read_error': ['Error reading item', 'Error code was IERR= 5'], 'real_optlay': ['REAL_OPTLAY: internal error', 'REAL_OPT: internal ERROR'], 'rhosyg': ['RHOSYG'], 'rot_matrix': ['Found some non-integer element in rotation matrix', 'SGRCON'], 'rspher': ['ERROR RSPHER'], 'set_core_wf': ['internal error in SET_CORE_WF'], 'slurm_error': ['slurmstepd: error', 'prterun noticed', 'srun: error'], 'subspacematrix': ['WARNING: Sub-Space-Matrix is not hermitian in DAV'], 'symprec_noise': ['determination of the symmetry of your systems shows a strong'], 'tet': ['Tetrahedron method fails', 'tetrahedron method fails', 'Routine TETIRR needs special values', 'Tetrahedron method fails (number of k-points < 4)'], 'tetirr': ['Routine TETIRR needs special values'], 'time_limit': ['JOB [0-9]+ ON [0-9a-z]+ CANCELLED AT [^ ]+ DUE TO TIME LIMIT'], 'too_few_bands': ['TOO FEW BANDS'], 'triple_product': ['ERROR: the triple product of the basis vectors'], 'unclassified': ['error'], 'vasp_bug': ['Please submit a bug report.'], 'vasp_runtime_error': ['Error termination'], 'zbrent': ['ZBRENT: fatal internal in', 'ZBRENT: fatal error in bracketing', 'ZBRENT:  can not reach accuracy'], 'zheev': ['ERROR EDDIAG: Call to routine ZHEEV failed!'], 'zpotrf': ['LAPACK: Routine ZPOTRF failed', 'Routine ZPOTRF ZTRTRI']}
classmethod from_dir(dirname)[source]

Parse all log files found in a directory.

Parameters:

dirname (str | Path) – Directory to search for VASP log files.

Returns:

One Vasplog instance per log file found.

Return type:

list[Vasplog]

parse(log_matchers)[source]

Parse log lines against the given matcher dictionary.

Parameters:

log_matchers

Dictionary of {name: [regexp, ...]} defining patterns to search for. May also contain special keys:

  • __exclude: list of regexps to exclude (false positives).

  • __context: {name: n_lines} of extra context lines.

  • __extra_message: {name: [tip_line, ...]} of explanatory messages.

Returns:

{name: VaspWarningRecord} where name is the log type and the record carries message, tips and count.

Return type:

VaspWarnings

property progress: VaspWarnings

Parsed progress messages.

Returns:

Name-keyed progress records. See VASP_PROGRESS for the full list of recognised progress types.

Return type:

VaspWarnings

classmethod vasp_log_files(path)[source]

Find VASP log files in a directory.

Files are sorted by modification time. OUTCAR is excluded unless no other log file is found (to avoid reading large files).

Parameters:

path (str | Path) – Directory to search.

Returns:

Sorted list of matching file paths. Empty list if no log files are found or path is not a directory.

Return type:

list[str]

property warnings: VaspWarnings

Parsed warning records.

Returns:

Name-keyed warning records. See VASP_WARNINGS for the full list of recognised warning types.

Return type:

VaspWarnings

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, separate_spins=False, exception_on_bad_xml=True)[source]

Bases: Vasprun

Modified version of pymatgen’s Vasprun class.

Adds checks for stress, forces, and energy accuracy when non-trivial ISIF values are used.

Initialize a Vasprun.

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. Note that the DOS output from VASP is rounded to 4 decimal places, which can give some slight inaccuracies.

  • 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 and magnetization. Defaults to False. Set to True to obtain projected eigenvalues and magnetization. Note that this can take an extreme amount of time and memory. So use this wisely.

  • parse_potcar_file (bool | PathLike) – 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 path is provided, look at that path.

  • 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.

  • separate_spins (bool) – Whether the band gap, CBM, and VBM should be reported for each individual spin channel. Defaults to False, which computes the eigenvalue band properties independent of the spin orientation. If True, the calculation must be spin-polarized.

  • 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.

PRESSURE_CONVERGENCE_THRESHOLD = 3
check_forces(threshold=0.05)[source]

Check residual forces, respecting selective dynamics.

Only force components in unconstrained directions are considered when selective dynamics information is available.

Parameters:

threshold – Force threshold in eV/Angstrom.

Returns:

True if all forces are below threshold.

Return type:

bool

check_stress()[source]

Check whether the residual hydrostatic stress is acceptable.

Returns:

True if the hydrostatic stress is below PRESSURE_CONVERGENCE_THRESHOLD. Records a stress_convergence warning and emits VaspWarning otherwise.

Return type:

bool

property converged_ionic: bool

Whether ionic convergence was reached.

Wraps pymatgen’s version but additionally checks stress and forces when ISIF is non-trivial.

property final_energy: float

Final energy from the VASP run.

Records an energy-accuracy warning when the energy may be inaccurate due to relaxation with ISIF values that change cell shape or volume.

property warnings: VaspWarnings

Structured warnings collected for this run.

On first access, runs the derived accuracy checks (energy, stress, forces) and returns their records. Accessing final_energy, check_stress, or check_forces directly also populates the container.

This module implements useful VASP input sets to be used for the group research.

class IMDDerivedInputSet(structure=<property object>, config_dict=<factory>, files_to_transfer=<factory>, user_incar_settings=<factory>, user_kpoints_settings=<factory>, user_potcar_settings=<factory>, constrain_total_magmom=False, sort_structure=True, user_potcar_functional=None, force_gamma=False, reduce_structure=None, vdw=None, use_structure_charge=False, standardize=False, sym_prec=0.1, international_monoclinic=True, validate_magmom=True, inherit_incar=False, auto_kspacing=False, auto_ismear=False, auto_ispin=False, auto_lreal=False, auto_metal_kpoints=False, bandgap_tol=0.0001, bandgap=None, prev_incar=None, prev_kpoints=None, _valid_potcars=None, functional=None, images=None, name=None, no_kpoints=False, no_potcar=False, no_poscar=False, no_incar=False, directory=None, force_prev_incar_file=False, force_prev_kpoints_file=False, inherit_prev_incarpy=False)[source]

Bases: IMDVaspInputSet

Input set derived from an existing VASP output or input directory.

Unlike plain IMDVaspInputSet, this class inherits settings (INCAR, KPOINTS, POTCAR, structure) from a previous calculation.

Key additions:

  • directory (mandatory): Source directory with VASP output/input.

  • force_prev_incar_file: When True, discard INCAR settings from vasprun.xml if no actual INCAR file is present.

  • force_prev_kpoints_file: Same for KPOINTS.

  • inherit_prev_incarpy: When True, copy INCAR.py from source.

  • INCAR.[0-9]* files are always copied (used by gorun workflows).

Parameters:
  • structure (Structure | None)

  • config_dict (dict)

  • files_to_transfer (dict)

  • user_incar_settings (dict)

  • user_kpoints_settings (dict)

  • user_potcar_settings (dict)

  • constrain_total_magmom (bool)

  • sort_structure (bool)

  • user_potcar_functional (UserPotcarFunctional)

  • force_gamma (bool)

  • reduce_structure (Literal['niggli', 'LLL'] | None)

  • vdw (str | None)

  • use_structure_charge (bool)

  • standardize (bool)

  • sym_prec (float)

  • international_monoclinic (bool)

  • validate_magmom (bool)

  • inherit_incar (bool | list[str])

  • auto_kspacing (bool)

  • auto_ismear (bool)

  • auto_ispin (bool)

  • auto_lreal (bool)

  • auto_metal_kpoints (bool)

  • bandgap_tol (float)

  • bandgap (float | None)

  • prev_incar (str | dict | None)

  • prev_kpoints (str | Kpoints | None)

  • _valid_potcars (Sequence[str] | None)

  • functional (str | None)

  • images (list[Self] | None)

  • name (str | None)

  • no_kpoints (bool)

  • no_potcar (bool)

  • no_poscar (bool)

  • no_incar (bool)

  • directory (str | None)

  • force_prev_incar_file (bool)

  • force_prev_kpoints_file (bool)

  • inherit_prev_incarpy (bool)

directory: str | None = None
force_prev_incar_file: bool = False
force_prev_kpoints_file: bool = False
images: list[Self] | None = None
property incar

INCAR for the derived input set.

Returns None when force_prev_incar_file is True and the previous directory has no INCAR file.

inherit_prev_incarpy: bool = False
property kpoints

KPOINTS for the derived input set.

Returns None when force_prev_kpoints_file is True and the previous directory has no KPOINTS file, or when the previous INCAR uses KSPACING.

property kpoints_updates

KPOINTS updates, preferring prev_kpoints unconditionally.

class IMDGraphite(structure=<property object>, config_dict=<factory>, files_to_transfer=<factory>, user_incar_settings=<factory>, user_kpoints_settings=<factory>, user_potcar_settings=<factory>, constrain_total_magmom=False, sort_structure=True, user_potcar_functional=None, force_gamma=True, reduce_structure=None, vdw=None, use_structure_charge=False, standardize=False, sym_prec=0.1, international_monoclinic=True, validate_magmom=True, inherit_incar=False, auto_kspacing=False, auto_ismear=False, auto_ispin=False, auto_lreal=False, auto_metal_kpoints=False, bandgap_tol=0.0001, bandgap=None, prev_incar=None, prev_kpoints=None, _valid_potcars=None)[source]

Bases: VaspInputSet

SCF input set for graphite (mp-48 from Materials Project).

Parameters:
  • user_kpoints_settings (dict) – Optional dict or Kpoints object to override k-point settings.

  • structure (Structure | None)

  • config_dict (dict)

  • files_to_transfer (dict)

  • user_incar_settings (dict)

  • user_potcar_settings (dict)

  • constrain_total_magmom (bool)

  • sort_structure (bool)

  • user_potcar_functional (UserPotcarFunctional)

  • force_gamma (bool)

  • reduce_structure (Literal['niggli', 'LLL'] | None)

  • vdw (str | None)

  • use_structure_charge (bool)

  • standardize (bool)

  • sym_prec (float)

  • international_monoclinic (bool)

  • validate_magmom (bool)

  • inherit_incar (bool | list[str])

  • auto_kspacing (bool)

  • auto_ismear (bool)

  • auto_ispin (bool)

  • auto_lreal (bool)

  • auto_metal_kpoints (bool)

  • bandgap_tol (float)

  • bandgap (float | None)

  • prev_incar (str | dict | None)

  • prev_kpoints (str | Kpoints | None)

  • _valid_potcars (Sequence[str] | None)

CONFIG = {'INCAR': {'ENCUT': 900.0, 'ISMEAR': -5, 'IVDW': 20, 'LVDW_EWALD': True, 'PREC': 'Accurate', 'SIGMA': 0.01}, 'KPOINTS': {'grid_density': 10000}, 'POTCAR': {'C': 'C'}, 'POTCAR_FUNCTIONAL': 'PBE_64'}
force_gamma: bool = True
class IMDNEBVaspInputSet(structure=<property object>, config_dict=<factory>, files_to_transfer=<factory>, user_incar_settings=<factory>, user_kpoints_settings=<factory>, user_potcar_settings=<factory>, constrain_total_magmom=False, sort_structure=True, user_potcar_functional=None, force_gamma=False, reduce_structure=None, vdw=None, use_structure_charge=False, standardize=False, sym_prec=0.1, international_monoclinic=True, validate_magmom=True, inherit_incar=False, auto_kspacing=False, auto_ismear=False, auto_ispin=False, auto_lreal=False, auto_metal_kpoints=False, bandgap_tol=0.0001, bandgap=None, prev_incar=None, prev_kpoints=None, _valid_potcars=None, functional=None, images=None, name=None, no_kpoints=False, no_potcar=False, no_poscar=False, no_incar=False, directory=None, force_prev_incar_file=False, force_prev_kpoints_file=False, inherit_prev_incarpy=False, target_directory=None, fix_cutoff=None, frac_tol=0.5, method='IDPP')[source]

Bases: IMDDerivedInputSet

Input set for NEB (Nudged Elastic Band) calculations.

Requires two directories: the source (directory) and the target (target_directory) containing well-converged VASP outputs for the initial and final structures.

References

IDPP: S. Smidstrup et al., J. Chem. Phys. 140, 214106 (2014).

Parameters:
  • structure (Structure | None)

  • config_dict (dict)

  • files_to_transfer (dict)

  • user_incar_settings (dict)

  • user_kpoints_settings (dict)

  • user_potcar_settings (dict)

  • constrain_total_magmom (bool)

  • sort_structure (bool)

  • user_potcar_functional (UserPotcarFunctional)

  • force_gamma (bool)

  • reduce_structure (Literal['niggli', 'LLL'] | None)

  • vdw (str | None)

  • use_structure_charge (bool)

  • standardize (bool)

  • sym_prec (float)

  • international_monoclinic (bool)

  • validate_magmom (bool)

  • inherit_incar (bool | list[str])

  • auto_kspacing (bool)

  • auto_ismear (bool)

  • auto_ispin (bool)

  • auto_lreal (bool)

  • auto_metal_kpoints (bool)

  • bandgap_tol (float)

  • bandgap (float | None)

  • prev_incar (str | dict | None)

  • prev_kpoints (str | Kpoints | None)

  • _valid_potcars (Sequence[str] | None)

  • functional (str | None)

  • images (list[Self] | None)

  • name (str | None)

  • no_kpoints (bool)

  • no_potcar (bool)

  • no_poscar (bool)

  • no_incar (bool)

  • directory (str | None)

  • force_prev_incar_file (bool)

  • force_prev_kpoints_file (bool)

  • inherit_prev_incarpy (bool)

  • target_directory (str | None)

  • fix_cutoff (float | None)

  • frac_tol (float)

  • method (str)

CONFIG = {'INCAR': {'IBRION': 1, 'IMAGES': 5, 'SPRING': -5}, 'POTCAR_FUNCTIONAL': 'PBE_64'}
fix_cutoff: float | None = None
frac_tol: float = 0.5
property incar: Incar

INCAR for the NEB run.

Warns when IMAGES=0 or IBRION != 1, and forces IBRION=1 (required for NEB in VASP).

method: str = 'IDPP'
target_directory: str | None = None
update_images(beg=None, end=None, **kwargs)[source]

Update NEB images by interpolating between start and end structures.

Parameters:
write_input(output_dir, **kwargs)[source]

Write NEB input files to a directory.

In addition to standard behaviour, writes a NEB-inputs.txt file recording the initial and final image source directories.

Parameters:
  • output_dir – Target directory for the input files.

  • **kwargs – Forwarded to VaspInputSet.write_input.

Return type:

None

exception IMDNEBVaspInputSetWarning[source]

Bases: UserWarning

Warning emitted by IMDNEBVaspInputSet.

class IMDRelaxCellulose(structure=<property object>, config_dict=<factory>, files_to_transfer=<factory>, user_incar_settings=<factory>, user_kpoints_settings=<factory>, user_potcar_settings=<factory>, constrain_total_magmom=False, sort_structure=True, user_potcar_functional=None, force_gamma=True, reduce_structure=None, vdw=None, use_structure_charge=False, standardize=False, sym_prec=0.1, international_monoclinic=True, validate_magmom=True, inherit_incar=False, auto_kspacing=False, auto_ismear=False, auto_ispin=False, auto_lreal=False, auto_metal_kpoints=False, bandgap_tol=0.0001, bandgap=None, prev_incar=None, prev_kpoints=None, _valid_potcars=None)[source]

Bases: VaspInputSet

Relaxation input set for cellulose.

Parameters:
  • structure (Structure | None) – A Structure object, or the strings "ialpha" or "ibeta" for the corresponding cellulose phase.

  • user_kpoints_settings (dict) – Optional dict or Kpoints object to override k-point settings.

  • config_dict (dict)

  • files_to_transfer (dict)

  • user_incar_settings (dict)

  • user_potcar_settings (dict)

  • constrain_total_magmom (bool)

  • sort_structure (bool)

  • user_potcar_functional (UserPotcarFunctional)

  • force_gamma (bool)

  • reduce_structure (Literal['niggli', 'LLL'] | None)

  • vdw (str | None)

  • use_structure_charge (bool)

  • standardize (bool)

  • sym_prec (float)

  • international_monoclinic (bool)

  • validate_magmom (bool)

  • inherit_incar (bool | list[str])

  • auto_kspacing (bool)

  • auto_ismear (bool)

  • auto_ispin (bool)

  • auto_lreal (bool)

  • auto_metal_kpoints (bool)

  • bandgap_tol (float)

  • bandgap (float | None)

  • prev_incar (str | dict | None)

  • prev_kpoints (str | Kpoints | None)

  • _valid_potcars (Sequence[str] | None)

References

Yadav, A., Bostroem, M. & Malyi, O.I. Understanding of dielectric properties of cellulose. Cellulose 31, 2783-2794 (2024). https://doi.org/10.1007/s10570-024-05754-7

CONFIG = {'INCAR': {'EDIFFG': -0.01, 'ENCUT': 550.0, 'IBRION': 2, 'ISIF': 4, 'NSW': 99}, 'KPOINTS': {'grid_density': 5000}, 'POTCAR': {'C': 'C', 'H': 'H', 'O': 'O'}, 'POTCAR_FUNCTIONAL': 'PBE_64'}
force_gamma: bool = True
class IMDStandardVaspInputSet(structure=<property object>, config_dict=<factory>, files_to_transfer=<factory>, user_incar_settings=<factory>, user_kpoints_settings=<factory>, user_potcar_settings=<factory>, constrain_total_magmom=False, sort_structure=True, user_potcar_functional=None, force_gamma=False, reduce_structure=None, vdw=None, use_structure_charge=False, standardize=False, sym_prec=0.1, international_monoclinic=True, validate_magmom=True, inherit_incar=False, auto_kspacing=False, auto_ismear=False, auto_ispin=False, auto_lreal=False, auto_metal_kpoints=False, bandgap_tol=0.0001, bandgap=None, prev_incar=None, prev_kpoints=None, _valid_potcars=None, functional=None, images=None, name=None, no_kpoints=False, no_potcar=False, no_poscar=False, no_incar=False)[source]

Bases: IMDVaspInputSet

Standard input set for IMDGroup.

Uses VASP-recommended potentials from ASE by default. Potentials do not need to be specified explicitly.

Parameters:
  • structure (Structure | None)

  • config_dict (dict)

  • files_to_transfer (dict)

  • user_incar_settings (dict)

  • user_kpoints_settings (dict)

  • user_potcar_settings (dict)

  • constrain_total_magmom (bool)

  • sort_structure (bool)

  • user_potcar_functional (UserPotcarFunctional)

  • force_gamma (bool)

  • reduce_structure (Literal['niggli', 'LLL'] | None)

  • vdw (str | None)

  • use_structure_charge (bool)

  • standardize (bool)

  • sym_prec (float)

  • international_monoclinic (bool)

  • validate_magmom (bool)

  • inherit_incar (bool | list[str])

  • auto_kspacing (bool)

  • auto_ismear (bool)

  • auto_ispin (bool)

  • auto_lreal (bool)

  • auto_metal_kpoints (bool)

  • bandgap_tol (float)

  • bandgap (float | None)

  • prev_incar (str | dict | None)

  • prev_kpoints (str | Kpoints | None)

  • _valid_potcars (Sequence[str] | None)

  • functional (str | None)

  • images (list[Self] | None)

  • name (str | None)

  • no_kpoints (bool)

  • no_potcar (bool)

  • no_poscar (bool)

  • no_incar (bool)

CONFIG = {'INCAR': {'ALGO': 'Normal', 'ENCUT': 500.0, 'ISMEAR': 0, 'LCHARG': False, 'LWAVE': False, 'NCORE': 16, 'NELMIN': 6, 'SIGMA': 0.04}, 'KPOINTS': {'grid_density': 10000}, 'POTCAR': {'At': 'At_d', 'Ba': 'Ba_sv', 'Bi': 'Bi_d', 'Ca': 'Ca_sv', 'Cr': 'Cr_pv', 'Cs': 'Cs_sv', 'Dy': 'Dy_3', 'Er': 'Er_3', 'Eu': 'Eu_2', 'Fr': 'Fr_sv', 'Ga': 'Ga_d', 'Gd': 'Gd_3', 'Ge': 'Ge_d', 'Hf': 'Hf_pv', 'Ho': 'Ho_3', 'In': 'In_d', 'K': 'K_sv', 'Li': 'Li_sv', 'Lu': 'Lu_3', 'Mn': 'Mn_pv', 'Mo': 'Mo_sv', 'Na': 'Na_pv', 'Nb': 'Nb_sv', 'Nd': 'Nd_3', 'Pb': 'Pb_d', 'Pm': 'Pm_3', 'Po': 'Po_d', 'Pr': 'Pr_3', 'Ra': 'Ra_sv', 'Rb': 'Rb_sv', 'Rh': 'Rh_pv', 'Ru': 'Ru_pv', 'Sc': 'Sc_sv', 'Sm': 'Sm_3', 'Sn': 'Sn_d', 'Sr': 'Sr_sv', 'Ta': 'Ta_pv', 'Tb': 'Tb_3', 'Tc': 'Tc_pv', 'Ti': 'Ti_sv', 'Tl': 'Tl_d', 'Tm': 'Tm_3', 'V': 'V_sv', 'W': 'W_sv', 'Y': 'Y_sv', 'Yb': 'Yb_2', 'Zr': 'Zr_sv'}, 'POTCAR_FUNCTIONAL': 'PBE_64'}
class IMDStandardVaspInputSet_relax(structure=<property object>, config_dict=<factory>, files_to_transfer=<factory>, user_incar_settings=<factory>, user_kpoints_settings=<factory>, user_potcar_settings=<factory>, constrain_total_magmom=False, sort_structure=True, user_potcar_functional=None, force_gamma=False, reduce_structure=None, vdw=None, use_structure_charge=False, standardize=False, sym_prec=0.1, international_monoclinic=True, validate_magmom=True, inherit_incar=False, auto_kspacing=False, auto_ismear=False, auto_ispin=False, auto_lreal=False, auto_metal_kpoints=False, bandgap_tol=0.0001, bandgap=None, prev_incar=None, prev_kpoints=None, _valid_potcars=None, functional=None, images=None, name=None, no_kpoints=False, no_potcar=False, no_poscar=False, no_incar=False)[source]

Bases: IMDStandardVaspInputSet

Standard input set for IMDGroup relaxation runs.

Sets defaults for EDIFF, EDIFFG, ISTART, and NSW suitable for geometry optimization.

Parameters:
  • structure (Structure | None)

  • config_dict (dict)

  • files_to_transfer (dict)

  • user_incar_settings (dict)

  • user_kpoints_settings (dict)

  • user_potcar_settings (dict)

  • constrain_total_magmom (bool)

  • sort_structure (bool)

  • user_potcar_functional (UserPotcarFunctional)

  • force_gamma (bool)

  • reduce_structure (Literal['niggli', 'LLL'] | None)

  • vdw (str | None)

  • use_structure_charge (bool)

  • standardize (bool)

  • sym_prec (float)

  • international_monoclinic (bool)

  • validate_magmom (bool)

  • inherit_incar (bool | list[str])

  • auto_kspacing (bool)

  • auto_ismear (bool)

  • auto_ispin (bool)

  • auto_lreal (bool)

  • auto_metal_kpoints (bool)

  • bandgap_tol (float)

  • bandgap (float | None)

  • prev_incar (str | dict | None)

  • prev_kpoints (str | Kpoints | None)

  • _valid_potcars (Sequence[str] | None)

  • functional (str | None)

  • images (list[Self] | None)

  • name (str | None)

  • no_kpoints (bool)

  • no_potcar (bool)

  • no_poscar (bool)

  • no_incar (bool)

CONFIG = {'INCAR': {'ALGO': 'Normal', 'EDIFF': 1e-06, 'EDIFFG': -0.01, 'ENCUT': 500.0, 'ISMEAR': 0, 'ISTART': 0, 'LCHARG': False, 'LWAVE': False, 'NCORE': 16, 'NELMIN': 6, 'NSW': 500, 'SIGMA': 0.04}, 'KPOINTS': {'grid_density': 10000}, 'POTCAR': {'At': 'At_d', 'Ba': 'Ba_sv', 'Bi': 'Bi_d', 'Ca': 'Ca_sv', 'Cr': 'Cr_pv', 'Cs': 'Cs_sv', 'Dy': 'Dy_3', 'Er': 'Er_3', 'Eu': 'Eu_2', 'Fr': 'Fr_sv', 'Ga': 'Ga_d', 'Gd': 'Gd_3', 'Ge': 'Ge_d', 'Hf': 'Hf_pv', 'Ho': 'Ho_3', 'In': 'In_d', 'K': 'K_sv', 'Li': 'Li_sv', 'Lu': 'Lu_3', 'Mn': 'Mn_pv', 'Mo': 'Mo_sv', 'Na': 'Na_pv', 'Nb': 'Nb_sv', 'Nd': 'Nd_3', 'Pb': 'Pb_d', 'Pm': 'Pm_3', 'Po': 'Po_d', 'Pr': 'Pr_3', 'Ra': 'Ra_sv', 'Rb': 'Rb_sv', 'Rh': 'Rh_pv', 'Ru': 'Ru_pv', 'Sc': 'Sc_sv', 'Sm': 'Sm_3', 'Sn': 'Sn_d', 'Sr': 'Sr_sv', 'Ta': 'Ta_pv', 'Tb': 'Tb_3', 'Tc': 'Tc_pv', 'Ti': 'Ti_sv', 'Tl': 'Tl_d', 'Tm': 'Tm_3', 'V': 'V_sv', 'W': 'W_sv', 'Y': 'Y_sv', 'Yb': 'Yb_2', 'Zr': 'Zr_sv'}, 'POTCAR_FUNCTIONAL': 'PBE_64'}
class IMDStandardVaspInputSet_scf(structure=<property object>, config_dict=<factory>, files_to_transfer=<factory>, user_incar_settings=<factory>, user_kpoints_settings=<factory>, user_potcar_settings=<factory>, constrain_total_magmom=False, sort_structure=True, user_potcar_functional=None, force_gamma=False, reduce_structure=None, vdw=None, use_structure_charge=False, standardize=False, sym_prec=0.1, international_monoclinic=True, validate_magmom=True, inherit_incar=False, auto_kspacing=False, auto_ismear=False, auto_ispin=False, auto_lreal=False, auto_metal_kpoints=False, bandgap_tol=0.0001, bandgap=None, prev_incar=None, prev_kpoints=None, _valid_potcars=None, functional=None, images=None, name=None, no_kpoints=False, no_potcar=False, no_poscar=False, no_incar=False)[source]

Bases: IMDStandardVaspInputSet

Standard input set for IMDGroup SCF (static) runs.

Sets NSW=0, IBRION=-1, ISMEAR=-5 (tetrahedron method) as recommended for accurate total energies.

Parameters:
  • structure (Structure | None)

  • config_dict (dict)

  • files_to_transfer (dict)

  • user_incar_settings (dict)

  • user_kpoints_settings (dict)

  • user_potcar_settings (dict)

  • constrain_total_magmom (bool)

  • sort_structure (bool)

  • user_potcar_functional (UserPotcarFunctional)

  • force_gamma (bool)

  • reduce_structure (Literal['niggli', 'LLL'] | None)

  • vdw (str | None)

  • use_structure_charge (bool)

  • standardize (bool)

  • sym_prec (float)

  • international_monoclinic (bool)

  • validate_magmom (bool)

  • inherit_incar (bool | list[str])

  • auto_kspacing (bool)

  • auto_ismear (bool)

  • auto_ispin (bool)

  • auto_lreal (bool)

  • auto_metal_kpoints (bool)

  • bandgap_tol (float)

  • bandgap (float | None)

  • prev_incar (str | dict | None)

  • prev_kpoints (str | Kpoints | None)

  • _valid_potcars (Sequence[str] | None)

  • functional (str | None)

  • images (list[Self] | None)

  • name (str | None)

  • no_kpoints (bool)

  • no_potcar (bool)

  • no_poscar (bool)

  • no_incar (bool)

CONFIG = {'INCAR': {'ALGO': 'Normal', 'ENCUT': 500.0, 'IBRION': -1, 'ISMEAR': -5, 'LCHARG': False, 'LWAVE': False, 'NCORE': 16, 'NELMIN': 6, 'NSW': 0, 'SIGMA': 0.04}, 'KPOINTS': {'grid_density': 10000}, 'POTCAR': {'At': 'At_d', 'Ba': 'Ba_sv', 'Bi': 'Bi_d', 'Ca': 'Ca_sv', 'Cr': 'Cr_pv', 'Cs': 'Cs_sv', 'Dy': 'Dy_3', 'Er': 'Er_3', 'Eu': 'Eu_2', 'Fr': 'Fr_sv', 'Ga': 'Ga_d', 'Gd': 'Gd_3', 'Ge': 'Ge_d', 'Hf': 'Hf_pv', 'Ho': 'Ho_3', 'In': 'In_d', 'K': 'K_sv', 'Li': 'Li_sv', 'Lu': 'Lu_3', 'Mn': 'Mn_pv', 'Mo': 'Mo_sv', 'Na': 'Na_pv', 'Nb': 'Nb_sv', 'Nd': 'Nd_3', 'Pb': 'Pb_d', 'Pm': 'Pm_3', 'Po': 'Po_d', 'Pr': 'Pr_3', 'Ra': 'Ra_sv', 'Rb': 'Rb_sv', 'Rh': 'Rh_pv', 'Ru': 'Ru_pv', 'Sc': 'Sc_sv', 'Sm': 'Sm_3', 'Sn': 'Sn_d', 'Sr': 'Sr_sv', 'Ta': 'Ta_pv', 'Tb': 'Tb_3', 'Tc': 'Tc_pv', 'Ti': 'Ti_sv', 'Tl': 'Tl_d', 'Tm': 'Tm_3', 'V': 'V_sv', 'W': 'W_sv', 'Y': 'Y_sv', 'Yb': 'Yb_2', 'Zr': 'Zr_sv'}, 'POTCAR_FUNCTIONAL': 'PBE_64'}
class IMDVaspInputSet(structure=<property object>, config_dict=<factory>, files_to_transfer=<factory>, user_incar_settings=<factory>, user_kpoints_settings=<factory>, user_potcar_settings=<factory>, constrain_total_magmom=False, sort_structure=True, user_potcar_functional=None, force_gamma=False, reduce_structure=None, vdw=None, use_structure_charge=False, standardize=False, sym_prec=0.1, international_monoclinic=True, validate_magmom=True, inherit_incar=False, auto_kspacing=False, auto_ismear=False, auto_ispin=False, auto_lreal=False, auto_metal_kpoints=False, bandgap_tol=0.0001, bandgap=None, prev_incar=None, prev_kpoints=None, _valid_potcars=None, functional=None, images=None, name=None, no_kpoints=False, no_potcar=False, no_poscar=False, no_incar=False)[source]

Bases: VaspInputSet

IMDGroup variant of VaspInputSet.

Key additions over pymatgen’s VaspInputSet:

  1. functional argument for specifying the exchange-correlation functional (see functionals.yaml).

  2. Automatic SYSTEM name generation from formula, lattice type, and space group.

  3. Structure and input validation (warnings for KPOINTS density, low ENCUT, conflicting NCORE/NPAR).

  4. Default POTCAR_FUNCTIONAL PBE_64.

  5. Visualization of non-trivial selective dynamics as a CIF file.

  6. images argument for NEB input sets (writes 00, 01, … subdirectories).

  7. no_kpoints, no_potcar, no_poscar, no_incar flags to suppress writing individual files.

Parameters:
  • structure (Structure | None)

  • config_dict (dict)

  • files_to_transfer (dict)

  • user_incar_settings (dict)

  • user_kpoints_settings (dict)

  • user_potcar_settings (dict)

  • constrain_total_magmom (bool)

  • sort_structure (bool)

  • user_potcar_functional (UserPotcarFunctional)

  • force_gamma (bool)

  • reduce_structure (Literal['niggli', 'LLL'] | None)

  • vdw (str | None)

  • use_structure_charge (bool)

  • standardize (bool)

  • sym_prec (float)

  • international_monoclinic (bool)

  • validate_magmom (bool)

  • inherit_incar (bool | list[str])

  • auto_kspacing (bool)

  • auto_ismear (bool)

  • auto_ispin (bool)

  • auto_lreal (bool)

  • auto_metal_kpoints (bool)

  • bandgap_tol (float)

  • bandgap (float | None)

  • prev_incar (str | dict | None)

  • prev_kpoints (str | Kpoints | None)

  • _valid_potcars (Sequence[str] | None)

  • functional (str | None)

  • images (list[Self] | None)

  • name (str | None)

  • no_kpoints (bool)

  • no_potcar (bool)

  • no_poscar (bool)

  • no_incar (bool)

CONFIG = {'INCAR': {}, 'POTCAR_FUNCTIONAL': 'PBE_64'}
functional: str | None = None
images: list[Self] | None = None
property incar: Incar | None

INCAR for the input set.

Automatically derives a SYSTEM name from formula, lattice type, and space group. Warns about low ENCUT settings and when both NCORE and NPAR are set.

property incar_updates: dict

INCAR updates derived from the functional choice.

property kpoints: Kpoints | None

KPOINTS for the input set.

When no_kpoints is True, returns None. Otherwise warns if the KPOINTS density is below 5000 or above 15000 k-points/atom.

name: str | None = None
no_incar: bool = False
no_kpoints: bool = False
no_poscar: bool = False
no_potcar: bool = False
property poscar: Poscar

POSCAR for the input set.

Validates the structure before generating the POSCAR.

property potcar: Potcar | None

POTCAR for the input set.

When no_potcar is True, returns None.

property potcar_symbols: list[str] | None

List of POTCAR symbols.

Auto-fills missing element potentials using ASE-recommended defaults.

write_input(output_dir, **kwargs)[source]

Write VASP input files to a directory.

In addition to standard pymatgen behaviour, writes an IMDVaspInputSet.log file and, for NEB runs, writes the image subdirectories and a trajectory CIF.

Parameters:
  • output_dir – Target directory for the input files.

  • **kwargs – Forwarded to VaspInputSet.write_input.

Return type:

None

write_selective_dynamics_summary_maybe(structure, fname)[source]

Visualize site constraints and write a CIF file if non-trivial.

The CIF uses species substitution for visual cues: Fe = fully fixed, Co = partially fixed, Ni = not fixed, X = unknown.

Parameters:
  • structure – Structure with optional selective_dynamics site properties.

  • fname – Output filename for the CIF.

Returns:

True if the file was written (non-trivial constraints were found), False otherwise.

Return type:

bool

This module implements helper functions to work with ATAT.

check_sublattice_flip(str_before, str_after, sublattice)[source]

Check whether the relaxed sublattice configuration is preserved.

Returns True when str_after occupies the same sublattice configuration as str_before, when compared against the reference sublattice.

The species scanned by cluster expansion must be marked with the same dummy species name (e.g. X) in all arguments. For example, in an ATAT Li,Vac system, both Li and Vac should be replaced with X.

Parameters:
  • str_before (Structure) – Structure before relaxation.

  • str_after (Structure) – Structure after relaxation.

  • sublattice (Structure) – Full sublattice with all sites occupied (as in str.in).

Returns:

True if the sublattice configuration is preserved.

Return type:

bool

check_volume_distortion(str_before, str_after, threshold=0.1)[source]

Check whether lattice distortion between two structures is acceptable.

The distortion is the norm of the engineering strain tensor. A distortion below threshold is considered acceptable. The default threshold follows ATAT’s checkcell subroutine.

Parameters:
  • str_before (Structure) – Initial structure.

  • str_after (Structure) – Deformed structure.

  • threshold (float) – Max allowed distortion (default: 0.1).

Returns:

True if distortion is below threshold, False otherwise.

Return type:

bool

fit_sublattice_to_structure(sublattice, structure)[source]

Adjust a reference sublattice to match a relaxed structure.

Useful for building a new str.out when the structure has flipped away from the initial sublattice guess (see check_sublattice_flip()). Use 'X' dummy species in place of vacancies.

Parameters:
  • sublattice (Structure) – Reference sublattice (as from str.in).

  • structure (Structure) – Relaxed structure with possible sublattice flip.

Returns:

Adjusted sublattice matching the relaxed structure.

Return type:

Structure

Diffusion

NEB pair generator for diffusion paths.

class NEB_Graph(*args, backend=None, **kwargs)[source]

Bases: MultiDiGraph

Graph representing diffusion paths between structures.

Nodes are structure indices. Edges are diffusion paths with attributes distance, vector, and energy_barrier.

structures

List of Structure objects forming the graph nodes.

multithread

Whether to use multithreading for distance matrix.

jimage_idxs

Indices of sites for which periodic images are considered when computing displacement vectors.

Build a complete NEB diffusion graph.

All structures must share the same lattice and have one-to-one site correspondence.

When jimage_idxs is None, edges use the shortest distances between structures under periodic boundary conditions (self-self paths are ignored).

When jimage_idxs is provided, the specified site indices are used for generating multiple periodic images (range -1..1 in each direction), enabling self-self diffusion path discovery.

Parameters:
  • structures (list[Structure] | None) – List of structures forming the graph nodes.

  • jimage_idxs (list[int] | None) – Site indices for periodic image enumeration, or None for shortest-path only.

  • multithread (bool) – Whether to use multithreading for distance matrix computation.

__init__(structures=None, jimage_idxs=None, multithread=False)[source]

Build a complete NEB diffusion graph.

All structures must share the same lattice and have one-to-one site correspondence.

When jimage_idxs is None, edges use the shortest distances between structures under periodic boundary conditions (self-self paths are ignored).

When jimage_idxs is provided, the specified site indices are used for generating multiple periodic images (range -1..1 in each direction), enabling self-self diffusion path discovery.

Parameters:
  • structures (list[Structure] | None) – List of structures forming the graph nodes.

  • jimage_idxs (list[int] | None) – Site indices for periodic image enumeration, or None for shortest-path only.

  • multithread (bool) – Whether to use multithreading for distance matrix computation.

all_diffusion_paths_infinite(idxs=None)[source]

Check whether all given vertices are on infinite diffusion paths.

Structures with the same _orig_idx property are assumed symmetrically equivalent and checked only once.

Parameters:

idxs (list[int] | None) – Indices to check. Defaults to all vertices.

Returns:

True if all checked vertices are on infinite paths.

Return type:

bool

connected(idxs=None)[source]

Check whether the graph is connected.

Parameters:

idxs (list[int] | None) – When provided, only check connectivity of these vertex indices.

Returns:

True if all relevant vertices are reachable.

Return type:

bool

diffusion_path_infinite(start_idx)[source]

Check whether a vertex lies on an infinite diffusion path.

An infinite path is a cycle whose sum of displacement vectors is non-zero, meaning the diffusing atom can move without bound through the material.

Parameters:

start_idx – Vertex index to check.

Returns:

True if the vertex is on an infinite diffusion path.

Return type:

bool

get_min_cutoff(idx_connected=None)[source]

Find the smallest edge distance cutoff that keeps the graph connected.

Also requires that all vertices be on infinite diffusion paths after applying the cutoff.

Parameters:

idx_connected (list[int] | None) – Indices that must remain connected. Defaults to all vertices.

Returns:

Minimum distance cutoff in Angstrom that satisfies both connectivity and infinite-path constraints.

Return type:

float

get_neb_pairs(structures, prototype, cutoff=None, remove_compound=False, multithread=False, limit=None, return_unfiltered=False)[source]

Construct all unique diffusion NEB pairs from a set of structures.

The structures must share the same lattice and be derived from a common prototype structure. Symmetry operations of the prototype are applied to enumerate equivalent diffusion paths.

Parameters:
  • structures (list[Structure]) – Candidate structures (e.g. with interstitial atoms at various positions).

  • prototype (Structure) – Reference structure defining the host lattice and symmetry.

  • cutoff (float | None | str) – Maximum allowed displacement distance (Angstrom). When 'auto', the smallest cutoff that keeps all lowest-energy structures connected is determined automatically.

  • remove_compound (bool) – When True, remove paths that can be composed from shorter paths (heuristic simplification).

  • multithread (bool) – Whether to use multithreading.

  • limit (None | int) – Maximum number of unique NEB pairs.

  • return_unfiltered (bool) – When True, return both the filtered unique pairs and all (symmetry-unfiltered) pairs.

Returns:

Pairs of (start, end) structures for NEB calculations. When return_unfiltered is True, returns (unique_pairs, all_pairs).

Return type:

list[tuple[Structure, Structure]]

exception get_neb_pairs_warning[source]

Bases: UserWarning

Warning emitted during NEB pair generation.

Transformations

Insert molecules and atoms into a given structure.

class InsertMoleculeTransformation(molecule, step, step_noise=None, anglestep=None, proximity_threshold=0.75, label='insert', selective_dynamics=None, reduce_supercell=True, matcher=<pymatgen.core.structure_matcher.StructureMatcher object>, multithread=False)[source]

Bases: AbstractTransformation

Generate structures with a molecule or atom inserted at all possible sites.

Scans a grid of fractional coordinates (optionally with random offsets) and, for molecules, also rotates the molecule across a grid of Euler angles. Inserts that do not violate proximity constraints and are symmetrically distinct are kept.

molecule

Molecule or atom to insert.

step

Grid spacing in Angstrom.

step_noise

Standard deviation of grid noise, or negative for fully random sampling.

anglestep

Angular step in radians for molecule rotation.

proximity_threshold

Threshold multiplier for atomic radii.

label

Label prefix for inserted atoms.

selective_dynamics

Selective dynamics for inserted atoms.

reduce_supercell

Whether to reduce to the primitive cell first.

matcher

StructureMatcher for duplicate detection.

multithread

Whether to use multithreading.

Initialise the insertion transformation.

Parameters:
  • molecule (Molecule | str | Element | Species | DummySpecies) – Species, Molecule, or path to a molecule file.

  • step (float) – Grid spacing in Angstrom for insertion site search.

  • step_noise (float | None) – When a positive float, standard deviation of noise added to the grid (as a fraction of step). When negative, use fully random sampling with abs(step_noise) points.

  • anglestep (float | None) – Angular step in radians for molecule rotation. Must be None for single-atom insertions.

  • proximity_threshold (float) – Two atoms are considered too close when their distance is less than proximity_threshold * (r1 + r2).

  • label (str | None) – Prefix for atom labels in the inserted molecule. Each atom gets {label}-{element}{index}.

  • selective_dynamics (ArrayLike | None) – Selective dynamics array for inserted atoms (used only when the host structure also uses selective dynamics).

  • reduce_supercell (bool) – When True, reduce the host to its primitive cell before scanning.

  • matcher (StructureMatcher | None) – StructureMatcher for detecting duplicate insertions.

  • multithread – Whether to use multithreading.

__init__(molecule, step, step_noise=None, anglestep=None, proximity_threshold=0.75, label='insert', selective_dynamics=None, reduce_supercell=True, matcher=<pymatgen.core.structure_matcher.StructureMatcher object>, multithread=False)[source]

Initialise the insertion transformation.

Parameters:
  • molecule (Molecule | str | Element | Species | DummySpecies) – Species, Molecule, or path to a molecule file.

  • step (float) – Grid spacing in Angstrom for insertion site search.

  • step_noise (float | None) – When a positive float, standard deviation of noise added to the grid (as a fraction of step). When negative, use fully random sampling with abs(step_noise) points.

  • anglestep (float | None) – Angular step in radians for molecule rotation. Must be None for single-atom insertions.

  • proximity_threshold (float) – Two atoms are considered too close when their distance is less than proximity_threshold * (r1 + r2).

  • label (str | None) – Prefix for atom labels in the inserted molecule. Each atom gets {label}-{element}{index}.

  • selective_dynamics (ArrayLike | None) – Selective dynamics array for inserted atoms (used only when the host structure also uses selective dynamics).

  • reduce_supercell (bool) – When True, reduce the host to its primitive cell before scanning.

  • matcher (StructureMatcher | None) – StructureMatcher for detecting duplicate insertions.

  • multithread – Whether to use multithreading.

all_inserts(structure, limit=None)[source]

Generate all possible molecule insertion configurations.

Parameters:
  • structure (Structure | str) – Host structure or path to a structure file.

  • limit (int | None) – Maximum number of structures to return. When negative, randomly sample abs(limit) structures.

Returns:

Structures with the molecule inserted at distinct positions.

Return type:

list[Structure]

apply_transformation(structure, return_ranked_list=False)[source]

Apply the insertion transformation.

Parameters:
  • structure (Structure | str) – Host structure or path to a structure file.

  • return_ranked_list (bool | int) – If an integer, return that many structures as ranked dictionaries.

Returns:

Single inserted structure when return_ranked_list is False, otherwise a list of {'structure': ...} dictionaries.

Return type:

Structure or list[dict]

property is_one_to_many: bool

Whether the transformation is one-to-many (always True).

rotate_molecule_euler(euler_angle)[source]

Rotate the molecule by a triplet of extrinsic Euler angles.

Parameters:

euler_angle (ArrayLike) – 3-element array of Euler angles in radians.

Returns:

Rotated copy of self.molecule.

Return type:

Molecule

get_all_molecule_inserts(molecule, structure, step, anglestep=None, label='insert', limit=None)[source]

Convenience wrapper for generating molecule insertion structures.

Parameters:
  • molecule (Molecule | str | Element | Species | DummySpecies) – Species, Molecule, or path to a molecule file.

  • structure (Structure | str) – Host structure or path to a structure file.

  • step (float) – Grid spacing in Angstrom.

  • anglestep (float | None) – Angular step in degrees. None means no rotation.

  • label (str | None) – Label prefix for inserted atoms.

  • limit (int | None) – Maximum number of structures. Negative for random sampling.

Returns:

Structures with the molecule inserted.

Return type:

list[Structure]

Generate all the symmetrically equivalent clones of a site in structure.

class SymmetryCloneTransformation(sym_operations, filter_cls=None, tol=0.5)[source]

Bases: AbstractTransformation

Generate symmetrically equivalent clones of a structure.

Applies all symmetry operations to produce a list of distinct configurations, filtering duplicates by structure distance.

sym_operations

List of fractional SymmOp objects.

tol

Distance threshold for considering two clones equivalent.

filter_cls

Optional filter with filter and final_filter methods.

Initialise symmetry clone transformation.

Parameters:
  • sym_operations (list[SymmOp] | Structure) – List of fractional SymmOp objects, or a Structure used to derive them via SpacegroupAnalyzer.

  • filter_cls – Optional filter object. Must implement filter(trial, clones) -> bool and may implement final_filter(clones) -> list.

  • tol (float) – Distance tolerance for equivalence. Two clones are considered identical if the sum of site distances is below tol.

__init__(sym_operations, filter_cls=None, tol=0.5)[source]

Initialise symmetry clone transformation.

Parameters:
  • sym_operations (list[SymmOp] | Structure) – List of fractional SymmOp objects, or a Structure used to derive them via SpacegroupAnalyzer.

  • filter_cls – Optional filter object. Must implement filter(trial, clones) -> bool and may implement final_filter(clones) -> list.

  • tol (float) – Distance tolerance for equivalence. Two clones are considered identical if the sum of site distances is below tol.

apply_transformation(structure, return_ranked_list=False)[source]

Apply symmetry clone transformation.

Parameters:
  • structure (Structure | str) – Structure to clone, or path to a structure file.

  • return_ranked_list (bool | int) – If an int, return that many structures as ranked dictionaries.

Returns:

Single clone when return_ranked_list is False, otherwise a list of {'structure': ...} dictionaries.

Return type:

Structure or list[dict]

get_all_clones(structure, progress_bar=True, multithread=False)[source]

Generate all distinct symmetry clones of a structure.

Clones are sorted by distance from the input structure.

Parameters:
  • structure (Structure) – Structure to clone.

  • progress_bar (bool) – Whether to display a progress bar.

  • multithread (bool) – Whether to use multithreading for duplicate detection.

Returns:

Distinct clones with one-to-one site matching and symop properties.

Return type:

list[Structure]

property is_one_to_many: bool

Whether the transformation is one-to-many (always True).

class SymmetryFillTransformation(sym_operations, element_list)[source]

Bases: AbstractTransformation

Clone selected sites according to symmetry operations.

Applies a list of symmetry operations to all sites of a given element set, adding new sites when they are not too close to existing ones.

Attributes:

  • sym_operations: List of fractional SymmOp objects.

  • element_set: Set of species to clone.

Create structure with sites cloned according to symmetry.

Parameters:
__init__(sym_operations, element_list)[source]

Create structure with sites cloned according to symmetry.

Parameters:
apply_transformation(structure, _return_ranked_list=False)[source]

Apply the symmetry fill transformation.

Parameters:
  • structure (Structure | str) – Structure to fill, or path to a structure file.

  • _return_ranked_list (bool | int) – Unused (one-to-one transformation).

Returns:

Filled structure. Each cloned site has a symop property set to the symmetry operation used.

Return type:

Structure

apply_operation_keep_lattice(structure, op)[source]

Apply a symmetry operation while preserving lattice vectors.

The modified structure will have atom-to-atom match and all fractional coordinates normalized within 0..1 range.

Parameters:
  • structure – Structure to transform.

  • op – SymmOp to apply.

Returns:

Modified copy with unchanged lattice.

Return type:

Structure

Command-line interface

Master script to work with VASP inputs and outputs.

main()[source]

Entry point for the imdg command.

Returns:

Exit code from the selected subcommand.

Return type:

int

setup_logger(args)[source]

Configure logging based on verbosity flags.

Parameters:

args – Parsed command-line arguments.

Analysis extensions specific to IMD group. Based on pymatgen’s pymatgen.cli.pmg_analyze.

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser – Sub-parser from argparse.

analyze(args)[source]

Run the analysis subcommand.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

Exit code (0 on success).

Return type:

int

read_field(field, vaspdir)[source]

Read a single analysis field from a VASP directory.

Parameters:
  • field (str) – Field name (see ALL_FIELDS for valid values).

  • vaspdir (IMDGVaspDir) – VASP directory wrapper.

Returns:

Field value, or "N/A" when data is unavailable.

imdg sub-command to create new VASP inputs from scratch.

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser – Sub-parser from argparse.

create(args)[source]

Run the create subcommand.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

Exit code (0 on success).

Return type:

int

create_from_atom_name(name, size)[source]

Create a boxed periodic structure with a single atom centred.

Parameters:
  • name – Element symbol.

  • size – 3-tuple of cell dimensions in Angstrom.

Returns:

Boxed structure containing a single atom.

Return type:

Structure

create_from_file(path)[source]

Load a structure from a file.

Parameters:

path – Path to a structure file readable by pymatgen.

Returns:

Structure.

create_from_mpid(mpid)[source]

Fetch and standardise a structure from Materials Project.

Parameters:

mpid – Materials Project ID (e.g. mp-48).

Returns:

Structure with the mpid property set.

imdg sub-command to create new VASP inputs from existing.

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser – Sub-parser from argparse.

atat(args)[source]

Create ATAT input according to str.out.

Preserve selective dynamics settings from the original POSCAR.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

Raises:

ValueError – If str.out structure length is inconsistent with POSCAR.

atat_add_args(parser)[source]

Setup parser arguments for ATAT input.

Parameters:

parser – Subparser from argparse.

delete(args)[source]

Delete a site/sites from structure.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

delete_add_args(parser)[source]

Setup parser arguments for deleting a site.

Parameters:

parser – Subparser from argparse.

derive(args)[source]

Run the derive subcommand.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

Exit code (0 on success).

Return type:

int

Raises:
  • IOError – If a RUNNING file is found in the input directory and --force_running is not set.

  • ValueError – If --output is empty.

fill(args)[source]

Create a structure file with all insertion sites filled.

Take prototype structure and a set of relaxed configurations with inserted atoms and generate a structure with all possible sites for insertions completely filled.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

fill_add_args(parser)[source]

Setup parser arguments for filling sites.

Parameters:

parser – Subparser from argparse.

fix(args)[source]

Apply selective dynamics constraints.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

Raises:

ValueError – If constraints cannot be parsed as a valid Python dict.

fix_add_args(parser)[source]

Setup parser arguments for selective dynamics.

Parameters:

parser – Subparser from argparse.

functional(args)[source]

Create custom functional setup.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

functional_add_args(parser)[source]

Setup parser arguments for functional.

Parameters:

parser – Subparser from argparse.

incar(args)[source]

Create custom incar setup.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

incar_add_args(parser)[source]

Setup parser arguments for incar.

Parameters:

parser – Subparser from argparse.

insert(args)[source]

Create setup for inserted molecules/atoms.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [<list of inputsets>]}.

Return type:

dict

insert_add_args(parser)[source]

Setup parser arguments for inserting an atom/molecule.

Parameters:

parser – Subparser from argparse.

kpoints(args)[source]

Create custom kpoints setup.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

kpoints_add_args(parser)[source]

Setup parser arguments for kpoints.

Parameters:

parser – Subparser from argparse.

neb(args)[source]

Create NEB input.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

neb_add_args(parser)[source]

Setup parser arguments for NEB input.

Parameters:

parser – Subparser from argparse.

neb_diffusion(args)[source]

Create NEB input for all possible diffusion paths.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': <list of inputsets>}.

Return type:

dict

neb_diffusion_add_args(parser)[source]

Setup parser arguments for diffusion NEB input.

Parameters:

parser – Subparser from argparse.

perturb(args)[source]

Create perturbed input.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [<inputset>]}.

Return type:

dict

perturb_add_args(parser)[source]

Setup parser arguments for perturb.

Parameters:

parser – Subparser from argparse.

relax(args)[source]

Create relaxation setup.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

relax_add_args(parser)[source]

Setup parser arguments for relax.

Parameters:

parser – Subparser from argparse.

scf(args)[source]

Create SCF setup.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

scf_add_args(parser)[source]

Setup parser arguments for SCF calculation.

Parameters:

parser – Subparser from argparse.

strain(args)[source]

Create strained input.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': <list of inputsets>}.

Return type:

dict

strain_add_args(parser)[source]

Setup parser arguments for strain.

Parameters:

parser – Subparser from argparse.

supercell(args)[source]

Create supercell.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [<inputset>]}.

Return type:

dict

supercell_add_args(parser)[source]

Setup parser arguments for supercell.

Parameters:

parser – Subparser from argparse.

imdg sub-command to compare VASP inputs/outputs.

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser – Sub-parser from argparse.

diff(args)[source]

Run the diff subcommand.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

Exit code (0 on success).

Return type:

int

diff_incar(args)[source]

Handle diff commands.

Parameters:

args – Args from command.

diff_structures(args)[source]

Compare structures.

Parameters:

args – Parsed command-line arguments from argparse.

incar_add_args(parser)[source]

Setup parser arguments for incar comparison.

Parameters:

parser – Subparser from argparse.

structure_add_args(parser)[source]

Setup parser arguments for structure comparison.

Parameters:

parser – Subparser from argparse.

Check status of running VASP calculations.

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser – Sub-parser from argparse.

custom_showwarning(message, category, _filename, _lineno, file=None, _line=None)[source]

Print warning in nicer way.

Parameters:
  • message – Warning message.

  • category – Warning category class.

  • _filename – File where the warning originated (unused).

  • _lineno – Line number (unused).

  • file – Output stream (default: stderr).

  • _line – Line context (unused).

print_seconds(seconds)[source]

Convert a duration in seconds to a human-readable string.

Parameters:

seconds – Duration in seconds. Negative values produce relative past-time strings.

Returns:

Human-readable duration (e.g. "in 2h 30m").

Return type:

str

slurm_runningp(path)[source]

Check whether a Slurm job is running in the given directory.

Parameters:

path – Directory path to check.

Returns:

True if a Slurm job is running in path or a parent NEB directory.

Return type:

bool

status(args)[source]

Run the status subcommand.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

Exit code (0 on success).

Return type:

int

vasp_output_time(path)[source]

Return last VASP output modification time.

Parameters:

path – VASP directory path.

Returns:

Modification timestamp, or None if no VASP output file is found. For NEB calculations, the maximum timestamp across all image directories is returned.

Return type:

float | None

Visualization extension specific to IMD group.

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser – Sub-parser from argparse.

atat(args)[source]

Create ATAT visualization.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

Exit code (0 on success).

Return type:

int

atat_add_args(parser)[source]

Setup parser arguments for ATAT visualization.

Parameters:

parser – Subparser from argparse.

hull(args)[source]

Plot formation energy hull from ATAT results.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

Exit code (0 on success, 1 on error).

Return type:

int

hull_add_args(parser)[source]

Setup parser arguments for formation energy hull visualization.

Parameters:

parser – Subparser from argparse.

neb(args)[source]

Create NEB visualization.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

Exit code (0 on success).

Return type:

int

neb_add_args(parser)[source]

Setup parser arguments for neb visualization.

Parameters:

parser – Subparser from argparse.

selective_dynamics(args)[source]

Visualize selective dynamics.

Parameters:

args – Parsed command-line arguments from argparse.

selective_dynamics_add_args(parser)[source]

Setup parser arguments for selective dynamics visualization.

Parameters:

parser – Subparser from argparse.

visualize(args)[source]

Run the visualize subcommand.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

Exit code from the selected sub-function.

Return type:

int

voltage(args)[source]

Plot voltage profile from ATAT results using pymatgen’s battery analysis tools.

Parameters:

args – Parsed command-line arguments from argparse.

Returns:

Exit code (0 on success).

Return type:

int

Raises:

ValueError – If no pure working-ion entry is found in the data.

voltage_add_args(parser)[source]

Setup parser arguments for voltage profile visualization.

Parameters:

parser – Subparser from argparse.

Utilities

Helpers for matplotlib plotting.

mpl_defaults(*, font_size=12, width=4.13, ratio=0.75, dpi=300, savefig_dpi=600)[source]

Configure matplotlib rcParams for publication-quality figures.

Applies consistent settings: editable PDF text, direction-in ticks, minor ticks, constrained layout, and a custom color/linestyle cycler. Scripts that need further customization (e.g. a seaborn base style) should call this function after any style sheet import so these values take precedence.

Parameters:
  • font_size (float) – Base font size in pt.

  • width (float) – Figure width in inches (default A4_WIDTH/2 = single-column).

  • ratio (float) – Height / width ratio (default 0.75 = 3:4).

  • dpi (int) – Screen DPI for interactive display.

  • savefig_dpi (int) – DPI for saved figures.

Return type:

None