"""Low-mode DFT Hessian of a large crystal cell: Rayleigh-Ritz in a trial subspace taken from an MLIP Hessian.

Why: a 116-atom P-1 cell on a 2x2x2 k mesh (VOPc) costs ~8-11 core-h per CP2K force evaluation, so full Gamma finite
differences (174+ displacements) are ~1,500-1,900 core-h, while the Raman T1 (spin_relaxation.compute_spin_relaxation_time)
only uses the Gamma modes below ~150 cm-1.

Mass-weighted coordinates throughout (atom-major x, y, z; D = M^-1/2 Phi M^-1/2 at Gamma, eV/(A^2 amu), as phonopy):
1. Trial subspace V (3n x N, orthonormal): the N lowest non-translational Gamma modes of an MLIP dynamical matrix of the UNIT
   CELL AT THE DFT GEOMETRY (pretrained UMA by default, 1x1x1 = Gamma-exact for the model). No MLIP relaxation: UMA's minimum of
   VO(acac)2 lies 0.16 A from DFT's and its relaxed-geometry dispersion had -60 cm-1 acoustic branches. The 3 rigid
   translations are projected out explicitly. Any phonopy_params.yaml (fine-tuned UMA, tests) can be the trial source.
   Default N = ceil(1.3 m) + 10, m = MLIP modes below mode_cutoff_cm1.
2. DFT along each v_k: x0 + delta_k M^-1/2 v_k (delta_k in amu^1/2 A; default: largest atomic displacement 0.015 A), CP2K
   energy_force with the stationary structure's Hamiltonian/spin contract/k mesh (crystal_phonons.displacement_settings), one
   Slurm array; d_k = -M^-1/2 (F+ - F0)/delta_k = D v_k, the full 3n column (default one-sided: F0 = the equilibrium job, which
   is needed anyway for the wavefunction restarts; error O(delta) from the cubic anharmonicity). plus_minus=True: x0 -/+, central
   -M^-1/2 (F+ - F-)/(2 delta_k), error O(delta^2), twice the jobs.
3. H = V^T [d_1..d_N] (symmetrized; the asymmetry measures noise) -> lambda_i, c_i; Ritz vectors y_i = V c_i; frequencies
   sign(lambda) sqrt|lambda| x phonopy's VaspToTHz x 33.356. Residual r_i = sum_k c_ik d_k - lambda_i y_i = D y_i - lambda_i y_i:
   D is symmetric, so an exact eigenvalue lies within |r_i| of lambda_i (frequency interval reported); |r_i|/|lambda_i| > 0.1 is
   flagged. Ritz values are upper bounds of the lowest exact ones, and a mode orthogonal to V is simply absent.
   The rigorous bound is loose for low modes: a contamination eps by a mode at w_h adds eps (w_h^2 - lambda) to |r| but only
   eps^2 (w_h^2 - lambda) to lambda, so on VO(acac)2 every mode below 150 cm-1 was flagged even when converged to 0.1 cm-1.
   The usable estimate is the MLIP-preconditioned Davidson correction t_i = -(D_MLIP - lambda_i)^-1 r_i (orthogonal to V):
   lambda_exact ~ lambda_i + t_i.r_i and |t_i| ~ the eigenvector error (VO(acac)2, N = 40: estimated vs true frequency
   errors 3.3/3.0, 13.3/12.7, 19.3/18.3 cm-1); modes whose estimate exceeds frequency_tolerance_cm1 are 'unconverged'.
4. Block-Davidson rounds: collect PROPOSES the corrections t_i of the unconverged modes below the cutoff, orthogonalized against
   the subspace (davidson_proposal.json, with its cost); run_low_mode_dft_hessian_round prepares/submits ONLY those displaced
   cells in the same directory, and collect merges every round: the union of all trial vectors is re-orthonormalized
   (V = U S W^T, Q = V W S^-1) and every measured column takes the same change, D Q = (D V) W S^-1, so one Rayleigh-Ritz uses all
   DFT data. Plain residual directions barely help (they point at the stiff modes); the preconditioned ones took VO(acac)2
   N = 40 from 4.5 to 0.09 cm-1 rms.
Emulation on the complete pilot DFT sets (pretrained UMA at the DFT geometry; Raman T1 from compute_spin_relaxation_time;
identical through the real tools with fake Slurm and harmonic DFT forces) with the defaults (one-sided, N = ceil(1.3 m) + 10,
one Davidson round, 1 cm-1 tolerance): VO(acac)2, m = 23 -> N = 40: round 1 4.5 cm-1 rms, T1 +21..+227%; + 21 vectors:
0.09 cm-1, T1 within 1.4%, the two imaginary modes recovered (-59.8/-55.2 vs -60.1/-55.4); 62 CP2K jobs vs 91 for full
one-sided phonons. C1 Z2, m = 31 -> N = 51: 0.79 cm-1, T1 +4..+9%; + 4 vectors: 0.56 cm-1, T1 within 1.9%; 56 jobs vs 169.
N below ~1.3 m stays wrong even after the Davidson round (VO N = 20/30, C1 N = 20).
"""

from __future__ import annotations

import json
from pathlib import Path
from types import SimpleNamespace
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 crystal_phonons as cp
from Hypothesis_generation.skill_library.periodic_dft import harness as _h

KIND = "low_mode_hessian"
LOW_MODE_RESULT = "low_mode_hessian.json"
TRIAL_SUBSPACE = "trial_subspace.json"
DAVIDSON_PROPOSAL = "davidson_proposal.json"


# --------------------------------------------------------------------------- #
# Linear algebra (pure numpy)
# --------------------------------------------------------------------------- #


def to_cm1(eigenvalues) -> np.ndarray:
    """Dynamical-matrix eigenvalues (eV/(A^2 amu)) -> cm-1, imaginary < 0, with phonopy's own conversion factor."""
    from phonopy.physical_units import get_physical_units

    lam = np.asarray(eigenvalues, dtype=float)
    return np.sign(lam) * np.sqrt(np.abs(lam)) * get_physical_units().DefaultToTHz * cp.THZ_TO_CM1


def translations(masses) -> np.ndarray:
    """(3n, 3) orthonormal rigid translations in mass-weighted coordinates."""
    m = np.asarray(masses, dtype=float)
    t = np.zeros((3 * len(m), 3))
    for a in range(3):
        t[a::3, a] = np.sqrt(m / m.sum())
    return t


def gamma_dynamical_matrix(phonon) -> np.ndarray:
    phonon.dynamical_matrix.run([0.0, 0.0, 0.0])
    return np.real(phonon.dynamical_matrix.dynamical_matrix)


def complement_modes(dyn, masses) -> tuple[np.ndarray, np.ndarray]:
    """Eigenvalues and eigenvectors (3n x 3n-3) of a Gamma dynamical matrix restricted to the translation-free complement."""
    q = np.linalg.qr(np.hstack([translations(masses), np.eye(len(dyn))]))[0][:, 3:]  # orthonormal complement of the translations
    lam, y = np.linalg.eigh(q.T @ ((dyn + dyn.T) / 2) @ q)
    return lam, q @ y


def mlip_trial_vectors(dyn, masses, n_vectors: int) -> tuple[np.ndarray, np.ndarray]:
    """The n_vectors lowest modes (3n x N, orthonormal, exactly orthogonal to the translations) of a Gamma dynamical matrix
    restricted to the translation-free complement, and their frequencies (cm-1)."""
    if not 0 < int(n_vectors) <= len(dyn) - 3:
        raise ValueError(f"n_trial_vectors must be in 1..{len(dyn) - 3} (3n - 3 for {len(masses)} atoms).")
    lam, y = complement_modes(dyn, masses)
    return y[:, : int(n_vectors)], to_cm1(lam[: int(n_vectors)])


