API Reference

Core

Common routines used across the sub-libraries.

configure_progress_output()[source]

Send alive_progress output to stderr.

alive_progress writes progress bars and their final receipt to stdout by default. For CLI tools, stdout is reserved for actual results, so redirect progress to stderr. This is a process-wide setting; call it once at each CLI entry point.

deprecated_aliases(module_globals, **aliases)[source]

Return a module-level __getattr__ resolving deprecated names.

aliases maps each legacy name to the current name present in module_globals. Accessing a legacy name emits a DeprecationWarning and returns the current object, so old IMD* / IMDG* class names keep working after the MatRiFFlow rename.

Usage (at the bottom of a module):

__getattr__ = deprecated_aliases(globals(), IMDGVaspDir="MRFVaspDir")
Parameters:
Return type:

Callable[[str], Any]

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

Group elements of a list by pairwise equality.

Each item is compared only against the first member of every existing group, so the number of cmp_eq calls is O(n * g), where g is the number of groups produced, instead of O(n^2) over group members.

This is exact when cmp_eq is an equivalence relation (reflexive, symmetric, and transitive). A non-transitive cmp_eq still works, but it is only compared against the first member of each group, so items that would match a later member but not the representative may be split into separate groups.

Parameters:
  • lst (Sequence[Any]) – List of elements to group.

  • cmp_eq (Callable[[Any, Any], bool]) – Function that takes two elements and returns True if they should belong to the same group. Ideally an equivalence relation; see above for the behavior when it is not transitive.

  • title_function (Callable[[Any], str] | None) – 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]

open_progress_bar(total, **options)[source]

Open an alive-progress context.

Parameters:
  • total (int | None)

  • options (Any)

Return type:

AbstractContextManager[Any]

short_path(path)[source]

Return the final path component for compact log messages.

gorun working directories live under long cluster mount points (e.g. /net/storage/.../generations.Li/.../relax.2). Repeating the full path on every line drowns out the useful information, so per-step messages only show the final component. The working directory is announced once at the start of a run.

Parameters:

path (str | Path)

Return type:

str

suppress_spglib_warnings()[source]

Silence spglib’s raw C-level warnings.

spglib prints internal retry diagnostics directly to stderr when symmetry detection needs several attempts (e.g. "spglib: ssm_get_exact_positions failed.", "spglib: No point group was found"). They are harmless and duplicate the structured warnings surfaced by matrifflow’s own diagnostics, but they interleave with rich tables and corrupt the display.

spglib reads SPGLIB_WARNING on every call (see its warning_enabled), so setting it at runtime is enough. We use setdefault so a user who has already chosen a value keeps control; only the absent-key case is forced to OFF.

Extension for pymatgen.core.structure.

class MRFStructure(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

MatRiFFlow 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 (Any) – 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 MRFStructure from an existing pymatgen Structure.

Parameters:

structure (Structure) – Structure to convert.

Returns:

Copy of structure as an MRFStructure.

Return type:

MRFStructure

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 (FileFormats | Literal["atat"]) – Format to output to. Defaults to JSON unless filename is provided. If fmt is specified, it overrides whatever the filename is. Options include “cif”, “poscar”, “cssr”, “json”, “xsf”, “mcsqs”, “prismatic”, “yaml”, “yml”, “fleur-inpgen”, “pwmat”, “aims”, plus new “atat”. 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)

  • fmt (Literal['cif', 'poscar', 'cssr', 'json', 'yaml', 'yml', 'xsf', 'mcsqs', 'res', 'pwmat', 'aims', '', 'atat'])

Return type:

str

exception StructureDuplicateWarning[source]

Bases: UserWarning

Warning emitted when duplicate input structures are detected.

filter_framework(structure, framework_elements)[source]

Return a copy of structure containing only framework sites.

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

  • framework_elements (Collection[str]) – Element symbols kept as the framework.

Returns:

A copy containing only sites of the framework elements.

Return type:

Structure

get_framework_elements(structure)[source]

Return the host-framework element symbols for structure.

The framework is the most common element, matching the default behaviour of MRFVaspDir.check_framework_symmetry(). Mobile species (intercalants, adsorbates) are assumed to be minority species.

Parameters:

structure (Structure) – Structure to inspect.

Returns:

Single-element list containing the framework symbol.

Return type:

list[str]

get_framework_space_group(structure, framework_elements=None, symprec=0.1)[source]

Return the space group of the host framework of structure.

