API Reference
Core
Common routines used across the sub-libraries.
- configure_progress_output()[source]
Send
alive_progressoutput to stderr.alive_progresswrites 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.aliasesmaps each legacy name to the current name present inmodule_globals. Accessing a legacy name emits aDeprecationWarningand returns the current object, so oldIMD*/IMDG*class names keep working after the MatRiFFlow rename.Usage (at the bottom of a module):
__getattr__ = deprecated_aliases(globals(), IMDGVaspDir="MRFVaspDir")
- 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_eqcalls is O(n * g), wheregis the number of groups produced, instead of O(n^2) over group members.This is exact when
cmp_eqis an equivalence relation (reflexive, symmetric, and transitive). A non-transitivecmp_eqstill 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:
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:
- open_progress_bar(total, **options)[source]
Open an alive-progress context.
- Parameters:
- Return type:
- 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.
- 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_WARNINGon every call (see itswarning_enabled), so setting it at runtime is enough. We usesetdefaultso a user who has already chosen a value keeps control; only the absent-key case is forced toOFF.
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:
StructureMatRiFFlow variant of pymatgen Structure.
Adds the ability to read and write ATAT
str.outfiles 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:
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.
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:
- classmethod from_structure(structure)[source]
Create an MRFStructure from an existing pymatgen Structure.
- Parameters:
structure (Structure) – Structure to convert.
- Returns:
Copy of
structureas an MRFStructure.- Return type:
- 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:
- exception StructureDuplicateWarning[source]
Bases:
UserWarningWarning 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.
- 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 (seeget_framework_elements()).symprec (float) – Symmetry tolerance (Angstrom). Defaults to
FRAMEWORK_SYMPREC.
- Returns:
International space group symbol of the framework.
- Return type:
- 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.
- 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.
- 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
tolAngstrom 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
tolAngstrom do not contribute.When the structures have similar but not identical lattices, fractional site positions of
structure2are mapped onto the lattice vectors ofstructure1.- 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:
- 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 thanfrac_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).
- 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
StructureDuplicateWarningon match.multithread (bool | int) – When True, use
cpu_count - 1workers. When an integer, use that many workers (capped at available CPUs).
- Returns:
True if a match is found, False otherwise.
- Return type:
- 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 honoursselective_dynamicssite 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 usesStructureMatcher(attempt_supercell=True, scale=False).fit.warn (bool) – When True, emit
StructureDuplicateWarningfor each duplicate found.multithread (bool | int) – When True, use
cpu_count - 1workers. 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]
I/O
This module implements abstraction over Vasp input/output directory.
- class MRFVaspDir(dirname, exclude_patterns=None)[source]
Bases:
Mapping[str,Any],MSONableDictionary-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"]readsvasprun.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_reliableinitial_structure,final_structuretotal_magnetizationconverged,converged_ionic,converged_electronic,converged_sequence,converged_manualnebp(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"]excludesmrf.log(already in the class default) as well as any other*.logfile.
- 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'>}
- TIMEOUT = 120
- __init__(dirname, exclude_patterns=None)[source]
Initialise from a directory path.
- Parameters:
dirname (str | Path) – Path to the VASP calculation directory.
exclude_patterns (Iterable[str] | None) – Extra glob patterns for files to skip during directory scanning. These are added to the class-level
EXCLUDE_PATTERNS. For example,["*.log"]excludesmrf.log(already in the class default) as well as any other*.logfile.
- 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:
- 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:
- property converged: bool
Overall convergence status.
Returns True only when the run is electronically and ionically converged, the convergence sequence is complete, and no
UNCONVERGEDmarker file is present. For NEB runs, all images must be converged.
- 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
UNCONVERGEDfile 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:
- property final_structure: Structure | None
Final structure of the calculation in the current directory.
Unlike
initial_structure, this never consultsprev_dirs: the final geometry always belongs to the current directory. Reads CONTCAR when present, otherwise the final structure from vasprun.xml.Returns
Nonewhen 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
Nonewhen 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. ReturnsVasploginstances for slurm/stdout/vasp.out logs and anOutcarwhen OUTCAR is the only log file.- Returns:
Parsed log objects, skipping files that fail to parse.
- Return type:
- max_force(include_constrained=False)[source]
Maximum residual force magnitude from vasprun.xml or OUTCAR.
When
include_constrainedis 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.
- mtime()[source]
Latest modification time across all relevant files.
Considers NEB subdirectories and previous-run directories.
- Return type:
- 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
IMAGESin 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
Nonewhen 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 aPOSCAR.- Returns:
Sorted list of previous-run directories. Empty when there are none.
- Return type:
- static read_vaspdirs(rootpath, path_filter=None)[source]
Recursively scan directories for VASP calculations.
- 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_PATTERNSor extra patterns from the constructor are skipped.
- property structure: Structure | None
Deprecated alias for
final_structure.Use
final_structureinstead.
- 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),Vasprunaccuracy 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:
ExceptionRaised when a VASP directory read operation times out.
- timeout_handler(signum, frame)[source]
Signal handler that raises TimeoutException.
- Parameters:
- 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:
IncarModified version of pymatgen’s Incar class.
Extensions:
Readable constants for INCAR values (ISIF_*, IBRION_*).
Warning when
IBRION=-1andNSW>0(useless combination).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:
- Returns:
INCAR parameter dictionary.
- Return type:
- Raises:
KeyError – If
nameis not a supported functional.ValueError – If
setupis unknown.
- static group_incars(incars, ignore_fields=None)[source]
Group similar INCARs together.
Differences in
ignore_fieldsare not considered when comparing INCARs.- Parameters:
- Returns:
(common_incar, groups)wherecommon_incaris an Incar with parameters shared by all groups, andgroupsis a list of lists of Incar objects.- Return type:
This module implements extensions to pymatgen.io.vasp.outputs module.
- class MeanStd(n, mean, std)[source]
Bases:
objectSample mean and standard deviation of a timing series.
- class Outcar(filename)[source]
Bases:
VasplogMixin,OutcarModified version of pymatgen’s Outcar that stores all fields.
Initialize an Outcar.
- Parameters:
filename (PathLike) – OUTCAR file to parse.
- property final_forces: ndarray | None
Force vectors from the final ionic step.
Parses the last
TOTAL-FORCEtable from the OUTCAR and returns one force vector per atom.- Returns:
Array of shape
(n_atoms, 3)with forces in eV/Angstrom, orNonewhen 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
Outcarobject cached byMRFVaspDirwithout re-reading the file from disk.
- class RunTimingStats(scf, ionic)[source]
Bases:
objectWall-clock timing statistics for a VASP run.
- class Vasplog(filename)[source]
Bases:
VasplogMixin,MSONableParser 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.
- class VasplogMixin[source]
Bases:
objectShared log-parsing logic for VASP log files and OUTCAR.
Builds a deduplicated line index (
self.linesandself.line_counts) and exposes regex-driven warning/progress extraction. Subclasses supply the raw log lines via_raw_log_lines():Vasplogreads them from a file,Outcarreuses 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']}
- 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}wherenameis the log type and the record carriesmessage,tipsandcount.- Return type:
VaspWarnings
- property progress: VaspWarnings
Parsed progress messages.
- Returns:
Name-keyed progress records. See
VASP_PROGRESSfor 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).
- property warnings: VaspWarnings
Parsed warning records.
- Returns:
Name-keyed warning records. See
VASP_WARNINGSfor 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:
VasprunModified 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_increasewarning. 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:
- 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.
- check_stress()[source]
Check whether the residual hydrostatic stress is acceptable.
- Returns:
True if the hydrostatic stress is below
PRESSURE_CONVERGENCE_THRESHOLD. Records astress_convergencewarning and emitsVaspWarningotherwise.- Return type:
- 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, orcheck_forcesdirectly 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
Outcarparse is not desirable.- Parameters:
- Returns:
Mean and sample std of wall-clock time per SCF cycle and per ionic step, in seconds.
- Return type:
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:
MRFVaspInputSetInput 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 fromvasprun.xmlif no actualINCARfile is present.force_prev_kpoints_file: Same for KPOINTS.inherit_prev_incarpy: When True, copyINCAR.pyfrom 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)
auto_kspacing (bool)
auto_ismear (bool)
auto_ispin (bool)
auto_lreal (bool)
auto_metal_kpoints (bool)
bandgap_tol (float)
bandgap (float | 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
- property incar
INCAR for the derived input set.
Returns None when
force_prev_incar_fileis True and the previous directory has no INCAR file.
- property kpoints
KPOINTS for the derived input set.
Returns None when
force_prev_kpoints_fileis True and the previous directory has no KPOINTS file, or when the previous INCAR usesKSPACING.
- 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:
MRFDerivedInputSetInput 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)
auto_kspacing (bool)
auto_ismear (bool)
auto_ispin (bool)
auto_lreal (bool)
auto_metal_kpoints (bool)
bandgap_tol (float)
bandgap (float | 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'}
- 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).
- target_directory: str | MRFVaspDir
- update_images(beg=None, end=None, **kwargs)[source]
Update NEB images by interpolating between start and end structures.
- Parameters:
beg (None | Structure) – Starting structure. Defaults to
self.structure.end (None | Structure) – Ending structure. Defaults to
self.target_structure.**kwargs (Any) – Forwarded to
matrifflow.pymatgen.core.structure.structure_interpolate2().
- write_input(output_dir, *args, **kwargs)[source]
Write NEB input files to a directory.
In addition to standard behaviour, writes a
NEB-inputs.txtfile recording the initial and final image source directories.- Parameters:
- Return type:
None
Any extra positional and keyword arguments are forwarded to
VaspInputSet.write_input.
- exception MRFNEBVaspInputSetWarning[source]
Bases:
UserWarningWarning 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:
MRFVaspInputSetStandard 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)
auto_kspacing (bool)
auto_ismear (bool)
auto_ispin (bool)
auto_lreal (bool)
auto_metal_kpoints (bool)
bandgap_tol (float)
bandgap (float | 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:
VaspInputSetMatRiFFlow variant of VaspInputSet.
Key additions over pymatgen’s VaspInputSet:
functionalargument for specifying the exchange-correlation functional (seefunctionals.yaml).Automatic SYSTEM name generation from formula, lattice type, and space group.
Structure and input validation (warnings for KPOINTS density, low ENCUT, conflicting NCORE/NPAR).
Default POTCAR_FUNCTIONAL
PBE_64.Visualization of non-trivial selective dynamics as a CIF file.
imagesargument for NEB input sets (writes 00, 01, … subdirectories).no_kpoints,no_potcar,no_poscar,no_incarflags to suppress writing individual files.Writes an
INCAR.tomlrecording non-default metadata (POTCAR mapping, k-point density, functional) so thatgorunand 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)
auto_kspacing (bool)
auto_ismear (bool)
auto_ispin (bool)
auto_lreal (bool)
auto_metal_kpoints (bool)
bandgap_tol (float)
bandgap (float | 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)
- 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 kpoints: Kpoints | None
KPOINTS for the input set.
When
no_kpointsis True, returns None. Otherwise warns if the KPOINTS density is below 5000 or above 15000 k-points/atom.
- property poscar: Poscar
POSCAR for the input set.
Validates the structure before generating the POSCAR.
- 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.logfile, anINCAR.tomlrecording non-default metadata (POTCAR mapping, k-point density, functional), and, for NEB runs, the image subdirectories and a trajectory CIF.- Parameters:
- Return type:
None
Any extra positional and keyword arguments are forwarded to
VaspInputSet.write_input.When
PMG_VASP_PSP_DIRis unconfigured,write_inputdegrades topotcar_spec=Trueinstead of failing: it emits a warning and writesPOTCAR.spec(the symbol list) rather than POTCAR content, leavingINCAR.tomlwith the POTCAR mapping so thatgoruncan regenerate the POTCAR on a cluster where the pseudopotential library is available. A configured-but-missingPMG_VASP_PSP_DIRraises 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 orNone) is marked X rather than silently treated as fixed or free, so that an inconsistent assignment is highlighted.
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_afteroccupies the same sublattice configuration asstr_before, when compared against the referencesublattice.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.
- 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
thresholdis considered acceptable. The default threshold follows ATAT’scheckcellsubroutine.
- fit_sublattice_to_structure(sublattice, structure)[source]
Adjust a reference sublattice to match a relaxed structure.
Useful for building a new
str.outwhen the structure has flipped away from the initial sublattice guess (seecheck_sublattice_flip()). Use'X'dummy species in place of vacancies.
Diffusion
NEB pair generator for diffusion paths.
- class NEB_Graph(*args, backend=None, **kwargs)[source]
Bases:
MultiDiGraphGraph representing diffusion paths between structures.
Nodes are structure indices. Edges are diffusion paths with attributes
distance,vector, andenergy_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_idxsis None, edges use the shortest distances between structures under periodic boundary conditions (self-self paths are ignored).When
jimage_idxsis 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:
- __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_idxsis None, edges use the shortest distances between structures under periodic boundary conditions (self-self paths are ignored).When
jimage_idxsis provided, the specified site indices are used for generating multiple periodic images (range -1..1 in each direction), enabling self-self diffusion path discovery.
- all_diffusion_paths_infinite(idxs=None)[source]
Check whether all given vertices are on infinite diffusion paths.
Structures with the same
_orig_idxproperty are assumed symmetrically equivalent and checked only once.
- 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.
- 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
prototypestructure. 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_unfilteredis True, returns(unique_pairs, all_pairs).- Return type:
- exception get_neb_pairs_warning[source]
Bases:
UserWarningWarning 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:
AbstractTransformationGenerate 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.
- __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.
- all_inserts(structure, limit=None)[source]
Generate all possible molecule insertion configurations.
- 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:
AbstractTransformationGenerate 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
filterandfinal_filtermethods.
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) -> booland may implementfinal_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) -> booland may implementfinal_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:
- Returns:
Single clone when
return_ranked_listis False, otherwise a list of{'structure': ...}dictionaries.- Return type:
- class SymmetryFillTransformation(sym_operations, element_list)[source]
Bases:
AbstractTransformationClone 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.
Command-line interface
Master CLI for VASP workflows and cluster job submission.
- main()[source]
Entry point for the
mrfcommand.- Returns:
Exit code from the selected subcommand.
- Return type:
- main_deprecated_imdg()[source]
Deprecated
imdgentry point: forwards tomain().Kept so the legacy
imdgconsole script keeps working after the MatRiFFlow rename. Prints a one-line notice to stderr first.- Return type:
- 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
- read_field(field, vaspdir)[source]
Read a single analysis field from a VASP directory.
- Parameters:
field (str) – Field name (see
ALL_FIELDSfor 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_from_atom_name(name, size)[source]
Create a boxed periodic structure with a single atom centred.
- 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
mpidproperty set.- Raises:
ValueError – If the Materials Project API key is missing or invalid.
- Return type:
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:
- 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_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:
- Raises:
IOError – If a RUNNING file is found in the input directory and
--force_runningis not set.ValueError – If
--outputis 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.
- 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:
- 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_add_args(parser)[source]
Setup parser arguments for functional.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- incar_add_args(parser)[source]
Setup parser arguments for incar.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- insert_add_args(parser)[source]
Setup parser arguments for inserting an atom/molecule.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- kpoints_add_args(parser)[source]
Setup parser arguments for kpoints.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- neb_add_args(parser)[source]
Setup parser arguments for NEB input.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- neb_diffusion_add_args(parser)[source]
Setup parser arguments for diffusion NEB input.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- perturb_add_args(parser)[source]
Setup parser arguments for perturb.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- potcar_add_args(parser)[source]
Setup parser arguments for POTCAR.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- relax_add_args(parser)[source]
Setup parser arguments for relax.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- scf_add_args(parser)[source]
Setup parser arguments for SCF calculation.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- strain_add_args(parser)[source]
Setup parser arguments for strain.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- 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_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
SYSTEMentry 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
....Noneshows 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:
- 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".
- 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:
- vasp_output_time(path)[source]
Return last VASP output modification time.
Deprecated: use
MRFVaspDir.output_mtime()instead.
Visualization extension specific to MRF group.
- add_args(parser)[source]
Register subcommand arguments.
- Parameters:
parser (ArgumentParser) – Sub-parser from argparse.
- Return type:
None
- atat_add_args(parser)[source]
Setup parser arguments for ATAT visualization.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- hull_add_args(parser)[source]
Setup parser arguments for formation energy hull visualization.
- Parameters:
parser (ArgumentParser) – Subparser from argparse.
- Return type:
None
- 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
- 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:
- 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.