"""Spin-lattice relaxation T1(T) of an S = 1/2 centre from first-principles spin-phonon couplings: direct + two-phonon Raman.

Lunghi & Sanvito, Sci. Adv. 5, eaax7163 (2019) [10.1126/sciadv.aax7163]; Lunghi & Sanvito, J. Phys. Chem. Lett. 11, 6273 (2020)
[10.1021/acs.jpclett.0c01681]; Lunghi, Sci. Adv. 8, eabn7880 (2022) [10.1126/sciadv.abn7880].

Chain: export_random_cluster_displacements -> ORCA g + A sweep (prepare/submit/collect_orca_displacement_sweep, observables
'g' and 'hfc:<metal index>') -> fit_spin_hamiltonian_derivatives (per observable) -> compute_spin_relaxation_time.

Spin Hamiltonian (cm-1): H_s = mu_B B.g.S + S.A.I (ORCA's BgS / SAI conventions, g_ij couples B_i S_j); A from ORCA in MHz
(/29979.2458), mu_B = 0.46686447783 cm-1/T, no nuclear Zeeman term; basis |m_S> x |m_I>, 2(2I+1) levels.

Phonons: crystal Gamma modes (phonopy, primitive = unit cell), Q_a = mass-weighted normal coordinate (sqrt(amu) A),
u_k = Q_a e_ka / sqrt(m_k). Acoustic modes (largest overlap with a uniform translation) and imaginary modes are dropped. The
derivatives of the displaced atoms are made translation-free (mass-weighted projection, as in analyze_spin_phonon_q_mesh):
rigidly shifting the displaced atoms must not change the tensor.
    dX/dQ_a = sum_k dX/du_k . e_ka/sqrt(m_k)        d2X/dQ_a dQ_b = sum_kl (e_ka/sqrt(m_k)) . d2X/du_k du_l . (e_lb/sqrt(m_l))
Amplitude: <Q_a^2>_0 = hbar/(2 w_a) (amu A^2); <Q_a^2>_T = <Q_a^2>_0 (2 n_a + 1) = crystal_phonons.mode_mean_square_q.

Rates a -> b in s^-1 (Fermi golden rule; w_ba = E_b - E_a in cm-1; V in cm-1 per sqrt(amu) A or per amu A^2; D = normalised
Gaussian of width sigma in 1/cm-1; c in cm/s; n(w) = 1/(exp(hc w/kT) - 1)):
    direct  W_ba = 4 pi^2 c sum_a |<b|dH/dQ_a|a>|^2 <Q_a^2>_0 D(|w_ba| - w_a) [n(|w_ba|) + (1 if w_ba < 0)]
    Raman   W_ba = 2 pi^2 c sum_{a,b ordered} |<b|d2H/dQ_a dQ_b|a>|^2 <Q_a^2>_0 <Q_b^2>_0
                   sum_{s_a = -s_b = +-1} D(w_ba - s_a w_a - s_b w_b) f(s_a, w_a') f(s_b, w_b')
            f(+, w) = n(w) (absorbed), f(-, w) = n(w) + 1 (emitted); this is (pi/hbar^2) sum |V|^2 G^2-ph of Lunghi 2019 with
            H_sph = 1/2 sum V_ab Q_a Q_b. Only the second-order coupling enters: products of first-order couplings through
            virtual states are excluded for S = 1/2 (Lunghi 2022). Double absorption / emission (s_a = s_b) is dropped: it needs
            w_a + w_b = |w_ba| <= ~1 cm-1, which only Gaussian tails reach (with Bose factors near |w_ba|/2: +22-28% spurious rate on
            VOPc, lowest mode 16.5 cm-1 at sigma 10), as on the q-mesh path. Absorbing and
            emitting the SAME mode leaves the bath unchanged (an elastic line at w_ba ~ 0.3 cm-1 that only the broadening lets
            through) and is excluded, as in Lunghi 2022 SI ("the term alpha = beta is only included for double absorption and double
            emission"). On VO(acac)2 (whole-molecule mode-space couplings, Gamma DFT phonons) it was 39-42% of the Raman rate at
            sigma 10 and 62% at sigma 5 (T1 1.7x / 2.7x longer without it).
Bose factors are taken at energy-conserving frequencies (w' = |w_ba| for one phonon; each of two phonons shifted by half the
mismatch, w' = w + s d/2), so every term obeys detailed balance exactly; D keeps the Gaussian of the mismatch.
D(x) = exp(-x^2 / 2 sigma^2) / (sigma sqrt(2 pi)): sigma (broadening_cm1) is the standard deviation. Lunghi 2019 SI Eq. 23 writes
exp(-x^2 / s^2) / (s sqrt(pi)) (standard deviation s / sqrt 2), so his s corresponds to broadening_cm1 = s / sqrt 2 (s = 10 -> 7.07);
MolForge (2025) calls sigma the standard deviation, as here.

T1: dp/dt = R p over the levels; p(0) = equilibrium after an ideal pi pulse on the electron spin (axis normal to the field);
M = <S.n> along the field; T1 = int_0^inf (M(t) - M_eq)/(M(0) - M_eq) dt, the area of the electron-spin recovery (T1_slowest_eigen_s,
the slowest non-zero eigenvalue of R, is reported separately and is not the metric). Lunghi fits exp(-(t/tau)^beta) to the same
recovery (beta ~0.7-0.9 for A-driven relaxation); its area is tau Gamma(1 + 1/beta), i.e. 1.05-1.27 tau.
Powder: 1/T1 averaged over the 14-point Lebedev grid of field directions (exact for spherical harmonics up to degree 5).
Gamma-only phonons carry no modes near a 0.3 cm-1 X-band gap: the direct rate is then a Gaussian tail (flagged), and the
Raman T1 is the metric (Lunghi 2022 used Gamma phonons with sigma ~10 cm-1 the same way).
gamma_modes_json (instead of phonon_dir) takes the Rayleigh-Ritz low modes of low_mode_hessian.py: the direct and Raman sums then
run over the trial subspace only -- modes outside it are ABSENT (not zero-coupled), so the rates are truncated to the subspace.

Mode-space derivatives (export_random_mode_displacements -> sweep -> fit_spin_hamiltonian_mode_derivatives): the WHOLE central
molecule moves along random combinations of the n real optical Gamma modes below a cutoff, restricted to its atoms with its net
translation removed (v_k = P e_k|mol, mass-weighted; u = sum_k Q_k M^-1/2 v_k), and g / A are fitted as quadratics in Q:
1 + n + n(n+1)/2 parameters whatever the molecule's size (VO(acac)2 Cartesian over 30 atoms: 4186). dX/dQ_k = e_k|mol . P w is the
Gamma path's projected coupling with every atom of the molecule displaced, so the rates use the fitted dX/dQ and d2X/dQdQ
directly; modes outside the set are absent. On VO(acac)2 the 300 K Raman rate came from modes below ~150 cm-1 (60-110 cm-1:
62%), and the derivative scope mattered ~5x (first shell 1.62 ms, + 4 chelate C 0.33 ms; both Cartesian fits had fewer +/- pairs
than second derivatives, i.e. min-norm Hessians): the molecule must move as a whole. Antithetic +/-Q pairs share their quadratic
features, so the auto training set is 2 ceil(1.5 n(n+1)/2) clusters and every fit reports its design rank.
mode_derivatives_to_cartesian turns them into Cartesian derivatives over every atom of the molecule (minimum-norm inside the span of
the restricted vectors; kind 'projected_mode_space') for the q-mesh path, which reports each phonon's coverage by that span.
VO(acac)2 (19 modes < 150 cm-1, fine-tuned-UMA mixed dispersion, 8x8x8, sigma 10): coverage 0.96-0.99 in every 10 cm-1 window;
Raman T1 3.3 s / 151 ms / 27 ms / 2.7 ms at 20 / 50 / 100 / 300 K vs Gamma 8.5 s / 249 ms / 44 ms / 4.4 ms.

q_mesh (dispersion; supercell or build_mixed_force_constants force constants): every (q, nu) of a Gamma-centred mesh enters through
the molecule's local displacement spectral matrix (mass-weighted, Bloch phases at the molecule's own cell images)
    rho_kl(w) = sum_{q,nu} hbar/(2 w) e_k e_l^* exp(i q.(R_k - R_l)) / N_q delta(w - w_q,nu)
(at Gamma, N_q = 1: sum_a <Q_a^2>_0 e_ka e_la delta(w - w_a)), contracted with the Cartesian couplings h = <b|d2H/dx dx|a>:
    direct  W_ba = 4 pi^2 c <b|dH/dx|a> . rho(|w_ba|) . <b|dH/dx|a>^* [n(|w_ba|) + (w_ba < 0)]
    Raman   W_ba = 4 pi^2 c sum_ij tr(rho_i h rho_j h^+) D(w_ba - w_i + w_j) n(w_i') (n(w_j') + 1)   (rho_i = rho in frequency bin i)
The Raman term is the quasi-elastic one (absorb a phonon at w_i, emit one at w_j ~ w_i): it is the Gamma sum's (+-) and (-+)
sign pairs with |V_ab|^2 <Q_a^2>_0 <Q_b^2>_0 = tr(rho_a h rho_b h^+), so a 1x1x1 mesh reproduces the Gamma path term by term.
Two-phonon absorption / emission needs w_i + w_j = |w_ba| ~ 0.3 cm-1, where the density (and translation-free coupling) vanishes;
under Gaussian broadening it would only pick up n(|w_ba|/2)^2 tails, so it is dropped (in the Gamma path too: < 1e-9 of the rate
when 2 w_min > ~8 sigma, but +22-28% spurious on VOPc whose lowest mode is 16.5 cm-1).
"""

from __future__ import annotations

import hashlib
import itertools
import json
import math
import re
from types import SimpleNamespace
from typing import Annotated, Any, Dict

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
from Hypothesis_generation.skill_library.periodic_dft.low_mode_hessian import translations

MU_B_CM1_PER_T = 0.46686447783
MHZ_PER_CM1 = 29979.2458
HC_OVER_K_CM_K = 1.438776877
NUCLEAR_SPINS = {"0": 0.0, "none": 0.0, "51V": 3.5, "63Cu": 1.5, "65Cu": 1.5, "59Co": 3.5, "55Mn": 2.5}
UNITS = {"g": "dimensionless", "hfc": "MHz", "zfs": "cm-1", "energy": "Eh"}
USE_R2 = 0.98
MODE_KIND, MODE_FIT_KIND = "random_modes", "mode_space_quadratic_fit"
MODE_AMPLITUDE_T = 300.0  # K: per-mode Q spreads of the mode-space sweep follow sqrt(<Q_k^2>) at this temperature


# --------------------------------------------------------------------------- #
# Derivatives of g / A from a displacement sweep
# --------------------------------------------------------------------------- #


def _quadratic_features(u: np.ndarray) -> np.ndarray:
    """[u_i, u_i u_j (i <= j)] per row: X - X0 = g.u + sum_i H_ii/2 u_i^2 + sum_{i<j} H_ij u_i u_j."""
    i, j = np.triu_indices(u.shape[1])
    return np.hstack([u, u[:, i] * u[:, j]])


def fit_quadratic(u_train, y_train, ridge: float = 0.0):
    """Least-squares first derivatives (n3 x nc) and symmetric second derivatives (n3 x n3 x nc) of y - y0 = g.u + 1/2 u.H.u."""
    phi = _quadratic_features(np.asarray(u_train, dtype=float))
    n3 = np.asarray(u_train).shape[1]
    if len(phi) < phi.shape[1] and ridge <= 0:
        raise ValueError(f"{len(phi)} training points for {phi.shape[1]} coefficients: add points, displace fewer atoms, or set ridge > 0.")
    scale = np.sqrt((phi**2).mean(axis=0))
    scale[scale == 0] = 1.0
    a = phi / scale
    if ridge > 0:
        theta = np.linalg.solve(a.T @ a + ridge * len(a) * np.eye(a.shape[1]), a.T @ y_train)
    else:
        theta = np.linalg.lstsq(a, y_train, rcond=None)[0]
    theta = theta / scale[:, None]
    i, j = np.triu_indices(n3)
    hess = np.zeros((n3, n3, theta.shape[1]))
    hess[i, j] = theta[n3:]
    hess = hess + hess.transpose(1, 0, 2)  # c_ij = H_ij (i < j); c_ii = H_ii / 2 -> doubled on the diagonal
    return theta[:n3], hess