Mobile species (intercalants, adsorbates) are removed before the space group is detected, so they cannot mask the framework symmetry.

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

  • framework_elements (Collection[str] | None) – Element symbols kept as the framework. When None, defaults to the most common element of structure (see get_framework_elements()).

  • symprec (float) – Symmetry tolerance (Angstrom). Defaults to FRAMEWORK_SYMPREC.

Returns:

International space group symbol of the framework.

Return type:

str

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 (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 (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 (bool) – 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 (float | None) – When set, return early if the accumulating distance exceeds this value.

  • norm (bool) – 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 (Any) – 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[[Structure, Structure], bool] | None) – Callable that takes two structures and returns True if they match. Defaults to StructureMatcher(attempt_supercell=True, scale=False).fit.

  • warn (bool) – When True, emit StructureDuplicateWarning on match.

  • multithread (bool | int) – 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 (Callable[[Structure, Structure], bool] | None) – Comparison function passed to structure_matches(). Defaults to None, which uses StructureMatcher(attempt_supercell=True, scale=False).fit.

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

  • multithread (bool | int) – 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 MRFVaspDir(dirname, exclude_patterns=None)[source]

Bases: Mapping[str, Any], MSONable

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

Files are lazily parsed to minimise initialisation cost. Example:

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

When file is absent but a compressed variant exists (.gz, .bz2, .xz, or .lzma), it is resolved and parsed: d["vasprun.xml"] reads vasprun.xml.gz. d["vasprun.xml.gz"] matches only that exact file.

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. Each directory caches two kinds of records: individual parsed files (raw parse results, keyed by file name) and a summary of memoized derived values (final_energy, converged_* flags, warnings, and similar). The two are kept separate because their invalidation needs differ; see the “Cache namespaces” comment near _index_key.

Properties that require parsing multiple files:

  • final_energy, final_energy_reliable

  • initial_structure, final_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 mrf.log (already in the class default) as well as any other *.log file.

CACHE_VERSION: ClassVar[int] = 12
COMPRESSION_EXTENSIONS: ClassVar[tuple[str, ...]] = ('.gz', '.bz2', '.xz', '.lzma')
EXCLUDE_PATTERNS: ClassVar[frozenset[str]] = frozenset({'mrf.log*'})
FILE_MAPPINGS: ClassVar[dict[str, type[Any]]] = {'CHGCAR': <class 'pymatgen.io.vasp.outputs.Chgcar'>, 'CONTCAR': <class 'pymatgen.io.vasp.inputs.Poscar'>, 'ELFCAR': <class 'pymatgen.io.vasp.outputs.Elfcar'>, 'INCAR': <class 'matrifflow.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 'matrifflow.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 'matrifflow.pymatgen.io.vasp.outputs.Vasplog'>, 'stdout.*': <class 'matrifflow.pymatgen.io.vasp.outputs.Vasplog'>, 'vasp\\.out.*': <class 'matrifflow.pymatgen.io.vasp.outputs.Vasplog'>, 'vasprun\\.xml': <class 'matrifflow.pymatgen.io.vasp.outputs.Vasprun'>}
MAP_SIZE: ClassVar[int] = 1099511627776
TIMEOUT = 120
VASP_INDICATOR_FILES: ClassVar[tuple[str, ...]] = ('OUTCAR', 'vasprun.xml', 'POSCAR', 'OSZICAR')
__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 mrf.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)[source]

Check whether the framework symmetry is preserved.

Reduces false positives from mobile atoms breaking symmetry.

Parameters:
  • framework_elements (Collection[str] | None) – List of element symbols for the framework. Defaults to the most common element.

  • symprec (float) – Symmetry tolerance for space group detection.

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

Latest recorded E0 from OSZICAR, falling back to vasprun.xml/OUTCAR.

OSZICAR steps without E0 are skipped, including empty entries in incomplete runs. Returns NaN when no energy is available.

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

property final_structure: Structure | None

Final structure of the calculation in the current directory.

Unlike initial_structure, this never consults prev_dirs: the final geometry always belongs to the current directory. Reads CONTCAR when present, otherwise the final structure from vasprun.xml.

Returns None when neither CONTCAR nor vasprun.xml is available.

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 | None

Initial structure of the calculation.

The initial state is the earliest structure in the calculation chain. When gorun_* subdirectories (prev_dirs) exist, their initial structure is returned, because the current directory is not the true starting geometry. Otherwise the current directory’s POSCAR, then the vasprun.xml initial structure, is used.

Returns None when no structure is available.

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 vasprun.xml or 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 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 (bool) – When False, exclude the first and last images.

