Mahpe commited on
Commit
cb907ab
·
verified ·
1 Parent(s): d875b14

Upload enumerate_disorder.py

Browse files
Files changed (1) hide show
  1. enumerate_disorder.py +234 -0
enumerate_disorder.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Enumerate all decorations of disordered sites on a supercell, then keep
3
+ symmetry-inequivalent structures.
4
+
5
+ Reads cif_path / supercell / swap species from config.toml (same keys as the
6
+ other Agenticoptimizer scripts).
7
+
8
+ Two-step flow
9
+ -------------
10
+ 1. Generate every assignment of swap species that matches the CIF /
11
+ ``[swap_params]`` occupancy ratio.
12
+ 2. Drop symmetry equivalents with ASE ``SymmetryEquivalenceCheck``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import itertools
19
+ import sys
20
+ from math import comb
21
+ from pathlib import Path
22
+
23
+ from ase.db import connect
24
+ from ase.utils.structure_comparator import SymmetryEquivalenceCheck
25
+ from tqdm import tqdm
26
+
27
+ from utils import (
28
+ DEFAULT_CONFIG,
29
+ identify_disorder_sublattices,
30
+ load_config,
31
+ normalize_supercell_size,
32
+ ordered_ase_from_supercell,
33
+ parse_cif_structure,
34
+ resolve_counts,
35
+ resolve_optimization_input,
36
+ species_and_ratio_from_signature,
37
+ )
38
+
39
+ MAX_ENUM = 200_000 # refuse enumerations larger than this
40
+
41
+
42
+ def build_parser() -> argparse.ArgumentParser:
43
+ p = argparse.ArgumentParser(
44
+ description="Generate ratio-matching supercell decorations, then drop ASE symmetry equivalents."
45
+ )
46
+ p.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="Path to config.toml")
47
+ p.add_argument(
48
+ "--out-dir",
49
+ type=Path,
50
+ default=None,
51
+ help="Directory for the unique-structure ASE database (default: cwd).",
52
+ )
53
+ return p
54
+
55
+
56
+ def load_enumeration_input(cfg: dict):
57
+ """Build an ordered supercell and the list of sites that will be decorated."""
58
+ prep = cfg.get("prep_params", {})
59
+ swap = cfg.get("swap_params", {})
60
+ relax = cfg.get("relax_params", {})
61
+
62
+ # If supercell_size is omitted, reuse the auto-prepared size from the CIF occupancy.
63
+ if not prep.get("supercell_size"):
64
+ opt_in = resolve_optimization_input(cfg)
65
+ prep["supercell_size"] = opt_in.manifest.get("supercell_size")
66
+ cfg["prep_params"] = prep
67
+
68
+ structure = parse_cif_structure(
69
+ cfg["cif_path"],
70
+ occupancy_tolerance=float(prep.get("occupancy_tolerance", 2.0)),
71
+ )
72
+ sublattices = identify_disorder_sublattices(structure)
73
+ if not sublattices:
74
+ raise SystemExit(f"No disordered sites found in {cfg['cif_path']}")
75
+
76
+ # One disorder group is enumerated; others are frozen at their majority species.
77
+ active = sublattices[int(prep.get("sublattice_index", 0))]
78
+ species, ratio = species_and_ratio_from_signature(active["signature"])
79
+ if swap.get("atom_swaps"):
80
+ species = [str(s) for s in swap["atom_swaps"]]
81
+ if swap.get("ratio"):
82
+ ratio = [float(x) for x in swap["ratio"]]
83
+
84
+ supercell_size = normalize_supercell_size(
85
+ prep.get("supercell_size", cfg.get("supercell_size", (1, 1, 1)))
86
+ )
87
+ unitcell = ordered_ase_from_supercell(
88
+ structure,
89
+ swap_indices=active["site_indices"],
90
+ other_disordered_signatures={
91
+ sub["signature"] for sub in sublattices if sub["signature"] != active["signature"]
92
+ },
93
+ placeholder=species[0],
94
+ )
95
+ supercell = unitcell * supercell_size
96
+ n_unit = len(unitcell)
97
+ n_images = int(supercell_size[0] * supercell_size[1] * supercell_size[2])
98
+ # ASE repeats the unit cell as [cell0, cell1, ...]; keep only the active sublattice.
99
+ swap_indices = [
100
+ index + image * n_unit
101
+ for image in range(n_images)
102
+ for index in active["site_indices"]
103
+ ]
104
+ # Template cell: fill every swap site with the first species; decorations overwrite this.
105
+ for index in swap_indices:
106
+ supercell.symbols[index] = species[0]
107
+
108
+ return {
109
+ "cif_path": cfg["cif_path"],
110
+ "label": active["label"],
111
+ "species": species,
112
+ "ratio": [float(x) for x in ratio],
113
+ "supercell_size": supercell_size,
114
+ "supercell": supercell,
115
+ "swap_indices": swap_indices,
116
+ "symprec": float(relax.get("symprec", 1e-3)),
117
+ }
118
+
119
+
120
+ def generate_configurations(species: list[str], n_sites: int, counts: dict[str, int]):
121
+ """All occupancy tuples with the integer site counts implied by the ratio."""
122
+ n_enum = 1
123
+ n_left = n_sites
124
+ for symbol in species[:-1]:
125
+ n_enum *= comb(n_left, counts[symbol])
126
+ n_left -= counts[symbol]
127
+ if n_enum > MAX_ENUM:
128
+ raise SystemExit(
129
+ f"Too many configurations ({n_enum} for counts {counts}). "
130
+ "Reduce [prep_params].supercell_size in config.toml."
131
+ )
132
+
133
+ occupancies: list[tuple[str, ...]] = []
134
+
135
+ def _place(remaining: list[int], species_idx: int, current: list[str | None]) -> None:
136
+ if species_idx == len(species) - 1:
137
+ occ = list(current)
138
+ for index in remaining:
139
+ occ[index] = species[species_idx]
140
+ occupancies.append(tuple(occ))
141
+ return
142
+ symbol = species[species_idx]
143
+ for chosen in itertools.combinations(remaining, counts[symbol]):
144
+ chosen_set = set(chosen)
145
+ nxt = list(current)
146
+ for index in chosen:
147
+ nxt[index] = symbol
148
+ rest = [index for index in remaining if index not in chosen_set]
149
+ _place(rest, species_idx + 1, nxt)
150
+
151
+ _place(list(range(n_sites)), 0, [None] * n_sites)
152
+ return occupancies, len(occupancies)
153
+
154
+
155
+ def occupancy_to_atoms(parent, swap_indices: list[int], occ: tuple[str, ...]):
156
+ """Copy the parent supercell and paint swap sites with one occupancy tuple."""
157
+ atoms = parent.copy()
158
+ for index, symbol in zip(swap_indices, occ):
159
+ atoms.symbols[index] = symbol
160
+ return atoms
161
+
162
+
163
+ ##### ASE symmetry filter #####
164
+ def unique_by_ase(atoms_list, stol: float):
165
+ """Keep structures that ASE ``SymmetryEquivalenceCheck`` does not match to a kept one."""
166
+ comp = SymmetryEquivalenceCheck(stol=stol)
167
+ not_sym_atoms = []
168
+ for atoms_0 in tqdm(atoms_list, desc="ASE symmetry check"):
169
+ # First structure is always kept.
170
+ if len(not_sym_atoms) == 0:
171
+ not_sym_atoms.append(atoms_0)
172
+ continue
173
+ # True if atoms_0 is equivalent to any already-kept structure.
174
+ c1 = comp.compare(atoms_0, not_sym_atoms)
175
+ if c1:
176
+ continue
177
+ # compare(a, b) can disagree with compare(b, a), so check both ways
178
+ c2 = [comp.compare(a, atoms_0) for a in not_sym_atoms]
179
+ if any(c2):
180
+ continue
181
+ not_sym_atoms.append(atoms_0)
182
+ return not_sym_atoms
183
+
184
+
185
+ def run_enumerate(cfg: dict, out_dir: Path | None = None) -> Path:
186
+ ##### Load CIF, supercell, and swap species #####
187
+ info = load_enumeration_input(cfg)
188
+ species = info["species"]
189
+ ratio = info["ratio"]
190
+ supercell = info["supercell"]
191
+ swap_indices = info["swap_indices"]
192
+ supercell_size = info["supercell_size"]
193
+ stol = info["symprec"]
194
+ counts = resolve_counts(len(swap_indices), species, ratio)
195
+
196
+ print(f"CIF: {info['cif_path']}")
197
+ print(f"Disorder sublattice: {info['label']} swaps={species}")
198
+ print(f"Supercell size: {supercell_size}")
199
+ print(f"Number of swap sites: {len(swap_indices)}")
200
+ print(f"Ratio: {ratio} counts: {counts}")
201
+
202
+ ##### 1. Generate ratio-matching configurations #####
203
+ print("----- Generate all configurations -----")
204
+ occupancies, n_enum = generate_configurations(species, len(swap_indices), counts)
205
+ print(f"Number of configurations: {n_enum}")
206
+
207
+ ##### 2. Drop ASE symmetry equivalents #####
208
+ print("-------- Symmetry check --------")
209
+ atoms_list = [occupancy_to_atoms(supercell, swap_indices, occ) for occ in occupancies]
210
+ not_sym_atoms_tot = unique_by_ase(atoms_list, stol)
211
+ print(f"Total number of symmetrical inequivalent structures: {len(not_sym_atoms_tot)}")
212
+
213
+ ##### Write unique structures #####
214
+ db_name = f"{supercell.get_chemical_formula()}_{supercell_size[0]}{supercell_size[1]}{supercell_size[2]}_unique.db"
215
+ db_path = (out_dir / db_name) if out_dir is not None else Path(db_name)
216
+ if out_dir is not None:
217
+ out_dir.mkdir(parents=True, exist_ok=True)
218
+ print(f"Database name: {db_path}")
219
+ db = connect(str(db_path), append=False)
220
+ for atoms in not_sym_atoms_tot:
221
+ db.write(atoms)
222
+ print(f"Wrote {len(db)} inequivalent structures")
223
+ return db_path
224
+
225
+
226
+ def main(argv: list[str] | None = None) -> int:
227
+ args = build_parser().parse_args(argv)
228
+ cfg = load_config(args.config)
229
+ run_enumerate(cfg, out_dir=args.out_dir)
230
+ return 0
231
+
232
+
233
+ if __name__ == "__main__":
234
+ sys.exit(main())