API Reference¶
This page is generated automatically from the docstrings of egqca. Everything listed here is re-exported through the package namespace, so it can be imported directly as egqca.<name>.
The narrative documentation of the individual workflows is in Home, ML Workflow, Cluster Reduction, Properties Averaging, and DFT Input Files.
Main Class¶
EGQCA ¶
EGQCA(
datafile: str | Path,
out_folder_name: str | None = None,
dft_out_file_name: str | None = None,
dft_out_file_subfolder: str = "vc-relax",
permutable_sites: int | None = None,
sites: int | None = None,
compound: str | None = None,
volume_file: str | None = None,
pressure_GPa: float = 0.0,
phonon_file_name: str | None = None,
aims_use_zero_broadening_corrected_energy: bool = False,
entropy_approximation: str = "overlapping",
)
Generalized quasichemical approximation (GQCA) for a binary alloy, with optional vibrational contributions from phonon DOS and optional PV (enthalpy) correction as described in https://doi.org/10.1016/j.mtphys.2024.101547
All energies are mixing energies in meV per site, where "site" is one of the
sites sites of a cluster (not one of the permutable_sites).
If volume_file and pressure_GPa are given, we add a PV term
(enthalpy per site) based on the cell volume from volume.dat.
Public usage: m = EGQCA( datafile="clusters.dat", # sites, permutable sites and compound phonon_file_name="phonons", # are read from its header volume_file="volume.dat", pressure_GPa=0.0, ) x = np.arange(0.0, 1.0, 1e-3) Tlist = [600, 800, 1000, 1400] m.thermodynamic_assessment(x, Tlist) # p_j(x,T), Delta H/G/S, miscibility gap m.average_properties("volume.dat") # any per-cluster property, averaged m.cluster_importance(x, Tlist) # smallest sufficient cluster set
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datafile
|
str
|
Path to clusters.dat (columns: ID, n_j, Nat, x_j, g_j, E_j in Ry). |
required |
permutable_sites
|
int
|
Number of permutable sites in the cluster. Read from the clusters.dat header (n=) when None. |
None
|
sites
|
int
|
Total number of sites in the cluster; all energies are reported per such site. Read from the clusters.dat header (sites=) when None. |
None
|
compound
|
str | None
|
Name of the compound in the format A\(_{1-x}\)B\(_x\) for plotting |
None
|
volume_file
|
str or None
|
Path to volume.dat with the lattice parameters of every cluster (ID, a, b, c, alpha, beta, gamma). Only used if pressure_GPa != 0. |
None
|
pressure_GPa
|
float
|
External pressure in GPa. If 0.0, no PV term. |
0.0
|
phonon_file_name
|
str | None
|
Either a directory of |
None
|
aims_use_zero_broadening_corrected_energy
|
bool
|
Whether to use the zero-broadening corrected energy from FHI-aims output or the total energy. |
False
|
entropy_approximation
|
str
|
How the clusters tile the crystal, which sets the weight of the Kullback-Leibler term in the entropy and, consistently, the Boltzmann factor of the cluster probabilities:
E_j is the mixing energy of the whole cluster (delta_j * sites). |
'overlapping'
|
Source code in src/egqca/egqca_model.py
def __init__(self, datafile: str | Path, out_folder_name: str | None = None,
dft_out_file_name:str | None = None, dft_out_file_subfolder: str = "vc-relax",
permutable_sites: int | None = None, sites: int | None = None,
compound: str | None = None,
volume_file: str | None = None, pressure_GPa: float=0.0,
phonon_file_name: str | None=None,
aims_use_zero_broadening_corrected_energy: bool = False,
entropy_approximation: str = "overlapping"):
"""
Parameters
----------
datafile : str
Path to clusters.dat (columns: ID, n_j, Nat, x_j, g_j, E_j in Ry).
permutable_sites : int
Number of permutable sites in the cluster. Read from the clusters.dat
header (n=) when None.
sites : int
Total number of sites in the cluster; all energies are reported per
such site. Read from the clusters.dat header (sites=) when None.
compound: str
Name of the compound in the format A$_{1-x}$B$_x$ for plotting
volume_file : str or None
Path to volume.dat with the lattice parameters of every cluster
(ID, a, b, c, alpha, beta, gamma). Only used if pressure_GPa != 0.
pressure_GPa : float
External pressure in GPa. If 0.0, no PV term.
phonon_file_name: str | None
Either a directory of ``<cluster_id>.dos`` files (resolved relative to
the clusters folder when not absolute, e.g. an ML run's
``<output_dir>/phonons``), or the name of the phonon DOS file expected
in each cluster folder under ``phonons/``.
aims_use_zero_broadening_corrected_energy: bool
Whether to use the zero-broadening corrected energy from FHI-aims output or the total energy.
entropy_approximation: str
How the clusters tile the crystal, which sets the weight of the
Kullback-Leibler term in the entropy and, consistently, the
Boltzmann factor of the cluster probabilities:
- ``"overlapping"``: S/kB = -(n/sites) [x ln x + (1-x) ln(1-x) + D],
p_j ~ p0_j exp(-E_j / (n kB T)).
- ``"non-overlapping"``: S/kB = -(n/sites) [x ln x + (1-x) ln(1-x)] - D/sites,
p_j ~ p0_j exp(-E_j / (kB T)).
E_j is the mixing energy of the whole cluster (delta_j * sites).
"""
# Plotting style
self.style = {
"font.family": "serif",
"font.serif": ["Times"],
"font.size": 22,
# fall back to mathtext when no LaTeX is installed
"text.usetex": _latex_available(),
"axes.linewidth": 3.5,
"xtick.major.width": 3.5,
"ytick.major.width": 3.5,
}
# Parameters
self.pressure_GPa = float(pressure_GPa)
self.pj = {}
# vibrational free energies per cluster and T: probability inputs, kept across
# init_thermo (they depend only on T and the phonon data)
self.Fvib_j = {}
self.deltaFvib_j = {}
self.grid_compare_rtol = 1e-8
self.grid_compare_atol = 1e-10
self.current_output_dir = None
self.thermodynamic_assessment_dir = None
self.averaging_dir = None
self.cluster_reduction_dir = None
self.entropy_approximation = entropy_approximation
self.set_up(
datafile=datafile,
out_folder_name=out_folder_name,
dft_out_file_name=dft_out_file_name,
dft_out_file_subfolder=dft_out_file_subfolder,
permutable_sites=permutable_sites,
sites=sites,
compound=compound,
volume_file=volume_file,
phonon_file_name=phonon_file_name,
aims_use_zero_broadening_corrected_energy=aims_use_zero_broadening_corrected_energy
)
entropy_approximation
property
writable
¶
entropy_approximation: str
"overlapping" or "non-overlapping", see the class docstring.
D_weight
property
¶
D_weight: float
Weight w of the KL divergence in the entropy, S/kB = ... - (w/sites) D.
w = n for overlapping clusters, w = 1 for non-overlapping clusters. The Boltzmann factor that minimizes F with this entropy is exp(-beta * delta_j * sites / w).
set_up ¶
set_up(
datafile: str | Path,
out_folder_name: str | None = None,
dft_out_file_name: str | None = None,
dft_out_file_subfolder: str = "vc-relax",
permutable_sites: int | None = None,
sites: int | None = None,
compound: str | None = None,
volume_file: str | None = None,
phonon_file_name: str | None = None,
aims_use_zero_broadening_corrected_energy: bool = False,
)
Read the EGQCA input files and initialize the model state.
Source code in src/egqca/egqca_model.py
def set_up(
self,
datafile: str | Path,
out_folder_name: str | None = None,
dft_out_file_name: str | None = None,
dft_out_file_subfolder: str = "vc-relax",
permutable_sites: int | None = None,
sites: int | None = None,
compound: str | None = None,
volume_file: str | None = None,
phonon_file_name: str | None = None,
aims_use_zero_broadening_corrected_energy: bool = False,
):
"""Read the EGQCA input files and initialize the model state."""
self.datafile = Path(datafile)
self.clusters_folder = self.datafile.parent.parent # folder containing S* cluster dirs
if out_folder_name is None:
self.out_dir = self.datafile.parent
else:
self.out_dir = self.datafile.parent / out_folder_name
self.dft_out_file_name = dft_out_file_name
self.dft_out_file_subfolder = dft_out_file_subfolder
# ------------------- Clusters -------------------- #
cluster_id, nj, Nat, xj, gj, Ej_Ry, sites, permutable_sites, compound = read_clusters_dat(
self,
self.datafile,
dft_out_file_name,
sites,
permutable_sites,
compound,
dft_out_file_subfolder,
aims_use_zero_broadening_corrected_energy,
)
Nat = np.asarray(Nat, dtype=int)
self.nj = np.asarray(nj, dtype=int)
self.xj = np.asarray(xj, dtype=float)
self.gj = np.asarray(gj, dtype=float)
self.n = permutable_sites
self.cluster_id = cluster_id
self.sites = sites
self.compound = compound
# meV / total sites
E_elec = Ej_Ry * Ry_to_mev / float(self.sites)
# ------------------- Volume -------------------- #
if volume_file is None and dft_out_file_name is None and self.pressure_GPa != 0.0:
warnings.warn(
f"pressure_GPa={self.pressure_GPa:g} was given, but including the pressure (PV term) "
"requires cell volumes (volume_file or dft_out_file_name). No volume was given, "
"so the pressure is set to 0 GPa.",
stacklevel=3,
)
self.pressure_GPa = 0.0
if (volume_file is not None or dft_out_file_name is not None) and (self.pressure_GPa != 0.0):
Ep, volume_file = read_volume_dat(
self,
volume_file,
dft_out_file_name,
dft_out_file_subfolder,
E_elec,
)
E_elec += Ep
self.volume_file = volume_file
self.Hj = E_elec
# ------------------- Phonons -------------------- #
self.phonon_file_name = phonon_file_name
if phonon_file_name is not None:
self.phonon_data = read_phonons(self, phonon_file_name, sites)
else:
self.phonon_data = None
# new data: no earlier result is valid any more
self._reset_results(keep_vibrational=False)
thermodynamic_assessment ¶
thermodynamic_assessment(
x: ndarray,
Tlist: list[float],
run_miscibility_gap: bool = True,
T_min_misc_gap: float = 30,
misc_gap_max_iter: int = 200,
dx_plot: float = 0.01,
plot_flag: bool = True,
figsize: tuple = (6, 6),
enumerate_clusters: bool = False,
)
Run the thermodynamic assessment workflow and save outputs in thermodynamic_assessment.
enumerate_clusters writes the cluster numbers (1, 2, ... in clusters.dat order)
into the excess energy and p_j plots, and the key cluster_numbers.dat.
Source code in src/egqca/egqca_model.py
@entry_point("Thermodynamic assessment", lambda b: b.arguments["self"]._run_summary("Thermodynamic assessment", b))
def thermodynamic_assessment(self, x:np.ndarray, Tlist:list[float], run_miscibility_gap:bool = True, T_min_misc_gap:float=30, misc_gap_max_iter:int=200, dx_plot:float= 0.01, plot_flag:bool = True, figsize:tuple=(6,6), enumerate_clusters:bool = False):
"""Run the thermodynamic assessment workflow and save outputs in ``thermodynamic_assessment``.
``enumerate_clusters`` writes the cluster numbers (1, 2, ... in clusters.dat order)
into the excess energy and p_j plots, and the key ``cluster_numbers.dat``.
"""
if not self._grid_matches_cached(x, Tlist):
self.pj = {}
x = self._prepare_main(x, Tlist, output_subfolder="thermodynamic_assessment")
# plot excess energies
self.plot_excess_enthalpy(figsize=figsize, enumerate_clusters=enumerate_clusters)
self.init_thermo()
self._ensure_probabilities(x, Tlist)
for T in Tlist:
print(f'Calculating the mixing free energy at T = {T}...')
self.thermo(T)
print('Done!')
if run_miscibility_gap:
self.calc_miscibility_gap(x, T_min=T_min_misc_gap, dx_plot=dx_plot, max_iter=misc_gap_max_iter)
print("Saving thermodynamic assessment...")
self.plot_thermo(addLineLabel=True, figsize=figsize)
if run_miscibility_gap:
self.plot_miscibility_gap(figsize=figsize)
if plot_flag and len(Tlist) > 1:
self.plot_probabilities_vs_T(x[np.unique([len(x)//4, len(x)//2, 3*len(x)//4])], figsize=figsize, enumerate_clusters=enumerate_clusters)
self.plot_KL_divergence_vs_T(x[np.unique([len(x)//4, len(x)//2, 3*len(x)//4])], figsize=figsize)
if self.volume_file is not None and (self.pressure_GPa != 0.0): # plot flag?
self.plot_lat_pars(self.x_plot, Tlist, figsize=figsize)
average_properties ¶
average_properties(
properties_file: str | Path | list[str | Path] | tuple[str | Path, ...],
Tlist: list[float] | None = None,
x: ndarray | None = None,
idx_clusters_surrogate: dict[float, dict[float | str, list[int]]] | None = None,
surrogate_model: (
str | Path | list[str | Path] | tuple[str | Path, ...] | None
) = None,
ylabels: list[str] | None = None,
columns: list[int] | list[list[int]] | None = None,
legend_labels: list[str] | None = None,
figsize: tuple = (6, 6),
)
Average properties and save outputs.
properties_file may be a single file or a list of files; when several are
given their curves for the same property are overlaid in one figure. columns
optionally selects a subset of property columns by index (excluding the ID
column), either as a single list applied to every file or one list per file.
If no new x or Tlist is provided, cached occurrence probabilities
from a previous thermodynamic assessment are reused. If a different grid
is requested, the probabilities are recalculated before averaging.
Source code in src/egqca/egqca_model.py
@entry_point("Property averaging", lambda b: b.arguments["self"]._run_summary("Property averaging", b))
def average_properties(
self,
properties_file: str | Path | list[str | Path] | tuple[str | Path, ...],
Tlist:list[float] | None = None,
x:np.ndarray | None = None,
idx_clusters_surrogate: dict[float, dict[float | str, list[int]]] | None = None,
surrogate_model: str | Path | list[str | Path] | tuple[str | Path, ...] | None = None,
ylabels: list[str] | None = None,
columns: list[int] | list[list[int]] | None = None,
legend_labels: list[str] | None = None,
figsize: tuple = (6, 6),
):
"""Average properties and save outputs.
``properties_file`` may be a single file or a list of files; when several are
given their curves for the same property are overlaid in one figure. ``columns``
optionally selects a subset of property columns by index (excluding the ID
column), either as a single list applied to every file or one list per file.
If no new ``x`` or ``Tlist`` is provided, cached occurrence probabilities
from a previous thermodynamic assessment are reused. If a different grid
is requested, the probabilities are recalculated before averaging.
"""
if isinstance(properties_file, (str, Path)):
properties_files = [Path(properties_file)]
else:
properties_files = [Path(pf) for pf in properties_file]
if not properties_files:
raise ValueError("At least one properties file must be provided.")
cached_x = getattr(self, "x", None)
cached_Tlist = getattr(self, "Tlist", None)
cached_pj = getattr(self, "pj", None)
has_cached_probabilities = bool(cached_pj)
if x is None and Tlist is None:
if not has_cached_probabilities or cached_x is None or cached_Tlist is None:
raise ValueError(
"No cached probabilities available. Run thermodynamic_assessment first or provide both x and Tlist."
)
x = np.asarray(cached_x, dtype=float)
Tlist = list(np.asarray(cached_Tlist, dtype=float))
reuse_probabilities = True
else:
if x is None:
if cached_x is None:
raise ValueError(
"No cached composition grid available. Provide x or run thermodynamic_assessment first."
)
x = np.asarray(cached_x, dtype=float)
if Tlist is None:
if cached_Tlist is None:
raise ValueError(
"No cached temperature grid available. Provide Tlist or run thermodynamic_assessment first."
)
Tlist = list(np.asarray(cached_Tlist, dtype=float))
x = self._sanitize_x_grid(x)
Tlist = list(self._sanitize_temperature_grid(Tlist))
reuse_probabilities = has_cached_probabilities and self._grid_matches_cached(x, Tlist)
if surrogate_model is not None and idx_clusters_surrogate is not None:
raise ValueError("Provide either surrogate_model or idx_clusters_surrogate, not both.")
if surrogate_model is not None:
if isinstance(surrogate_model, (str, Path)):
surrogate_models = [Path(surrogate_model)]
else:
surrogate_models = [Path(model_path) for model_path in surrogate_model]
if not surrogate_models:
raise ValueError("At least one surrogate model path must be provided.")
surrogate_indices_by_name = {
surrogate_path.stem: self._read_surrogate_model_indices(surrogate_path)
for surrogate_path in surrogate_models
}
idx_clusters_surrogate = {
T: surrogate_indices_by_name
for T in Tlist
}
x = self._prepare_main(x, Tlist, output_subfolder="results")
if not reuse_probabilities:
self.pj = {}
self._ensure_probabilities(x, Tlist)
return properties.calculate_averages(self, properties_file=properties_files, Tlist=Tlist, x_grid=self.x_plot, idx_clusters_surrogate=idx_clusters_surrogate, ylabels=ylabels, columns=columns, legend_labels=legend_labels, figsize=figsize)
cluster_importance ¶
cluster_importance(
x: ndarray,
Tlist: list[float],
top_percentage: list[float] = [0.02, 0.05, 0.1],
plot_flag: bool = True,
figsize: tuple = (6, 6),
enumerate_clusters: bool = False,
)
Find a subset with top_percentage% of cluster which are sufficient to describe the properties of the solid solution.
enumerate_clusters writes the cluster numbers into the p_j plots, see
:meth:thermodynamic_assessment.
Source code in src/egqca/egqca_model.py
@entry_point("Cluster importance", lambda b: b.arguments["self"]._run_summary("Cluster importance", b))
def cluster_importance(self, x:np.ndarray, Tlist:list[float], top_percentage:list[float]=[0.02, 0.05, 0.1], plot_flag:bool = True, figsize:tuple=(6,6), enumerate_clusters:bool = False):
"""
Find a subset with top_percentage% of cluster which are sufficient to describe the properties of the solid solution.
``enumerate_clusters`` writes the cluster numbers into the p_j plots, see
:meth:`thermodynamic_assessment`.
"""
x = self._prepare_main(x, Tlist, output_subfolder="cluster_reduction")
# probabilities of earlier calls on the same x grid are reused
self._ensure_probabilities(x, Tlist)
# --- find most important clusters --- #
self.rank_clusters(x, Tlist, top_percentage)
# ---------------- Plot -------------- #
# plot cluster occurence probabilities
if plot_flag:
self.plot_probabilities_vs_x(Tlist, figsize=figsize, enumerate_clusters=enumerate_clusters)
return self.S_clusters
Cluster and DFT Setup¶
set_up_clusters_and_dft ¶
set_up_clusters_and_dft(
supercell_program: str,
path_to_cif: str,
supercell_size: str,
out_dir: str,
qe_par: dict | None = None,
aims_par: dict | None = None,
vasp_par: dict | None = None,
kpts=None,
create_dft_folders: bool = False,
substitution_mode: str = "auto",
cif_only: bool = False,
)
Create all non-equivalent clusters of size supercell_size and set up the corresponding folder structure containing templates for the DFT input files.
The cluster setup (compound, sites, permutable sites n, one row per cluster) is
written to <out_dir>/clusters_template.dat, which every run folder (DFT, ML,
EDDP) reads. The DFT run folder <out_dir>/DFT with a copy of it as
clusters.dat is only created when create_dft_folders is set or one of
qe_par, aims_par, vasp_par is given; :func:update_DFT_in creates it
later otherwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
supercell_program
|
str
|
Path to the supercell executable. |
required |
path_to_cif
|
str
|
Path to the CIF file. See the documentation for the expected format. |
required |
supercell_size
|
str
|
Size of the supercell in the format |
required |
out_dir
|
str
|
Path to the output directory. Must not contain any subdirectory yet. |
required |
qe_par
|
dict or None
|
Quantum ESPRESSO input parameters. Input files are only written if it
contains |
None
|
aims_par
|
dict or None
|
FHI-aims input parameters. Input files are only written if it contains
|
None
|
vasp_par
|
dict or None
|
VASP input parameters. Input files are only written if it contains
|
None
|
kpts
|
tuple or None
|
k-point grid for the DFT calculations, e.g. |
None
|
create_dft_folders
|
bool
|
Create the |
False
|
substitution_mode
|
str
|
How the substituting atoms are distributed when more than one site is
substituted: |
'auto'
|
cif_only
|
bool
|
Write all cluster CIF files directly into |
False
|
Source code in src/egqca/workflow.py
@entry_point("Cluster and DFT setup", lambda b: [
("CIF file", b.arguments["path_to_cif"]),
("Supercell size", b.arguments["supercell_size"]),
("Output folder", b.arguments["out_dir"]),
("Substitution mode", b.arguments["substitution_mode"]),
("DFT inputs for", _dft_codes(b)),
("k-points", b.arguments["kpts"]),
("CIF files only", b.arguments["cif_only"]),
])
def set_up_clusters_and_dft(supercell_program:str, path_to_cif:str, supercell_size:str,
out_dir:str,
qe_par: dict | None = None,
aims_par: dict | None = None,
vasp_par: dict | None = None,
kpts = None,
create_dft_folders: bool = False,
substitution_mode: str = "auto",
cif_only: bool = False):
"""
Create all non-equivalent clusters of size supercell_size and set up the corresponding folder
structure containing templates for the DFT input files.
The cluster setup (compound, sites, permutable sites n, one row per cluster) is
written to ``<out_dir>/clusters_template.dat``, which every run folder (DFT, ML,
EDDP) reads. The DFT run folder ``<out_dir>/DFT`` with a copy of it as
``clusters.dat`` is only created when ``create_dft_folders`` is set or one of
``qe_par``, ``aims_par``, ``vasp_par`` is given; :func:`update_DFT_in` creates it
later otherwise.
Parameters
----------
supercell_program : str
Path to the supercell executable.
path_to_cif : str
Path to the CIF file. See the documentation for the expected format.
supercell_size : str
Size of the supercell in the format ``1x1x1``, with the letter x as separator.
out_dir : str
Path to the output directory. Must not contain any subdirectory yet.
qe_par : dict or None
Quantum ESPRESSO input parameters. Input files are only written if it
contains ``pseudo_dir``.
aims_par : dict or None
FHI-aims input parameters. Input files are only written if it contains
``species_dir``.
vasp_par : dict or None
VASP input parameters. Input files are only written if it contains
``potcar_dir``.
kpts : tuple or None
k-point grid for the DFT calculations, e.g. ``(12, 12, 12)``.
create_dft_folders : bool
Create the ``vc-relax``, ``bands``, and ``phonons`` subfolder of every
cluster even when no solver parameters are given. Set it to False for an
ML-only run, which reads none of them. They are written regardless when
``qe_par``, ``aims_par`` or ``vasp_par`` asks for input files, since the
writers create their own.
substitution_mode : str
How the substituting atoms are distributed when more than one site is
substituted: ``"auto"``, ``"independent"``, or ``"coupled"``.
cif_only : bool
Write all cluster CIF files directly into ``out_dir`` and skip the folder
organisation, the DFT setup, and the clusters template.
"""
qe_par = {} if qe_par is None else dict(qe_par)
aims_par = {} if aims_par is None else dict(aims_par)
vasp_par = {} if vasp_par is None else dict(vasp_par)
# Check if out_dir exists and is empty, if not raise error
path = Path(out_dir)
if path.exists():
if any(p.is_dir() for p in path.iterdir()):
raise OSError(f"{path} is not empty. Please choose an empty directory or remove the existing files.")
# Check if cif-file exists
if not Path(path_to_cif).is_file():
raise FileNotFoundError(f"{path_to_cif} is not a valid path to a cif-file.")
# get elements
elements, permutable_elements_label, sites, permutable_sites, compound = get_elements(path_to_cif, supercell_size, substitution_mode)
# create supercells
run_supercell(supercell_program, path_to_cif, supercell_size, permutable_sites,
permutable_elements_label, out_dir, cif_only=cif_only,
create_dft_folders=create_dft_folders)
if cif_only:
print("CIF files created. Skipping DFT input and clusters.dat setup.\n")
return
# Create input for QE, AIMS, and VASP
if any([qe_par, aims_par, vasp_par]) or create_dft_folders:
create_DFT_in(
out_dir,
qe_par=qe_par,
aims_par=aims_par,
vasp_par=vasp_par,
kpts=kpts,
)
Nat = _nat_from_cif(path_to_cif, supercell_size)
# the clusters template (energies missing) that every run folder starts from;
# the DFT run folder gets its copy only when DFT inputs or folders are set up
set_up_clusters_dat(out_dir, permutable_sites, sites, Nat, compound)
if create_dft_folders or any([qe_par, aims_par, vasp_par]):
_copy_template_to_run_folder(out_dir, Path(out_dir) / "DFT")
print("Set up finished!\n")
set_up_clusters_dat ¶
set_up_clusters_dat(
clusters_folder: str | Path,
permutable_sites: int,
sites: int,
Nat: int,
compound: str,
filename: str = CLUSTERS_TEMPLATE_NAME,
) -> Path
Write the clusters template <clusters_folder>/clusters_template.dat.
One row per cluster folder S*/S*_i*_w*: the ID, the number of substituted
atoms n_j, the total number of atoms Nat, the composition x = n_j / n, the
degeneracy g_j and the energy missing. The header holds the compound, the
total number of sites and the number of permutable sites n. Every run folder
(DFT, ML, EDDP) takes its cluster setup from this file; the DFT run folder
starts from a copy of it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clusters_folder
|
str or Path
|
Folder containing the |
required |
permutable_sites
|
int
|
Number of permutable sites, written to the header and used for x = n_j / n. |
required |
sites
|
int
|
Total number of sites, written to the header. |
required |
Nat
|
int
|
Total number of atoms of a cluster. |
required |
compound
|
str
|
Compound label written to the header, e.g. |
required |
filename
|
str
|
Name of the template file. |
CLUSTERS_TEMPLATE_NAME
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the written template. |
Source code in src/egqca/workflow.py
def set_up_clusters_dat(clusters_folder: str | Path, permutable_sites: int, sites: int, Nat: int, compound: str, filename: str = CLUSTERS_TEMPLATE_NAME) -> Path:
"""Write the clusters template ``<clusters_folder>/clusters_template.dat``.
One row per cluster folder ``S*/S*_i*_w*``: the ID, the number of substituted
atoms n_j, the total number of atoms Nat, the composition x = n_j / n, the
degeneracy g_j and the energy ``missing``. The header holds the compound, the
total number of sites and the number of permutable sites n. Every run folder
(DFT, ML, EDDP) takes its cluster setup from this file; the DFT run folder
starts from a copy of it.
Parameters
----------
clusters_folder : str or Path
Folder containing the ``S*/S*_i*_w*`` cluster subdirectories; the template
is written into it.
permutable_sites : int
Number of permutable sites, written to the header and used for x = n_j / n.
sites : int
Total number of sites, written to the header.
Nat : int
Total number of atoms of a cluster.
compound : str
Compound label written to the header, e.g. ``A$_{1-x}$B$_x$C``.
filename : str
Name of the template file.
Returns
-------
pathlib.Path
Path to the written template.
"""
clusters_folder = Path(clusters_folder)
clusters_info = []
# Loop over all subfolders S*_i*_w* and extract the information for the template
for sub_dir in get_directories(clusters_folder):
cluster_id = sub_dir.name
match = re.search(r"S(\d+)_", str(sub_dir.name))
if match:
n_j = int(match.group(1))
x = n_j / permutable_sites
else:
n_j = None
x = None
match = re.search(r"_w(\d+)", str(sub_dir.name))
g_j = int(match.group(1)) if match else None
clusters_info.append((cluster_id, n_j, Nat, x, g_j))
clusters_file = clusters_folder / filename
_write_ml_clusters_header(
clusters_file,
permutable_sites=permutable_sites,
sites=sites,
compound=compound,
ML_model=None,
)
with open(clusters_file, "a") as f:
for cluster_info in clusters_info:
f.write("\t".join(map(str, cluster_info)) + "\tmissing\n")
return clusters_file
set_up_volume_dat ¶
set_up_volume_dat(
clusters_folder: str | Path,
dft_out_file: str | None = None,
dft_out_file_subfolder: str = "vc-relax",
filename: str = "volume.dat",
run_folder: str | Path | None = None,
)
Write volume.dat with the lattice parameters of every cluster from its DFT output.
The file holds a, b, c in Angstrom and alpha, beta, gamma in degree, read from
the relaxed structure in <cluster>/<dft_out_file_subfolder>/<dft_out_file>.
It is written into the DFT run folder run_folder (default
<clusters_folder>/DFT). The ML route writes its own volume_<model>.dat.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clusters_folder
|
str or Path
|
Folder containing the |
required |
dft_out_file
|
str
|
Name of the DFT output file to read the relaxed structure from. |
None
|
dft_out_file_subfolder
|
str
|
Subfolder of each cluster folder holding the DFT output file. |
'vc-relax'
|
filename
|
str
|
Name of the output file. |
'volume.dat'
|
run_folder
|
str or Path or None
|
DFT run folder the file is written into; default |
None
|
Returns:
| Type | Description |
|---|---|
tuple
|
|
Source code in src/egqca/workflow.py
def set_up_volume_dat(clusters_folder: str | Path, dft_out_file: str | None = None, dft_out_file_subfolder: str = "vc-relax", filename: str = "volume.dat", run_folder: str | Path | None = None):
"""Write volume.dat with the lattice parameters of every cluster from its DFT output.
The file holds a, b, c in Angstrom and alpha, beta, gamma in degree, read from
the relaxed structure in ``<cluster>/<dft_out_file_subfolder>/<dft_out_file>``.
It is written into the DFT run folder ``run_folder`` (default
``<clusters_folder>/DFT``). The ML route writes its own ``volume_<model>.dat``.
Parameters
----------
clusters_folder : str or Path
Folder containing the ``S*/S*_i*_w*`` cluster subdirectories.
dft_out_file : str
Name of the DFT output file to read the relaxed structure from.
dft_out_file_subfolder : str
Subfolder of each cluster folder holding the DFT output file.
filename : str
Name of the output file.
run_folder : str or Path or None
DFT run folder the file is written into; default ``<clusters_folder>/DFT``.
Returns
-------
tuple
``(volume_file, cluster_id, a, b, c, alpha, beta, gamma)``.
"""
clusters_folder = Path(clusters_folder)
if dft_out_file is None:
raise ValueError("dft_out_file is required: volume.dat is read from the DFT output files.")
run_folder = clusters_folder / "DFT" if run_folder is None else Path(run_folder)
run_folder.mkdir(parents=True, exist_ok=True)
volume_file = run_folder / filename
volume_info = []
cluster_id = []
for sub_dir in get_directories(clusters_folder):
cluster_id.append(sub_dir.name)
path_dft_out = sub_dir/dft_out_file_subfolder/dft_out_file
dft_solver = determine_dft_solver(path_dft_out)
# ASE
if dft_solver == "vasp":
atom = read(path_dft_out, format="vasp-out", index=-1)
else:
with open(path_dft_out, "r") as f:
if dft_solver == "espresso":
atom = list(read_espresso_out(f))[-1]
elif dft_solver == "aims":
atom = read_aims_output(f)
a,b,c,alpha,beta,gamma = atom.cell.cellpar()
volume_info.append((a, b, c, alpha, beta, gamma))
# Write the extracted information to the volume.dat file
_write_ml_volume_header(volume_file, ML_model=None)
with open(volume_file, "a") as f:
for cl, vol in zip(cluster_id, volume_info):
f.write(cl+"\t"+"\t".join(map(str, vol)) + "\n")
a,b,c,alpha,beta, gamma = np.array(volume_info, dtype=float).T
return volume_file, np.array(cluster_id).T, a,b,c,alpha,beta, gamma
create_bands_in ¶
create_bands_in(
outdir: Path | str,
qe_par: dict | None = None,
espresso_out_file: str | None = None,
aims_par: dict | None = None,
aims_out_file: str | None = None,
vasp_par: dict | None = None,
vasp_out_file: str | None = None,
kpts=None,
bands: dict | None = None,
)
Create the band-structure input files of every cluster in bands/.
Called after the relaxation: the structure is read from the relaxation output of the corresponding solver, so the band path follows the relaxed cell. Quantum ESPRESSO, FHI-aims, and VASP are supported and can be combined in one call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outdir
|
str or Path
|
Folder containing the |
required |
qe_par
|
dict or None
|
Solver parameters. A solver is only processed if its resource directory
( |
None
|
aims_par
|
dict or None
|
Solver parameters. A solver is only processed if its resource directory
( |
None
|
vasp_par
|
dict or None
|
Solver parameters. A solver is only processed if its resource directory
( |
None
|
espresso_out_file
|
str or None
|
Name of the relaxation output file inside |
None
|
aims_out_file
|
str or None
|
Name of the relaxation output file inside |
None
|
vasp_out_file
|
str or None
|
Name of the relaxation output file inside |
None
|
kpts
|
tuple or None
|
k-point grid used for the self-consistent part of the FHI-aims input. |
None
|
bands
|
dict or None
|
Band path settings, |
None
|
Source code in src/egqca/workflow.py
def create_bands_in(outdir:Path | str,
qe_par: dict | None = None, espresso_out_file: str | None = None,
aims_par: dict | None = None, aims_out_file: str | None = None,
vasp_par: dict | None = None, vasp_out_file: str | None = None,
kpts = None, bands: dict | None = None):
"""Create the band-structure input files of every cluster in ``bands/``.
Called after the relaxation: the structure is read from the relaxation output of
the corresponding solver, so the band path follows the relaxed cell. Quantum
ESPRESSO, FHI-aims, and VASP are supported and can be combined in one call.
Parameters
----------
outdir : str or Path
Folder containing the ``S*/S*_i*_w*`` cluster subdirectories.
qe_par, aims_par, vasp_par : dict or None
Solver parameters. A solver is only processed if its resource directory
(``pseudo_dir``, ``species_dir``, ``potcar_dir``) is present.
espresso_out_file, aims_out_file, vasp_out_file : str or None
Name of the relaxation output file inside ``vc-relax/``. Required for the
corresponding solver.
kpts : tuple or None
k-point grid used for the self-consistent part of the FHI-aims input.
bands : dict or None
Band path settings, ``{"path": "", "kpoint_density": 20}`` by default. An
empty ``path`` lets ASE choose the default path of the Bravais lattice. The
path is set up once on the unrelaxed S0 cluster and used for every cluster
(same scaled special points and number of points), see
:func:`egqca.create_dft_inputs.reference_bandpath`.
"""
outdir = Path(outdir)
qe_par = {} if qe_par is None else dict(qe_par)
aims_par = {} if aims_par is None else dict(aims_par)
vasp_par = {} if vasp_par is None else dict(vasp_par)
bands = {"path": "", "kpoint_density": 20} if bands is None else dict(bands)
# One band path for all clusters, from the unrelaxed S0 cluster (full parent
# symmetry): same special points (scaled) and number of points for every cluster.
s0_dirs = [d for d in get_directories(outdir) if d.parent.name == "S0"]
if not s0_dirs or not (s0_dirs[0]/f"{s0_dirs[0].name}.cif").is_file():
raise FileNotFoundError(f"No S0 cluster CIF in {outdir}: needed as reference for the band path.")
bands = reference_bandpath(read(s0_dirs[0]/f"{s0_dirs[0].name}.cif").cell,
bands.get("path", ""), bands.get("kpoint_density", 20))
# QE parameters common to all clusters, with the same cutoffs as create_DFT_in
if "pseudo_dir" in qe_par:
qe_common = _merge_qe_defaults(qe_par)
_set_common_qe_cutoffs(qe_common, [d/f"{d.name}.cif" for d in get_directories(outdir)])
# FHI-aims parameters common to all clusters, set up once
if "species_dir" in aims_par:
aims_common = AIMS_DEFAULTS | aims_par
_set_aims_k_grid(aims_common, kpts)
# one pass per cluster folder: the structure comes from the vc-relax output, so
# further CIFs in the folder (e.g. <id>_<suffix>.cif) must not repeat the inputs
for sub_dir in get_directories(outdir):
relax_dir = sub_dir/"vc-relax/"
bands_dir = sub_dir/"bands/"
# -------- Espresso -------- #
if "pseudo_dir" in qe_par:
pseudo_dir = Path(qe_par["pseudo_dir"])
if not pseudo_dir.is_dir():
raise NotADirectoryError(f"Not a directory: {pseudo_dir}")
if espresso_out_file is None:
raise ValueError("qe_par was given but espresso_out_file is None.")
atoms = read(relax_dir/espresso_out_file)
write_qe_bands(
atoms,
bands_dir,
sub_dir.name,
qe_par=copy.deepcopy(qe_common),
bands = bands
)
elif qe_par:
warnings.warn("qe_par was provided but 'pseudo_dir' is missing. bands.in will not be generated.", UserWarning, stacklevel=2)
# -------- FHI-aims -------- #
if "species_dir" in aims_par:
aims_species_dir = Path(aims_par["species_dir"])
if not aims_species_dir.is_dir():
raise NotADirectoryError(f"Not a directory: {aims_species_dir}")
if aims_out_file is None:
raise ValueError("aims_par was given but aims_out_file is None.")
atoms = read(relax_dir/aims_out_file)
write_aims_bands(
atoms,
bands_dir,
dict(aims_common),
bands= bands,
)
elif aims_par:
print(aims_par)
warnings.warn(
"aims_par was provided but 'species_dir' is missing. bands/control.in will not be generated.", UserWarning, stacklevel=2
)
# -------- VASP bands -------- #
if "potcar_dir" in vasp_par:
potcar_dir = Path(vasp_par["potcar_dir"])
if not potcar_dir.is_dir():
raise NotADirectoryError(f"Not a directory: {potcar_dir}")
if vasp_out_file is None:
raise ValueError("vasp_par was given but vasp_out_file is None.")
vasp_par = VASP_DEFAULTS | vasp_par
atoms = read(relax_dir / vasp_out_file, format="vasp-out", index=-1)
write_vasp_bands(
atoms,
bands_dir,
vasp_par=vasp_par,
bands=bands,
)
elif vasp_par:
warnings.warn(
"vasp_par was provided but 'potcar_dir' is missing. VASP bands inputs will not be generated.", UserWarning, stacklevel=2
)
create_phonons_in ¶
create_phonons_in(
outdir: Path | str,
qe_par: dict | None = None,
espresso_out_file: str | None = None,
aims_par: dict | None = None,
aims_out_file: str | None = None,
vasp_par: dict | None = None,
vasp_out_file: str | None = None,
kpts=None,
phonon_supercell: tuple[int, int, int] = (1, 1, 1),
aims_calculate_friction: bool = False,
)
Create the phonon input files of every cluster in phonons/.
Quantum ESPRESSO gets a ph.in built from qe_par merged with
QE_PHONON_DEFAULTS; FHI-aims gets geometry.in of the relaxed structure
for the phonon supercell plus control.in from aims_par. VASP is not
implemented.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outdir
|
str or Path
|
Folder containing the |
required |
qe_par
|
dict or None
|
Solver parameters. For Quantum ESPRESSO this is a |
None
|
aims_par
|
dict or None
|
Solver parameters. For Quantum ESPRESSO this is a |
None
|
vasp_par
|
dict or None
|
Solver parameters. For Quantum ESPRESSO this is a |
None
|
espresso_out_file
|
str or None
|
Name of the relaxation output file inside |
None
|
aims_out_file
|
str or None
|
Name of the relaxation output file inside |
None
|
vasp_out_file
|
str or None
|
Name of the relaxation output file inside |
None
|
kpts
|
tuple or None
|
k-point grid written to the FHI-aims |
None
|
phonon_supercell
|
tuple of int
|
Supercell of the FHI-aims phonon geometry, |
(1, 1, 1)
|
aims_calculate_friction
|
bool
|
Write |
False
|
Source code in src/egqca/workflow.py
def create_phonons_in(outdir:Path | str,
qe_par: dict | None = None, espresso_out_file: str | None = None,
aims_par: dict | None = None, aims_out_file: str | None = None,
vasp_par: dict | None = None, vasp_out_file: str | None = None,
kpts = None, phonon_supercell: tuple[int, int, int] = (1,1,1),
aims_calculate_friction: bool = False):
"""Create the phonon input files of every cluster in ``phonons/``.
Quantum ESPRESSO gets a ``ph.in`` built from ``qe_par`` merged with
``QE_PHONON_DEFAULTS``; FHI-aims gets ``geometry.in`` of the relaxed structure
for the phonon supercell plus ``control.in`` from ``aims_par``. VASP is not
implemented.
Parameters
----------
outdir : str or Path
Folder containing the ``S*/S*_i*_w*`` cluster subdirectories.
qe_par, aims_par, vasp_par : dict or None
Solver parameters. For Quantum ESPRESSO this is a ``ph.x`` dictionary, but it
must still contain ``pseudo_dir``, which is what selects the solver.
espresso_out_file, aims_out_file, vasp_out_file : str or None
Name of the relaxation output file inside ``vc-relax/``. Required for Quantum
ESPRESSO. For FHI-aims the relaxed structure is the last one in
``aims_out_file``; if it is None, ``vc-relax/geometry.in.next_step`` is used.
kpts : tuple or None
k-point grid written to the FHI-aims ``control.in``.
phonon_supercell : tuple of int
Supercell of the FHI-aims phonon geometry, ``atoms.repeat(phonon_supercell)``.
aims_calculate_friction : bool
Write ``calculate_friction .true.`` after every atom of the FHI-aims
``geometry.in``.
"""
outdir = Path(outdir)
qe_par = {} if qe_par is None else dict(qe_par)
aims_par = {} if aims_par is None else dict(aims_par)
if vasp_par:
warnings.warn("VASP phonon inputs are not yet implemented.", UserWarning, stacklevel=2)
# FHI-aims parameters common to all clusters, set up once
if "species_dir" in aims_par:
aims_common = dict(aims_par)
_set_aims_k_grid(aims_common, kpts)
# one pass per cluster folder (further CIFs in the folder must not repeat the inputs)
for sub_dir in get_directories(outdir):
relax_dir = sub_dir/"vc-relax/"
phonon_dir = sub_dir/"phonons/"
# -------- Espresso -------- #
if "pseudo_dir" in qe_par:
pseudo_dir = Path(qe_par["pseudo_dir"])
if not pseudo_dir.is_dir():
raise NotADirectoryError(f"Not a directory: {pseudo_dir}")
if espresso_out_file is None:
raise ValueError("qe_par was given but espresso_out_file is None.")
if not (relax_dir/espresso_out_file).is_file():
raise FileNotFoundError(f"No relaxation output {relax_dir/espresso_out_file}.")
write_qe_phonons(phonon_dir, sub_dir.name, _qe_phonon_parameters(qe_par))
elif qe_par:
warnings.warn("qe_par was provided but 'pseudo_dir' is missing. ph.in will not be generated.", UserWarning, stacklevel=2)
# -------- FHI-aims -------- #
if "species_dir" in aims_par:
aims_species_dir = Path(aims_par["species_dir"])
if not aims_species_dir.is_dir():
raise NotADirectoryError(f"Not a directory: {aims_species_dir}")
write_aims_ph(
_read_aims_relaxed_structure(relax_dir, aims_out_file),
phonon_dir,
aims_ph_param=dict(aims_common),
phonon_supercell=phonon_supercell,
calculate_friction=aims_calculate_friction,
)
elif aims_par:
print(aims_par)
warnings.warn(
"aims_par was provided but 'species_dir' is missing. phonons/control.in will not be generated.", UserWarning, stacklevel=2
)
update_DFT_in ¶
update_DFT_in(
out_dir: str | Path,
qe_par: dict | None = None,
aims_par: dict | None = None,
vasp_par: dict | None = None,
kpts=None,
cif_file_suffix: str | None = None,
dft_folder_name: str | None = None,
) -> None
Update the vc-relax input files of an existing cluster tree.
Use this to change solver parameters after the supercell program has been run and the folder structure is set up.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out_dir
|
str or Path
|
Cluster folder containing the |
required |
qe_par
|
dict or None
|
Solver parameters, as in :func: |
None
|
aims_par
|
dict or None
|
Solver parameters, as in :func: |
None
|
vasp_par
|
dict or None
|
Solver parameters, as in :func: |
None
|
kpts
|
tuple or None
|
k-point grid for the DFT calculations. |
None
|
cif_file_suffix
|
str or None
|
Read |
None
|
dft_folder_name
|
str or None
|
DFT run folder inside |
None
|
Warnings
Input files of the solvers given here are overwritten in every vc-relax
folder. Input files of other solvers are left untouched.
Source code in src/egqca/workflow.py
def update_DFT_in(
out_dir: str | Path,
qe_par: dict | None = None,
aims_par: dict | None = None,
vasp_par: dict | None = None,
kpts = None,
cif_file_suffix: str | None = None,
dft_folder_name: str | None = None,
) -> None:
"""Update the vc-relax input files of an existing cluster tree.
Use this to change solver parameters after the supercell program has been run and
the folder structure is set up.
Parameters
----------
out_dir : str or Path
Cluster folder containing the ``S*/S*_i*_w*`` subdirectories.
qe_par, aims_par, vasp_par : dict or None
Solver parameters, as in :func:`set_up_clusters_and_dft`.
kpts : tuple or None
k-point grid for the DFT calculations.
cif_file_suffix : str or None
Read ``<cluster_id>_<cif_file_suffix>.cif`` instead of ``<cluster_id>.cif``,
e.g. to build the inputs from an ML-relaxed structure.
dft_folder_name : str or None
DFT run folder inside ``out_dir`` (default ``DFT``). Its ``clusters.dat`` is
created as a copy of ``clusters_template.dat`` if it does not exist yet; an
existing one is never changed. Use another name for a second DFT run, or
the new name of a renamed DFT folder.
Warnings
--------
Input files of the solvers given here are overwritten in every ``vc-relax``
folder. Input files of other solvers are left untouched.
"""
qe_par = {} if qe_par is None else dict(qe_par)
aims_par = {} if aims_par is None else dict(aims_par)
vasp_par = {} if vasp_par is None else dict(vasp_par)
create_DFT_in(
base_path=out_dir,
qe_par=qe_par,
aims_par=aims_par,
vasp_par=vasp_par,
kpts=kpts,
cif_file_suffix=cif_file_suffix,
)
_copy_template_to_run_folder(out_dir, Path(out_dir) / (dft_folder_name or "DFT"))
get_directories ¶
get_directories(base_dir: str | Path)
Return all S*/S*_i*_w* cluster folders of a cluster tree.
The list is sorted by the number of substituted atoms and, within one S*, by
folder name. Every workflow function that loops over clusters uses this order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_dir
|
str or Path
|
Folder containing the |
required |
Returns:
| Type | Description |
|---|---|
list of pathlib.Path
|
One entry per cluster folder. |
Source code in src/egqca/workflow.py
def get_directories(base_dir: str | Path):
"""Return all ``S*/S*_i*_w*`` cluster folders of a cluster tree.
The list is sorted by the number of substituted atoms and, within one ``S*``, by
folder name. Every workflow function that loops over clusters uses this order.
Parameters
----------
base_dir : str or Path
Folder containing the ``S*`` subdirectories.
Returns
-------
list of pathlib.Path
One entry per cluster folder.
"""
base_dir = Path(base_dir)
directories = []
# ------------ Loop over S* ------------ #
for S_dir in sorted((p for p in base_dir.glob("S*") if p.is_dir() and re.search(r"S(\d+)", p.name)), key=extract_Snumber):
# ------- Loop over S*_i*_w* ------- #
for sub_dir in sorted(S_dir.glob("S*_i*_w*")):
if not sub_dir.is_dir():
continue
directories.append(sub_dir)
return directories
Reading Results¶
extract_total_energies ¶
extract_total_energies(
datafile: str | Path,
clusters_folder: str | Path,
out_file_name: str,
dft_out_file_subfolder: str = "vc-relax",
aims_use_zero_broadening_corrected_energy: bool = False,
)
Extract the total energy from the DFT output files and write it to clusters.dat .
Quantum ESPRESSO, FHI-aims, and VASP outputs are recognized automatically and the
energies are converted to Ry. A run that did not finish successfully, or whose
relaxation did not converge, keeps its energy but gets a # WARNING: comment
appended to its row in clusters.dat.
The code is determined for every output file; outputs of different codes raise a
ValueError, since their total energies are not comparable.
The energy of every cluster in clusters.dat is (re-)extracted from
<clusters_folder>/S<n>/<cluster_id>/<dft_out_file_subfolder>/<out_file_name>
and written to clusters.dat. A cluster without folder, output file or energy in
its output keeps its entry: missing stays missing, an existing energy is
kept with a warning. If any cluster is still missing afterwards, a ValueError
lists all of them. Cluster folders that are not in clusters.dat only give a
warning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datafile
|
str or Path
|
clusters.dat file whose energy column is filled. |
required |
clusters_folder
|
str or Path
|
Folder containing the |
required |
out_file_name
|
str
|
Name of the DFT output file inside each cluster folder. |
required |
dft_out_file_subfolder
|
str
|
Subfolder of each cluster folder holding the DFT output file. |
'vc-relax'
|
aims_use_zero_broadening_corrected_energy
|
bool
|
Use the zero-broadening corrected energy of the FHI-aims output instead of the total energy. |
False
|
Source code in src/egqca/workflow.py
def extract_total_energies(datafile: str | Path, clusters_folder:str | Path, out_file_name: str, dft_out_file_subfolder: str = "vc-relax", aims_use_zero_broadening_corrected_energy: bool = False):
"""
Extract the total energy from the DFT output files and write it to clusters.dat .
Quantum ESPRESSO, FHI-aims, and VASP outputs are recognized automatically and the
energies are converted to Ry. A run that did not finish successfully, or whose
relaxation did not converge, keeps its energy but gets a ``# WARNING:`` comment
appended to its row in clusters.dat.
The code is determined for every output file; outputs of different codes raise a
ValueError, since their total energies are not comparable.
The energy of every cluster in clusters.dat is (re-)extracted from
``<clusters_folder>/S<n>/<cluster_id>/<dft_out_file_subfolder>/<out_file_name>``
and written to clusters.dat. A cluster without folder, output file or energy in
its output keeps its entry: ``missing`` stays ``missing``, an existing energy is
kept with a warning. If any cluster is still ``missing`` afterwards, a ValueError
lists all of them. Cluster folders that are not in clusters.dat only give a
warning.
Parameters
----------
datafile : str or Path
clusters.dat file whose energy column is filled.
clusters_folder : str or Path
Folder containing the ``S*/S*_i*_w*`` cluster subdirectories.
out_file_name : str
Name of the DFT output file inside each cluster folder.
dft_out_file_subfolder : str
Subfolder of each cluster folder holding the DFT output file.
aims_use_zero_broadening_corrected_energy : bool
Use the zero-broadening corrected energy of the FHI-aims output instead of
the total energy.
"""
datafile = Path(datafile)
base = Path(clusters_folder)
with open(datafile) as f:
lines = f.readlines()
rows = {
l.split()[0]: l.split()[5]
for l in lines if l.strip() and not l.lstrip().startswith("#")
}
results = {}
failed = {} # cluster_id -> (reason, path)
solvers = {} # DFT code -> cluster IDs
for cluster_id in rows:
sub_dir = base / cluster_id.split("_")[0] / cluster_id
filepath = sub_dir / dft_out_file_subfolder / out_file_name
if not sub_dir.is_dir():
failed[cluster_id] = ("no cluster folder", sub_dir)
elif not filepath.is_file():
failed[cluster_id] = ("no output file", filepath)
else:
energy, dft_calculation_okay, solver = _read_dft_energy(filepath, aims_use_zero_broadening_corrected_energy)
if solver is not None:
solvers.setdefault(solver, []).append(cluster_id)
if energy is None:
failed[cluster_id] = ("no energy in the output file", filepath)
else:
results[cluster_id] = (energy, dft_calculation_okay)
if len(solvers) > 1:
# total energies of different codes (pseudopotentials, all-electron) are not comparable
raise ValueError(
f"The DFT outputs of the clusters in {datafile} come from different codes; their "
"total energies cannot be compared. Nothing was written.\n"
+ "\n".join(f" {solver} ({len(ids)}): {', '.join(ids)}" for solver, ids in solvers.items())
)
extra = sorted({d.name for d in get_directories(base)} - set(rows))
if extra:
warnings.warn(f"Cluster folders not listed in {datafile} are ignored: {', '.join(extra)}")
new_lines = []
for line in lines:
cluster_id = line.split()[0] if line.strip() and not line.lstrip().startswith("#") else None
if cluster_id not in results:
new_lines.append(line)
continue
energy, dft_calculation_okay = results[cluster_id]
new_lines.append(_set_energy_column(line, energy, dft_calculation_okay))
if not dft_calculation_okay:
warnings.warn(f"DFT run did not finish or its relaxation did not converge for cluster {cluster_id}.")
# replace the file in one step, so an interrupted run leaves it unchanged
with _atomic_write(datafile) as f:
f.write("".join(new_lines))
kept = [cid for cid in failed if rows[cid] != "missing"]
if kept:
warnings.warn(
f"No DFT energy found for {', '.join(kept)}; the energies already in {datafile.name} are kept."
)
still_missing = {cid: failed[cid] for cid in failed if rows[cid] == "missing"}
if still_missing:
reasons = {}
for reason, path in still_missing.values():
reasons.setdefault(reason, []).append(str(path))
report = "\n".join(
f" {reason} ({len(paths)}):\n" + "\n".join(f" {p}" for p in paths)
for reason, paths in reasons.items()
)
raise ValueError(
f"Could not extract the DFT energies of {len(still_missing)} of the {len(rows)} "
f"clusters in {datafile}:\n{report}\n"
f"The {len(results)} extracted energies were written to {datafile.name}; the other "
"clusters stay 'missing'. Every cluster needs its energy before EGQCA can run."
)
extract_eddp_energies ¶
extract_eddp_energies(
out_dir: str | Path,
permutable_sites: int | None = None,
sites: int | None = None,
Nat: int | None = None,
compound: str | None = None,
filename: str = "clusters_eddp.dat",
not_converged_filename: str = "not_converged_clusters.dat",
energy_filename: str = "energy.dat",
) -> Path
Read each cluster's relaxed energy from its eddp/energy.dat file (an
AIRSS repose log, see collect_eddp_clusters.sh) and write
clusters_eddp.dat into a new "eddp" subfolder of out_dir.
Clusters whose relaxation did not converge are additionally listed (one
cluster id per line, with the reason in a second column) in
not_converged_clusters.dat next to clusters_eddp.dat. A cluster counts as
converged only if repose logged its "converged in
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
out_dir
|
str or Path
|
Folder containing the |
required |
permutable_sites
|
optional
|
Number of permutable sites (x = n_j / n), total number of sites, atoms per
cluster and compound label for the header. By default read from
|
None
|
sites
|
optional
|
Number of permutable sites (x = n_j / n), total number of sites, atoms per
cluster and compound label for the header. By default read from
|
None
|
Nat
|
optional
|
Number of permutable sites (x = n_j / n), total number of sites, atoms per
cluster and compound label for the header. By default read from
|
None
|
compound
|
optional
|
Number of permutable sites (x = n_j / n), total number of sites, atoms per
cluster and compound label for the header. By default read from
|
None
|
filename
|
str
|
Name of the cluster file written into the |
'clusters_eddp.dat'
|
not_converged_filename
|
str
|
Name of the summary file listing the clusters without a converged relaxation. |
'not_converged_clusters.dat'
|
energy_filename
|
str
|
Name of the repose output file inside each cluster's |
'energy.dat'
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the written cluster file. |
Source code in src/egqca/workflow.py
@entry_point("EDDP energy collection", lambda b: [
("Clusters folder", b.arguments["out_dir"]),
("Compound", b.arguments.get("compound") or "from clusters_template.dat"),
("Sites per cluster", b.arguments.get("sites") or "from clusters_template.dat"),
("Permutable sites n", b.arguments.get("permutable_sites") or "from clusters_template.dat"),
("repose log per cluster", f"eddp/{b.arguments['energy_filename']}"),
("Output file", f"eddp/{b.arguments['filename']}"),
])
def extract_eddp_energies(
out_dir: str | Path,
permutable_sites: int | None = None,
sites: int | None = None,
Nat: int | None = None,
compound: str | None = None,
filename: str = "clusters_eddp.dat",
not_converged_filename: str = "not_converged_clusters.dat",
energy_filename: str = "energy.dat",
) -> Path:
"""
Read each cluster's relaxed energy from its eddp/energy.dat file (an
AIRSS `repose` log, see collect_eddp_clusters.sh) and write
clusters_eddp.dat into a new "eddp" subfolder of out_dir.
Clusters whose relaxation did not converge are additionally listed (one
cluster id per line, with the reason in a second column) in
not_converged_clusters.dat next to clusters_eddp.dat. A cluster counts as
converged only if repose logged its "converged in <n> steps" marker.
Parameters
----------
out_dir : str or Path
Folder containing the ``S*/S*_i*_w*`` cluster subdirectories.
permutable_sites, sites, Nat, compound : optional
Number of permutable sites (x = n_j / n), total number of sites, atoms per
cluster and compound label for the header. By default read from
``<out_dir>/clusters_template.dat`` (else ``DFT/clusters.dat`` of an older
tree, else a scan of the cluster CIFs, which writes the template). A value
that differs from the template raises a ValueError.
filename : str
Name of the cluster file written into the ``eddp`` subfolder.
not_converged_filename : str
Name of the summary file listing the clusters without a converged relaxation.
energy_filename : str
Name of the repose output file inside each cluster's ``eddp`` subfolder.
Defaults to ``energy.dat``. Use this to read an alternative relaxation of
the same cluster set, for example ``RHO.energy.dat`` from a run with the
cell constrained to the rhombohedral Bravais lattice.
Returns
-------
pathlib.Path
Path to the written cluster file.
"""
out_dir = Path(out_dir)
permutable_sites, sites, Nat, compound, _ = _resolve_cluster_setup(
out_dir, permutable_sites=permutable_sites, sites=sites, Nat=Nat, compound=compound,
)
eddp_dir = out_dir / "eddp"
eddp_dir.mkdir(exist_ok=True)
clusters_file = eddp_dir / filename
not_converged_file = eddp_dir / not_converged_filename
directories = get_directories(out_dir)
clusters_info = []
not_converged = []
# per-S counts for the header of not_converged_clusters.dat, keyed by n_j
n_total_per_S = {}
n_not_converged_per_S = {}
n_missing = 0
n_incomplete = 0
for sub_dir in directories:
cluster_id = sub_dir.name
energy_file = sub_dir / "eddp" / energy_filename
match = re.search(r"S(\d+)_", cluster_id)
n_j = int(match.group(1)) if match else None
x = n_j / permutable_sites if n_j is not None else None
match = re.search(r"_w(\d+)", cluster_id)
g_j = int(match.group(1)) if match else None
n_total_per_S[n_j] = n_total_per_S.get(n_j, 0) + 1
if not energy_file.exists():
n_missing += 1
not_converged.append((cluster_id, f"missing eddp/{energy_filename}"))
n_not_converged_per_S[n_j] = n_not_converged_per_S.get(n_j, 0) + 1
clusters_info.append((cluster_id, n_j, Nat, x, g_j, "missing"))
continue
with open(energy_file) as f:
lines = f.readlines()
# repose ends the optimisation block with either "converged in <n> steps"
# or "did not converge after <n> steps" (followed by "STOP repose: failed
# to converge"). A truncated log has neither -- treat that as unconverged
# too, since convergence cannot be confirmed.
converged = any("converged in" in line for line in lines)
if not converged:
if any("did not converge" in line or "failed to converge" in line for line in lines):
reason = "repose did not converge"
else:
reason = f"no convergence marker in eddp/{energy_filename}"
not_converged.append((cluster_id, reason))
n_not_converged_per_S[n_j] = n_not_converged_per_S.get(n_j, 0) + 1
energy_eV = None
for line in reversed(lines):
if line.strip().startswith("Energy:"):
energy_eV = float(line.split(":")[1].strip())
break
if energy_eV is None:
n_incomplete += 1
warnings.warn(f"No 'Energy:' line in {energy_file}, skipping cluster {cluster_id}.")
clusters_info.append((cluster_id, n_j, Nat, x, g_j, "missing"))
continue
energy_Ry = energy_eV / (Ry_to_mev / 1000)
# an energy from an unconverged relaxation is kept but flagged on its row, as
# in the ML route; read_clusters_dat repeats the warning when the file is read
clusters_info.append((cluster_id, n_j, Nat, x, g_j, energy_Ry) if converged
else (cluster_id, n_j, Nat, x, g_j, energy_Ry, "\t # WARNING: Relaxation did not converge"))
_write_ml_clusters_header(
clusters_file,
permutable_sites=permutable_sites,
sites=sites,
compound=compound,
ML_model="eddp",
)
with open(clusters_file, "a") as f:
for cluster_info in clusters_info:
row, comment = cluster_info[:6], "".join(cluster_info[6:])
f.write("\t".join(map(str, row)) + comment + "\n")
if any(len(cluster_info) > 6 for cluster_info in clusters_info):
# same header warning as the ML route
text = clusters_file.read_text()
clusters_file.write_text(
"# WARNING: Relaxation did not converge for some of the clusters. "
f"They are listed in {not_converged_file.name}.\n" + text
)
with open(not_converged_file, "w") as f:
f.write(f"# Clusters without a converged eddp relaxation ({len(not_converged)} of {len(directories)})\n")
# per-S breakdown; S* groups in which everything converged are not listed
for n_j in sorted(n_not_converged_per_S, key=lambda k: (k is None, k)):
S_label = f"S{n_j}" if n_j is not None else "unknown"
f.write(f"# {S_label}: {n_not_converged_per_S[n_j]}/{n_total_per_S[n_j]} not converged\n")
f.write("#ID\treason\n")
for cluster_id, reason in not_converged:
f.write(f"{cluster_id}\t{reason}\n")
print(
f"#####################################################################################\n"
f"Summary:\n"
f"({n_missing} missing eddp/{energy_filename}, {n_incomplete} without a completed relaxation).\n"
f"{len(not_converged)} of {len(directories)} clusters did not converge, listed in {not_converged_file}.\n"
f"#####################################################################################\n"
)
return clusters_file
write_properties_file ¶
write_properties_file(
clusters_folder: str | Path,
properties_extraction: dict,
filename: str = "properties.dat",
)
Extract per-cluster properties and write them to a properties.dat file.
The file is written into clusters_folder and has the format expected by
:meth:egqca.EGQCA.average_properties: the cluster ID in the first column and
one column per property.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clusters_folder
|
str or Path
|
Folder containing the |
required |
properties_extraction
|
dict
|
Mapping of property name to a callable that accepts a cluster directory and returns the value of that property for the cluster. |
required |
filename
|
str
|
Name of the output file. |
'properties.dat'
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the written properties file. |
Examples:
>>> egqca.write_properties_file(
... out_dir,
... {"N(e_F)": lambda cluster_dir: read_dos_at_ef(cluster_dir / "bands")},
... )
Source code in src/egqca/workflow.py
def write_properties_file(clusters_folder: str | Path, properties_extraction: dict, filename: str = "properties.dat"):
"""Extract per-cluster properties and write them to a properties.dat file.
The file is written into ``clusters_folder`` and has the format expected by
:meth:`egqca.EGQCA.average_properties`: the cluster ID in the first column and
one column per property.
Parameters
----------
clusters_folder : str or Path
Folder containing the ``S*/S*_i*_w*`` cluster subdirectories; the file is
written into it. A ValueError is raised if it holds no cluster folders.
properties_extraction : dict
Mapping of property name to a callable that accepts a cluster directory and
returns the value of that property for the cluster.
filename : str
Name of the output file.
Returns
-------
pathlib.Path
Path to the written properties file.
Examples
--------
>>> egqca.write_properties_file(
... out_dir,
... {"N(e_F)": lambda cluster_dir: read_dos_at_ef(cluster_dir / "bands")},
... )
"""
clusters_folder = Path(clusters_folder)
directories = get_directories(clusters_folder)
if not directories:
raise ValueError(
f"No S*/S*_i*_w* cluster folders in {clusters_folder}. write_properties_file "
"takes the clusters folder, the folder that contains the S* folders."
)
prop_file = clusters_folder / filename
prop_names = list(properties_extraction.keys())
with open(prop_file, "w") as f:
f.write("# Properties for EGQCA\n")
f.write("#ID\t" + "\t".join(prop_names) + "\n")
for sub_dir in directories:
values = [extractor(sub_dir) for extractor in properties_extraction.values()]
f.write(sub_dir.name + "\t" + "\t".join(str(v) for v in values) + "\n")
return prop_file
convert_volume_file ¶
convert_volume_file(
volume_file: str | Path, conversion_function, volume_file_name: str | None = None
) -> Path
Convert lattice parameters in a volume.dat-style file on demand.
The volume-file convention is:
ID, a, b, c, alpha, beta, gamma, with lengths in Angstrom and angles
in degrees. The conversion function is called once for each data row as
conversion_function(a, b, c, alpha, beta, gamma). It must return either
a sequence (a, b, c, alpha, beta, gamma) or a dictionary with these
six keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
volume_file
|
str | Path
|
Input volume file. |
required |
conversion_function
|
Callable that converts one row of lattice parameters. |
required | |
volume_file_name
|
str | None
|
Optional output filename. If omitted, the output is written next to the
input as |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the converted volume file. |
Source code in src/egqca/io.py
def convert_volume_file(
volume_file: str | Path,
conversion_function,
volume_file_name: str | None = None,
) -> Path:
"""
Convert lattice parameters in a volume.dat-style file on demand.
The volume-file convention is:
ID, a, b, c, alpha, beta, gamma, with lengths in Angstrom and angles
in degrees. The conversion function is called once for each data row as
``conversion_function(a, b, c, alpha, beta, gamma)``. It must return either
a sequence ``(a, b, c, alpha, beta, gamma)`` or a dictionary with these
six keys.
Parameters
----------
volume_file
Input volume file.
conversion_function
Callable that converts one row of lattice parameters.
volume_file_name
Optional output filename. If omitted, the output is written next to the
input as ``<input filename>_converted.dat``.
Returns
-------
pathlib.Path
Path to the converted volume file.
"""
volume_file = Path(volume_file)
if volume_file_name is None:
volume_name = volume_file.name
if volume_name.endswith(".dat"):
volume_name = volume_name[:-4]
converted_volume_file = volume_file.with_name(f"{volume_name}_converted.dat")
else:
converted_volume_file = Path(volume_file_name)
if not converted_volume_file.is_absolute():
converted_volume_file = volume_file.parent / converted_volume_file
if converted_volume_file.exists():
print(f"Converted volume file already exists: {converted_volume_file}")
return converted_volume_file
if not callable(conversion_function):
raise TypeError("conversion_function must be callable.")
lattice_keys = ("a", "b", "c", "alpha", "beta", "gamma")
# written to a temporary file and moved into place only when every row converted:
# a failing row raises and leaves no truncated file that a later call would return
with open(volume_file) as fin, _atomic_write(converted_volume_file) as fout:
for line_number, line in enumerate(fin, start=1):
stripped = line.strip()
if not stripped or stripped.startswith("#"):
fout.write(line)
continue
columns = stripped.split()
if len(columns) != 7:
raise ValueError(
f"Expected 7 columns in {volume_file} line {line_number}: "
"ID, a, b, c, alpha, beta, gamma."
)
cluster_id = columns[0]
lattice_parameters = tuple(float(value) for value in columns[1:])
converted = conversion_function(*lattice_parameters)
if isinstance(converted, dict):
try:
converted_values = tuple(converted[key] for key in lattice_keys)
except KeyError as exc:
raise ValueError(
"conversion_function returned a dictionary, but one of "
"the required keys is missing: a, b, c, alpha, beta, gamma."
) from exc
else:
converted_values = tuple(converted)
if len(converted_values) != 6:
raise ValueError(
"conversion_function must return six values: "
"a, b, c, alpha, beta, gamma."
)
fout.write(
cluster_id
+ "\t"
+ "\t".join(str(float(value)) for value in converted_values)
+ "\n"
)
return converted_volume_file
Comparing Several Calculations¶
EGQCAInput
dataclass
¶
EGQCAInput(
cluster_file: Path,
volume_file: Path | None = None,
label: str | None = None,
entropy_approximation: str | None = None,
phonon_file_name: str | None = None,
)
Input file pair used for comparing several EGQCA calculations.
entropy_approximation ("overlapping" or "non-overlapping") overrides the
default of :func:run_egqca_comparison for this input, so the same cluster
file can be compared under both approximations. phonon_file_name is passed
to :class:EGQCA to include the vibrational free energy of this input.
discover_egqca_inputs ¶
discover_egqca_inputs(
folder: str | Path,
*,
cluster_pattern: str = "*/clusters*.dat",
labels: dict[str | Path, str] | None = None,
require_volume: bool = True
) -> list[EGQCAInput]
Find clusters*.dat files and matching volume*.dat files in one folder.
Labels default to the cluster-file suffix, e.g. clusters_mace.dat becomes
mace. labels may map either a full cluster path or a filename to a
custom label. Default labels that are equal get their folder prefixed
(A/clusters.dat, B/clusters.dat -> A_clusters, B_clusters);
equal custom labels raise a ValueError.
Source code in src/egqca/comparison.py
def discover_egqca_inputs(
folder: str | Path,
*,
cluster_pattern: str = "*/clusters*.dat",
labels: dict[str | Path, str] | None = None,
require_volume: bool = True,
) -> list[EGQCAInput]:
"""Find ``clusters*.dat`` files and matching ``volume*.dat`` files in one folder.
Labels default to the cluster-file suffix, e.g. ``clusters_mace.dat`` becomes
``mace``. ``labels`` may map either a full cluster path or a filename to a
custom label. Default labels that are equal get their folder prefixed
(``A/clusters.dat``, ``B/clusters.dat`` -> ``A_clusters``, ``B_clusters``);
equal custom labels raise a ValueError.
"""
folder = Path(folder)
label_map = {str(key): value for key, value in (labels or {}).items()}
items = []
for cluster_file in sorted(folder.glob(cluster_pattern)):
if not cluster_file.is_file():
continue
volume_file = _matching_volume_file(cluster_file)
if not volume_file.exists():
if require_volume:
continue
volume_file = None
label = label_map.get(str(cluster_file)) or label_map.get(cluster_file.name)
explicit = label is not None
if not explicit:
label = _default_label(cluster_file, volume_file)
items.append((EGQCAInput(cluster_file=cluster_file, volume_file=volume_file, label=label), explicit))
return _unique_labels(items)
make_egqca_inputs ¶
make_egqca_inputs(
pairs: Iterable[
EGQCAInput
| tuple[str | Path, str | Path | None]
| tuple[str | Path, str | Path | None, str]
| dict[str, str | Path | None]
],
*,
labels: Iterable[str] | None = None
) -> list[EGQCAInput]
Create comparison inputs from explicitly provided cluster/volume paths.
Each entry is an :class:EGQCAInput, a (cluster_file, volume_file[, label])
tuple or a dict with the keys cluster_file, volume_file, label,
entropy_approximation and phonon_file_name (only cluster_file is
required). An input with
an entropy_approximation but no label gets it appended to the default
label, e.g. clusters_non-overlapping. Default labels that are equal get
their folder prefixed (A_clusters, B_clusters), or a number appended if
they come from one folder (clusters_2); equal custom labels raise a
ValueError.
Source code in src/egqca/comparison.py
def make_egqca_inputs(
pairs: Iterable[
EGQCAInput
| tuple[str | Path, str | Path | None]
| tuple[str | Path, str | Path | None, str]
| dict[str, str | Path | None]
],
*,
labels: Iterable[str] | None = None,
) -> list[EGQCAInput]:
"""Create comparison inputs from explicitly provided cluster/volume paths.
Each entry is an :class:`EGQCAInput`, a ``(cluster_file, volume_file[, label])``
tuple or a dict with the keys ``cluster_file``, ``volume_file``, ``label``,
``entropy_approximation`` and ``phonon_file_name`` (only ``cluster_file`` is
required). An input with
an ``entropy_approximation`` but no label gets it appended to the default
label, e.g. ``clusters_non-overlapping``. Default labels that are equal get
their folder prefixed (``A_clusters``, ``B_clusters``), or a number appended if
they come from one folder (``clusters_2``); equal custom labels raise a
ValueError.
"""
label_list = list(labels) if labels is not None else None
items = []
for idx, pair in enumerate(pairs):
if isinstance(pair, EGQCAInput):
item = pair
elif isinstance(pair, dict):
cluster_file = Path(pair["cluster_file"])
volume_value = pair.get("volume_file")
volume_file = Path(volume_value) if volume_value is not None else None
item = EGQCAInput(
cluster_file=cluster_file,
volume_file=volume_file,
label=pair.get("label"),
entropy_approximation=pair.get("entropy_approximation"),
phonon_file_name=pair.get("phonon_file_name"),
)
else:
cluster_file = Path(pair[0])
volume_file = Path(pair[1]) if pair[1] is not None else None
item_label = pair[2] if len(pair) > 2 else None
item = EGQCAInput(cluster_file=cluster_file, volume_file=volume_file, label=item_label)
override_label = label_list[idx] if label_list is not None else None
label = override_label or item.label
explicit = label is not None
if not explicit:
label = _default_label(item.cluster_file, item.volume_file)
if item.entropy_approximation is not None:
label = f"{label}_{item.entropy_approximation}"
items.append((replace(item, label=label), explicit))
return _unique_labels(items)
run_egqca_comparison ¶
run_egqca_comparison(
inputs: Iterable[EGQCAInput],
x: ndarray,
Tlist: list[float],
*,
run_miscibility_gap: bool = True,
T_min_misc_gap: float = 30,
misc_gap_max_iter: int = 200,
pressure_GPa: float = 0.0,
recompute_output_subfolder: str | None = None,
entropy_approximation: str = "overlapping"
) -> list[EGQCA]
Instantiate and recompute EGQCA models without saving comparison figures.
entropy_approximation is used for every input that does not set its own
(see :class:EGQCAInput).
Source code in src/egqca/comparison.py
@entry_point("EGQCA comparison", _comparison_summary)
def run_egqca_comparison(
inputs: Iterable[EGQCAInput],
x: np.ndarray,
Tlist: list[float],
*,
run_miscibility_gap: bool = True,
T_min_misc_gap: float = 30,
misc_gap_max_iter: int = 200,
pressure_GPa: float = 0.0,
recompute_output_subfolder: str | None = None,
entropy_approximation: str = "overlapping",
) -> list[EGQCA]:
"""Instantiate and recompute EGQCA models without saving comparison figures.
``entropy_approximation`` is used for every input that does not set its own
(see :class:`EGQCAInput`).
"""
inputs = list(inputs)
labelled = _unique_labels([
(item if item.label is not None
else replace(item, label=_default_label(item.cluster_file, item.volume_file)),
item.label is not None)
for item in inputs
])
models = []
for item, labelled_item in zip(inputs, labelled):
model = EGQCA(
datafile=item.cluster_file,
volume_file=item.volume_file,
phonon_file_name=item.phonon_file_name,
out_folder_name=item.label,
pressure_GPa=pressure_GPa,
entropy_approximation=item.entropy_approximation or entropy_approximation,
)
model.comparison_label = labelled_item.label
x_prepared = model._prepare_main(x, Tlist, output_subfolder=recompute_output_subfolder)
model.init_thermo()
model._ensure_probabilities(x_prepared, Tlist)
for T in model.Tlist:
model.thermo(T)
if run_miscibility_gap:
model.calc_miscibility_gap(
x_prepared,
T_min=T_min_misc_gap,
dx_plot=0.01,
max_iter=misc_gap_max_iter,
)
models.append(model)
return models
plot_thermodynamic_comparison ¶
plot_thermodynamic_comparison(
models: list[EGQCA],
*,
quantities: Iterable[str] = ("U", "F", "Fv"),
temperatures: Iterable[float] | None = None,
show: bool = True
) -> dict[str, plt.Figure]
Plot thermodynamic quantities for several EGQCA models.
Each quantity gets one figure with one subplot per temperature. Values are shown in meV/site.
Source code in src/egqca/comparison.py
def plot_thermodynamic_comparison(
models: list[EGQCA],
*,
quantities: Iterable[str] = ("U", "F", "Fv"),
temperatures: Iterable[float] | None = None,
show: bool = True,
) -> dict[str, plt.Figure]:
"""Plot thermodynamic quantities for several EGQCA models.
Each quantity gets one figure with one subplot per temperature.
Values are shown in meV/site.
"""
quantity_info = {
"U": (r"$\Delta H$", "Mixing enthalpy"),
"F": (r"$\Delta G$", "Mixing free energy"),
"S": (r"$T\Delta S$", "Mixing entropy term"),
"Fv": (r"$\Delta F_{vib}$", "Vibrational free energy"),
}
Ts = _temperatures(models, temperatures)
figures = {}
for quantity in quantities:
if quantity == "Fv" and not any(model.phonon_data is not None for model in models):
continue
ylabel, title = quantity_info[quantity]
fig, axes = plt.subplots(1, len(Ts), figsize=(6 * len(Ts), 5), squeeze=False)
for ax, T in zip(axes[0], Ts):
for model in models:
values_by_T = getattr(model, quantity)
if T not in values_by_T:
continue
ax.plot(model.x_plot, values_by_T[T], label=_model_label(model), linewidth=2)
ax.set_title(f"{title}, T = {T:g} K")
ax.set_xlabel(model.xlabel_compound())
ax.set_ylabel(f"{ylabel} [meV/site]")
ax.legend()
fig.tight_layout()
figures[quantity] = fig
if show:
plt.show()
return figures
plot_excess_enthalpy_comparison ¶
plot_excess_enthalpy_comparison(
models: list[EGQCA], *, show: bool = True, enumerate_clusters: bool = False
) -> plt.Figure
Plot cluster excess enthalpies for several EGQCA models in one axes.
enumerate_clusters draws the numbers 1, 2, ... (clusters.dat order) as markers and
writes the key cluster_numbers.dat into each model's output folder.
Source code in src/egqca/comparison.py
def plot_excess_enthalpy_comparison(models: list[EGQCA], *, show: bool = True,
enumerate_clusters: bool = False) -> plt.Figure:
"""Plot cluster excess enthalpies for several EGQCA models in one axes.
``enumerate_clusters`` draws the numbers 1, 2, ... (clusters.dat order) as markers and
writes the key ``cluster_numbers.dat`` into each model's output folder.
"""
fig, ax = plt.subplots(figsize=(7, 5))
for model in models:
# same x scale as all other plots: x = 0 ... composition number of the compound
x_cluster = model.xj * model.extract_composition_number(model.compound)
if enumerate_clusters:
# the cluster numbers are the markers, in the model's color
(handle,) = ax.plot([], [], marker=r"$\#$", linestyle=" ", label=_model_label(model))
cluster_number_markers(ax, x_cluster, model.delta_j, handle.get_color())
ax.update_datalim(np.column_stack((x_cluster, model.delta_j)))
ax.autoscale_view()
else:
ax.plot(
x_cluster,
model.delta_j,
marker="o",
linestyle=" ",
alpha=0.75,
label=_model_label(model),
)
if enumerate_clusters:
_write_cluster_numbers(models)
ax.axhline(0, color="black", linestyle="--", linewidth=1)
ax.set_xlabel(models[0].xlabel_compound())
ax.set_ylabel(r"$\Delta_j$ [meV/site]")
ax.legend()
fig.tight_layout()
if show:
plt.show()
return fig
plot_miscibility_gap_comparison ¶
plot_miscibility_gap_comparison(
models: list[EGQCA], *, show: bool = True
) -> plt.Figure
Plot spinodal and binodal lines from several recomputed models.
Models whose scan did not converge onto a critical point are still drawn when they have lines, marked "(no T_c)" in the legend.
Source code in src/egqca/comparison.py
def plot_miscibility_gap_comparison(models: list[EGQCA], *, show: bool = True) -> plt.Figure:
"""Plot spinodal and binodal lines from several recomputed models.
Models whose scan did not converge onto a critical point are still drawn when
they have lines, marked "(no T_c)" in the legend.
"""
fig, ax = plt.subplots(figsize=(7, 5))
for model in models:
label = _model_label(model)
if getattr(model, "T_c_miscibility_gap", None) is None:
label += " (no T_c)"
if getattr(model, "binodal_line", np.empty(0)).size:
ax.plot(model.binodal_line[:, 1], model.binodal_line[:, 0], linestyle="--", label=f"{label} binodal")
if getattr(model, "spinodal_line", np.empty(0)).size:
ax.plot(model.spinodal_line[:, 1], model.spinodal_line[:, 0], linestyle="-", label=f"{label} spinodal")
ax.set_xlabel(models[0].xlabel_compound())
ax.set_ylabel("T [K]")
ax.legend()
fig.tight_layout()
if show:
plt.show()
return fig
plot_occurrence_probabilities_comparison ¶
plot_occurrence_probabilities_comparison(
models: list[EGQCA],
*,
x_values: Iterable[float] | None = None,
show: bool = True,
enumerate_clusters: bool = False
) -> dict[float, plt.Figure]
Plot occurrence probabilities vs temperature with one subplot per model.
enumerate_clusters writes the cluster number on each curve, near the high-T end, see
:func:plot_excess_enthalpy_comparison.
Source code in src/egqca/comparison.py
def plot_occurrence_probabilities_comparison(
models: list[EGQCA],
*,
x_values: Iterable[float] | None = None,
show: bool = True,
enumerate_clusters: bool = False,
) -> dict[float, plt.Figure]:
"""Plot occurrence probabilities vs temperature with one subplot per model.
``enumerate_clusters`` writes the cluster number on each curve, near the high-T end, see
:func:`plot_excess_enthalpy_comparison`.
"""
if x_values is None:
x = models[0].x
x_values = x[np.unique([len(x) // 4, len(x) // 2, 3 * len(x) // 4])]
figures = {}
for x_value in x_values:
fig, axes = plt.subplots(1, len(models), figsize=(6 * len(models), 5), squeeze=False)
for ax, model in zip(axes[0], models):
x_idx = np.abs(model.x - x_value).argmin()
lines = []
for idx_cluster in range(len(model.cluster_id)):
probabilities = [model.pj[T][x_idx, idx_cluster] for T in model.Tlist]
lines += ax.plot(model.Tlist, probabilities, linewidth=1)
if enumerate_clusters:
T_label = model.Tlist[0] + 0.9 * (model.Tlist[-1] - model.Tlist[0])
label_cluster_curves(ax, lines, np.full(len(lines), T_label))
ax.set_title(_model_label(model))
ax.set_xlabel(f"T [K] at x = {model.x[x_idx]:.3g}")
ax.set_ylabel(r"$p_j$")
fig.tight_layout()
figures[float(x_value)] = fig
if enumerate_clusters:
_write_cluster_numbers(models)
if show:
plt.show()
return figures
plot_occurrence_probability_difference_from_ideal ¶
plot_occurrence_probability_difference_from_ideal(
models: list[EGQCA],
*,
temperatures: Iterable[float] | None = None,
show: bool = True,
enumerate_clusters: bool = False
) -> dict[float, plt.Figure]
Plot p_j - p_j^ideal versus composition for all clusters.
enumerate_clusters writes the cluster number at the largest deviation of each
curve, see :func:plot_excess_enthalpy_comparison.
p_j^ideal is the ideal solid-solution, or a priori, cluster probability.
One figure is created per temperature. If several comparison models are
provided, each model gets one subplot and all clusters are overlaid.
Source code in src/egqca/comparison.py
def plot_occurrence_probability_difference_from_ideal(
models: list[EGQCA],
*,
temperatures: Iterable[float] | None = None,
show: bool = True,
enumerate_clusters: bool = False,
) -> dict[float, plt.Figure]:
"""Plot ``p_j - p_j^ideal`` versus composition for all clusters.
``enumerate_clusters`` writes the cluster number at the largest deviation of each
curve, see :func:`plot_excess_enthalpy_comparison`.
``p_j^ideal`` is the ideal solid-solution, or a priori, cluster probability.
One figure is created per temperature. If several comparison models are
provided, each model gets one subplot and all clusters are overlaid.
"""
Ts = _temperatures(models, temperatures)
figures = {}
for T in Ts:
fig, axes = plt.subplots(
1,
len(models),
figsize=(6 * len(models), 5),
squeeze=False,
)
for ax, model in zip(axes[0], models):
if T not in model.pj:
continue
if getattr(model, "pj0", None) is None or np.shape(model.pj0) != np.shape(
model.pj[T]
):
model.apriori(model.x)
probability_difference = model.pj[T] - model.pj0
lines = []
for idx_cluster in range(len(model.cluster_id)):
lines += ax.plot(
model.x_plot,
probability_difference[:, idx_cluster],
linewidth=1,
alpha=0.75,
)
if enumerate_clusters:
i_max = np.abs(probability_difference).argmax(axis=0)
label_cluster_curves(ax, lines, model.x_plot[i_max])
ax.axhline(0.0, color="black", linestyle="--", linewidth=1)
ax.set_title(f"{_model_label(model)}, T = {T:g} K")
ax.set_xlabel(model.xlabel_compound())
ax.set_ylabel(r"$p_j - p_j^{ideal}$")
fig.tight_layout()
figures[float(T)] = fig
if enumerate_clusters:
_write_cluster_numbers(models)
if show:
plt.show()
return figures
plot_average_properties_comparison ¶
plot_average_properties_comparison(
models: list[EGQCA],
property_files: Iterable[str | Path] | dict[str, str | Path],
*,
columns: Iterable[int | str] | None = None,
temperatures: Iterable[float] | None = None,
show_std: bool = False,
show: bool = True
) -> dict[float, plt.Figure]
Average selected property columns and overlay them in one figure per temperature.
Source code in src/egqca/comparison.py
def plot_average_properties_comparison(
models: list[EGQCA],
property_files: Iterable[str | Path] | dict[str, str | Path],
*,
columns: Iterable[int | str] | None = None,
temperatures: Iterable[float] | None = None,
show_std: bool = False,
show: bool = True,
) -> dict[float, plt.Figure]:
"""Average selected property columns and overlay them in one figure per temperature."""
if isinstance(property_files, dict):
file_by_label = {str(key): Path(value) for key, value in property_files.items()}
labels = [_model_label(model) for model in models]
duplicates = sorted(label for label, count in Counter(labels).items() if count > 1)
if duplicates:
raise ValueError(
f"Several models share the label(s) {duplicates}, so property_files cannot be "
"matched by label. Pass property_files as a list in the order of the models."
)
unknown = [label for label in labels if label not in file_by_label]
if unknown:
raise ValueError(
f"property_files has no entry for the model label(s) {unknown}; "
f"given: {sorted(file_by_label)}."
)
property_file_list = [file_by_label[label] for label in labels]
else:
property_file_list = [Path(path) for path in property_files]
if len(property_file_list) != len(models):
raise ValueError("property_files must have the same length as models.")
Ts = _temperatures(models, temperatures)
figures = {}
for T in Ts:
fig, ax = plt.subplots(figsize=(8, 5))
ylabel_parts = []
for model, property_file in zip(models, property_file_list):
prop_values, prop_names, prop_cluster_ids = read_properties(model, property_file)
selected_indices = _selected_property_indices(prop_names, columns)
prop_cluster_ids = np.asarray(prop_cluster_ids)
cluster_index_by_id = {cluster_id: idx for idx, cluster_id in enumerate(model.cluster_id)}
prop_cluster_indices = [cluster_index_by_id[cluster_id] for cluster_id in prop_cluster_ids]
for idx in selected_indices:
prop = prop_values[:, idx]
if len(prop_cluster_ids) == len(model.cluster_id):
avg = model.gqca_mean(prop, T)
std = model.gqca_std(prop, T)
else:
norm_probs, idx_sorted = normalize_probabilities(model, T, prop_cluster_indices)
prop_position_by_cluster_idx = {
cluster_idx: pos for pos, cluster_idx in enumerate(prop_cluster_indices)
}
avg = norm_probs @ prop[[prop_position_by_cluster_idx[cluster_idx] for cluster_idx in idx_sorted]]
std = None
prop_name = prop_names[idx]
ylabel_parts.append(prop_name)
line_label = f"{_model_label(model)}: {prop_name}"
ax.plot(model.x_plot, avg, linewidth=2, label=line_label)
if show_std and std is not None:
ax.fill_between(model.x_plot, avg - std, avg + std, alpha=0.12)
ax.set_title(f"Averaged properties, T = {T:g} K")
ax.set_xlabel(models[0].xlabel_compound())
ax.set_ylabel(", ".join(dict.fromkeys(ylabel_parts)))
ax.legend()
fig.tight_layout()
figures[float(T)] = fig
if show:
plt.show()
return figures
Optional ML Helpers¶
These functions are always importable; they only need ASE, which is a core dependency. The
backend of a built-in model is imported when the model is first used, so install the matching
extra (egqca[upet], egqca[mace], egqca[mattersim] or egqca[grace]) before running it,
otherwise an ImportError is raised. A user-supplied calculator needs no extra.
run_ml_relaxation ¶
run_ml_relaxation(
clusters_folder: str | Path,
ML_model: MLModel = "mattersim-5m",
ml_clusters_filename: str | None = None,
ml_volume_filename: str | None = None,
out_folder_name: str | None = None,
save_relaxed_structure: bool = True,
start_from_relaxed: bool = False,
relaxation_constraint: bool | str | None = DEFAULT_RELAXATION_CONSTRAINT,
CellFilter_mask: list[bool] | None = None,
bravais_supercell: list[int] | tuple[int, int, int] = (1, 1, 1),
fix_bravais_positions: bool = False,
bravais_tol: float = DEFAULT_BRAVAIS_TOL,
calc_phonons: bool = False,
save_phonon_cache: bool = True,
pressure_GPa: float | None = None,
N_phonon_supercell: int | list[int] = 2,
steps: int = 5000,
device: str = "cpu",
fmax: float = 0.0001,
optimizer: Any = FIRE,
optimizer_kwargs: dict | None = None,
ML_model_name: str | None = None,
permutable_sites: int | None = None,
) -> tuple[dict[str, float], dict[str, np.ndarray]]
Run ML relaxations for all cluster CIF files and write ML-specific cluster and volume files.
Results are written into a run folder inside clusters_folder. If
out_folder_name is None, the model name (ML_model_name, else
the model string) is used, except for
ML_model="eddp:<path>" where the folder is named
"eddp-<file name without .eddp>" (the full model path would make for
an unwieldy folder name).
Slashes in the run folder name are replaced by underscores. The same name
always means the same folder (as in the parallel script and
:func:rerun_nonconverged_ml): a run folder that is already complete is not
replaced; its results are returned. Use another out_folder_name for a new
run with the same model.
The cluster setup (n, sites, Nat, compound) is read from
<clusters_folder>/clusters_template.dat, else from DFT/clusters.dat of
an older tree, else from a scan of the cluster CIFs; the template is written
in the latter two cases.
An incomplete run folder is continued, but only with the settings it was
started with: the first run records them in <run_folder>/run_settings.json
(phonon supercell in phonons/phonon_settings.json), and a run with
different settings stops with an error listing them. steps and
device may differ, see :func:egqca._ml_utils._run_settings.
If save_relaxed_structure is True, each relaxed structure is written
into <run_folder>/cif_relaxed/<cluster_id>_<model name>.cif.
If it is False, relaxed structures are not written.
With start_from_relaxed=True, a cluster that is relaxed (again) starts
from its structure in cif_relaxed/ if there is one, e.g. the last
structure of a non-converged relaxation, instead of from its original CIF.
Each relaxation writes its optimizer output to
<run_folder>/ML_logs/clusters/<cluster_id>.log.
A global <run_folder>/ML_logs/<model name>.log records resume
decisions, missing rows, non-converged relaxations, and final completeness.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ML_model
|
str, ASE calculator, or callable
|
The ML potential. Either
One calculator instance serves all clusters and their phonons. The
|
'mattersim-5m'
|
ML_model_name
|
str
|
Name of the model in the run folder, output file names and logs.
Required if |
None
|
relaxation_constraint
|
bool, str, or None
|
Space-group / Bravais-lattice ASE constraint forwarded to
:func: |
DEFAULT_RELAXATION_CONSTRAINT
|
CellFilter_mask
|
list[bool] or None
|
Strain mask of six bools forwarded to
:func: .. note::
These are not the cell parameters .. warning::
Setting both |
None
|
bravais_supercell
|
list[int] or tuple[int, int, int]
|
Diagonal supercell sizes |
(1, 1, 1)
|
fix_bravais_positions
|
bool
|
Only used when |
False
|
bravais_tol
|
float
|
Relative tolerance of the Bravais lattice detection used by the
FixBravaisCell constraint (default 0.01, i.e. about 1 % in cell lengths
and angles). A start cell within this tolerance of a higher-symmetry
lattice is projected onto that exact lattice; the detected lattice is
also the one reported as initial and target lattice. Only used when
|
DEFAULT_BRAVAIS_TOL
|
save_phonon_cache
|
bool
|
Only used when |
True
|
permutable_sites
|
int
|
Number of permutable sites n, used for x = n_j / n. By default read from
the clusters template (see above), else taken as the highest |
None
|
Source code in src/egqca/ml.py
@entry_point("ML relaxation", lambda b: [
("Clusters folder", b.arguments["clusters_folder"]),
("ML model", _ml_model_label(b.arguments["ML_model"], b.arguments["ML_model_name"])),
("Output folder", b.arguments["out_folder_name"] or "model name (default)"),
("Pressure (GPa)", b.arguments["pressure_GPa"]),
("Relaxation constraint", b.arguments["relaxation_constraint"]
if b.arguments["relaxation_constraint"] in (None, "FixSymmetry")
else f"{b.arguments['relaxation_constraint']} (bravais_tol {b.arguments['bravais_tol']:g})"),
("Cell filter mask", b.arguments["CellFilter_mask"]),
("fmax (eV/A) / max steps", f"{b.arguments['fmax']:g} / {b.arguments['steps']}"),
("Device", b.arguments["device"]),
("Phonons", f"yes (supercell {b.arguments['N_phonon_supercell']})" if b.arguments["calc_phonons"] else "no"),
])
def run_ml_relaxation(
clusters_folder: str | Path,
ML_model: MLModel = "mattersim-5m",
ml_clusters_filename: str | None = None,
ml_volume_filename: str | None = None,
out_folder_name: str | None = None,
save_relaxed_structure: bool = True,
start_from_relaxed: bool = False,
relaxation_constraint: bool | str | None = DEFAULT_RELAXATION_CONSTRAINT,
CellFilter_mask: list[bool] | None = None,
bravais_supercell: list[int] | tuple[int, int, int] = (1, 1, 1),
fix_bravais_positions: bool = False,
bravais_tol: float = DEFAULT_BRAVAIS_TOL,
calc_phonons: bool = False,
save_phonon_cache: bool = True,
pressure_GPa: float | None = None,
N_phonon_supercell: int | list[int] = 2, # phonon supercell: int N (N x N x N) or [N1, N2, N3]
steps: int = 5000, # max optimization steps
device: str = "cpu",
fmax: float = 1e-4, # eV/Å, force convergence threshold
optimizer: Any = FIRE,
optimizer_kwargs: dict | None = None,
ML_model_name: str | None = None,
permutable_sites: int | None = None,
) -> tuple[dict[str, float], dict[str, np.ndarray]]:
"""Run ML relaxations for all cluster CIF files and write ML-specific cluster and volume files.
Results are written into a run folder inside ``clusters_folder``. If
``out_folder_name`` is ``None``, the model name (``ML_model_name``, else
the model string) is used, except for
``ML_model="eddp:<path>"`` where the folder is named
``"eddp-<file name without .eddp>"`` (the full model path would make for
an unwieldy folder name).
Slashes in the run folder name are replaced by underscores. The same name
always means the same folder (as in the parallel script and
:func:`rerun_nonconverged_ml`): a run folder that is already complete is not
replaced; its results are returned. Use another ``out_folder_name`` for a new
run with the same model.
The cluster setup (n, sites, Nat, compound) is read from
``<clusters_folder>/clusters_template.dat``, else from ``DFT/clusters.dat`` of
an older tree, else from a scan of the cluster CIFs; the template is written
in the latter two cases.
An incomplete run folder is continued, but only with the settings it was
started with: the first run records them in ``<run_folder>/run_settings.json``
(phonon supercell in ``phonons/phonon_settings.json``), and a run with
different settings stops with an error listing them. ``steps`` and
``device`` may differ, see :func:`egqca._ml_utils._run_settings`.
If ``save_relaxed_structure`` is ``True``, each relaxed structure is written
into ``<run_folder>/cif_relaxed/<cluster_id>_<model name>.cif``.
If it is ``False``, relaxed structures are not written.
With ``start_from_relaxed=True``, a cluster that is relaxed (again) starts
from its structure in ``cif_relaxed/`` if there is one, e.g. the last
structure of a non-converged relaxation, instead of from its original CIF.
Each relaxation writes its optimizer output to
``<run_folder>/ML_logs/clusters/<cluster_id>.log``.
A global ``<run_folder>/ML_logs/<model name>.log`` records resume
decisions, missing rows, non-converged relaxations, and final completeness.
Parameters
----------
ML_model : str, ASE calculator, or callable
The ML potential. Either
- a model string of one of the built-in model families (e.g.
``"mattersim-5m"``, ``"mace-medium-mpa-0"``, ``"pet-oam-xl"``,
``"GRACE-3L-OMAT-large-ft-AM"``, ``"eddp:<path>"``),
- any ASE calculator providing energy, forces and stress, e.g. a
fine-tuned model ``MACECalculator(model_paths="my.model")``, or
- a function (or calculator class) that returns such a calculator when
called without arguments, e.g. ``functools.partial(MyCalculator,
model="my.ckpt")``. It is only called once a cluster actually needs
relaxing, so a run with nothing left to do never loads the model.
One calculator instance serves all clusters and their phonons. The
``device`` argument only applies to model strings; set the device of
your own calculator when you build it.
ML_model_name : str, optional
Name of the model in the run folder, output file names and logs.
Required if ``ML_model`` is a calculator or a function, defaults to
the model string otherwise. A resumed run is matched by this name and
by the model behind it: a model string, or the class of a user-supplied
calculator. Checkpoints of one calculator class cannot be told apart, so
give each its own name.
relaxation_constraint : bool, str, or None, optional
Space-group / Bravais-lattice ASE constraint forwarded to
:func:`geometry_relaxation`. See that function for accepted values,
including ``True`` for auto-detecting the Bravais type from each
cluster's own (pre-relaxation) cell -- since EGQCA's substitutional
clusters share one template's cell shape before relaxation, this
constrains every cluster to the same cell family regardless of
composition, which is the common case for a set of clusters whose
excess energies should be compared on a consistent basis.
CellFilter_mask : list[bool] or None, optional
Strain mask of six bools forwarded to
:func:`geometry_relaxation` and passed on to ``FrechetCellFilter``, in ASE's Voigt
order of the Cartesian strain components ``[xx, yy, zz, yz, xz, xy]``.
``True`` = component free to relax, ``False`` = fixed. ``None``
(default) leaves all six components free.
.. note::
These are not the cell parameters ``[a, b, c, alpha, beta, gamma]``.
The two only coincide for an orthogonal cell aligned with the
Cartesian axes; for a hexagonal, monoclinic or triclinic cell, e.g.,
fixing ``yz, xz, xy`` does not keep the cell angles. To keep a cell
shape, use ``relaxation_constraint`` instead.
.. warning::
Setting both ``relaxation_constraint`` and ``CellFilter_mask``
applies an ASE constraint (FixSymmetry / FixBravaisCell) *and* a
FrechetCellFilter mask simultaneously, which may cause unexpected
behaviour.
bravais_supercell : list[int] or tuple[int, int, int], optional
Diagonal supercell sizes ``[n1, n2, n3]`` describing how the cluster
cells relate to the underlying primitive cell. The lattice vectors
are divided by these factors before the Bravais lattice is detected
and before the FixBravaisCell symmetry operations are built, so
supercell inputs are constrained to the correct primitive lattice
type. Default ``(1, 1, 1)`` (cells are treated as-is). Only
relevant when ``relaxation_constraint`` is a Bravais key or crystal
system string; it additionally controls the lattice reported in the
per-cluster logs.
fix_bravais_positions : bool, optional
Only used when ``relaxation_constraint`` is ``True``, a Bravais key or a
crystal system string. If ``True`` the atomic positions are frozen at
their starting fractional coordinates (forces are zeroed), so only the
cell relaxes: no internal relaxation at all, not a projection onto the
symmetry-allowed positions. Atoms of a decorated cluster generally have
positional freedom, so this neglects their local relaxation. ``False``
(default) constrains only the cell metric / stress and leaves the
internal coordinates of the cluster free to relax.
bravais_tol : float, optional
Relative tolerance of the Bravais lattice detection used by the
FixBravaisCell constraint (default 0.01, i.e. about 1 % in cell lengths
and angles). A start cell within this tolerance of a higher-symmetry
lattice is projected onto that exact lattice; the detected lattice is
also the one reported as initial and target lattice. Only used when
``relaxation_constraint`` is ``True``, a Bravais key or a crystal system.
save_phonon_cache : bool, optional
Only used when ``calc_phonons`` is ``True``. If ``True`` (default) the
finite-displacement forces of each cluster are kept in
``<run_folder>/phonons/<cluster_id>_cache/`` together with the
equilibrium structure and ``phonon_info.json``. The DOS can then be
re-sampled with different ``kpts``/``npts``/``width`` (or different
force-constant settings) via :func:`phonon_dos_from_cache` without
re-running the ML model, and an interrupted phonon run resumes from the
displacements already in the cache.
permutable_sites : int, optional
Number of permutable sites n, used for x = n_j / n. By default read from
the clusters template (see above), else taken as the highest ``S*``
folder number. Give it only when neither is right, e.g. for a tree
without template whose clusters cover a sub-range of compositions; it is
then written into the template. A value that differs from the template
raises a ValueError.
"""
t0 = time.monotonic()
clusters_folder = Path(clusters_folder)
# case-insensitive, as on the command line; recorded and compared in this form
relaxation_constraint = _normalize_relaxation_constraint(relaxation_constraint)
model_name = _ml_model_name(ML_model, ML_model_name)
model_description = _ml_model_description(ML_model, ML_model_name)
safe_ML_model = _ml_model_display_name(model_name)
if ml_clusters_filename is None:
ml_clusters_filename = f"clusters_{safe_ML_model}.dat"
if ml_volume_filename is None:
ml_volume_filename = f"volume_{safe_ML_model}.dat"
permutable_sites, sites, Nat, compound, _ = _resolve_cluster_setup(
clusters_folder, permutable_sites=permutable_sites,
)
target_cifs = _ml_target_cifs(clusters_folder)
target_cluster_ids = {sub_dir.name for sub_dir, _ in target_cifs}
run_folder = _prepare_ml_run_folder(
clusters_folder,
out_folder_name,
model_name,
ml_clusters_filename,
ml_volume_filename,
target_cluster_ids=target_cluster_ids,
calc_phonons=calc_phonons,
)
# file-based models (eddp): refuse to resume a run folder made with another model file
model_identity = _model_identity(ML_model)
_check_model_identity(run_folder, model_identity)
# refuse to continue a run folder with settings other than those it was started with
_check_run_settings(
run_folder,
_run_settings(
model=model_name,
pressure_GPa=pressure_GPa,
relaxation_constraint=relaxation_constraint,
CellFilter_mask=CellFilter_mask,
bravais_supercell=bravais_supercell,
fix_bravais_positions=fix_bravais_positions,
fmax=fmax,
optimizer=optimizer,
optimizer_kwargs=optimizer_kwargs,
bravais_tol=bravais_tol,
model_source=_ml_model_source(ML_model),
),
_phonon_settings(N_phonon_supercell) if calc_phonons else None,
)
(
ml_clusters_filename,
ml_volume_filename,
resume_existing,
) = _prepare_ml_output_files(
run_folder,
ml_clusters_filename,
ml_volume_filename,
target_cluster_ids=target_cluster_ids,
permutable_sites=permutable_sites,
sites=sites,
compound=compound,
ML_model=model_description,
)
clusters_file = run_folder / ml_clusters_filename
volume_file = run_folder / ml_volume_filename
# results of parallel jobs (ml_relaxation_parallel.py) in this run folder; the
# shared run_settings.json guarantees they were made with the same settings
per_cluster_files = sorted((run_folder / "per_cluster").glob(f"*_{safe_ML_model}_ml_result.dat"))
per_cluster_rows, _ = _parse_result_files(per_cluster_files, safe_ML_model)
imported_ids, imported_non_converged = _merge_per_cluster_results(
[row for row in per_cluster_rows if row[0] in target_cluster_ids],
clusters_file, volume_file,
permutable_sites=permutable_sites, Nat_default=Nat,
)
completed_clusters = _read_completed_ids(clusters_file)
completed_volumes = _read_completed_ids(volume_file)
completed_ids = completed_clusters & completed_volumes
pending_ids = target_cluster_ids - completed_ids
global_log_file = _global_ml_log_file(run_folder, model_name)
_write_global_ml_run_settings(
global_log_file,
clusters_folder=clusters_folder,
run_folder=run_folder,
ML_model=model_name,
model_description=model_description,
model_identity=model_identity,
clusters_file=clusters_file,
volume_file=volume_file,
save_relaxed_structure=save_relaxed_structure,
relaxation_constraint=relaxation_constraint,
CellFilter_mask=CellFilter_mask,
bravais_supercell=bravais_supercell,
fix_bravais_positions=fix_bravais_positions,
bravais_tol=bravais_tol,
calc_phonons=calc_phonons,
N_phonon_supercell=N_phonon_supercell,
pressure_GPa=pressure_GPa,
steps=steps,
fmax=fmax,
device=device if isinstance(ML_model, str) else "set by the user-supplied calculator",
optimizer=optimizer,
optimizer_kwargs=optimizer_kwargs,
)
_write_global_ml_log(
global_log_file,
f"Starting ML relaxation run for model {model_description}. \n"
f"Total clusters: {len(target_cluster_ids)}. \n"
f"Already complete: {len(completed_ids)}. \n"
f"Pending: {len(pending_ids)}.\n"
)
if resume_existing:
_write_global_ml_log(
global_log_file,
f"Continuing existing run folder: {run_folder.name}. "
f"Output files: {clusters_file.name}, {volume_file.name}."
)
if imported_ids:
_write_global_ml_log(
global_log_file,
f"Imported {len(imported_ids)} results from per_cluster/ (parallel runs)."
)
for cluster_id, final_fmax in imported_non_converged:
final_fmax_text = "unavailable" if np.isnan(final_fmax) else f"{final_fmax:.6g}"
_write_global_ml_log(
global_log_file,
f"Imported relaxation did not converge: {cluster_id}. Final fmax: {final_fmax_text}."
)
ML_energy = {}
ML_latpar = {}
n_converged = 0
n_not_converged = 0
n_skipped = len(completed_ids)
n_phonons_resumed = 0
bravais_mismatch_ids: list[str] = []
phonon_dir = run_folder / "phonons"
for sub_dir, cif_file in target_cifs:
relaxed_cif_path = run_folder / "cif_relaxed" / f"{sub_dir.name}_{safe_ML_model}.cif"
phonon_dos_path = phonon_dir / f"{sub_dir.name}.dos"
# A cluster already in completed_ids has an energy/lattice row, but if
# calc_phonons was turned on after that row was written (or the phonon
# step previously raised and stopped the run before this cluster's turn
# came around again), its phonon DOS may still be missing. Don't treat
# it as complete in that case.
phonons_pending = calc_phonons and not phonon_dos_path.exists()
if sub_dir.name in completed_ids and not phonons_pending:
print("Already complete: "+sub_dir.name)
continue
# Reuse the already-relaxed structure instead of paying for a full
# relaxation again when only the phonon DOS is missing.
resume_phonons_only = (
sub_dir.name in completed_ids
and phonons_pending
and relaxed_cif_path.exists()
)
try:
ml_output_file = _cluster_ml_log_file(run_folder, sub_dir.name)
# a phonons-only pass keeps the relaxation's log (runtime, Bravais check)
with open(ml_output_file, "a" if resume_phonons_only else "w") as f:
if resume_phonons_only:
f.write(f"\n{_PHONONS_ONLY_SEPARATOR} (reusing {relaxed_cif_path.name}) =====\n")
tee_stdout = _Tee(sys.stdout, f)
tee_stderr = _Tee(sys.stderr, f)
with redirect_stdout(tee_stdout), redirect_stderr(tee_stderr):
t_total0 = time.monotonic()
if resume_phonons_only:
print(
"\n----- Reusing relaxed structure for "+sub_dir.name+
" (phonons pending) -----"
)
atoms_relaxed = read(relaxed_cif_path)
t_relax = 0.0
n_phonons_resumed += 1
else:
if sub_dir.name in completed_ids:
print(
f"\n{sub_dir.name}: relaxation already recorded but phonon "
f"DOS is missing, and no relaxed CIF ({relaxed_cif_path}) is "
f"available to resume from; relaxing again from scratch."
)
if start_from_relaxed and relaxed_cif_path.exists():
print(f"\nStarting from the relaxed structure {relaxed_cif_path}")
atoms = read(relaxed_cif_path)
else:
atoms = read(cif_file)
print("\n----- Geometry relaxation for "+sub_dir.name+" -----")
_save_cif = (
relaxed_cif_path if save_relaxed_structure else None
)
atoms_relaxed = geometry_relaxation(
atoms.copy(),
ML_model=ML_model,
pressure_GPa=pressure_GPa,
relaxation_constraint=relaxation_constraint,
CellFilter_mask=CellFilter_mask,
bravais_supercell=bravais_supercell,
fix_bravais_positions=fix_bravais_positions,
bravais_tol=bravais_tol,
steps=steps,
device=device,
fmax=fmax,
optimizer=optimizer,
optimizer_kwargs=optimizer_kwargs,
save_cif=_save_cif,
ML_model_name=ML_model_name,
)
t_relax = time.monotonic() - t_total0
energy = atoms_relaxed.get_potential_energy()/(Ry_to_mev/1000)
latpar = np.hstack((atoms_relaxed.cell.lengths(), atoms_relaxed.cell.angles()))
ML_energy[sub_dir.name] = energy
ML_latpar[sub_dir.name] = latpar
if sub_dir.name not in completed_clusters:
_append_ml_cluster_result(
clusters_file,
sub_dir.name,
energy,
permutable_sites=permutable_sites,
Nat=Nat,
converged=atoms_relaxed.info.get("egqca_ml_converged", True),
)
completed_clusters.add(sub_dir.name)
if not atoms_relaxed.info.get("egqca_ml_converged", True):
n_not_converged += 1
final_fmax = atoms_relaxed.info.get("egqca_ml_final_fmax")
final_fmax_text = (
"unavailable" if final_fmax is None else f"{final_fmax:.6g}"
)
_write_global_ml_log(
global_log_file,
f"Relaxation did not converge within {steps} steps: {sub_dir.name}. "
f"Final fmax: {final_fmax_text}."
)
else:
n_converged += 1
if sub_dir.name not in completed_volumes:
_append_ml_volume_result(volume_file, sub_dir.name, latpar)
completed_volumes.add(sub_dir.name)
if atoms_relaxed.info.get("egqca_ml_bravais_mismatch"):
bravais_mismatch_ids.append(sub_dir.name)
if calc_phonons:
print("\n----- Phonon calculation for "+sub_dir.name+" -----")
t_phonon0 = time.monotonic()
# Keeping the forces makes the DOS re-samplable with
# egqca.ml.phonon_dos_from_cache, and lets an
# interrupted phonon run resume where it stopped.
cache_dir = (
phonon_dir / f"{sub_dir.name}_cache"
if save_phonon_cache else None
)
dos = phonons(
atoms_relaxed,
ML_model,
N_phonon_supercell,
device=device,
cache_dir=cache_dir,
ML_model_name=ML_model_name,
)
# Save DOS data: energy in first column, density of states in second column
dos_data = np.column_stack((dos.get_energies(), dos.get_weights()))
phonon_dir.mkdir(parents=True, exist_ok=True)
with _atomic_write(phonon_dos_path) as f_dos:
np.savetxt(f_dos, dos_data, fmt="%.6e", header="Energy(eV) DOS")
t_phonon = time.monotonic() - t_phonon0
print(f"Relaxation runtime: {t_relax:.2f} s")
print(f"Phonon runtime: {t_phonon:.2f} s")
print(_runtime_line(time.monotonic() - t_total0))
#_write_global_ml_log(global_log_file, f"Completed {sub_dir.name}.")
except Exception as exc:
_write_global_ml_error(global_log_file, sub_dir.name, exc)
raise
_update_convergence_warning(clusters_file, volume_file)
final_clusters = _read_completed_ids(clusters_file)
final_volumes = _read_completed_ids(volume_file)
still_missing = target_cluster_ids - (final_clusters & final_volumes)
n_total_run = n_converged + n_not_converged
summary = (
f"Summary:\n"
f"Converged: {n_converged}\n"
f"Not converged: {n_not_converged}\n"
f"skipped (already complete): {n_skipped}\n"
)
if calc_phonons and n_phonons_resumed:
summary += (
f"phonons computed for already-relaxed clusters (reused "
f"cif_relaxed/, not re-relaxed): {n_phonons_resumed}\n"
)
_write_global_ml_log(global_log_file, summary)
if bravais_mismatch_ids:
_write_global_ml_log(
global_log_file,
f"Bravais lattice changed (incompatible with constraint): "
f"{len(bravais_mismatch_ids)}/{n_total_run} clusters."
)
if still_missing:
_write_global_ml_log(
global_log_file,
"Run ended with missing entries: " + ", ".join(sorted(still_missing))
)
else:
_write_global_ml_log(global_log_file, "Run ended with complete output files.")
if calc_phonons:
for line in _phonon_stability_report_lines(run_folder / "phonons"):
_write_global_ml_log(global_log_file, line)
_write_global_ml_log(global_log_file, f"\nTotal runtime: {time.monotonic() - t0:.2f} s")
# clusters completed by earlier runs or parallel jobs, from the files
energy_rows, volume_rows = _read_ml_rows(clusters_file), _read_ml_rows(volume_file)
for cid in sorted(target_cluster_ids - set(ML_energy)):
if cid in energy_rows and cid in volume_rows:
ML_energy[cid] = float(energy_rows[cid][5])
ML_latpar[cid] = np.array([float(v) for v in volume_rows[cid][1:7]])
return ML_energy, ML_latpar
collect_ml_results ¶
collect_ml_results(
run_folder: str | Path,
*,
clusters_folder: str | Path | None = None,
clusters_template: str | Path | None = None,
model: str | None = None,
ml_clusters_filename: str | None = None,
ml_volume_filename: str | None = None,
log_file: str | Path | None = None,
permutable_sites: int | None = None
) -> tuple[Path, Path, Path]
Aggregate per-cluster ml_result.dat files into clusters.dat and volume_*.dat.
run_folder is the model run folder (e.g. <clusters_folder>/mattersim-5m/).
Result files are read from run_folder/per_cluster/.
Aggregated output (clusters_.dat, volume_.dat) and the convergence log are
written into run_folder.
clusters_folder defaults to run_folder.parent and is used to infer
system setup (permutable sites, atom count, compound name) from the S* structure.
Header metadata (permutable_sites, sites, Nat, compound) and the list of all
clusters are read from clusters_template if given, else from
<clusters_folder>/clusters_template.dat, else from DFT/clusters.dat of an
older tree, else from a scan of the cluster CIFs with n = permutable_sites or
the highest S* folder number; in the latter two cases clusters_template.dat is
written. A permutable_sites that differs from the template raises a ValueError.
If model is None the model name is inferred from the filenames; an error
is raised when multiple models are found.
Returns the paths to the written clusters, volume, and log files.
Source code in src/egqca/ml.py
def collect_ml_results(
run_folder: str | Path,
*,
clusters_folder: str | Path | None = None,
clusters_template: str | Path | None = None,
model: str | None = None,
ml_clusters_filename: str | None = None,
ml_volume_filename: str | None = None,
log_file: str | Path | None = None,
permutable_sites: int | None = None,
) -> tuple[Path, Path, Path]:
"""Aggregate per-cluster *_ml_result.dat files into clusters_*.dat and volume_*.dat.
``run_folder`` is the model run folder (e.g. ``<clusters_folder>/mattersim-5m/``).
Result files are read from ``run_folder/per_cluster/``.
Aggregated output (clusters_*.dat, volume_*.dat) and the convergence log are
written into ``run_folder``.
``clusters_folder`` defaults to ``run_folder.parent`` and is used to infer
system setup (permutable sites, atom count, compound name) from the S* structure.
Header metadata (permutable_sites, sites, Nat, compound) and the list of all
clusters are read from ``clusters_template`` if given, else from
``<clusters_folder>/clusters_template.dat``, else from ``DFT/clusters.dat`` of an
older tree, else from a scan of the cluster CIFs with n = ``permutable_sites`` or
the highest S* folder number; in the latter two cases clusters_template.dat is
written. A ``permutable_sites`` that differs from the template raises a ValueError.
If ``model`` is ``None`` the model name is inferred from the filenames; an error
is raised when multiple models are found.
Returns the paths to the written clusters, volume, and log files.
"""
run_folder = Path(run_folder)
per_cluster_dir = run_folder / "per_cluster"
clusters_folder = Path(clusters_folder) if clusters_folder is not None else run_folder.parent
result_files = sorted(per_cluster_dir.glob("*_ml_result.dat"))
if not result_files:
warnings.warn(f"No *_ml_result.dat files found under {per_cluster_dir}")
safe_model = _detect_ml_model(result_files) if model is None else _ml_model_display_name(model)
matching = [
rf for rf in result_files
if rf.stem.endswith(f"_{safe_model}_ml_result")
]
if not matching:
warnings.warn(f"No *_{safe_model}_ml_result.dat files found under {per_cluster_dir}")
matching.sort(key=lambda p: tuple(
int(x) for x in re.match(r"S(\d+)(?:_d(\d+))?_i(\d+)_w(\d+)", p.name).groups(default='0')
))
permutable_sites, sites, Nat_default, compound, all_cluster_ids = _resolve_cluster_setup(
clusters_folder, permutable_sites=permutable_sites, clusters_template=clusters_template,
)
if ml_clusters_filename is None:
ml_clusters_filename = f"clusters_{safe_model}.dat"
if ml_volume_filename is None:
ml_volume_filename = f"volume_{safe_model}.dat"
run_folder.mkdir(parents=True, exist_ok=True)
clusters_path = run_folder / ml_clusters_filename
volume_path = run_folder / ml_volume_filename
log_path = Path(log_file) if log_file is not None else run_folder / f"ML_logs/convergence_{safe_model}.log"
# clusters_path/volume_path may already hold rows from an earlier
# run_ml_relaxation (sequential) run, or an earlier collect_ml_results call,
# on this same run folder. Those rows have no corresponding per_cluster/
# file, so they must be preserved rather than clobbered: the header is only
# (re-)written when the file doesn't exist yet, and only cluster IDs not
# already present are appended below.
# parse first: only files with a data row count as found; unreadable files
# (e.g. a killed job) are missing, so they get requeued
parsed_rows, unreadable_ids = _parse_result_files(matching, safe_model, progress=True)
matching_ids = {row[0] for row in parsed_rows}
if not clusters_path.exists():
_write_ml_clusters_header(
clusters_path,
permutable_sites=permutable_sites,
sites=sites,
compound=compound,
ML_model=model or safe_model,
)
if not volume_path.exists():
_write_ml_volume_header(volume_path, ML_model=model or safe_model)
_merge_per_cluster_results(
parsed_rows, clusters_path, volume_path,
permutable_sites=permutable_sites, Nat_default=Nat_default,
)
_update_convergence_warning(clusters_path, volume_path)
# counts from the state of the files after the merge, so that every call
# reports the same for the same results
cluster_order = lambda cid: [int(n) for n in re.findall(r"\d+", cid)]
recorded_ids = _read_completed_ids(clusters_path) & _read_completed_ids(volume_path)
flagged_ids = _read_non_converged_legacy_ids(clusters_path)
fmax_by_id = {row[0]: row[13] for row in parsed_rows}
not_converged_ids = sorted(recorded_ids & flagged_ids, key=cluster_order)
missing_ids = [cid for cid in all_cluster_ids if cid not in recorded_ids]
missing_ids += [cid for cid in unreadable_ids if cid not in recorded_ids and cid not in missing_ids]
cluster_log_dir = run_folder / "ML_logs" / "clusters"
bravais_mismatch_ids = [
cid for cid in sorted(recorded_ids, key=cluster_order)
if _extract_log_bravais_mismatch(cluster_log_dir / f"{cid}.log")
]
n_total = len(matching)
n_unreadable = len(unreadable_ids)
n_non_converged = len(not_converged_ids)
n_converged = len(recorded_ids) - n_non_converged
n_missing = len(missing_ids)
n_legacy_only = len(recorded_ids - matching_ids)
# Write the missing clusters to a standalone, condor-ready file in the same
# "<S folder>, <cluster id>" format as condor_jobs.txt, so they can be
# requeued directly with
# queue S_DIR, CLUSTER_ID from missing_clusters.txt
# It lives in clusters_folder, the directory condor_submit is run from, and
# always lists what is missing now: without missing clusters it is removed.
missing_clusters_path = clusters_folder / "missing_clusters.txt"
if missing_ids:
with open(missing_clusters_path, "w") as mf:
for cid in missing_ids:
m = re.match(r"(S\d+)", cid)
s_dir = m.group(1) if m else cid
mf.write(f"{s_dir}, {cid}\n")
print(f"Wrote {n_missing} missing clusters to {missing_clusters_path}")
else:
missing_clusters_path.unlink(missing_ok=True)
log_path.parent.mkdir(parents=True, exist_ok=True)
with open(log_path, "w") as f:
cluster_logs = sorted(cluster_log_dir.glob("S*.log"))
if cluster_logs:
header = _extract_log_header(cluster_logs[0])
if header:
f.write(f"ML-relaxation settings (from <cluster>.log):\n")
f.write(header)
f.write("\n\n")
f.write(f"ML collect results summary\n")
f.write(f"Model: {model or safe_model}\n")
f.write(f"Run folder: {run_folder}\n")
f.write(f"Clusters folder: {clusters_folder}\n")
f.write(f"Clusters file: {clusters_path}\n")
f.write(f"Volume file: {volume_path}\n")
f.write(f"\n")
f.write(f"Total clusters: {len(all_cluster_ids)}\n")
f.write(f"Total result files: {n_total}\n")
if n_legacy_only:
f.write(
f"Recorded without per_cluster file (e.g. by run_ml_relaxation): "
f"{n_legacy_only}\n"
)
f.write(f"Missing clusters: {n_missing}"
+ (f" (incl. {n_unreadable} unreadable result files)" if n_unreadable else "") + "\n")
f.write(f"Converged: {n_converged}\n")
f.write(f"Not converged: {n_non_converged}\n")
f.write(f"Unreadable files: {n_unreadable}\n")
if bravais_mismatch_ids:
f.write(
f"Bravais lattice violations: "
f"{len(bravais_mismatch_ids)}/{len(recorded_ids)}\n"
)
cluster_log_files = sorted(cluster_log_dir.glob("S*.log"))
if cluster_log_files:
runtimes = [_extract_log_runtime(p) for p in cluster_log_files]
runtimes = [r for r in runtimes if r is not None]
if runtimes:
f.write(
f"\nTotal runtime ({len(runtimes)} clusters): "
f"{sum(runtimes):.2f} s\n"
)
f.write(
f"Average runtime per cluster: "
f"{(sum(runtimes)/len(runtimes)):.2f} s\n"
)
phonon_report = _phonon_stability_report_lines(run_folder / "phonons")
if phonon_report:
f.write("\n")
for line in phonon_report:
f.write(line + "\n")
if missing_ids:
f.write(f"\nMissing clusters ({n_missing}) written to: {missing_clusters_path}\n")
if not_converged_ids:
f.write(f"\nNon-converged clusters: {n_non_converged}\n")
for cid in not_converged_ids:
fmax = fmax_by_id.get(cid, float("nan"))
if cid not in fmax_by_id:
fmax_str = "unavailable (no per_cluster file)"
elif np.isnan(fmax):
fmax_str = "unavailable"
else:
fmax_str = f"{fmax:.6g} eV/Å"
f.write(f" {cid} final_fmax: {fmax_str}\n")
if unreadable_ids:
f.write(
f"\nUnreadable result files (empty, header only or malformed), "
f"requeued via missing_clusters.txt: {n_unreadable}\n"
)
for cid in unreadable_ids:
f.write(f" {cid}\n")
return clusters_path, volume_path, log_path
reset_ml_clusters ¶
reset_ml_clusters(
run_folder: str | Path,
model: str | None = None,
cluster_ids: Iterable[str] | None = None,
*,
clusters_folder: str | Path | None = None,
ml_clusters_filename: str | None = None,
ml_volume_filename: str | None = None
) -> list[str]
Undo the results of clusters so that they are relaxed again.
Removes the clusters' rows from clusters_<model>.dat and
volume_<model>.dat, their per_cluster/ result files and their phonon
DOS; phonon force caches are discarded by :func:phonons once the structure
has changed. Both :func:run_ml_relaxation and ml_relaxation_parallel.py
then relax them again, e.g. with more steps.
cluster_ids=None resets the non-converged clusters: those flagged in the
clusters file and those whose per_cluster/ result is not converged, also
when it has not been collected yet. model is detected from the result
file names when None. The reset clusters are written to
<clusters_folder>/rerun_clusters.txt in the <S folder>, <cluster id>
format of missing_clusters.txt, ready to be queued; clusters_folder
defaults to the parent of run_folder. Returns the reset cluster IDs.
Source code in src/egqca/ml.py
def reset_ml_clusters(
run_folder: str | Path,
model: str | None = None,
cluster_ids: Iterable[str] | None = None,
*,
clusters_folder: str | Path | None = None,
ml_clusters_filename: str | None = None,
ml_volume_filename: str | None = None,
) -> list[str]:
"""Undo the results of clusters so that they are relaxed again.
Removes the clusters' rows from ``clusters_<model>.dat`` and
``volume_<model>.dat``, their ``per_cluster/`` result files and their phonon
DOS; phonon force caches are discarded by :func:`phonons` once the structure
has changed. Both :func:`run_ml_relaxation` and ``ml_relaxation_parallel.py``
then relax them again, e.g. with more ``steps``.
``cluster_ids=None`` resets the non-converged clusters: those flagged in the
clusters file and those whose ``per_cluster/`` result is not converged, also
when it has not been collected yet. ``model`` is detected from the result
file names when ``None``. The reset clusters are written to
``<clusters_folder>/rerun_clusters.txt`` in the ``<S folder>, <cluster id>``
format of ``missing_clusters.txt``, ready to be queued; ``clusters_folder``
defaults to the parent of ``run_folder``. Returns the reset cluster IDs.
"""
run_folder = Path(run_folder)
clusters_folder = Path(clusters_folder) if clusters_folder is not None else run_folder.parent
per_cluster_dir = run_folder / "per_cluster"
if model is None:
safe_model = _detect_ml_model(sorted(per_cluster_dir.glob("*_ml_result.dat")))
else:
safe_model = _ml_model_display_name(model)
clusters_path = run_folder / (ml_clusters_filename or f"clusters_{safe_model}.dat")
volume_path = run_folder / (ml_volume_filename or f"volume_{safe_model}.dat")
result_file = lambda cid: per_cluster_dir / f"{cid}_{safe_model}_ml_result.dat"
if cluster_ids is None:
targets = set(_read_non_converged_legacy_ids(clusters_path))
for rf in per_cluster_dir.glob(f"*_{safe_model}_ml_result.dat"):
row = _read_ml_result_file(rf)
if row is not None and not row[12]:
targets.add(row[0])
else:
targets = set(cluster_ids)
# numeric order of S, d, i, w, as in the other cluster lists
targets = sorted(targets, key=lambda cid: [int(n) for n in re.findall(r"\d+", cid)])
_remove_rows(clusters_path, set(targets))
_remove_rows(volume_path, set(targets))
_update_convergence_warning(clusters_path, volume_path)
for cid in targets:
result_file(cid).unlink(missing_ok=True)
(run_folder / "phonons" / f"{cid}.dos").unlink(missing_ok=True)
rerun_path = clusters_folder / "rerun_clusters.txt"
if targets:
with open(rerun_path, "w") as f:
for cid in targets:
m = re.match(r"(S\d+)", cid)
f.write(f"{m.group(1) if m else cid}, {cid}\n")
print(f"Reset {len(targets)} clusters; queue them from {rerun_path}")
else:
# nothing to rerun: an old list would requeue clusters that are done
rerun_path.unlink(missing_ok=True)
print("No clusters to reset.")
return targets
rerun_nonconverged_ml ¶
rerun_nonconverged_ml(
clusters_folder: str | Path,
ML_model: MLModel,
*,
ML_model_name: str | None = None,
out_folder_name: str | None = None,
steps: int = 20000,
device: str = "cpu",
optimizer_kwargs: dict | None = None,
start_from_relaxed: bool = True
) -> list[str]
Relax the non-converged clusters of an existing run folder again.
The clusters are reset with :func:reset_ml_clusters and relaxed with
:func:run_ml_relaxation, using the settings recorded in the run folder; only
steps, device and start_from_relaxed are taken from the arguments.
ML_model and ML_model_name must be those of the original run (checked
against the recorded settings). By default the relaxation continues from the
last structure in cif_relaxed/. device is not recorded and defaults to
"cpu": pass it again for a GPU run. optimizer_kwargs is only needed when
the original values were not plain JSON and could not be recorded.
Returns the IDs of the clusters that were relaxed again.
Source code in src/egqca/ml.py
def rerun_nonconverged_ml(
clusters_folder: str | Path,
ML_model: MLModel,
*,
ML_model_name: str | None = None,
out_folder_name: str | None = None,
steps: int = 20000,
device: str = "cpu",
optimizer_kwargs: dict | None = None,
start_from_relaxed: bool = True,
) -> list[str]:
"""Relax the non-converged clusters of an existing run folder again.
The clusters are reset with :func:`reset_ml_clusters` and relaxed with
:func:`run_ml_relaxation`, using the settings recorded in the run folder; only
``steps``, ``device`` and ``start_from_relaxed`` are taken from the arguments.
``ML_model`` and ``ML_model_name`` must be those of the original run (checked
against the recorded settings). By default the relaxation continues from the
last structure in ``cif_relaxed/``. ``device`` is not recorded and defaults to
``"cpu"``: pass it again for a GPU run. ``optimizer_kwargs`` is only needed when
the original values were not plain JSON and could not be recorded.
Returns the IDs of the clusters that were relaxed again.
"""
clusters_folder = Path(clusters_folder)
model_name = _ml_model_name(ML_model, ML_model_name)
run_folder = clusters_folder / (out_folder_name or _ml_model_display_name(model_name))
settings, phonon_settings = _load_run_settings(run_folder)
if optimizer_kwargs is None:
if settings.get("optimizer_kwargs_not_json"):
raise ValueError(
f"The optimizer_kwargs {settings['optimizer_kwargs_not_json']} of {run_folder} were "
"not plain JSON values and are only recorded as text. Pass them as optimizer_kwargs."
)
optimizer_kwargs = settings["optimizer_kwargs"]
# n as the run used it: its clusters file records it in the header (needed for a
# tree without DFT/clusters.dat, where the run was started with permutable_sites)
run_clusters_file = run_folder / f"clusters_{_ml_model_display_name(model_name)}.dat"
permutable_sites = _header_permutable_sites(run_clusters_file) if run_clusters_file.exists() else None
nonconverged = reset_ml_clusters(run_folder, model_name, clusters_folder=clusters_folder)
if not nonconverged:
return []
run_ml_relaxation(
clusters_folder,
permutable_sites=permutable_sites,
ML_model=ML_model,
ML_model_name=ML_model_name,
out_folder_name=run_folder.name,
steps=steps,
device=device,
start_from_relaxed=start_from_relaxed,
pressure_GPa=settings["pressure_GPa"],
relaxation_constraint=settings["relaxation_constraint"],
# an all-free mask is recorded for None; None avoids the constraint-and-mask warning
CellFilter_mask=None if all(settings["CellFilter_mask"]) else settings["CellFilter_mask"],
bravais_supercell=settings["bravais_supercell"],
fix_bravais_positions=settings["fix_bravais_positions"],
bravais_tol=settings.get("bravais_tol", DEFAULT_BRAVAIS_TOL),
fmax=settings["fmax"],
optimizer=_parse_optimizer(settings["optimizer"]),
optimizer_kwargs=optimizer_kwargs,
calc_phonons=phonon_settings is not None,
N_phonon_supercell=phonon_settings["phonon_supercell"] if phonon_settings else 2,
save_relaxed_structure=True,
)
return nonconverged
geometry_relaxation ¶
geometry_relaxation(
atoms: Atoms,
ML_model: str,
pressure_GPa: float | None = None,
relaxation_constraint: bool | str | None = DEFAULT_RELAXATION_CONSTRAINT,
CellFilter_mask: list[bool] | None = None,
bravais_supercell: list[int] | tuple[int, int, int] = (1, 1, 1),
fix_bravais_positions: bool = False,
bravais_tol: float = DEFAULT_BRAVAIS_TOL,
steps: int = 5000,
device: str = "cpu",
fmax: float = 0.0001,
optimizer: Any = FIRE,
optimizer_kwargs: dict | None = None,
save_cif: Path | str | None = None,
ML_model_name: str | None = None,
) -> Atoms
Run geometry relaxation with an ML potential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
atoms
|
Atoms
|
Input structure. |
required |
ML_model
|
str, ASE calculator, or callable
|
ML potential: a model string (e.g. |
required |
pressure_GPa
|
float
|
External scalar pressure in GPa added to the stress. |
None
|
relaxation_constraint
|
bool, str, or None
|
Controls the space-group / Bravais-lattice ASE constraint applied
during relaxation.
Strings are case-insensitive (
|
DEFAULT_RELAXATION_CONSTRAINT
|
CellFilter_mask
|
list[bool] or None
|
Strain mask of six bools passed to .. note::
These are not the cell parameters .. warning::
Setting both |
None
|
fix_bravais_positions
|
bool
|
Only used when |
False
|
bravais_tol
|
float
|
Relative tolerance of the Bravais lattice detection used by the
FixBravaisCell constraint (default 0.01, i.e. about 1 % in cell lengths
and angles). A start cell within this tolerance of a higher-symmetry
lattice is projected onto that exact lattice; the detected lattice is
also the one reported as initial and target lattice. Only used when
|
DEFAULT_BRAVAIS_TOL
|
steps
|
int
|
Maximum number of optimizer steps. |
5000
|
device
|
str
|
Calculator device ( |
'cpu'
|
fmax
|
float
|
Force convergence threshold in eV/Å. |
0.0001
|
optimizer
|
optimizer class
|
ASE optimizer class (default: FIRE). |
FIRE
|
optimizer_kwargs
|
dict
|
Extra keyword arguments forwarded to the optimizer constructor. |
None
|
ML_model_name
|
str
|
Name of a user-supplied calculator, only used in the printed output. |
None
|
Source code in src/egqca/ml.py
def geometry_relaxation(
atoms: Atoms,
ML_model: str,
pressure_GPa: float | None = None,
relaxation_constraint: bool | str | None = DEFAULT_RELAXATION_CONSTRAINT,
CellFilter_mask: list[bool] | None = None,
bravais_supercell: list[int] | tuple[int, int, int] = (1, 1, 1),
fix_bravais_positions: bool = False,
bravais_tol: float = DEFAULT_BRAVAIS_TOL,
steps: int = 5000,
device: str = "cpu",
fmax: float = 1e-4,
optimizer: Any = FIRE,
optimizer_kwargs: dict | None = None,
save_cif: Path | str | None = None,
ML_model_name: str | None = None,
) -> Atoms:
"""Run geometry relaxation with an ML potential.
Parameters
----------
atoms : Atoms
Input structure.
ML_model : str, ASE calculator, or callable
ML potential: a model string (e.g. ``"mattersim-5m"``), an ASE
calculator, or a function returning one (see :func:`run_ml_relaxation`).
pressure_GPa : float, optional
External scalar pressure in GPa added to the stress.
relaxation_constraint : bool, str, or None, optional
Controls the space-group / Bravais-lattice ASE constraint applied
during relaxation.
Strings are case-insensitive (``"fcc"`` is ``"FCC"``); ``"auto"`` and
``"none"`` are accepted for ``True`` and ``None``, as on the command line.
- ``None`` — no ASE constraint; cell degrees of freedom are
controlled solely by ``CellFilter_mask``.
- ``"FixSymmetry"`` (default) — ASE FixSymmetry constraint that
preserves the space group of each cluster throughout the relaxation.
- ``True`` — FixBravaisCell constraint with the Bravais type
auto-detected from ``atoms``' own cell (within ``bravais_tol``)
rather than specified explicitly. Note
this only looks at the cell geometry, not the atomic decoration:
for a set of clusters generated from one template (e.g. EGQCA's
own substitutional-alloy workflow, where every cluster shares the
template's pre-relaxation cell shape by construction), this
detects the *same* Bravais type for every cluster -- including
intermediate compositions whose true space group is lower once
the atomic decoration breaks the end-members' symmetry. Use this
when constraining every cluster to a common cell shape is the
intended behaviour (e.g. so their excess energies are comparable
on a consistent cell family); use an explicit Bravais key/crystal
system (below) or ``"FixSymmetry"`` when it isn't.
- ``str`` (Bravais lattice key or crystal system name, e.g.
``"RHL"``, ``"rhombohedral"``) — FixBravaisCell constraint that
keeps the cell metric consistent with the specified Bravais type.
Accepted keys: ``_BRAVAIS_LATTICE_SYSTEMS``; accepted crystal
system names: ``_CRYSTAL_SYSTEMS``.
Supercell inputs are handled automatically via ``bravais_supercell``.
CellFilter_mask : list[bool] or None, optional
Strain mask of six bools passed to ``FrechetCellFilter``, in ASE's Voigt
order of the Cartesian strain components ``[xx, yy, zz, yz, xz, xy]``.
``True`` = component free to relax, ``False`` = fixed. ``None``
(default) leaves all six components free.
.. note::
These are not the cell parameters ``[a, b, c, alpha, beta, gamma]``.
The two only coincide for an orthogonal cell aligned with the
Cartesian axes; for a hexagonal, monoclinic or triclinic cell, e.g.,
fixing ``yz, xz, xy`` does not keep the cell angles. To keep a cell
shape, use ``relaxation_constraint`` instead.
.. warning::
Setting both ``relaxation_constraint`` and ``CellFilter_mask``
applies an ASE constraint (FixSymmetry / FixBravaisCell) *and* a
FrechetCellFilter mask simultaneously, which may cause unexpected
behaviour.
fix_bravais_positions : bool, optional
Only used when ``relaxation_constraint`` is ``True``, a Bravais key or a
crystal system string. If ``True`` the atomic positions are frozen at
their starting fractional coordinates (forces are zeroed), so only the
cell relaxes: no internal relaxation at all, not a projection onto the
symmetry-allowed positions. Atoms of a decorated cluster generally have
positional freedom, so this neglects their local relaxation. ``False``
(default) constrains only the cell metric / stress and leaves the
internal coordinates free to relax.
bravais_tol : float, optional
Relative tolerance of the Bravais lattice detection used by the
FixBravaisCell constraint (default 0.01, i.e. about 1 % in cell lengths
and angles). A start cell within this tolerance of a higher-symmetry
lattice is projected onto that exact lattice; the detected lattice is
also the one reported as initial and target lattice. Only used when
``relaxation_constraint`` is ``True``, a Bravais key or a crystal system.
steps : int
Maximum number of optimizer steps.
device : str
Calculator device (``"cpu"`` or ``"cuda"``). Only used for model
strings; a user-supplied calculator runs where it was set up.
fmax : float
Force convergence threshold in eV/Å.
optimizer : optimizer class
ASE optimizer class (default: FIRE).
optimizer_kwargs : dict, optional
Extra keyword arguments forwarded to the optimizer constructor.
ML_model_name : str, optional
Name of a user-supplied calculator, only used in the printed output.
"""
# Suppress warnings about matrix logarithm accuracy issued by scipy during geometry
# optimization to avoid cluttering the output
warnings.filterwarnings(
"ignore",
category=RuntimeWarning,
message="logm result may be inaccurate, approximate err",
)
# We suggest using double precison (``dtype="float64"``) for geometry optimization, as
# it allows smaller values of the ``fmax`` convergence threshold and more reliable
# symmetry detection.
# case-insensitive, as on the command line ("fcc" -> "FCC")
relaxation_constraint = _normalize_relaxation_constraint(relaxation_constraint)
calc = _ml_calculator(ML_model, device=device)
# Starting message
bravais_constraint = None
if relaxation_constraint is not None and relaxation_constraint != "FixSymmetry":
bravais_constraint = _bravais_cell_constraint(
relaxation_constraint, atoms, supercell=bravais_supercell,
fix_positions=fix_bravais_positions, bravais_tol=bravais_tol,
)
# the lattice the constraint was built from
initial_bravais_lattice = bravais_constraint.bravais_lattice
else:
initial_bravais_lattice = _bravais_lattice_name(atoms, supercell=bravais_supercell)
print(f"\n{'='*62}")
print(f" ML model : {_ml_model_description(ML_model, ML_model_name)}")
print(f" steps / fmax : {steps} / {fmax} eV/Å")
print(f" Initial lattice: {_bravais_full_name(initial_bravais_lattice)} ({initial_bravais_lattice})")
_print_cell(" "*18, atoms, supercell=bravais_supercell)
if relaxation_constraint is None:
print(f" Constraint : none")
elif relaxation_constraint == "FixSymmetry":
atoms.set_constraint(FixSymmetry(atoms))
print(f" Constraint : FixSymmetry")
report_symmetry(atoms, " Space group :")
else:
atoms.info["egqca_ml_initial_bravais_lattice"] = initial_bravais_lattice
atoms.set_constraint(bravais_constraint)
sc_str = "x".join(str(n) for n in bravais_supercell)
pos_str = "cell+positions" if fix_bravais_positions else "cell only"
if relaxation_constraint is True:
print(
f" Target lattice : "
f"{_bravais_full_name(initial_bravais_lattice)} ({initial_bravais_lattice})"
)
else:
print(f" Target lattice : {_bravais_full_name(relaxation_constraint)} ({relaxation_constraint})")
print(f" Supercell : {sc_str} [{pos_str}]")
print(f" Bravais tol : {bravais_tol:g} (relative)")
if CellFilter_mask is not None:
CellFilter_mask = _validate_cell_mask(CellFilter_mask)
print(f" Cell mask : {CellFilter_mask}")
if relaxation_constraint is not None and CellFilter_mask is not None:
warnings.warn(
"Both relaxation_constraint and CellFilter_mask are set. "
"Using an ASE constraint (FixSymmetry/FixBravaisCell) together with a "
"FrechetCellFilter mask may cause unexpected behavior.",
UserWarning,
stacklevel=2,
)
cell_mask = CellFilter_mask if CellFilter_mask is not None else [True] * 6
print(f"{'='*62}")
print()
atoms.calc = calc
# ----------------------- optimization ----------------------- #
cell_filter_kwargs = {}
cell_filter_kwargs["mask"] = cell_mask
if pressure_GPa is not None:
cell_filter_kwargs["scalar_pressure"] = pressure_GPa * units.GPa
optimizer_kwargs = {} if optimizer_kwargs is None else dict(optimizer_kwargs)
cell_filter = FrechetCellFilter(atoms, **cell_filter_kwargs)
opt_al = optimizer(
cell_filter,
**optimizer_kwargs,
)
converged = opt_al.run(fmax=fmax, steps=steps)
atoms.info["egqca_ml_converged"] = converged
final_forces = np.asarray(cell_filter.get_forces())
atoms.info["egqca_ml_final_fmax"] = float(
np.sqrt((final_forces**2).sum(axis=1)).max()
)
# ------------------------ print results ----------------------- #
if not converged:
print("Warning: Geometry optimization did not converge within the maximum number of steps.")
# Lattice geometry
print()
print(f"{'='*13}"+" After relaxation "+f"{'='*13}")
report_symmetry(atoms, " Space group: ")
final_bravais_lattice = _bravais_lattice_name(atoms, supercell=bravais_supercell)
atoms.info["egqca_ml_final_bravais_lattice"] = final_bravais_lattice
print(f" Bravais lattice: {_bravais_full_name(final_bravais_lattice)} ({final_bravais_lattice})")
_print_cell(" "*18, atoms, supercell=bravais_supercell)
# Additional information if fix bravais constraint
if relaxation_constraint is True or (
isinstance(relaxation_constraint, str) and relaxation_constraint != "FixSymmetry"
):
# initial_bravais_lattice is already a resolved Bravais key (from
# atoms.cell.get_bravais_lattice()), so the auto-detect case always
# takes this branch rather than the crystal-system-name one below.
key = initial_bravais_lattice if relaxation_constraint is True else str(relaxation_constraint).upper()
requested_label = "auto-detected" if relaxation_constraint is True else "requested"
if key in _BRAVAIS_LATTICE_SYSTEMS:
# Accept any Bravais type in the same crystal system.
# Cell.get_bravais_lattice() uses geometry only, so conventional cells
# (e.g. BCC or FCC conventional) are reported as CUB; a strict equality
# check would therefore always fail for conventional-cell inputs.
target_systems = _BRAVAIS_LATTICE_SYSTEMS[key]
final_systems = _BRAVAIS_LATTICE_SYSTEMS.get(final_bravais_lattice, set())
if not target_systems & final_systems:
_bravais_mismatch_warning = (
f"WARNING: Final Bravais lattice {final_bravais_lattice!r} (crystal system "
f"{sorted(final_systems)}) is not compatible with the {requested_label} "
f"Bravais type {key!r} (crystal system {sorted(target_systems)})."
)
print(_bravais_mismatch_warning)
atoms.info["egqca_ml_bravais_mismatch"] = _bravais_mismatch_warning
else:
crystal_system = str(relaxation_constraint).lower()
valid = {bl for bl, systems in _BRAVAIS_LATTICE_SYSTEMS.items()
if crystal_system in systems}
if final_bravais_lattice not in valid:
_bravais_mismatch_warning = (
f"WARNING: Final Bravais lattice {final_bravais_lattice!r} is not compatible "
f"with the requested crystal system {crystal_system!r}. "
f"Expected one of: {sorted(valid)}."
)
print(_bravais_mismatch_warning)
atoms.info["egqca_ml_bravais_mismatch"] = _bravais_mismatch_warning
if save_cif is not None:
save_cif = Path(save_cif)
save_cif.parent.mkdir(parents=True, exist_ok=True)
with _atomic_write(save_cif, "wb") as f:
write(f, atoms, format="cif")
return atoms
phonons ¶
phonons(
atoms: Atoms,
ML_model: MLModel = "mattersim-5m",
N: int | list[int] = 2,
device: str = "cpu",
delta: float = 0.01,
kpts: tuple[int, int, int] = (20, 20, 20),
npts: int = 500,
width: float = 0.0001,
cache_dir: Path | str | None = None,
ML_model_name: str | None = None,
) -> Any
Run a phonon calculation with ASE's finite-displacement Phonons class,
using the given ML model as calculator.
The DOS is sampled on the kpts q-point grid with npts points and
width smearing, and is written by :func:run_ml_relaxation as
<run_folder>/phonons/<cluster_id>.dos with the mode energy hbar*omega
in eV in the first column. It integrates to 3 modes per atom, including
any imaginary (negative-energy) modes of a dynamically unstable cluster;
those are reported by the stability summary at the end of the run and are
excluded again when :func:egqca.io.read_phonons reads the file back.
param atoms: ASE Atoms object with the relaxed geometry
param ML_model: ML model to use for the phonon calculation: a model string,
an ASE calculator, or a function returning one (see
:func:run_ml_relaxation)
param N: supercell size for the phonon calculation. Either a single int
(interpreted as an N x N x N supercell) or a list of three ints
[N1, N2, N3] for an N1 x N2 x N3 supercell.
param device: device to use for the calculation
param delta: finite-displacement amplitude in Angstrom
param kpts: Monkhorst-Pack grid the phonon frequencies are sampled on
param npts: number of energy points of the sampled DOS
param width: Gaussian smearing width in eV of the sampled DOS
param cache_dir: folder to keep the finite-displacement forces and their
metadata in, so that the DOS can be re-sampled later by
:func:phonon_dos_from_cache without repeating the force
evaluations. An existing cache of the same structure, supercell,
displacement and model is reused: ASE skips the displacements it
already finds there, which also makes an interrupted run
restartable. A rigidly rotated copy of the structure, e.g. the
relaxed structure read back from its CIF, counts as the same; the
calculation then continues with the cached structure, in the frame
the cached forces belong to. A cache of anything else is discarded.
None (default) uses a temporary folder that is deleted again.
param ML_model_name: name of a user-supplied calculator, recorded in the
phonon cache metadata
return: ASE DOS object with the phonon density of states
Source code in src/egqca/ml.py
def phonons(
atoms: Atoms,
ML_model: MLModel = "mattersim-5m",
N: int | list[int] = 2,
device: str = "cpu",
delta: float = 0.01,
kpts: tuple[int, int, int] = (20, 20, 20),
npts: int = 500,
width: float = 1e-4,
cache_dir: Path | str | None = None,
ML_model_name: str | None = None,
) -> Any:
''' Run a phonon calculation with ASE's finite-displacement ``Phonons`` class,
using the given ML model as calculator.
The DOS is sampled on the ``kpts`` q-point grid with ``npts`` points and
``width`` smearing, and is written by :func:`run_ml_relaxation` as
``<run_folder>/phonons/<cluster_id>.dos`` with the mode energy hbar*omega
in eV in the first column. It integrates to 3 modes per atom, including
any imaginary (negative-energy) modes of a dynamically unstable cluster;
those are reported by the stability summary at the end of the run and are
excluded again when :func:`egqca.io.read_phonons` reads the file back.
param atoms: ASE Atoms object with the relaxed geometry
param ML_model: ML model to use for the phonon calculation: a model string,
an ASE calculator, or a function returning one (see
:func:`run_ml_relaxation`)
param N: supercell size for the phonon calculation. Either a single int
(interpreted as an N x N x N supercell) or a list of three ints
[N1, N2, N3] for an N1 x N2 x N3 supercell.
param device: device to use for the calculation
param delta: finite-displacement amplitude in Angstrom
param kpts: Monkhorst-Pack grid the phonon frequencies are sampled on
param npts: number of energy points of the sampled DOS
param width: Gaussian smearing width in eV of the sampled DOS
param cache_dir: folder to keep the finite-displacement forces and their
metadata in, so that the DOS can be re-sampled later by
:func:`phonon_dos_from_cache` without repeating the force
evaluations. An existing cache of the same structure, supercell,
displacement and model is reused: ASE skips the displacements it
already finds there, which also makes an interrupted run
restartable. A rigidly rotated copy of the structure, e.g. the
relaxed structure read back from its CIF, counts as the same; the
calculation then continues with the cached structure, in the frame
the cached forces belong to. A cache of anything else is discarded.
``None`` (default) uses a temporary folder that is deleted again.
param ML_model_name: name of a user-supplied calculator, recorded in the
phonon cache metadata
return: ASE DOS object with the phonon density of states
'''
supercell = _phonon_supercell(N)
# Suppress warnings about matrix logarithm accuracy issued by scipy during geometry
# optimization to avoid cluttering the output
warnings.filterwarnings(
"ignore",
category=RuntimeWarning,
message="logm result may be inaccurate, approximate err",
)
calc = _ml_calculator(ML_model, device=device)
atoms.calc = calc
# Remove constraints before phonon calculation (incompatible with supercell creation)
atoms.set_constraint()
with contextlib.ExitStack() as stack:
if cache_dir is None:
# Temporary directory, discarded together with the forces
tmpdir = stack.enter_context(tempfile.TemporaryDirectory())
force_dir = os.path.join(tmpdir, 'phonons')
else:
cache_dir = Path(cache_dir)
cache_dir.mkdir(parents=True, exist_ok=True)
force_dir = str(cache_dir / PHONON_FORCE_CACHE_NAME)
model_description = _ml_model_description(ML_model, ML_model_name)
# ASE reuses every force it finds in the cache, so forces of another
# structure (e.g. before a re-relaxation), supercell or model must go
if Path(force_dir).exists():
if _phonon_cache_matches(cache_dir, atoms, supercell, delta, model_description):
# the cached forces are Cartesian in the frame of the cached
# structure, which may be rotated against atoms: continue with it
atoms = read(cache_dir / PHONON_EQUILIBRIUM_NAME, format="extxyz")
atoms.calc = calc
else:
print(f"Discarding the phonon force cache {force_dir}: it belongs to another "
"structure, supercell, displacement or model.")
shutil.rmtree(force_dir)
# written before the forces, so that an interrupted run can be checked as well
_write_phonon_cache_metadata(
cache_dir, atoms, supercell, delta, model_description, kpts, npts, width,
)
# Phonon calculator
ph = Phonons(atoms, calc, supercell=supercell, delta=delta, name=force_dir)
# a job killed during a force evaluation leaves an empty entry, which
# run() would take as done
ph.cache.strip_empties()
ph.run()
# Read forces and assemble the dynamical matrix
ph.read(**PHONON_READ_DEFAULTS)
t_dos0 = time.monotonic()
dos = _sampled_phonon_dos(ph, len(atoms), kpts, npts, width)
print(f"DOS runtime: {time.monotonic() - t_dos0:.2f} s")
if cache_dir is None:
ph.clean()
return dos
phonon_dos_from_cache ¶
phonon_dos_from_cache(
cache_dir: Path | str,
kpts: tuple[int, int, int] | None = None,
npts: int | None = None,
width: float | None = None,
method: str | None = None,
symmetrize: int | None = None,
acoustic: bool | None = None,
cutoff: float | None = None,
save_dos: Path | str | None = None,
) -> Any
Re-sample a phonon DOS from a saved force cache, without any ML calls.
cache_dir is a folder written by :func:phonons (as
<run_folder>/phonons/<cluster_id>_cache when it comes from
:func:run_ml_relaxation) holding the finite-displacement forces, the
equilibrium structure and phonon_info.json. Every parameter left as
None falls back to the value recorded there, so
phonon_dos_from_cache(cache_dir, npts=2000, width=5e-4)
reproduces the original DOS at a finer sampling. kpts repeats the
Fourier interpolation and the diagonalizations, the read parameters
(method, symmetrize, acoustic, cutoff) re-derive the force
constants from the stored forces — neither re-runs the ML model.
param cache_dir: folder holding the phonon force cache
param save_dos: optional path to write the DOS to, in the two-column
Energy(eV) DOS format read by :func:egqca.io.read_phonons
return: ASE DOS object with the phonon density of states
Source code in src/egqca/ml.py
def phonon_dos_from_cache(
cache_dir: Path | str,
kpts: tuple[int, int, int] | None = None,
npts: int | None = None,
width: float | None = None,
method: str | None = None,
symmetrize: int | None = None,
acoustic: bool | None = None,
cutoff: float | None = None,
save_dos: Path | str | None = None,
) -> Any:
"""Re-sample a phonon DOS from a saved force cache, without any ML calls.
``cache_dir`` is a folder written by :func:`phonons` (as
``<run_folder>/phonons/<cluster_id>_cache`` when it comes from
:func:`run_ml_relaxation`) holding the finite-displacement forces, the
equilibrium structure and ``phonon_info.json``. Every parameter left as
``None`` falls back to the value recorded there, so
phonon_dos_from_cache(cache_dir, npts=2000, width=5e-4)
reproduces the original DOS at a finer sampling. ``kpts`` repeats the
Fourier interpolation and the diagonalizations, the ``read`` parameters
(``method``, ``symmetrize``, ``acoustic``, ``cutoff``) re-derive the force
constants from the stored forces — neither re-runs the ML model.
param cache_dir: folder holding the phonon force cache
param save_dos: optional path to write the DOS to, in the two-column
``Energy(eV) DOS`` format read by :func:`egqca.io.read_phonons`
return: ASE DOS object with the phonon density of states
"""
cache_dir = Path(cache_dir)
info_path = cache_dir / PHONON_INFO_NAME
if not info_path.is_file():
raise FileNotFoundError(f"No {PHONON_INFO_NAME} in {cache_dir}")
with open(info_path) as f:
info = json.load(f)
atoms = read(cache_dir / info.get("equilibrium", PHONON_EQUILIBRIUM_NAME))
force_dir = cache_dir / info.get("force_cache", PHONON_FORCE_CACHE_NAME)
if not force_dir.is_dir():
raise FileNotFoundError(f"No force cache in {force_dir}")
read_kwargs = {**PHONON_READ_DEFAULTS, **info.get("read", {})}
for key, value in (
("method", method),
("symmetrize", symmetrize),
("acoustic", acoustic),
("cutoff", cutoff),
):
if value is not None:
read_kwargs[key] = value
dos_info = info.get("dos", {})
kpts = tuple(kpts if kpts is not None else dos_info.get("kpts", (20, 20, 20)))
npts = npts if npts is not None else dos_info.get("npts", 500)
width = width if width is not None else dos_info.get("width", 1e-4)
# calc=None: the forces come from the cache, the ML model is never loaded.
ph = Phonons(
atoms,
calc=None,
supercell=_phonon_supercell(info["supercell"]),
delta=info["delta"],
name=str(force_dir),
)
ph.read(**read_kwargs)
dos = _sampled_phonon_dos(ph, len(atoms), kpts, npts, width)
if save_dos is not None:
save_dos = Path(save_dos)
save_dos.parent.mkdir(parents=True, exist_ok=True)
with _atomic_write(save_dos) as f:
np.savetxt(
f,
np.column_stack((dos.get_energies(), dos.get_weights())),
fmt="%.6e",
header="Energy(eV) DOS",
)
return dos