Returns:

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

Return type:

list[MRFVaspDir] | None

property nebp: bool

Whether this directory contains a NEB-like calculation.

Detected by the presence of IMAGES in the INCAR.

output_mtime()[source]

Modification time of the newest VASP output file, or None.

Reports the OUTCAR mtime when present, otherwise the vasprun.xml mtime; both resolve through compression variants. For NEB directories, returns the maximum across image directories. Returns None when no VASP output file exists, distinguishing “no output yet” from a zero/old timestamp.

Return type:

float | None

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. Empty when there are none.

Return type:

list[MRFVaspDir]

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 (Callable[[Path], bool] | None) – Optional callable that returns True for paths to include.

Returns:

Mapping of {path: MRFVaspDir}.

Return type:

dict[str, MRFVaspDir]

refresh()[source]

Reload cache validity metadata or reset to an empty state.

Loads only the tiny per-directory index (version + hash). The summary (memoized derived values) is loaded lazily on first access, and parsed files are fetched lazily by __getitem__().

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 run_stats: dict[str, Any] | None

Cached Outcar.run_stats, or None without OUTCAR.

property structure: Structure | None

Deprecated alias for final_structure.

Use final_structure instead.

property timing_stats: RunTimingStats | None

Cached Outcar.timing_stats, or None without OUTCAR.

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 memoized 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 (int) – Signal number.

  • frame (FrameType | None) – Current stack frame.

Raises:

TimeoutException – Always raised.

Return type:

None

This module implements MRF 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 (case-insensitive). Supported values: pbe, pbesol, pbe+d2, pbe+d3-0, pbe+d3-bj, pbe+ts, vdw-df, vdw-df2, optb88-vdw, optb86b-vdw.

Returns:

INCAR parameter dictionary.

Return type:

dict

Raises:
static group_incars(incars, ignore_fields=None)[source]

Group similar INCARs together.

Differences in ignore_fields are not considered when comparing INCARs.

Parameters:
  • incars (list[Incar]) – List of Incar objects.

  • ignore_fields (list[str] | None) – INCAR keys to ignore when grouping. Defaults to INCAR_GROUP_IGNORE_FIELDS.

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 MeanStd(n, mean, std)[source]

Bases: object

Sample mean and standard deviation of a timing series.

Parameters:
mean: float
n: int
std: float
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[str, Any]

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

property timing_stats: RunTimingStats

Mean +/- std of SCF cycle and ionic step wall-clock time.

Parses pymatgen’s in-memory OUTCAR lines, so it reuses the Outcar object cached by MRFVaspDir without re-reading the file from disk.

class RunTimingStats(scf, ionic)[source]

Bases: object

Wall-clock timing statistics for a VASP run.

Parameters:
ionic: MeanStd
scf: MeanStd
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': ['Might happen when NCORE/NPAR is too large or atoms are very close. 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 (dict[str, Any]) –

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.

ENERGY_INCREASE_TOLERANCE = 0.001
PRESSURE_CONVERGENCE_THRESHOLD = 3
check_energy_increase(tolerance=None)[source]

Check whether the final ionic energy is above an intermediate one.

A proper ionic relaxation should end at (or below) the lowest energy reached in earlier ionic steps. When the final energy is higher than the best intermediate energy by more than tolerance per atom, records an energy_increase warning. Missing or nonnumeric energy values leave the history unchecked.

Parameters:

tolerance (float | None) – Energy increase per atom (eV/atom) that triggers a warning. Defaults to ENERGY_INCREASE_TOLERANCE.

Returns:

True when the energy is monotonic (or cannot be checked), False when a warning was recorded.

Return type:

bool

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 (float) – 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, and warns when the final energy is higher than an intermediate step’s energy.

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.

read_outcar_timing_stats(filename)[source]

Stream OUTCAR and compute SCF / ionic step timing statistics.

Reads only timing markers, so it is cheap enough for ongoing runs where a full pymatgen Outcar parse is not desirable.

Parameters:

filename (str | Path) – Path to the OUTCAR file.

Returns:

Mean and sample std of wall-clock time per SCF cycle and per ionic step, in seconds.

Return type:

RunTimingStats

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

class MRFDerivedInputSet(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, force_prev_incar_file=False, force_prev_kpoints_file=False, inherit_prev_incarpy=False, *, directory)[source]

Bases: MRFVaspInputSet

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