def held_out_quadratic_fit(members, values, x0, coords, ridge: float, negligible_fraction: float) -> tuple[np.ndarray, np.ndarray, dict]:
    """fit_quadratic of values - x0 over coords(member) of the 'train' members, scored on the 'test' members (R^2, RMSE per component),
    with the rank of the design: antithetic +/-u pairs share their quadratic features, so each pair gives ONE equation for the
    n(n+1)/2 second derivatives -- fewer pairs than that leave a min-norm (shrunk) Hessian however good the held-out R^2."""
    sets = {}
    for split in ("train", "test"):
        rows = [m for m in members if m["split"] == split and m["member"] in values]
        if not rows:
            raise ValueError(f"No {split} member has a value.")
        sets[split] = (np.array([coords(m) for m in rows]), np.array([values[m["member"]] for m in rows]) - x0)
    first, second = fit_quadratic(*sets["train"], ridge=float(ridge))
    u_test, y_test = sets["test"]
    nc, n3 = y_test.shape[1], u_test.shape[1]
    phi = _quadratic_features(sets["train"][0])
    rank = int(np.linalg.matrix_rank(phi / np.where(np.abs(phi).max(axis=0) > 0, np.abs(phi).max(axis=0), 1.0)))
    pred = u_test @ first + 0.5 * np.einsum("ni,ijc,nj->nc", u_test, second, u_test)
    ss_res, ss_tot = ((y_test - pred) ** 2).sum(axis=0), ((y_test - y_test.mean(axis=0)) ** 2).sum(axis=0)
    spread = y_test.std(axis=0)
    negligible = spread < float(negligible_fraction) * spread.max() if spread.max() > 0 else np.ones(nc, bool)
    labels = ["".join(p) for p in itertools.product("xyz", repeat=2)] if nc == 9 else [str(c) for c in range(nc)]
    fit = {"n_train": len(sets["train"][0]), "n_test": len(u_test), "n_parameters_per_component": n3 + n3 * (n3 + 1) // 2, "design_rank": rank,
           "n_members_without_value": len(members) - len(sets["train"][0]) - len(u_test), "ridge": float(ridge),
           "r2_overall": float(1 - ss_res.sum() / ss_tot.sum()) if ss_tot.sum() > 0 else float("nan"),
           "rmse_overall": float(np.sqrt(((y_test - pred) ** 2).mean())),
           "per_component": [{"component": lab, "r2": float(1 - r / t) if t > 0 else None, "rmse": float(np.sqrt(r / len(u_test))),
                              "test_std": float(s), "negligible_variance": bool(neg)}
                             for lab, r, t, s, neg in zip(labels, ss_res, ss_tot, spread, negligible)]}
    return first, second, fit


def fit_verdict(fit: dict) -> str:
    if fit["design_rank"] < fit["n_parameters_per_component"] and fit["ridge"] <= 0:
        return (f"underdetermined: design rank {fit['design_rank']} < {fit['n_parameters_per_component']} coefficients (min-norm second derivatives, "
                "biased small); add +/- pairs (>= n(n+1)/2 pairs for n coordinates)")
    return "use" if fit["r2_overall"] >= USE_R2 else "more points or smaller amplitude"


def _derivatives_out(root, mpath, values_json: str, stem: str, observable: str):
    text = values_json.strip()
    out_dir = mpath.parent if text.startswith("{") else _h._resolve_path(root, text, must_exist=True, dir_ok=False).parent
    return out_dir / f"{stem}_{re.sub(r'[^A-Za-z0-9]+', '', observable) or 'X'}.json"


