API Reference#
Python API documentation for matchest modules.
Module Overview#
Python functions underlying CLI commands
WorkChains and workgraphs for automated calculations
Structure manipulation, k-points, analysis tools
Code-specific parsing and utilities
Auto-generated Documentation#
CLI Modules#
- matchest.cli.structure.get_primitive_atoms(atoms, threshold=1e-05, angle_tolerance=-1.0, print_spacegroup=False)[source]#
Convert ASE Atoms to primitive cell using spglib
- matchest.cli.structure.get_primitive(input_file=PosixPath('POSCAR'), input_format=None, output_file=None, output_format=None, threshold=1e-05, angle_tolerance=-1.0, verbose=False, precision=6)[source]#
Routines to handle kpoints, mostly based on: WMD-group/kgrid
The reciprocal space of a given structure needs to be sampled with a mesh, the routines in this module is for working out the grid needed with a given spacing (in the reciprocal space) or a cut off length (in the real space).
The former has different units in different codes. In CASTEP, it has a unit of 2pi A^-1 while in VASP/QE it does not have the 2pi factor. In addition, for lattices with orthogonal vectors, the length of a* is simply 1/a, but it is not the case in monoclinic/triclinic systems. So the user may choose to calculate the mesh based on the real space lattice vectors length or with reciprocal lattice vector lengths.
- matchest.cli.kpoints.calc_kpt_tuple_naive(atoms, cutoff_length=10, rounding='up')[source]#
Calculate k-point grid using real-space lattice vectors
- matchest.cli.kpoints.calc_kpt_tuple_recip(atoms, cutoff_length=10, rounding='up')[source]#
Calculate reciprocal-space sampling with real-space parameter
- matchest.cli.kpoints.calc_kpt_tuple(atoms, cutoff_length=10, realspace=False, mode='default')[source]#
Return the kpoint mesh in a tuple with given structure and real space cut off distance
- matchest.cli.kpoints.get_increments(lattice_lengths)[source]#
Calculate the vector l0 of increments between significant length cutoffs for each reciprocal lattice vector.
- matchest.cli.kpoints.cutoff_series(atoms, l_min, l_max, decimals=4)[source]#
Find multiples of l0 members within a range.
- matchest.cli.kpoints.kspacing_series(atoms, l_min, l_max, decimals=4)[source]#
Find series of KSPACING values with different results.
- matchest.cli.kpoints.kpoints_main(filename, file_type, l_min, l_max, comma_sep, vasp, realspace)[source]#
Getting geometry optimization convergence information
Analyze VASP geometry optimization convergence from OUTCAR file.
This module provides a function to extract and analyze convergence information from a VASP OUTCAR file, including energy, forces, stress, computational time, and convergence status.
Based on Fortran code written by Yida Yang
Functions#
- analyze_vasp_convergence(outcar_file: str) -> None
Analyze VASP convergence from OUTCAR file and print results.
- matchest.cli.geomconv.print_vasp_conv(outcar_file)[source]#
Extract and analyze VASP geometry optimization convergence information.
- Parameters:
outcar_file (str) – Path to the VASP OUTCAR file to analyze.
- Returns:
None – Prints formatted convergence information to stdout.
- Return type:
None
Notes
The function extracts the following information for each ionic step: - Total energy (eV) - Energy difference between steps (eV) - Maximum atomic force (eV/Å) - Maximum stress component (GPa) - Computational time (s) - Average drift - Convergence status (YES/NO)
Example
>>> analyze_vasp_convergence("OUTCAR") Step | E (eV) | dE (eV) | Fmax (eV/Å) | Smax (Gpa) | Time (s) | Average drift | Convergence | ----------------------------------------------------------------------------------------------------- 1 -42.123456 -------- 0.123456 1.234567 120.0 0.000123 YES 2 -42.123789 0.000333 0.098765 0.987654 240.0 0.000098 YES EDIFFG= 0.100
VASP input file checker module.
This module provides comprehensive tools to check VASP input files for optimal parallelization settings and computational efficiency. It analyzes INCAR, POSCAR, POTCAR, and KPOINTS files to identify potential issues and provide recommendations for better performance.
- Classes:
VASPInputChecker: Main class for checking individual VASP calculations VaspScanner: Scanner for finding and analyzing multiple VASP calculations CalculationInfo: Data class containing calculation analysis results
- Exceptions:
InputCheckError: Non-critical input file validation errors CriticalInputError: Critical errors that prevent analysis
Example
Basic usage for checking a single calculation:
>>> checker = VASPInputChecker("/path/to/vasp/calculation")
>>> calc_info = checker.check_calculation()
>>> print(f"Found {len(calc_info.issues)} issues")
Scanning multiple calculations:
>>> scanner = VaspScanner("/path/to/calculations", show_progress=True)
>>> dirs = scanner.find_vasp_calculations(recursive=True)
>>> calculations = scanner.check_calculations(dirs)
>>> report = scanner.generate_report(calculations)
- exception matchest.cli.vaspcheck.InputCheckError[source]#
Bases:
ValueErrorError indicating a non-critical problem with the input file.
This exception is raised when there are issues with input files that don’t prevent the analysis from continuing, such as missing optional files or minor formatting issues.
- exception matchest.cli.vaspcheck.CriticalInputError[source]#
Bases:
ValueErrorCritical error when checking inputs that prevents analysis.
This exception is raised for serious issues that make it impossible to analyze the calculation, such as missing required files or severely malformed input files.
- class matchest.cli.vaspcheck.CalculationInfo(path, n_atoms, n_kpoints, n_bands, n_electrons, ncore=None, kpar=None, npar=None, issues=None, ntasks=None, is_hybrid_dft=False, outcar_info=None, metadata=<factory>)[source]#
Bases:
objectInformation about a VASP calculation and its analysis results.
This dataclass stores comprehensive information about a VASP calculation including system properties, parallelization settings, and identified issues.
- path#
Path to the calculation directory
- Type:
- outcar_info#
Additional information extracted from OUTCAR if available
- Properties:
computational_cost: Estimated computational cost (n_kpoints * n_bands²)
- property computational_cost: float | None#
Estimate computational cost proportional to n_kpoints * n_bands².
This provides a rough estimate of the computational complexity, useful for determining appropriate parallelization strategies.
- Returns:
Estimated computational cost, or None if information is insufficient
- __init__(path, n_atoms, n_kpoints, n_bands, n_electrons, ncore=None, kpar=None, npar=None, issues=None, ntasks=None, is_hybrid_dft=False, outcar_info=None, metadata=<factory>)#
- class matchest.cli.vaspcheck.VASPInputChecker(root_dir, min_cost_threshold=1000.0, max_cost_threshold=1000000.0)[source]#
Bases:
objectA comprehensive checker for VASP input files and parallelization settings.
This class examines INCAR, POSCAR, POTCAR, and KPOINTS files to: 1. Parse parallelization settings (NCORE, KPAR, NPAR) 2. Estimate computational requirements 3. Validate parallelization settings against calculation size 4. Identify potential performance issues and provide recommendations
The checker analyzes both input files and output files (if available) to provide comprehensive feedback on calculation setup and efficiency.
- root_dir#
Path to the calculation directory
- min_cost_threshold#
Minimum cost below which parallelization warnings are issued
- max_cost_threshold#
Maximum cost above which efficiency warnings are issued
- incar_path#
Path to INCAR file
- kpoints_path#
Path to KPOINTS file
- poscar_path#
Path to POSCAR file
- potcar_path#
Path to POTCAR file
Example
>>> checker = VASPInputChecker("/path/to/calculation") >>> calc_info = checker.check_calculation(ntasks=64) >>> if calc_info.issues: ... for issue in calc_info.issues: ... print(f"Issue: {issue}")
- __init__(root_dir, min_cost_threshold=1000.0, max_cost_threshold=1000000.0)[source]#
Initialize the VASP input checker.
- parse_incar()[source]#
Parse INCAR file into a dictionary with appropriate type conversion.
Reads the INCAR file and converts values to appropriate Python types: - Boolean values (TRUE/FALSE) are converted to bool - Numeric values are converted to int or float - Other values remain as strings
Comments (lines starting with # or !) are ignored.
- Returns:
Dictionary of INCAR parameters with lowercase keys
- Raises:
InputCheckError – If INCAR file does not exist
- Return type:
Example
>>> checker = VASPInputChecker("/path/to/calc") >>> incar = checker.parse_incar() >>> print(incar['ncore']) # Returns integer value >>> print(incar['lhfcalc']) # Returns boolean value
- parse_poscar_elements()[source]#
Parse POSCAR file to extract element types and their counts.
Reads the element symbols and atom counts from lines 5 and 6 of the POSCAR file. Validates that element names are properly formatted.
- Returns:
Tuple containing – - List of element symbols (e.g., [‘Li’, ‘Fe’, ‘P’, ‘O’]) - List of atom counts for each element (e.g., [1, 1, 1, 4])
- Raises:
CriticalInputError – If element names are invalid or file is malformed
- Return type:
Example
>>> elements, counts = checker.parse_poscar_elements() >>> print(f"System has {sum(counts)} atoms") >>> print(f"Elements: {elements}")
- parse_poscar_structure()[source]#
Parse the complete POSCAR structure including lattice and atomic positions.
Extracts comprehensive structural information from the POSCAR file including lattice vectors, element information, and atomic coordinates. Handles both direct/fractional and Cartesian coordinate formats.
- Returns:
Tuple containing – - lattice_vectors: 3x3 matrix of lattice vectors in Angstroms - element_types: List of element symbols - element_counts: List of atom counts for each element type - atomic_positions: List of atomic positions (fractional or Cartesian)
- Raises:
ValueError – If POSCAR file is malformed or has insufficient data
InputCheckError – If POSCAR file is missing
- Return type:
Tuple[List[List[float]], List[str], List[int], List[List[float]]]
Example
>>> lattice, elements, counts, positions = checker.parse_poscar_structure() >>> print(f"Unit cell volume: {det(lattice):.2f} ų")
- parse_potcar()[source]#
Parse POTCAR file to extract valence electron information.
Reads the POTCAR file to determine the number of valence electrons for each element type. The order matches the element order in POSCAR.
- Returns:
- List of tuples for each element containing – - Element symbol (e.g., ‘Li’)
POTCAR identifier (e.g., ‘Li_sv’)
Number of valence electrons (e.g., 3.0)
Returns None if POTCAR file doesn’t exist
- Return type:
Example
>>> valence_info = checker.parse_potcar() >>> for elem, potcar_id, valence in valence_info: ... print(f"{elem} ({potcar_id}): {valence} valence electrons")
- parse_kpoints()[source]#
Parse KPOINTS file to determine k-point sampling scheme.
Supports multiple k-point generation modes: - Gamma-centered or Monkhorst-Pack grids - Explicit k-point lists - Automatic generation
- Returns:
- For grid-based sampling – Tuple of (mesh_size, mode, shifts) where:
mesh_size: (kx, ky, kz) k-point grid dimensions
mode: ‘g’ for Gamma-centered, ‘m’ for Monkhorst-Pack
shifts: List of shift values or None
- For explicit k-points:
Tuple of (is_cartesian, coordinates, weights) where: - is_cartesian: True if Cartesian coordinates, False if fractional - coordinates: List of k-point coordinates - weights: List of k-point weights
- For automatic:
Returns -1
- Raises:
CriticalInputError – If KPOINTS file is missing
ValueError – If KPOINTS file is malformed
- Return type:
Tuple[Tuple[int, int, int], str, List[int] | None] | Tuple[bool, List[List[float]], List[float]] | int
Example
>>> kpoints_info = checker.parse_kpoints() >>> if isinstance(kpoints_info[0], tuple): ... mesh, mode, shifts = kpoints_info ... print(f"K-point grid: {mesh}")
- parse_outcar()[source]#
Parse OUTCAR file for post-calculation analysis.
Extracts runtime information from a completed or running calculation, including actual parallelization parameters and resource usage.
- Returns:
Dictionary containing – - ‘vasp_version’: VASP version string - ‘ntasks’: Number of MPI tasks used - ‘nkpts’: Actual number of k-points - ‘nbands’: Actual number of bands - ‘each_k_on’: Number of cores per k-point group - ‘num_k_groups’: Number of k-point groups - ‘each_band_on’: Number of cores per band group - ‘num_band_groups’: Number of band groups - ‘loop’: Electronic loop found by LOOP - ‘loop+’: Ionic loop times found by LOOP+
- Return type:
Note
Only available if OUTCAR file exists and calculation has started.
Example
>>> outcar_info = checker.parse_outcar() >>> print(f"Calculation used {outcar_info['ntasks']} MPI tasks")
- parse_submit_script()[source]#
Find and parse job submission script for parallelization settings.
Searches the calculation directory for SLURM submission scripts and extracts resource allocation information.
- Returns:
Dictionary containing – - ‘ntasks’: Total number of tasks requested - ‘found’: Whether a submission script was found - ‘ntasks_per_node’: Tasks per node (if specified) - ‘nodes’: Number of nodes (if specified)
- Return type:
Note
Currently supports SLURM batch scripts. Looks for files with #!/bin/bash shebang and #SBATCH directives.
Example
>>> submit_info = checker.parse_submit_script() >>> if submit_info['found']: ... print(f"Job requested {submit_info['ntasks']} tasks")
- get_ir_kpoints_and_weights(is_time_reversal=True, symprec=1e-05, symmetry_reduce=True)[source]#
Calculate irreducible k-points and weights using crystal symmetry.
Uses the crystal structure and symmetry to determine the minimal set of k-points needed for the calculation.
- Parameters:
- Returns:
Tuple of (irreducible_kpoints, weights) or None if automatic generation
- Raises:
NotImplementedError – For explicit k-point coordinates (not mesh)
- Return type:
Example
>>> ir_kpts, weights = checker.get_ir_kpoints_and_weights() >>> print(f"Reduced to {len(ir_kpts)} irreducible k-points")
- get_kpoints_spacing()[source]#
Return the current effective kpoints spacing
- Returns:
Spacing along a b c directions, in $2pi A^{-1}$
- estimate_nkpts(is_time_reversal=True, symprec=1e-05, symmetry_reduce=True)[source]#
Estimate the number of k-points based on structure and mesh.
Calculates the number of irreducible k-points that will be used in the calculation after symmetry reduction.
- Parameters:
- Returns:
Estimated number of k-points, or None if cannot be determined
- Return type:
int | None
Example
>>> n_kpts = checker.estimate_nkpts() >>> print(f"Calculation will use ~{n_kpts} k-points")
- estimate_bands(elements, counts, valence_list)[source]#
Estimate number of electrons and bands for the calculation.
Calculates the total number of valence electrons and estimates the number of electronic bands needed for the calculation.
- Parameters:
- Returns:
Tuple of (n_electrons, n_bands) or (None, None) if insufficient data
- Raises:
ValueError – If element mismatch between POSCAR and POTCAR
- Return type:
Note
Band estimation uses a heuristic: max(1.3 * n_electrons/2, n_electrons/2 + 10)
Example
>>> n_elec, n_bands = checker.estimate_bands(elements, counts, valence_list) >>> print(f"System has {n_elec} electrons, estimating {n_bands} bands")
- check_calculation(ntasks=None, return_critical=False)[source]#
Perform comprehensive analysis of a VASP calculation.
Analyzes all input files, estimates computational requirements, and identifies potential issues with parallelization settings.
- Parameters:
- Returns:
CalculationInfo object containing complete analysis results
- Return type:
Example
>>> calc_info = checker.check_calculation(ntasks=64) >>> print(f"Computational cost: {calc_info.computational_cost:.2e}") >>> for issue in calc_info.issues: ... print(f"Issue: {issue}")
- class matchest.cli.vaspcheck.VaspScanner(directory, show_progress=False)[source]#
Bases:
objectA scanner for finding and analyzing multiple VASP calculations.
This class provides functionality to: 1. Recursively find VASP calculation directories 2. Scan running/queued SLURM jobs for VASP calculations 3. Batch analyze multiple calculations 4. Generate comprehensive reports
- directory#
Root directory to scan for calculations
- show_progress#
Whether to display progress bars during operations
Example
>>> scanner = VaspScanner("/path/to/calculations", show_progress=True) >>> dirs = scanner.find_vasp_calculations(recursive=True) >>> calculations = scanner.check_calculations(dirs) >>> report = scanner.generate_report(calculations, table_format=True) >>> print(report)
- find_vasp_calculations(recursive=True)[source]#
Find all VASP calculation directories in the specified directory.
Searches for directories containing the minimum required VASP input files (INCAR and POSCAR). Can operate recursively or on the top level only.
- Parameters:
recursive (bool) – If True, search subdirectories recursively
- Returns:
List of Path objects to directories containing VASP calculations
- Return type:
Note
A directory is considered a VASP calculation if it contains both INCAR and POSCAR files.
Example
>>> scanner = VaspScanner("/calculations") >>> vasp_dirs = scanner.find_vasp_calculations(recursive=True) >>> print(f"Found {len(vasp_dirs)} VASP calculations")
- find_vasp_calculations_in_queue()[source]#
Find VASP calculations from running and queued SLURM jobs.
Uses the squeue command to get working directories of all running and queued jobs for the current user, then checks which directories contain VASP calculations. Inaccessible directories are silently ignored.
- Returns:
List of Path objects to VASP calculation directories from active jobs
- Return type:
Note
Requires SLURM workload manager and squeue command availability. Only finds jobs belonging to the current user.
Example
>>> scanner = VaspScanner(".") >>> active_calcs = scanner.find_vasp_calculations_in_queue() >>> print(f"Found {len(active_calcs)} active VASP jobs")
- check_calculations(paths, dir_metadata=None, include_critical=False)[source]#
Analyze multiple VASP calculations in batch.
Processes a list of calculation directories and generates CalculationInfo objects for each valid calculation.
- Parameters:
- Returns:
List of CalculationInfo objects for analyzed calculations
- Return type:
Note
Calculations with critical errors are excluded by default unless include_critical=True. Progress is shown if show_progress=True.
Example
>>> paths = scanner.find_vasp_calculations() >>> calculations, dir_info = scanner.check_calculations(paths, include_critical=True) >>> problematic = [c for c in calculations if c.issues]
- generate_report(calculations=None, output_file=None, only_has_issues=True, table_format=False)[source]#
Generate a comprehensive analysis report.
Creates a detailed report of the calculation analysis results with summary statistics and detailed findings for each calculation.
- Parameters:
calculations (List[CalculationInfo] | None) – List of CalculationInfo objects to report on
output_file (Path | None) – Optional file path to write the report
only_has_issues (bool) – If True, only show calculations with identified issues
table_format (bool) – If True, use tabular format (requires tabulate package)
- Returns:
Report as a formatted string
- Return type:
Note
Table format provides a more compact overview, while detailed format shows comprehensive information for each calculation.
Example
>>> report = scanner.generate_report(calculations, ... output_file=Path("report.txt"), ... table_format=True) >>> print("Report generated successfully")
AiiDA Workflows#
AiiDA Workgraphs#
Utilities#
Generating (symmetry-reduced) k-point grids using spglib
- matchest.utils.kmesh.grid_address_to_recip_coord(points, mesh, is_shift=None)[source]#
Convert grid address to fractional coordinates in the reciprocal space
- matchest.utils.kmesh.get_ir_kpoints_and_weights(cell, scaled_positions, numbers, mesh, is_time_reversal=True, symprec=1e-05, is_shift=None, symmetry_reduce=True)[source]#
Return fractional coordinates of irreducible k-points from a given mesh. Note: The current implementation does not support using only time-reversal symmetry.
- Parameters:
atoms – An ASE atoms object
mesh – A tuple/list for the meshes in each direction or a single number for kpoint distance
is_time_reversal – Whether to use time-reversal symmetry or not.
symprec – Symmetry precision
is_shift – A tuple/list for the shift of the mesh, use [1, 1, 1] for MP Grid.
use_symmetry – Whether to use symmetry or not. If False, the k-points are not reduced at all.
- Returns:
A tuple of (kpoints, weights).
- matchest.utils.kmesh.get_ir_kpoints_and_weights_from_atoms(atoms, mesh, is_time_reversal=True, symprec=1e-05, is_shift=None, symmetry_reduce=True)[source]#
Return fractional coordinates of irreducible k-points from a given mesh. Note: The current implementation does not support using only time-reversal symmetry.
- Parameters:
atoms – An ASE atoms object
mesh – A tuple/list for the meshes in each direction or a single number for kpoint distance
is_time_reversal – Whether to use time-reversal symmetry or not.
symprec – Symmetry precision
is_shift – A tuple/list for the shift of the mesh, use [1, 1, 1] for MP Grid.
symmetry_reduce – Whether to reduce the k-points using symmetry.
- Returns:
A tuple of (kpoints, weights).
- matchest.utils.kmesh.get_ir_kpoints_and_weights_from_pymatgen(structure, mesh, is_time_reversal=True, symprec=1e-05, is_shift=None, symmetry_reduce=True)[source]#
Return fractional coordinates of irreducible k-points from a given mesh. Note: The current implementation does not support using only time-reversal symmetry.
- Parameters:
structure – A pymatgen Structure object
mesh – A tuple/list for the meshes in each direction or a single number for kpoint distance
is_time_reversal – Whether to use time-reversal symmetry or not.
symprec – Symmetry precision
is_shift – A tuple/list for the shift of the mesh, use [1, 1, 1] for MP Grid.
symmetry_reduce – Whether to reduce the k-points using symmetry.
- Returns:
A tuple of (kpoints, weights).
Pymatgen related tools
- matchest.aiida_utils.pmg.get_energy_from_misc(misc)[source]#
Get energy from misc output Dict/dictionary
- matchest.aiida_utils.pmg.load_mp_struct(mp_id, api_key=None)[source]#
Load Material Project structures using its api
- matchest.aiida_utils.pmg.reduce_formula_no_polyanion(sym_amt, iupac_ordering=False)[source]#
Helper method to reduce a sym_amt dict to a reduced formula and factor. Unlike the original pymatgen version, this function does not do any polyanion reduction
- Parameters:
sym_amt (dict) – {symbol: amount}.
iupac_ordering (bool, optional) – Whether to order the formula by the iupac “electronegativity” series, defined in Table VI of “Nomenclature of Inorganic Chemistry (IUPAC Recommendations 2005)”. This ordering effectively follows the groups and rows of the periodic table, except the Lanthanides, Actanides and hydrogen. Note that polyanions will still be determined based on the true electronegativity of the elements.
- Returns:
(reduced_formula, factor).
- Return type:
- matchest.aiida_utils.pmg.get_entry_from_calc(calc)[source]#
Get a ComputedStructure entry from a given calculation/workchain
VASP relaxed utility functions
CASTEP Utilities#
Utility module for analysing CASTEP data
- matchest.casteputils.atoms_to_castep(atoms, index)[source]#
Convert ase atoms’ index to castep like return (Specie, Ion) Depricatede, use ase_to_castep_index
- matchest.casteputils.ase_to_castep_index(atoms, indices)[source]#
Convert a list of indices to castep syle return list of (element, i in the same element)
- matchest.casteputils.generate_ionic_fix_cons(atoms, indices, mask=None)[source]#
create ionic constraint section via indices and ase Atoms mask: a list of 3 integers, must be 0 (no fix) or 1 (fix this cartesian)
- matchest.casteputils.castep_to_atoms(atoms, specie, ion)[source]#
Convert castep like index to ase Atoms index
- matchest.casteputils.sort_atoms_castep(atoms, copy=True, order=(0, 1, 2))[source]#
Sort atoms to castep style :param copy: If True then return a copy of the atoms. :param order: orders of coordinates. (0, 1, 2) means the sorted atoms will be ascending by x, then y, then z if there are equal x or ys.
- matchest.casteputils.take_popn(seed)[source]#
Take section of population analysis from a seed.castep file Return a list of StringIO of the population analysis section
- matchest.casteputils.count_scf_lines(lines)[source]#
Extract the number of SCF cycles in the CASTEP files
A parser for dot casteps
- class matchest.dotcastep.ScfStats(data, tags)[source]#
Bases:
objectClass representation of SCF loops leading to electronic convergence
- property avg_time#
- property mean_loop#
The mean time of a electronic (SCF) loop
- property ffree#
Final free energy
- property duration#
- property start#
- property finish#
- class matchest.dotcastep.DotCastep(fhandle)[source]#
Bases:
objectClass for a .castep file
- __init__(fhandle)[source]#
Initialise an DotCastep instance
- Parameters:
fhandle (handle-like object) – A file handle for the CASTEP file
- property scfs#
Return a list of SCF stats objects
- property mean_loop#
Return the average LOOP times
This does not include the time for computing forces/stress etc.
- property mean_scf_steps#
The average number of electronic steps per ionic step
- property mean_ionic_loop#
The average time spent on each ionic step
- property parallel_info#
Acquire the parallelisation information
Usage Examples#
Importing Modules#
# CLI functions
from matchest.cli.structure import get_primitive_atoms
from matchest.cli.kpoints import calc_kpt_tuple
# AiiDA workflows
from matchest.aiida_utils.workflows.elastic import VaspElasticWorkChain
# Utilities
from matchest.aiida_utils.pmg import aiida_to_pymatgen
Structure Analysis#
import ase.io
from matchest.cli.structure import get_primitive_atoms
atoms = ase.io.read("POSCAR")
primitive = get_primitive_atoms(atoms, threshold=1e-5)
print(f"Reduced from {len(atoms)} to {len(primitive)} atoms")
K-points Calculation#
from matchest.cli.kpoints import calc_kpt_tuple, cutoff_series
import ase.io
atoms = ase.io.read("POSCAR")
# Single k-point grid
kpts = calc_kpt_tuple(atoms, cutoff_length=15.0)
print(f"K-points: {kpts}")
# Series for convergence
cutoffs = cutoff_series(atoms, l_min=10, l_max=30)
for cutoff in cutoffs:
kpts = calc_kpt_tuple(atoms, cutoff_length=cutoff)
print(f"{cutoff:.2f} Å → {kpts}")