Unlike plain MRFVaspInputSet, 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[MRFVaspInputSet] | None)

  • name (str | None)

  • no_kpoints (bool)

  • no_potcar (bool)

  • no_poscar (bool)

  • no_incar (bool)

  • force_prev_incar_file (bool)

  • force_prev_kpoints_file (bool)

  • inherit_prev_incarpy (bool)

  • directory (str | MRFVaspDir)

directory: str | MRFVaspDir
force_prev_incar_file: bool = False
force_prev_kpoints_file: bool = False
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 MRFNEBVaspInputSet(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, force_prev_incar_file=False, force_prev_kpoints_file=False, inherit_prev_incarpy=False, fix_cutoff=None, frac_tol=0.5, method='IDPP', *, directory, target_directory)[source]

Bases: MRFDerivedInputSet

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[MRFVaspInputSet] | None)

  • name (str | None)

  • no_kpoints (bool)

  • no_potcar (bool)

  • no_poscar (bool)

  • no_incar (bool)

  • force_prev_incar_file (bool)

  • force_prev_kpoints_file (bool)

  • inherit_prev_incarpy (bool)

  • fix_cutoff (float | None)

  • frac_tol (float)

  • method (str)

  • directory (str | MRFVaspDir)

  • target_directory (str | MRFVaspDir)

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

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 | MRFVaspDir
update_images(beg=None, end=None, **kwargs)[source]

Update NEB images by interpolating between start and end structures.

Parameters:
write_input(output_dir, *args, **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 (str | Path) – Target directory for the input files.

  • args (Any)

  • kwargs (Any)

Return type:

None

Any extra positional and keyword arguments are forwarded to VaspInputSet.write_input.

exception MRFNEBVaspInputSetWarning[source]

Bases: UserWarning

Warning emitted by MRFNEBVaspInputSet.

class MRFStandardVaspInputSet(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: MRFVaspInputSet

Standard input set for MatRiFFlow.

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[MRFVaspInputSet] | None)

  • name (str | None)

  • no_kpoints (bool)

  • no_potcar (bool)

  • no_poscar (bool)

  • no_incar (bool)

CONFIG: ClassVar[dict[str, Any]] = {'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 MRFVaspInputSet(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

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

  8. Writes an INCAR.toml recording non-default metadata (POTCAR mapping, k-point density, functional) so that gorun and other tools can reproduce the written inputs.

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[MRFVaspInputSet] | None)

  • name (str | None)

  • no_kpoints (bool)

  • no_potcar (bool)

  • no_poscar (bool)

  • no_incar (bool)

CONFIG: ClassVar[dict[str, Any]] = {'INCAR': {}, 'POTCAR_FUNCTIONAL': 'PBE_64'}
functional: str | None = None
images: list[MRFVaspInputSet] | 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[str, Any]

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]

List of POTCAR symbols.

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

write_input(output_dir, *args, **kwargs)[source]

Write VASP input files to a directory.

In addition to standard pymatgen behaviour, writes an MRFVaspInputSet.log file, an INCAR.toml recording non-default metadata (POTCAR mapping, k-point density, functional), and, for NEB runs, the image subdirectories and a trajectory CIF.

Parameters:
  • output_dir (str | Path) – Target directory for the input files.

  • args (Any)

  • kwargs (Any)

Return type:

None

Any extra positional and keyword arguments are forwarded to VaspInputSet.write_input.

When PMG_VASP_PSP_DIR is unconfigured, write_input degrades to potcar_spec=True instead of failing: it emits a warning and writes POTCAR.spec (the symbol list) rather than POTCAR content, leaving INCAR.toml with the POTCAR mapping so that gorun can regenerate the POTCAR on a cluster where the pseudopotential library is available. A configured-but-missing PMG_VASP_PSP_DIR raises instead: the user intended to configure it, so proceeding silently would hide a setup mistake.

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 = no selective dynamics assigned.

A site with no selective_dynamics (missing key or None) is marked X rather than silently treated as fixed or free, so that an inconsistent assignment is highlighted.

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

  • fname (str | Path) – 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.

