File size: 8,499 Bytes
cb907ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
"""
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())