matcalc._base module
Define basic API.
- class ChainedCalc(prop_calcs: Sequence[PropCalc])[source]
Bases:
PropCalcA chained calculator that runs a series of PropCalcs on a structure or set of structures.
Often, you may want to obtain multiple properties at once, e.g., perform a relaxation followed by a formation energy computation and an elasticity calculation. This can be done by supplying a list of calculators. Each calculator receives the full result dict from the previous step, so downstream calculators can skip redundant relaxations by setting
relax_structure=False.Initialize a chained calculator.
- Parameters:
prop_calcs – Sequence of prop calcs.
- calc(structure: Structure | Atoms | dict[str, Any]) dict[str, Any][source]
Runs the series of PropCalcs on a structure.
- Parameters:
structure – Pymatgen structure or a dict containing a pymatgen Structure under a “final_structure” or “structure” key. Allowing dicts provide the means to chain calculators, e.g., do a relaxation followed by an elasticity calculation.
- Returns:
Merged dict from all steps (final keys depend on the chain).
- calc_many(structures: Sequence[Structure | Atoms | dict[str, Any]], n_jobs: int | None = None, allow_errors: bool = False, **kwargs: Any) Generator[dict | None, None, None][source]
Runs the sequence of PropCalc on many structures.
Each structure is run through the whole chain in a single job, so intermediate results are not shipped between workers and a structure that fails at any step yields
None(withallow_errors) instead of being fed to the next calculator.- Parameters:
structures – List or generator of Structures.
n_jobs – The maximum number of concurrently running jobs. If -1 all CPUs are used. For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. None is a marker for unset that will be interpreted as n_jobs=1 unless the call is performed under a parallel_config() context manager that sets another value for n_jobs.
allow_errors – Whether to skip failed calculations. For these calculations, None will be returned. For large scale calculations, you may want this to be True to avoid the entire calculation failing. Defaults to False.
**kwargs – Passthrough to
joblib.Parallel.
- Returns:
Generator of dicts.
- class PropCalc[source]
Bases:
ABCAbstract base class for property calculations.
This class defines the interface for performing property calculations on structures (using pymatgen’s Structure objects or a dictionary containing a pymatgen structure). Subclasses are expected to implement the calc method to define specific property calculation logic. Additionally, this class provides an implementation of the calc_many method, which enables concurrent calculations on multiple structures using joblib.
- _check_and_prelax(structure: Structure | Atoms, result: dict[str, Any], *, relax: bool | None = None, **relax_kwargs: Any) tuple[dict[str, Any], Structure | Atoms][source]
Optionally relax
structureand merge the relaxation result.Centralises the
if self.relax_structure: ... else ...pattern shared by most property calculators. Honorsself.relax_structure; when False (or absent), the input is returned unchanged.Constructs a fresh
RelaxCalcusingself.calculatorand the merged kwargs each call. Callers that need to reuse a relaxer for downstream relaxations (deformed cells, elemental references, …) should hold their ownRelaxCalcinstance and use it directly.- Parameters:
structure – Input structure (already extracted from the result dict).
result – The current result dict; relaxation outputs are merged in.
relax – Whether to relax.
None(default) usesself.relax_structure; calcs that gate the relaxation on another flag (e.g.relax_bulk) pass it explicitly.**relax_kwargs – Forwarded to
RelaxCalc.relax_calc_kwargson the subclass (if any) takes precedence over these, mirroring the existing per-calc convention.
- Returns:
(result, structure)— both updated when a relaxation ran, both unchanged otherwise.- Raises:
RuntimeError – If the pre-relaxation did not converge within
max_steps. Downstream property calculations (elastic constants, EOS, phonons, …) sample the PES around what is meant to be an equilibrium structure; running them on an unrelaxed structure yields physically meaningless numbers, so the chain is aborted rather than propagating bad inputs.
- static _merge_units(prev: dict[str, Any] | None, new: dict[str, str]) dict[str, str][source]
Merge unit annotations, preserving upstream entries.
Use this when building the
_unitsfield on a result dict that may already contain_unitsfrom an earlier step in a chain. Keys present innewoverwrite the upstream value (the calc emitting them owns the unit string for those fields).- Parameters:
prev – The upstream result dict (or its
_unitsvalue), orNone.new – The units this calc is contributing.
- Returns:
A merged dict suitable for use as the
_unitsfield.
- _relaxer(**kwargs: Any) RelaxCalc[source]
Build a
RelaxCalcforself.calculator, withrelax_calc_kwargstaking precedence.Use this instead of
RelaxCalc(..., fmax=..., **self.relax_calc_kwargs), which raises a duplicate-keywordTypeErrorwhenrelax_calc_kwargsrepeats one of the explicit arguments.- Parameters:
**kwargs – Default
RelaxCalcarguments for this relaxation (e.g.fmax,relax_cell). Entries in the subclass’srelax_calc_kwargs(if any) override them.- Returns:
A new
RelaxCalc.
- abstractmethod calc(structure: Structure | Atoms | dict[str, Any]) dict[str, Any][source]
Abstract method to calculate and process a given structure.
Processes a provided structure in the form of a pymatgen Structure, ASE Atoms, or a dictionary with specific keys, and returns a processed dictionary. If the input structure is a dictionary, it must contain the key final_structure or structure; otherwise, a ValueError is raised. The returned dictionary includes the key final_structure pointing to the provided or derived structure.
- Parameters:
structure – A Structure, Atoms, or dict containing structural data to be processed. If a dictionary is provided, it must include either final_structure or structure keys.
- Returns:
A dictionary with the key final_structure, representing the provided structure or the structure derived from the dictionary input.
- Raises:
ValueError – If the provided dictionary does not contain the required keys final_structure or structure.
- calc_many(structures: Sequence[Structure | dict[str, Any] | Atoms], n_jobs: int | None = None, allow_errors: bool = False, **kwargs: Any) Generator[dict | None, None, None][source]
Calculates multiple structures in parallel with optional error tolerance.
This method processes a sequence of structures, allowing them to be calculated in parallel. It offers the ability to handle errors on a per-structure basis. If error tolerance is enabled, calculation failures for individual structures result in returning None for those structures, without raising exceptions.
With the default (loky) backend, joblib limits each worker to
cpu_count() // n_workersBLAS/OpenMP/torch threads. If such a limit (e.g.OMP_NUM_THREADS) is set to a larger value in the calling environment, joblib would pass it through to every worker and oversubscribe the CPU, so it is lowered tocpu_count() // n_workersin the workers. To choose the per-worker thread count yourself, wrap the call injoblib.parallel_config(backend="loky", inner_max_num_threads=...)or passbackend.- Parameters:
structures – Sequence of structures or structure dicts.
n_jobs –
joblibworker count;Noneuses joblib defaults.allow_errors – If True, failed structures yield
Noneinstead of raising.**kwargs – Forwarded to
joblib.Parallel.
- Yields:
Result dict from
calc, orNonewhenallow_errorsand a structure fails.- Raises:
Exception – Any error from
calcwhenallow_errorsis False.
- property calculator: Calculator[source]
Provides access to the Calculator instance used internally.
This property retrieves an instance of the Calculator class, which is associated with the current object and utilized internally for performing operations or calculations. The property ensures encapsulation and controlled access to the underlying calculator.
- Returns:
The internal ASE calculator instance.
- _worker_thread_cap(n_jobs: int | None, parallel_kwargs: dict[str, Any]) int | None[source]
Per-worker thread limit needed to keep loky workers from oversubscribing the CPU.
joblib’s loky backend sets
OMP_NUM_THREADS,MKL_NUM_THREADS, … tocpu_count() // n_workersin its workers, which is what keeps torch’s intra-op thread pool in check. It does so only for variables that are unset in the parent: an inherited value (e.g.OMP_NUM_THREADS=$SLURM_CPUS_PER_TASKin a job script) is passed to every worker unchanged, so n_workers processes each run that many torch threads.- Parameters:
n_jobs –
n_jobsas passed tocalc_many.parallel_kwargs – Extra
joblib.Parallelkwargs; an explicit backend choice is left alone.
- Returns:
min(cpu_count() // n_workers, inherited limits)if an inherited limit would oversubscribe the default loky backend, elseNone(joblib’s own behavior is kept).