Vacancies must be marked with a dummy species (e.g. X) in all arguments. The scanned species (e.g. Li in an ATAT Li,Vac system) must keep its real element symbol; otherwise a flipped configuration is indistinguishable from the original.

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 (int) – 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 flags 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 (Iterable[bool] | None) – Selective dynamics flags for the inserted atoms. When None (or all-True, meaning free) and the host uses selective dynamics, inserted atoms default to free [True, True, True]. A partial constraint (e.g. [True, True, False]) is applied verbatim and, when the host lacks selective dynamics, the host atoms are given free flags so the result stays consistent. An all-True value on a host without selective dynamics is a no-op (no constraints written).

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

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

  • multithread (bool | int) – 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 (Iterable[bool] | None) – Selective dynamics flags for the inserted atoms. When None (or all-True, meaning free) and the host uses selective dynamics, inserted atoms default to free [True, True, True]. A partial constraint (e.g. [True, True, False]) is applied verbatim and, when the host lacks selective dynamics, the host atoms are given free flags so the result stays consistent. An all-True value on a host without selective dynamics is a no-op (no constraints written).

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

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

  • multithread (bool | int) – 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 (Sequence[float]) – 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 (Any | None) – 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 (Any | None) – 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:
Return type:

None

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) – Structure to transform.

  • op (SymmOp) – SymmOp to apply.

Returns:

Modified copy with unchanged lattice.

Return type:

Structure

Command-line interface

Master CLI for VASP workflows and cluster job submission.

main()[source]

Entry point for the mrf command.

Returns:

Exit code from the selected subcommand.

Return type:

int

main_deprecated_imdg()[source]

Deprecated imdg entry point: forwards to main().

Kept so the legacy imdg console script keeps working after the MatRiFFlow rename. Prints a one-line notice to stderr first.

Return type:

int

setup_logger(args)[source]

Configure logging based on verbosity flags.

Parameters:

args (Namespace) – Parsed command-line arguments.

Return type:

None

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

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser (ArgumentParser) – Sub-parser from argparse.

Return type:

None

analyze(args)[source]

Run the analysis subcommand.

Parameters:

args (Namespace) – 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 (MRFVaspDir) – VASP directory wrapper.

Returns:

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

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

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser (ArgumentParser) – Sub-parser from argparse.

Return type:

None

create(args)[source]

Run the create subcommand.

Parameters:

args (Namespace) – 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:
Returns:

Boxed structure containing a single atom.

Return type:

Structure

create_from_file(path)[source]

Load a structure from a file.

Parameters:

path (str | Path) – Path to a structure file readable by pymatgen.

Returns:

Structure.

Return type:

Structure

create_from_mpid(mpid)[source]

Fetch and standardise a structure from Materials Project.

Parameters:

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

Returns:

Structure with the mpid property set.

Raises:

ValueError – If the Materials Project API key is missing or invalid.

Return type:

Structure

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

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser (ArgumentParser) – Sub-parser from argparse.

Return type:

None

atat(args)[source]

Create ATAT input according to str.out.

Preserve selective dynamics settings from the original POSCAR.

Parameters:

