"""Crystal phonons, thermal ensembles and magnetic orderings on a real cell.

The New_agents brief asked for the condensed phase -- "the real crystal, its
phonons, genuine lattice strain" -- and for responses judged "thermally and
vibrationally averaged, not the value at a rigid geometry".  The campaign
stopped before any of it.  These tools close that loop with the same CP2K
Hamiltonian as the crystal single points and relaxations (site magnetizations,
DFT+U, the semicore cutoff floor, FULL_ALL OT), so forces, modes and snapshots
are mutually consistent:

* ``run_periodic_dft_phonons`` -- equilibrium SCF, then every phonopy finite
  displacement as one Slurm array restarted from the equilibrium wavefunction.
* ``collect_periodic_dft_phonons`` -- forces -> force constants (equilibrium
  residual forces subtracted), Gamma modes, DOS/thermodynamics, imaginary-mode
  check; resubmits only missing/failed displacements.
* ``generate_phonon_thermal_snapshots`` -- quantum (Bose-Einstein + zero-point)
  harmonic snapshots at T; at the 5-20 K of the campaign zero-point motion
  dominates, which classical MD would miss.
* ``export_phonon_mode_displacements`` -- +/-Q cells per Gamma mode with
  <Q^2>_T, for dX/dQ and second-order vibronic averages of any property X.
* ``export_random_cluster_displacements`` -- randomly displaced clusters for a
  quadratic fit of g / A (first + full second derivatives; spin_relaxation.py).
* ``run_periodic_dft_magnetic_orderings`` -- symmetry-distinct collinear
  orderings of the metal sites as single points, with a check that each SCF kept
  the intended spin pattern.
"""

from __future__ import annotations

import itertools
import json
import math
import re
from pathlib import Path
from typing import Annotated, Any, Dict

import numpy
import numpy as np
from langchain.tools import ToolRuntime
from langchain_core.tools import tool

from Hypothesis_generation.skill_library.periodic_dft import crystal_calcs as cc
from Hypothesis_generation.skill_library.periodic_dft import harness as _h

PHONON_MANIFEST = "phonon_manifest.json"
PHONON_SUMMARY = "phonon_summary.json"
PHONOPY_PARAMS = "phonopy_params.yaml"
FC_PROVENANCE = "fc_provenance.json"  # label of a force-constant set not made by run_periodic_dft_phonons (MLIP, mixed)
MIXED_FC_SOURCE = "mixed_dft_gamma+mlip_supercell"
ORDERING_MANIFEST = "magnetic_ordering_manifest.json"
THZ_TO_CM1 = 33.35640951981521
HARTREE_PER_BOHR_TO_EV_PER_ANG = cc.HARTREE_PER_BOHR_TO_EV_PER_ANG
# Residual equilibrium force above which finite-displacement phonons are unreliable.
STATIONARY_MAX_FORCE_HA_BOHR = 1.0e-3


def _phonopy_atoms(atoms):
    from phonopy.structure.atoms import PhonopyAtoms

    return PhonopyAtoms(symbols=atoms.get_chemical_symbols(), cell=atoms.cell.array, positions=atoms.get_positions())


def _ase_atoms(patoms):
    from ase import Atoms

    return Atoms(patoms.symbols, cell=patoms.cell, positions=patoms.positions, pbc=True)


def _supercell_matrix(text: str):
    values = [int(v) for v in str(text).replace(",", " ").split()]
    if len(values) == 3:
        return np.diag(values)
    if len(values) == 9:
        return np.array(values).reshape(3, 3)
    raise ValueError("supercell must be 'a b c' or nine integers.")


def _stationary_provenance(structure: Path) -> dict[str, Any]:
    """Was this structure produced by a converged, all-atom crystal optimization?"""
    results = cc._read_json(structure.parent / cc.JOB_RESULTS)
    state = cc._read_json(structure.parent / cc.JOB_STATE)
    fixed = state.get("fixed_indices") or []
    ok = (
        results.get("calculation") in {"geo_opt", "cell_opt"}
        and bool(results.get("converged"))
        and not fixed
        and structure.name.startswith("final_structure")
    )
    return {
        "from_converged_all_atom_optimization": ok,
        "source_calculation": results.get("calculation"),
        "fixed_atoms_in_source": len(fixed),
    }


def _stage_dir(root: Path, structure: Path, name: str) -> Path:
    """Sibling of the producing crystal job (calculations/periodic_dft_<x>/<name>), else a new folder."""
    return cc.crystal_family_dir(root, structure) / name


def _array_script(*, np_threads: int, settings: dict[str, str]) -> str:
    setup = _h._periodic_runtime_setup_lines(
        cp2k_exec=settings["cp2k_exec"], phonopy="", phonopy_init="", mpi_run=settings["mpi_run"],
        np=int(np_threads), environment_setup=settings["environment_setup"],
    )
    return "\n".join(
        [
            "#!/bin/bash",
            *setup,
            'cd "${SLURM_SUBMIT_DIR:-$(dirname "$0")}"',
            'TASK_DIR=$(printf "disp-%04d" "$SLURM_ARRAY_TASK_ID")',
            'cd "$TASK_DIR" || exit 3',
            'echo "started $(date -Is) on $(hostname)" > cp2k_crystal.started',
            'if [ -n "${MPI_RUN:-}" ]; then',
            f'  $MPI_RUN -np "$NP" "$CP2K_EXEC" -i {cc.JOB_INPUT} -o {cc.JOB_OUTPUT}',
            "else",
            f'  "$CP2K_EXEC" -i {cc.JOB_INPUT} -o {cc.JOB_OUTPUT}',
            "fi",
            "rc=$?",
            'echo "$rc" > cp2k_crystal.exit_code',
            "exit $rc",
            "",
        ]
    )


def _task_forces(task_dir: Path, kinds: dict[str, str]) -> tuple[np.ndarray | None, dict[str, Any]]:
    out = task_dir / cc.JOB_OUTPUT
    if not out.is_file():
        return None, {"status": "missing"}
    parsed = cc.parse_crystal_output(out.read_text(errors="replace"), kinds)
    forces = (parsed.get("forces") or {}).get("per_atom_hartree_per_bohr")
    ok = parsed.get("normal_termination") and not parsed.get("scf_not_converged") and not parsed.get("walltime_stop") and forces
    status = "ok" if ok else ("scf_not_converged" if parsed.get("scf_not_converged") else ("walltime" if parsed.get("walltime_stop") else "incomplete"))
    timing = re.search(r"^ CP2K\s+1\s+[\d.]+\s+[\d.]+\s+[\d.]+\s+[\d.]+\s+([\d.]+)\s*$", out.read_text(errors="replace"), re.M)
    return (np.array(forces) if ok else None), {
        "status": status, "energy_hartree": parsed.get("energy_hartree"),
        "wall_seconds": float(timing.group(1)) if timing else None,
    }


def displaced_input(template: str, positions, wfn_path: str, walltime_seconds: int = 0) -> str:
    """Equilibrium CP2K input with new Cartesian positions (same atom order) and a wavefunction restart."""
    lines = template.splitlines()
    start = next(i for i, line in enumerate(lines) if line.strip() == "&COORD")
    end = next(i for i in range(start, len(lines)) if lines[i].strip() == "&END COORD")
    coords = lines[start + 1 : end]
    if len(coords) != len(positions):
        raise ValueError(f"Displaced cell has {len(positions)} atoms but the template has {len(coords)}.")
    lines[start + 1 : end] = [
        f"      {line.split()[0]:<6} {x: .12f} {y: .12f} {z: .12f}" for line, (x, y, z) in zip(coords, positions)
    ]
    out = []
    for line in lines:
        key = line.strip().split()[0] if line.strip() else ""
        if key in {"WFN_RESTART_FILE_NAME", "STRESS_TENSOR"}:  # displaced cells need forces only
            continue
        if key == "SCF_GUESS":
            line = line.split("SCF_GUESS")[0] + "SCF_GUESS RESTART"
        if key == "WALLTIME" and walltime_seconds:  # this job's own graceful stop, before Slurm's limit
            line = line.split("WALLTIME")[0] + f"WALLTIME {int(walltime_seconds)}"
        if key == "CHARGE" and line.startswith("    CHARGE"):
            out.append(f"    WFN_RESTART_FILE_NAME {wfn_path}")
        out.append(line)
    return "\n".join(out) + "\n"


def _inherited_contract(structure: Path, n_cells: int) -> dict[str, Any]:
    """Spin contract / DFT+U of the crystal job that produced ``structure`` (scaled to the supercell)."""
    state = cc._read_json(structure.parent / cc.JOB_STATE)
    spin = state.get("spin_contract") or {}
    if not spin:
        return {}
    mult = spin.get("multiplicity")
    return {
        "charge": None if spin.get("charge") is None else int(spin["charge"]) * n_cells,
        "multiplicity": None if mult is None else (int(mult) - 1) * n_cells + 1,
        "rationale": spin.get("rationale") or "",
        "site_magnetization_json": json.dumps({"indices": spin["site_magnetizations"]}) if spin.get("site_magnetizations") else "",
        "dft_plus_u": state.get("dft_plus_u") or {},
        "hamiltonian": state.get("hamiltonian") or {},
    }


# --------------------------------------------------------------------------- #
# Phonons
# --------------------------------------------------------------------------- #