def fit_spin_hamiltonian_derivatives(
    displacement_manifest: Annotated[str, "random_displacements_manifest.json (export_random_cluster_displacements) or a +/-step cartesian_displacements_manifest.json."],
    values_json: Annotated[str, "sweep_values.json of collect_orca_displacement_sweep (or inline JSON) {member: [tensor components]}, incl. 'reference'."],
    observable: Annotated[str, "What the values are: 'g' (9 components), 'hfc:<atom>' (9 A components, MHz) or 'zfs' (labels/units only)."] = "g",
    ridge: Annotated[float, "Ridge strength on column-standardised features (0 = plain least squares; > 0 only to stabilise an ill-conditioned fit)."] = 0.0,
    negligible_fraction: Annotated[float, "Flag components whose held-out spread is below this fraction of the largest component's (R^2 meaningless there)."] = 1e-3,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """First and second Cartesian derivatives of a spin-Hamiltonian tensor: quadratic fit scored on held-out clusters (random
    manifest), or central differences with DIAGONAL second derivatives only (cartesian +/-step manifest, flagged 'diagonal_only')."""
    root = _h._root(runtime)
    try:
        mpath = _h._resolve_path(root, displacement_manifest, must_exist=True, dir_ok=False)
        man = json.loads(mpath.read_text())
        values = cp._load_values(root, values_json)
        if "reference" not in values:
            raise ValueError("values_json needs 'reference' (the undisplaced cluster): it is the intercept.")
        x0 = values["reference"]
        nc, atoms = len(x0), man["atoms"]
        n3 = 3 * len(atoms)
        result: dict[str, Any] = {"observable": observable, "unit": UNITS.get(observable.split(":")[0].strip().lower(), ""),
                                  "displacement_manifest": _h._rel(root, mpath), "phonon_dir": man.get("phonon_dir"),
                                  "reference_cluster": man.get("reference_cluster"), "reference_manifest": man.get("reference_manifest"),
                                  "atoms": atoms, "coordinate_order": "atom-major (atom0 x, y, z, atom1 x, ...) over 'atoms'",
                                  "component_order": "row-major 3x3 (xx, xy, xz, yx, ...) as collected" if nc == 9 else "as collected",
                                  "reference": x0.tolist()}
        if man.get("kind") == "random":
            first, second, fit = held_out_quadratic_fit(man["members"], values, x0, lambda m: np.ravel(m["displacement"]), ridge, negligible_fraction)
            result.update({"kind": "random_quadratic_fit", "diagonal_only": False, "fit": {**fit, "rms_angstrom": man.get("rms_angstrom")},
                           "verdict": fit_verdict(fit)})
        elif man.get("kind") == "cartesian":
            step = float(man["step_angstrom"])
            pm: dict[tuple[int, int], dict[int, np.ndarray]] = {}
            for m in man["members"]:
                if m["member"] in values:
                    pm.setdefault((int(m["cluster_atom"]), int(m["axis"])), {})[int(m["sign"])] = values[m["member"]]
            first, second = np.zeros((n3, nc)), np.zeros((n3, n3, nc))
            for k, a in enumerate(atoms):
                for ax in range(3):
                    v = pm.get((int(a["cluster_atom"]), ax), {})
                    if 1 not in v or -1 not in v:
                        raise ValueError(f"Missing +/- value for cluster atom {a['cluster_atom']} axis {'xyz'[ax]}.")
                    first[3 * k + ax] = (v[1] - v[-1]) / (2 * step)
                    second[3 * k + ax, 3 * k + ax] = (v[1] - 2 * x0 + v[-1]) / step**2
            result.update({"kind": "cartesian_central_difference", "diagonal_only": True, "fit": {"step_angstrom": step},
                           "verdict": "diagonal_only: first derivatives O(step^2); second derivatives without cross terms "
                                      "(export_random_cluster_displacements gives the full matrix)"})
        else:
            raise ValueError("Needs a random_displacements_manifest.json or a cartesian_displacements_manifest.json "
                             "(a random_mode_displacements_manifest.json goes to fit_spin_hamiltonian_mode_derivatives).")
        unit = {"dimensionless": "1", "": "X"}.get(result["unit"], result["unit"])
        result.update({"first_derivatives": first.reshape(len(atoms), 3, nc).tolist(), "first_derivative_unit": f"{unit}/A",
                       "second_derivatives": second.tolist(), "second_derivative_unit": f"{unit}/A^2"})
        out = _derivatives_out(root, mpath, values_json, "spin_hamiltonian_derivatives", observable)
        out.write_text(json.dumps(result))
        brief = {k: v for k, v in result.items() if k not in {"first_derivatives", "second_derivatives", "reference"}}
        return {"ok": True, **brief, "saved": _h._rel(root, out)}
    except Exception as exc:
        return _h._error(exc)


def load_gamma_set(root, phonon_dir: str, gamma_modes_json: str) -> SimpleNamespace:
    """Gamma modes of a phonopy directory (primitive = unit cell; acoustic three flagged) or of a low_mode_hessian.json (Rayleigh-Ritz;
    Ritz values whose error estimate says 'imaginary' are 'suspect'), with the sha256 of the file that defines them."""
    if gamma_modes_json.strip():
        if phonon_dir.strip():
            raise ValueError("Pass phonon_dir OR gamma_modes_json, not both.")
        path = _h._resolve_path(root, gamma_modes_json, must_exist=True, dir_ok=False)
        low = json.loads(path.read_text())
        freqs = np.array(low["frequencies_cm1"], dtype=float)
        # A Ritz value between a partly captured imaginary mode and the real ones: its MLIP-preconditioned estimate says the
        # exact mode is imaginary (VO(acac)2, N = 20: Ritz 14.7 cm-1, estimate -53, exact -55); dropped like an imaginary mode.
        est = np.array(low.get("estimated_frequency_error_cm1") or np.zeros(len(freqs)))
        lat = np.array(low["structure"]["cell"], dtype=float)
        return SimpleNamespace(
            freqs=freqs, vecs=np.array(low["eigenvectors_mass_weighted"], dtype=float).reshape(len(freqs), -1).T, acoustic=[],
            masses=np.array(low["structure"]["masses"], dtype=float), suspect={i for i in range(len(freqs)) if freqs[i] > 0 and freqs[i] - est[i] <= 0},
            phonon=SimpleNamespace(primitive=SimpleNamespace(cell=lat, scaled_positions=np.array(low["structure"]["positions_angstrom"]) @ np.linalg.inv(lat))),
            ph_dir=None, low_mode=low, path=path, sha256=hashlib.sha256(path.read_bytes()).hexdigest())
    path = _h._resolve_path(root, phonon_dir, must_exist=True, file_ok=False)
    phonon = cp._load_phonon(path)
    if len(phonon.primitive) != len(phonon.unitcell):
        raise ValueError("The phonopy primitive cell must be the unit cell (primitive_matrix 'P'): cluster indices refer to the unit cell.")
    freqs, vecs, acoustic = gamma_modes(phonon)
    return SimpleNamespace(freqs=freqs, vecs=vecs, acoustic=acoustic, masses=np.array(phonon.primitive.masses), suspect=set(), phonon=phonon,
                           ph_dir=path, low_mode=None, path=path, sha256=hashlib.sha256((path / cp.PHONOPY_PARAMS).read_bytes()).hexdigest())


def export_random_mode_displacements(
    cluster_manifest: Annotated[str, "cluster_manifest.json of the reference cluster (extract_molecular_cluster_from_crystal on the phonon reference cell)."],
    phonon_dir: Annotated[str, "Crystal phonon directory (phonopy_params.yaml; primitive = the unit cell the cluster was carved from)."] = "",
    gamma_modes_json: Annotated[str, "Alternative to phonon_dir: low_mode_hessian.json of collect_low_mode_dft_hessian (Rayleigh-Ritz Gamma modes)."] = "",
    mode_cutoff_cm1: Annotated[float, "Real optical Gamma modes up to this frequency span the displacements (VO(acac)2's 300 K Raman rate: modes < 150 cm-1)."] = 150.0,
    molecule: Annotated[str, "'center' (every atom of the cluster's central molecule) or explicit 0-based cluster indices '0 5 7'."] = "center",
    n_train: Annotated[int, "Training clusters; 0 = 2 ceil(1.5 n(n+1)/2) for n modes (each +/-Q pair is ONE equation for the n(n+1)/2 second derivatives)."] = 0,
    n_test: Annotated[int, "Held-out clusters that score the fit; 0 = ~20% of n_train."] = 0,
    target_rms_angstrom: Annotated[float, "Expected rms Cartesian displacement per coordinate (A) of the amplitude_reference atoms; per-mode Q spreads are sqrt(<Q_k^2>_300K) x one common scale."] = 0.02,
    amplitude_reference: Annotated[str, "'first_shell' (metal + bonded donors set the scale: soft modes move H most) or 'all' (every displaced atom)."] = "first_shell",
    max_atom_displacement_angstrom: Annotated[float, "Members (with their -Q partner) whose largest atomic move exceeds this are scaled down to it (methyl torsions)."] = 0.25,
    seed: Annotated[int, "Random seed (record it)."] = 20261006,
    output_dir: Annotated[str, "Default <cluster folder>/random_mode_displacements."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Clusters with the WHOLE central molecule displaced along random combinations of the crystal's soft Gamma modes (restricted to
    its atoms, net translation removed, mass-weighted: u = sum_k Q_k M^-1/2 v_k; antithetic +/-Q pairs): the sweep of a quadratic fit
    in the mode coordinates Q (fit_spin_hamiltonian_mode_derivatives), n + n(n+1)/2 coefficients for n modes whatever the molecule size."""
    root = _h._root(runtime)
    try:
        from ase.io import write

        gs = load_gamma_set(root, phonon_dir, gamma_modes_json)
        mpath, man, cluster, origin, chosen = cp._cluster_selection(root, cluster_manifest, "molecule" if molecule.strip() == "center" else molecule, "")
        if int(man["cell_atoms"]) != len(gs.masses):
            raise ValueError(f"The cluster was carved from a {man['cell_atoms']}-atom cell but the phonon cell has {len(gs.masses)} atoms.")
        cell_atoms = [int(origin[k][0]) for k in chosen]
        deviation = cp.molecule_positions_in_phonon_cell(gs.phonon, cluster.positions[chosen], cell_atoms)[1]
        modes = [int(i) for i in np.argsort(gs.freqs) if i not in gs.acoustic and i not in gs.suspect and 0 < gs.freqs[i] <= float(mode_cutoff_cm1)]
        if not modes:
            raise ValueError(f"No real optical Gamma mode up to {mode_cutoff_cm1:g} cm-1.")
        rows = np.ravel([[3 * c, 3 * c + 1, 3 * c + 2] for c in cell_atoms])
        masses = gs.masses[cell_atoms]
        e, t = gs.vecs[rows][:, modes], translations(masses)
        vec = e - t @ (t.T @ e)  # the molecule's rows of each mode, its net (mass-weighted) translation removed
        cart = vec / np.repeat(np.sqrt(masses), 3)[:, None]  # A per unit Q (amu^1/2 A)
        if amplitude_reference not in {"first_shell", "all"}:
            raise ValueError("amplitude_reference must be 'first_shell' or 'all'.")
        shell = cp._cluster_selection(root, cluster_manifest, "first_shell", "")[4] if amplitude_reference == "first_shell" else chosen
        if not set(shell) <= set(chosen):
            raise ValueError("The metal and its first-shell donors must be among the displaced atoms for amplitude_reference='first_shell'.")
        ref_rows = np.ravel([[3 * chosen.index(k) + a for a in range(3)] for k in shell])
        q_thermal = np.sqrt([cp.mode_mean_square_q(float(gs.freqs[i]), MODE_AMPLITUDE_T) for i in modes])
        scale = float(target_rms_angstrom) / math.sqrt(float((q_thermal**2 * (cart[ref_rows] ** 2).sum(axis=0)).sum()) / len(ref_rows))
        cap = float(max_atom_displacement_angstrom)
        n = len(modes)
        n_params = n + n * (n + 1) // 2
        n_quad = n * (n + 1) // 2  # +/-Q pairs share their quadratic features: one equation per PAIR for the second derivatives
        n_train, n_test = int(n_train) or 2 * math.ceil(1.5 * n_quad), int(n_test)
        n_test = n_test or 2 * math.ceil(0.1 * n_train)
        out = _h._under_root(root, _h._resolve_path(root, output_dir) if output_dir.strip() else mpath.parent / "random_mode_displacements")
        out.mkdir(parents=True, exist_ok=True)
        write(str(out / "reference.xyz"), cluster)
        rng = np.random.default_rng(int(seed))
        members, disp, n_capped = [], [], 0
        for split, count in (("train", n_train), ("test", n_test)):
            draws = rng.normal(0.0, 1.0, size=(math.ceil(count / 2), n)) * scale * q_thermal
            peak = np.linalg.norm((draws @ cart.T).reshape(len(draws), -1, 3), axis=2).max(axis=1)
            draws[peak > cap] *= (cap / peak[peak > cap])[:, None]
            n_capped += int(np.concatenate([peak > cap, peak > cap])[:count].sum())
            for k, q in enumerate(np.concatenate([draws, -draws])[:count]):  # +Q/-Q pairs: odd and even features orthogonal
                u = (cart @ q).reshape(-1, 3)
                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, "q": q.tolist(), "displacement": np.round(u, 10).tolist(),
                                "qm_xyz": _h._rel(root, out / f"{label}.xyz")})
                disp.append(u)
        disp = np.array(disp)
        symbols = np.array(cluster.get_chemical_symbols())[chosen]
        weight, trans = (e**2).sum(axis=0), ((t.T @ e) ** 2).sum(axis=0)
        source = {"phonon_dir": _h._rel(root, gs.ph_dir) if gs.ph_dir is not None else None,
                  "gamma_modes_json": _h._rel(root, gs.path) if gs.low_mode is not None else None, "phonon_set_sha256": gs.sha256}
        manifest = {
            "kind": MODE_KIND, "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"), **source,
            "seed": int(seed), "n_train": n_train, "n_test": n_test, "n_fit_parameters": n_params, "target_rms_angstrom": float(target_rms_angstrom),
            "rms_angstrom": round(float(np.sqrt((disp**2).mean())), 5), "max_atom_displacement_angstrom": round(float(np.linalg.norm(disp, axis=2).max()), 4),
            "rms_by_element_angstrom": {s: round(float(np.sqrt((disp[:, symbols == s] ** 2).mean())), 5) for s in sorted(set(symbols))},
            "max_by_element_angstrom": {s: round(float(np.linalg.norm(disp[:, symbols == s], axis=2).max()), 4) for s in sorted(set(symbols))},
            "amplitude_reference": amplitude_reference, "reference_atoms_rms_angstrom": round(float(np.sqrt((disp.reshape(len(disp), -1)[:, ref_rows] ** 2).mean())), 5),
            "max_atom_displacement_cap_angstrom": cap, "n_members_capped": n_capped,
            "amplitude_rule": f"Q_k ~ N(0, (s sqrt(<Q_k^2>_{MODE_AMPLITUDE_T:g}K))^2), s = {scale:.4g} (expected rms per coordinate of the "
                              f"{amplitude_reference} atoms = target); a +/-Q pair moving any atom > {cap:g} A is scaled down to {cap:g} A",
            "mapping_max_deviation_angstrom": round(deviation, 5),
            "modes": {"indices": modes, "frequencies_cm1": [float(gs.freqs[i]) for i in modes], "q_std_sqrt_amu_angstrom": (scale * q_thermal).tolist(),
                      "weight_on_molecule": weight.tolist(), "translation_fraction": (trans / weight).tolist()},
            "excluded": {"acoustic": [int(i) for i in gs.acoustic], "imaginary_or_suspect_cm1": [round(float(gs.freqs[i]), 2) for i in np.argsort(gs.freqs)
                                                                                              if i not in gs.acoustic and (gs.freqs[i] <= 0 or i in gs.suspect)]},
            "mode_vectors_mass_weighted": vec.T.tolist(),
            "atoms": [{"cluster_atom": k, "cell_atom": c, "element": cluster[k].symbol} for k, c in zip(chosen, cell_atoms)],
            "displacement_convention": "displacement = sum_k q_k mode_vectors_mass_weighted[k] / sqrt(m) on atoms (A); member geometry = reference + "
                                       "displacement[i] on atoms[i]; every other atom fixed. Vectors: the molecule's rows of each Gamma eigenvector "
                                       "(weight_on_molecule = their squared norm) minus their mass-weighted net translation (translation_fraction).",
            "members": members,
            "protocol_rule": "Same ORCA protocol and point charges for all members (prepare_orca_displacement_sweep); then fit_spin_hamiltonian_mode_derivatives.",
        }
        (out / "random_mode_displacements_manifest.json").write_text(json.dumps(manifest, indent=1))
        result = {"ok": True, **{k: manifest[k] for k in ("n_train", "n_test", "n_fit_parameters", "rms_angstrom", "max_atom_displacement_angstrom",
                                                           "rms_by_element_angstrom", "max_by_element_angstrom", "reference_atoms_rms_angstrom",
                                                           "n_members_capped", "amplitude_rule", "excluded", "phonon_set_sha256")},
                  "n_atoms_displaced": len(chosen), "n_modes": n, "n_clusters": len(members),
                  "modes": [{"mode": i, "frequency_cm1": round(float(gs.freqs[i]), 2), "weight_on_molecule": round(float(w), 4),
                             "translation_fraction": round(float(f), 4)} for i, w, f in zip(modes, weight, trans / weight)],
                  "manifest": _h._rel(root, out / "random_mode_displacements_manifest.json")}
        if n_train // 2 < 1.5 * n_quad:
            result["warning"] = (f"n_train={n_train}: {n_train // 2} +/-Q pairs for {n_quad} second derivatives (one equation per pair; "
                                 f"{'UNDERDETERMINED' if n_train // 2 < n_quad else 'little margin'}): use n_train >= {2 * math.ceil(1.5 * n_quad)} or lower mode_cutoff_cm1.")
        if n_capped > 0.3 * len(members):
            result["warning_amplitude"] = f"{n_capped}/{len(members)} members capped at {cap:g} A: the amplitude distribution is far from thermal; lower target_rms_angstrom."
        return result
    except Exception as exc:
        return _h._error(exc)


def fit_spin_hamiltonian_mode_derivatives(
    displacement_manifest: Annotated[str, "random_mode_displacements_manifest.json (export_random_mode_displacements)."],
    values_json: Annotated[str, "sweep_values.json of collect_orca_displacement_sweep (or inline JSON) {member: [tensor components]}, incl. 'reference'."],
    observable: Annotated[str, "What the values are: 'g' (9 components), 'hfc:<atom>' (9 A components, MHz) or 'zfs' (labels/units only)."] = "g",
    ridge: Annotated[float, "Ridge strength on column-standardised features (0 = plain least squares)."] = 0.0,
    negligible_fraction: Annotated[float, "Flag components whose held-out spread is below this fraction of the largest component's."] = 1e-3,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """dX/dQ_k (n x 9) and d2X/dQ_k dQ_l (n x n x 9) of a spin-Hamiltonian tensor in the crystal's soft Gamma-mode coordinates: per-component
    quadratic fit in Q (reference value as intercept) scored on held-out clusters (verdict 'use' at R^2 >= 0.98). Pass the g and A
    outputs to compute_spin_relaxation_time as g_mode_derivatives_json / a_mode_derivatives_json."""
    root = _h._root(runtime)
    try:
        mpath = _h._resolve_path(root, displacement_manifest, must_exist=True, dir_ok=False)
        man = json.loads(mpath.read_text())
        if man.get("kind") != MODE_KIND:
            raise ValueError("Needs a random_mode_displacements_manifest.json (export_random_mode_displacements); Cartesian manifests go to "
                             "fit_spin_hamiltonian_derivatives.")
        values = cp._load_values(root, values_json)
        if "reference" not in values:
            raise ValueError("values_json needs 'reference' (the undisplaced cluster): it is the intercept.")
        x0 = values["reference"]
        first, second, fit = held_out_quadratic_fit(man["members"], values, x0, lambda m: np.asarray(m["q"], dtype=float), ridge, negligible_fraction)
        unit = UNITS.get(observable.split(":")[0].strip().lower(), "")
        label = {"dimensionless": "1", "": "X"}.get(unit, unit)
        result = {
            "kind": MODE_FIT_KIND, "observable": observable, "unit": unit, "displacement_manifest": _h._rel(root, mpath),
            "reference_cluster": man.get("reference_cluster"), "reference_manifest": man.get("reference_manifest"), "atoms": man["atoms"],
            "modes": {"indices": man["modes"]["indices"], "frequencies_cm1": man["modes"]["frequencies_cm1"], "phonon_dir": man.get("phonon_dir"),
                      "gamma_modes_json": man.get("gamma_modes_json"), "phonon_set_sha256": man["phonon_set_sha256"]},
            "component_order": "row-major 3x3 (xx, xy, xz, yx, ...) as collected" if len(x0) == 9 else "as collected", "reference": x0.tolist(),
            "fit": {**fit, "rms_angstrom": man.get("rms_angstrom"), "n_modes": len(man["modes"]["indices"])},
            "verdict": fit_verdict(fit),
            "first_derivatives": first.tolist(), "first_derivative_unit": f"{label}/(amu^1/2 A)",
            "second_derivatives": second.tolist(), "second_derivative_unit": f"{label}/(amu A^2)",
        }
        out = _derivatives_out(root, mpath, values_json, "spin_hamiltonian_mode_derivatives", observable)
        out.write_text(json.dumps(result))
        brief = {k: v for k, v in result.items() if k not in {"first_derivatives", "second_derivatives", "reference", "atoms"}}
        return {"ok": True, **brief, "saved": _h._rel(root, out)}
    except Exception as exc:
        return _h._error(exc)


PROJECTED_KIND = "projected_mode_space"


def mode_derivatives_to_cartesian(
    mode_derivatives_json: Annotated[str, "fit_spin_hamiltonian_mode_derivatives output (g or hfc)."],
    rcond: Annotated[float, "Restricted mode-vector directions with singular value < rcond x the largest are dropped as null."] = 1e-3,
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """Cartesian dX/du (every atom of the molecule) and d2X/du du from mode-space derivatives, for the q-mesh path of
    compute_spin_relaxation_time: the minimum-norm mass-weighted gradient w and Hessian H inside the span S of the sweep's
    molecule-restricted, translation-free Gamma vectors V (V^T w = dX/dQ, V^T H V = d2X/dQdQ; V = U s W^T, s < rcond s_max dropped),
    zero along every direction outside S. Reports the span dimension and how consistently the fitted couplings fit one w and H."""
    root = _h._root(runtime)
    try:
        dpath = _h._resolve_path(root, mode_derivatives_json, must_exist=True, dir_ok=False)
        der = json.loads(dpath.read_text())
        if der.get("kind") != MODE_FIT_KIND:
            raise ValueError(f"{dpath.name} is not a fit_spin_hamiltonian_mode_derivatives output.")
        man = json.loads(_h._resolve_path(root, der["displacement_manifest"], must_exist=True, dir_ok=False).read_text())
        gs = load_gamma_set(root, "" if man.get("gamma_modes_json") else man.get("phonon_dir") or "", man.get("gamma_modes_json") or "")
        if gs.sha256 != man["phonon_set_sha256"]:
            raise ValueError("The phonon set changed since the mode-space sweep was exported (sha256 differs).")
        v = np.array(man["mode_vectors_mass_weighted"], dtype=float).T  # (3m, n)
        u, s, wt = np.linalg.svd(v, full_matrices=False)
        keep = s >= float(rcond) * s.max()
        pinv = u[:, keep] @ np.diag(1.0 / s[keep]) @ wt[keep]  # w = pinv a: the minimum-norm solution of V^T w = a
        a1, a2 = np.array(der["first_derivatives"], dtype=float), np.array(der["second_derivatives"], dtype=float)
        w, h = pinv @ a1, np.einsum("in,nmc,jm->ijc", pinv, a2, pinv)
        sq = np.repeat(np.sqrt(gs.masses[[int(a["cell_atom"]) for a in man["atoms"]]]), 3)  # dX/du = sqrt(m) dX/d(sqrt(m) u)
        nc = a1.shape[1]
        unit = {"dimensionless": "1", "": "X"}.get(der["unit"], der["unit"])
        result = {
            "kind": PROJECTED_KIND, "observable": der["observable"], "unit": der["unit"], "mode_derivatives": _h._rel(root, dpath),
            **{k: der.get(k) for k in ("displacement_manifest", "reference_cluster", "reference_manifest", "component_order", "fit", "verdict")},
            "phonon_dir": man.get("phonon_dir"), "atoms": man["atoms"], "coordinate_order": "atom-major (atom0 x, y, z, atom1 x, ...) over 'atoms'",
            "span": {"dimension": int(keep.sum()), "n_modes": int(v.shape[1]), "rcond": float(rcond), "relative_singular_values": (s / s.max()).round(5).tolist(),
                     "consistency_residual_first": float(np.linalg.norm(v.T @ w - a1) / max(np.linalg.norm(a1), 1e-300)),
                     "consistency_residual_second": float(np.linalg.norm(np.einsum("in,ijc,jm->nmc", v, h, v) - a2) / max(np.linalg.norm(a2), 1e-300)),
                     "rule": "derivatives are zero along every direction outside the span (and along the molecule's net translation)"},
            "span_basis_mass_weighted": u[:, keep].tolist(), "reference": der["reference"],
            "first_derivatives": (w * sq[:, None]).reshape(len(man["atoms"]), 3, nc).tolist(), "first_derivative_unit": f"{unit}/A",
            "second_derivatives": (h * sq[:, None, None] * sq[None, :, None]).tolist(), "second_derivative_unit": f"{unit}/A^2",
        }
        out = dpath.parent / f"spin_hamiltonian_derivatives_from_modes_{re.sub(r'[^A-Za-z0-9]+', '', der['observable']) or 'X'}.json"
        out.write_text(json.dumps(result))
        return {"ok": True, "kind": PROJECTED_KIND, "observable": der["observable"], "span": result["span"], "n_atoms": len(man["atoms"]),
                "saved": _h._rel(root, out)}
    except Exception as exc:
        return _h._error(exc)


# --------------------------------------------------------------------------- #
# Spin levels, rates and T1
# --------------------------------------------------------------------------- #


def lebedev14() -> tuple[np.ndarray, np.ndarray]:
    """Lebedev 14-point sphere grid: 6 octahedral (weight 1/15) + 8 cubic (3/40) unit vectors; weights sum to 1."""
    cube = np.array(list(itertools.product((1.0, -1.0), repeat=3))) / np.sqrt(3.0)
    return np.vstack([np.eye(3), -np.eye(3), cube]), np.array([1 / 15] * 6 + [3 / 40] * 8)


def bose(w_cm1, t_k):
    """Bose-Einstein occupation n(w) at T (w > 0 in cm-1)."""
    return 1.0 / np.expm1(np.minimum(HC_OVER_K_CM_K * np.asarray(w_cm1, dtype=float) / max(float(t_k), 1e-12), 700.0))


def zero_point_q2(freqs_cm1) -> np.ndarray:
    """<Q^2>_0 = hbar/(2 w) in amu A^2 (mode_mean_square_q at T = 0)."""
    return np.array([cp.mode_mean_square_q(float(f), 0.0) for f in np.atleast_1d(freqs_cm1)])


def _spin_matrices(s: float) -> np.ndarray:
    """(3, 2s+1, 2s+1) Sx, Sy, Sz in the |s>, |s-1>, ..., |-s> basis."""
    m = np.arange(s, -s - 0.5, -1.0)
    sp = np.diag(np.sqrt(s * (s + 1) - m[1:] * (m[1:] + 1)), 1)  # <m+1|S+|m>
    return np.array([(sp + sp.T) / 2, (sp - sp.T) / 2j, np.diag(m).astype(complex)])


def spin_system(g0, a0_mhz, nuclear_spin: float, field_tesla: float, direction) -> dict[str, np.ndarray]:
    """Levels (cm-1, ascending) of H_s and, in their eigenbasis, the operators multiplying each g component
    (O_g[3i+j] = mu_B B n_i S_j) and each A component in MHz (O_A[3i+j] = S_i I_j / 29979.2458), S.n and S.m (m normal to n)."""
    n = np.asarray(direction, dtype=float) / np.linalg.norm(direction)
    s, nuc = _spin_matrices(0.5), _spin_matrices(float(nuclear_spin))
    s_full = np.array([np.kron(x, np.eye(nuc.shape[1])) for x in s])
    i_full = np.array([np.kron(np.eye(2), x) for x in nuc])
    o_g = np.array([MU_B_CM1_PER_T * field_tesla * n[a] * s_full[b] for a in range(3) for b in range(3)])
    o_a = np.array([s_full[a] @ i_full[b] / MHZ_PER_CM1 for a in range(3) for b in range(3)])
    h0 = np.einsum("c,cij->ij", np.ravel(g0), o_g)
    if a0_mhz is not None:
        h0 = h0 + np.einsum("c,cij->ij", np.ravel(a0_mhz), o_a)
    e, u = np.linalg.eigh(h0)
    m_axis = np.cross(n, np.eye(3)[np.argmin(np.abs(n))])
    m_axis /= np.linalg.norm(m_axis)

    def rot(op):
        return np.einsum("ji,...jk,kl->...il", u.conj(), op, u)

    return {"energies": e, "g": rot(o_g), "A": rot(o_a), "s_n": rot(np.einsum("a,aij->ij", n, s_full)),
            "s_m": rot(np.einsum("a,aij->ij", m_axis, s_full))}


def coupling_strengths(system, d1: dict, d2: dict) -> tuple[dict, dict]:
    """|<b|V|a>|^2 per mode (n1, L, L) and ordered mode pair (n2, n2, L, L) for the 'total', 'g'-only and 'A'-only couplings.
    d1[key] = dX/dQ (n1, 9), d2[key] = d2X/dQdQ (n2, n2, 9) for key 'g' (dimensionless) and 'A' (MHz)."""
    keys = [k for k in ("g", "A") if d1.get(k) is not None]
    abs1, abs2 = {}, {}
    for name, use in (("total", keys), *((k, [k]) for k in keys)):
        v1 = sum(np.einsum("ac,cij->aij", d1[k], system[k]) for k in use)
        v2 = sum(np.einsum("abc,cij->abij", d2[k], system[k]) for k in use)
        abs1[name], abs2[name] = np.abs(v1) ** 2, np.abs(v2) ** 2
    return abs1, abs2


def rate_kernels(energies, f1, f2, t_k: float, sigma: float) -> tuple[np.ndarray, np.ndarray]:
    """K1 (n1, L, L), K2 (n2, n2, L, L) with W_ba = 4 pi^2 c sum_a |V1|^2 K1 + 2 pi^2 c sum_ab |V2|^2 K2 (s^-1; see module doc).
    Bose factors at energy-conserving frequencies, so W_ba p_a = W_ab p_b exactly."""
    f1, f2 = np.asarray(f1, dtype=float), np.asarray(f2, dtype=float)
    w = energies[:, None] - energies[None, :]  # w[b, a] = E_b - E_a

    def gauss(x):
        return np.exp(-0.5 * (x / sigma) ** 2) / (np.sqrt(2 * np.pi) * sigma)

    gap = np.abs(w) > 1e-9  # off-diagonal, non-degenerate: a one-phonon transition needs w' = |w_ba| > 0
    occ1 = np.where(gap, bose(np.where(gap, np.abs(w), 1.0), t_k) + (w < 0), 0.0)
    k1 = zero_point_q2(f1)[:, None, None] * gauss(np.abs(w)[None] - f1[:, None, None]) * occ1[None]
    fa, fb = f2[:, None, None, None], f2[None, :, None, None]
    off = ~np.eye(len(energies), dtype=bool)
    k2 = np.zeros((len(f2), len(f2)) + w.shape)
    for sa, sb in ((1, -1), (-1, 1)):
        # Double absorption / emission (sa == sb) would need w_a + w_b = |w_ba| <= ~1 cm-1 for S = 1/2: only Gaussian tails reach it,
        # and their energy-conserving Bose factors sit at ~|w_ba|/2 (n ~ 1e3 at 300 K) -- +22-28% spurious rate on VOPc (lowest
        # mode 16.5 cm-1, sigma 10). Dropped, as on the q-mesh path.
        d = w[None, None] - sa * fa - sb * fb  # energy mismatch of absorbing (s=+1) / emitting (s=-1) each phonon
        wa, wb = fa + sa * d / 2, fb + sb * d / 2
        ok = (wa > 0) & (wb > 0) & off
        na = bose(np.where(ok, wa, 1.0), t_k) + (sa < 0)
        nb = bose(np.where(ok, wb, 1.0), t_k) + (sb < 0)
        term = np.where(ok, gauss(d) * na * nb, 0.0)
        if sa != sb and not INCLUDE_SAME_MODE_RAMAN:  # absorb and emit the SAME mode: elastic, excluded (Lunghi 2022 SI)
            term[np.arange(len(f2)), np.arange(len(f2))] = 0.0
        k2 += term
    q2 = zero_point_q2(f2)
    return k1, k2 * q2[:, None, None, None] * q2[None, :, None, None]


def equilibrium(energies, t_k: float) -> np.ndarray:
    p = np.exp(-HC_OVER_K_CM_K * (energies - energies.min()) / float(t_k))
    return np.maximum(p / p.sum(), 1e-300)


def t1_from_rates(w, system, t_k: float) -> dict[str, float]:
    """T1 = int (M(t) - M_eq)/(M(0) - M_eq) dt after an electron-spin pi pulse (M = <S.n>), the slowest non-zero relaxation
    time of the rate matrix and the detailed-balance error max|W_ba p_a - W_ab p_b| / max(W p)."""
    p = equilibrium(system["energies"], t_k)
    w = np.where(np.eye(len(p), dtype=bool), 0.0, w)
    flux = w * p[None, :]
    balance = float(np.abs(flux - flux.T).max() / flux.max()) if flux.max() > 0 else 0.0
    r = w - np.diag(w.sum(axis=0))
    sq = np.sqrt(p)
    rs = r * sq[None, :] / sq[:, None]  # D^-1/2 R D^1/2: symmetric under detailed balance
    lam, vec = np.linalg.eigh((rs + rs.T) / 2)
    m = np.real(np.diag(system["s_n"]))
    dp = 4 * (np.abs(system["s_m"]) ** 2) @ p - p  # p(0) - p_eq; p(0) = 4 diag((S.m) rho_eq (S.m))
    weight = (vec.T @ (dp / sq)) * (vec.T @ (m * sq))
    keep = np.arange(len(p)) != np.argmax(np.abs(vec.T @ sq))  # drop the stationary (equilibrium) eigenvector
    stuck = keep & (lam > -1e-13 * max(np.abs(lam).max(), 1e-300))
    if np.any(np.abs(weight[stuck]) > 1e-9 * abs(m @ dp)) or m @ dp == 0:
        t1 = math.inf
    else:
        t1 = float((weight[keep & ~stuck] / -lam[keep & ~stuck]).sum() / (m @ dp))
    live = lam[keep & ~stuck]
    return {"T1_s": t1, "slowest_s": float(-1.0 / live.max()) if len(live) else math.inf, "detailed_balance_error": balance}


CASES = ("total", "direct", "raman", "g_only", "A_only")


def relaxation_vs_temperature(direction, field_tesla, g0, a0_mhz, nuclear_spin, d1, d2, f1, f2, temps, sigma,
                              report_t: float | None = None) -> dict[str, Any]:
    """Per temperature: T1 total / direct-only / Raman-only / g-only / A-only for one field direction, plus, at report_t,
    the spin-flip-weighted rate of each mode (direct, n1) and mode pair (Raman, n2 x n2)."""
    system = spin_system(g0, a0_mhz, nuclear_spin, field_tesla, direction)
    abs1, abs2 = coupling_strengths(system, d1, d2)
    pre1, pre2 = 4 * np.pi**2 * cp.C_CM_PER_S, 2 * np.pi**2 * cp.C_CM_PER_S
    out: dict[str, Any] = {"energies": system["energies"], "rows": []}
    for t in temps:
        k1, k2 = rate_kernels(system["energies"], f1, f2, t, sigma)
        w1 = {k: pre1 * np.einsum("aij,aij->ij", v, k1) for k, v in abs1.items()}
        w2 = {k: pre2 * np.einsum("abij,abij->ij", v, k2) for k, v in abs2.items()}
        cases = {"total": w1["total"] + w2["total"], "direct": w1["total"], "raman": w2["total"]}
        cases.update({f"{k}_only": w1[k] + w2[k] for k in ("g", "A") if k in w1})
        out["rows"].append({"T_K": t, **{c: t1_from_rates(w, system, t) for c, w in cases.items()}})
        if report_t is not None and t == report_t:
            p, m = equilibrium(system["energies"], t), np.real(np.diag(system["s_n"]))
            flip = p[None, :] * (m[:, None] - m[None, :]) ** 2  # rates that move M (electron-spin flips)
            out["direct_by_mode"] = pre1 * np.einsum("aij,aij,ij->a", abs1["total"], k1, flip)
            out["raman_by_pair"] = pre2 * np.einsum("abij,abij,ij->ab", abs2["total"], k2, flip)
    return out


def gamma_modes(phonon) -> tuple[np.ndarray, np.ndarray, list[int]]:
    """Real Gamma modes: frequencies (cm-1, ascending; imaginary < 0), mass-weighted eigenvectors (3N x 3N columns) and the three
    acoustic modes (largest overlap with a uniform translation)."""
    phonon.dynamical_matrix.run([0.0, 0.0, 0.0])
    w, e = np.linalg.eigh(np.real(phonon.dynamical_matrix.dynamical_matrix))
    freqs = np.sign(w) * np.sqrt(np.abs(w)) * phonon.unit_conversion_factor * cp.THZ_TO_CM1
    masses = np.array(phonon.primitive.masses)
    t = np.zeros((3 * len(masses), 3))
    for a in range(3):
        t[a::3, a] = np.sqrt(masses / masses.sum())
    return freqs, e, sorted(np.argsort(-(np.abs(t.T @ e) ** 2).sum(axis=0))[:3].tolist())


def project_couplings(first, second, masses, e_loc, n2: int) -> tuple[np.ndarray, np.ndarray, float]:
    """dX/dQ (nk, nc) and d2X/dQdQ (n2, n2, nc) from Cartesian derivatives of the displaced atoms (first: n x 3 x nc, second:
    3n x 3n x nc) and their rows of the mass-weighted eigenvectors (e_loc: 3n x nk, the first n2 columns are the Raman modes),
    after removing the net translation (mass-weighted projection). Also returns the removed fraction of |dX/du|^2/m."""
    inv = np.repeat(1.0 / np.sqrt(masses), 3)
    w = np.asarray(first, dtype=float).reshape(len(inv), -1) * inv[:, None]
    h = np.asarray(second, dtype=float) * inv[:, None, None] * inv[None, :, None]
    t = np.zeros((len(inv), 3))
    for a in range(3):
        t[a::3, a] = np.sqrt(masses / masses.sum())
    proj = np.eye(len(inv)) - t @ t.T
    removed = float(((t.T @ w) ** 2).sum() / (w**2).sum()) if (w**2).sum() > 0 else 0.0
    w, h = proj @ w, np.einsum("ij,jkc,kl->ilc", proj, h, proj)
    ec = e_loc[:, :n2]
    return e_loc.T @ w, np.einsum("ia,ijc,jb->abc", ec, h, ec), removed


# --------------------------------------------------------------------------- #
# Phonon dispersion: local displacement spectral matrices on a q mesh
# --------------------------------------------------------------------------- #

INCLUDE_SAME_MODE_RAMAN = False  # True only for basis-independent identities (e.g. a commensurate q mesh vs its supercell's Gamma path)
EXACT_MODE_LIMIT = 1500  # up to this many (q, nu) modes each is its own spectral bin (exact); denser meshes use sigma/20 bins
W_NODES = 7  # Chebyshev-Lobatto nodes in w^2 spanning the spin gaps, for the Raman kernel's dependence on the transition energy


def local_spectral_modes(phonon, positions, cell_atoms, mesh, max_cm1: float, chunk: int = 64) -> tuple[np.ndarray, np.ndarray, np.ndarray, dict]:
    """Modes 0 < w <= max_cm1 of a Gamma-centred q mesh as (w (cm-1), rho (n, 3m, 3m)) on the molecule's m atoms (mass-weighted):
    rho_A = <|Q_A|^2>_0 Re(eps_A eps_A^H), eps_kA = e_k(q nu) exp(i q.R_k) / sqrt(N_q) (positional phases as in
    crystal_phonons.bloch_couplings), so sum_A rho_A delta(w - w_A) = rho_kl(w) = sum_{q nu} hbar/(2 w) e_k e_l^* exp(i q.(R_k - R_l))
    / N_q delta(w - w_q nu); the real part is the +-q pair sum. Gamma uses gamma_modes (its acoustic three dropped), so a 1x1x1
    mesh is the Gamma path's mode set. Imaginary (q, nu) modes are left out and counted. Also returns eps_A (n, 3m) of the used modes."""
    qpts = cp.gamma_centred_mesh(mesh)
    idx = np.ravel([[3 * c, 3 * c + 1, 3 * c + 2] for c in cell_atoms])
    frac = np.repeat(np.asarray(positions, dtype=float) @ np.linalg.inv(np.array(phonon.primitive.cell)), 3, axis=0)
    f0, e0, acoustic = gamma_modes(phonon)
    optical = np.setdiff1d(np.arange(len(f0)), acoustic)
    freqs, eps = [f0[optical]], [e0[idx][:, optical].T.astype(complex)]
    for start in range(1, len(qpts), chunk):
        q = qpts[start : start + chunk]
        phonon.run_qpoints(q, with_eigenvectors=True)
        e = np.asarray(phonon.qpoints.eigenvectors)[:, idx, :] * np.exp(2j * np.pi * q @ frac.T)[:, :, None]
        freqs.append(np.ravel(phonon.qpoints.frequencies) * cp.THZ_TO_CM1)
        eps.append(e.transpose(0, 2, 1).reshape(-1, len(idx)))
    w, eps = np.concatenate(freqs), np.concatenate(eps) / np.sqrt(len(qpts))
    use = (w > 0) & (w <= max_cm1)
    rho = zero_point_q2(w[use])[:, None, None] * np.real(eps[use][:, :, None] * eps[use].conj()[:, None, :])
    stats = {"mesh": [int(n) for n in mesh], "n_q": len(qpts), "n_modes_used": int(use.sum()), "n_imaginary": int((w <= 0).sum()),
             "min_frequency_cm1": round(float(w.min()), 3), "lowest_used_cm1": round(float(w[use].min()), 3) if use.any() else None}
    return w[use], rho, eps[use], stats


def spectral_bins(freqs, rho, width: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Modes summed into bins [k w, (k+1) w) at their tr(rho)-weighted mean frequency (exact for a bin of degenerate modes, so the
    Bose factors carry no O(w / kT) shift); width 0 = every mode its own bin (exact). Also returns each mode's bin."""
    if width <= 0:
        return freqs, rho, np.arange(len(freqs))
    inv = np.unique(np.floor(freqs / width).astype(int), return_inverse=True)[1]
    out = np.zeros((inv.max() + 1,) + rho.shape[1:])
    np.add.at(out, inv, rho)
    weight = np.trace(rho, axis1=1, axis2=2)
    return np.bincount(inv, weights=weight * freqs) / np.bincount(inv, weights=weight), out, inv


def quasi_elastic_kernel(fb, w: float, t_k: float, sigma: float) -> np.ndarray:
    """K_ij = D(w - w_i + w_j) n(w_i') (n(w_j') + 1): absorb a phonon of bin i, emit one of bin j, the spin gains w; Bose factors at
    the energy-conserving w_i' = (w_i + w_j + w)/2 and w_j' = w_i' - w (the Gamma path's rule, so detailed balance is exact)."""
    wi, wj = fb[:, None], fb[None, :]
    a, e = (wi + wj + w) / 2, (wi + wj - w) / 2
    ok = (a > 0) & (e > 0)
    gauss = np.exp(-0.5 * ((w - wi + wj) / sigma) ** 2) / (np.sqrt(2 * np.pi) * sigma)
    return np.where(ok, gauss * bose(np.where(ok, a, 1.0), t_k) * (bose(np.where(ok, e, 1.0), t_k) + 1), 0.0)


def raman_spectral_kernel(fb, rho, rho_h, h, w: float, t_k: float, sigma: float) -> np.ndarray:
    """G_i,cd(w) = sum_j K_ij(w) tr(rho_i h_c rho_j h_d), symmetrised in (c, d), per absorbing bin i (rho_h = rho_i h_c, (n, C, 3m, 3m))."""
    z = (quasi_elastic_kernel(fb, w, t_k, sigma) @ rho.reshape(len(fb), -1)).reshape(rho.shape)
    zh = np.matmul(z[:, None], h[None]).transpose(0, 1, 3, 2).reshape(len(fb), len(h), -1)
    g = rho_h.reshape(len(fb), len(h), -1) @ zh.transpose(0, 2, 1)
    return (g + g.transpose(0, 2, 1)) / 2


def lagrange_weights(nodes, x) -> np.ndarray:
    """(len(nodes),) + x.shape Lagrange basis polynomials of the nodes evaluated at x."""
    x = np.asarray(x, dtype=float)
    out = np.ones((len(nodes),) + x.shape)
    for k, xk in enumerate(nodes):
        for j, xj in enumerate(nodes):
            if j != k:
                out[k] *= (x - xj) / (xk - xj)
    return out


def qmesh_relaxation(phonon, positions, cell_atoms, g1, h2, keys, statics, spin_i, field_tesla, directions, dir_weights, temps, sigma,
                     cutoff, mesh, span=None, masses=None) -> dict[str, Any]:
    """Powder (or single-direction) rates and T1 per case from the local spectral matrices of one q mesh.

    g1 (3m, C) and h2 (C, 3m, 3m) are the mass-weighted, translation-free first and second derivatives of the C stacked tensor
    components (keys: [('g', 9), ('A', 9)] in that order) on the molecule's atoms. With M_cd[b, a] = Re(O_c[b, a] O_d[b, a]^*):
        direct  W_ba = 4 pi^2 c sum_cd M_cd J_cd(|w_ba|) [n(|w_ba|) + (w_ba < 0)],  J_cd(w) = sum_A D(w - w_A) g_c.rho_A.g_d
        Raman   W_ba = 4 pi^2 c sum_cd M_cd G_cd(w_ba),  G_cd(w) = sum_ij K_ij(w) tr(rho_i h_c rho_j h_d)   (quasi-elastic only)
    which on a 1x1x1 mesh is term by term the Gamma path (its (+-) and (-+) sign pairs are the two orderings of a mode pair).
    G(-w) = exp(w/kT) G(w), so exp(w/2kT) G(w) is even in w: it is computed at W_NODES Chebyshev-Lobatto nodes in w^2 over the
    spin gaps and interpolated (detailed balance stays exact). Absorbing and emitting the same (q, nu) is excluded like the Gamma
    path's a = b: sum_A K_AA(w) v_Ac v_Ad, v_Ac = <Q_A^2>_0 eps_A^H h_c eps_A, is subtracted (a 1/N_q share on dense meshes).
    span (3m, r, orthonormal, mass-weighted) = the subspace the derivatives live in (projected_mode_space): each used mode's coverage
    |span^T P eps_A|^2 / |P eps_A|^2 (P removes the molecule's net translation), weighted by |P eps_A|^2 per 10 cm-1 window."""
    freqs, rho, eps, stats = local_spectral_modes(phonon, positions, cell_atoms, mesh, cutoff)
    exact = len(freqs) <= EXACT_MODE_LIMIT
    fb, rb, bin_of = spectral_bins(freqs, rho, 0.0 if exact else sigma / 20)
    stats["spectral_bins"] = "exact modes" if exact else f"{len(fb)} bins of {sigma / 20:g} cm-1"
    v_same = None if INCLUDE_SAME_MODE_RAMAN else (eps.conj()[None] * np.matmul(eps, h2)).sum(axis=2).real.T * zero_point_q2(freqs)[:, None]
    if span is not None:
        t = translations(masses)
        free = eps - (eps @ t) @ t.T
        weight = (np.abs(free) ** 2).sum(axis=1)
        inside = (np.abs(free @ span) ** 2).sum(axis=1)
        win = np.floor(freqs / 10.0).astype(int)
        stats["coverage_by_frequency"] = [
            {"cm1": [10 * int(b), 10 * int(b) + 10], "n_modes": int((win == b).sum()),
             "coverage": round(float(inside[win == b].sum() / max(weight[win == b].sum(), 1e-300)), 4)} for b in np.unique(win)]
    rho_h = np.matmul(rb[:, None], h2[None])  # rho_i h_c
    m1 = np.einsum("kc,ikl,ld->icd", g1, rb, g1)  # direct: g_c . rho_i . g_d per bin
    systems = [spin_system(statics["g"], statics.get("A"), spin_i, field_tesla, d) for d in directions]
    w_max = max(float(np.ptp(s["energies"])) for s in systems)
    nodes = (w_max**2 / 2) * (1 - np.cos(np.pi * np.arange(W_NODES) / (W_NODES - 1)))
    blocks, start = {}, 0
    for key, n in keys:
        blocks[key], start = slice(start, start + n), start + n
    masks = {"total": slice(None), "direct": slice(None), "raman": slice(None), **{f"{k}_only": s for k, s in blocks.items()}}
    pre = 4 * np.pi**2 * cp.C_CM_PER_S
    rate = {c: np.zeros(len(temps)) for c in CASES}
    slow, balance = np.zeros(len(temps)), 0.0
    by_bin = np.zeros((len(temps), len(fb)))
    for k, t in enumerate(temps):
        g_hat = np.array([np.exp(HC_OVER_K_CM_K * np.sqrt(x) / (2 * t)) * raman_spectral_kernel(fb, rb, rho_h, h2, np.sqrt(x), t, sigma)
                          for x in nodes])  # (nodes, bins, C, C)
        if v_same is not None:
            for k_node, x in enumerate(nodes):
                wn = np.sqrt(x)  # K_AA(w): quasi_elastic_kernel at w_i = w_j = w_A
                ok = freqs > wn / 2
                kaa = np.where(ok, np.exp(-0.5 * (wn / sigma) ** 2) / (np.sqrt(2 * np.pi) * sigma) * bose(np.where(ok, freqs + wn / 2, 1.0), t)
                               * (bose(np.where(ok, freqs - wn / 2, 1.0), t) + 1), 0.0)
                same = np.zeros(g_hat.shape[1:])
                np.add.at(same, bin_of, kaa[:, None, None] * v_same[:, :, None] * v_same[:, None, :])
                g_hat[k_node] -= np.exp(HC_OVER_K_CM_K * np.sqrt(x) / (2 * t)) * same
        g_nodes = g_hat.sum(axis=1)
        for system, wd in zip(systems, dir_weights):
            e = system["energies"]
            w = e[:, None] - e[None, :]
            o = np.concatenate([system[key] for key, _ in keys])
            m = np.real(o[:, None] * o[None, :].conj())  # (C, C, L, L)
            lag = lagrange_weights(nodes, w**2) * np.exp(-HC_OVER_K_CM_K * w / (2 * t))[None]
            gap = np.abs(w) > 1e-9
            occ1 = np.where(gap, bose(np.where(gap, np.abs(w), 1.0), t) + (w < 0), 0.0)
            dgauss = np.exp(-0.5 * ((np.abs(w)[..., None] - fb) / sigma) ** 2) / (np.sqrt(2 * np.pi) * sigma)  # (L, L, bins)
            jw = np.einsum("bai,icd->cdba", dgauss, m1)
            cases = {}
            for c, s in masks.items():
                direct = pre * np.einsum("cdba,cdba->ba", m[s, s], jw[s, s]) * occ1
                raman = pre * np.einsum("kba,kcd,cdba->ba", lag, g_nodes[:, s, s], m[s, s])
                cases[c] = {"direct": direct, "raman": raman}.get(c, direct + raman)
            for c, wm in cases.items():
                row = t1_from_rates(wm, system, t)
                rate[c][k] += wd / row["T1_s"]
                if c == "total":
                    slow[k] += wd / row["slowest_s"]
                balance = max(balance, row["detailed_balance_error"])
            p, mz = equilibrium(e, t), np.real(np.diag(system["s_n"]))
            flip = p[None, :] * (mz[:, None] - mz[None, :]) ** 2  # rates that move M (electron-spin flips)
            by_bin[k] += wd * pre * np.einsum("kicd,kcd->i", g_hat, np.einsum("kba,ba,cdba->kcd", lag, flip, m))
    return {"rate": rate, "slow": slow, "balance": balance, "gaps": w_max, "stats": stats, "bins": fb, "raman_by_bin": by_bin}


def _finite(x):
    return float(x) if math.isfinite(x) else None


def compute_spin_relaxation_time(
    displacement_manifest: Annotated[str, "The displacement manifest of the sweep (random or cartesian): reference cluster, atoms -> cell atoms."],
    phonon_dir: Annotated[str, "Crystal phonon directory (phonopy_params.yaml; primitive = the unit cell the cluster was carved from). '' = the manifest's (unless gamma_modes_json is given)."],
    g_derivatives_json: Annotated[str, "fit_spin_hamiltonian_derivatives output for observable 'g' (also gives the static g). '' with g_mode_derivatives_json."] = "",
    a_derivatives_json: Annotated[str, "fit_spin_hamiltonian_derivatives output for 'hfc:<metal>' (A in MHz). '' = no hyperfine levels/couplings."] = "",
    nucleus: Annotated[str, "Metal nucleus: '51V' (I=7/2), '63Cu'/'65Cu' (3/2), '59Co' (7/2), '55Mn' (5/2), a spin value like '1.5', or '0' (none)."] = "51V",
    field_tesla: Annotated[float, "Magnetic field (T): 0.35 X band, 1.2 Q band."] = 0.35,
    field_direction: Annotated[str, "'powder' (1/T1 averaged over the Lebedev-14 grid) or a vector 'x y z' in the cluster/cell Cartesian frame."] = "powder",
    temperatures_k: Annotated[str, "Temperatures (K)."] = "5 10 20 50 100 200 300",
    broadening_cm1: Annotated[float, "Gaussian standard deviation sigma (cm-1) of the energy-conserving delta functions (Lunghi 2022 used ~10 with Gamma phonons; Lunghi 2019's exp(-x^2/s^2) width s is sigma = s/sqrt(2))."] = 10.0,
    mode_cutoff_cm1: Annotated[float, "Raman (second-order) couplings only for modes up to this frequency (the S=1/2 Raman rate lives below ~50-100 cm-1)."] = 150.0,
    compound: Annotated[str, "Compound label for the calibration record."] = "",
    metal: Annotated[str, "Metal label for the calibration record, e.g. 'V'."] = "",
    gamma_modes_json: Annotated[str, "Alternative to phonon_dir (pass exactly one): low_mode_hessian.json of collect_low_mode_dft_hessian (Rayleigh-Ritz Gamma modes in an MLIP trial subspace). The Raman/direct sums are then TRUNCATED to that subspace: modes outside it are absent; residual-flagged modes are reported."] = "",
    q_mesh: Annotated[str, "Phonon dispersion instead of Gamma only: Gamma-centred q mesh 'n1 n2 n3', or 'coarse; ...; dense' (last = production, the others = convergence), on a phonon_dir with SUPERCELL force constants (DFT supercell, or build_mixed_force_constants with a fine-tuned UMA). '' = Gamma modes only."] = "",
    g_mode_derivatives_json: Annotated[str, "Instead of g_derivatives_json: fit_spin_hamiltonian_mode_derivatives output for 'g' (whole molecule, soft Gamma modes; the default for the Raman metric). Couplings are used directly on those modes; modes outside the set contribute nothing."] = "",
    a_mode_derivatives_json: Annotated[str, "Instead of a_derivatives_json: fit_spin_hamiltonian_mode_derivatives output for 'hfc:<metal>' from the same sweep."] = "",
    runtime: ToolRuntime = None,
) -> Dict[str, Any]:
    """S = 1/2 spin-lattice T1(T) from g and A spin-phonon couplings on the crystal's Gamma phonons: one-phonon (direct) and
    two-phonon Raman (second derivatives) rates between all electron-nuclear levels, population dynamics after a pi pulse;
    total, direct-only, Raman-only, g-only and A-only T1 and the dominant modes / mode pairs. For S = 1/2 at >= 77 K the Raman T1
    is the metric (the one-phonon q-mesh rate is not). With q_mesh the phonons of the whole mesh enter through the molecule's local
    displacement spectral matrices (qmesh_relaxation; '1 1 1' = the Gamma path), with mesh convergence and the Raman share per
    absorbed-phonon frequency. g/a_mode_derivatives_json (fit_spin_hamiltonian_mode_derivatives) give the couplings directly on the
    exported soft Gamma modes (same rate formulas as the Gamma path; modes outside the set are absent)."""
    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())
        warnings, low_mode = [], None
        meshes = [[int(v) for v in m.split()] for m in q_mesh.split(";") if m.strip()]
        if any(len(m) != 3 or min(m) < 1 for m in meshes):
            raise ValueError("q_mesh must be 'n1 n2 n3' or ';'-separated meshes (coarse to dense).")
        mode_space = bool(g_mode_derivatives_json.strip() or a_mode_derivatives_json.strip())
        if mode_space and (g_derivatives_json.strip() or a_derivatives_json.strip()):
            raise ValueError("Pass the Cartesian derivative files OR the mode-space ones (g/a_mode_derivatives_json), not both.")
        if mode_space and meshes:
            raise ValueError("q_mesh needs Cartesian derivatives: mode-space couplings live on the Gamma modes of their set.")
        gamma_json = gamma_modes_json.strip() or ("" if phonon_dir.strip() else man.get("gamma_modes_json") or "")
        if gamma_json and meshes:
            raise ValueError("q_mesh needs force constants (phonon_dir), not Rayleigh-Ritz Gamma modes.")
        gs = load_gamma_set(root, phonon_dir.strip() or ("" if gamma_json else man.get("phonon_dir") or ""), gamma_json)
        freqs, vecs, acoustic, masses, suspect, phonon = gs.freqs, gs.vecs, gs.acoustic, gs.masses, gs.suspect, gs.phonon
        ph_dir, gpath, low_mode = gs.ph_dir, gs.path, gs.low_mode
        bad = [" ".join(map(str, m)) for m in meshes if cp.fc_supercell_support(phonon, m)["unsupported_axes"]]
        if bad:
            raise ValueError(f"Force-constant supercell periods {cp.fc_supercell_support(phonon, [1, 1, 1])['fc_supercell_periods']} cannot "
                             f"support q meshes {bad} (1-cell axes hold lattice sums): use '1 1 1', a DFT supercell, or "
                             "build_mixed_force_constants (DFT 1x1x1 Gamma + fine-tuned UMA supercell dispersion).")
        temps = [float(t) for t in temperatures_k.split()]
        sigma, cutoff = float(broadening_cm1), float(mode_cutoff_cm1)
        if field_tesla <= 0 or sigma <= 0 or not temps or min(temps) <= 0:
            raise ValueError("field_tesla, broadening_cm1 and every temperature must be > 0.")
        imaginary = [i for i in range(len(freqs)) if i not in acoustic and (freqs[i] <= 0 or i in suspect)]
        kept = [int(i) for i in np.argsort(freqs) if i not in acoustic and freqs[i] > 0 and i not in suspect]
        ders = {}
        for key, path, unit in (("g", g_mode_derivatives_json if mode_space else g_derivatives_json, "dimensionless"),
                                ("A", a_mode_derivatives_json if mode_space else a_derivatives_json, "MHz")):
            if path.strip():
                dpath = _h._resolve_path(root, path, must_exist=True, dir_ok=False)
                ders[key] = (dpath, json.loads(dpath.read_text()))
                if ders[key][1].get("unit") != unit:
                    raise ValueError(f"{dpath.name}: unit {ders[key][1].get('unit')!r}, expected {unit!r} for the {key} derivatives.")
                if (ders[key][1].get("kind") == MODE_FIT_KIND) != mode_space:
                    raise ValueError(f"{dpath.name} ({ders[key][1].get('kind')}) passed as {'mode-space' if mode_space else 'Cartesian'} derivatives.")
        if "g" not in ders:
            raise ValueError("g_derivatives_json (or g_mode_derivatives_json) is required (it also sets the Zeeman levels).")
        mode_set = None
        if mode_space:  # the couplings exist only on the exported modes: every other mode is absent from the sums
            sets = {(tuple(d["modes"]["indices"]), d["modes"]["phonon_set_sha256"]) for _p, d in ders.values()}
            if len(sets) != 1:
                raise ValueError("The g and A mode-space derivatives come from different mode sets: fit both on the same sweep.")
            listed = dict(zip(ders["g"][1]["modes"]["indices"], ders["g"][1]["modes"]["frequencies_cm1"]))
            if ders["g"][1]["modes"]["phonon_set_sha256"] != gs.sha256:
                raise ValueError(f"The phonon set {_h._rel(root, gpath)} is not the one the mode-space sweep was exported from (sha256 differs).")
            missing = [i for i in kept if i not in listed and freqs[i] <= cutoff]
            mode_set = {"n_modes": len(listed), "max_cm1": round(max(listed.values()), 2), "phonon_set_sha256": gs.sha256,
                        "n_missing_below_cutoff": len(missing), "n_absent_above": int(sum(i not in listed and freqs[i] > cutoff for i in kept)),
                        "max_frequency_drift_cm1": round(max(abs(float(freqs[i]) - f) for i, f in listed.items()), 6)}
            if missing:
                warnings.append(f"Modes {[round(float(freqs[i]), 1) for i in missing]} cm-1 lie below the {cutoff:g} cm-1 cutoff but outside the "
                                f"mode-space set (exported up to {mode_set['max_cm1']} cm-1): they contribute nothing; re-export with a higher "
                                "mode_cutoff_cm1 or lower this cutoff.")
            kept = [i for i in kept if i in listed]
        n2 = sum(freqs[i] <= cutoff for i in kept)
        cluster = read(str(root / man["reference_cluster"]))
        d1, d2, info, statics, cart, span = {}, {}, {}, {}, {}, None
        for key, (dpath, der) in ders.items():
            if mode_space:
                pos_of = {int(i): k for k, i in enumerate(der["modes"]["indices"])}
                sel = [pos_of[i] for i in kept]
                d1[key] = np.array(der["first_derivatives"], dtype=float)[sel]
                d2[key] = np.array(der["second_derivatives"], dtype=float)[np.ix_(sel[:n2], sel[:n2])]
                info[key] = {"file": _h._rel(root, dpath), "kind": der.get("kind"), "verdict": der.get("verdict"), "n_atoms": len(der["atoms"]),
                             "n_modes": len(sel), "held_out_r2": (der.get("fit") or {}).get("r2_overall")}
            else:
                cell_atoms = [int(a["cell_atom"]) for a in der["atoms"]]
                pos, dev = cp.molecule_positions_in_phonon_cell(phonon, cluster.positions[[int(a["cluster_atom"]) for a in der["atoms"]]], cell_atoms)
                rows = np.ravel([[3 * c, 3 * c + 1, 3 * c + 2] for c in cell_atoms])
                d1[key], d2[key], removed = project_couplings(der["first_derivatives"], der["second_derivatives"], masses[cell_atoms], vecs[rows][:, kept], n2)
                if meshes:  # the same translation-free, mass-weighted couplings in Cartesian form
                    cart[key] = (cell_atoms, pos, *project_couplings(der["first_derivatives"], der["second_derivatives"], masses[cell_atoms],
                                                                     np.eye(len(rows)), len(rows))[:2])
                info[key] = {"file": _h._rel(root, dpath), "kind": der.get("kind"), "verdict": der.get("verdict"), "n_atoms": len(cell_atoms),
                             "mapping_max_deviation_angstrom": round(dev, 5), "translational_fraction_removed": round(removed, 5),
                             "held_out_r2": (der.get("fit") or {}).get("r2_overall")}
                if der.get("kind") == PROJECTED_KIND:
                    info[key]["span_dimension"] = der["span"]["dimension"]
                    span = np.array(der["span_basis_mass_weighted"], dtype=float)
                    if key == "g":
                        warnings.append(f"Couplings projected from {der['span']['n_modes']} mode-space derivatives (span {der['span']['dimension']}): zero "
                                        "along every displacement outside that span; read q_mesh.coverage_by_frequency (a low-coverage window's "
                                        "rate is a lower bound).")
            statics[key] = np.array(der["reference"], dtype=float)
            if der.get("diagonal_only"):
                warnings.append(f"{key}: diagonal_only second derivatives (+/-step sweep): Raman couplings miss every Cartesian cross term; "
                                "use export_random_cluster_displacements + fit_spin_hamiltonian_derivatives for the metric.")
            elif der.get("verdict") != "use":
                warnings.append(f"{key}: derivative fit verdict {der.get('verdict')!r} (held-out R^2 {info[key]['held_out_r2']}).")
        spin_i = NUCLEAR_SPINS[nucleus.strip()] if nucleus.strip() in NUCLEAR_SPINS else float(nucleus)
        if "A" not in d1 and spin_i:
            warnings.append(f"No A derivatives: hyperfine levels and A couplings omitted (nucleus {nucleus} ignored, I = 0).")
            spin_i = 0.0
        if imaginary:
            warnings.append(f"{len(imaginary)} imaginary Gamma modes excluded {[round(float(freqs[i]), 1) for i in imaginary]} cm-1: "
                            "their couplings are missing; relax the structure further.")
        if low_mode is not None:
            warnings.append(f"Gamma modes from a {low_mode.get('subspace_size')}-vector Rayleigh-Ritz subspace ({gamma_modes_json}): the Raman and direct "
                            "sums are truncated to it -- modes outside the subspace are absent, so T1 is an upper bound if any are missing.")
            flagged = [i for i in low_mode.get("flagged_modes", []) if 0 < freqs[i] <= cutoff]
            if flagged:
                warnings.append(f"Ritz modes {flagged} ({[round(float(freqs[i]), 1) for i in flagged]} cm-1) have relative residual > "
                                f"{low_mode.get('relative_residual_threshold')}: uncertain frequencies/shapes; report them with the T1.")
            if suspect:
                warnings.append(f"Ritz modes {sorted(suspect)} ({[round(float(freqs[i]), 1) for i in sorted(suspect)]} cm-1) are estimated to be "
                                "imaginary (frequency - estimated error <= 0): dropped with the imaginary modes.")
            loose = [i for i in low_mode.get("unconverged_modes", []) if 0 < freqs[i] <= cutoff and i not in suspect]
            if loose:
                est = low_mode["estimated_frequency_error_cm1"]
                warnings.append(f"Ritz modes {loose} are unconverged (MLIP-preconditioned error estimates {[round(est[i], 1) for i in loose]} cm-1 > "
                                f"{low_mode.get('frequency_tolerance_cm1')}): on VO(acac)2 a first round left the Raman T1 off by up to +227%, merged "
                                "with one Davidson round (run_low_mode_dft_hessian_round) within 1.4%. Run that round before quoting T1.")
            if len(freqs) and freqs.max() <= cutoff:
                warnings.append(f"Every Ritz mode lies below the {cutoff:g} cm-1 cutoff: exact modes up to the cutoff are likely missing.")
        noise = (cc._read_json(ph_dir / cp.PHONON_SUMMARY).get("numerical_noise") or {}) if ph_dir is not None else {}
        if noise.get("verdict") not in {None, "clean"}:
            warnings.append(f"Phonons numerically {noise['verdict']} (raw acoustic {noise.get('raw_acoustic_frequencies_cm1')} cm-1): "
                            "the soft modes that carry the Raman rate are uncertain.")
        if field_direction.strip().lower() == "powder":
            directions, dir_weights = lebedev14()
        else:
            directions, dir_weights = np.array([[float(v) for v in field_direction.replace(",", " ").split()]]), np.array([1.0])
            if directions.shape != (1, 3) or not np.linalg.norm(directions):
                raise ValueError("field_direction must be 'powder' or three numbers 'x y z'.")
        f1, f2 = freqs[kept], freqs[kept[:n2]]
        rate = {c: np.zeros(len(temps)) for c in CASES}
        slow, balance, gaps = np.zeros(len(temps)), 0.0, 0.0
        by_mode, by_pair = np.zeros(len(kept)), np.zeros((n2, n2))
        if meshes:
            if len({tuple(v[0]) for v in cart.values()}) != 1:
                raise ValueError("q_mesh needs the g and A derivatives on the same displaced atoms.")
            keys = [(k, 9) for k in ("g", "A") if k in cart]
            g1 = np.hstack([cart[k][2] for k, _ in keys])
            h2 = np.concatenate([np.moveaxis(cart[k][3], 2, 0) for k, _ in keys])
            runs = [qmesh_relaxation(phonon, cart["g"][1], cart["g"][0], g1, h2, keys, statics, spin_i, float(field_tesla), directions,
                                     dir_weights, temps, sigma, cutoff, m, span=span, masses=masses[cart["g"][0]]) for m in meshes]
            rate, slow, gaps, balance = runs[-1]["rate"], runs[-1]["slow"], runs[-1]["gaps"], max(r["balance"] for r in runs)
        else:
            for direction, wd in zip(directions, dir_weights):
                res = relaxation_vs_temperature(direction, float(field_tesla), statics["g"], statics.get("A"), spin_i, d1, d2, f1, f2, temps, sigma, temps[-1])
                gaps = max(gaps, float(np.ptp(res["energies"])))
                for k, row in enumerate(res["rows"]):
                    for c in CASES:
                        rate[c][k] += wd / row[c]["T1_s"] if c in row else np.nan
                    slow[k] += wd / row["total"]["slowest_s"]
                    balance = max(balance, *(row[c]["detailed_balance_error"] for c in CASES if c in row))
                by_mode += wd * res["direct_by_mode"]
                by_pair += wd * res["raman_by_pair"]
        t1 = {c: [_finite(1.0 / r) if r > 0 else None for r in rate[c]] for c in CASES}
        if meshes:
            stats, lowest = runs[-1]["stats"], runs[-1]["stats"]["lowest_used_cm1"] or 0.0
            low = [w["cm1"] for w in stats.get("coverage_by_frequency", []) if w["coverage"] < 0.7]
            if low:
                warnings.append(f"Phonon windows {low} cm-1 lie < 70% inside the span of the mode-space derivatives: their couplings are "
                                "truncated, so their Raman share is a lower bound.")
            direct_resolved = bool(gaps >= lowest + sigma)  # analyze_spin_phonon_q_mesh's rule
            if not direct_resolved:
                warnings.append(f"Direct process unresolved on the {'x'.join(map(str, meshes[-1]))} mesh: the spin gaps (<= {gaps:.3g} cm-1) lie below "
                                f"the lowest sampled mode ({lowest:.2f} cm-1) + sigma, so the one-phonon rate is a Gaussian tail (its continuum limit: "
                                "analyze_spin_phonon_q_mesh acoustic_continuum). The metric is the Raman-only T1.")
            if min(temps) < lowest * HC_OVER_K_CM_K / 2:
                warnings.append(f"Below ~{lowest * HC_OVER_K_CM_K / 2:.0f} K the Raman rate is thermal activation over the lowest sampled mode "
                                f"({lowest:.2f} cm-1): densify the mesh before quoting T1 there.")
            provenance = cc._read_json(ph_dir / cp.FC_PROVENANCE)
            if str(provenance.get("force_constants_source", "")).startswith(cp.MIXED_FC_SOURCE):
                warnings.append(f"Mixed force constants: Gamma is DFT, the dispersion is the MLIP's ({provenance.get('mlip_source')}); read the "
                                f"MLIP-vs-DFT Gamma check and warnings in {cp.FC_PROVENANCE}.")
            if stats["n_imaginary"]:
                warnings.append(f"{stats['n_imaginary']} imaginary (q, nu) modes (down to {stats['min_frequency_cm1']} cm-1) on the production mesh are left "
                                "out: their phonons are missing from the rates.")
            order = np.argsort(runs[-1]["bins"])
            fb, windows = runs[-1]["bins"][order], np.floor(runs[-1]["bins"][order] / 10.0).astype(int)
            shares = {}
            for k, t in enumerate(temps):
                part = runs[-1]["raman_by_bin"][k][order] / max(runs[-1]["raman_by_bin"][k].sum(), 1e-300)
                shares[f"{t:g}K"] = {"median_absorbed_phonon_cm1": round(float(fb[np.searchsorted(np.cumsum(part), 0.5)]), 2),
                                     "windows": [{"cm1": [10 * w, 10 * w + 10], "fraction": round(float(s), 4)}
                                                 for w, s in enumerate(np.bincount(windows, weights=part)) if s >= 0.005]}
            per_mesh = [{**r["stats"], "T1_raman_s": [_finite(1.0 / x) if x > 0 else None for x in r["rate"]["raman"]],
                         "T1_s": [_finite(1.0 / x) if x > 0 else None for x in r["rate"]["total"]]} for r in runs]
            soft = max(sum(w["fraction"] for w in s["windows"] if w["cm1"][1] <= 10) for s in shares.values())
            if soft > 0.25:
                warnings.append(f"Modes below 10 cm-1 carry up to {soft:.0%} of the Raman rate: near-zero modes of soft or zero-crossing (imaginary "
                                "nearby) branches can dominate artificially -- check that the acoustic branches are real and linear before quoting T1.")
            if len(runs) > 1:
                last = [(a, b) for a, b in zip(per_mesh[-2]["T1_raman_s"], per_mesh[-1]["T1_raman_s"]) if a and b]
                if last and max(abs(b - a) / b for a, b in last) > 0.1:
                    warnings.append(f"Raman T1 still changes by up to {max(abs(b - a) / b for a, b in last):.0%} between the last two meshes: not converged.")
            qmesh = {
                "force_constants_source": provenance.get("force_constants_source") or "phonopy force constants",
                "fc_supercell_periods": cp.fc_supercell_support(phonon, meshes[-1])["fc_supercell_periods"],
                "meshes": per_mesh,
                "convergence_raman_last_two": {f"{t:g}K": round(abs(b - a) / b, 4) if a and b else None
                                               for t, a, b in zip(temps, per_mesh[-2]["T1_raman_s"], per_mesh[-1]["T1_raman_s"])} if len(runs) > 1 else None,
                "raman_by_absorbed_phonon_frequency": shares,
            }
        else:
            direct_resolved = bool(kept) and bool(freqs[kept[0]] - gaps <= 2 * sigma)
            if not direct_resolved:
                warnings.append(f"Direct process unresolved: the spin gaps (<= {gaps:.3g} cm-1) lie > 2 sigma below the lowest optical Gamma mode "
                                f"({freqs[kept[0]]:.1f} cm-1), so the one-phonon rate is a Gaussian tail; it needs acoustic phonons (q mesh). "
                                "The metric is the Raman-only T1.")
            t_floor = float(freqs[kept[0]]) * HC_OVER_K_CM_K / 2 if kept else 0.0  # kT = w_min / 2
            if min(temps) < t_floor:
                warnings.append(f"Below ~{t_floor:.0f} K the Gamma-only Raman rate is thermal activation over the lowest optical mode "
                                f"({freqs[kept[0]]:.1f} cm-1); acoustic phonons are missing, so T1 there is an upper bound.")
        metric = "total" if direct_resolved else "raman"
        flips = by_mode.sum() + by_pair.sum()
        pairs = sorted(((by_pair[a, b] + (by_pair[b, a] if a != b else 0.0), a, b) for a in range(n2) for b in range(a, n2)), reverse=True)
        tag = f"{_h._safe_path_part(compound, 'run')}_{float(field_tesla):g}T" + ("_lowmode" if low_mode is not None else "") \
            + (f"_q{'x'.join(map(str, meshes[-1]))}" if meshes else "") + ("_modespace" if mode_space else "")
        out_dir = ders["g"][0].parent
        result = {
            "compound": compound, "metal": metal, "nucleus": nucleus, "nuclear_spin": spin_i, "field_tesla": float(field_tesla),
            "field_direction": field_direction, "n_field_directions": len(directions), "broadening_cm1": sigma, "mode_cutoff_cm1": cutoff,
            "phonon_dir": _h._rel(root, ph_dir) if ph_dir is not None else None, "derivatives": info,
            "gamma_modes_json": _h._rel(root, gpath) if low_mode is not None else None,
            "modes": {"source": f"q mesh {'x'.join(map(str, meshes[-1]))}: local displacement spectral matrices (direct + quasi-elastic Raman)"
                      if meshes else f"Rayleigh-Ritz subspace of {low_mode.get('subspace_size')} vectors (truncated)" if low_mode is not None
                      else "complete phonopy Gamma modes",
                      **({"mode_space": {**mode_set, "rule": "fitted dX/dQ, d2X/dQdQ on the exported modes; every other mode is absent"}} if mode_set else {}), "n_gamma": len(freqs), "n_acoustic_dropped": len(acoustic), "n_imaginary_dropped": len(imaginary),
                      "imaginary_cm1": [round(float(freqs[i]), 2) for i in imaginary], "n_direct": len(kept), "n_raman": int(n2),
                      "lowest_used_cm1": round(float(freqs[kept[0]]), 2) if kept else None,
                      **({"q_mesh": runs[-1]["stats"]} if meshes else {})},
            **({"q_mesh": qmesh} if meshes else {}),
            "max_spin_gap_cm1": gaps, "direct_resolved": direct_resolved, "metric": metric,
            "results": [{"T_K": t, "T1_s": t1["total"][k], "T1_direct_s": t1["direct"][k], "T1_raman_s": t1["raman"][k],
                         "T1_g_only_s": t1["g_only"][k], "T1_A_only_s": t1["A_only"][k],
                         "T1_slowest_eigen_s": _finite(1.0 / slow[k]) if slow[k] > 0 else None,
                         "metric_T1_s": t1[metric][k]} for k, t in enumerate(temps)],
            "detailed_balance_max_relative_error": balance,
            f"top_direct_modes_{temps[-1]:g}K": [{"mode": kept[a], "frequency_cm1": round(float(f1[a]), 2), "fraction": round(float(by_mode[a] / flips), 4)}
                                                 for a in np.argsort(-by_mode)[:8]] if flips > 0 else [],
            f"top_raman_mode_pairs_{temps[-1]:g}K": [{"modes": [kept[a], kept[b]], "frequencies_cm1": [round(float(f2[a]), 2), round(float(f2[b]), 2)],
                                                      "fraction": round(float(v / flips), 4)} for v, a, b in pairs[:10]] if flips > 0 else [],
            "warnings": warnings,
            "calibration_record": {"compound": compound, "metal": metal, "T_K": temps, "T1_s": t1[metric], "process": metric},
            "conventions": {
                "hamiltonian": "H = mu_B B.g.S + S.A.I (cm-1; A from MHz), S = 1/2, no nuclear Zeeman",
                "direct": "W_ba = 4 pi^2 c sum_a |<b|dH/dQ_a|a>|^2 <Q_a^2>_0 D(|w_ba| - w_a) [n(|w_ba|) + (w_ba < 0)]",
                "raman": "W_ba = 4 pi^2 c sum_cd Re(O_c O_d^*)_ba sum_ij tr(rho_i h_c rho_j h_d) D(w_ba - w_i + w_j) n(w_i') (n(w_j') + 1): "
                         "quasi-elastic (absorb one, emit one) over the mesh's local spectral matrices rho; two-phonon absorption/emission "
                         "needs phonons below w_ba ~ 0.3 cm-1 and is dropped" if meshes else
                         "W_ba = 2 pi^2 c sum_ab |<b|d2H/dQ_a dQ_b|a>|^2 <Q_a^2>_0 <Q_b^2>_0 sum_s D(w_ba - s_a w_a - s_b w_b) f f "
                         "(second-order couplings only; Bose factors at energy-conserving frequencies)",
                "T1": "int (M(t) - M_eq)/(M(0) - M_eq) dt, M = <S.n>, pi pulse on the electron spin",
                "powder": "1/T1 averaged over the Lebedev-14 grid" if len(directions) > 1 else "single field direction",
                "fractions": f"spin-flip-weighted rate shares at {temps[-1]:g} K (sum_ab p_a (m_b - m_a)^2 W_ba)",
            },
        }
        (out_dir / f"spin_relaxation_{tag}.json").write_text(json.dumps(result, indent=1))
        cols = ["T_K", "T1_s", "T1_direct_s", "T1_raman_s", "T1_g_only_s", "T1_A_only_s", "T1_slowest_eigen_s", "metric_T1_s"]
        (out_dir / f"spin_relaxation_{tag}.csv").write_text(
            ",".join(cols) + "\n" + "\n".join(",".join("" if r[c] is None else f"{r[c]:.6g}" for c in cols) for r in result["results"]) + "\n")
        return {"ok": True, **result, "saved": _h._rel(root, out_dir / f"spin_relaxation_{tag}.json"),
                "csv": _h._rel(root, out_dir / f"spin_relaxation_{tag}.csv")}
    except Exception as exc:
        return _h._error(exc)


spin_relaxation_tool_map = {name: tool(fn) for name, fn in {
    "fit_spin_hamiltonian_derivatives": fit_spin_hamiltonian_derivatives,
    "export_random_mode_displacements": export_random_mode_displacements,
    "fit_spin_hamiltonian_mode_derivatives": fit_spin_hamiltonian_mode_derivatives,
    "mode_derivatives_to_cartesian": mode_derivatives_to_cartesian,
    "compute_spin_relaxation_time": compute_spin_relaxation_time,
}.items()}