args (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

delete(args)[source]

Delete a site/sites from structure.

Parameters:

args (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

derive(args)[source]

Run the derive subcommand.

Parameters:

args (Namespace) – 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 (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

fix(args)[source]

Apply selective dynamics constraints.

Parameters:

args (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

functional(args)[source]

Create custom functional setup.

Parameters:

args (Namespace) – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

functional_add_args(parser)[source]

Setup parser arguments for functional.

Parameters:

parser (ArgumentParser) – Subparser from argparse.

Return type:

None

incar(args)[source]

Create custom incar setup.

Parameters:

args (Namespace) – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

incar_add_args(parser)[source]

Setup parser arguments for incar.

Parameters:

parser (ArgumentParser) – Subparser from argparse.

Return type:

None

insert(args)[source]

Create setup for inserted molecules/atoms.

Parameters:

args (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

kpoints(args)[source]

Create custom kpoints setup.

Parameters:

args (Namespace) – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

kpoints_add_args(parser)[source]

Setup parser arguments for kpoints.

Parameters:

parser (ArgumentParser) – Subparser from argparse.

Return type:

None

neb(args)[source]

Create NEB input.

Parameters:

args (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

neb_diffusion(args)[source]

Create NEB input for all possible diffusion paths.

Parameters:

args (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

perturb(args)[source]

Create perturbed input.

Parameters:

args (Namespace) – Parsed command-line arguments from argparse.

Returns:

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

Return type:

dict

perturb_add_args(parser)[source]

Setup parser arguments for perturb.

Parameters:

parser (ArgumentParser) – Subparser from argparse.

Return type:

None

potcar(args)[source]

Create custom POTCAR setup.

Parameters:

args (Namespace) – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

potcar_add_args(parser)[source]

Setup parser arguments for POTCAR.

Parameters:

parser (ArgumentParser) – Subparser from argparse.

Return type:

None

relax(args)[source]

Create relaxation setup.

Parameters:

args (Namespace) – Parsed command-line arguments from argparse.

Returns:

{'inputsets': [inputset]}.

Return type:

dict

relax_add_args(parser)[source]

Setup parser arguments for relax.

Parameters:

parser (ArgumentParser) – Subparser from argparse.

Return type:

None

scf(args)[source]

Create SCF setup.

Parameters:

args (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

strain(args)[source]

Create strained input.

Parameters:

args (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

supercell(args)[source]

Create supercell.

Parameters:

args (Namespace) – Parsed command-line arguments from argparse.

Returns:

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

Return type:

dict

supercell_add_args(parser)[source]

Setup parser arguments for supercell.

Parameters:

parser (ArgumentParser) – Subparser from argparse.

Return type:

None

mrf sub-command to compare VASP inputs/outputs.

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser (ArgumentParser) – Sub-parser from argparse.

Return type:

None

diff(args)[source]

Run the diff subcommand.

Parameters:

args (Namespace) – Parsed command-line arguments from argparse.

Returns:

Exit code (0 on success).

Return type:

int

diff_incar(args)[source]

Handle diff commands.

Parameters:

args (Namespace) – Args from command.

Return type:

int

diff_structures(args)[source]

Compare structures.

Parameters:

args (Namespace) – Parsed command-line arguments from argparse.

Return type:

None

incar_add_args(parser)[source]

Setup parser arguments for incar comparison.

Parameters:

parser (ArgumentParser) – Subparser from argparse.

Return type:

None

print_incar_groups(common_incar, groups, console=None, max_names=None)[source]

Print common INCAR parameters (condensed) and per-group differences.

Parameters:
  • common_incar (Incar) – Incar with parameters shared by every group.

  • groups (list[list[Incar]]) – List of groups, each a list of Incar instances carrying a SYSTEM entry with the source directory name.

  • console (Console | None) – rich Console to print to (defaults to a new one).

  • max_names (int | None) – Cap the number of directory names shown per group; remaining names are collapsed into .... None shows every name.

Return type:

None

structure_add_args(parser)[source]

Setup parser arguments for structure comparison.

Parameters:

parser (ArgumentParser) – Subparser from argparse.

Return type:

None

Check status of running VASP calculations.

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser (ArgumentParser) – Sub-parser from argparse.

Return type:

None

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

Print warning in nicer way.

Parameters:
  • message (Warning | str) – Warning message.

  • category (type[Warning]) – Warning category class.

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

  • _lineno (int) – Line number (unused).

  • file (TextIO | None) – Output stream (default: stderr).

  • _line (str | None) – Line context (unused).

Return type:

None

format_duration(seconds)[source]

Format a duration in seconds compactly.

Rounds to the most significant non-zero unit so the string stays short in table cells: "6s", "15m", "1h".

Parameters:

seconds (float | None) – Duration in seconds, or NaN for undefined.

Returns:

Human-readable duration, or "N/A" when seconds is NaN.

Return type:

str

format_timing_stats(stats)[source]

Format RunTimingStats for display.

Omits the +/- std term when fewer than two samples are available, and returns an empty string when no SCF cycle was recorded.

Parameters:

stats (RunTimingStats) – RunTimingStats instance.

Returns:

e.g. "SCF: 6.1±2.5s relax: 14m51s".

Return type:

str

print_seconds(seconds)[source]

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

Parameters:

seconds (float) – 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 (str | 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 (Namespace) – 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.

Deprecated: use MRFVaspDir.output_mtime() instead.

Parameters:

path (str | 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 MRF group.

add_args(parser)[source]

Register subcommand arguments.

Parameters:

parser (ArgumentParser) – Sub-parser from argparse.

Return type:

None

atat(args)[source]

Create ATAT visualization.

Parameters:

args (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

hull(args)[source]

Plot formation energy hull from ATAT results.

Parameters:

args (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

neb(args)[source]

Create NEB visualization.

Parameters:

args (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

selective_dynamics(args)[source]

Visualize selective dynamics.

Parameters:

args (Namespace) – Parsed command-line arguments from argparse.

Return type:

None

selective_dynamics_add_args(parser)[source]

Setup parser arguments for selective dynamics visualization.

Parameters:

parser (ArgumentParser) – Subparser from argparse.

Return type:

None

visualize(args)[source]

Run the visualize subcommand.

Parameters:

args (Namespace) – 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 (Namespace) – 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 (ArgumentParser) – Subparser from argparse.

Return type:

None

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