def hessian_columns(f_plus, f_ref, steps, masses) -> tuple[np.ndarray, float]:
    """d_k = -M^-1/2 (F_k - F_ref,k) / step_k (3n x N, eV/(A^2 amu)) from forces in eV/A (N, n, 3): central differences
    (F_ref = the -delta cell, step = 2 delta) or one-sided (F_ref = equilibrium, step = delta). The net force (drift, a
    translation component that the symmetric, translation-invariant D cannot produce) is removed; its share is returned."""
    inv = np.repeat(1.0 / np.sqrt(np.asarray(masses, dtype=float)), 3)
    diff = (np.asarray(f_plus, dtype=float) - np.asarray(f_ref, dtype=float)).reshape(len(steps), -1)
    d = -(diff.T * inv[:, None]) / np.asarray(steps, dtype=float)[None, :]
    t = translations(masses)
    drift = t.T @ d
    return d - t @ drift, float((drift**2).sum() / max((d**2).sum(), 1e-300))


def rayleigh_ritz(v, dv, relative_residual_threshold: float = 0.1) -> dict[str, Any]:
    """Ritz pairs of D in span(v) (v orthonormal, 3n x N) from dv = D v (3n x N)."""
    h = v.T @ dv
    lam, c = np.linalg.eigh((h + h.T) / 2)
    y = v @ c
    r = dv @ c - y * lam
    res = np.linalg.norm(r, axis=0)
    f, lo, hi = to_cm1(lam), to_cm1(lam - res), to_cm1(lam + res)
    rel = res / np.maximum(np.abs(lam), 1e-300)
    return {"eigenvalues": lam, "frequencies_cm1": f, "vectors": y, "residuals": r, "residual_norms": res,
            "relative_residuals": rel, "frequency_interval_cm1": np.array([lo, hi]).T,
            "frequency_error_bound_cm1": np.maximum(hi - f, f - lo), "flagged": rel > float(relative_residual_threshold),
            "asymmetry_relative": float(np.linalg.norm(h - h.T) / max(np.linalg.norm(h), 1e-300))}


def add_error_estimates(rr: dict[str, Any], v, dyn_mlip, masses, frequency_tolerance_cm1: float = 1.0, floor: float = 0.05) -> dict[str, Any]:
    """MLIP-preconditioned Davidson corrections t_i = -(D_MLIP - lambda_i)^-1 r_i, orthogonal to span(v) and the translations
    (|mu - lambda_i| floored at floor |lambda_i| near resonance), and the error estimates they imply: estimated_frequency_error_cm1
    = w(lambda_i) - w(lambda_i + t_i.r_i) (> 0: the Ritz value is too high), estimated_eigenvector_error = |t_i|. 'unconverged':
    estimated |error| > frequency_tolerance_cm1. An estimate (the MLIP stands in for D), not a bound."""
    mu, y = complement_modes(dyn_mlip, masses)
    corr, dlam = np.zeros_like(rr["vectors"]), np.zeros(len(rr["eigenvalues"]))
    for i, (lam, r) in enumerate(zip(rr["eigenvalues"], rr["residuals"].T)):
        den = mu - lam
        f = float(floor) * max(abs(lam), 1e-4)
        den = np.where(np.abs(den) < f, np.where(den < 0, -f, f), den)
        t = -(y @ ((y.T @ r) / den))
        corr[:, i] = t - v @ (v.T @ t)
        dlam[i] = corr[:, i] @ r
    err = rr["frequencies_cm1"] - to_cm1(rr["eigenvalues"] + dlam)
    rr.update(corrections=corr, estimated_frequency_error_cm1=err, estimated_eigenvector_error=np.linalg.norm(corr, axis=0),
              unconverged=np.abs(err) > float(frequency_tolerance_cm1), frequency_tolerance_cm1=float(frequency_tolerance_cm1))
    return rr


def davidson_directions(v, residuals, masses, tol: float = 1e-3) -> np.ndarray:
    """Residual directions orthogonalized (twice) against span(v), the translations and each other: one block-Davidson
    enrichment of the trial subspace (3n x k)."""
    basis = np.hstack([translations(masses), v])
    out: list[np.ndarray] = []
    for r in np.asarray(residuals).T:
        x = r.copy()
        for _ in range(2):
            x -= basis @ (basis.T @ x)
            for o in out:
                x -= o * (o @ x)
        if np.linalg.norm(x) > tol * max(np.linalg.norm(r), 1e-300):
            out.append(x / np.linalg.norm(x))
    return np.array(out).T if out else np.zeros((len(basis), 0))


def displacement_steps(v, masses, max_atom_displacement_angstrom: float, fixed_delta: float = 0.0) -> tuple[np.ndarray, np.ndarray]:
    """delta_k (amu^1/2 A) per trial vector and the resulting largest atomic displacement (A): fixed_delta for all, or (0) each
    vector scaled so its largest atomic displacement is max_atom_displacement_angstrom."""
    inv = 1.0 / np.sqrt(np.asarray(masses, dtype=float))
    per_unit = np.linalg.norm(v.T.reshape(v.shape[1], -1, 3) * inv[None, :, None], axis=2).max(axis=1)
    deltas = np.full(v.shape[1], float(fixed_delta)) if fixed_delta > 0 else float(max_atom_displacement_angstrom) / per_unit
    return deltas, deltas * per_unit


def _modes_json(rr: dict[str, Any], masses, cell, positions, symbols, extra: dict[str, Any]) -> dict[str, Any]:
    """low_mode_hessian.json payload: the gamma_modes_json input of compute_spin_relaxation_time."""
    n = len(masses)
    return {
        "kind": KIND,
        "frequencies_cm1": [float(f) for f in rr["frequencies_cm1"]],
        "eigenvectors_mass_weighted": rr["vectors"].T.reshape(-1, n, 3).tolist(),
        "eigenvector_convention": "mass-weighted, unit norm, atom order of 'structure'; u_k = Q e_k / sqrt(m_k)",
        "residual_norms_eV_per_A2_amu": rr["residual_norms"].tolist(),
        "relative_residuals": rr["relative_residuals"].tolist(),
        "frequency_error_bound_cm1": [round(float(b), 4) for b in rr["frequency_error_bound_cm1"]],
        "frequency_interval_cm1": np.round(rr["frequency_interval_cm1"], 4).tolist(),
        "flagged_modes": [int(i) for i in np.flatnonzero(rr["flagged"])],
        **({"estimated_frequency_error_cm1": [round(float(x), 4) for x in rr["estimated_frequency_error_cm1"]],
            "estimated_eigenvector_error": [round(float(x), 4) for x in rr["estimated_eigenvector_error"]],
            "frequency_tolerance_cm1": rr["frequency_tolerance_cm1"],
            "unconverged_modes": [int(i) for i in np.flatnonzero(rr["unconverged"])]} if "unconverged" in rr else {}),
        "projected_hessian_asymmetry_relative": rr["asymmetry_relative"],
        "subspace_size": int(rr["vectors"].shape[1]),
        "structure": {"symbols": list(symbols), "masses": [float(m) for m in masses], "cell": np.asarray(cell).tolist(),
                      "positions_angstrom": np.asarray(positions).tolist()},
        "completeness": "Only modes inside the trial subspace exist here: a Raman sum over these modes is truncated to the subspace "
                        "(modes orthogonal to it are absent, not zero-coupled). No acoustic modes (translations projected out).",
        **extra,
    }


def _mode_table(rr: dict[str, Any], cutoff: float) -> list[dict[str, Any]]:
    rows = []
    for i in np.flatnonzero(rr["frequencies_cm1"] <= cutoff):
        rows.append({"mode": int(i), "frequency_cm1": round(float(rr["frequencies_cm1"][i]), 2), "error_bound_cm1": round(float(rr["frequency_error_bound_cm1"][i]), 2),
                     "relative_residual": round(float(rr["relative_residuals"][i]), 4), "flagged": bool(rr["flagged"][i])})
        if "unconverged" in rr:
            rows[-1].update(estimated_error_cm1=round(float(rr["estimated_frequency_error_cm1"][i]), 2), unconverged=bool(rr["unconverged"][i]))
    return rows