def run_periodic_dft_phonons(
    structure_path: Annotated[str, "Stationary periodic structure: final_structure.extxyz/.cif of a CONVERGED all-atom geo_opt/cell_opt (run it with tight_for_phonons=True)."],
    charge: Annotated[int | None, "Total cell charge."] = None,
    multiplicity: Annotated[int | None, "Total cell multiplicity (of the SUPERCELL: scales with the number of cells)."] = None,
    spin_state_rationale: Annotated[str, "Spin/charge justification (required for TM cells)."] = "",
    site_magnetization_json: Annotated[str, "Initial spins per site, e.g. '{\"Co\": 3}' -- keep the ordering of the relaxation."] = "",
    supercell: Annotated[str, "Force-constant supercell 'a b c'. '1 1 1' gives Gamma-exact modes; larger for dispersion."] = "1 1 1",
    kpoints: Annotated[str, "k mesh of the displaced SUPERCELL. '' (default) = the relaxation's mesh divided by the supercell (equivalent sampling, e.g. unit cell '4 4 4' -> '2 2 2' for a 2x2x2 supercell), or 'GAMMA' / 'auto' / 'n1 n2 n3'."] = "",
    displacement_angstrom: Annotated[float, "Finite-displacement amplitude (A)."] = 0.01,
    plus_minus: Annotated[bool, "Displace +/- (central differences, default). False halves the jobs (one-sided; the equilibrium residual force is subtracted, error ~ anharmonicity x step)."] = True,
    symprec: Annotated[float, "Symmetry tolerance (A) used to reduce displacements; relaxed P1 cells keep symmetry to ~1e-4 A."] = 1.0e-3,
    symmetrize_symprec: Annotated[float, "Symmetrize the structure first (spglib refinement of cell and positions at this tolerance in A, atom order kept; 0 = off). A DFT-relaxed P1 cell of a symmetric crystal then needs far fewer displacements (urea form I: 16 (P-42_1m) or 24 (P2_12_12) instead of 96); the detected space group and the largest atom shift are reported, and the equilibrium residual forces are subtracted as usual."] = 0.0,
    dft_plus_u_json: Annotated[str, "DFT+U per element (eV) -- must match the relaxation."] = "",
    dft_plus_u_rationale: Annotated[str, "Required with dft_plus_u_json."] = "",
    functional: Annotated[str, "XC functional (must match the relaxation)."] = "PBE",
    basis_set: Annotated[str, "Basis family (must match the relaxation)."] = "DZVP-MOLOPT-SR-GTH",
    cutoff_ry: Annotated[int, "Plane-wave cutoff; the 600 Ry semicore floor applies."] = 400,
    rel_cutoff_ry: Annotated[int, "Relative cutoff (Ry)."] = 60,
    dispersion: Annotated[bool, "DFT-D3 (must match the relaxation)."] = True,
    dispersion_type: Annotated[str, "'DFTD3' or 'DFTD3(BJ)' (inherited from the relaxation when left at the default)."] = "DFTD3",
    phonon_grade_grid: Annotated[bool, "800 Ry + finer XC grid for semicore-metal cells (default). On C1 the 600 Ry grid gave 24-31 cm-1 raw acoustic noise. Relax with tight_for_phonons=True so the equilibrium is stationary on the same grid."] = True,
    np: Annotated[int, "Threads per job (equilibrium and each displacement). 8 is the most core-hour-efficient for ~140-atom cells (0.77 vs 0.90 core-h per displacement at 16)."] = 8,
    mem: Annotated[str, "Memory per job (a 140-atom Co cell peaks at ~4.4 GB)."] = "16G",
    max_core_hours_equilibrium: Annotated[float, "Hard core-hour cap of the equilibrium SCF."] = 24.0,
    max_core_hours_per_displacement: Annotated[float, "Hard core-hour cap per displacement (restarted from the equilibrium wavefunction)."] = 8.0,
    max_total_core_hours: Annotated[float, "Refuse to start if equilibrium + all displacement caps exceed this."] = 600.0,
    array_parallelism: Annotated[int, "Maximum displacement jobs running at once."] = 40,
    partition: Annotated[str, "Optional Slurm partition."] = "",
    allow_non_stationary: Annotated[bool, "Allow a structure that is not the product of a converged all-atom optimization (imaginary modes expected)."] = False,
    output_dir: Annotated[str, "Phonon directory; default calculations/periodic_dft_<structure>/phonons_<supercell>."] = "",
    execution_mode: Annotated[str, "'dry_run' (write everything, CP2K --check, count displacements and cost) or 'submit'."] = "dry_run",
    submit_approved: Annotated[bool, "Must be True to submit."] = False,
    wait_for_completion: Annotated[bool, "Wait for the equilibrium and the displacement array, then collect."] = True,
    max_wait_hours: Annotated[float, "Upper bound on waiting in this call."] = 72.0,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Finite-displacement phonons of a real crystal with the crystal-calculation Hamiltonian (Slurm array, wavefunction restarts)."""
    root = _h._root(runtime)
    try:
        from phonopy import Phonopy

        structure = _h._resolve_path(root, structure_path, must_exist=True, dir_ok=False)
        atoms, warnings = cc.load_periodic_structure(structure)
        provenance = _stationarity_gate(structure, allow_non_stationary, warnings)
        symmetrization = None
        if float(symmetrize_symprec) > 0:
            from ase.spacegroup.symmetrize import check_symmetry, refine_symmetry

            before = atoms.copy()
            found = check_symmetry(atoms, symprec=float(symmetrize_symprec)).international
            refine_symmetry(atoms, symprec=float(symmetrize_symprec))
            frac = atoms.get_scaled_positions(wrap=False) - before.get_scaled_positions(wrap=False)
            shift = numpy.linalg.norm((frac - numpy.round(frac)) @ atoms.cell.array, axis=1)  # np is the thread count here
            symmetrization = {
                "symprec_angstrom": float(symmetrize_symprec),
                "spacegroup_before_at_1e-3": check_symmetry(before, symprec=1e-3).international,
                "spacegroup": found,
                "max_atom_shift_angstrom": round(float(shift.max()), 5),
                "max_cell_change_angstrom": round(float(numpy.abs(atoms.cell.array - before.cell.array).max()), 5),
            }
            if shift.max() > 0.5 * float(symmetrize_symprec):
                warnings.append(f"Symmetrization to {found} moved an atom by {shift.max():.3f} A: the equilibrium is no longer "
                                "stationary to that extent (residual forces are subtracted); imaginary modes mean the symmetric "
                                "structure is not the DFT minimum.")
        phonon = Phonopy(_phonopy_atoms(atoms), supercell_matrix=_supercell_matrix(supercell), primitive_matrix="P", symprec=float(symprec))
        phonon.generate_displacements(distance=float(displacement_angstrom), is_plusminus="auto" if plus_minus else False)
        parent_mem = parent_job_mem(structure)
        if parent_mem and (cs_mem_gb(mem) or 0) < cs_mem_gb(parent_mem):
            # H01 cand02 2026-10-11: the relaxation peaked at 29 of 32 GB (16 ranks, k 2x3x1); the phonons asked 20G on 8 ranks and
            # the equilibrium job was OOM-killed in 32 s (k-point data is replicated per rank, so fewer ranks need about as much).
            warnings.append(f"mem raised {mem or 'default'} -> {parent_mem}: the relaxation that produced this structure ran with {parent_mem} "
                            "and the same Hamiltonian.")
            mem = parent_mem
        if cc.crystal_runtime_settings()["mpi_run"] and mpi_job_mem(mem, int(np)) != mem:
            warnings.append(f"MPI build: mem raised {mem} -> {mpi_job_mem(mem, int(np))} ({np} ranks; data is replicated per rank).")
            mem = mpi_job_mem(mem, int(np))
        common, kpoints = displacement_settings(
            structure, atoms, phonon, kpoints, warnings, charge=charge, multiplicity=multiplicity,
            spin_state_rationale=spin_state_rationale, site_magnetization_json=site_magnetization_json,
            dft_plus_u_json=dft_plus_u_json, dft_plus_u_rationale=dft_plus_u_rationale, functional=functional,
            basis_set=basis_set, cutoff_ry=cutoff_ry, rel_cutoff_ry=rel_cutoff_ry, dispersion=dispersion,
            dispersion_type=dispersion_type, phonon_grade_grid=phonon_grade_grid, np=np, mem=mem, partition=partition,
        )
        n_cells = int(round(abs(numpy.linalg.det(_supercell_matrix(supercell)))))
        supercells = phonon.supercells_with_displacements
        n_disp = len(supercells)
        planned = float(max_core_hours_equilibrium) + n_disp * float(max_core_hours_per_displacement)
        if planned > float(max_total_core_hours):
            raise ValueError(
                f"{n_disp} displacements x {max_core_hours_per_displacement} + {max_core_hours_equilibrium} core-h = {planned:g} "
                f"exceeds max_total_core_hours={max_total_core_hours:g}. Raise the approved total or lower the per-job caps "
                "(displacements restart from the equilibrium wavefunction and usually need far less than a cold SCF)."
            )
        sc_tag = "x".join(str(int(v)) for v in numpy.diag(_supercell_matrix(supercell)))
        ph_dir = _h._under_root(
            root,
            _h._resolve_path(root, output_dir) if output_dir.strip()
            else _stage_dir(root, structure, f"phonons_{sc_tag}"),
        )
        ph_dir.mkdir(parents=True, exist_ok=True)
        if cc._read_json(ph_dir / PHONON_MANIFEST).get("equilibrium_job_id"):
            return {"ok": True, "duplicate_submission_prevented": True, **collect_periodic_dft_phonons(_h._rel(root, ph_dir), runtime=runtime)}

        ideal = _ase_atoms(phonon.supercell)
        eq, disp_rows = prepare_displaced_jobs(
            root, structure, ph_dir, ideal, [sc.positions for sc in supercells], kpoints, common, warnings,
            max_core_hours_equilibrium=max_core_hours_equilibrium, max_core_hours_per_displacement=max_core_hours_per_displacement,
            execution_mode=execution_mode, submit_approved=submit_approved, restart_from_relaxation=n_cells == 1,
        )
        if not eq.get("ok"):
            return {"ok": False, "status": "equilibrium_preparation_failed", "detail": eq}
        phonon.save(filename=str(ph_dir / "phonopy_disp.yaml"))
        manifest = {
            "structure": _h._rel(root, structure),
            "structure_provenance": provenance,
            "supercell_matrix": _supercell_matrix(supercell).tolist(),
            "displacement_angstrom": float(displacement_angstrom),
            "symprec": float(symprec),
            "spacegroup": phonon.symmetry.dataset.international if phonon.symmetry.dataset is not None else None,
            "symmetrization": symmetrization,
            "n_displacements": n_disp,
            "n_atoms_supercell": len(ideal),
            "kind_to_element": cc._read_json(ph_dir / "equilibrium" / cc.JOB_STATE).get("kind_to_element"),
            "planned_core_hours_cap": planned,
            "np": int(np), "mem": mem, "partition": partition,
            "max_core_hours_per_displacement": float(max_core_hours_per_displacement),
            "array_parallelism": int(array_parallelism),
            "displacements": disp_rows,
        }
        if execution_mode == "dry_run":
            (ph_dir / PHONON_MANIFEST).write_text(json.dumps(manifest, indent=1))
            return {
                "ok": True, "status": "dry_run_validated", "phonon_dir": _h._rel(root, ph_dir),
                "spacegroup": manifest["spacegroup"], "symmetrization": symmetrization, "n_displacements": n_disp, "n_atoms_supercell": len(ideal),
                "planned_core_hours_cap": planned, "kpoints": kpoints, "equilibrium_check": eq.get("cp2k_check", {}).get("ok"),
                "warnings": eq.get("warnings", []),
            }
        manifest["equilibrium_job_id"] = eq.get("job_id")
        array = _submit_array(ph_dir, list(range(1, n_disp + 1)), manifest, dependency_job=eq.get("job_id"))
        manifest["array_submissions"] = [array]
        (ph_dir / PHONON_MANIFEST).write_text(json.dumps(manifest, indent=1))
        if not array.get("ok"):
            return {"ok": False, "status": "array_submission_failed", "phonon_dir": _h._rel(root, ph_dir), "submission": array}
        result = {
            "ok": True, "status": "submitted", "phonon_dir": _h._rel(root, ph_dir), "equilibrium_job_id": eq.get("job_id"),
            "array_job_id": array.get("job_id"), "n_displacements": n_disp, "planned_core_hours_cap": planned,
            "spacegroup": manifest["spacegroup"], "symmetrization": symmetrization, "warnings": warnings,
        }
        if not wait_for_completion:
            result["next_step"] = "collect_periodic_dft_phonons(phonon_dir, wait=True) to monitor, resubmit failures and build the phonons."
            return result
        return collect_periodic_dft_phonons(_h._rel(root, ph_dir), wait=True, max_wait_hours=max_wait_hours, runtime=runtime)
    except Exception as exc:
        return _h._error(exc, hint="Dry-run first; phonons need the relaxed structure and the SAME settings as the relaxation.")


def _stationarity_gate(structure: Path, allow_non_stationary: bool, warnings: list[str]) -> dict[str, Any]:
    """Finite differences need the final_structure of a converged all-atom optimization (raises otherwise)."""
    provenance = _stationary_provenance(structure)
    if not provenance["from_converged_all_atom_optimization"]:
        if not allow_non_stationary:
            raise ValueError(
                "Phonons need a stationary structure: pass the final_structure of a CONVERGED all-atom geo_opt or "
                "cell_opt (e.g. run_periodic_dft_crystal_calculation(calculation='geo_opt', continue_from_job_dir=<H-only job>, "
                "tight_for_phonons=True)). An H-only relaxation leaves the heavy atoms non-stationary. "
                "Set allow_non_stationary=True only for a deliberate test."
            )
        warnings.append("Structure is not from a converged all-atom optimization: expect spurious imaginary modes.")
    return provenance


def displacement_settings(structure: Path, atoms, phonon, kpoints: str, warnings: list[str], **requested) -> tuple[dict[str, Any], str]:
    """(cc._prepare_and_submit settings, k mesh) of every displaced cell of ``phonon.supercell``: the relaxation's spin contract,
    DFT+U, Hamiltonian and Brillouin-zone sampling, scaled to the supercell. ``requested`` = run_periodic_dft_phonons' charge,
    multiplicity, spin_state_rationale, site_magnetization_json, dft_plus_u_json, dft_plus_u_rationale, functional, basis_set,
    cutoff_ry, rel_cutoff_ry, dispersion, dispersion_type, phonon_grade_grid, np, mem, partition (defaults are overridden by
    the relaxation's values)."""
    r = dict(requested)
    ham_relax = cc._read_json(structure.parent / cc.JOB_STATE).get("hamiltonian") or {}
    if r["phonon_grade_grid"] and ham_relax.get("phonon_grade_grid") is False:
        warnings.append(
            "The structure was relaxed on the standard grid but phonons use the phonon-grade grid: re-relax with "
            "tight_for_phonons=True (continue_from_job_dir) so the equilibrium is stationary on the same grid."
        )
    sc_matrix = np.array(phonon.supercell_matrix)
    n_cells = int(round(abs(np.linalg.det(sc_matrix))))
    if not kpoints.strip():
        # A small molecular cell relaxed with k points must keep the same Brillouin-zone sampling: Gamma-only
        # displaced cells of urea (4.7 A) are not even the relaxation's Hamiltonian.
        relax_k = cc._mp_grid(ham_relax.get("kpoints") or "GAMMA")
        sc_diag = np.diag(sc_matrix)
        mesh = [-(-k // int(n)) for k, n in zip(relax_k, sc_diag)]
        kpoints = "GAMMA" if mesh == [1, 1, 1] else " ".join(map(str, mesh))
        if any(k % int(n) for k, n in zip(relax_k, sc_diag)) or not np.allclose(sc_matrix, np.diag(sc_diag)):
            warnings.append(f"Relaxation k mesh {relax_k} is not divisible by the supercell: displaced cells use '{kpoints}', "
                            "a different Brillouin-zone sampling (the equilibrium is then not exactly stationary).")
    inherited = _inherited_contract(structure, n_cells)
    if inherited:
        # Same Hamiltonian as the relaxation that produced this structure.
        r["charge"] = inherited["charge"] if r["charge"] is None else r["charge"]
        r["multiplicity"] = inherited["multiplicity"] if r["multiplicity"] is None else r["multiplicity"]
        r["spin_state_rationale"] = r["spin_state_rationale"] or inherited["rationale"]
        r["site_magnetization_json"] = r["site_magnetization_json"] or inherited["site_magnetization_json"]
        if not r["dft_plus_u_json"].strip() and inherited["dft_plus_u"]:
            r["dft_plus_u_json"] = json.dumps(inherited["dft_plus_u"]["u_minus_j_ev"])
            r["dft_plus_u_rationale"] = r["dft_plus_u_rationale"] or inherited["dft_plus_u"]["rationale"]
        ham = inherited["hamiltonian"]
        # Forces must come from the relaxation's Hamiltonian, or the "equilibrium" is not stationary.
        r["functional"] = ham.get("functional", r["functional"]) if r["functional"] == "PBE" else r["functional"]
        r["basis_set"] = ham.get("basis_set", r["basis_set"]) if r["basis_set"] == "DZVP-MOLOPT-SR-GTH" else r["basis_set"]
        r["cutoff_ry"] = max(int(ham.get("cutoff_ry", r["cutoff_ry"])), int(r["cutoff_ry"]))
        r["rel_cutoff_ry"] = int(ham.get("rel_cutoff_ry", r["rel_cutoff_ry"])) if r["rel_cutoff_ry"] == 60 else r["rel_cutoff_ry"]
        r["dispersion"] = bool(ham.get("dispersion", r["dispersion"])) if r["dispersion"] else r["dispersion"]
        r["dispersion_type"] = ham.get("dispersion_type", r["dispersion_type"]) if r["dispersion_type"] == "DFTD3" else r["dispersion_type"]
        warnings.append(f"Spin contract/DFT+U/Hamiltonian inherited from {structure.parent.name} (scaled to {n_cells} cell(s)).")
    r["site_magnetization_json"] = _supercell_magnetization(r["site_magnetization_json"], atoms, _ase_atoms(phonon.supercell), phonon)
    common = dict(
        **r, relax_only_elements="", fixed_elements="", fixed_indices="", strain_voigt=None,
        electric_field_v_per_m=0.0, field_direction="z", kpoints=kpoints, basis_set_file_name="BASIS_MOLOPT",
        potential_file_name="GTH_POTENTIALS", potential_prefix="GTH-PBE", basis_overrides_json="", potential_overrides_json="",
        eps_scf="1.0E-8", max_scf=150, max_iter=1, max_force="4.5E-4", rms_force="3.0E-4", external_pressure_bar=1.01325,
        sbatch_others="", overwrite=False, eps_default="1.0E-14",
    )
    return common, kpoints


def restart_file_name(kpoints: str, atoms) -> str:
    """CP2K wavefunction restart of an energy_force run: .wfn at Gamma, .kp with k points."""
    return "crystal-RESTART.wfn" if cc.gamma_only(kpoints if kpoints.strip().lower() != "auto" else cc.auto_kpoints(atoms)) else "crystal-RESTART.kp"


def write_displaced_inputs(ph_dir: Path, displaced_positions, first_index: int, max_core_hours_per_displacement: float, np_threads: int,
                           restart_name: str) -> list[dict[str, Any]]:
    """One disp-%04d input per displaced cell (numbered from first_index): the equilibrium input with new coordinates, SCF
    restarted from the equilibrium wavefunction (a fraction of a cold SCF)."""
    eq_input = (ph_dir / "equilibrium" / cc.JOB_INPUT).read_text()
    eq_wfn = (ph_dir / "equilibrium" / restart_name).resolve()  # k-point runs write the .kp restart
    disp_wall = int(float(max_core_hours_per_displacement) * 3600 / max(1, int(np_threads)))
    disp_cp2k_wall = max(600, disp_wall - max(600, disp_wall // 20))
    rows = []
    for index, positions in enumerate(displaced_positions, start=int(first_index)):
        task_dir = ph_dir / f"disp-{index:04d}"
        task_dir.mkdir(exist_ok=True)
        (task_dir / cc.JOB_INPUT).write_text(displaced_input(eq_input, positions, str(eq_wfn), disp_cp2k_wall))
        rows.append({"index": index, "dir": task_dir.name})
    return rows


def prepare_displaced_jobs(root: Path, structure: Path, ph_dir: Path, ideal, displaced_positions, kpoints: str, common: dict[str, Any],
                           warnings: list[str], *, max_core_hours_equilibrium: float, max_core_hours_per_displacement: float,
                           execution_mode: str, submit_approved: bool, restart_from_relaxation: bool) -> tuple[dict[str, Any], list[dict[str, Any]]]:
    """Equilibrium energy_force job of ``ideal`` (submitted or dry-run) and one disp-%04d input per displaced cell: the same
    Hamiltonian, only the coordinates change, SCF restarted from the equilibrium wavefunction (a fraction of a cold SCF)."""
    from ase.io import write

    write(str(ph_dir / "supercell_ideal.extxyz"), ideal, format="extxyz")
    restart_name = restart_file_name(kpoints, ideal)
    eq = cc._prepare_and_submit(
        root, atoms=ideal, job_dir=ph_dir / "equilibrium",
        source_structure={"path": _h._rel(root, structure), "sha256": cc._sha256(structure)},
        calculation="energy_force", max_core_hours=max_core_hours_equilibrium,
        execution_mode=execution_mode, submit_approved=submit_approved, warnings=warnings,
        wfn_restart_source=str(structure.parent / restart_name) if restart_from_relaxation else "", **common,
    )
    if not eq.get("ok"):
        return eq, []
    return eq, write_displaced_inputs(ph_dir, displaced_positions, 1, max_core_hours_per_displacement, common["np"], restart_name)


def _supercell_magnetization(spec_json: str, atoms, supercell_atoms, phonon) -> str:
    """Map a unit-cell magnetization spec onto the supercell (element form passes through)."""
    spec = cc._parse_json_arg(spec_json, "site_magnetization_json")
    if not spec or "indices" not in spec:
        return spec_json
    s2u = phonon.supercell.s2u_map if hasattr(phonon.supercell, "s2u_map") else None
    u2u = phonon.supercell.u2u_map if hasattr(phonon.supercell, "u2u_map") else None
    if s2u is None or u2u is None:
        raise ValueError("Cannot map index-based magnetizations onto the supercell; use the element form.")
    unit_moments = {int(k): float(v) for k, v in spec["indices"].items()}
    # phonopy supercell atoms are ordered unit-cell-atom-major: atom j of the supercell images unit atom u2u[s2u[j]].
    mapped = {}
    for j in range(len(supercell_atoms)):
        unit_index = int(u2u[int(s2u[j])])
        if unit_index in unit_moments:
            mapped[str(j)] = unit_moments[unit_index]
    return json.dumps({"indices": mapped})


def cs_mem_gb(mem) -> float | None:
    """'32G' -> 32.0 (crystal_spin's parser); None for '' or unparsable."""
    from Hypothesis_generation.skill_library.periodic_dft import crystal_spin as cs

    return cs._mem_gb(mem) if mem else None


def parent_job_mem(structure) -> str | None:
    """The Slurm memory of the crystal job whose final structure this is (its periodic_crystal_job.json), or None."""
    state = Path(structure).parent / cc.JOB_STATE
    try:
        return json.loads(state.read_text()).get("mem") or None
    except (OSError, ValueError):
        return None


def mpi_job_mem(mem: str, ranks: int) -> str:
    """MPI cp2k.psmp replicates data per rank: CuOEP (255 atoms, +U, Gamma, 800 Ry) peaked at 2.2 GB per rank, so 26 ranks at
    58G ran at 57.6G and one task died OUT_OF_MEMORY (2026-10-09). Floor the request at QUNTUR_MPI_MEM_PER_RANK_GB (2.5) x ranks."""
    import os
    from Hypothesis_generation.skill_library.periodic_dft import crystal_spin as cs

    floor = math.ceil(float(os.getenv("QUNTUR_MPI_MEM_PER_RANK_GB", "2.5")) * ranks)
    given = cs._mem_gb(mem)
    return mem if given is not None and given >= floor else f"{floor}G"


def _submit_array(ph_dir: Path, task_ids: list[int], manifest: dict[str, Any], dependency_job: Any = None) -> dict[str, Any]:
    settings = cc.crystal_runtime_settings()
    np_threads = int(manifest["np"])
    uses_mpi = bool(settings["mpi_run"])
    if uses_mpi:
        manifest["mem"] = mpi_job_mem(manifest["mem"], np_threads)
    script = ph_dir / "run_displacements.sbatch"
    script.write_text(_array_script(np_threads=np_threads, settings=settings))
    _h._ensure_submit_path_is_persistent(ph_dir)
    walltime_s = int(float(manifest["max_core_hours_per_displacement"]) * 3600 / np_threads)
    spec = _h._array_spec_from_task_ids(task_ids, int(manifest.get("array_parallelism") or 20))
    extra = " ".join(p for p in ["--nodes=1", "" if uses_mpi else f"--cpus-per-task={np_threads}", "--kill-on-invalid-dep=yes", f"--partition={manifest['partition']}" if manifest.get("partition") else ""] if p)
    submission = _h._submit_local_sbatch(
        script_path=script, cwd=ph_dir, job_name=f"cp2k_phonons_{ph_dir.name}"[:60], walltime=cc._walltime_text(walltime_s),
        ntasks=np_threads if uses_mpi else 1, mem=manifest["mem"], sbatch_others=extra, mem_option="--mem", array=spec,
        dependency=f"afterok:{dependency_job}" if dependency_job else "",
    )
    return {**submission, "task_ids": task_ids, "array_spec": spec, "submitted_at": _h._utc_now()}


def resubmit_failed_tasks(ph_dir: Path, manifest: dict[str, Any], bad: list[int]) -> dict[str, Any]:
    """Resubmit only the failed/missing disp-%04d tasks (one array), each continuing its own partial SCF when it wrote one."""
    for index in bad:
        task = ph_dir / f"disp-{index:04d}"
        # Continue this displacement's own partially converged SCF (walltime/SCF stop): .wfn at Gamma, .kp with k-points.
        # H01 cand02 2026-10-11: only the .wfn was looked for, so 22 cut k-point tasks would have restarted from the equilibrium
        # wavefunction and been cut again at the same CP2K walltime. Their own .kp files were complete (graceful stop).
        for own in (task / "crystal-RESTART.wfn", task / "crystal-RESTART.kp"):
            if own.is_file() and own.stat().st_size > 0 and (own.suffix == ".wfn" or cc.kp_restart_complete(own) is not False):
                text = (task / cc.JOB_INPUT).read_text()
                (task / cc.JOB_INPUT).write_text(re.sub(r"WFN_RESTART_FILE_NAME .*", f"WFN_RESTART_FILE_NAME {own.resolve()}", text))
                break
        for name in (cc.JOB_OUTPUT, "cp2k_crystal.exit_code", "cp2k_crystal.started"):
            (task / name).unlink(missing_ok=True)
    sub = _submit_array(ph_dir, bad, manifest)
    manifest.setdefault("array_submissions", []).append(sub)
    (ph_dir / PHONON_MANIFEST).write_text(json.dumps(manifest, indent=1))
    return sub


def _array_state(ph_dir: Path, manifest: dict[str, Any]) -> str:
    states = []
    for sub in manifest.get("array_submissions") or []:
        if sub.get("job_id"):
            states.append(_h._local_slurm_status(int(sub["job_id"]), cwd=ph_dir))
    if manifest.get("equilibrium_job_id"):
        states.append(_h._local_slurm_status(int(manifest["equilibrium_job_id"]), cwd=ph_dir))
    return _h._aggregate_slurm_states(states) if states else "NOT_SUBMITTED"


def _elapsed_minutes(text: str) -> float:
    days, _, clock = text.strip().rpartition("-")
    parts = [float(x) for x in clock.split(":")]
    while len(parts) < 3:
        parts.insert(0, 0.0)
    return (float(days or 0) * 24 + parts[0]) * 60 + parts[1] + parts[2] / 60


def cancel_stalled_tasks(ph_dir: Path, manifest: dict[str, Any], stall_minutes: float = 10.0) -> list[int]:
    """Cancel array tasks wedged in CONFIGURING (node prolog hang) that never started CP2K.

    On bosque, 7 of 210 C1 displacement tasks sat in CONFIGURING for 27 min holding
    array slots; cancelled tasks are resubmitted by the collector's retry round.
    """
    import subprocess

    cancelled = []
    for sub in manifest.get("array_submissions") or []:
        if not sub.get("job_id"):
            continue
        out = subprocess.run(["squeue", "-h", "-j", str(sub["job_id"]), "-t", "CF", "-o", "%i %M"],
                             capture_output=True, text=True, check=False).stdout
        for line in out.splitlines():
            parts = line.split()
            if len(parts) != 2 or "_" not in parts[0]:
                continue
            task = parts[0].split("_", 1)[1]
            if not task.isdigit() or _elapsed_minutes(parts[1]) < stall_minutes:
                continue
            if (ph_dir / f"disp-{int(task):04d}" / "cp2k_crystal.started").exists():
                continue
            subprocess.run(["scancel", parts[0]], check=False)
            cancelled.append(int(task))
    if cancelled:
        manifest.setdefault("cancelled_stalled_tasks", []).extend(cancelled)
        (ph_dir / PHONON_MANIFEST).write_text(json.dumps(manifest, indent=1))
    return cancelled


def _wait_for_phonons(ph_dir: Path, manifest: dict[str, Any], max_wait_seconds: float, runtime) -> dict[str, Any]:
    started = _h._monotonic()
    while True:
        cancel_stalled_tasks(ph_dir, manifest)
        state = _array_state(ph_dir, manifest)
        elapsed = _h._monotonic() - started
        if state not in _h.ACTIVE_SLURM_STATUSES:
            return {"scheduler_state": state, "waited_seconds": round(elapsed, 1), "timed_out": False}
        if elapsed >= max_wait_seconds or _h._periodic_monitor_interrupted(runtime):
            return {"scheduler_state": state, "waited_seconds": round(elapsed, 1), "timed_out": True}
        _h._sleep(min(120.0, max(1.0, max_wait_seconds - elapsed)))


def _build_phonons(ph_dir: Path, manifest: dict[str, Any], forces: list[np.ndarray], eq_forces: np.ndarray):
    import phonopy

    # The symmetry that reduced the displacements must also be used to rebuild the force constants:
    # phonopy.load defaults to symprec 1e-5, which reads a relaxed P2_1/c cell as P1 ("forces not enough").
    phonon = phonopy.load(str(ph_dir / "phonopy_disp.yaml"), produce_fc=False, log_level=0, symprec=float(manifest.get("symprec", 1e-3)))
    # Subtract the equilibrium residual forces: removes the leftover gradient of a
    # not-perfectly-stationary cell to first order (standard drift correction).
    phonon.forces = np.array([f - eq_forces for f in forces]) * HARTREE_PER_BOHR_TO_EV_PER_ANG
    phonon.produce_force_constants()
    raw = _noise_diagnostic(phonon)
    phonon.symmetrize_force_constants()
    phonon.save(filename=str(ph_dir / PHONOPY_PARAMS), settings={"force_constants": True})
    return phonon, raw


def _noise_diagnostic(phonon) -> dict[str, Any]:
    """How far the RAW force constants violate translational invariance (grid/egg-box + SCF noise).

    Symmetrization hides the noise; unsymmetrized acoustic frequencies of tens of
    cm-1 mean the lowest optical modes (the ones that matter at 5-20 K) are unreliable.
    """
    fc = np.array(phonon.force_constants)
    asr = np.abs(fc.sum(axis=1)).max()
    diag = max(np.abs(np.einsum("iiab->iab", fc)).max(), 1e-12)
    phonon.run_qpoints([[0.0, 0.0, 0.0]])
    freqs = phonon.qpoints.frequencies[0] * THZ_TO_CM1
    acoustic = np.sort(np.abs(freqs))[:3]
    worst = float(acoustic.max())
    return {
        "asr_violation_relative": round(float(asr / diag), 5),
        "raw_acoustic_frequencies_cm1": [round(float(f), 2) for f in acoustic],
        "verdict": "clean" if worst < 10 else ("noisy_low_modes" if worst < 30 else "too_noisy"),
        "note": (
            "Raw (pre-symmetrization) acoustic frequencies measure numerical noise. >10 cm-1: treat optical modes "
            "below ~3x that value as uncertain; >30 cm-1: tighten EPS_SCF/EPS_DEFAULT or raise the cutoff."
        ),
    }


def harmonic_thermodynamics(freqs_thz, weights, temperatures, cutoff_thz: float = 1e-3) -> list[dict[str, float]]:
    """F, S, Cv per mole of cells from mesh frequencies, overflow-free (phonopy returns NaN Cv at ~5 K
    when high-frequency modes overflow exp(hw/kT))."""
    h, kb, na = 6.62607015e-34, 1.380649e-23, 6.02214076e23
    f = np.asarray(freqs_thz, dtype=float)
    w = np.asarray(weights, dtype=float)[:, None] * np.ones_like(f)
    keep = f > cutoff_thz
    e = h * f[keep] * 1e12
    w = w[keep] / np.asarray(weights, dtype=float).sum()
    rows = []
    for t in temperatures:
        zpe = (w * e / 2).sum()
        if t <= 0:
            rows.append({"T_K": float(t), "free_energy_kJ_mol": round(float(zpe * na / 1000), 4), "entropy_J_K_mol": 0.0, "cv_J_K_mol": 0.0})
            continue
        x = e / (kb * t)
        q = np.exp(-np.minimum(x, 700.0))
        free = zpe + (w * kb * t * np.log1p(-q)).sum()
        entropy = (w * kb * (x * q / (1 - q) - np.log1p(-q))).sum()
        cv = (w * kb * x**2 * q / (1 - q) ** 2).sum()
        rows.append({"T_K": float(t), "free_energy_kJ_mol": round(float(free * na / 1000), 4),
                     "entropy_J_K_mol": round(float(entropy * na), 4), "cv_J_K_mol": round(float(cv * na), 4)})
    return rows


def _gamma_modes(phonon, near_zero_cm1: float = 15.0) -> dict[str, Any]:
    phonon.run_qpoints([[0.0, 0.0, 0.0]], with_eigenvectors=True)
    freqs = phonon.qpoints.frequencies[0] * THZ_TO_CM1
    acoustic = set(np.argsort(np.abs(freqs))[:3].tolist())
    imaginary = [float(f) for i, f in enumerate(freqs) if f < -near_zero_cm1 and i not in acoustic]
    return {
        "frequencies_cm1": [round(float(f), 3) for f in freqs],
        "acoustic_mode_indices": sorted(acoustic),
        "acoustic_frequencies_cm1": [round(float(freqs[i]), 3) for i in sorted(acoustic)],
        "imaginary_modes_cm1": [round(f, 3) for f in imaginary],
        "n_imaginary": len(imaginary),
        "lowest_optical_cm1": round(float(min(f for i, f in enumerate(freqs) if i not in acoustic)), 3) if len(freqs) > 3 else None,
    }


def collect_periodic_dft_phonons(
    phonon_dir: Annotated[str, "Relative phonon directory (contains phonon_manifest.json)."],
    wait: Annotated[bool, "Wait until the equilibrium job and the displacement array are terminal."] = False,
    max_wait_hours: Annotated[float, "Upper bound on waiting."] = 72.0,
    resubmit_failed: Annotated[bool, "Resubmit ONLY missing/failed displacements (one bounded retry round per call)."] = True,
    temperatures_k: Annotated[str, "Temperatures for thermodynamics (K), e.g. '5 20 77 150 300'."] = "5 20 77 150 300",
    q_mesh: Annotated[str, "q mesh for DOS/thermodynamics, e.g. '4 4 4'."] = "4 4 4",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Collect displacement forces, build force constants, report Gamma modes, imaginary modes and thermodynamics."""
    root = _h._root(runtime)
    try:
        ph_dir = _h._resolve_path(root, phonon_dir, must_exist=True, file_ok=False)
        manifest = cc._read_json(ph_dir / PHONON_MANIFEST)
        if not manifest:
            raise FileNotFoundError(f"No {PHONON_MANIFEST} in {phonon_dir}.")
        wait_info = _wait_for_phonons(ph_dir, manifest, float(max_wait_hours) * 3600.0, runtime) if wait else None
        if not wait:
            # Non-blocking pollers (run_csp_funnel_workflow) also free tasks wedged in CONFIGURING: the
            # cancelled tasks fail and the retry round below resubmits them (urea phonons, 2026-10-02).
            cancel_stalled_tasks(ph_dir, manifest)
        state = _array_state(ph_dir, manifest)
        kinds = manifest.get("kind_to_element") or {}
        eq_forces, eq_info = _task_forces(ph_dir / "equilibrium", kinds)
        rows, forces, bad = [], [], []
        for row in manifest["displacements"]:
            f, info = _task_forces(ph_dir / row["dir"], kinds)
            rows.append({**row, **info})
            if f is None:
                bad.append(row["index"])
            else:
                forces.append(f)
        active = state in _h.ACTIVE_SLURM_STATUSES
        walls = [r.get("wall_seconds") or 0.0 for r in rows] + [eq_info.get("wall_seconds") or 0.0]
        summary: dict[str, Any] = {
            "core_hours_used": round(sum(walls) * int(manifest.get("np") or 1) / 3600.0, 2),
            "planned_core_hours_cap": manifest.get("planned_core_hours_cap"),
            "phonon_dir": _h._rel(root, ph_dir),
            "scheduler_state": state,
            "equilibrium": eq_info,
            "n_displacements": manifest["n_displacements"],
            "completed_displacements": len(forces),
            "failed_or_missing": bad if not active else [],
            "wait": wait_info,
        }
        if eq_forces is not None:
            residual = float(np.linalg.norm(eq_forces, axis=1).max())
            summary["equilibrium_max_residual_force_ha_bohr"] = round(residual, 6)
            if residual > STATIONARY_MAX_FORCE_HA_BOHR:
                summary["warning"] = (
                    f"Equilibrium residual force {residual:.2e} Ha/bohr > {STATIONARY_MAX_FORCE_HA_BOHR:g}: the cell is not "
                    "stationary; low-frequency/imaginary modes are unreliable. Relax further (tight_for_phonons=True)."
                )
        if active:
            summary["status"] = "running"
            return {"ok": True, **summary}
        if bad and eq_forces is not None:
            retries = [sub for sub in manifest.get("array_submissions", [])[1:]]
            if resubmit_failed and len(retries) < 2:
                sub = resubmit_failed_tasks(ph_dir, manifest, bad)
                if wait and sub.get("ok"):
                    remaining = float(max_wait_hours) - (wait_info or {}).get("waited_seconds", 0.0) / 3600.0
                    return collect_periodic_dft_phonons(
                        phonon_dir, wait=True, max_wait_hours=max(0.0, remaining), resubmit_failed=resubmit_failed,
                        temperatures_k=temperatures_k, q_mesh=q_mesh, runtime=runtime,
                    )
                summary.update(status="resubmitted_failed", resubmission=sub)
                return {"ok": True, **summary, "next_step": "collect_periodic_dft_phonons again (wait=True)."}
            summary["status"] = "incomplete"
            return {"ok": False, **summary, "error": f"{len(bad)} displacements failed after retries: {bad[:20]}"}
        if eq_forces is None:
            summary["status"] = "equilibrium_failed"
            eq_state = _h._local_slurm_status(int(manifest["equilibrium_job_id"]), cwd=ph_dir) if manifest.get("equilibrium_job_id") else None
            hint = (
                "OUT_OF_MEMORY: raise mem (the 800 Ry + finer-XC phonon-grade grid needs ~1.4 GB per MPI rank more "
                "than the 600 Ry grid on a 140-atom cell; 16 ranks took ~40 GB), delete this phonon directory and rerun."
                if eq_state == "OUT_OF_MEMORY" else "Diagnose its job directory (slurm-*.out, cp2k_crystal.out)."
            )
            return {"ok": False, **summary, "equilibrium_scheduler_state": eq_state,
                    "error": f"The equilibrium SCF did not finish; nothing can be built. {hint}"}
        eq_text = (ph_dir / "equilibrium" / cc.JOB_INPUT).read_text()
        summary["hamiltonian"] = {
            "xc": (re.search(r"&XC_FUNCTIONAL\s+(\S+)", eq_text) or [None, None])[1],
            "dispersion_d3": "&VDW_POTENTIAL" in eq_text,
            "cutoff_ry": int((re.search(r"^\s*CUTOFF\s+(\d+)", eq_text, re.M) or [None, 0])[1]),
            "dft_plus_u": "&DFT_PLUS_U" in eq_text,
        }
        phonon, noise = _build_phonons(ph_dir, manifest, forces, eq_forces)
        summary["numerical_noise"] = noise
        gamma = _gamma_modes(phonon)
        mesh = [int(v) for v in q_mesh.split()]
        phonon.run_mesh(mesh)
        temps = [float(t) for t in temperatures_k.split()]
        thermo = harmonic_thermodynamics(phonon.mesh.frequencies, phonon.mesh.weights, temps)
        summary.update(
            status="completed",
            phonopy_params=_h._rel(root, ph_dir / PHONOPY_PARAMS),
            gamma=gamma,
            thermodynamics=thermo,
        )
        (ph_dir / PHONON_SUMMARY).write_text(json.dumps(summary, indent=1, default=str))
        (ph_dir / "gamma_modes.csv").write_text(
            "mode,frequency_cm1\n" + "\n".join(f"{i},{f}" for i, f in enumerate(gamma["frequencies_cm1"]))
        )
        summary["next_step"] = (
            "generate_phonon_thermal_snapshots (quantum harmonic ensemble at T) and/or export_phonon_mode_displacements, "
            "then carve identical clusters (extract_molecular_cluster_from_crystal with reuse_selection_from) for ORCA."
            if gamma["n_imaginary"] == 0
            else "Imaginary modes: the structure is not a minimum (or not converged). Relax further before using the modes."
        )
        return {"ok": True, **summary}
    except Exception as exc:
        return _h._error(exc)


def experimental_ueq(cif_path: Path) -> tuple[list[dict[str, Any]], float | None]:
    """Every unit-cell site of a CIF with its label, element, fractional position and U_eq (A^2)."""
    import gemmi

    small = gemmi.read_small_structure(str(cif_path))
    a = np.array(small.cell.orth.mat.tolist())  # columns = lattice vectors
    metric = a.T @ a
    recip = np.array([small.cell.reciprocal().a, small.cell.reciprocal().b, small.cell.reciprocal().c])
    ueq = {}
    for site in small.sites:
        an = site.aniso
        if an.nonzero():
            u = np.array([[an.u11, an.u12, an.u13], [an.u12, an.u22, an.u23], [an.u13, an.u23, an.u33]])
            n = np.diag(recip)
            ueq[site.label] = (float(np.trace(n @ u @ n @ metric) / 3.0), True)
        else:
            ueq[site.label] = (float(site.u_iso), False)
    sites = [
        {"label": s.label, "element": s.element.name, "fract": np.array(s.fract.tolist()), "ueq": ueq[s.label][0], "aniso": ueq[s.label][1]}
        for s in small.get_all_unit_cell_sites()
    ]
    temperature = None
    doc = gemmi.cif.read(str(cif_path)).sole_block()
    for tag in ("_diffrn_ambient_temperature", "_cell_measurement_temperature"):
        value = doc.find_value(tag)
        if value and value not in {"?", "."}:
            temperature = float(re.sub(r"\(.*\)", "", value))
            break
    return sites, temperature


def compare_phonon_adps_with_experiment(
    phonon_dir: Annotated[str, "Completed phonon directory (phonopy_params.yaml)."],
    cif_path: Annotated[str, "Experimental CIF with anisotropic displacement parameters (the X-ray structure of this crystal)."],
    temperature_k: Annotated[float, "ADP temperature; 0 = the CIF's _diffrn_ambient_temperature."] = 0.0,
    q_mesh: Annotated[str, "q mesh for the thermal displacement matrices."] = "4 4 4",
    min_frequency_cm1: Annotated[float, "Ignore modes below this (acoustic modes at Gamma diverge)."] = 5.0,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Validate phonons against experiment: computed vs measured U_eq of every non-H atom at the diffraction temperature."""
    root = _h._root(runtime)
    try:
        ph_dir = _h._resolve_path(root, phonon_dir, must_exist=True, file_ok=False)
        cif = _h._resolve_path(root, cif_path, must_exist=True, dir_ok=False)
        phonon = _load_phonon(ph_dir)
        sites, cif_t = experimental_ueq(cif)
        temp = float(temperature_k) or cif_t
        if not temp:
            raise ValueError("The CIF has no diffraction temperature; pass temperature_k.")
        phonon.run_mesh([int(v) for v in q_mesh.split()], with_eigenvectors=True, is_mesh_symmetry=False)
        phonon.run_thermal_displacement_matrices(temperatures=[temp], freq_min=float(min_frequency_cm1) / THZ_TO_CM1)
        u_calc = np.array(phonon.thermal_displacement_matrices.thermal_displacement_matrices[0])
        cell = _ase_atoms(phonon.unitcell)
        frac = cell.get_scaled_positions()
        symbols = cell.get_chemical_symbols()
        rows = []
        for site in sites:
            if site["element"] == "H" or not site["aniso"]:
                continue
            d = frac - site["fract"]
            d -= np.round(d)
            dist = np.linalg.norm(d @ cell.cell.array, axis=1)
            dist[[sym != site["element"] for sym in symbols]] = np.inf
            j = int(np.argmin(dist))
            if dist[j] > 0.5:
                continue
            ueq_calc = float(np.trace(u_calc[j]) / 3.0)
            rows.append({"label": site["label"], "element": site["element"], "atom_index": j, "ueq_exp": round(site["ueq"], 5),
                         "ueq_calc": round(ueq_calc, 5), "ratio": round(ueq_calc / site["ueq"], 3)})
        if not rows:
            raise ValueError("No non-H atoms with anisotropic ADPs could be matched to the phonon cell.")
        by_label = {}
        for r in rows:
            by_label.setdefault(r["label"], r)
        unique = list(by_label.values())
        ratios = np.array([r["ratio"] for r in unique])
        per_element = {}
        for el in sorted({r["element"] for r in unique}):
            vals = np.array([r["ratio"] for r in unique if r["element"] == el])
            per_element[el] = round(float(vals.mean()), 3)
        supercell = np.array(phonon.supercell_matrix)
        result = {
            "temperature_k": temp, "q_mesh": q_mesh, "n_sites_compared": len(unique),
            "median_ratio_calc_over_exp": round(float(np.median(ratios)), 3),
            "ratio_range": [round(float(ratios.min()), 3), round(float(ratios.max()), 3)],
            "mean_ratio_by_element": per_element,
            "sites": unique,
            "interpretation": (
                "Ratios ~0.7-1.0 are typical of good harmonic phonons (experiment adds static disorder and absorption "
                "errors, so calc < exp is normal). Ratios << 0.5 point to missing low-frequency/acoustic motion "
                "(e.g. a 1x1x1 force-constant cell interpolated to q != 0) or a too-stiff structure; ratios > 1.3 point to "
                "spuriously soft modes."
            ),
        }
        noise = (cc._read_json(ph_dir / PHONON_SUMMARY).get("numerical_noise") or {})
        if noise.get("verdict") not in {None, "clean"}:
            result["caveat"] = (
                f"The phonons are numerically {noise['verdict']} (raw acoustic {noise.get('raw_acoustic_frequencies_cm1')} cm-1): "
                "noise stiffens the soft modes and lowers U_eq (C1: ratio 0.49 at 600 Ry vs 0.88 on the phonon-grade grid). Fix the noise first."
            )
        elif np.allclose(supercell, np.eye(3)):
            result["caveat"] = "1x1x1 force constants: acoustic/low-q motion is only interpolated, so heavy-atom U_eq at 100+ K may be somewhat underestimated."
        (ph_dir / "adp_comparison.json").write_text(json.dumps(result, indent=1))
        return {"ok": True, **{k: v for k, v in result.items() if k != "sites"}, "worst_sites": sorted(unique, key=lambda r: abs(np.log(r["ratio"])))[-5:]}
    except Exception as exc:
        return _h._error(exc)


# --------------------------------------------------------------------------- #
# Thermal ensembles and mode displacements
# --------------------------------------------------------------------------- #


def _load_phonon(ph_dir: Path):
    import phonopy

    params = ph_dir / PHONOPY_PARAMS
    if not params.is_file():
        raise FileNotFoundError(f"{params.name} missing: collect the phonons first.")
    symprec = float(cc._read_json(ph_dir / PHONON_MANIFEST).get("symprec") or cc._read_json(ph_dir / FC_PROVENANCE).get("symprec") or 1e-5)
    return phonopy.load(str(params), log_level=0, symprec=symprec)


def generate_phonon_thermal_snapshots(
    phonon_dir: Annotated[str, "Completed phonon directory (has phonopy_params.yaml)."],
    temperature_k: Annotated[float, "Temperature (K). Quantum sampling includes zero-point motion, dominant at 5-20 K."] = 20.0,
    n_snapshots: Annotated[int, "Number of snapshot files (with antithetic_pairs: n/2 random draws + their mirrors, rounded up to even)."] = 16,
    random_seed: Annotated[int, "Seed (record it; reuse it for reproducible ensembles)."] = 20260929,
    distribution: Annotated[str, "'quantum' (Bose-Einstein + zero point, default) or 'classical'."] = "quantum",
    cutoff_frequency_cm1: Annotated[float, "Exclude modes below this |frequency| from the sampling. 0 = automatic: 3x the measured numerical noise (raw acoustic frequencies), at least 5 cm-1."] = 0.0,
    antithetic_pairs: Annotated[bool, "Also write the mirrored snapshot -u for each u (cancels first-order noise in averages)."] = True,
    output_dir: Annotated[str, "Output directory; default <phonon_dir>/thermal_<T>K."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Harmonic thermal ensemble of the real crystal: displaced cells (same atom order) for ensemble-averaged properties."""
    root = _h._root(runtime)
    try:
        from ase.io import write
        from phonopy.phonon.random_displacements import RandomDisplacements

        ph_dir = _h._resolve_path(root, phonon_dir, must_exist=True, file_ok=False)
        summary = cc._read_json(ph_dir / PHONON_SUMMARY)
        if (summary.get("gamma") or {}).get("n_imaginary"):
            raise ValueError("The phonons have imaginary modes: a harmonic ensemble would be meaningless. Relax further first.")
        phonon = _load_phonon(ph_dir)
        if float(cutoff_frequency_cm1) <= 0:
            noise = max((summary.get("numerical_noise") or {}).get("raw_acoustic_frequencies_cm1") or [0.0])
            cutoff_frequency_cm1 = max(5.0, 3.0 * float(noise))
        rd = RandomDisplacements(
            phonon.supercell, phonon.primitive, phonon.force_constants,
            dist_func=distribution, cutoff_frequency=float(cutoff_frequency_cm1) / THZ_TO_CM1,
        )
        draws = max(1, math.ceil(int(n_snapshots) / 2)) if antithetic_pairs else max(1, int(n_snapshots))
        rd.run(float(temperature_k), number_of_snapshots=draws, random_seed=int(random_seed))
        gamma = summary.get("gamma") or {}
        excluded = [
            f for i, f in enumerate(gamma.get("frequencies_cm1") or [])
            if i not in set(gamma.get("acoustic_mode_indices") or []) and abs(f) < float(cutoff_frequency_cm1)
        ]
        disps = np.array(rd.u)
        if antithetic_pairs:
            disps = np.concatenate([disps, -disps])
        out = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else ph_dir / f"thermal_{temperature_k:g}K")
        out.mkdir(parents=True, exist_ok=True)
        base = _ase_atoms(phonon.supercell)
        files = []
        for k, u in enumerate(disps):
            snap = base.copy()
            snap.positions = base.positions + u
            path = out / f"snapshot_{k:04d}.extxyz"
            write(str(path), snap, format="extxyz")
            files.append(_h._rel(root, path))
        symbols = np.array(base.get_chemical_symbols())
        rms = {str(el): round(float(np.sqrt((disps[:, symbols == el, :] ** 2).sum(axis=2).mean())), 5) for el in sorted(set(symbols))}
        manifest = {
            "phonon_dir": _h._rel(root, ph_dir), "temperature_k": float(temperature_k), "distribution": distribution,
            "random_seed": int(random_seed), "n_snapshots": len(files), "antithetic_pairs": bool(antithetic_pairs),
            "cutoff_frequency_cm1": float(cutoff_frequency_cm1),
            "excluded_optical_modes_cm1": excluded,  # not sampled: lower cutoff_frequency_cm1 if they matter
            "rms_displacement_angstrom_by_element": rms,
            "max_displacement_angstrom": round(float(np.linalg.norm(disps, axis=2).max()), 5),
            "reference_cell": _h._rel(root, ph_dir / "supercell_ideal.extxyz"),
            "snapshots": files,
            "how_to_average": (
                "Carve each snapshot with extract_molecular_cluster_from_crystal(reuse_selection_from=<manifest carved from "
                "supercell_ideal.extxyz>), compute the property with ONE fixed protocol, and report mean and standard error; "
                "the spread is the static vibrational distribution, not a coherence time."
            ),
        }
        (out / "thermal_snapshots_manifest.json").write_text(json.dumps(manifest, indent=1))
        return {"ok": True, **{k: v for k, v in manifest.items() if k != "snapshots"}, "first_snapshots": files[:4], "manifest": _h._rel(root, out / "thermal_snapshots_manifest.json")}
    except Exception as exc:
        return _h._error(exc)


def mode_mean_square_q(freq_cm1: float, temperature_k: float) -> float:
    """<Q^2>_T in amu*A^2 for a harmonic mode (quantum): hbar/(2 w) coth(hbar w / 2kT)."""
    hbar = 1.054571817e-34
    kb = 1.380649e-23
    amu_a2 = 1.66053906660e-27 * 1e-20
    omega = 2 * math.pi * 2.99792458e10 * abs(freq_cm1)
    if omega == 0:
        return float("inf")
    x = hbar * omega / (2 * kb * temperature_k) if temperature_k > 0 else float("inf")
    coth = 1.0 if x > 50 else 1.0 / math.tanh(x)
    return hbar / (2 * omega) * coth / amu_a2


TAIL_MODE_BASE = 100000  # mode numbers of the stochastic tail pairs in a mode manifest (cluster members mode_100000_p/m, ...)


def _supercell_phonon(phonon):
    """The force-constant supercell as its own 1x1x1 phonopy object: its Gamma modes are every mode commensurate with the
    supercell -- the mode set generate_phonon_thermal_snapshots samples (identical to the primitive Gamma modes for 1x1x1)."""
    import phonopy
    from phonopy.harmonic.force_constants import compact_fc_to_full_fc

    fc = phonon.force_constants
    if fc.shape[0] != fc.shape[1]:
        fc = compact_fc_to_full_fc(phonon.primitive, fc)
    sc = phonopy.Phonopy(phonon.supercell, supercell_matrix=np.eye(3, dtype=int), primitive_matrix=np.eye(3))
    sc.force_constants = fc
    return sc


def first_shell_internal_weight(u_shell: np.ndarray, positions: np.ndarray) -> float:
    """|u|^2 of a coordination-shell displacement after removing its best rigid translation + rotation (A^2).

    A rigid motion of the metal + donors barely changes a spin-Hamiltonian tensor (a rotation changes lab components only at
    O(angle^2 * anisotropy)); the low-frequency lattice modes that dominate the raw first-shell amplitude are mostly that."""
    r = positions - positions.mean(axis=0)
    basis = []
    for a in range(3):
        t = np.zeros_like(r)
        t[:, a] = 1.0
        axis = np.zeros(3)
        axis[a] = 1.0
        basis += [t.ravel(), np.cross(axis, r).ravel()]
    b = np.array(basis).T
    resid = u_shell.ravel() - b @ np.linalg.lstsq(b, u_shell.ravel(), rcond=None)[0]
    return float(resid @ resid)


def _first_shell_cell_atoms(root: Path, cluster_manifest: str, n_cell_atoms: int) -> tuple[list[int], np.ndarray]:
    """Cell indices and (unwrapped) cluster positions of the metal + bonded donors of a carved cluster."""
    from ase.data import covalent_radii
    from ase.io import read

    man = json.loads(_h._resolve_path(root, cluster_manifest, must_exist=True, dir_ok=False).read_text())
    if int(man["cell_atoms"]) != n_cell_atoms:
        raise ValueError(f"rank_cluster_manifest was carved from a {man['cell_atoms']}-atom cell, the mode cell has {n_cell_atoms} atoms.")
    cluster = read(str(root / man["qm_xyz"]))
    origin = man["qm_atom_origin_cell_index_and_image"]
    center = next(k for k, o in enumerate(origin) if o[0] == int(man["center_index"]))
    rc = covalent_radii[cluster.numbers]
    d = np.linalg.norm(cluster.positions - cluster.positions[center], axis=1)
    n_central = _formula_atom_count(man["qm_molecules"][0]["formula"])
    shell = [center] + [k for k in range(n_central) if k != center and d[k] <= 1.25 * (rc[k] + rc[center])]
    return [int(origin[k][0]) for k in shell], cluster.positions[shell]


def export_phonon_mode_displacements(
    phonon_dir: Annotated[str, "Completed phonon directory."],
    mode_indices: Annotated[str, "Gamma mode indices (0-based, ascending frequency order as in gamma_modes.csv), e.g. '3 4 5'. Empty = all optical modes below max_frequency_cm1."] = "",
    max_frequency_cm1: Annotated[float, "With no mode_indices and select_top_n=0: export optical modes up to this frequency (soft modes carry the thermal response)."] = 200.0,
    amplitude_q: Annotated[float, "Displacement along the mass-weighted normal coordinate Q (sqrt(amu)*A); ignored when thermal_amplitude_k > 0."] = 0.05,
    temperatures_k: Annotated[str, "Temperatures for <Q^2>_T in the manifest."] = "5 20",
    output_dir: Annotated[str, "Output directory; default <phonon_dir>/mode_displacements."] = "",
    select_top_n: Annotated[int, "Second-order thermal average: keep the N modes with the largest first-shell INTERNAL amplitude <Q_k^2>_T |u_shell,k|^2 "
                                 "(metal + donors of rank_cluster_manifest, rigid translation/rotation removed), ranked over every optical mode >= "
                                 "min_frequency_cm1 (or over mode_indices). 0 = no ranking."] = 0,
    rank_cluster_manifest: Annotated[str, "cluster_manifest.json carved on the mode cell (defines the first shell); required with select_top_n."] = "",
    thermal_amplitude_k: Annotated[float, "> 0: each mode's step is sqrt(3 <Q_k^2>_T) at this temperature (3-point Gauss-Hermite node: X0 + 1/2 "
                                          "<Q^2> (X+ - 2X0 + X-)/Q^2 is then the exact thermal mean of that mode's 1D cut through 5th order)."] = 0.0,
    min_frequency_cm1: Annotated[float, "Exclude modes below this frequency (use the snapshot ensemble's cutoff_frequency_cm1 to compare with it)."] = 0.0,
    mode_cell: Annotated[str, "'primitive' (Gamma modes of the phonopy primitive cell) or 'supercell' (every mode commensurate with the force-constant "
                              "supercell, displaced supercells: the mode set generate_phonon_thermal_snapshots samples; same as primitive for 1x1x1)."] = "primitive",
    tail_pairs: Annotated[int, "With select_top_n: also write this many antithetic pairs of cells displaced by +/- sum_k z_k sqrt(<Q_k^2>_T) e_k/sqrt(m) "
                               "over the UNSELECTED modes (z_k = +/-1): an unbiased (Hutchinson) estimate of their second-order shift, so the "
                               "truncation is corrected instead of guessed. 0 = none."] = 0,
    random_seed: Annotated[int, "Seed of the tail signs (record it)."] = 20261003,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """+/-Q displaced cells per Gamma mode with <Q^2>_T, for dX/dQ and <X>_T = X0 + 1/2 sum d2X/dQ2 <Q^2>_T (optionally the top-N
    modes by first-shell internal amplitude, with Gauss-Hermite thermal steps, plus stochastic tail pairs for the rest)."""
    root = _h._root(runtime)
    try:
        from ase.io import write

        ph_dir = _h._resolve_path(root, phonon_dir, must_exist=True, file_ok=False)
        phonon = _load_phonon(ph_dir)
        if mode_cell not in {"primitive", "supercell"}:
            raise ValueError("mode_cell must be 'primitive' or 'supercell'.")
        work = _supercell_phonon(phonon) if mode_cell == "supercell" else phonon
        work.run_qpoints([[0.0, 0.0, 0.0]], with_eigenvectors=True)
        freqs = work.qpoints.frequencies[0] * THZ_TO_CM1
        vecs = work.qpoints.eigenvectors[0]
        order = np.argsort(freqs)
        acoustic = set(_gamma_modes(phonon)["acoustic_mode_indices"]) if mode_cell == "primitive" else set(np.argsort(np.abs(freqs))[:3].tolist())
        temps = [float(t) for t in temperatures_k.split()]
        if mode_indices.strip():
            chosen = [int(v) for v in mode_indices.replace(",", " ").split()]
        elif int(select_top_n) > 0:
            chosen = [int(i) for i in order if int(i) not in acoustic and freqs[i] > 0]
        else:
            chosen = [int(i) for i in order if int(i) not in acoustic and 0 < freqs[i] <= max_frequency_cm1]
        chosen = [m for m in chosen if m not in acoustic and freqs[m] >= float(min_frequency_cm1)]
        cell_obj = work.primitive
        base = _ase_atoms(cell_obj)
        masses = np.array(cell_obj.masses)

        def displacement(m: int) -> np.ndarray:
            # Cartesian displacement per atom for unit Q: e_i / sqrt(m_i); eigenvector is real at Gamma up to a phase.
            e = vecs[:, m].reshape(-1, 3)
            e = np.real(e * np.exp(-1j * np.angle(e.flat[np.argmax(np.abs(e))])))
            return e / np.sqrt(masses)[:, None]

        t_rank = float(thermal_amplitude_k) if float(thermal_amplitude_k) > 0 else (temps[0] if temps else 20.0)
        selection = None
        weights = {}
        if int(select_top_n) > 0:
            if not rank_cluster_manifest.strip():
                raise ValueError("select_top_n needs rank_cluster_manifest (a cluster carved on the mode cell).")
            shell, shell_xyz = _first_shell_cell_atoms(root, rank_cluster_manifest, len(base))
            weights = {m: mode_mean_square_q(float(freqs[m]), t_rank) * first_shell_internal_weight(displacement(m)[shell], shell_xyz) for m in chosen}
            total = sum(weights.values())
            chosen = sorted(chosen, key=lambda m: -weights[m])[: int(select_top_n)]
            selection = {"criterion": "first-shell internal amplitude <Q_k^2>_T |u_shell,k|^2 (rigid translation+rotation removed)",
                         "temperature_k": t_rank, "first_shell_cell_atoms": shell, "n_candidates": len(weights), "n_selected": len(chosen),
                         "captured_weight_fraction": round(sum(weights[m] for m in chosen) / total, 4) if total > 0 else None}
        out = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else ph_dir / "mode_displacements")
        out.mkdir(parents=True, exist_ok=True)
        write(str(out / "reference_cell.extxyz"), base, format="extxyz")
        modes, large = [], []
        for rank, m in enumerate(chosen):
            u = displacement(m)
            q_step = math.sqrt(3.0 * mode_mean_square_q(float(freqs[m]), float(thermal_amplitude_k))) if float(thermal_amplitude_k) > 0 else float(amplitude_q)
            entry = {"mode": m, "frequency_cm1": round(float(freqs[m]), 3), "amplitude_q": q_step, "rank": rank, "files": {}}
            if weights:
                entry["first_shell_weight_A2"] = weights[m]
            for sign, tag in ((1, "p"), (-1, "m")):
                cell = base.copy()
                cell.positions = base.positions + sign * q_step * u
                path = out / f"mode_{m:04d}_{tag}.extxyz"
                write(str(path), cell, format="extxyz")
                entry["files"][tag] = _h._rel(root, path)
            entry["max_atom_displacement_angstrom"] = round(float(q_step * np.linalg.norm(u, axis=1).max()), 4)
            if entry["max_atom_displacement_angstrom"] > 0.3:
                large.append(m)
            entry["mean_square_q_amu_A2"] = {f"{t:g}K": mode_mean_square_q(float(freqs[m]), t) for t in temps}
            modes.append(entry)
        tail = None
        if int(tail_pairs) > 0:
            if not weights:
                raise ValueError("tail_pairs needs select_top_n (the tail is the unselected candidate modes).")
            rest = [m for m in weights if m not in set(chosen)]
            rng = np.random.default_rng(int(random_seed))
            shifts = [sum(z * math.sqrt(mode_mean_square_q(float(freqs[m]), t_rank)) * displacement(m) for z, m in zip(rng.choice([-1.0, 1.0], len(rest)), rest))
                      for _ in range(int(tail_pairs))] if rest else []
            for i, u in enumerate(shifts):
                entry = {"mode": TAIL_MODE_BASE + i, "kind": "rademacher_tail", "rank": len(chosen) + i, "files": {}}
                for sign, tag in ((1, "p"), (-1, "m")):
                    cell = base.copy()
                    cell.positions = base.positions + sign * u
                    path = out / f"mode_{TAIL_MODE_BASE + i:04d}_{tag}.extxyz"
                    write(str(path), cell, format="extxyz")
                    entry["files"][tag] = _h._rel(root, path)
                entry["max_atom_displacement_angstrom"] = round(float(np.linalg.norm(u, axis=1).max()), 4)
                modes.append(entry)
            tail = {"n_modes": len(rest), "pairs": len(shifts), "temperature_k": t_rank, "random_seed": int(random_seed),
                    "rule": "E[(X(+u)+X(-u))/2 - X0] = 1/2 sum_{k in tail} d2X/dQ_k^2 <Q_k^2>_T (Rademacher z_k; off-diagonal terms average out)"}
        manifest = {
            "phonon_dir": _h._rel(root, ph_dir), "amplitude_q_sqrt_amu_angstrom": float(amplitude_q), "mode_cell": mode_cell,
            "thermal_amplitude_k": float(thermal_amplitude_k), "min_frequency_cm1": float(min_frequency_cm1),
            "reference_cell": _h._rel(root, out / "reference_cell.extxyz"),
            "convention": "x = x0 + Q e/sqrt(m); d2X/dQ2 ~ (X(+Q) - 2X0 + X(-Q))/Q^2 with Q = each mode's amplitude_q; <X>_T ~ X0 + 1/2 sum_k d2X/dQ_k^2 <Q_k^2>_T "
                          "(exact for a harmonic ensemble: <Q_k Q_l> = 0 for k != l, so no mixed derivatives are needed)",
            "selection": selection, "tail": tail, "modes": modes,
        }
        (out / "mode_displacements_manifest.json").write_text(json.dumps(manifest, indent=1))
        return {"ok": True, "n_modes": len(modes) - (tail or {}).get("pairs", 0), "selection": selection, "tail": tail,
                **({"warning": f"modes {large[:10]} move an atom > 0.3 A at their step"} if large else {}),
                "modes": [{k: v for k, v in m.items() if k != "files"} for m in modes[:40]], "manifest": _h._rel(root, out / "mode_displacements_manifest.json")}
    except Exception as exc:
        return _h._error(exc)


def _formula_atom_count(formula: str) -> int:
    return sum(int(n or 1) for _el, n in re.findall(r"([A-Z][a-z]?)(\d*)", formula))


def _cluster_selection(root: Path, cluster_manifest: str, atoms: str, phonon_dir: str):
    """(manifest path, manifest, cluster, cell origin per cluster atom, chosen cluster indices) of a carved cluster."""
    from ase.data import covalent_radii
    from ase.io import read

    mpath = _h._resolve_path(root, cluster_manifest, must_exist=True, dir_ok=False)
    man = json.loads(mpath.read_text())
    cluster = read(str(root / man["qm_xyz"]))
    origin = man["qm_atom_origin_cell_index_and_image"]
    n_central = _formula_atom_count(man["qm_molecules"][0]["formula"])
    center = next(k for k, o in enumerate(origin) if o[0] == int(man["center_index"]))
    if atoms.strip() == "first_shell":
        rc = covalent_radii[cluster.numbers]
        d = np.linalg.norm(cluster.positions - cluster.positions[center], axis=1)
        chosen = [center] + [k for k in range(n_central) if k != center and d[k] <= 1.25 * (rc[k] + rc[center])]
    elif atoms.strip() == "molecule":
        chosen = list(range(n_central))
    else:
        chosen = [int(v) for v in atoms.replace(",", " ").split()]
    if phonon_dir.strip():
        ph = _load_phonon(_h._resolve_path(root, phonon_dir, must_exist=True, file_ok=False))
        if len(ph.primitive) != int(man["cell_atoms"]):
            raise ValueError(f"The cluster was carved from a {man['cell_atoms']}-atom cell but the phonon cell has {len(ph.primitive)} atoms.")
    return mpath, man, cluster, origin, chosen


def export_cluster_cartesian_displacements(
    cluster_manifest: Annotated[str, "cluster_manifest.json of the reference cluster (extract_molecular_cluster_from_crystal on the phonon reference cell)."],
    atoms: Annotated[str, "'first_shell' (metal + bonded donors; the dominant spin-phonon physics), 'molecule' (every atom of the central molecule, 6N clusters) or explicit 0-based cluster indices '0 5 7'."] = "first_shell",
    step_angstrom: Annotated[float, "Cartesian finite-difference step (literature standard 0.01 A)."] = 0.01,
    phonon_dir: Annotated[str, "Optional phonon directory whose Gamma modes the gradients will be projected on (checked for atom-list consistency)."] = "",
    output_dir: Annotated[str, "Default <cluster folder>/cartesian_displacements."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """+/- step clusters along x, y, z for selected atoms of the central molecule: dX/dr for spin-phonon couplings (Lunghi-type)."""
    root = _h._root(runtime)
    try:
        from ase.io import write

        mpath, man, cluster, origin, chosen = _cluster_selection(root, cluster_manifest, atoms, phonon_dir)
        out = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else mpath.parent / "cartesian_displacements")
        out.mkdir(parents=True, exist_ok=True)
        members = []
        for k in chosen:
            for axis, name in enumerate("xyz"):
                for sign, tag in ((1, "p"), (-1, "m")):
                    displaced = cluster.copy()
                    displaced.positions[k, axis] += sign * float(step_angstrom)
                    label = f"atom{k:03d}_{name}{tag}"
                    write(str(out / f"{label}.xyz"), displaced)
                    members.append({"member": label, "cluster_atom": k, "cell_atom": int(origin[k][0]), "element": cluster[k].symbol,
                                    "axis": axis, "sign": sign, "qm_xyz": _h._rel(root, out / f"{label}.xyz")})
        manifest = {
            "kind": "cartesian", "reference_cluster": man["qm_xyz"], "reference_manifest": _h._rel(root, mpath),
            "pointcharge_file": man.get("pointcharge_file"), "qm_charge": man.get("qm_charge"), "step_angstrom": float(step_angstrom),
            "phonon_dir": phonon_dir.strip() or None, "atoms": [{"cluster_atom": k, "cell_atom": int(origin[k][0]), "element": cluster[k].symbol} for k in chosen],
            "members": members,
            "protocol_rule": "Same ORCA protocol and point charges as the reference cluster for all members; then analyze_vibronic_property.",
        }
        (out / "cartesian_displacements_manifest.json").write_text(json.dumps(manifest, indent=1))
        return {"ok": True, "n_atoms_displaced": len(chosen), "n_clusters": len(members), "atoms": manifest["atoms"],
                "manifest": _h._rel(root, out / "cartesian_displacements_manifest.json")}
    except Exception as exc:
        return _h._error(exc)


def export_random_cluster_displacements(
    cluster_manifest: Annotated[str, "cluster_manifest.json of the reference cluster (extract_molecular_cluster_from_crystal on the phonon reference cell)."],
    atoms: Annotated[str, "'first_shell' (metal + bonded donors), 'molecule' or explicit 0-based cluster indices '0 5 7'."] = "first_shell",
    n_train: Annotated[int, "Training clusters (fit set): +/-u pairs, each ONE equation for the 3n(3n+1)/2 second derivatives, so n_train >= 2 x that "
                            "(171 for a 6-atom first shell: >= 342, ~514 recommended); whole molecules: export_random_mode_displacements."] = 300,
    n_test: Annotated[int, "Held-out clusters that score the fit (never used in it)."] = 60,
    rms_angstrom: Annotated[float, "Standard deviation of every displaced Cartesian coordinate (A)."] = 0.03,
    seed: Annotated[int, "Random seed (record it)."] = 20261005,
    phonon_dir: Annotated[str, "Optional phonon directory the derivatives will be projected on (checked for atom-list consistency)."] = "",
    output_dir: Annotated[str, "Default <cluster folder>/random_displacements."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Clusters with ALL selected atoms displaced at random (antithetic +/-u pairs): the training/test set of a quadratic fit of
    g / A over the displaced coordinates (fit_spin_hamiltonian_derivatives) -- full second derivatives, incl. cross terms."""
    root = _h._root(runtime)
    try:
        from ase.io import write

        mpath, man, cluster, origin, chosen = _cluster_selection(root, cluster_manifest, atoms, phonon_dir)
        out = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else mpath.parent / "random_displacements")
        out.mkdir(parents=True, exist_ok=True)
        write(str(out / "reference.xyz"), cluster)
        rng = np.random.default_rng(int(seed))
        members = []
        for split, n in (("train", int(n_train)), ("test", int(n_test))):
            draws = rng.normal(0.0, float(rms_angstrom), size=(math.ceil(n / 2), len(chosen), 3))
            # +u/-u pairs: odd (linear) and even (quadratic) columns are then exactly orthogonal in the fit.
            for k, u in enumerate(np.concatenate([draws, -draws])[:n]):
                displaced = cluster.copy()
                displaced.positions[chosen] += u
                label = f"rand_{split}_{k:04d}"
                write(str(out / f"{label}.xyz"), displaced)
                members.append({"member": label, "split": split, "displacement": np.round(u, 10).tolist(), "qm_xyz": _h._rel(root, out / f"{label}.xyz")})
        n_params = 3 * len(chosen) + 3 * len(chosen) * (3 * len(chosen) + 1) // 2
        manifest = {
            "kind": "random", "reference_cluster": _h._rel(root, out / "reference.xyz"), "reference_manifest": _h._rel(root, mpath),
            "pointcharge_file": man.get("pointcharge_file"), "qm_charge": man.get("qm_charge"), "rms_angstrom": float(rms_angstrom),
            "seed": int(seed), "n_train": int(n_train), "n_test": int(n_test), "n_fit_parameters": n_params,
            "phonon_dir": phonon_dir.strip() or None, "atoms": [{"cluster_atom": k, "cell_atom": int(origin[k][0]), "element": cluster[k].symbol} for k in chosen],
            "displacement_convention": "member geometry = reference + displacement[i] on atoms[i] (A); every other atom fixed",
            "members": members,
            "protocol_rule": "Same ORCA protocol and point charges for all members (prepare_orca_displacement_sweep); then fit_spin_hamiltonian_derivatives.",
        }
        (out / "random_displacements_manifest.json").write_text(json.dumps(manifest, indent=1))
        result = {"ok": True, "n_atoms_displaced": len(chosen), "n_clusters": len(members), "n_fit_parameters": n_params, "atoms": manifest["atoms"],
                  "manifest": _h._rel(root, out / "random_displacements_manifest.json")}
        n_quad = n_params - 3 * len(chosen)
        if int(n_train) < 1.5 * n_params or int(n_train) // 2 < n_quad:
            result["warning"] = (f"n_train={n_train}: {int(n_train) // 2} +/-u pairs for {n_quad} second derivatives (one equation per pair; fewer "
                                 f"leave a min-norm Hessian): use n_train >= {2 * math.ceil(1.5 * n_quad)}, displace fewer atoms, or use "
                                 "export_random_mode_displacements.")
        return result
    except Exception as exc:
        return _h._error(exc)


def _load_values(root: Path, values_json: str) -> dict[str, np.ndarray]:
    text = values_json.strip()
    if text and not text.startswith("{"):
        text = _h._resolve_path(root, text, must_exist=True, dir_ok=False).read_text()
    raw = json.loads(text or "{}")
    return {str(k): np.atleast_1d(np.array(v, dtype=float)) for k, v in raw.items()}


def _cartesian_gradient(man: dict[str, Any], values: dict[str, np.ndarray]) -> dict[tuple[int, int], np.ndarray]:
    """Central-difference dX/dr (per A) for each (cluster atom, axis) of a cartesian_displacements manifest."""
    step = float(man["step_angstrom"])
    grads: dict[tuple[int, int], dict[int, np.ndarray]] = {}
    for member in man["members"]:
        if member["member"] in values:
            grads.setdefault((member["cluster_atom"], member["axis"]), {})[member["sign"]] = values[member["member"]]
    complete = {k: (v[1] - v[-1]) / (2 * step) for k, v in grads.items() if 1 in v and -1 in v}
    if not complete:
        raise ValueError("No atom/axis had both +step and -step values.")
    return complete


ZFS_LABELS = ("Dxx", "Dyy", "Dzz", "Dxy", "Dxz", "Dyz")


def _zfs_d_e(v) -> dict[str, float]:
    """Axial D, rhombic E (>= 0) and E/D of a raw ZFS tensor given as (Dxx, Dyy, Dzz, Dxy, Dxz, Dyz) in cm-1."""
    xx, yy, zz, xy, xz, yz = [float(x) for x in v]
    t = np.array([[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]])
    w = np.linalg.eigvalsh(t - np.trace(t) / 3 * np.eye(3))
    z = int(np.argmax(np.abs(w)))
    x, y = [i for i in range(3) if i != z]
    d, e = 1.5 * w[z], abs(w[x] - w[y]) / 2
    return {"D": round(float(d), 4), "E": round(float(e), 4), "E_over_D": round(float(e / abs(d)), 4) if d else None}


def analyze_vibronic_property(
    ensemble_manifest:Annotated[str, "thermal_snapshots_manifest.json, mode_displacements_manifest.json, cartesian_displacements_manifest.json or a cluster_ensemble_manifest.json."],
    values_json: Annotated[str, "JSON (or path to a .json file) {member name: value}. Value = number or list (e.g. [D, E] in cm-1). Include 'reference' = the undisplaced value."],
    temperatures_k: Annotated[str, "Temperatures for thermal averages/fluctuations."] = "5 20",
    property_labels: Annotated[str, "Optional comma names for vector components, e.g. 'D,E'."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Thermal averages, fluctuations and mode-resolved couplings of a computed property (e.g. ZFS D) over a phonon ensemble."""
    root = _h._root(runtime)
    try:
        mpath = _h._resolve_path(root, ensemble_manifest, must_exist=True, dir_ok=False)
        man = json.loads(mpath.read_text())
        if "ensemble_manifest" in man:  # cluster ensemble -> the underlying snapshot/mode manifest
            mpath = _h._resolve_path(root, man["ensemble_manifest"], must_exist=True, dir_ok=False)
            man = json.loads(mpath.read_text())
        values = _load_values(root, values_json)
        temps = [float(t) for t in temperatures_k.split()]
        labels = [x.strip() for x in property_labels.split(",") if x.strip()]
        ref = values.get("reference")

        def fmt(v):
            v = np.atleast_1d(v)
            if labels and len(labels) == len(v):
                return {lab: round(float(x), 6) for lab, x in zip(labels, v)}
            return [round(float(x), 6) for x in v] if len(v) > 1 else round(float(v[0]), 6)

        if "snapshots" in man:
            names = [Path(f).stem for f in man["snapshots"]]
            missing = [n for n in names if n not in values]
            data = np.array([values[n] for n in names if n in values])
            if len(data) < 2:
                raise ValueError(f"Need values for at least 2 snapshots (missing: {missing[:5]}).")
            half = len(names) // 2
            paired = man.get("antithetic_pairs") and not missing
            # Antithetic pairs are correlated: the pair means are the independent samples.
            samples = (data[:half] + data[half:2 * half]) / 2.0 if paired else data
            mean = data.mean(axis=0)
            sem = samples.std(axis=0, ddof=1) / np.sqrt(len(samples))
            result = {
                "kind": "snapshots", "temperature_k": man.get("temperature_k"), "n_used": len(data), "missing": missing,
                "mean": fmt(mean), "standard_error": fmt(sem), "std_over_snapshots": fmt(data.std(axis=0, ddof=1)),
            }
            if ref is not None:
                result["static_reference"] = fmt(ref)
                result["thermal_shift"] = fmt(mean - ref)
                result["shift_significant"] = bool(np.all(np.abs(mean - ref) > 2 * sem))
                if labels == list(ZFS_LABELS):  # D/E of the mean TENSOR (single snapshots can flip the sign of D near E/D = 1/3)
                    result["zfs_D_E"] = {"reference": _zfs_d_e(ref), "mean_tensor": _zfs_d_e(mean)}
        elif "modes" in man:
            if ref is None:
                raise ValueError("Mode analysis needs values['reference'] (the undisplaced cluster).")
            q_default = man.get("amplitude_q_sqrt_amu_angstrom")
            rows, contrib, missing = [], [], []
            sigma2 = {t: np.zeros_like(ref) for t in temps}
            tail_samples = []
            for m in sorted(man["modes"], key=lambda m: m.get("rank", 0)):  # rank order (selection) for the convergence table
                tag = f"mode_{m['mode']:04d}"
                if f"{tag}_p" not in values or f"{tag}_m" not in values:
                    missing.append(m["mode"])
                    continue
                if m.get("kind") == "rademacher_tail":  # stochastic estimate of the unselected modes' second-order shift
                    tail_samples.append((values[f"{tag}_p"] + values[f"{tag}_m"]) / 2 - ref)
                    continue
                q = float(m.get("amplitude_q", q_default))  # per-mode step (Gauss-Hermite thermal steps) or the global one
                xp, xm = values[f"{tag}_p"], values[f"{tag}_m"]
                d1 = (xp - xm) / (2 * q)
                d2 = (xp - 2 * ref + xm) / q**2
                row = {"mode": m["mode"], "frequency_cm1": m["frequency_cm1"], "dX_dQ": fmt(d1), "d2X_dQ2": fmt(d2)}
                contrib.append({t: 0.5 * d2 * mode_mean_square_q(m["frequency_cm1"], t) for t in temps})
                for t in temps:
                    sigma2[t] += d1**2 * mode_mean_square_q(m["frequency_cm1"], t)
                rows.append(row)
            if not rows:
                raise ValueError("No mode had both +Q and -Q values.")
            shift = {t: np.sum([c[t] for c in contrib], axis=0) for t in temps}
            # Convergence in the number of modes (rank order): cumulative shift after 1/4, 1/2, 3/4 and all of the modes.
            n = len(rows)
            marks = sorted({max(1, round(n * f)) for f in (0.25, 0.5, 0.75, 1.0)})
            t_conv = temps[-1]
            cum = {k: np.sum([c[t_conv] for c in contrib[:k]], axis=0) for k in marks}
            last = cum[n] - cum[marks[-2]] if len(marks) > 1 else cum[n]
            scale = float(np.max(np.abs(cum[n]))) or 1.0
            result = {
                "kind": "modes", "n_modes": len(rows), "missing_modes": missing, "reference": fmt(ref),
                "thermal_average": {f"{t:g}K": fmt(ref + shift[t]) for t in temps},
                "thermal_shift": {f"{t:g}K": fmt(shift[t]) for t in temps},
                "thermal_rms_fluctuation": {f"{t:g}K": fmt(np.sqrt(sigma2[t])) for t in temps},
                "convergence_in_modes": {
                    "temperature_k": t_conv, "cumulative_shift": {str(k): fmt(cum[k]) for k in marks}, "last_block_change": fmt(last),
                    "converged": bool(np.all(np.abs(last) <= 0.1 * scale)),
                    "rule": "converged when adding the last quarter of the (ranked) modes changes every component by <= 10% of the largest |shift|",
                    "selection": man.get("selection"),
                },
                "modes": sorted(rows, key=lambda r: -float(np.max(np.abs(np.atleast_1d(list(r["dX_dQ"].values()) if isinstance(r["dX_dQ"], dict) else r["dX_dQ"]))))),
                "caveat": "Only the exported modes contribute: check convergence_in_modes (and selection.captured_weight_fraction); unexported "
                          "modes add shifts not included here.",
            }
            if labels == list(ZFS_LABELS):
                result["zfs_D_E"] = {"reference": _zfs_d_e(ref), **{f"thermal_average_{t:g}K": _zfs_d_e(ref + shift[t]) for t in temps}}
            if tail_samples:  # only at the temperature the tail amplitudes were drawn for
                t_tail = float((man.get("tail") or {}).get("temperature_k") or temps[-1])
                ts = np.array(tail_samples)
                tail_se = ts.std(axis=0, ddof=1) / np.sqrt(len(ts)) if len(ts) > 1 else np.full_like(ref, np.nan)
                result["tail_estimate"] = {"temperature_k": t_tail, "n_pairs": len(ts), "n_tail_modes": (man.get("tail") or {}).get("n_modes"),
                                           "shift": fmt(ts.mean(axis=0)), "standard_error": fmt(tail_se)}
                if t_tail in shift:
                    result["thermal_shift_with_tail"] = {f"{t_tail:g}K": fmt(shift[t_tail] + ts.mean(axis=0))}
                    if labels == list(ZFS_LABELS):
                        result["zfs_D_E"][f"thermal_average_with_tail_{t_tail:g}K"] = _zfs_d_e(ref + shift[t_tail] + ts.mean(axis=0))
                result["caveat"] = ("Selected modes exactly (diagonal second order, Gauss-Hermite steps) + the unselected modes as a stochastic "
                                    "(Hutchinson) tail estimate with its standard error, at the tail's temperature only.")
        elif man.get("kind") == "cartesian":
            complete = _cartesian_gradient(man, values)
            atoms = man["atoms"]
            per_atom = []
            for a in atoms:
                g = [complete.get((a["cluster_atom"], ax)) for ax in range(3)]
                if all(x is not None for x in g):
                    norm = np.sqrt(sum(np.asarray(x) ** 2 for x in g))
                    per_atom.append({"cluster_atom": a["cluster_atom"], "element": a["element"], "gradient_norm_per_angstrom": fmt(norm)})
            result = {"kind": "cartesian", "per_atom_gradient": sorted(per_atom, key=lambda r: -float(np.max(np.atleast_1d(list(r["gradient_norm_per_angstrom"].values()) if isinstance(r["gradient_norm_per_angstrom"], dict) else r["gradient_norm_per_angstrom"]))))}
            if man.get("phonon_dir"):
                ph = _load_phonon(_h._resolve_path(root, man["phonon_dir"], must_exist=True, file_ok=False))
                ph.run_qpoints([[0.0, 0.0, 0.0]], with_eigenvectors=True)
                freqs = ph.qpoints.frequencies[0] * THZ_TO_CM1
                vecs = ph.qpoints.eigenvectors[0]
                masses = np.array(ph.primitive.masses)
                acoustic = set(np.argsort(np.abs(freqs))[:3].tolist())
                dim = len(np.atleast_1d(next(iter(complete.values()))))
                couplings, sigma2 = [], {t: np.zeros(dim) for t in temps}
                for j in range(len(freqs)):
                    if j in acoustic or freqs[j] <= 1.0:
                        continue
                    e = np.real(vecs[:, j]).reshape(-1, 3)
                    dq = np.zeros(dim)
                    for a in atoms:
                        i = a["cell_atom"]
                        for ax in range(3):
                            if (a["cluster_atom"], ax) in complete:
                                dq += complete[(a["cluster_atom"], ax)] * e[i, ax] / np.sqrt(masses[i])
                    zp = np.sqrt(mode_mean_square_q(freqs[j], 0.0))
                    couplings.append({"mode": j, "frequency_cm1": round(float(freqs[j]), 3), "dX_dQ": fmt(dq), "coupling_zero_point": fmt(dq * zp)})
                    for t in temps:
                        sigma2[t] += dq**2 * mode_mean_square_q(freqs[j], t)

                def strength(r):
                    v = r["coupling_zero_point"]
                    return float(np.max(np.abs(np.atleast_1d(list(v.values()) if isinstance(v, dict) else v))))
                result.update({
                    "strongest_coupled_modes": sorted(couplings, key=strength, reverse=True)[:15],
                    "lowest_frequency_couplings": sorted(couplings, key=lambda r: r["frequency_cm1"])[:10],
                    "thermal_rms_fluctuation": {f"{t:g}K": fmt(np.sqrt(sigma2[t])) for t in temps},
                    "note": "Gamma modes; gradients only for the displaced atoms (first shell carries most of the coupling). "
                            "coupling_zero_point = dX/dQ * sqrt(<Q^2>_0): the one-phonon spin-phonon matrix-element scale.",
                })
                (mpath.parent / "mode_couplings.csv").write_text(
                    "mode,frequency_cm1,dX_dQ\n" + "\n".join(f"{c['mode']},{c['frequency_cm1']},{json.dumps(c['dX_dQ'])}" for c in couplings)
                )
        else:
            raise ValueError("Unknown ensemble manifest type.")
        (mpath.parent / "vibronic_analysis.json").write_text(json.dumps(result, indent=1, default=str))
        return {"ok": True, **result, "saved": _h._rel(root, mpath.parent / "vibronic_analysis.json")}
    except Exception as exc:
        return _h._error(exc)


# --------------------------------------------------------------------------- #
# Spin-phonon coupling on a q mesh (Lunghi-type, beyond Gamma)
# --------------------------------------------------------------------------- #

# Below this force-constant supercell width the dispersion between commensurate q is poorly interpolated.
MIN_FC_SUPERCELL_WIDTH_ANGSTROM = 10.0
C_CM_PER_S = 2.99792458e10
TO_CM1 = {"cm-1": 1.0, "mev": 8.065543937, "ghz": 1.0 / 29.9792458, "mhz": 1.0 / 29979.2458}


def gamma_centred_mesh(mesh) -> np.ndarray:
    """Every q of a Gamma-centred n1 x n2 x n3 mesh in reduced coordinates (no symmetry reduction; Gamma first)."""
    return np.array(list(itertools.product(*[np.arange(int(n)) / int(n) for n in mesh])), dtype=float)


def fc_supercell_support(phonon, mesh) -> dict[str, Any]:
    """Can the force-constant supercell carry phonons at the q of ``mesh``?

    Along a lattice direction whose supercell period is one cell, the force constants are lattice
    sums (every image folded onto the home cell), so q != 0 along it is invention, not interpolation.
    q with M q integer (M = supercell in primitive units) are exact; the rest are Fourier-interpolated.
    """
    prim, sc = np.array(phonon.primitive.cell), np.array(phonon.supercell.cell)
    inv_sc = np.linalg.inv(sc)
    periods = []
    for a in prim:
        periods.append(next(k for k in range(1, 1000) if np.allclose(k * a @ inv_sc, np.rint(k * a @ inv_sc), atol=1e-6)))
    s = gamma_centred_mesh(mesh) @ np.rint(sc @ np.linalg.inv(prim)).T
    volume = abs(np.linalg.det(sc))
    widths = [volume / np.linalg.norm(np.cross(sc[(i + 1) % 3], sc[(i + 2) % 3])) for i in range(3)]
    return {
        "fc_supercell_periods": periods,
        "fc_supercell_min_width_angstrom": round(float(min(widths)), 2),
        "commensurate_fraction": round(float(np.all(np.abs(s - np.rint(s)) < 1e-8, axis=1).mean()), 4),
        "unsupported_axes": [i for i in range(3) if periods[i] == 1 and int(mesh[i]) > 1],
    }


def molecule_positions_in_phonon_cell(phonon, cluster_positions, cell_atoms, tol: float = 0.05) -> tuple[np.ndarray, float]:
    """Cartesian R_k of the molecule's atoms as phonopy's own r_kappa + whole lattice vectors.

    Phonopy's dynamical matrix uses the atomic-position phase convention, so exp(i q.R_k) must be
    built from its r_kappa (then V is periodic in q). The cluster's global shift only adds a phase.
    """
    lat = np.array(phonon.primitive.cell)
    base = np.array(phonon.primitive.scaled_positions)[list(cell_atoms)]
    d = np.asarray(cluster_positions, dtype=float) @ np.linalg.inv(lat) - base
    d -= d[0]
    image = np.rint(d)
    dev = float(np.linalg.norm((d - image) @ lat, axis=1).max())
    if dev > tol:
        raise ValueError(
            f"Cluster atoms are not lattice translates of the phonon cell atoms (max deviation {dev:.3f} A): carve the "
            "cluster from the SAME cell the force constants were computed on (its phonon reference structure)."
        )
    return (base + image) @ lat, dev


def _acoustic_corrected_modes(phonon, qpoints) -> tuple[np.ndarray, np.ndarray]:
    """Small-q modes with the spurious O(q) acoustic term removed (rotational / Born-Huang invariance).

    In the basis of the three Gamma translations, the acoustic 3x3 block of D(q) is real-symmetric
    (O(q^2), elastic) plus i x antisymmetric (odd in q). Its O(q) part vanishes for any rotationally
    invariant force-constant set, but truncated/noisy supercell sets break that and push one acoustic
    branch imaginary as -|q| (urea/UMA: -3.7 cm-1 at 0.5% of the zone). Dropping the antisymmetric part of
    that block removes only this artifact (+ O(q^3)); acoustic-optical coupling (internal strain) is kept.
    """
    from scipy.linalg import null_space

    m = np.array(phonon.primitive.masses)
    t = np.zeros((3 * len(m), 3))
    for a in range(3):
        t[a::3, a] = np.sqrt(m / m.sum())
    basis = np.hstack([t, null_space(t.T)])
    freqs, vecs = [], []
    for q in np.atleast_2d(qpoints):
        phonon.dynamical_matrix.run(q)
        b = basis.T @ phonon.dynamical_matrix.dynamical_matrix @ basis
        b[:3, :3] = b[:3, :3].real
        w, v = np.linalg.eigh(b)
        freqs.append(np.sign(w) * np.sqrt(np.abs(w)) * phonon.unit_conversion_factor * THZ_TO_CM1)
        vecs.append(basis @ v)
    return np.array(freqs), np.array(vecs)


def bloch_couplings(phonon, gradient, positions, cell_atoms, qpoints, n_cells: int | None = None, chunk: int = 64,
                    acoustic_corrected: bool = False):
    """Frequencies (cm-1, nq x nb) and V_{q,nu} = sum_k g_k . e_k(q,nu) exp(i q.R_k) / sqrt(N m_k).

    g_k = dX/du_k (X per A) of one molecule's atoms, e = phonopy eigenvectors (unit norm, positional
    phase convention: u_k = e_k exp(i q.R_k) Q / sqrt(N m_k)), N = n_cells (default len(qpoints)),
    so V is dX/dQ in X per (sqrt(amu) A) and sum_{q,nu} |V|^2 = sum_k |g_k|^2 / m_k on any full mesh.
    acoustic_corrected: small-q modes from _acoustic_corrected_modes (continuum limit only).
    """
    qpoints = np.atleast_2d(np.asarray(qpoints, dtype=float))
    idx = list(cell_atoms)
    w = np.asarray(gradient, dtype=float) / np.sqrt(np.array(phonon.primitive.masses)[idx])[:, None]
    frac = np.asarray(positions, dtype=float) @ np.linalg.inv(np.array(phonon.primitive.cell))
    n_atoms = len(phonon.primitive)
    freqs, couplings = [], []
    for start in range(0, len(qpoints), chunk):
        q = qpoints[start : start + chunk]
        if acoustic_corrected:
            f, e = _acoustic_corrected_modes(phonon, q)
        else:
            phonon.run_qpoints(q, with_eigenvectors=True)
            f, e = np.asarray(phonon.qpoints.frequencies) * THZ_TO_CM1, np.asarray(phonon.qpoints.eigenvectors)
        e = e.reshape(len(q), n_atoms, 3, -1)[:, idx]
        couplings.append(np.einsum("ka,qkab,qk->qb", w, e, np.exp(2j * np.pi * q @ frac.T)))
        freqs.append(f)
    return np.concatenate(freqs), np.concatenate(couplings) / np.sqrt(n_cells or len(qpoints))


def acoustic_continuum_coefficient(phonon, gradient, positions, cell_atoms, n_directions: int = 400, q_fraction: float = 0.02) -> dict[str, Any]:
    """Long-wavelength limit J(w) -> C w^4 from the exact small-q acoustic modes (elastic continuum).

    C = V_cell/(2 pi)^3 sum_nu int dOmega A_nu(q^)/v_nu(q^)^5 with A = |V(q)|^2 N/|q|^2, v = w/|q|, averaged
    over Fibonacci directions at |q| = q_fraction x (1, 2, 4, 8) of the shortest reciprocal vector: C must
    not drift while the w^4 law holds, which bounds its range (valid_below_cm1). Needs a translation-free
    gradient. The acoustic modes carry the rotational-invariance correction of _acoustic_corrected_modes.
    """
    cell = np.array(phonon.primitive.cell)
    k = np.arange(n_directions) + 0.5
    theta, phi = np.arccos(1 - 2 * k / n_directions), np.pi * (1 + 5**0.5) * k
    dirs = np.stack([np.cos(phi) * np.sin(theta), np.sin(phi) * np.sin(theta), np.cos(theta)], axis=1)
    qmin = 2 * np.pi * np.linalg.norm(np.linalg.inv(cell).T, axis=1).min()
    values, omegas, qmags = [], [], []
    for scale in (1.0, 2.0, 4.0, 8.0):
        qmag = scale * q_fraction * qmin
        q_red = dirs * qmag @ cell.T / (2 * np.pi)
        f, v = bloch_couplings(phonon, gradient, positions, cell_atoms, q_red, n_cells=1, acoustic_corrected=True)
        if scale == 1.0:
            phonon.run_qpoints(q_red)
            raw_min = round(float(phonon.qpoints.frequencies[:, 0].min() * THZ_TO_CM1), 3)
        if (f[:, :3] <= 0).any():
            if scale > 1.0:
                break
            return {
                "available": False, "raw_small_q_acoustic_min_cm1": raw_min,
                "fraction_of_directions_imaginary": round(float((f[:, :3] <= 0).any(axis=1).mean()), 3),
                "reason": f"acoustic branches imaginary at |q| = {qmag:.4f} 1/A even after the rotational-invariance "
                          "correction: these force constants imply a non-positive elastic tensor (truncated or noisy "
                          "long-range force constants; try another/larger supercell or tighter forces).",
            }
        speed = f[:, :3] / qmag
        values.append(abs(np.linalg.det(cell)) / (2 * np.pi) ** 3 * 4 * np.pi * float(np.mean(((np.abs(v[:, :3]) ** 2 / qmag**2) / speed**5).sum(axis=1))))
        omegas.append(float(np.median(f[:, :3])))
        qmags.append(qmag)
        if scale == 1.0:
            sound = speed * (2 * np.pi * C_CM_PER_S * 1e-10)  # (cm-1 per 1/A) -> m/s
    drift = [abs(c / values[0] - 1) for c in values]
    valid = next((i for i, d in enumerate(drift) if d > 0.2), len(drift)) - 1
    return {
        "available": True, "J_over_omega4": values[0], "linearity_check_relative": round(drift[1], 4) if len(drift) > 1 else None,
        "C_drift_by_median_acoustic_cm1": {f"{w:.3g}": round(c / values[0], 3) for w, c in zip(omegas, values)},
        "valid_below_cm1": round(omegas[max(valid, 0)], 3),
        "valid_q_inv_angstrom": qmags[max(valid, 0)],
        "raw_small_q_acoustic_min_cm1": raw_min,
        "sound_speeds_m_per_s": {"min": round(float(sound.min()), 1), "mean": round(float(sound.mean()), 1), "max": round(float(sound.max()), 1)},
        "check": "Compare sound_speeds with an independent elastic tensor (strain-stress): finite-supercell force constants "
                 "can misrepresent soft shears and C scales as v^-5.",
    }


def _gaussian_sum(freqs, weights, at, sigma):
    """sum_i weights_i * N(at - freqs_i; sigma) for every value in ``at`` (chunked)."""
    at = np.atleast_1d(np.asarray(at, dtype=float))
    out = np.zeros(len(at))
    for s in range(0, len(freqs), 20000):
        x = at[:, None] - freqs[None, s : s + 20000]
        out += (np.exp(-0.5 * (x / sigma) ** 2) * weights[None, s : s + 20000]).sum(axis=1)
    return out / (np.sqrt(2 * np.pi) * sigma)


def analyze_spin_phonon_q_mesh(
    displacement_manifest: Annotated[str, "cartesian_displacements_manifest.json (export_cluster_cartesian_displacements) of a cluster carved from the phonon UNIT cell."],
    values_json: Annotated[str, "JSON (or .json path) {member: value} as for analyze_vibronic_property; value = number or list."],
    phonon_dir: Annotated[str, "Directory with phonopy_params.yaml from SUPERCELL force constants (run_periodic_dft_phonons supercell >= ~10 A, or a labelled MLIP set). Default: the manifest's phonon_dir."] = "",
    force_constants_source: Annotated[str, "Provenance label; REQUIRED unless phonon_dir is a run_periodic_dft_phonons directory, e.g. 'MLIP: UMA uma-s-1p2 (omc), 2x2x3 supercell'."] = "",
    q_meshes: Annotated[str, "Gamma-centred q meshes, ';'-separated, coarse to dense (last = production), e.g. '1 1 1; 2 2 2; 4 4 4; 8 8 8'."] = "1 1 1; 2 2 2; 4 4 4; 8 8 8",
    property_index: Annotated[int, "Component of a list-valued property (0-based)."] = 0,
    property_unit: Annotated[str, "Unit of X: 'cm-1', 'meV', 'GHz', 'MHz' (rates computed) or 'none' (spectral densities only)."] = "cm-1",
    transition_energies_cm1: Annotated[str, "Spin transition energies (cm-1) for one-phonon rates; X band ~0.31, excited Kramers doublets 10-300."] = "0.31 10 50 100",
    temperatures_k: Annotated[str, "Temperatures (K)."] = "5 20 100",
    spin_matrix_element: Annotated[float, "|<a|O|b>| of the spin operator O multiplying X in H_spin between the two levels (rates scale with its square)."] = 1.0,
    broadening_cm1: Annotated[float, "Gaussian sigma (cm-1) of the delta functions; must exceed the mesh frequency spacing near the transition."] = 2.0,
    acoustic_sum_rule: Annotated[bool, "Remove the net gradient sum_k dX/du_k (rigid translation against the frozen embedding) by mass-weighted projection, so long-wavelength acoustic phonons decouple. Needed for the low-energy continuum."] = True,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Spin-phonon coupling of one molecule's property X to every phonon (q, nu) of a q mesh: J(w), thermal spectral density, one-phonon rates, mesh convergence."""
    root = _h._root(runtime)
    try:
        from ase.io import read

        mpath = _h._resolve_path(root, displacement_manifest, must_exist=True, dir_ok=False)
        man = json.loads(mpath.read_text())
        if man.get("kind") != "cartesian":
            raise ValueError("Needs a cartesian_displacements_manifest.json (export_cluster_cartesian_displacements).")
        ph_rel = phonon_dir.strip() or man.get("phonon_dir") or ""
        if not ph_rel:
            raise ValueError("Pass phonon_dir (supercell force constants).")
        ph_dir = _h._resolve_path(root, ph_rel, must_exist=True, file_ok=False)
        provenance = cc._read_json(ph_dir / FC_PROVENANCE)
        if (ph_dir / PHONON_MANIFEST).is_file():
            source = force_constants_source.strip() or "DFT (CP2K finite displacements, run_periodic_dft_phonons)"
        elif force_constants_source.strip() or provenance.get("force_constants_source"):
            source = force_constants_source.strip() or provenance["force_constants_source"]
        else:
            raise ValueError("These force constants do not come from run_periodic_dft_phonons: label them with force_constants_source (e.g. 'MLIP: UMA ...').")
        phonon = _load_phonon(ph_dir)
        n_cell = len(phonon.primitive)
        if n_cell != len(phonon.unitcell):
            raise ValueError("The phonopy primitive cell must be the unit cell (primitive_matrix 'P'): cluster indices refer to the unit cell.")
        ref_man = json.loads(_h._resolve_path(root, man["reference_manifest"], must_exist=True, dir_ok=False).read_text())
        if int(ref_man["cell_atoms"]) != n_cell:
            raise ValueError(f"The cluster was carved from a {ref_man['cell_atoms']}-atom cell but the phonon cell has {n_cell} atoms.")
        meshes = [[int(v) for v in m.split()] for m in q_meshes.split(";") if m.strip()]
        if not meshes or any(len(m) != 3 or min(m) < 1 for m in meshes):
            raise ValueError("q_meshes must be ';'-separated 'n1 n2 n3' meshes.")
        support = [fc_supercell_support(phonon, m) for m in meshes]
        bad = [" ".join(map(str, m)) for m, s in zip(meshes, support) if s["unsupported_axes"]]
        if bad:
            raise ValueError(
                f"Force-constant supercell periods {support[0]['fc_supercell_periods']} cannot support q meshes {bad}: along a "
                "1-cell period the force constants are lattice sums and q != 0 there is meaningless (e.g. a 1x1x1 phonon set). "
                "Use '1 1 1' only (= analyze_vibronic_property), rerun the phonons in a supercell >= ~10 A wide, or "
                "build_mixed_force_constants (these DFT 1x1x1 Gamma force constants + MLIP supercell dispersion)."
            )
        warnings = []
        if source.startswith(MIXED_FC_SOURCE):
            warnings.append(
                "Mixed force constants: every Gamma frequency is the DFT one, the dispersion away from Gamma is the MLIP's "
                f"(DFT 1x1x1 cannot resolve it). Check the MLIP-vs-DFT Gamma differences in {FC_PROVENANCE} before trusting "
                "low-energy rates."
            )
        if support[0]["fc_supercell_min_width_angstrom"] < MIN_FC_SUPERCELL_WIDTH_ANGSTROM and max(max(m) for m in meshes) > 1:
            warnings.append(f"Force-constant supercell only {support[0]['fc_supercell_min_width_angstrom']} A wide: interactions beyond half of it are missing, so dispersion between commensurate q is poorly interpolated.")
        unit = property_unit.strip().lower()
        to_cm1 = TO_CM1.get(unit) if unit != "none" else None
        if unit != "none" and to_cm1 is None:
            raise ValueError(f"property_unit must be one of {sorted(TO_CM1)} or 'none'.")

        values = _load_values(root, values_json)
        complete = _cartesian_gradient(man, values)
        missing = [(a["cluster_atom"], ax) for a in man["atoms"] for ax in range(3) if (a["cluster_atom"], ax) not in complete]
        if missing:
            raise ValueError(f"Missing +/- values for (cluster atom, axis) {missing[:6]}: every displaced atom needs all three axes.")
        cell_atoms = [int(a["cell_atom"]) for a in man["atoms"]]
        if len(set(cell_atoms)) != len(cell_atoms):
            raise ValueError("Two displaced cluster atoms map onto the same cell atom: displace atoms of ONE molecule only.")
        grad = np.array([[np.atleast_1d(complete[(a["cluster_atom"], ax)])[property_index] for ax in range(3)] for a in man["atoms"]])
        cluster = read(str(root / man["reference_cluster"]))
        positions, map_dev = molecule_positions_in_phonon_cell(phonon, cluster.positions[[a["cluster_atom"] for a in man["atoms"]]], cell_atoms)
        masses = np.array(phonon.primitive.masses)[cell_atoms]
        norm2 = float((grad**2 / masses[:, None]).sum())
        net = grad.sum(axis=0)
        if acoustic_sum_rule:
            grad = grad - masses[:, None] * net / masses.sum()
        grad_info = {
            "n_atoms": len(cell_atoms), "cell_atoms": cell_atoms, "mapping_max_deviation_angstrom": round(map_dev, 5),
            "mass_weighted_norm2": norm2, "net_gradient": [float(x) for x in net],
            "acoustic_sum_rule": bool(acoustic_sum_rule),
            "translational_fraction_removed": round(float((net @ net) / masses.sum() / norm2), 5) if acoustic_sum_rule and norm2 > 0 else 0.0,
        }
        norm2_used = float((grad**2 / masses[:, None]).sum())

        temps = [float(t) for t in temperatures_k.split()]
        deltas = [float(d) for d in transition_energies_cm1.split()]
        sigma = float(broadening_cm1)
        msq = np.vectorize(mode_mean_square_q)
        rate_scale = 4 * np.pi**2 * C_CM_PER_S * float(spin_matrix_element) ** 2 * (to_cm1 or 0.0) ** 2
        rows, spectra = [], []
        for mesh, sup in zip(meshes, support):
            freqs, v = bloch_couplings(phonon, grad, positions, cell_atoms, gamma_centred_mesh(mesh))
            f, w2 = freqs.ravel(), np.abs(v.ravel()) ** 2
            band = np.tile(np.arange(freqs.shape[1]), freqs.shape[0])
            keep = f > 0.1
            keep[:3] = False  # Gamma acoustic (q index 0): zero frequency, uniform translation
            imaginary = (f < -1.0) & (np.arange(len(f)) >= 3)
            fk, wk, bk = f[keep], w2[keep], band[keep]
            qk = np.repeat(np.arange(freqs.shape[0]), freqs.shape[1])[keep]
            row: dict[str, Any] = {
                "mesh": mesh, "n_q": int(np.prod(mesh)), **{k: sup[k] for k in ("commensurate_fraction",)},
                "sum_rule_ratio": round(float(w2.sum() / norm2_used), 8) if norm2_used > 0 else None,
                "lowest_sampled_cm1": round(float(fk.min()), 3) if len(fk) else None,
                "n_imaginary_modes": int(imaginary.sum()),
                "thermal_rms_fluctuation": {f"{t:g}K": float(np.sqrt((wk * msq(fk, t)).sum())) for t in temps},
                "transitions": {},
            }
            for d in deltas:
                j = float(_gaussian_sum(fk, wk, d, sigma)[0])
                entry = {
                    "J": j, "acoustic_band_fraction": round(float(_gaussian_sum(fk[bk < 3], wk[bk < 3], d, sigma)[0] / j), 4) if j > 0 else None,
                    "resolved": bool(len(fk) and d >= fk.min() + sigma),
                }
                for t in temps:
                    s_t = float(_gaussian_sum(fk, wk * msq(fk, t), d, sigma)[0])
                    entry[f"S_{t:g}K"] = s_t
                    if to_cm1 and entry["resolved"]:  # below the sampled spectrum S is only Gaussian tails
                        nbar = 1.0 / math.expm1(min(700.0, d * 1.4387769 / t)) if t > 0 else 0.0
                        total = rate_scale * s_t
                        entry[f"rate_{t:g}K_per_s"] = {"total_1_over_T1": total, "absorption_orbach_like": total * nbar / (2 * nbar + 1)}
                row["transitions"][f"{d:g}cm-1"] = entry
            rows.append(row)
            spectra.append((mesh, fk, wk, bk, qk))

        mesh_d, fk, wk, bk, qk = spectra[-1]
        continuum = acoustic_continuum_coefficient(phonon, grad, positions, cell_atoms) if acoustic_sum_rule else {
            "available": False, "reason": "acoustic_sum_rule=False: a net gradient couples acoustic phonons at q -> 0 (J ~ w^2), no w^4 limit."}
        if continuum["available"]:
            # The w^4 law also ends where any branch away from small q (e.g. a soft zone-boundary mode) comes lower.
            q_red = gamma_centred_mesh(mesh_d)
            q_cart = np.linalg.norm((q_red - np.rint(q_red)) @ (2 * np.pi * np.linalg.inv(np.array(phonon.primitive.cell)).T), axis=1)
            outside = fk[q_cart[qk] > continuum["valid_q_inv_angstrom"]]
            if len(outside) and outside.min() < continuum["valid_below_cm1"]:
                continuum["valid_below_cm1"] = round(float(outside.min()), 3)
                continuum["valid_range_limited_by"] = f"a mode at {outside.min():.2f} cm-1 outside the small-q region of the {'x'.join(map(str, mesh_d))} mesh"
            continuum["transitions"] = {}
            for d in deltas:
                e = {"J": continuum["J_over_omega4"] * d**4, "within_valid_range": d <= continuum["valid_below_cm1"]}
                for t in temps:
                    s_t = e["J"] * float(mode_mean_square_q(d, t))
                    e[f"S_{t:g}K"] = s_t
                    if to_cm1:
                        e[f"rate_{t:g}K_per_s"] = rate_scale * s_t
                continuum["transitions"][f"{d:g}cm-1"] = e

        convergence = {}
        if len(rows) > 1:
            a, b = rows[-2], rows[-1]
            for d in deltas:
                key, t0 = f"{d:g}cm-1", f"S_{temps[0]:g}K"
                sa, sb = a["transitions"][key][t0], b["transitions"][key][t0]
                convergence[key] = {
                    f"{t0}_by_mesh": [r["transitions"][key][t0] for r in rows],
                    "relative_change_last_two": round(abs(sb - sa) / max(abs(sb), 1e-300), 4),
                    "use": "mesh" if b["transitions"][key]["resolved"] and abs(sb - sa) <= 0.25 * abs(sb)
                    else ("acoustic_continuum" if continuum.get("available") and d <= continuum["valid_below_cm1"]
                          else "unconverged: denser mesh, wider broadening or (below the mesh) a valid acoustic continuum"),
                }
            convergence["thermal_rms_fluctuation_by_mesh"] = {f"{t:g}K": [r["thermal_rms_fluctuation"][f"{t:g}K"] for r in rows] for t in temps}

        t0 = temps[0]
        contrib = wk * msq(fk, t0)
        by_band = np.bincount(bk, weights=contrib)
        top = [{"band": int(b), "frequency_range_cm1": [round(float(fk[bk == b].min()), 2), round(float(fk[bk == b].max()), 2)],
                f"fraction_of_variance_{t0:g}K": round(float(by_band[b] / contrib.sum()), 4),
                "fraction_of_coupling_norm": round(float(wk[bk == b].sum() / wk.sum()), 4)}
               for b in np.argsort(-by_band)[:8]]

        grid = np.arange(0.0, min(float(fk.max()) if len(fk) else 0.0, 1000.0) + 4 * sigma, sigma / 2)
        header = ["frequency_cm1"] + [f"J_{'x'.join(map(str, m))}" for m, *_ in spectra] + [f"S_{t:g}K_{'x'.join(map(str, mesh_d))}" for t in temps]
        cols = [grid] + [_gaussian_sum(ff, ww, grid, sigma) for _m, ff, ww, *_ in spectra] + [_gaussian_sum(fk, wk * msq(fk, t), grid, sigma) for t in temps]
        out_dir, tag = mpath.parent, f"{ph_dir.name}_p{int(property_index)}"
        (out_dir / f"spin_phonon_spectral_density_{tag}.csv").write_text(
            ",".join(header) + "\n" + "\n".join(",".join(f"{c[i]:.6e}" for c in cols) for i in range(len(grid))) + "\n"
        )
        result = {
            "force_constants_source": source, "phonon_dir": _h._rel(root, ph_dir),
            "mlip_derived": "mlip" in source.lower(), "mixed_dft_gamma_mlip_dispersion": source.startswith(MIXED_FC_SOURCE),
            "fc_supercell_periods": support[0]["fc_supercell_periods"],
            "fc_supercell_min_width_angstrom": support[0]["fc_supercell_min_width_angstrom"],
            "property_index": int(property_index), "property_unit": property_unit, "spin_matrix_element": float(spin_matrix_element),
            "broadening_cm1": sigma, "gradient": grad_info, "meshes": rows, "convergence": convergence,
            "acoustic_continuum": continuum, f"top_branches_{'x'.join(map(str, mesh_d))}": top, "warnings": warnings,
            "units": {
                "V": "X per (sqrt(amu) A) = dX/dQ_{q,nu}; |V|^2 summed over a full mesh = sum_k |dX/du_k|^2 / m_k (sum_rule_ratio = 1)",
                "J": "sum |V|^2 delta(w - w_{q,nu}) in X^2/(amu A^2) per cm-1 (bare spin-phonon spectral density)",
                "S_T": "sum |V|^2 <|Q|^2>_T delta(w - w_{q,nu}) in X^2 per cm-1; integrates to the thermal variance of X",
                "rates": "1/T1 = 4 pi^2 c |M|^2 S_T(Delta) [X in cm-1] = Fermi golden rule, phonon absorption + emission "
                         "(Lunghi's G^1-ph); absorption part = Orbach-type activation into a level Delta above.",
            },
            "notes": (
                "Gamma acoustic modes (w = 0) and imaginary modes are excluded from J, S_T and the fluctuations. "
                "'resolved' = Delta above the lowest sampled mode + sigma (rates are given only then); below it use "
                "acoustic_continuum (J = C w^4, the Delta^3 coth direct-process law) up to its valid_below_cm1, after checking its "
                "sound speeds against an elastic tensor. Only the molecule's own atoms carry gradients (frozen embedding): "
                "couplings through neighbours' displacements are not included. Rotation of a lab-frame tensor component with "
                "the lattice (transverse acoustic waves) is kept: real for a fixed field direction, absent for invariants."
            ),
        }
        (out_dir / f"spin_phonon_q_{tag}.json").write_text(json.dumps(result, indent=1, default=str))
        # The reply keeps the production mesh in full and one summary line per coarser mesh (all of it is saved).
        brief = [{k: r[k] for k in ("mesh", "n_q", "commensurate_fraction", "sum_rule_ratio", "lowest_sampled_cm1",
                                    "n_imaginary_modes", "thermal_rms_fluctuation")} for r in rows]
        return {"ok": True, **{k: v for k, v in result.items() if k != "meshes"}, "mesh_summary": brief,
                "production_mesh": rows[-1], "saved": _h._rel(root, out_dir / f"spin_phonon_q_{tag}.json"),
                "spectral_density_csv": _h._rel(root, out_dir / f"spin_phonon_spectral_density_{tag}.csv")}
    except Exception as exc:
        return _h._error(exc)


# --------------------------------------------------------------------------- #
# Mixed force constants: DFT unit cell (Gamma) + MLIP supercell (dispersion)
# --------------------------------------------------------------------------- #


def _compact_fc(phonon) -> np.ndarray:
    """Force constants as (n_unit, n_supercell, 3, 3): rows of the home-cell atoms."""
    from phonopy.harmonic.force_constants import full_fc_to_compact_fc

    fc = np.asarray(phonon.force_constants, dtype=float)
    if fc.shape[0] == len(phonon.supercell) != len(phonon.primitive):
        fc = full_fc_to_compact_fc(phonon.primitive, fc)
    return fc


def _unit_index(phonon) -> np.ndarray:
    """Unit-cell (primitive) index of every supercell atom."""
    p2p = phonon.primitive.p2p_map
    return np.array([p2p[int(s)] for s in phonon.primitive.s2p_map])


def fold_force_constants(phonon) -> np.ndarray:
    """sum_L Phi(0i; Lj) as (n, n, 3, 3): the force constants a 1x1x1 cell sees, = sqrt(m_i m_j) D(q=0)."""
    fc, unit = _compact_fc(phonon), _unit_index(phonon)
    return np.stack([fc[:, unit == j].sum(axis=1) for j in range(len(phonon.primitive))], axis=1)


def nearest_image_weights(phonon, tol: float = 1e-4, reach: int = 2) -> np.ndarray:
    """(n_unit, n_supercell) share of the pair (i, unit(b)) carried by supercell atom b when a lattice sum is placed
    on the NEAREST image r_j + L of j seen from r_i (equidistant images share equally, like phonopy's multiplicity).

    b carries image L when L - R_b is a supercell lattice vector (R_b = the cell of b); the shares of each j sum to 1.
    """
    lat = np.array(phonon.primitive.cell)
    unit = _unit_index(phonon)
    frac = np.array(phonon.supercell.positions) @ np.linalg.inv(lat)  # supercell atoms in unit-cell coordinates
    home = frac[np.asarray(phonon.primitive.p2s_map)]  # not necessarily wrapped into [0, 1)
    diff = home[None, :, :] - home[:, None, :]  # (i, j): r_j - r_i in unit-cell coordinates
    grid = np.array(list(itertools.product(range(-reach, reach + 1), repeat=3)), dtype=float)
    images = -np.rint(diff)[:, :, None, :] + grid  # candidate L around the wrapped difference, (i, j, G, 3)
    dist = np.linalg.norm((diff[:, :, None, :] + images) @ lat, axis=-1)
    ties = dist <= dist.min(axis=2, keepdims=True) + tol
    if ties[:, :, np.abs(grid).max(axis=1) == reach].any():
        raise ValueError("Nearest images lie at the edge of the search: Niggli-reduce this (very skewed) cell first.")
    cell_of = np.rint(frac - home[unit])  # R_b
    inv_m = np.linalg.inv(np.rint(np.array(phonon.supercell.cell) @ np.linalg.inv(lat)))
    weights = np.zeros((len(home), len(unit)))
    for i in range(len(home)):
        rel = (images[i, unit] - cell_of[:, None, :]) @ inv_m  # (b, G, 3)
        t = ties[i, unit]
        weights[i] = (t & np.all(np.abs(rel - np.rint(rel)) < 1e-6, axis=-1)).sum(axis=-1) / t.sum(axis=-1)
    return weights


def mlip_weighted_weights(phonon, floor: float = 1e-8, power: float = 1.5) -> np.ndarray:
    """(n_unit, n_supercell) share of the pair (i, unit(b)) carried by b in proportion to the MLIP's own |Phi(i, b)|**power
    (Frobenius norm): the lattice-sum correction goes where the MLIP says the pair interacts. Pairs whose images all
    have |Phi| below ``floor`` (eV/A^2) fall back to the nearest image. Index-symmetric (|Phi(i,b)| = |Phi(b,i)|) and
    invariant under the space group, so the mixture keeps both.

    power interpolates between proportional (1) and nearest image (infinity). 1.5 beat 1 on all four DFT supercell
    checks (urea 2x2x2 with two UMA sets, C1 1x2x1 with pretrained and fine-tuned UMA): zone-boundary RMS below
    200-250 cm-1 8-30% lower, lowest-branch error 3-10x lower (urea Z soft mode, C1 Y acoustic branch)."""
    norm = np.linalg.norm(_compact_fc(phonon), axis=(2, 3))
    unit = _unit_index(phonon)
    total = np.stack([norm[:, unit == j].sum(axis=1) for j in range(len(phonon.primitive))], axis=1)[:, unit]
    share = norm ** float(power)
    share_total = np.stack([share[:, unit == j].sum(axis=1) for j in range(len(phonon.primitive))], axis=1)[:, unit]
    weights = np.divide(share, share_total, out=np.zeros_like(norm), where=total > floor)
    weak = total <= floor
    if weak.any():
        weights[weak] = nearest_image_weights(phonon)[weak]
    return weights


def mix_force_constants(dft, mlip, placement: str = "mlip_weighted") -> tuple[np.ndarray, np.ndarray]:
    """(compact FC_mix, Delta): FC_MLIP(supercell) + Delta distributed over the images of each pair, Delta = fold FC_DFT(1x1x1) - fold FC_MLIP.

    The shares of each pair sum to one, so folding FC_mix returns the DFT 1x1x1 force constants exactly: D(q=0) and
    every Gamma frequency are DFT's. Away from Gamma, the q dependence of the part of Delta spread over several images
    is unknowable from a 1x1x1 cell; ``placement`` chooses the model:
    'mlip_weighted' (default) -- in proportion to the MLIP's |Phi|^1.5 per image (assumes the MLIP error is
    concentrated where the interaction is strongest). Urea vs a true DFT 2x2x2 (UMA 2x2x2): zone-boundary RMS below
    250 cm-1 2.3-2.6 cm-1, Z soft mode -30.2 vs DFT -33.3 cm-1, F(300 K) within 0.15 kJ/mol per molecule. C1
    ([Co(tu)4]I2, 140 atoms) vs a true DFT 1x2x1 at Y = (0, 1/2, 0): RMS below 200 cm-1 0.49 cm-1 (max 1.7) with a
    fine-tuned UMA, 1.0-1.1 (max 3.5) with the pretrained one, F(300 K) on {Gamma, Y} within 0.1 kJ/mol per formula unit.
    'mlip_weighted_linear' -- |Phi|^1 (the default before 2026-10-03; urea 2.5-2.8 cm-1, Z -24.7; C1 0.63 / 1.6 cm-1).
    'nearest_image' -- all on the nearest image (exact when DFT and MLIP differ only there, e.g. intramolecular
    stiffness; urea 7.5-8.3 cm-1, worst along the 4.7 A c axis where H-bonded chains interact through several images;
    C1 0.79 cm-1 but spurious imaginary modes). Acoustic sum rule and index symmetry carry over from the inputs.
    Both phonopy objects need primitive = unit cell, same atoms in the same order.
    """
    weights = {"mlip_weighted": mlip_weighted_weights, "nearest_image": nearest_image_weights,
               "mlip_weighted_linear": lambda ph: mlip_weighted_weights(ph, power=1.0)}.get(placement)
    if weights is None:
        raise ValueError("placement must be 'mlip_weighted', 'mlip_weighted_linear' or 'nearest_image'.")
    delta = fold_force_constants(dft) - fold_force_constants(mlip)
    return _compact_fc(mlip) + delta[:, _unit_index(mlip)] * weights(mlip)[:, :, None, None], delta


def _cell_deviation(a, b) -> float:
    """Largest Cartesian difference (A) between two unit cells with the same atom order (lattice rows, positions mod lattice)."""
    if list(a.symbols) != list(b.symbols):
        raise ValueError("The DFT and MLIP force constants have different atoms or atom order.")
    lat = np.array(a.cell)
    d = np.array(a.scaled_positions) - np.array(b.scaled_positions)
    d -= np.rint(d)
    return float(max(np.abs(lat - np.array(b.cell)).max(), np.linalg.norm(d @ lat, axis=1).max()))


def _mesh_check(phonon, mesh, temps) -> dict[str, Any]:
    phonon.run_mesh(mesh, is_mesh_symmetry=False, is_gamma_center=True)
    f = np.array(phonon.mesh.frequencies) * THZ_TO_CM1
    gamma = int(np.flatnonzero(np.all(np.abs(phonon.mesh.qpoints) < 1e-12, axis=1))[0])
    rest = np.delete(f, gamma, axis=0)
    return {"mesh": list(mesh), "min_frequency_off_gamma_cm1": round(float(rest.min()), 3),
            "n_modes_below_minus1_cm1_off_gamma": int((rest < -1.0).sum()),
            "thermodynamics": harmonic_thermodynamics(phonon.mesh.frequencies, phonon.mesh.weights, temps)}


UMA_LARGE_CELL_ATOMS = 500  # UMA calls on more atoms ran out of memory on the 8 GB RTX 2070s (VO(acac)2 3x2x3, 1080 atoms)
UMA_LARGE_CELL_GRES = "gpu:rtx5000:1"


def uma_gpu_gres(atoms, min_width: float) -> tuple[str, int]:
    """(gres, atoms per UMA call) for UMA force constants of ``atoms`` in a >= min_width supercell, each call itself replicated to
    >= 9 A by supercell_calculator: above UMA_LARGE_CELL_ATOMS only the large-memory GPU is requested."""
    from Hypothesis_generation.skill_library.clari_uma_relax import uma_supercell_repeats
    from Hypothesis_generation.skill_library.uma_phonon_free_energy import supercell_for

    sc = supercell_for(np.array(atoms.cell), float(min_width))
    n = len(atoms) * int(np.prod(sc)) * int(np.prod(uma_supercell_repeats(np.array(atoms.cell) * np.array(sc)[:, None])))
    return (UMA_LARGE_CELL_GRES if n > UMA_LARGE_CELL_ATOMS else "gpu:1"), n


def mlip_force_constant_job(root: Path, cell_file: Path, ml_dir: Path, *, min_width: float, symprec: float, uma_checkpoint: str,
                            relax_positions: bool, mode: str, slurm_walltime: str, job_name: str, gres: str = "") -> dict[str, Any]:
    """UMA force constants of cell_file (mlip_force_constants, experts merged on the cell) into ml_dir/phonopy_params.yaml, on this
    host's CPU (mode 'local') or one GPU Slurm job (gres '' = uma_gpu_gres by atoms per call). min_width 0 = the 1x1x1 cell: its
    Gamma dynamical matrix is exact."""
    from ase.io import read

    from Hypothesis_generation.skill_library.clari import harness as ch

    args = ["--mlip-fc", _h._rel(root, cell_file), "--output-dir", _h._rel(root, ml_dir), "--min-width", str(float(min_width)),
            "--symprec", str(symprec)]
    if uma_checkpoint.strip():
        args += ["--checkpoint", str(_h._resolve_path(root, uma_checkpoint, must_exist=True, dir_ok=False))]
    if relax_positions:
        args.append("--relax-positions")
    module = "Hypothesis_generation.skill_library.mlip_force_constants"  # outside periodic_dft: no MongoDB import on the GPU node
    if mode == "local":
        proc = ch._run_clari_module(root, module, [*args, "--device", "auto"])
        return {"ok": True} if proc.returncode == 0 else {"ok": False, "error": (proc.stderr or proc.stdout)[-3000:]}
    gres = gres.strip() or uma_gpu_gres(read(str(cell_file)), min_width)[0]
    run = ch._run_clari_module_slurm(
        root, module, [*args, "--device", "cuda"], job_name=job_name, partition="gpunodes", gres=gres, walltime=slurm_walltime,
        mem="64G", cpus_per_task=4, sbatch_others="", poll_interval_seconds=15.0, max_wait_seconds=0.0,
    )
    if not run.get("ok") or not (ml_dir / PHONOPY_PARAMS).is_file():
        return {"ok": False, "slurm_job_id": run.get("job_id"), "gres": gres, "slurm": {k: run.get(k) for k in ("job_id", "state", "stderr")}}
    return {"ok": True, "slurm_job_id": run.get("job_id"), "gres": gres}


def build_mixed_force_constants(
    dft_phonon_dir: Annotated[str, "Completed run_periodic_dft_phonons directory with UNIT-CELL (1x1x1) force constants: they fix every Gamma frequency."],
    mlip_phonon_dir: Annotated[str, "Optional existing MLIP phonopy set (phonopy_params.yaml, labelled in fc_provenance.json or by mlip_source) computed on the SAME cell and atom order as the DFT phonons. Empty = compute UMA force constants on the DFT reference cell now."] = "",
    mlip_source: Annotated[str, "Label for an mlip_phonon_dir without fc_provenance.json, e.g. 'MLIP: UMA uma-s-1p2 (omc), 3x3x4 supercell'."] = "",
    min_supercell_width_angstrom: Annotated[float, "MLIP supercell computed here: every width >= this (>= 2 cells per axis, so q != 0 is supported). ~15 A or more for dispersion and low-energy rates."] = 15.0,
    uma_checkpoint: Annotated[str, "Fine-tuned UMA checkpoint (finetune_uma_model verdict 'use'); empty = pretrained uma-s-1p2. A model fine-tuned on this crystal's DFT gives the better dispersion (C1 vs DFT 1x2x1: zone-boundary RMS below 200 cm-1 0.49 vs 1.1 cm-1 pretrained)."] = "",
    mlip_relax_positions: Annotated[bool, "Take the MLIP Hessian at the MLIP's own minimum (ions relaxed in the fixed DFT cell, symmetry kept) instead of at the DFT positions, where an MLIP with large residual forces has spurious negative curvature."] = True,
    execution_mode: Annotated[str, "MLIP force constants: 'auto' (GPU Slurm job unless this host sees CUDA), 'submit_local_slurm_gpu', or 'local' (this host's CPU; refused above ~20 CPU-minutes unless allow_long_local)."] = "auto",
    allow_long_local: Annotated[bool, "Run the UMA force constants on this CPU even when slow."] = False,
    slurm_walltime: Annotated[str, "GPU job walltime."] = "02:00:00",
    gpu_gres: Annotated[str, "Slurm GPU request for the UMA force constants; '' = by atoms per UMA call: > 500 -> gpu:rtx5000:1 (the 8 GB RTX 2070s run out of memory on a ~1000-atom supercell), else gpu:1."] = "",
    max_geometry_deviation_angstrom: Annotated[float, "Refuse an MLIP set whose cell or positions differ from the DFT reference cell by more than this."] = 0.01,
    correction_placement: Annotated[str, "How each pair's Gamma correction is spread over its images: 'mlip_weighted' (default, in proportion to the MLIP's |force constant|^1.5 per image; best on urea vs a true DFT 2x2x2 and C1 vs a true DFT 1x2x1), 'mlip_weighted_linear' (|force constant|^1, the pre-2026-10-03 default) or 'nearest_image'."] = "mlip_weighted",
    temperatures_k: Annotated[str, "Temperatures for the free-energy comparison."] = "5 20 100 300",
    output_dir: Annotated[str, "Default <dft_phonon_dir>_mixed next to the DFT phonons."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Dense-q phonons without a DFT supercell: DFT 1x1x1 force constants (exact Gamma) + MLIP supercell force constants (dispersion), for analyze_spin_phonon_q_mesh."""
    root = _h._root(runtime)
    try:
        from phonopy import Phonopy

        dft_dir = _h._resolve_path(root, dft_phonon_dir, must_exist=True, file_ok=False)
        if not (dft_dir / PHONON_MANIFEST).is_file():
            raise ValueError("dft_phonon_dir must be a completed run_periodic_dft_phonons directory.")
        dft = _load_phonon(dft_dir)
        if not len(dft.supercell) == len(dft.primitive) == len(dft.unitcell):
            raise ValueError("The DFT set must be 1x1x1 with primitive = unit cell; a DFT supercell set can be used directly.")
        symprec = float(cc._read_json(dft_dir / PHONON_MANIFEST).get("symprec") or 1e-3)
        temps = [float(t) for t in temperatures_k.split()]
        warnings = []
        noise = cc._read_json(dft_dir / PHONON_SUMMARY).get("numerical_noise") or {}
        if noise.get("verdict") not in (None, "clean"):
            warnings.append(f"The DFT phonons are numerically {noise['verdict']}: the Gamma frequencies imposed on the mixture carry that noise.")
        mlip_run = None
        if mlip_phonon_dir.strip():
            ml_dir = _h._resolve_path(root, mlip_phonon_dir, must_exist=True, file_ok=False)
            ml_prov = cc._read_json(ml_dir / FC_PROVENANCE)
            ml_label = mlip_source.strip() or ml_prov.get("force_constants_source") or ml_prov.get("label") or ""
            if not ml_label:
                raise ValueError("Label the MLIP set with mlip_source (e.g. 'MLIP: UMA uma-s-1p2 (omc), 3x3x4 supercell').")
            out = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else dft_dir.parent / f"{dft_dir.name}_mixed_{ml_dir.name}")
        else:
            from Hypothesis_generation.skill_library.clari import harness as ch
            from Hypothesis_generation.skill_library.periodic_dft.crystal_csp import UMA_CPU_SECONDS_PER_ATOM
            from Hypothesis_generation.skill_library.uma_phonon_free_energy import supercell_for

            out = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else dft_dir.parent / f"{dft_dir.name}_mixed")
            ml_dir = out / "mlip"
            if not (ml_dir / PHONOPY_PARAMS).is_file():
                from ase.io import write

                ml_dir.mkdir(parents=True, exist_ok=True)
                cell_file = ml_dir / "dft_reference_cell.extxyz"
                write(str(cell_file), _ase_atoms(dft.unitcell), format="extxyz")
                # >= 2 periods per axis: analyze_spin_phonon_q_mesh refuses 1-period axes (C1, a = 18 A, got 1x2x2 at 15 A).
                sc = [max(2, n) for n in supercell_for(np.array(dft.unitcell.cell), float(min_supercell_width_angstrom))]
                probe = Phonopy(dft.unitcell, supercell_matrix=np.diag(sc), primitive_matrix="P", symprec=symprec)
                probe.generate_displacements(distance=0.01, is_plusminus="auto")
                evals = (len(probe.supercells_with_displacements) + 1) * len(probe.supercell)
                mode = ch._normalize_clari_execution_mode(execution_mode, device="auto", num_gpus=1)
                mlip_run = {"supercell": sc, "n_displacements": len(probe.supercells_with_displacements), "n_atoms_supercell": len(probe.supercell),
                            "cpu_minutes_estimate": round(evals * UMA_CPU_SECONDS_PER_ATOM / 60.0, 1), "execution_mode": mode,
                            "gpu_gres": gpu_gres.strip() or uma_gpu_gres(_ase_atoms(probe.supercell), 0.0)[0]}
                if mode == "local" and mlip_run["cpu_minutes_estimate"] > 20 and not allow_long_local:
                    return {"ok": False, "status": "too_slow_for_local_cpu", "mlip": mlip_run,
                            "error": "UMA force constants would take too long on this CPU: use execution_mode='submit_local_slurm_gpu' (or allow_long_local=True)."}
                job = mlip_force_constant_job(root, cell_file, ml_dir, min_width=float(min_supercell_width_angstrom), symprec=symprec,
                                              uma_checkpoint=uma_checkpoint, relax_positions=mlip_relax_positions, mode=mode,
                                              slurm_walltime=slurm_walltime, job_name=f"{dft_dir.name}_mlip_fc", gres=mlip_run["gpu_gres"])
                if "slurm_job_id" in job:
                    mlip_run["slurm_job_id"] = job.pop("slurm_job_id")
                if not job["ok"]:
                    return {"ok": False, "mlip": mlip_run, **job}
            ml_label = cc._read_json(ml_dir / FC_PROVENANCE)["force_constants_source"]
        mlip = _load_phonon(ml_dir)
        if len(mlip.primitive) != len(mlip.unitcell):
            raise ValueError("The MLIP set needs primitive_matrix 'P' (primitive = unit cell).")
        deviation = _cell_deviation(dft.unitcell, mlip.unitcell)
        if deviation > float(max_geometry_deviation_angstrom):
            raise ValueError(
                f"The MLIP force constants were computed on a different cell ({deviation:.3f} A from the DFT reference): both "
                "Hessians must be taken at the same structure. Leave mlip_phonon_dir empty to compute UMA force constants on the DFT cell."
            )
        periods = fc_supercell_support(mlip, [1, 1, 1])["fc_supercell_periods"]
        if min(periods) < 2:
            warnings.append(f"MLIP supercell periods {periods}: q != 0 stays unsupported along the 1-period axes.")
        ml_prov = cc._read_json(ml_dir / FC_PROVENANCE)
        if "UMA" in ml_label and not ml_prov.get("uma_experts_merged_on"):
            # UMA mixes its experts by atom count: unmerged, a 1120-atom supercell is not the 140-atom cell's model
            # (C1 pretrained: +161 meV/cell, forces up to 0.19 eV/A for the same structure).
            warnings.append("UMA force constants made without merged experts (older mlip_force_constants run): the supercell model differs "
                            "from the unit-cell one. Recompute them (leave mlip_phonon_dir empty) for a size-consistent set.")
        moved = ml_prov.get("max_displacement_from_input_A")
        if moved and float(moved) > 0.1:
            warnings.append(f"The MLIP minimum lies up to {float(moved):.2f} A from the DFT structure (C1 with pretrained UMA: 0.41 A): its "
                            "dispersion describes a different structure. Fine-tune the MLIP on this crystal's DFT (finetune_uma_model) before trusting q != 0.")

        fc_mix, delta = mix_force_constants(dft, mlip, correction_placement.strip())
        mixed = _load_phonon(ml_dir)
        mixed.force_constants = fc_mix
        mixed.symmetrize_force_constants(show_drift=False)

        def gamma(ph):
            ph.run_qpoints([[0.0, 0.0, 0.0]])
            return np.array(ph.qpoints.frequencies[0]) * THZ_TO_CM1

        f_dft, f_ml, f_mix = gamma(dft), gamma(mlip), gamma(mixed)
        opt = slice(3, None)
        lat = np.array(dft.primitive.cell)
        frac = np.array(dft.primitive.scaled_positions)
        d = frac[None] - frac[:, None]
        d -= np.rint(d)
        pair = np.linalg.norm(d @ lat, axis=-1)  # pair distance in the unit cell (minimum image within ~1 cell)
        w2 = (delta**2).sum(axis=(2, 3))
        widths = [abs(np.linalg.det(lat)) / np.linalg.norm(np.cross(lat[(i + 1) % 3], lat[(i + 2) % 3])) for i in range(3)]
        mesh = [max(2, int(math.ceil(40.0 / w))) for w in widths]
        checks = {
            "gamma_max_abs_deviation_mixed_vs_dft_cm1": float(np.abs(f_mix - f_dft).max()),
            "mlip_vs_dft_gamma_optical_cm1": {
                "rms": round(float(np.sqrt(np.mean((f_ml[opt] - f_dft[opt]) ** 2))), 3),
                "max_abs": round(float(np.abs(f_ml[opt] - f_dft[opt]).max()), 3),
                "rms_below_200cm1": round(float(np.sqrt(np.mean(((f_ml - f_dft)[opt][f_dft[opt] < 200.0]) ** 2))), 3) if (f_dft[opt] < 200.0).any() else None,
            },
            "correction_relative_norm": round(float(np.sqrt(w2.sum() / (fold_force_constants(dft) ** 2).sum())), 5),
            "correction_share_on_pairs_within_2A": round(float(w2[pair < 2.0].sum() / w2.sum()), 4) if w2.sum() > 0 else None,
            "mlip_only_mesh": _mesh_check(mlip, mesh, temps),
            "mixed_mesh": _mesh_check(mixed, mesh, temps),
            "dft_gamma_only_thermodynamics": harmonic_thermodynamics([f_dft / THZ_TO_CM1], [1.0], temps),
            "geometry_deviation_angstrom": round(deviation, 6),
        }
        if checks["gamma_max_abs_deviation_mixed_vs_dft_cm1"] > 0.05:
            warnings.append("Symmetrization moved the mixed Gamma frequencies off the DFT ones: one input violates the acoustic sum rule or index symmetry.")
        if checks["mixed_mesh"]["n_modes_below_minus1_cm1_off_gamma"]:
            warnings.append(f"{checks['mixed_mesh']['n_modes_below_minus1_cm1_off_gamma']} imaginary modes away from Gamma on the {mesh} mesh "
                            f"(MLIP alone: {checks['mlip_only_mesh']['n_modes_below_minus1_cm1_off_gamma']}): soft MLIP dispersion or a too-small supercell.")
        out.mkdir(parents=True, exist_ok=True)
        mixed.save(filename=str(out / PHONOPY_PARAMS), settings={"force_constants": True, "force_sets": False, "displacements": False})
        sc_tag = "x".join(str(int(v)) for v in np.diag(np.array(mlip.supercell_matrix)))
        provenance = {
            "force_constants_source": f"{MIXED_FC_SOURCE}: DFT {_h._rel(root, dft_dir)} (1x1x1, Gamma exact) + {ml_label} ({sc_tag})",
            "symprec": symprec, "dft_phonon_dir": _h._rel(root, dft_dir), "mlip_phonon_dir": _h._rel(root, ml_dir), "mlip_source": ml_label,
            "scheme": f"FC_mix = FC_MLIP(supercell) + [fold FC_DFT(1x1x1) - fold FC_MLIP] spread over each pair's images "
                      f"({correction_placement.strip()}, shares sum to 1); translational + index symmetrization. "
                      "fold FC_mix = FC_DFT(1x1x1): Gamma = DFT exactly.",
            "correction_placement": correction_placement.strip(),
            "checks": checks, "mlip_run": mlip_run, "warnings": warnings,
        }
        (out / FC_PROVENANCE).write_text(json.dumps(provenance, indent=1, default=str))
        return {"ok": True, "phonon_dir": _h._rel(root, out), "force_constants_source": provenance["force_constants_source"],
                "fc_supercell": sc_tag, **{k: v for k, v in checks.items() if not k.endswith("_mesh")},
                "mlip_only_mesh": {k: v for k, v in checks["mlip_only_mesh"].items() if k != "thermodynamics"},
                "mixed_mesh": checks["mixed_mesh"], "mlip_run": mlip_run, "warnings": warnings,
                "next_step": "analyze_spin_phonon_q_mesh(..., phonon_dir=<this phonon_dir>) with q meshes up to 12^3-16^3 (the label is read automatically)."}
    except Exception as exc:
        return _h._error(exc)


# --------------------------------------------------------------------------- #
# Magnetic orderings
# --------------------------------------------------------------------------- #


def _site_permutations(atoms, metal_indices: list[int], symprec: float = 1e-3) -> list[list[int]]:
    """How each space-group operation permutes the metal sites (positions in metal_indices)."""
    import spglib

    cell = (atoms.cell.array, atoms.get_scaled_positions(), atoms.get_atomic_numbers())
    ops = spglib.get_symmetry(cell, symprec=symprec) or {"rotations": [np.eye(3, dtype=int)], "translations": [np.zeros(3)]}
    frac = atoms.get_scaled_positions()
    perms = []
    for rot, trans in zip(ops["rotations"], ops["translations"]):
        perm = []
        for i in metal_indices:
            image = (rot @ frac[i] + trans) % 1.0
            d = frac[metal_indices] - image
            d -= np.round(d)
            perm.append(int(np.argmin(np.linalg.norm(d @ atoms.cell.array, axis=1))))
        perms.append(perm)
    return perms


def pair_classes(atoms, metal_indices: list[int]) -> list[list[tuple[int, int]]]:
    """Symmetry-equivalence classes of site pairs (positions in metal_indices)."""
    perms = _site_permutations(atoms, metal_indices)
    classes, seen = [], set()
    for pair in itertools.combinations(range(len(metal_indices)), 2):
        if pair in seen:
            continue
        orbit = {tuple(sorted((perm[pair[0]], perm[pair[1]]))) for perm in perms}
        seen |= orbit
        classes.append(sorted(orbit))
    return classes


def fit_ising_exchange(rows: list[dict[str, Any]], classes: list[list[tuple[int, int]]], spin: float) -> dict[str, Any]:
    """E(sigma) = E0 + sum_t J_t sum_(ij in t) sigma_i sigma_j  (J_t > 0 antiferromagnetic).

    J_t is per pair and already includes S^2 and every periodic image of that pair
    type; J_heis = J_t / S^2 is the H = sum J S_i.S_j constant (cm-1 also given).
    """
    design = [[1.0] + [float(sum(r["pattern"][i] * r["pattern"][j] for i, j in cls)) for cls in classes] for r in rows]
    energy = [r["energy_hartree"] * 27211.386 for r in rows]
    a, e = np.array(design), np.array(energy)
    if len(rows) < a.shape[1] or np.linalg.matrix_rank(a) < a.shape[1]:
        return {"fitted": False, "reason": f"{len(rows)} usable orderings cannot determine E0 + {len(classes)} pair classes."}
    coef, *_ = np.linalg.lstsq(a, e, rcond=None)
    resid = e - a @ coef
    out = []
    for cls, j in zip(classes, coef[1:]):
        out.append({
            "pairs": [list(p) for p in cls], "J_meV": round(float(j), 4),
            "J_heisenberg_cm1": round(float(j) / spin**2 * 8.0655, 4) if spin else None,
            "sign": "antiferromagnetic" if j > 0 else "ferromagnetic",
        })
    return {
        "fitted": True, "classes": out, "overdetermined_by": len(rows) - a.shape[1],
        "residual_rms_meV": round(float(np.sqrt(np.mean(resid**2))), 5),
        "convention": "E = E0 + sum J_t sigma_i sigma_j per cell; H = sum J S_i.S_j with J = J_t/S^2 (J>0 AFM)",
    }


def enumerate_collinear_orderings(atoms, metal_indices: list[int], symprec: float = 1e-3) -> list[tuple[int, ...]]:
    """Symmetry-distinct up/down patterns of the metal sites (global flip removed)."""
    perms = _site_permutations(atoms, metal_indices, symprec)
    seen, reps = set(), []
    for pattern in itertools.product((1, -1), repeat=len(metal_indices)):
        if pattern[0] != 1:
            continue
        orbit = set()
        for perm in perms:
            image = tuple(pattern[perm[k]] for k in range(len(pattern)))
            orbit.add(image)
            orbit.add(tuple(-s for s in image))
        if not orbit & seen:
            reps.append(pattern)
        seen |= orbit
    return reps


def run_periodic_dft_magnetic_orderings(
    structure_path: Annotated[str, "Periodic structure (relaxed, or the experimental cell for a first look)."] = "",
    metal: Annotated[str, "Metal element whose moments are ordered, e.g. 'Co'."] = "",
    moment: Annotated[float, "Unpaired electrons per metal (2S), e.g. 3 for Co(II) high spin."] = 0.0,
    charge: Annotated[int | None, "Total cell charge."] = None,
    spin_state_rationale: Annotated[str, "Local spin state and why (required for TM cells)."] = "",
    max_orderings: Annotated[int, "Refuse if more symmetry-distinct orderings than this (large supercells explode)."] = 12,
    continue_from_job_dir: Annotated[str, "Optional converged crystal job whose structure/wavefunction seeds the FM point."] = "",
    dft_plus_u_json: Annotated[str, "Optional DFT+U (same for all orderings)."] = "",
    dft_plus_u_rationale: Annotated[str, "Required with dft_plus_u_json."] = "",
    functional: Annotated[str, "'PBE' or 'PBE0' (ADMM2 hybrid: far better exchange constants; seed it with seed_from_orderings_dir)."] = "PBE",
    dispersion_type: Annotated[str, "'DFTD3' or 'DFTD3(BJ)'."] = "DFTD3",
    seed_from_orderings_dir: Annotated[str, "Earlier orderings directory (e.g. the PBE set): each ordering restarts from its own converged wavefunction there."] = "",
    cutoff_ry: Annotated[int, "Plane-wave cutoff (semicore floor applies)."] = 400,
    np: Annotated[int, "Cores per ordering."] = 16,
    mem: Annotated[str, "Memory per ordering."] = "32G",
    max_core_hours_per_ordering: Annotated[float, "Hard cap per ordering."] = 24.0,
    max_total_core_hours: Annotated[float, "Hard cap on the sum."] = 150.0,
    partition: Annotated[str, "Optional partition."] = "",
    output_dir: Annotated[str, "Default calculations/periodic_dft_<structure>/magnetic_orderings."] = "",
    execution_mode: Annotated[str, "'dry_run' or 'submit'."] = "dry_run",
    submit_approved: Annotated[bool, "Must be True to submit."] = False,
    wait_for_completion: Annotated[bool, "Wait and summarize."] = True,
    max_wait_hours: Annotated[float, "Upper bound on waiting."] = 48.0,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Single points of every symmetry-distinct collinear ordering of one metal's moments; energies and pattern checks."""
    root = _h._root(runtime)
    try:
        wfn = ""
        if continue_from_job_dir.strip():
            prior = cc._continuation_inputs(root, _h._resolve_path(root, continue_from_job_dir, must_exist=True, file_ok=False))
            structure_path = structure_path.strip() or _h._rel(root, prior["structure"])
            wfn = prior["wfn"]
            charge = prior["charge"] if charge is None else charge
            spin_state_rationale = spin_state_rationale or prior["rationale"]
        structure = _h._resolve_path(root, structure_path, must_exist=True, dir_ok=False)
        atoms, warnings = cc.load_periodic_structure(structure)
        sites = [i for i, s in enumerate(atoms.get_chemical_symbols()) if s == metal]
        if len(sites) < 2:
            raise ValueError(f"Need at least two {metal!r} sites to compare orderings (found {len(sites)}).")
        if moment <= 0:
            raise ValueError("moment (unpaired electrons per metal) must be positive.")
        patterns = enumerate_collinear_orderings(atoms, sites)
        if len(patterns) > max_orderings:
            raise ValueError(f"{len(patterns)} symmetry-distinct orderings > max_orderings={max_orderings}.")
        planned = len(patterns) * float(max_core_hours_per_ordering)
        if planned > float(max_total_core_hours):
            raise ValueError(f"{len(patterns)} orderings x {max_core_hours_per_ordering} = {planned:g} core-h > max_total_core_hours.")
        out = _h._under_root(
            root,
            _h._resolve_path(root, output_dir) if output_dir.strip()
            else _stage_dir(root, structure, "magnetic_orderings" if functional == "PBE" else f"magnetic_orderings_{functional.lower()}"),
        )
        out.mkdir(parents=True, exist_ok=True)
        seed_dir = _h._resolve_path(root, seed_from_orderings_dir, must_exist=True, file_ok=False) if seed_from_orderings_dir.strip() else None
        rows = []
        for n, pattern in enumerate(patterns):
            label = "FM" if all(s == 1 for s in pattern) else "order_" + "".join("u" if s > 0 else "d" for s in pattern)
            seed = str(seed_dir / label / "crystal-RESTART.wfn") if seed_dir and (seed_dir / label / "crystal-RESTART.wfn").is_file() else (wfn if label == "FM" else "")
            net = abs(sum(pattern)) * moment
            mags = {str(site): float(s * moment) for site, s in zip(sites, pattern)}
            outcome = cc._prepare_and_submit(
                root, atoms=atoms, job_dir=out / label,
                source_structure={"path": _h._rel(root, structure), "sha256": cc._sha256(structure), "pattern": list(pattern)},
                calculation="energy_force", charge=charge, multiplicity=int(round(net)) + 1,
                spin_state_rationale=f"{spin_state_rationale} | collinear ordering {pattern} of {metal} (2S={moment:g} each); broken-symmetry for antiparallel sites",
                site_magnetization_json=json.dumps({"indices": mags}),
                relax_only_elements="", fixed_elements="", fixed_indices="", strain_voigt=None,
                electric_field_v_per_m=0.0, field_direction="z", kpoints="GAMMA", functional=functional,
                basis_set="DZVP-MOLOPT-SR-GTH", basis_set_file_name="BASIS_MOLOPT", potential_file_name="GTH_POTENTIALS",
                potential_prefix="GTH-PBE", basis_overrides_json="", potential_overrides_json="", cutoff_ry=cutoff_ry,
                rel_cutoff_ry=60, eps_scf="1.0E-7", max_scf=150, dispersion=True, max_iter=1, max_force="4.5E-4",
                rms_force="3.0E-4", external_pressure_bar=1.01325, np=np, mem=mem, max_core_hours=max_core_hours_per_ordering,
                partition=partition, sbatch_others="", execution_mode=execution_mode, submit_approved=submit_approved,
                overwrite=False, warnings=[], dft_plus_u_json=dft_plus_u_json, dft_plus_u_rationale=dft_plus_u_rationale,
                wfn_restart_source=seed, dispersion_type=dispersion_type,
            )
            rows.append({"label": label, "pattern": list(pattern), "sites": sites, "status": outcome.get("status"), "job_id": outcome.get("job_id")})
            if not outcome.get("ok") and not outcome.get("duplicate_submission_prevented"):
                return {"ok": False, "status": "ordering_failed_before_submission", "failed": label, "detail": outcome}
        manifest = {"structure": _h._rel(root, structure), "metal": metal, "moment": moment, "sites": sites, "orderings": rows,
                    "functional": functional, "seeded_from": seed_from_orderings_dir.strip() or None}
        (out / ORDERING_MANIFEST).write_text(json.dumps(manifest, indent=1))
        if execution_mode == "dry_run" or not wait_for_completion:
            return {"ok": True, "status": "dry_run_validated" if execution_mode == "dry_run" else "submitted", "dir": _h._rel(root, out), "orderings": rows, "planned_core_hours_cap": planned, "warnings": warnings}
        return collect_periodic_dft_magnetic_orderings(_h._rel(root, out), wait=True, max_wait_hours=max_wait_hours, runtime=runtime)
    except Exception as exc:
        return _h._error(exc)


def collect_periodic_dft_magnetic_orderings(
    ordering_dir: Annotated[str, "Directory with magnetic_ordering_manifest.json."],
    wait: Annotated[bool, "Wait for all orderings."] = False,
    max_wait_hours: Annotated[float, "Upper bound on waiting."] = 48.0,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Energies of each ordering relative to the lowest, whether each SCF kept its spin pattern, and an Ising exchange fit."""
    root = _h._root(runtime)
    try:
        directory = _h._resolve_path(root, ordering_dir, must_exist=True, file_ok=False)
        manifest = cc._read_json(directory / ORDERING_MANIFEST)
        deadline = _h._monotonic() + float(max_wait_hours) * 3600.0
        rows = []
        for entry in manifest["orderings"]:
            job = directory / entry["label"]
            if wait:
                cc._wait(root, job, max_wait_seconds=max(0.0, deadline - _h._monotonic()), poll_seconds=60.0, runtime=runtime)
            collected = cc._collect(root, job, runtime=runtime)
            full = cc._read_json(job / cc.JOB_RESULTS).get("results") or {}
            spins = {a["index"]: a["spin"] for a in ((full.get("mulliken") or {}).get("atoms") or [])}
            site_spins = [spins.get(i) for i in entry["sites"]]
            kept = all(sp is not None and np.sign(sp) == np.sign(s) and abs(sp) > 0.5 for sp, s in zip(site_spins, entry["pattern"])) if spins else None
            rows.append({
                "label": entry["label"], "pattern": entry["pattern"], "status": collected.get("status"),
                "energy_hartree": (collected.get("results") or {}).get("energy_hartree"),
                "site_spins": [round(s, 3) if s is not None else None for s in site_spins],
                "pattern_kept": kept, "core_hours_used": collected.get("core_hours_used"),
            })
        done = [r for r in rows if r["status"] == "completed" and r["energy_hartree"] is not None and r["pattern_kept"]]
        if done:
            e0 = min(r["energy_hartree"] for r in done)
            for r in rows:
                if r["energy_hartree"] is not None:
                    r["relative_energy_meV_per_cell"] = round((r["energy_hartree"] - e0) * 27211.386, 2)
        exchange = None
        if len(done) >= 3 and manifest.get("structure"):
            atoms, _w = cc.load_periodic_structure(_h._resolve_path(root, manifest["structure"], must_exist=True, dir_ok=False))
            sites = manifest["sites"]
            classes = pair_classes(atoms, sites)
            exchange = fit_ising_exchange(done, classes, float(manifest.get("moment") or 0) / 2.0)
            if exchange.get("fitted"):
                for entry in exchange["classes"]:
                    i, j = entry["pairs"][0]
                    entry["min_image_distance_angstrom"] = round(float(atoms.get_distance(sites[i], sites[j], mic=True)), 3)
        summary = {
            "dir": _h._rel(root, directory), "metal": manifest.get("metal"), "orderings": rows, "exchange_fit": exchange,
            "lowest": min(done, key=lambda r: r["energy_hartree"])["label"] if done else None,
            "pattern_not_kept": [r["label"] for r in rows if r["pattern_kept"] is False],
            "pending": [r["label"] for r in rows if r["status"] == "running"],
            "caveat": "Broken-symmetry PBE(-D3) energies: order-of-magnitude exchange only; compare within this set, same geometry and settings.",
        }
        (directory / "magnetic_ordering_summary.json").write_text(json.dumps(summary, indent=1, default=str))
        status = "running" if summary["pending"] else ("completed" if len(done) == len(rows) else "finished_with_issues")
        return {"ok": True, "status": status, **summary}
    except Exception as exc:
        return _h._error(exc)


def compare_phonon_hamiltonians(
    phonon_dir_reference: Annotated[str, "Phonon directory of the structure under the reference Hamiltonian (e.g. plain PBE-D3(BJ))."],
    phonon_dir_test: Annotated[str, "Phonon directory of the SAME structure (same atom order) under the alternative Hamiltonian (e.g. PBE-D3(BJ)+U 4 eV on Cu 3d)."],
    band_cm1: Annotated[str, "Frequency band (cm-1, of the reference modes) whose matched shift decides: 'lo hi'."] = "150 400",
    shift_threshold: Annotated[float, "Largest acceptable |mean relative shift| of the matched band modes."] = 0.05,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Gamma modes of one structure under two Hamiltonians, matched by eigenvector overlap (assignment on |<e_a|e_b>|^2), and the
    relative frequency shift of the matched modes in the band. Cu(II) U-check (user rule 2026-10-10): the CuOEP control
    (err_2) used PBE-D3+U 4 eV in a Gamma supercell; plain-PBE k-point phonons of a Cu candidate may feed Gamma_II only if the
    isolated molecule (20 A box, Gamma) gives |mean relative shift| <= 5% over 150-400 cm-1 between PBE and PBE+U 4 eV, and
    the crystal's Cu spin is ~0.5-0.6 with each N <= 0.1. Otherwise the carried polymorph is relaxed and its phonons redone
    with +U in a Gamma supercell."""
    root = _h._root(runtime)
    try:
        from scipy.optimize import linear_sum_assignment
        from Hypothesis_generation.skill_library.periodic_dft import spin_relaxation as sr

        a, b = sr.load_gamma_set(root, phonon_dir_reference, ""), sr.load_gamma_set(root, phonon_dir_test, "")
        if len(a.masses) != len(b.masses) or not np.allclose(a.masses, b.masses):
            raise ValueError("The two phonon sets are not the same atoms in the same order.")
        lo, hi = (float(x) for x in band_cm1.split())
        ia = [i for i in range(len(a.freqs)) if i not in a.acoustic]
        ib = [i for i in range(len(b.freqs)) if i not in b.acoustic]
        overlap = (a.vecs[:, ia].T @ b.vecs[:, ib]) ** 2
        rows, cols = linear_sum_assignment(-overlap)
        pairs = [{"reference_cm1": round(float(a.freqs[ia[r]]), 2), "test_cm1": round(float(b.freqs[ib[c]]), 2),
                  "overlap": round(float(overlap[r, c]), 4)} for r, c in zip(rows, cols) if lo <= a.freqs[ia[r]] <= hi]
        if not pairs:
            raise ValueError(f"No reference mode in {lo:g}-{hi:g} cm-1.")
        rel = np.array([p["test_cm1"] / p["reference_cm1"] - 1.0 for p in pairs])
        mean = float(rel.mean())
        ok = abs(mean) <= float(shift_threshold)
        weak = [p for p in pairs if p["overlap"] < 0.5]
        return {"ok": True, "band_cm1": [lo, hi], "n_band_modes": len(pairs), "mean_relative_shift": round(mean, 4),
                "max_abs_relative_shift": round(float(np.abs(rel).max()), 4), "median_overlap": round(float(np.median([p["overlap"] for p in pairs])), 4),
                "verdict": "within_threshold" if ok else "exceeds_threshold", "shift_threshold": float(shift_threshold),
                "next_step": ("plain-Hamiltonian phonons may be used (record this verdict as the candidate's U-check gate)" if ok else
                              "relax the carried polymorph and redo its phonons with the test Hamiltonian (+U: Gamma supercell ~14 A)"),
                "warnings": [f"{len(weak)} band modes match with overlap < 0.5 (mixed modes): the shift there is approximate."] if weak else [],
                "pairs": pairs}
    except Exception as exc:
        return _h._error(exc)


crystal_phonon_tool_map = {name: tool(fn) for name, fn in {
    "run_periodic_dft_phonons": run_periodic_dft_phonons,
    "collect_periodic_dft_phonons": collect_periodic_dft_phonons,
    "generate_phonon_thermal_snapshots": generate_phonon_thermal_snapshots,
    "export_phonon_mode_displacements": export_phonon_mode_displacements,
    "compare_phonon_adps_with_experiment": compare_phonon_adps_with_experiment,
    "export_cluster_cartesian_displacements": export_cluster_cartesian_displacements,
    "export_random_cluster_displacements": export_random_cluster_displacements,
    "analyze_vibronic_property": analyze_vibronic_property,
    "analyze_spin_phonon_q_mesh": analyze_spin_phonon_q_mesh,
    "build_mixed_force_constants": build_mixed_force_constants,
    "run_periodic_dft_magnetic_orderings": run_periodic_dft_magnetic_orderings,
    "collect_periodic_dft_magnetic_orderings": collect_periodic_dft_magnetic_orderings,
    "compare_phonon_hamiltonians": compare_phonon_hamiltonians,
}.items()}
