Agentic_Global_optimization / enumerate_disorder.py
Mahpe's picture
Upload enumerate_disorder.py
cb907ab verified
Raw History Blame Contribute Delete
8.5 kB
"""
Enumerate all decorations of disordered sites on a supercell, then keep
symmetry-inequivalent structures.
Reads cif_path / supercell / swap species from config.toml (same keys as the
other Agenticoptimizer scripts).
Two-step flow
-------------
1. Generate every assignment of swap species that matches the CIF /
``[swap_params]`` occupancy ratio.
2. Drop symmetry equivalents with ASE ``SymmetryEquivalenceCheck``.
"""
from __future__ import annotations
import argparse
import itertools
import sys
from math import comb
from pathlib import Path
from ase.db import connect
from ase.utils.structure_comparator import SymmetryEquivalenceCheck
from tqdm import tqdm
from utils import (
DEFAULT_CONFIG,
identify_disorder_sublattices,
load_config,
normalize_supercell_size,
ordered_ase_from_supercell,
parse_cif_structure,
resolve_counts,
resolve_optimization_input,
species_and_ratio_from_signature,
)
MAX_ENUM = 200_000 # refuse enumerations larger than this
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
description="Generate ratio-matching supercell decorations, then drop ASE symmetry equivalents."
)
p.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="Path to config.toml")
p.add_argument(
"--out-dir",
type=Path,
default=None,
help="Directory for the unique-structure ASE database (default: cwd).",
)
return p
def load_enumeration_input(cfg: dict):
"""Build an ordered supercell and the list of sites that will be decorated."""
prep = cfg.get("prep_params", {})
swap = cfg.get("swap_params", {})
relax = cfg.get("relax_params", {})
# If supercell_size is omitted, reuse the auto-prepared size from the CIF occupancy.
if not prep.get("supercell_size"):
opt_in = resolve_optimization_input(cfg)
prep["supercell_size"] = opt_in.manifest.get("supercell_size")
cfg["prep_params"] = prep
structure = parse_cif_structure(
cfg["cif_path"],
occupancy_tolerance=float(prep.get("occupancy_tolerance", 2.0)),
)
sublattices = identify_disorder_sublattices(structure)
if not sublattices:
raise SystemExit(f"No disordered sites found in {cfg['cif_path']}")
# One disorder group is enumerated; others are frozen at their majority species.
active = sublattices[int(prep.get("sublattice_index", 0))]
species, ratio = species_and_ratio_from_signature(active["signature"])
if swap.get("atom_swaps"):
species = [str(s) for s in swap["atom_swaps"]]
if swap.get("ratio"):
ratio = [float(x) for x in swap["ratio"]]
supercell_size = normalize_supercell_size(
prep.get("supercell_size", cfg.get("supercell_size", (1, 1, 1)))
)
unitcell = ordered_ase_from_supercell(
structure,
swap_indices=active["site_indices"],
other_disordered_signatures={
sub["signature"] for sub in sublattices if sub["signature"] != active["signature"]
},
placeholder=species[0],
)
supercell = unitcell * supercell_size
n_unit = len(unitcell)
n_images = int(supercell_size[0] * supercell_size[1] * supercell_size[2])
# ASE repeats the unit cell as [cell0, cell1, ...]; keep only the active sublattice.
swap_indices = [
index + image * n_unit
for image in range(n_images)
for index in active["site_indices"]
]
# Template cell: fill every swap site with the first species; decorations overwrite this.
for index in swap_indices:
supercell.symbols[index] = species[0]
return {
"cif_path": cfg["cif_path"],
"label": active["label"],
"species": species,
"ratio": [float(x) for x in ratio],
"supercell_size": supercell_size,
"supercell": supercell,
"swap_indices": swap_indices,
"symprec": float(relax.get("symprec", 1e-3)),
}
def generate_configurations(species: list[str], n_sites: int, counts: dict[str, int]):
"""All occupancy tuples with the integer site counts implied by the ratio."""
n_enum = 1
n_left = n_sites
for symbol in species[:-1]:
n_enum *= comb(n_left, counts[symbol])
n_left -= counts[symbol]
if n_enum > MAX_ENUM:
raise SystemExit(
f"Too many configurations ({n_enum} for counts {counts}). "
"Reduce [prep_params].supercell_size in config.toml."
)
occupancies: list[tuple[str, ...]] = []
def _place(remaining: list[int], species_idx: int, current: list[str | None]) -> None:
if species_idx == len(species) - 1:
occ = list(current)
for index in remaining:
occ[index] = species[species_idx]
occupancies.append(tuple(occ))
return
symbol = species[species_idx]
for chosen in itertools.combinations(remaining, counts[symbol]):
chosen_set = set(chosen)
nxt = list(current)
for index in chosen:
nxt[index] = symbol
rest = [index for index in remaining if index not in chosen_set]
_place(rest, species_idx + 1, nxt)
_place(list(range(n_sites)), 0, [None] * n_sites)
return occupancies, len(occupancies)
def occupancy_to_atoms(parent, swap_indices: list[int], occ: tuple[str, ...]):
"""Copy the parent supercell and paint swap sites with one occupancy tuple."""
atoms = parent.copy()
for index, symbol in zip(swap_indices, occ):
atoms.symbols[index] = symbol
return atoms
##### ASE symmetry filter #####
def unique_by_ase(atoms_list, stol: float):
"""Keep structures that ASE ``SymmetryEquivalenceCheck`` does not match to a kept one."""
comp = SymmetryEquivalenceCheck(stol=stol)
not_sym_atoms = []
for atoms_0 in tqdm(atoms_list, desc="ASE symmetry check"):
# First structure is always kept.
if len(not_sym_atoms) == 0:
not_sym_atoms.append(atoms_0)
continue
# True if atoms_0 is equivalent to any already-kept structure.
c1 = comp.compare(atoms_0, not_sym_atoms)
if c1:
continue
# compare(a, b) can disagree with compare(b, a), so check both ways
c2 = [comp.compare(a, atoms_0) for a in not_sym_atoms]
if any(c2):
continue
not_sym_atoms.append(atoms_0)
return not_sym_atoms
def run_enumerate(cfg: dict, out_dir: Path | None = None) -> Path:
##### Load CIF, supercell, and swap species #####
info = load_enumeration_input(cfg)
species = info["species"]
ratio = info["ratio"]
supercell = info["supercell"]
swap_indices = info["swap_indices"]
supercell_size = info["supercell_size"]
stol = info["symprec"]
counts = resolve_counts(len(swap_indices), species, ratio)
print(f"CIF: {info['cif_path']}")
print(f"Disorder sublattice: {info['label']} swaps={species}")
print(f"Supercell size: {supercell_size}")
print(f"Number of swap sites: {len(swap_indices)}")
print(f"Ratio: {ratio} counts: {counts}")
##### 1. Generate ratio-matching configurations #####
print("----- Generate all configurations -----")
occupancies, n_enum = generate_configurations(species, len(swap_indices), counts)
print(f"Number of configurations: {n_enum}")
##### 2. Drop ASE symmetry equivalents #####
print("-------- Symmetry check --------")
atoms_list = [occupancy_to_atoms(supercell, swap_indices, occ) for occ in occupancies]
not_sym_atoms_tot = unique_by_ase(atoms_list, stol)
print(f"Total number of symmetrical inequivalent structures: {len(not_sym_atoms_tot)}")
##### Write unique structures #####
db_name = f"{supercell.get_chemical_formula()}_{supercell_size[0]}{supercell_size[1]}{supercell_size[2]}_unique.db"
db_path = (out_dir / db_name) if out_dir is not None else Path(db_name)
if out_dir is not None:
out_dir.mkdir(parents=True, exist_ok=True)
print(f"Database name: {db_path}")
db = connect(str(db_path), append=False)
for atoms in not_sym_atoms_tot:
db.write(atoms)
print(f"Wrote {len(db)} inequivalent structures")
return db_path
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
cfg = load_config(args.config)
run_enumerate(cfg, out_dir=args.out_dir)
return 0
if __name__ == "__main__":
sys.exit(main())