def _load_trial(root: Path, trial_source: str, label: str) -> tuple[Any, str, Path]:
    path = _h._resolve_path(root, trial_source, must_exist=True)
    trial_dir = path if path.is_dir() else path.parent
    phonon = cp._load_phonon(trial_dir)
    if len(phonon.primitive) != len(phonon.unitcell):
        raise ValueError("The trial phonopy set needs primitive_matrix 'P' (primitive = unit cell).")
    prov = cc._read_json(trial_dir / cp.FC_PROVENANCE)
    label = label.strip() or prov.get("force_constants_source") or prov.get("label") or ""
    if not label:
        raise ValueError("Label the trial force constants with trial_source_label (e.g. 'MLIP: UMA uma-s-1p2, 1x1x1, DFT geometry').")
    if prov.get("relaxed_positions_in_fixed_cell"):
        label += " [WARNING: Hessian taken at the MLIP minimum, not at the DFT geometry]"
    return phonon, label, trial_dir


def auto_trial_count(dyn_mlip, masses, mode_cutoff_cm1: float) -> tuple[int, int]:
    """(m, N): m = MLIP Gamma modes (translations excluded, imaginary included) at or below the cutoff; N = ceil(1.3 m) + 10,
    at most 3n - 3. Emulation: N < ~1.3 m left modes unconverged even after a Davidson round (VO(acac)2 N = 20/30, C1 N = 20)."""
    m = int((to_cm1(complement_modes(dyn_mlip, masses)[0]) <= float(mode_cutoff_cm1)).sum())
    return m, min(int(numpy.ceil(1.3 * m)) + 10, len(dyn_mlip) - 3)


def merge_rounds(blocks) -> tuple[np.ndarray, np.ndarray, int]:
    """One subspace from every round: blocks = [(V_r, D V_r), ...]. The union of the trial vectors is re-orthonormalized by SVD,
    V = U S W^T -> Q = V W S^-1, and the measured columns take the same basis change, D Q = (D V) W S^-1. Returns (Q, D Q, number
    of linearly dependent directions dropped)."""
    v = np.hstack([b[0] for b in blocks])
    dv = np.hstack([b[1] for b in blocks])
    _u, s, wt = np.linalg.svd(v, full_matrices=False)
    keep = s > 1e-6 * s.max()
    x = wt[keep].T / s[keep]
    return v @ x, dv @ x, int((~keep).sum())


def _vectors(trial: dict[str, Any]) -> np.ndarray:
    vec = np.array(trial["vectors_mass_weighted"], dtype=float)
    return vec.reshape(len(vec), -1).T


def _write_round(lm_dir: Path, manifest: dict[str, Any], round_no: int, v, masses, x0, extra: dict[str, Any]) -> list[dict[str, Any]]:
    """Displaced inputs of one round (numbered after the existing ones), its trial-subspace file and manifest rows."""
    deltas, max_disp = displacement_steps(v, masses, manifest["max_atom_displacement_angstrom"], manifest["displacement_amu_angstrom"])
    shapes = (v.T.reshape(v.shape[1], -1, 3) / np.sqrt(masses)[None, :, None]) * deltas[:, None, None]
    cells = [(k, s, x0 + s * shapes[k]) for k in range(v.shape[1]) for s in ((1, -1) if manifest["plus_minus"] else (1,))]
    restart = cp.restart_file_name(manifest["kpoints"], cp._ase_atoms(SimpleNamespace(symbols=manifest["symbols"], cell=manifest["cell"], positions=x0)))
    rows = cp.write_displaced_inputs(lm_dir, [c[2] for c in cells], len(manifest["displacements"]) + 1,
                                     manifest["max_core_hours_per_displacement"], manifest["np"], restart)
    for row, (k, s, _x) in zip(rows, cells):
        row.update(round=round_no, vector=k, sign=s)
    name = TRIAL_SUBSPACE if round_no == 1 else f"trial_subspace_round{round_no}.json"
    (lm_dir / name).write_text(json.dumps({**extra, "round": round_no, "masses": np.asarray(masses).tolist(), "delta_amu_angstrom": deltas.tolist(),
                                           "max_atom_displacement_angstrom": max_disp.tolist(), "vectors_mass_weighted": v.T.reshape(v.shape[1], -1, 3).tolist()}))
    manifest["rounds"].append({"round": round_no, "trial_subspace": name, "n_vectors": int(v.shape[1]), "n_displacements": len(rows),
                               "status": "dry_run", "source": extra.get("source")})
    manifest["displacements"].extend(rows)
    manifest["n_displacements"] = len(manifest["displacements"])
    return rows


# --------------------------------------------------------------------------- #
# Tools
# --------------------------------------------------------------------------- #


