ev-tlt's picture
Add files using upload-large-folder tool
2ce10b7 verified
Raw
History Blame
21.8 kB
import argparse
import json
import sys
import time
from pathlib import Path
import numpy as np
from ase import Atoms
from ase.build import make_supercell
from ase.data import atomic_numbers, covalent_radii
from ase.io import write
from ase.optimize import LBFGS
from ase.filters import FrechetCellFilter
from ase.units import GPa
from mace.calculators import MACECalculator
from pyxtal import pyxtal as pyxtal_cls
from pyxtal.tolerance import Tol_matrix
def log(msg):
print(msg, flush=True)
# ---------------------------------------------------------------------------
# Structure generation
# ---------------------------------------------------------------------------
def scale_to_covalent_radii(atoms: Atoms) -> Atoms:
"""Isotropically rescale so nearest-neighbour distance matches sum of covalent radii."""
atoms = atoms.copy()
sc = make_supercell(atoms, 2 * np.eye(3))
distances = sc.get_all_distances(mic=True)
np.fill_diagonal(distances, np.inf)
radii = np.array(
[covalent_radii[atomic_numbers[s]] for s in sc.get_chemical_symbols()]
)
target_matrix = radii[:, None] + radii[None, :]
closest_idx = np.unravel_index(np.argmin(distances), distances.shape)
min_dist = distances[closest_idx]
target_bond = target_matrix[closest_idx]
if min_dist <= 0.0:
raise ValueError("Degenerate geometry")
atoms.set_cell(atoms.cell * (target_bond / min_dist), scale_atoms=True)
return atoms
def gen_random_structure(
composition: dict[str, int],
seed: int | None = None,
max_attempts: int = 100,
volume_factor: float = 0.35,
) -> Atoms:
"""Generate a random periodic crystal via PyXtal with random space groups."""
rng = np.random.default_rng(seed)
species = list(composition.keys())
num_atoms = list(composition.values())
custom_tol = Tol_matrix(prototype="atomic", factor=1.0)
for attempt in range(max_attempts):
sg = int(rng.integers(1, 231))
try:
crystal = pyxtal_cls()
crystal.from_random(
dim=3,
group=sg,
species=species,
numIons=num_atoms,
random_state=int(rng.integers(0, 2**31)),
tm=custom_tol,
max_count=10,
factor=volume_factor,
)
if not crystal.valid:
continue
atoms = crystal.to_ase()
atoms.pbc = True
atoms = scale_to_covalent_radii(atoms)
atoms.info["space_group"] = sg
return atoms
except Exception:
continue
raise RuntimeError(
f"Failed to generate structure for {composition} after {max_attempts} attempts"
)
def generate_random_structures(
compositions: list[dict[str, int]],
n_per_composition: int,
seed: int = 42,
) -> list[Atoms]:
"""Generate n_per_composition random structures for each composition."""
rng = np.random.default_rng(seed)
all_structures = []
for comp in compositions:
label = "-".join(f"{k}{v}" for k, v in sorted(comp.items()))
log(f" Composition {label}: generating {n_per_composition} structures...")
n_success = 0
n_fail = 0
for i in range(n_per_composition):
try:
atoms = gen_random_structure(
comp,
seed=int(rng.integers(0, 2**31)),
)
formula = atoms.get_chemical_formula()
sg = atoms.info.get("space_group", "?")
atoms.info["label"] = f"{formula}_rss_{i}"
atoms.info["composition"] = label
atoms.info["stage"] = "initial"
all_structures.append(atoms)
n_success += 1
except Exception as exc:
n_fail += 1
if n_fail <= 3:
log(f" Failed #{i}: {exc}")
log(f" Done: {n_success} succeeded, {n_fail} failed")
log(f" Total: {len(all_structures)} initial structures")
return all_structures
# ---------------------------------------------------------------------------
# Relaxation with relax-rattle cycles
# ---------------------------------------------------------------------------
def relax_rattle_cycle(
atoms: Atoms,
calc,
n_cycles: int = 3,
fmax: float = 1e-3,
max_steps_per_cycle: int = 500,
rattle_stdev: float = 0.05,
rattle_seed: int = 42,
max_time: float = 120.0,
) -> Atoms:
"""
Relax with interleaved rattle perturbations to escape local minima.
Pattern: relax -> rattle -> relax -> rattle -> ... -> final relax
Rattle amplitude decays by 0.5x each cycle.
Returns the lowest-energy structure found across all cycles.
Bails out early if energy/volume diverge or wall-clock exceeds max_time.
"""
atoms = atoms.copy()
atoms.calc = calc
rng = np.random.default_rng(rattle_seed)
best_energy = np.inf
best_atoms = atoms.copy()
t_start = time.time()
for cycle in range(n_cycles):
if time.time() - t_start > max_time:
log(f" Timeout after {time.time()-t_start:.0f}s, stopping early")
break
try:
filtered = FrechetCellFilter(atoms, scalar_pressure=0.1 * GPa)
opt = LBFGS(filtered, logfile=None)
converged = opt.run(fmax=fmax, steps=max_steps_per_cycle)
e = atoms.get_potential_energy() / len(atoms)
v = atoms.get_volume() / len(atoms)
if abs(e) > 1e4 or v < 0.01 or v > 1e4:
log(f" Cycle {cycle}: runaway detected (E/at={e:.1f}, V/at={v:.2f}), stopping")
break
if e < best_energy:
best_energy = e
best_atoms = atoms.copy()
best_atoms.calc = None
best_atoms.info["energy_per_atom"] = float(e)
best_atoms.info["volume_per_atom"] = float(v)
best_atoms.info["converged"] = bool(converged)
best_atoms.info["relax_cycle"] = cycle
best_atoms.info["n_steps"] = opt.nsteps
if cycle < n_cycles - 1:
stdev = rattle_stdev * (0.5 ** cycle)
atoms.rattle(stdev=stdev, rng=rng)
except Exception as exc:
log(f" Cycle {cycle} failed: {exc}")
break
return best_atoms
def relax_structures(
structures: list[Atoms],
calc,
out_dir: Path,
n_cycles: int = 3,
fmax: float = 1e-3,
max_steps_per_cycle: int = 500,
rattle_stdev: float = 0.05,
seed: int = 42,
) -> list[Atoms]:
"""Relax all structures, writing each result incrementally."""
relaxed = []
failed = []
rng = np.random.default_rng(seed)
n_total = len(structures)
traj_path = out_dir / "relaxed_structures.xyz"
for idx, atoms in enumerate(structures):
label = atoms.info.get("label", f"struct_{idx}")
comp = atoms.info.get("composition", "?")
t0 = time.time()
try:
result = relax_rattle_cycle(
atoms,
calc,
n_cycles=n_cycles,
fmax=fmax,
max_steps_per_cycle=max_steps_per_cycle,
rattle_stdev=rattle_stdev,
rattle_seed=int(rng.integers(0, 2**31)),
)
result.info["label"] = label
result.info["composition"] = comp
result.info["stage"] = "relaxed"
dt = time.time() - t0
e = result.info.get("energy_per_atom", np.nan)
v = result.info.get("volume_per_atom", np.nan)
conv = result.info.get("converged", False)
steps = result.info.get("n_steps", "?")
log(f" [{idx+1}/{n_total}] {label}: E/at={e:.4f} eV V/at={v:.2f} A3 conv={conv} steps={steps} ({dt:.1f}s)")
relaxed.append(result)
try:
write(traj_path, result, format="extxyz", append=True)
except Exception as write_exc:
log(f" [{idx+1}/{n_total}] {label}: write failed — {write_exc}")
except Exception as exc:
dt = time.time() - t0
log(f" [{idx+1}/{n_total}] {label}: FAILED ({dt:.1f}s) — {exc}")
failed.append({"label": label, "error": str(exc)})
log(f" Relaxation complete: {len(relaxed)} succeeded, {len(failed)} failed")
return relaxed
# ---------------------------------------------------------------------------
# Analysis
# ---------------------------------------------------------------------------
def analyse_results(relaxed: list[Atoms], out_dir: Path):
"""Compute and save energy-volume data; flag possible energy holes."""
records = []
for atoms in relaxed:
records.append({
"label": atoms.info.get("label", "unknown"),
"composition": atoms.info.get("composition", "unknown"),
"formula": atoms.get_chemical_formula(),
"n_atoms": len(atoms),
"energy_per_atom_eV": atoms.info.get("energy_per_atom", np.nan),
"volume_per_atom_A3": atoms.info.get("volume_per_atom", np.nan),
"converged": atoms.info.get("converged", False),
})
csv_path = out_dir / "rss_results.csv"
with open(csv_path, "w") as f:
if records:
header = list(records[0].keys())
f.write(",".join(header) + "\n")
for rec in records:
f.write(",".join(str(rec[k]) for k in header) + "\n")
log(f" Results saved to {csv_path}")
compositions = sorted(set(r["composition"] for r in records))
for comp in compositions:
energies = np.array([
r["energy_per_atom_eV"] for r in records
if r["composition"] == comp and np.isfinite(r["energy_per_atom_eV"])
])
if len(energies) == 0:
continue
median_e = np.median(energies)
iqr = np.percentile(energies, 75) - np.percentile(energies, 25)
threshold = median_e - 5 * max(iqr, 0.5)
n_suspicious = int(np.sum(energies < threshold))
log(f"\n [{comp}] n={len(energies)} min={np.min(energies):.4f} median={median_e:.4f} max={np.max(energies):.4f} eV/atom")
if n_suspicious > 0:
log(f" WARNING: {n_suspicious} structures below {threshold:.4f} eV/atom — possible energy holes!")
for r in records:
if r["composition"] == comp and r["energy_per_atom_eV"] < threshold:
log(f" {r['label']}: {r['energy_per_atom_eV']:.4f} eV/atom")
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(description="Random Structure Search with MACE")
parser.add_argument("model_path", type=str, help="Path to MACE .model file")
parser.add_argument("--device", type=str, default="cuda", choices=["cuda", "cpu"])
parser.add_argument("--dtype", type=str, default="float64", choices=["float32", "float64"])
parser.add_argument("--compositions", type=str, default=None,
help="Explicit compositions as 'Na4Cl4,Na2Cl6,Na8,Cl8,...' — "
"element followed by count, comma-separated")
parser.add_argument("--elements", type=str, default=None,
help="Comma-separated elements (e.g. 'Na,Cl') to auto-enumerate compositions")
parser.add_argument("--min-atoms", type=int, default=8,
help="Min total atoms per cell when using --elements (default: 8)")
parser.add_argument("--max-atoms", type=int, default=12,
help="Max total atoms per cell when using --elements (default: 12)")
parser.add_argument("--total-structures", type=int, default=500,
help="Target total structures when using --elements (default: 500)")
parser.add_argument("--random-compositions", type=str, default=None,
help="Element pool for random composition sampling (e.g. 'Li,P,S,Ge,Cl,As,Si,Sn')")
parser.add_argument("--n-compositions", type=int, default=10,
help="Number of random compositions to sample (default: 10)")
parser.add_argument("--n-species", type=int, default=3,
help="Number of species per random composition (default: 3)")
parser.add_argument("--anchor-element", type=str, default=None,
help="Element to include in most compositions (e.g. 'Li')")
parser.add_argument("--n-per-composition", type=int, default=None,
help="Number of random structures per composition (required with --compositions)")
parser.add_argument("--n-cycles", type=int, default=3,
help="Number of relax-rattle cycles")
parser.add_argument("--fmax", type=float, default=1e-3,
help="Force convergence threshold (eV/A)")
parser.add_argument("--max-steps", type=int, default=500,
help="Max optimizer steps per relax cycle")
parser.add_argument("--rattle-stdev", type=float, default=0.05,
help="Initial rattle amplitude (A), halved each cycle")
parser.add_argument("--head", type=str, default=None,
help="Head name for multi-head models (e.g. 'omat_pbe')")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--out-dir", type=str, default="rss_output")
args = parser.parse_args()
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
if args.compositions:
compositions = parse_compositions(args.compositions)
n_per_composition = args.n_per_composition if args.n_per_composition else 100
elif args.random_compositions:
pool = [e.strip() for e in args.random_compositions.split(",")]
compositions = sample_random_compositions(
element_pool=pool,
n_compositions=args.n_compositions,
n_species=args.n_species,
min_atoms=args.min_atoms,
max_atoms=args.max_atoms,
anchor_element=args.anchor_element,
seed=args.seed,
)
n_per_composition = args.n_per_composition if args.n_per_composition else 50
log(f" Sampled {len(compositions)} random compositions from {pool}, "
f"{n_per_composition} structures each")
elif args.elements:
elements = [e.strip() for e in args.elements.split(",")]
compositions = enumerate_compositions(elements, args.min_atoms, args.max_atoms)
n_per_composition = max(1, args.total_structures // len(compositions))
log(f" Auto-enumerated {len(compositions)} compositions from {elements}, "
f"{n_per_composition} structures each (target total={args.total_structures})")
else:
parser.error("Either --compositions, --elements, or --random-compositions is required")
log("=" * 70)
log("Random Structure Search")
log("=" * 70)
log(f"Model: {args.model_path}")
log(f"Device: {args.device}")
log(f"Compositions: {len(compositions)} total")
for comp in compositions:
label = "-".join(f"{k}{v}" for k, v in sorted(comp.items()))
log(f" {label}")
log(f"N per comp: {n_per_composition}")
log(f"Relax cycles: {args.n_cycles} (fmax={args.fmax} eV/A, max_steps={args.max_steps})")
log(f"Rattle: stdev={args.rattle_stdev} A (halved each cycle)")
log(f"Seed: {args.seed}")
log(f"Output: {out_dir}")
log("=" * 70)
# --- Stage 1: Generate ---
log("\n>>> Stage 1: Generating random structures...")
t0 = time.time()
structures = generate_random_structures(
compositions=compositions,
n_per_composition=n_per_composition,
seed=args.seed,
)
write(out_dir / "initial_structures.xyz", structures, format="extxyz")
log(f" Saved initial structures ({time.time()-t0:.1f}s)")
# --- Stage 2: Relax ---
log("\n>>> Stage 2: Relaxing structures...")
calc_kwargs = dict(
model_paths=args.model_path,
device=args.device,
default_dtype=args.dtype,
)
if args.head:
calc_kwargs["head"] = args.head
calc = MACECalculator(**calc_kwargs)
t0 = time.time()
relaxed = relax_structures(
structures,
calc,
out_dir,
n_cycles=args.n_cycles,
fmax=args.fmax,
max_steps_per_cycle=args.max_steps,
rattle_stdev=args.rattle_stdev,
seed=args.seed,
)
log(f" Total relaxation time: {time.time()-t0:.1f}s")
# --- Stage 3: Analyse ---
log("\n>>> Stage 3: Analysis...")
analyse_results(relaxed, out_dir)
log("\nDone!")
def parse_compositions(comp_str: str) -> list[dict[str, int]]:
"""Parse 'Na4Cl4,Na8,Cl12' into [{'Na': 4, 'Cl': 4}, {'Na': 8}, {'Cl': 12}]."""
import re
compositions = []
for part in comp_str.split(","):
part = part.strip()
comp = {}
for match in re.finditer(r"([A-Z][a-z]?)(\d+)", part):
elem, count = match.group(1), int(match.group(2))
comp[elem] = count
if comp:
compositions.append(comp)
else:
raise ValueError(f"Could not parse composition: '{part}'")
return compositions
def enumerate_compositions(
elements: list[str],
min_atoms: int = 8,
max_atoms: int = 12,
) -> list[dict[str, int]]:
"""Enumerate all stoichiometric combinations of elements with total atoms in [min_atoms, max_atoms].
Each element present in a composition has at least 1 atom. Pure-element
compositions (single species) are included.
"""
from itertools import combinations_with_replacement
compositions = []
n_elems = len(elements)
for n_total in range(min_atoms, max_atoms + 1):
if n_elems == 1:
compositions.append({elements[0]: n_total})
continue
for n_sub in range(1, n_elems + 1):
for elem_subset in combinations_with_replacement(elements, n_sub):
unique = sorted(set(elem_subset))
_enumerate_partitions(unique, n_total, {}, compositions)
seen = set()
unique_compositions = []
for comp in compositions:
key = tuple(sorted(comp.items()))
if key not in seen:
seen.add(key)
unique_compositions.append(comp)
return unique_compositions
def _enumerate_partitions(
elements: list[str],
n_total: int,
current: dict[str, int],
results: list[dict[str, int]],
):
"""Recursively partition n_total atoms among elements (each gets >= 1)."""
if len(elements) == 1:
if n_total >= 1:
comp = dict(current)
comp[elements[0]] = n_total
results.append(comp)
return
elem = elements[0]
remaining = elements[1:]
min_for_rest = len(remaining)
for count in range(1, n_total - min_for_rest + 1):
current[elem] = count
_enumerate_partitions(remaining, n_total - count, current, results)
if elem in current:
del current[elem]
def sample_random_compositions(
element_pool: list[str],
n_compositions: int = 10,
n_species: int = 3,
min_atoms: int = 8,
max_atoms: int = 12,
anchor_element: str | None = None,
anchor_fraction: float = 0.7,
seed: int = 42,
) -> list[dict[str, int]]:
"""Sample random compositions from an element pool.
Generates diverse compositions by picking n_species elements per composition
and assigning random atom counts summing to min_atoms..max_atoms.
Sampling strategy (3 tiers for chemical diversity):
- Tier 1 (~anchor_fraction of compositions): anchor_element + 2 random others
- Tier 2 (remaining): any 3 random elements from pool, no anchor constraint
Within each composition, atom counts are drawn from a Dirichlet distribution
(alpha=1 = uniform on the simplex), then rounded to integers >= 1. This gives
a spread of stoichiometries rather than always near-equal splits.
"""
rng = np.random.default_rng(seed)
compositions = []
seen = set()
n_anchored = int(n_compositions * anchor_fraction) if anchor_element else 0
non_anchor_pool = [e for e in element_pool if e != anchor_element]
for i in range(n_compositions * 10):
if len(compositions) >= n_compositions:
break
if len(compositions) < n_anchored and anchor_element:
others = list(rng.choice(non_anchor_pool, size=n_species - 1, replace=False))
species = [anchor_element] + others
else:
species = list(rng.choice(element_pool, size=n_species, replace=False))
species = sorted(species)
n_total = int(rng.integers(min_atoms, max_atoms + 1))
alphas = np.ones(len(species))
fractions = rng.dirichlet(alphas)
raw_counts = fractions * n_total
counts = np.maximum(np.round(raw_counts).astype(int), 1)
diff = n_total - counts.sum()
if diff > 0:
for _ in range(diff):
counts[rng.integers(len(counts))] += 1
elif diff < 0:
for _ in range(-diff):
idx = rng.choice(np.where(counts > 1)[0])
counts[idx] -= 1
comp = {str(s): int(c) for s, c in zip(species, counts)}
key = tuple(sorted(comp.items()))
if key not in seen:
seen.add(key)
compositions.append(comp)
return compositions
if __name__ == "__main__":
main()