def run_low_mode_dft_hessian(
    structure_path: Annotated[str, "Stationary periodic structure: final_structure.extxyz/.cif of a CONVERGED all-atom geo_opt/cell_opt (tight_for_phonons=True), as for run_periodic_dft_phonons."],
    trial_source: Annotated[str, "Trial Hessian: a directory (or its phonopy_params.yaml) with force constants of the SAME cell and atom order, e.g. a fine-tuned UMA set. '' (default) = pretrained UMA force constants of the unit cell AT THE DFT POSITIONS (1x1x1, no MLIP relaxation), computed now."] = "",
    trial_source_label: Annotated[str, "Label for a trial_source without fc_provenance.json."] = "",
    n_trial_vectors: Annotated[int, "Subspace size N of round 1 (the N lowest non-translational MLIP Gamma modes). 0 (default) = ceil(1.3 m) + 10, m = MLIP modes below mode_cutoff_cm1 (reported)."] = 0,
    mode_cutoff_cm1: Annotated[float, "Highest frequency the consumer needs (Raman T1: 150 cm-1): sets m and the default N."] = 150.0,
    max_atom_displacement_angstrom: Annotated[float, "Default step: each trial vector scaled so its largest atomic displacement is this (A)."] = 0.015,
    displacement_amu_angstrom: Annotated[float, "Fixed step delta (amu^1/2 A) for every vector instead; 0 = per-vector from max_atom_displacement_angstrom."] = 0.0,
    plus_minus: Annotated[bool, "False (default): one-sided, N + 1 jobs, equilibrium residual forces subtracted (error O(delta x anharmonicity)). True: central differences, 2N + 1 jobs."] = False,
    charge: Annotated[int | None, "Total cell charge (inherited from the relaxation when None)."] = None,
    multiplicity: Annotated[int | None, "Total cell multiplicity (inherited when None)."] = None,
    spin_state_rationale: Annotated[str, "Spin/charge justification (inherited)."] = "",
    site_magnetization_json: Annotated[str, "Initial spins per site (inherited)."] = "",
    kpoints: Annotated[str, "k mesh; '' = the relaxation's (same Brillouin-zone sampling as the stationary structure)."] = "",
    dft_plus_u_json: Annotated[str, "DFT+U per element (eV); inherited from the relaxation when empty."] = "",
    dft_plus_u_rationale: Annotated[str, "Required with dft_plus_u_json."] = "",
    functional: Annotated[str, "XC functional (inherited from the relaxation when left at PBE)."] = "PBE",
    basis_set: Annotated[str, "Basis family (inherited when left at the default)."] = "DZVP-MOLOPT-SR-GTH",
    cutoff_ry: Annotated[int, "Plane-wave cutoff (the relaxation's when higher; 600 Ry semicore floor)."] = 400,
    rel_cutoff_ry: Annotated[int, "Relative cutoff (Ry)."] = 60,
    dispersion: Annotated[bool, "DFT-D3 (inherited)."] = True,
    dispersion_type: Annotated[str, "'DFTD3' or 'DFTD3(BJ)' (inherited when left at the default)."] = "DFTD3",
    phonon_grade_grid: Annotated[bool, "800 Ry + finer XC grid (as run_periodic_dft_phonons)."] = True,
    np: Annotated[int, "Threads per job."] = 8,
    mem: Annotated[str, "Memory per job."] = "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 displaced cell (restarted from the equilibrium wavefunction)."] = 12.0,
    max_total_core_hours: Annotated[float, "Refuse to start if equilibrium + all round-1 displacement caps exceed this."] = 800.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 from a converged all-atom optimization (deliberate tests only)."] = False,
    uma_checkpoint: Annotated[str, "Fine-tuned UMA checkpoint for the trial Hessian; '' = pretrained uma-s-1p2."] = "",
    mlip_execution_mode: Annotated[str, "Trial UMA force constants: 'auto' (GPU Slurm job unless this host sees CUDA), 'submit_local_slurm_gpu' or 'local' (refused above ~20 CPU-minutes unless allow_long_local)."] = "auto",
    allow_long_local: Annotated[bool, "Run the trial UMA force constants on this CPU even when slow."] = False,
    max_geometry_deviation_angstrom: Annotated[float, "Refuse a trial set whose cell or positions differ from the structure by more than this."] = 0.01,
    output_dir: Annotated[str, "Default calculations/periodic_dft_<structure>/low_mode_hessian."] = "",
    execution_mode: Annotated[str, "'dry_run' (write everything, CP2K --check, count jobs 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 array, then collect."] = True,
    max_wait_hours: Annotated[float, "Upper bound on waiting in this call."] = 72.0,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Round 1 of the low-mode DFT Hessian of a large cell: DFT finite differences along N MLIP trial modes (one Slurm array, the
    stationary structure's Hamiltonian), then collect_low_mode_dft_hessian (Rayleigh-Ritz + error estimates + Davidson proposal)
    and, for the unconverged modes, run_low_mode_dft_hessian_round."""
    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 = cp._stationarity_gate(structure, allow_non_stationary, warnings)
        unit = Phonopy(cp._phonopy_atoms(atoms), supercell_matrix=numpy.eye(3, dtype=int), primitive_matrix="P", symprec=1e-3)
        common, kpoints = cp.displacement_settings(
            structure, atoms, unit, 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,
        )
        lm_dir = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else cp._stage_dir(root, structure, "low_mode_hessian"))
        lm_dir.mkdir(parents=True, exist_ok=True)
        if cc._read_json(lm_dir / cp.PHONON_MANIFEST).get("equilibrium_job_id"):
            return {"ok": True, "duplicate_submission_prevented": True, **collect_low_mode_dft_hessian(_h._rel(root, lm_dir), runtime=runtime)}

        mlip_run = None
        if trial_source.strip():
            trial, label, trial_dir = _load_trial(root, trial_source, trial_source_label)
        else:
            from Hypothesis_generation.skill_library.clari import harness as ch
            from Hypothesis_generation.skill_library.clari_uma_relax import uma_supercell_repeats
            from Hypothesis_generation.skill_library.periodic_dft.crystal_csp import UMA_CPU_SECONDS_PER_ATOM
            from ase.io import write

            trial_dir = lm_dir / "mlip_trial"
            if not (trial_dir / cp.PHONOPY_PARAMS).is_file():
                trial_dir.mkdir(parents=True, exist_ok=True)
                cell_file = trial_dir / "dft_reference_cell.extxyz"
                write(str(cell_file), atoms, format="extxyz")
                probe = Phonopy(cp._phonopy_atoms(atoms), supercell_matrix=numpy.eye(3, dtype=int), primitive_matrix="P", symprec=1e-3)
                probe.generate_displacements(distance=0.01, is_plusminus="auto")
                evals = (len(probe.supercells_with_displacements) + 1) * len(atoms) * int(numpy.prod(uma_supercell_repeats(atoms.cell.array)))
                mode = ch._normalize_clari_execution_mode(mlip_execution_mode, device="auto", num_gpus=1)
                mlip_run = {"supercell": [1, 1, 1], "n_displacements": len(probe.supercells_with_displacements), "execution_mode": mode,
                            "cpu_minutes_estimate": round(evals * UMA_CPU_SECONDS_PER_ATOM / 60.0, 1)}
                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": "Trial UMA force constants would take too long on this CPU: mlip_execution_mode='submit_local_slurm_gpu' (or allow_long_local=True)."}
                job = cp.mlip_force_constant_job(root, cell_file, trial_dir, min_width=0.0, symprec=1e-3, uma_checkpoint=uma_checkpoint,
                                                 relax_positions=False, mode=mode, slurm_walltime="02:00:00", job_name=f"{lm_dir.name}_mlip_trial")
                mlip_run.update({k: v for k, v in job.items() if k != "ok"})
                if not job["ok"]:
                    return {"ok": False, "status": "trial_hessian_failed", "mlip": mlip_run}
            trial, label, trial_dir = _load_trial(root, _h._rel(root, trial_dir), "")
        deviation = cp._cell_deviation(cp._phonopy_atoms(atoms), trial.unitcell)
        if deviation > float(max_geometry_deviation_angstrom):
            raise ValueError(f"The trial Hessian belongs to a different structure ({deviation:.3f} A away): take it at the DFT positions.")
        masses = numpy.array(trial.primitive.masses)
        d_mlip = gamma_dynamical_matrix(trial)
        n_soft, n_auto = auto_trial_count(d_mlip, masses, mode_cutoff_cm1)
        n_vec = int(n_trial_vectors) or n_auto
        if n_vec < 1.3 * n_soft:
            warnings.append(f"The trial Hessian has {n_soft} modes below {float(mode_cutoff_cm1):g} cm-1 but N = {n_vec}: use N >= "
                            f"{int(numpy.ceil(1.3 * n_soft))} (emulation: N < 1.3x the soft-mode count left modes unconverged even after a Davidson round).")
        v, trial_freqs = mlip_trial_vectors(d_mlip, masses, n_vec)
        planned = float(max_core_hours_equilibrium) + n_vec * (2 if plus_minus else 1) * float(max_core_hours_per_displacement)
        if planned > float(max_total_core_hours):
            raise ValueError(f"{n_vec * (2 if plus_minus else 1)} displaced cells x {max_core_hours_per_displacement} + {max_core_hours_equilibrium} "
                             f"core-h = {planned:g} exceeds max_total_core_hours={max_total_core_hours:g}.")
        ideal = cp._ase_atoms(unit.supercell)  # same atoms and order as the structure (1x1x1)
        eq, _none = cp.prepare_displaced_jobs(
            root, structure, lm_dir, ideal, [], 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=True,
        )
        if not eq.get("ok"):
            return {"ok": False, "status": "equilibrium_preparation_failed", "detail": eq}
        manifest = {
            "kind": KIND, "structure": _h._rel(root, structure), "structure_provenance": provenance,
            "supercell_matrix": numpy.eye(3, dtype=int).tolist(), "plus_minus": bool(plus_minus), "kpoints": kpoints,
            "max_atom_displacement_angstrom": float(max_atom_displacement_angstrom), "displacement_amu_angstrom": float(displacement_amu_angstrom),
            "mode_cutoff_cm1": float(mode_cutoff_cm1), "n_atoms_supercell": len(atoms), "symbols": ideal.get_chemical_symbols(),
            "cell": ideal.cell.array.tolist(), "kind_to_element": cc._read_json(lm_dir / "equilibrium" / cc.JOB_STATE).get("kind_to_element"),
            "trial_source": _h._rel(root, trial_dir), "trial_label": label, "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), "rounds": [], "displacements": [],
        }
        rows = _write_round(lm_dir, manifest, 1, v, masses, ideal.get_positions(), {
            "source": f"lowest {n_vec} MLIP modes", "trial_source": _h._rel(root, trial_dir), "trial_label": label, "mlip_run": mlip_run,
            "geometry_deviation_angstrom": round(deviation, 6), "symbols": atoms.get_chemical_symbols(), "trial_frequencies_cm1": trial_freqs.round(3).tolist()})
        trial_json = json.loads((lm_dir / TRIAL_SUBSPACE).read_text())
        brief = {
            "low_mode_dir": _h._rel(root, lm_dir), "n_mlip_modes_below_cutoff": n_soft, "n_trial_vectors": n_vec,
            "n_trial_vectors_rule": "ceil(1.3 m) + 10" if not int(n_trial_vectors) else "user", "n_displacements": len(rows),
            "n_cp2k_jobs": len(rows) + 1, "planned_core_hours_cap": planned, "plus_minus": bool(plus_minus), "kpoints": kpoints, "trial_label": label,
            "trial_frequencies_cm1": [round(float(f), 1) for f in trial_freqs],
            "delta_amu_angstrom_range": [round(min(trial_json["delta_amu_angstrom"]), 4), round(max(trial_json["delta_amu_angstrom"]), 4)],
            "max_atom_displacement_angstrom_range": [round(min(trial_json["max_atom_displacement_angstrom"]), 4), round(max(trial_json["max_atom_displacement_angstrom"]), 4)],
            "mlip": mlip_run, "warnings": warnings,
        }
        if execution_mode == "dry_run":
            (lm_dir / cp.PHONON_MANIFEST).write_text(json.dumps(manifest, indent=1))
            return {"ok": True, "status": "dry_run_validated", **brief, "equilibrium_check": eq.get("cp2k_check", {}).get("ok")}
        manifest["equilibrium_job_id"] = eq.get("job_id")
        array = cp._submit_array(lm_dir, [r["index"] for r in rows], manifest, dependency_job=eq.get("job_id"))
        manifest["array_submissions"] = [{**array, "round": 1}]
        manifest["rounds"][0]["status"] = "submitted"
        (lm_dir / cp.PHONON_MANIFEST).write_text(json.dumps(manifest, indent=1))
        if not array.get("ok"):
            return {"ok": False, "status": "array_submission_failed", "low_mode_dir": brief["low_mode_dir"], "submission": array}
        if not wait_for_completion:
            return {"ok": True, "status": "submitted", **brief, "equilibrium_job_id": eq.get("job_id"), "array_job_id": array.get("job_id"),
                    "next_step": "collect_low_mode_dft_hessian(low_mode_dir, wait=True)."}
        return collect_low_mode_dft_hessian(brief["low_mode_dir"], wait=True, max_wait_hours=max_wait_hours, runtime=runtime)
    except Exception as exc:
        return _h._error(exc, hint="Dry-run first; the structure must be the stationary final_structure and the trial Hessian its own cell.")


def run_low_mode_dft_hessian_round(
    low_mode_dir: Annotated[str, "A collected run_low_mode_dft_hessian directory (its equilibrium job finished)."],
    trial_vectors_json: Annotated[str, "Extra trial vectors: 'vectors_mass_weighted' (k x n_atoms x 3). '' (default) = <low_mode_dir>/davidson_proposal.json written by collect_low_mode_dft_hessian."] = "",
    max_total_core_hours: Annotated[float, "Refuse this round if its displaced cells x the per-displacement cap exceed this."] = 400.0,
    execution_mode: Annotated[str, "'dry_run' (write the inputs, count jobs and cost) or 'submit'."] = "dry_run",
    submit_approved: Annotated[bool, "Must be True to submit."] = False,
    wait_for_completion: Annotated[bool, "Wait for this round's array, then collect (all rounds merged)."] = True,
    max_wait_hours: Annotated[float, "Upper bound on waiting in this call."] = 72.0,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Next Davidson round of a low-mode DFT Hessian: ONLY the extra displaced cells along the proposed corrections, in the SAME
    directory (numbering continues), from the same equilibrium input and wavefunction, one-sided or central as round 1, one
    array without dependency. collect_low_mode_dft_hessian then merges every round into one Rayleigh-Ritz."""
    root = _h._root(runtime)
    try:
        import hashlib

        from ase.io import read

        lm_dir = _h._resolve_path(root, low_mode_dir, must_exist=True, file_ok=False)
        manifest = cc._read_json(lm_dir / cp.PHONON_MANIFEST)
        if manifest.get("kind") != KIND:
            raise ValueError(f"{low_mode_dir} is not a run_low_mode_dft_hessian directory.")
        if execution_mode not in {"dry_run", "submit"} or (execution_mode == "submit" and not submit_approved):
            raise ValueError("execution_mode must be 'dry_run' or 'submit' (with submit_approved=True).")
        if cp._task_forces(lm_dir / "equilibrium", manifest.get("kind_to_element") or {})[0] is None:
            raise ValueError("The equilibrium job has not finished: collect round 1 first (its wavefunction and forces are reused).")
        source = _h._resolve_path(root, trial_vectors_json, must_exist=True, dir_ok=False) if trial_vectors_json.strip() else lm_dir / DAVIDSON_PROPOSAL
        if not source.is_file():
            return {"ok": True, "status": "nothing_to_do", "detail": "No Davidson proposal: collect reported no unconverged modes below the cutoff."}
        sha = hashlib.sha256(source.read_bytes()).hexdigest()
        if any(r.get("source_sha256") == sha and r["status"] == "submitted" for r in manifest["rounds"]):
            return {"ok": True, "duplicate_submission_prevented": True, **collect_low_mode_dft_hessian(_h._rel(root, lm_dir), runtime=runtime)}
        stale = [r for r in manifest["rounds"] if r["status"] == "dry_run" and r["round"] > 1]  # an earlier dry run of this round
        for r in stale:
            for row in [x for x in manifest["displacements"] if x.get("round") == r["round"]]:
                for f in (lm_dir / row["dir"]).glob("*"):
                    f.unlink()
                (lm_dir / row["dir"]).rmdir()
            (lm_dir / r["trial_subspace"]).unlink(missing_ok=True)
        manifest["rounds"] = [r for r in manifest["rounds"] if r not in stale]
        manifest["displacements"] = [x for x in manifest["displacements"] if x.get("round") in {r["round"] for r in manifest["rounds"]}]
        trial1 = json.loads((lm_dir / TRIAL_SUBSPACE).read_text())
        masses = np.array(trial1["masses"])
        previous = merge_rounds([(_vectors(json.loads((lm_dir / r["trial_subspace"]).read_text())),) * 2 for r in manifest["rounds"]])[0]
        new = davidson_directions(previous, _vectors(json.loads(source.read_text())), masses)
        if not new.shape[1]:
            return {"ok": True, "status": "nothing_to_do", "detail": "The proposed vectors lie inside the existing subspace."}
        jobs = new.shape[1] * (2 if manifest["plus_minus"] else 1)
        cost = jobs * float(manifest["max_core_hours_per_displacement"])
        if cost > float(max_total_core_hours):
            raise ValueError(f"{jobs} displaced cells x {manifest['max_core_hours_per_displacement']} core-h = {cost:g} exceeds max_total_core_hours={max_total_core_hours:g}.")
        round_no = max(r["round"] for r in manifest["rounds"]) + 1
        rows = _write_round(lm_dir, manifest, round_no, new, masses, read(str(lm_dir / "supercell_ideal.extxyz")).get_positions(),
                            {"source": _h._rel(root, source), "symbols": trial1["symbols"]})
        manifest["rounds"][-1]["source_sha256"] = sha
        manifest["planned_core_hours_cap"] = float(manifest.get("planned_core_hours_cap") or 0.0) + cost
        brief = {"low_mode_dir": _h._rel(root, lm_dir), "round": round_no, "n_new_vectors": int(new.shape[1]), "n_displacements": len(rows),
                 "disp_dirs": [rows[0]["dir"], rows[-1]["dir"]], "round_core_hours_cap": cost, "total_planned_core_hours_cap": manifest["planned_core_hours_cap"],
                 "subspace_size_after": int(previous.shape[1] + new.shape[1])}
        if execution_mode == "dry_run":
            (lm_dir / cp.PHONON_MANIFEST).write_text(json.dumps(manifest, indent=1))
            return {"ok": True, "status": "dry_run_validated", **brief}
        array = cp._submit_array(lm_dir, [r["index"] for r in rows], manifest)
        manifest.setdefault("array_submissions", []).append({**array, "round": round_no})
        manifest["rounds"][-1]["status"] = "submitted"
        (lm_dir / cp.PHONON_MANIFEST).write_text(json.dumps(manifest, indent=1))
        if not array.get("ok"):
            return {"ok": False, "status": "array_submission_failed", **brief, "submission": array}
        if not wait_for_completion:
            return {"ok": True, "status": "submitted", **brief, "array_job_id": array.get("job_id"),
                    "next_step": "collect_low_mode_dft_hessian(low_mode_dir, wait=True) merges every round."}
        return collect_low_mode_dft_hessian(brief["low_mode_dir"], wait=True, max_wait_hours=max_wait_hours, runtime=runtime)
    except Exception as exc:
        return _h._error(exc)


def collect_low_mode_dft_hessian(
    low_mode_dir: Annotated[str, "Directory of run_low_mode_dft_hessian (phonon_manifest.json kind 'low_mode_hessian')."],
    wait: Annotated[bool, "Wait until the equilibrium job and the arrays are terminal."] = False,
    max_wait_hours: Annotated[float, "Upper bound on waiting."] = 72.0,
    resubmit_failed: Annotated[bool, "Resubmit ONLY missing/failed displaced cells of submitted rounds (bounded retries)."] = True,
    mode_cutoff_cm1: Annotated[float, "Report modes up to this frequency (the Raman consumer's cutoff); 0 = the run's."] = 0.0,
    relative_residual_threshold: Annotated[float, "Flag Ritz modes with |r|/|lambda| above this (rigorous but loose for low modes)."] = 0.1,
    frequency_tolerance_cm1: Annotated[float, "A mode is 'unconverged' when its MLIP-preconditioned error estimate exceeds this."] = 1.0,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Collect every submitted round, merge all measured DFT columns into one Rayleigh-Ritz over the union of trial vectors, with
    residual bounds and MLIP-preconditioned error estimates (per round and merged); write low_mode_hessian.json for
    compute_spin_relaxation_time(gamma_modes_json=...) and, for unconverged modes, a Davidson proposal for
    run_low_mode_dft_hessian_round (never submitted here)."""
    root = _h._root(runtime)
    try:
        from ase.io import read

        lm_dir = _h._resolve_path(root, low_mode_dir, must_exist=True, file_ok=False)
        manifest = cc._read_json(lm_dir / cp.PHONON_MANIFEST)
        if manifest.get("kind") != KIND:
            raise ValueError(f"{low_mode_dir} is not a run_low_mode_dft_hessian directory.")
        wait_info = cp._wait_for_phonons(lm_dir, manifest, float(max_wait_hours) * 3600.0, runtime) if wait else None
        if not wait:
            cp.cancel_stalled_tasks(lm_dir, manifest)
        state = cp._array_state(lm_dir, manifest)
        kinds = manifest.get("kind_to_element") or {}
        live = [r for r in manifest["rounds"] if r["round"] == 1 or r["status"] == "submitted"]  # a dry-run later round is never collected
        live_ids = {r["round"] for r in live}
        eq_forces, eq_info = cp._task_forces(lm_dir / "equilibrium", kinds)
        forces, bad, walls = {}, [], [eq_info.get("wall_seconds") or 0.0]
        for row in manifest["displacements"]:
            if row["round"] not in live_ids:
                continue
            f, info = cp._task_forces(lm_dir / row["dir"], kinds)
            walls.append(info.get("wall_seconds") or 0.0)
            if f is None:
                bad.append(row["index"])
            else:
                forces[(row["round"], row["vector"], row["sign"])] = f * cp.HARTREE_PER_BOHR_TO_EV_PER_ANG
        active = state in _h.ACTIVE_SLURM_STATUSES
        summary: dict[str, Any] = {
            "low_mode_dir": _h._rel(root, lm_dir), "scheduler_state": state, "equilibrium": eq_info,
            "rounds": [{k: r.get(k) for k in ("round", "n_vectors", "n_displacements", "status", "source")} for r in manifest["rounds"]],
            "n_displacements": sum(r["n_displacements"] for r in live), "completed_displacements": len(forces),
            "failed_or_missing": bad if not active else [], "wait": wait_info,
            "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"),
        }
        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 > cp.STATIONARY_MAX_FORCE_HA_BOHR:
                summary["warning"] = f"Equilibrium residual force {residual:.2e} Ha/bohr: not stationary; the lowest modes are unreliable."
        if active:
            return {"ok": True, "status": "running", **summary}
        if bad and eq_forces is not None:
            retries = [s for s in manifest.get("array_submissions", []) if s.get("round") is None]  # round arrays are not retries
            if resubmit_failed and len(retries) < 2:
                sub = cp.resubmit_failed_tasks(lm_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_low_mode_dft_hessian(low_mode_dir, wait=True, max_wait_hours=max(0.0, remaining), resubmit_failed=resubmit_failed,
                                                        mode_cutoff_cm1=mode_cutoff_cm1, relative_residual_threshold=relative_residual_threshold,
                                                        frequency_tolerance_cm1=frequency_tolerance_cm1, runtime=runtime)
                return {"ok": True, "status": "resubmitted_failed", **summary, "resubmission": sub}
            return {"ok": False, "status": "incomplete", **summary, "error": f"{len(bad)} displaced cells failed after retries: {bad[:20]}"}
        if eq_forces is None:
            return {"ok": False, "status": "equilibrium_failed", **summary, "error": "The equilibrium SCF did not finish (needed for wavefunction restarts and one-sided differences)."}

        trial1 = json.loads((lm_dir / TRIAL_SUBSPACE).read_text())
        masses = np.array(trial1["masses"])
        eq_ev = eq_forces * cp.HARTREE_PER_BOHR_TO_EV_PER_ANG
        blocks, drifts = [], []
        for r in live:
            t = json.loads((lm_dir / r["trial_subspace"]).read_text())
            v_r, deltas = _vectors(t), np.array(t["delta_amu_angstrom"])
            k_range = range(v_r.shape[1])
            if manifest["plus_minus"]:
                dv_r, drift = hessian_columns([forces[(r["round"], k, 1)] for k in k_range], [forces[(r["round"], k, -1)] for k in k_range], 2 * deltas, masses)
            else:
                dv_r, drift = hessian_columns([forces[(r["round"], k, 1)] for k in k_range], [eq_ev] * v_r.shape[1], deltas, masses)
            blocks.append((v_r, dv_r))
            drifts.append(drift)
        cutoff = float(mode_cutoff_cm1) or float(manifest.get("mode_cutoff_cm1") or 150.0)
        trial_dir = root / manifest["trial_source"]
        d_mlip = gamma_dynamical_matrix(cp._load_phonon(trial_dir)) if (trial_dir / cp.PHONOPY_PARAMS).is_file() else None

        def ritz(upto):
            v, dv, dropped = merge_rounds(blocks[:upto])
            rr = rayleigh_ritz(v, dv, relative_residual_threshold)
            if d_mlip is not None:
                add_error_estimates(rr, v, d_mlip, masses, frequency_tolerance_cm1)
            low = rr["frequencies_cm1"] <= cutoff
            return v, rr, {"rounds": [r["round"] for r in live[:upto]], "subspace_size": int(v.shape[1]), "dependent_directions_dropped": dropped,
                           "n_ritz_below_cutoff": int(low.sum()), "n_flagged_below_cutoff": int((rr["flagged"] & low).sum()),
                           "n_unconverged_below_cutoff": int((rr["unconverged"] & low).sum()) if "unconverged" in rr else None,
                           "max_abs_estimated_error_below_cutoff_cm1": round(float(np.abs(rr["estimated_frequency_error_cm1"][low]).max()), 3)
                           if "unconverged" in rr and low.any() else None}

        by_round = [ritz(k)[2] for k in range(1, len(blocks))]
        v, rr, merged = ritz(len(blocks))
        low = rr["frequencies_cm1"] <= cutoff
        warnings = []
        if low.all():
            warnings.append(f"All {v.shape[1]} Ritz modes lie below {cutoff:g} cm-1: exact modes up to the cutoff are probably missing; enlarge n_trial_vectors.")
        flagged_low = [int(i) for i in np.flatnonzero(rr["flagged"] & low)]
        if flagged_low:
            warnings.append(f"Ritz modes {flagged_low} below {cutoff:g} cm-1 have relative residual > {relative_residual_threshold:g} (rigorous bound; "
                            "loose for low modes): report them with the estimated errors.")
        unconverged_low: list[int] = []
        if d_mlip is None:
            warnings.append(f"Trial set {manifest['trial_source']} not found: no error estimates or Davidson proposal.")
        else:
            unconverged_low = [int(i) for i in np.flatnonzero(rr["unconverged"] & low)]
            if unconverged_low:
                warnings.append(f"Ritz modes {unconverged_low} below {cutoff:g} cm-1 have MLIP-preconditioned error estimates > {frequency_tolerance_cm1:g} cm-1 "
                                f"({[round(float(rr['estimated_frequency_error_cm1'][i]), 1) for i in unconverged_low]}): unconverged -- report them, "
                                "or run_low_mode_dft_hessian_round on the Davidson proposal.")
        equilibrium_atoms = read(str(lm_dir / "supercell_ideal.extxyz"))
        eq_text = (lm_dir / "equilibrium" / cc.JOB_INPUT).read_text()
        result = _modes_json(rr, masses, equilibrium_atoms.cell.array, equilibrium_atoms.positions, trial1["symbols"], {
            "method": "Rayleigh-Ritz over every round: CP2K finite differences along MLIP trial modes + Davidson corrections"
                      + (" (central)" if manifest["plus_minus"] else " (one-sided, equilibrium forces subtracted)"),
            "relative_residual_threshold": float(relative_residual_threshold), "mode_cutoff_cm1": cutoff,
            "unconverged_below_cutoff": unconverged_low, "rounds_merged": merged["rounds"], "by_round": by_round + [merged],
            "translational_drift_removed_fraction": drifts, "trial_source": manifest["trial_source"], "trial_label": manifest["trial_label"],
            "hamiltonian": {"cp2k_input": _h._rel(root, lm_dir / "equilibrium" / cc.JOB_INPUT), "kpoints": manifest.get("kpoints"),
                            "dft_plus_u": "&DFT_PLUS_U" in eq_text, "structure": manifest["structure"]},
            "warnings": warnings,
        })
        (lm_dir / LOW_MODE_RESULT).write_text(json.dumps(result))
        proposal = None
        (lm_dir / DAVIDSON_PROPOSAL).unlink(missing_ok=True)  # never leave a stale proposal for the round tool
        if unconverged_low:
            new = davidson_directions(v, rr["corrections"][:, unconverged_low], masses)
            jobs = new.shape[1] * (2 if manifest["plus_minus"] else 1)
            proposal = {"status": "proposed_not_submitted", "after_rounds": merged["rounds"], "n_new_vectors": int(new.shape[1]),
                        "for_ritz_modes": unconverged_low,
                        "kind": "MLIP-preconditioned Davidson corrections -(D_MLIP - lambda_i)^-1 r_i, orthonormalized against the merged subspace",
                        "n_extra_displacements": jobs, "planned_core_hours_cap": jobs * float(manifest["max_core_hours_per_displacement"]),
                        "vectors_mass_weighted": new.T.reshape(new.shape[1], -1, 3).tolist()}
            (lm_dir / DAVIDSON_PROPOSAL).write_text(json.dumps(proposal))
        pending = [r["round"] for r in manifest["rounds"] if r["round"] not in live_ids]
        return {"ok": True, "status": "completed", **summary, "low_mode_hessian": _h._rel(root, lm_dir / LOW_MODE_RESULT),
                "by_round": by_round, "merged": merged, "projected_hessian_asymmetry_relative": round(rr["asymmetry_relative"], 5),
                "translational_drift_removed_fraction": [round(x, 6) for x in drifts], "modes_below_cutoff": _mode_table(rr, cutoff),
                "davidson_proposal": None if proposal is None else {**{key: val for key, val in proposal.items() if key != "vectors_mass_weighted"},
                                                                    "file": _h._rel(root, lm_dir / DAVIDSON_PROPOSAL)},
                "dry_run_rounds_not_submitted": pending, "warnings": warnings,
                "next_step": ("run_low_mode_dft_hessian_round(low_mode_dir) (dry run, then submit after approval) for the unconverged modes"
                              if proposal else "compute_spin_relaxation_time(..., gamma_modes_json=<low_mode_hessian>) -- the Raman sum is truncated to this subspace.")}
    except Exception as exc:
        return _h._error(exc)


def _first_shell(cell_atoms, center: int, radius: float) -> list[int]:
    d = cell_atoms.get_distances(center, range(len(cell_atoms)), mic=True)
    return [int(i) for i in np.argsort(d) if d[i] <= radius]


def raman_type_sum(freqs, vecs, masses, shell, k_matrix, t_k: float) -> float:
    """S = sum_ij |<e_i|K|e_j>|^2 n_i (n_j + 1) / (w_i w_j) over the given modes (w > 0, cm-1), with K a Cartesian coupling
    matrix on the shell atoms and e_i/sqrt(m) their Cartesian mode shapes (the w^-1 factors are the <Q^2>_0 amplitudes)."""
    from Hypothesis_generation.skill_library.periodic_dft.spin_relaxation import bose

    rows = np.ravel([[3 * a, 3 * a + 1, 3 * a + 2] for a in shell])
    e = vecs[rows] / np.repeat(np.sqrt(np.asarray(masses)[shell]), 3)[:, None]
    k = e.T @ k_matrix @ e
    n = bose(freqs, t_k)
    return float(((k**2) * (n[:, None] * (n[None, :] + 1)) / np.outer(freqs, freqs)).sum())


def emulate_low_mode_hessian(
    full_dft_phonon_dir: Annotated[str, "Completed 1x1x1 DFT phonon directory (phonopy_params.yaml): its Gamma dynamical matrix plays the DFT."],
    trial_source: Annotated[str, "Trial Hessian directory (phonopy_params.yaml) on the same cell: e.g. UMA at the DFT geometry."],
    n_modes: Annotated[int, "Round-1 subspace size N; 0 (default) = ceil(1.3 m) + 10 as run_low_mode_dft_hessian (m = trial modes below the cutoff)."] = 0,
    mode_cutoff_cm1: Annotated[float, "Compare the exact modes below this frequency."] = 150.0,
    relative_residual_threshold: Annotated[float, "Flag Ritz modes above this relative residual."] = 0.1,
    frequency_tolerance_cm1: Annotated[float, "'unconverged' above this MLIP-preconditioned error estimate; their corrections form the Davidson step."] = 1.0,
    temperatures_k: Annotated[str, "Temperatures of the Raman-type sum."] = "20 100 300",
    coupling_center: Annotated[int, "Cell atom index of the spin centre (-1 = the first transition-metal atom)."] = -1,
    first_shell_radius_angstrom: Annotated[float, "Atoms within this distance of the centre carry the random couplings."] = 2.6,
    n_random_couplings: Annotated[int, "Random symmetric coupling matrices K averaged in the Raman-type sum."] = 20,
    random_seed: Annotated[int, "Seed of the random couplings."] = 20261005,
    trial_source_label: Annotated[str, "Label for a trial set without fc_provenance.json."] = "",
    output_dir: Annotated[str, "Default: the trial directory."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Zero-cost validation of the low-mode route on a COMPLETE DFT phonon set: the same Rayleigh-Ritz (trial modes from
    trial_source, D v_k taken from the exact DFT D) vs the exact DFT modes below the cutoff (frequency errors and their
    estimates, overlaps, residuals), one emulated preconditioned Davidson step, and the change of a Raman-type sum. Writes the
    Ritz modes (with and without the Davidson step) as gamma_modes_json files."""
    root = _h._root(runtime)
    try:
        dft_dir = _h._resolve_path(root, full_dft_phonon_dir, must_exist=True, file_ok=False)
        dft = cp._load_phonon(dft_dir)
        trial, label, trial_dir = _load_trial(root, trial_source, trial_source_label)
        deviation = cp._cell_deviation(dft.unitcell, trial.unitcell)
        masses = np.array(dft.primitive.masses)
        d = gamma_dynamical_matrix(dft)
        d = (d + d.T) / 2
        lam, e = np.linalg.eigh(d)
        exact = to_cm1(lam)
        acoustic = set(np.argsort(-(np.abs(translations(masses).T @ e) ** 2).sum(axis=0))[:3].tolist())
        cutoff = float(mode_cutoff_cm1)
        targets = [j for j in range(len(lam)) if j not in acoustic and exact[j] <= cutoff]
        if not targets:
            raise ValueError(f"No non-acoustic DFT mode below {cutoff:g} cm-1 to compare.")
        d_mlip = gamma_dynamical_matrix(trial)
        m_soft, n_auto = auto_trial_count(d_mlip, masses, cutoff)
        n_modes = int(n_modes) or n_auto
        v, trial_freqs = mlip_trial_vectors(d_mlip, masses, n_modes)
        tol = float(frequency_tolerance_cm1)

        def compare(basis, dbasis):
            # dbasis = D basis: the "measured" columns (one-sided and central differences give the same column for a harmonic D)
            rr = add_error_estimates(rayleigh_ritz(basis, dbasis, relative_residual_threshold), basis, d_mlip, masses, tol)
            ov = np.abs(rr["vectors"].T @ e[:, targets])  # (N, n_targets)
            match = ov.argmax(axis=0)
            low = rr["frequencies_cm1"] <= cutoff + 50.0  # Ritz modes that can stand for a target (near-degenerate mixing)
            rows = [{"exact_mode": int(j), "exact_cm1": round(float(exact[j]), 2), "ritz_mode": int(i), "ritz_cm1": round(float(rr["frequencies_cm1"][i]), 2),
                     "error_cm1": round(float(rr["frequencies_cm1"][i] - exact[j]), 2), "estimated_error_cm1": round(float(rr["estimated_frequency_error_cm1"][i]), 2),
                     "max_overlap": round(float(ov[i, c]), 4), "captured_by_low_ritz_modes": round(float((ov[low, c] ** 2).sum()), 4),
                     "in_trial_subspace": round(float(np.linalg.norm(basis.T @ e[:, j]) ** 2), 4),
                     "ritz_relative_residual": round(float(rr["relative_residuals"][i]), 4), "ritz_error_bound_cm1": round(float(rr["frequency_error_bound_cm1"][i]), 2),
                     "flagged": bool(rr["flagged"][i]), "unconverged": bool(rr["unconverged"][i])} for c, (j, i) in enumerate(zip(targets, match))]
            err = np.array([r["error_cm1"] for r in rows])
            est = np.array([r["estimated_error_cm1"] for r in rows])
            ovl = np.array([r["max_overlap"] for r in rows])
            real = np.array([r["exact_cm1"] > 0 for r in rows])
            ritz_low = rr["frequencies_cm1"] <= cutoff
            stats = {"subspace_size": int(basis.shape[1]), "n_exact_below_cutoff": len(targets), "n_ritz_below_cutoff": int(ritz_low.sum()),
                     "rms_error_cm1": round(float(np.sqrt((err[real] ** 2).mean())), 3) if real.any() else None,
                     "max_abs_error_cm1": round(float(np.abs(err[real]).max()), 3) if real.any() else None,
                     "min_overlap": round(float(ovl.min()), 4), "n_overlap_above_0.9": int((ovl > 0.9).sum()), "n_overlap_above_0.99": int((ovl > 0.99).sum()),
                     "n_flagged_below_cutoff": int((rr["flagged"] & ritz_low).sum()), "n_unconverged_below_cutoff": int((rr["unconverged"] & ritz_low).sum()),
                     "max_abs_estimate_minus_error_cm1": round(float(np.abs(est - err).max()), 3),
                     "converged_but_wrong": int(sum(1 for r in rows if not r["unconverged"] and (r["max_overlap"] < 0.9 or abs(r["error_cm1"]) > 2 * tol))),
                     "rigorous_bound_holds": bool(all(abs(r["error_cm1"]) <= r["ritz_error_bound_cm1"] + 1e-6 or r["max_overlap"] < 0.9 for r in rows)),
                     "imaginary_ritz_cm1": [round(float(f), 2) for f in rr["frequencies_cm1"] if f < 0]}
            return rr, rows, stats

        cell_atoms = cp._ase_atoms(dft.unitcell)
        center = int(coupling_center) if int(coupling_center) >= 0 else next(
            i for i, z in enumerate(cell_atoms.numbers) if 21 <= z <= 30 or 39 <= z <= 48 or 57 <= z <= 80)
        shell = _first_shell(cell_atoms, center, float(first_shell_radius_angstrom))
        temps = [float(t) for t in temperatures_k.split()]
        pos_exact = [j for j in targets if exact[j] > 0]

        def raman_change(rr):
            rng = np.random.default_rng(int(random_seed))  # the same couplings for every subspace
            pos = [i for i in range(len(rr["eigenvalues"])) if 0 < rr["frequencies_cm1"][i] <= cutoff]
            change = {f"{t:g}K": [] for t in temps}
            for _ in range(int(n_random_couplings)):
                k = rng.normal(size=(3 * len(shell), 3 * len(shell)))
                k = k + k.T
                for t in temps:
                    s_exact = raman_type_sum(exact[pos_exact], e[:, pos_exact], masses, shell, k, t)
                    change[f"{t:g}K"].append(raman_type_sum(rr["frequencies_cm1"][pos], rr["vectors"][:, pos], masses, shell, k, t) / s_exact - 1.0)
            return {key: {"mean_relative_change": round(float(np.mean(vals)), 4), "max_abs_relative_change": round(float(np.max(np.abs(vals))), 4)}
                    for key, vals in change.items()}

        out_dir = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else trial_dir)
        out_dir.mkdir(parents=True, exist_ok=True)

        def write_modes(rr, tag):
            path = out_dir / f"low_mode_hessian_emulated_{tag}.json"
            path.write_text(json.dumps(_modes_json(rr, masses, dft.unitcell.cell, dft.unitcell.positions, dft.unitcell.symbols, {
                "method": "EMULATED Rayleigh-Ritz: D v_k from the complete DFT dynamical matrix of " + _h._rel(root, dft_dir),
                "relative_residual_threshold": float(relative_residual_threshold), "trial_source": _h._rel(root, trial_dir), "trial_label": label})))
            return _h._rel(root, path)

        rr, rows, stats = compare(v, d @ v)
        unconverged_low = np.flatnonzero(rr["unconverged"] & (rr["frequencies_cm1"] <= cutoff))
        extra = davidson_directions(v, rr["corrections"][:, unconverged_low], masses)
        davidson = None
        if extra.shape[1]:
            # round 2 exactly as collect merges it: union of both rounds' vectors re-orthonormalized, columns transformed alike
            q, dq, _dropped = merge_rounds([(v, d @ v), (extra, d @ extra)])
            rr2, _rows2, stats2 = compare(q, dq)
            davidson = {"n_new_vectors": int(extra.shape[1]), "stats": stats2, "raman_type_sum": raman_change(rr2),
                        "gamma_modes_json": write_modes(rr2, f"N{int(n_modes)}_davidson{int(extra.shape[1])}")}
        report = {
            "full_dft_phonon_dir": _h._rel(root, dft_dir), "trial_source": _h._rel(root, trial_dir), "trial_label": label,
            "geometry_deviation_angstrom": round(deviation, 6), "m_trial_modes_below_cutoff": m_soft, "n_modes": int(n_modes),
            "n_cp2k_jobs_one_sided": {"round_1": int(n_modes) + 1, "with_davidson_round": int(n_modes) + 1 + (int(extra.shape[1]) if extra.shape[1] else 0)},
            "mode_cutoff_cm1": cutoff, "frequency_tolerance_cm1": tol,
            "trial_frequencies_cm1": [round(float(f), 1) for f in trial_freqs], **stats,
            "imaginary_exact_cm1": [round(float(exact[j]), 2) for j in targets if exact[j] < 0],
            "davidson_one_step": davidson,
            "raman_type_sum": {"formula": "sum_ij |<e_i|K|e_j>|^2 n_i (n_j+1) / (w_i w_j), modes 0 < w <= cutoff, random symmetric K on the first shell",
                               "center_atom": center, "shell_atoms": shell, "n_random_couplings": int(n_random_couplings), "by_temperature": raman_change(rr)},
            "modes": rows, "gamma_modes_json": write_modes(rr, f"N{int(n_modes)}"),
        }
        report_file = out_dir / f"low_mode_emulation_N{int(n_modes)}.json"
        report_file.write_text(json.dumps(report, indent=1))
        return {"ok": True, **{k: v for k, v in report.items() if k != "modes"}, "report": _h._rel(root, report_file)}
    except Exception as exc:
        return _h._error(exc)


low_mode_hessian_tool_map = {name: tool(fn) for name, fn in {
    "run_low_mode_dft_hessian": run_low_mode_dft_hessian,
    "run_low_mode_dft_hessian_round": run_low_mode_dft_hessian_round,
    "collect_low_mode_dft_hessian": collect_low_mode_dft_hessian,
    "emulate_low_mode_hessian": emulate_low_mode_hessian,
}.items()}
