"""
deconv_sim.py -- Harmonised simulation code for
"A new estimation procedure of a noisy blind deconvolution model".

One single implementation is used for the three models M1, M2, M3, so that the
numerical section of the paper can describe ONE algorithm.

Conventions (identical to the paper)
------------------------------------
* Model           : Y_t = (u * X)_t + sigma0 W_t,  W_t complex Gaussian with
                    E|W_t|^2 = 1 (real and imaginary parts i.i.d. N(0, 1/2)),
                    X_t i.i.d. on {a_1, ..., a_p} with masses (pi_1, ..., pi_p).
                    The noise is added AFTER the filter u.
* Inverse filter  : theta * u = delta_0, so that (theta * Y)_t = X_t + sigma0 (theta * W)_t.
* Filtering       : Z_t = (theta * Y)_t = sum_j theta_j Y_{t-j}  (np.convolve, no reversal).
* Window          : theta = (theta_{-k}, ..., theta_{k}) is stored in an array of
                    length 2k+1, array index i <-> paper index j = i - k.
* Canonical form  : ||theta|| = 1 and theta_{-k} >= theta_t for all t
                    (paper, Section 5.4): the dominant coefficient is made
                    positive and moved to the first position.
* Moments         : d_n[j(p+1)+k] = mean( conj(Z)^j Z^k ),  d~ = A(sigma ||theta||) d_n,
                    D~ = Hermitian part of reshape(d~, (p+1, p+1)).
* sigma-hat       : smallest sigma at which lambda_min(D~_n(sigma, theta)) can be made
                    <= 0 by a choice of theta (Definition Def:esti, with lambda_min
                    in place of J_n = det D~_n; both have the same zero set).
* a-hat, pi-hat   : roots of sum_j v_j z^j (v eigenvector of the smallest eigenvalue
                    of D~_n at (sigma-hat, theta-hat)), in lexicographic order; pi-hat
                    solves the Vandermonde system d~_k = sum_l pi_l a_l^k, k = 0..p-1.
"""

from __future__ import annotations

import math
import os
import pickle
import time
import zlib
from dataclasses import dataclass, asdict, field
from typing import Optional, Sequence

import numpy as np
from scipy import optimize, signal


# =============================================================================
# 1. Models
# =============================================================================

@dataclass
class Model:
    """u = u_num / u_den (rational transfer function), theta = u_den / u_num."""
    name: str
    u_num: np.ndarray            # MA part of u
    u_den: np.ndarray            # AR part of u
    theta_full: np.ndarray       # true inverse filter, lags 0, 1, 2, ... (unit norm)
    label: str = ""


def _impulse_response(b, a, length):
    x = np.zeros(length)
    x[0] = 1.0
    return signal.lfilter(b, a, x)


def make_M1() -> Model:
    """Mixture model: u = delta_0, theta = delta_0."""
    return Model("M1", np.array([1.0]), np.array([1.0]), np.array([1.0]),
                 "mixture model")


def make_M2() -> Model:
    """AR(2): theta finite, theta = (6, -2, 3)/7 = (0.8571, -0.2857, 0.4286),
    already of unit norm; u = 1/theta is infinite (roots of 6 - 2z + 3z^2 have
    modulus sqrt(2) > 1, so u is causal)."""
    theta = np.array([6.0, -2.0, 3.0]) / 7.0
    return Model("M2", np.array([1.0]), theta.copy(), theta.copy(),
                 "second order autoregressive model")


def make_M3(u_raw=(1.0, -0.6, 0.08), length=400) -> Model:
    """MA(2): u finite, theta = 1/u infinite.
    With u proportional to (1, -0.6, 0.08) and theta normalised to unit norm,
    theta = (0.8289, 0.4973, 0.2321, 0.0995, 0.0411, 0.0167, ...), i.e. the
    values used in the draft."""
    u_raw = np.asarray(u_raw, dtype=float)
    th_raw = _impulse_response([1.0], u_raw, length)
    c = np.linalg.norm(th_raw)
    return Model("M3", u_raw * c, np.array([1.0]), th_raw / c,
                 "second order moving average model")


MODELS = {"M1": make_M1(), "M2": make_M2(), "M3": make_M3()}

# Distribution of X
SUPPORTS = {
    "base":      np.array([-2 - 1j, -1 + 3j, 4 + 1j]),
    "close":     np.array([-2 - 1j, -1.5 - 1j, 4 + 1j]),     # two close support points
    "separated": 2.0 * np.array([-2 - 1j, -1 + 3j, 4 + 1j]),  # base support scaled by 2
}
WEIGHTS = np.array([0.60, 0.25, 0.15])


def check_inverse(model: Model, length=200) -> float:
    """max |theta * u - delta_0| (should be ~1e-15)."""
    u = _impulse_response(model.u_num, model.u_den, length)
    conv = np.convolve(model.theta_full, u)[:length]
    target = np.zeros(length)
    target[0] = 1.0
    return float(np.max(np.abs(conv - target)))


# =============================================================================
# 2. Volume v_p (Lindsay)
# =============================================================================

def volume(support, weights) -> float:
    """Closed form v_p = (prod pi_l) prod_{j<k} |a_k - a_j|^2."""
    a = np.asarray(support, dtype=complex)
    w = np.asarray(weights, dtype=float)
    vdm = 1.0
    for j in range(len(a)):
        for k in range(j + 1, len(a)):
            vdm *= abs(a[k] - a[j]) ** 2
    return float(np.prod(w) * vdm)


def volume_from_moments(support, weights) -> float:
    """det of the p x p moment matrix M_{p-1}, (M)_{jk} = E[conj(X)^j X^k] (check)."""
    a = np.asarray(support, dtype=complex)
    w = np.asarray(weights, dtype=float)
    p = len(a)
    V = np.vander(a, p, increasing=True)            # (p, p): row l = a_l^k
    M = V.conj().T @ np.diag(w) @ V
    return float(np.real(np.linalg.det(M)))


# =============================================================================
# 3. Data generation
# =============================================================================

def simulate_Y(model: Model, sigma0: float, n: int, rng: np.random.Generator,
               support=SUPPORTS["base"], weights=WEIGHTS, n_burn: int = 500):
    """Y = u * X + sigma0 W (noise added after the filter, as in the paper)."""
    N = n + n_burn
    X = rng.choice(np.asarray(support, dtype=complex), size=N, p=weights)
    S = signal.lfilter(model.u_num, model.u_den, X)[n_burn:]
    W = (rng.standard_normal(n) + 1j * rng.standard_normal(n)) / np.sqrt(2.0)
    return S + sigma0 * W


# =============================================================================
# 4. Contrast: A(sigma ||theta||), D~_n, lambda_min, J_n
# =============================================================================

_A_CACHE = {}


def _A_structure(p: int):
    """A(s)[row, col] = C[row, col] * s**E[row, col]  (Lemma Lemm:A)."""
    if p in _A_CACHE:
        return _A_CACHE[p]
    q = p + 1
    C = np.zeros((q * q, q * q))
    E = np.zeros((q * q, q * q))
    for j in range(q):
        for m in range(j + 1):
            for k in range(q):
                for l in range(k + 1):
                    r = j - m
                    if r != k - l:          # gamma_{j-m, k-l} = (j-m)! 1{j-m = k-l}
                        continue
                    C[j * q + k, m * q + l] = ((-1) ** r) * math.comb(k, l) \
                        * math.comb(j, m) * math.factorial(r)
                    E[j * q + k, m * q + l] = 2 * r
    _A_CACHE[p] = (C, E)
    return C, E


def A_matrix(s: float, p: int) -> np.ndarray:
    C, E = _A_structure(p)
    return C * np.power(s, E)


def canonicalize(theta) -> np.ndarray:
    """||theta|| = 1, dominant coefficient positive and placed at index -k."""
    th = np.asarray(theta, dtype=float)
    th = th / np.linalg.norm(th)
    i = int(np.argmax(np.abs(th)))
    th = np.roll(th, -i)
    if th[0] < 0:
        th = -th
    return th


def theta_window(model: Model, k: int) -> np.ndarray:
    """True theta seen through the window of length 2k+1 (truncated if theta is
    infinite), renormalised and in canonical form."""
    L = 2 * k + 1
    th = np.zeros(L)
    q = min(L, len(model.theta_full))
    th[:q] = model.theta_full[:q]
    return canonicalize(th)


class Contrast:
    """Evaluates D~_n(sigma, theta), lambda_min and J_n for a fixed sample Y."""

    def __init__(self, Y: np.ndarray, p: int):
        self.Y = np.asarray(Y, dtype=complex)
        self.p = p
        self.n_eval = 0

    def moments(self, theta: np.ndarray) -> np.ndarray:
        Z = np.convolve(self.Y, theta, mode="valid")   # Z_t = sum_j theta_j Y_{t-j}
        P = np.vander(Z, self.p + 1, increasing=True)   # P[t, k] = Z_t^k
        D = (P.conj().T @ P) / len(Z)                   # D[j, k] = mean(conj(Z)^j Z^k)
        return D.reshape(-1)

    def d_tilde(self, sigma: float, theta: np.ndarray) -> np.ndarray:
        return A_matrix(sigma * np.linalg.norm(theta), self.p) @ self.moments(theta)

    def D_tilde(self, sigma: float, theta: np.ndarray) -> np.ndarray:
        q = self.p + 1
        D = self.d_tilde(sigma, theta).reshape(q, q)
        return 0.5 * (D + D.conj().T)

    def lambda_min(self, sigma: float, theta: np.ndarray) -> float:
        self.n_eval += 1
        return float(np.linalg.eigvalsh(self.D_tilde(sigma, theta))[0])

    def J(self, sigma: float, theta: np.ndarray) -> float:
        return float(np.real(np.linalg.det(self.D_tilde(sigma, theta))))


# =============================================================================
# 5. Root search (one algorithm for all models)
# =============================================================================

@dataclass
class Settings:
    n_grid: int = 20               # M: points of the (log-spaced) initial grid in sigma
    grid_lo: float = 1e-3          # grid = [grid_lo * s_Y, grid_hi * s_Y], s_Y = sd(Y)
    grid_hi: float = 1.0
    restarts: int = 4              # R: random starting points on the unit sphere per sigma
    restarts_bisect: int = 1       # random starting points per bisection step (+ warm starts)
    eps_sigma: float = 1e-6        # stop when (sigma+ - sigma-) <= eps_sigma * sigma+
    max_bisect: int = 40           # safeguard on the number of bisection steps
    maxiter: int = 200             # L-BFGS-B iterations per start
    ftol: float = 1e-12


class NoRootError(RuntimeError):
    pass


def _random_unit(rng, dim):
    v = rng.standard_normal(dim)
    return v / np.linalg.norm(v)


def _min_lambda(contrast: Contrast, sigma: float, starts, st: Settings,
                stop_if_negative: bool):
    """min over the unit sphere of lambda_min(D~_n(sigma, theta)), multistart L-BFGS-B
    on v -> theta = v/||v||. Returns (value, theta)."""
    def obj(v):
        return contrast.lambda_min(sigma, v / np.linalg.norm(v))

    best_val, best_th = np.inf, None
    for v0 in starts:
        res = optimize.minimize(obj, v0, method="L-BFGS-B",
                                options={"maxiter": st.maxiter, "ftol": st.ftol})
        th = res.x / np.linalg.norm(res.x)
        val = float(res.fun)
        if val < best_val:
            best_val, best_th = val, th
        if stop_if_negative and best_val < 0:
            break
    return best_val, best_th


def estimate_sigma_theta(Y: np.ndarray, p: int, k: int, st: Settings,
                         rng: np.random.Generator):
    """Returns sigma_hat, theta_hat (canonical) and a dict of diagnostics.

    Step 1 (grid):      sigma_1 < ... < sigma_M (log-spaced); at each sigma, minimise
                        lambda_min over theta from the previous minimiser (warm start)
                        and R random points; stop at the first sigma where the minimum
                        is negative -> bracket [sigma-, sigma+].
    Step 2 (bisection): halve the bracket until its relative width is <= eps_sigma.
    Step 3:             sigma_hat = midpoint, theta_hat = argmin lambda_min(sigma_hat, .).
    """
    contrast = Contrast(Y, p)
    dim = 2 * k + 1
    sY = float(np.sqrt(np.mean(np.abs(Y - Y.mean()) ** 2)))
    grid = np.geomspace(st.grid_lo * sY, st.grid_hi * sY, st.n_grid)

    def starts(warm, n_rand):
        out = [w for w in warm if w is not None]
        out += [_random_unit(rng, dim) for _ in range(n_rand)]
        return out

    # ---- Step 1: grid -------------------------------------------------------
    th_prev, sig_prev = None, 0.0
    bracket = None
    for m, s in enumerate(grid):
        val, th = _min_lambda(contrast, s, starts([th_prev], st.restarts), st,
                              stop_if_negative=True)
        if val < 0:
            bracket = (sig_prev, s, th_prev, th, m + 1)
            break
        th_prev, sig_prev = th, s
    if bracket is None:
        raise NoRootError("no sign change of lambda_min on the grid")
    s_minus, s_plus, th_minus, th_plus, n_grid_used = bracket

    # ---- Step 2: bisection --------------------------------------------------
    n_bis = 0
    while (s_plus - s_minus) > st.eps_sigma * s_plus and n_bis < st.max_bisect:
        mid = 0.5 * (s_minus + s_plus)
        val, th = _min_lambda(contrast, mid,
                              starts([th_plus, th_minus], st.restarts_bisect), st,
                              stop_if_negative=True)
        if val < 0:
            s_plus, th_plus = mid, th
        else:
            s_minus, th_minus = mid, th
        n_bis += 1

    # ---- Step 3: estimate ---------------------------------------------------
    sigma_hat = 0.5 * (s_minus + s_plus)
    val, th = _min_lambda(contrast, sigma_hat,
                          starts([th_plus, th_minus], st.restarts), st,
                          stop_if_negative=False)
    theta_hat = canonicalize(th)
    info = dict(n_grid_used=n_grid_used, n_bisect=n_bis,
                bracket_width=s_plus - s_minus,
                lambda_at_hat=contrast.lambda_min(sigma_hat, theta_hat),
                n_lambda_eval=contrast.n_eval)
    return sigma_hat, theta_hat, info


def estimate_support_weights(Y: np.ndarray, p: int, sigma_hat: float,
                             theta_hat: np.ndarray):
    """a-hat: roots of sum_j v_j z^j, lexicographic order; pi-hat: Vandermonde system."""
    contrast = Contrast(Y, p)
    dt = contrast.d_tilde(sigma_hat, theta_hat)
    q = p + 1
    D = dt.reshape(q, q)
    D = 0.5 * (D + D.conj().T)
    _, vecs = np.linalg.eigh(D)
    v = vecs[:, 0]
    if abs(v[-1]) < 1e-12:
        raise RuntimeError("leading coefficient of the polynomial is ~0")
    a = np.roots(v[::-1])                         # np.roots: highest degree first
    a = a[np.lexsort((a.imag, a.real))]
    Vdm = np.vander(a, p, increasing=True).T      # row k: a_l^k, k = 0..p-1
    pi_c = np.linalg.solve(Vdm, dt[:p])           # dt[k] = d~_{k+1} = E[X^k]
    return a, pi_c


def estimate_all(Y, p, k, st: Settings, rng):
    sigma_hat, theta_hat, info = estimate_sigma_theta(Y, p, k, st, rng)
    a_hat, pi_c = estimate_support_weights(Y, p, sigma_hat, theta_hat)
    return dict(sigma_hat=sigma_hat, theta_hat=theta_hat, a_hat=a_hat,
                pi_hat=np.real(pi_c), pi_imag=float(np.max(np.abs(np.imag(pi_c)))),
                **info)


# =============================================================================
# 6. Monte Carlo
# =============================================================================

def _seed(*ints):
    return [int(abs(x)) for x in ints]


def one_run(task):
    """One Monte Carlo replication (top-level function so that it can be pickled)."""
    (model_name, support_name, support, sigma0, n, k, rep, base_seed, st_dict) = task
    model = MODELS[model_name]
    support = np.asarray(support, dtype=complex)
    st = Settings(**st_dict)
    rng = np.random.default_rng(_seed(base_seed, int(model_name[1:]),
                                      zlib.crc32(support_name.encode()),
                                      round(sigma0 * 1e6), n, k, rep))
    t0 = time.perf_counter()
    out = dict(model=model_name, support=support_name, sigma0=sigma0, n=n, k=k,
               rep=rep)
    try:
        Y = simulate_Y(model, sigma0, n, rng, support, WEIGHTS)
        res = estimate_all(Y, len(support), k, st, rng)
        out.update(res)
        ok = np.all(np.isfinite(res["pi_hat"])) and np.all(res["pi_hat"] >= 0)
        out["status"] = "ok" if ok else "negative_weight"
    except NoRootError:
        out["status"] = "no_root"
    except (np.linalg.LinAlgError, RuntimeError, ValueError) as e:
        out["status"] = f"error: {e}"
    out["time"] = time.perf_counter() - t0
    return out


def run_tasks(tasks, n_jobs: Optional[int] = None, verbose: bool = True):
    """Runs the tasks sequentially (n_jobs in {None, 1}) or in parallel processes.
    On Windows, call it under `if __name__ == "__main__":` (scripts) -- it works
    directly from a notebook because one_run lives in this module."""
    results = []
    t0 = time.perf_counter()
    if not n_jobs or n_jobs == 1:
        for i, t in enumerate(tasks):
            results.append(one_run(t))
            if verbose and (i + 1) % max(1, len(tasks) // 10) == 0:
                print(f"  {i + 1}/{len(tasks)} runs ({time.perf_counter() - t0:.0f} s)")
    else:
        from concurrent.futures import ProcessPoolExecutor
        with ProcessPoolExecutor(max_workers=n_jobs) as ex:
            for i, r in enumerate(ex.map(one_run, tasks, chunksize=1)):
                results.append(r)
                if verbose and (i + 1) % max(1, len(tasks) // 10) == 0:
                    print(f"  {i + 1}/{len(tasks)} runs ({time.perf_counter() - t0:.0f} s)")
    return results


def make_tasks(model, sigma0, k, n_values, N_mc, support="base", base_seed=2026,
               settings: Settings = Settings()):
    st = asdict(settings)
    a = tuple(complex(z) for z in SUPPORTS[support])
    return [(model, support, a, float(sigma0), int(n), int(k), rep, base_seed, st)
            for n in n_values for rep in range(N_mc)]


# =============================================================================
# 7. Summaries and LaTeX tables
# =============================================================================

def _ms(x, dec=4):
    x = np.asarray(x, dtype=float)
    sd = x.std(ddof=1) if len(x) > 1 else 0.0
    return f"${x.mean():.{dec}f} \\pm {sd:.{dec}f}$"


def _ms_complex(z, dec=4):
    z = np.asarray(z, dtype=complex)
    m = z.mean()
    sd = np.sqrt(np.sum(np.abs(z - m) ** 2) / (len(z) - 1)) if len(z) > 1 else 0.0
    return f"${m.real:+.{dec}f}{m.imag:+.{dec}f}i \\pm {sd:.{dec}f}$"


def _fmt_true_complex(z):
    def num(x):
        return f"{x:g}"
    re, im = z.real, z.imag
    s = "" if re == 0 else num(re)
    if im != 0:
        sign = "+" if im > 0 and s else ("-" if im < 0 else "")
        mag = abs(im)
        s += f"{sign}{'' if mag == 1 else num(mag)}i"
    return f"${s or '0'}$"


def summarize(results, model, support, sigma0, k, n_values):
    """Dict n -> dict of arrays of the accepted runs + counters."""
    out = {}
    for n in n_values:
        rs = [r for r in results if r["model"] == model and r["support"] == support
              and r["sigma0"] == sigma0 and r["k"] == k and r["n"] == n]
        ok = [r for r in rs if r["status"] == "ok"]
        out[n] = dict(
            N=len(rs), Nelim=len(rs) - len(ok),
            Nnoroot=sum(r["status"] == "no_root" for r in rs),
            Nneg=sum(r["status"] == "negative_weight" for r in rs),
            time=np.mean([r["time"] for r in rs]) if rs else np.nan,
            sigma=np.array([r["sigma_hat"] for r in ok]),
            theta=np.array([r["theta_hat"] for r in ok]).reshape(len(ok), 2 * k + 1),
            a=np.array([r["a_hat"] for r in ok]),
            pi=np.array([r["pi_hat"] for r in ok]),
        )
    return out


def latex_table(results, model, sigma0, k, n_values, support="base", dec=4,
                label=None, caption=None):
    """LaTeX table in the layout of the draft (True values | Estimation | n = ...)."""
    mdl = MODELS[model]
    a_true = SUPPORTS[support]
    p = len(a_true)
    th_true = theta_window(mdl, k)
    S = summarize(results, model, support, sigma0, k, n_values)
    N_mc = max(S[n]["N"] for n in n_values)
    cols = len(n_values)

    lines = [r"\begin{table}[H]", r"\centering", r"\resizebox{\textwidth}{!}{",
             r"\begin{tabular}{|c|c|c|" + "c|" * cols + "}", r"\hline",
             r"\multicolumn{2}{|c|}{True values} & Estimation & "
             + " & ".join(f"$n={n}$" for n in n_values) + r" \\", r"\hline"]

    def row(true_name, true_val, est_name, cells):
        lines.append(f"{true_name} & {true_val} & {est_name} & " + " & ".join(cells) + r" \\")

    def cell(n, f):
        return f(S[n]) if len(S[n]["sigma"]) > 0 else "--"

    row(r"$\sigma_0$", f"{sigma0:g}", r"$\widehat\sigma$",
        [cell(n, lambda s: _ms(s["sigma"], dec)) for n in n_values])
    for i in range(2 * k + 1):
        j = i - k
        row(f"$\\theta_{{{j}}}$", f"{th_true[i]:.{dec}f}", f"$\\widehat\\theta_{{{j}}}$",
            [cell(n, lambda s, i=i: _ms(s["theta"][:, i], dec)) for n in n_values])
    lines.append(r"\hline")
    for l in range(p):
        row(f"$a_{l + 1}$", _fmt_true_complex(a_true[l]), f"$\\widehat a_{l + 1}$",
            [cell(n, lambda s, l=l: _ms_complex(s["a"][:, l], dec)) for n in n_values])
    lines.append(r"\hline")
    for l in range(p):
        row(f"$\\pi_{l + 1}$", f"{WEIGHTS[l]:.2f}", f"$\\widehat\\pi_{l + 1}$",
            [cell(n, lambda s, l=l: _ms(s["pi"][:, l], dec)) for n in n_values])
    lines += [r"\hline",
              r"\multicolumn{3}{|c|}{$v_p$} & " + f"\\multicolumn{{{cols}}}{{c|}}"
              + f"{{{volume(a_true, WEIGHTS):.1f}}}" + r" \\", r"\hline",
              r"\multicolumn{3}{|c|}{Nelim} & "
              + " & ".join(str(S[n]["Nelim"]) for n in n_values) + r" \\", r"\hline",
              r"\multicolumn{3}{|c|}{Mean time per run (s)} & "
              + " & ".join(f"{S[n]['time']:.2f}" for n in n_values) + r" \\", r"\hline",
              r"\end{tabular}}"]
    if caption is None:
        caption = (f"Estimates for model \\textbf{{{model}}} ({mdl.label}), "
                   f"$\\sigma_0={sigma0:g}$, $k(n)={k}$, "
                   f"$N={N_mc}$ Monte Carlo runs.")
    lines.append(f"\\caption{{{caption}}}")
    if label is None:   # same labels as in the draft (mix./ar./ma.)
        prefix = {"M1": "mix", "M2": "ar", "M3": "ma"}[model]
        extra = "" if support == "base" else f".{support}"
        label = f"{prefix}{extra}.kn={k}.sig={sigma0:g}"
    lines.append(f"\\label{{{label}}}")
    lines.append(r"\end{table}")
    return "\n".join(lines)


def save_results(results, path):
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "wb") as f:
        pickle.dump(results, f)


def load_results(path):
    with open(path, "rb") as f:
        return pickle.load(f)


# =============================================================================
# 8. Figures
# =============================================================================

_STYLE = {"font.family": "serif", "mathtext.fontset": "cm", "font.size": 11,
          "axes.titlesize": 11, "axes.labelsize": 11, "legend.fontsize": 9,
          "axes.spines.top": False, "axes.spines.right": False}
_COLORS = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]


def _G(J):
    return np.sign(J) * np.log1p(np.abs(J))


def first_root_J(contrast, theta, sigmas):
    """J_n(., theta) on the grid and its first zero (refined by Brent's method)."""
    J = np.array([contrast.J(s, theta) for s in sigmas])
    idx = np.flatnonzero(np.sign(J[:-1]) * np.sign(J[1:]) < 0)
    if len(idx) == 0:
        return None, J
    i = idx[0]
    root = optimize.brentq(lambda s: contrast.J(s, theta), sigmas[i], sigmas[i + 1])
    return root, J


def plot_roots(model_name="M2", sigma0=0.05, k=1, n_values=(50, 100, 500, 1000, 2000),
               theta_wrong=None, sigma_max=3.0, n_sigma=1500, seed=1, zoom=(0.0, 0.15),
               path=None):
    """Figure 'figcoupe': G_n(sigma) = sign(J_n) log(1 + |J_n|) for theta fixed at the
    true filter (left) and at a wrong filter (right); dashed lines: first zero of J_n
    for each n; dotted black line: sigma_0. Inset: zoom around sigma_0 (left panel)."""
    import matplotlib.pyplot as plt
    mdl = MODELS[model_name]
    th_true = theta_window(mdl, k)
    if theta_wrong is None:
        theta_wrong = np.zeros(2 * k + 1)
        theta_wrong[0] = 1.0
    th_wrong = canonicalize(theta_wrong)
    titles = (r"true filter $\check{s}(\xi_0)=(" + r",\,".join(f"{t:.4f}" for t in th_true) + ")$",
              r"wrong filter $\check{s}(\xi)=(" + r",\,".join(f"{t:g}" for t in th_wrong) + ")$")
    sigmas = np.linspace(1e-3, sigma_max, n_sigma)
    Y = simulate_Y(mdl, sigma0, max(n_values), np.random.default_rng(seed))
    cmap = plt.get_cmap("viridis")
    cols = [cmap(x) for x in np.linspace(0.0, 0.85, len(n_values))]
    p = len(SUPPORTS["base"])
    with plt.rc_context(_STYLE):
        fig, axes = plt.subplots(1, 2, figsize=(12, 4.6), sharey=True)
        curves = {}
        for j, (ax, th, ttl) in enumerate(zip(axes, (th_true, th_wrong), titles)):
            for n, c in zip(n_values, cols):
                con = Contrast(Y[:n], p)
                root, J = first_root_J(con, th, sigmas)
                curves[(j, n)] = (J, root)
                lab = f"$n={n}$" + (f": first zero at ${root:.3f}$" if root is not None else "")
                ax.plot(sigmas, _G(J), color=c, lw=1.3, label=lab)
                if root is not None:
                    ax.axvline(root, color=c, ls="--", lw=0.8)
            ax.axvline(sigma0, color="k", ls=":", lw=1.0)
            ax.axhline(0, color="k", lw=0.6)
            ax.set_xlabel(r"$\sigma$")
            ax.set_title(ttl)
            ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.16), ncol=2, frameon=False)
        axes[0].set_ylabel(r"$G_n(\sigma)$")
        if zoom is not None:
            ins = axes[0].inset_axes([0.25, 0.5, 0.3, 0.38])
            m = (sigmas >= zoom[0]) & (sigmas <= zoom[1])
            fine = np.linspace(max(zoom[0], 1e-3), zoom[1], 400)
            for n, c in zip(n_values, cols):
                con = Contrast(Y[:n], p)
                ins.plot(fine, _G(np.array([con.J(s, th_true) for s in fine])), color=c, lw=1.1)
            ins.axvline(sigma0, color="k", ls=":", lw=1.0)
            ins.axhline(0, color="k", lw=0.6)
            ins.set_xlim(zoom)
            ins.tick_params(labelsize=8)
            ins.set_xticks([0, 0.05, 0.1])
            ins.text(0.97, 0.92, r"zoom", transform=ins.transAxes, ha="right", fontsize=9)
        fig.tight_layout()
        if path:
            fig.savefig(path, dpi=300, bbox_inches="tight")
    return fig


def _filtered_sample(model_name, sigma0, n, rng, support="base"):
    """theta * Y for one sample (= X + sigma0 theta * W): the cloud around the a_l's."""
    mdl = MODELS[model_name]
    Y = simulate_Y(mdl, sigma0, n, rng, SUPPORTS[support], WEIGHTS)
    th = mdl.theta_full[:60]
    return np.convolve(Y, th, mode="valid")


def plot_support_estimates(results, model, sigma0, k, n, support="base", ax=None,
                           seed=0, show_sample=True, legend=True, path=None):
    """Estimated support points over the Monte Carlo runs (dots), true support points
    (stars, area proportional to the mass pi_l), same colour for a_l and its estimates;
    grey: one filtered sample theta * Y (for M1, theta * Y = Y)."""
    import matplotlib.pyplot as plt
    S = summarize(results, model, support, sigma0, k, [n])[n]
    a_true = SUPPORTS[support]
    with plt.rc_context(_STYLE):
        if ax is None:
            fig, ax = plt.subplots(figsize=(6.4, 4.8))
        else:
            fig = ax.figure
        if show_sample:
            Z = _filtered_sample(model, sigma0, n, np.random.default_rng(seed), support)
            ax.scatter(Z.real, Z.imag, s=4, color="0.6", alpha=0.25, lw=0,
                       label=r"one sample of $\theta\star Y$")
        for l in range(len(a_true)):
            c = _COLORS[l]
            ax.scatter(S["a"][:, l].real, S["a"][:, l].imag, s=16, color=c, alpha=0.55, lw=0,
                       label=rf"$\widehat a_{l + 1}$ ({len(S['a'])} runs)")
            ax.scatter(a_true[l].real, a_true[l].imag, marker="*", s=1200 * WEIGHTS[l],
                       color=c, edgecolor="k", lw=0.9, zorder=5,
                       label=rf"$a_{l + 1}$, $\pi_{l + 1}={WEIGHTS[l]:.2f}$")
        ax.set_aspect("equal", adjustable="datalim")
        ax.set_xlabel(r"$\mathrm{Re}$")
        ax.set_ylabel(r"$\mathrm{Im}$")
        ax.set_title(rf"{model}: $\sigma_0={sigma0:g}$, $k(n)={k}$, $n={n}$")
        if legend:
            ax.legend(loc="center left", bbox_to_anchor=(1.02, 0.5), frameon=False,
                      markerscale=0.6)
        if path:
            fig.savefig(path, dpi=300, bbox_inches="tight")
    return ax


# =============================================================================
# 9. Error versus volume
# =============================================================================

def make_volume_tasks(model, sigma0, k, n_values, scales, N_mc, base_seed=2026,
                      settings: Settings = Settings()):
    """Supports c * a for c in scales (v_p scales as c^{p(p-1)}), sigma0 and masses fixed."""
    if np.isscalar(n_values):
        n_values = [n_values]
    tasks = []
    for c in scales:
        name = f"scale_{c:g}"
        SUPPORTS[name] = c * SUPPORTS["base"]
        tasks += make_tasks(model, sigma0, k, list(n_values), N_mc, support=name,
                            base_seed=base_seed, settings=settings)
    return tasks


def volume_sweep_summary(results, model, sigma0, k, n_values, scales):
    """One row per (n, scale): v_p, v_p^{1/(p(p-1))}/sigma0 and RMSE of each estimator
    (per component; for a-hat, relative to the scale c)."""
    if np.isscalar(n_values):
        n_values = [n_values]
    th_true = theta_window(MODELS[model], k)
    rows = []
    for n in n_values:
        for c in scales:
            name = f"scale_{c:g}"
            a_true = c * SUPPORTS["base"]
            p = len(a_true)
            S = summarize(results, model, name, sigma0, k, [n])[n]
            if len(S["sigma"]) == 0:
                continue
            vp = volume(a_true, WEIGHTS)
            rows.append(dict(
                n=n, scale=c, v_p=vp, snr=vp ** (1 / (p * (p - 1))) / sigma0,
                err_sigma=float(np.sqrt(np.mean((S["sigma"] - sigma0) ** 2))),
                err_theta=float(np.sqrt(np.mean((S["theta"] - th_true) ** 2))),
                err_a=float(np.sqrt(np.mean(np.abs(S["a"] - a_true) ** 2)) / c),
                err_pi=float(np.sqrt(np.mean((S["pi"] - WEIGHTS) ** 2))),
                Nelim=S["Nelim"], N=S["N"]))
    return rows


def plot_error_vs_volume(rows, sigma0, path=None):
    """RMSE of each estimator against v_p (log-log), one curve per n."""
    import matplotlib.pyplot as plt
    ns = sorted({r["n"] for r in rows})
    cmap = plt.get_cmap("viridis")
    cols = [cmap(x) for x in np.linspace(0.0, 0.8, len(ns))]
    panels = (("err_sigma", r"$\widehat\sigma_0$"), ("err_theta", r"$\widehat\theta$"),
              ("err_a", r"$\widehat a$ (relative)"), ("err_pi", r"$\widehat\Pi$"))
    vp_base = volume(SUPPORTS["base"], WEIGHTS)
    with plt.rc_context(_STYLE):
        fig, axes = plt.subplots(1, 4, figsize=(14, 3.6))
        for ax, (key, lab) in zip(axes, panels):
            for n, c in zip(ns, cols):
                rr = sorted((r for r in rows if r["n"] == n), key=lambda r: r["v_p"])
                ax.loglog([r["v_p"] for r in rr], [r[key] for r in rr], "o-", color=c,
                          ms=4, lw=1.3, label=f"$n={n}$")
            ax.axvline(vp_base, color="k", ls=":", lw=0.9)
            ax.set_title("RMSE of " + lab)
            ax.set_xlabel(r"$v_p$")
            ax.grid(True, which="major", alpha=0.3)
        axes[0].legend(frameon=False)
        fig.suptitle(rf"Model M1, $\sigma_0={sigma0:g}$: support $c\,(a_1,a_2,a_3)$, "
                     r"masses fixed; dotted line: configuration of the tables ($v_p=443.7$)",
                     y=1.03, fontsize=11)
        fig.tight_layout()
        if path:
            fig.savefig(path, dpi=300, bbox_inches="tight")
    return fig


def plot_volume_clouds(model="M1", sigma0=1.0, k=1, n=2000, scales=(0.35, 1.0, 2.0),
                       seed=0, settings: Settings = Settings(), path=None):
    """One sample for a few values of v_p: data (grey), true support (stars, area
    proportional to pi_l) and the corresponding estimates (crosses), same colours."""
    import matplotlib.pyplot as plt
    with plt.rc_context(_STYLE):
        fig, axes = plt.subplots(1, len(scales), figsize=(4.6 * len(scales), 4.4))
        for ax, c in zip(np.atleast_1d(axes), scales):
            name = f"scale_{c:g}"
            SUPPORTS[name] = c * SUPPORTS["base"]
            rng = np.random.default_rng(seed)
            Y = simulate_Y(MODELS[model], sigma0, n, rng, SUPPORTS[name], WEIGHTS)
            r = estimate_all(Y, len(WEIGHTS), k, settings, rng)
            ax.scatter(Y.real, Y.imag, s=3, color="0.6", alpha=0.25, lw=0)
            for l, a in enumerate(SUPPORTS[name]):
                ax.scatter(a.real, a.imag, marker="*", s=1000 * WEIGHTS[l], color=_COLORS[l],
                           edgecolor="k", lw=0.9, zorder=5)
                ax.scatter(r["a_hat"][l].real, r["a_hat"][l].imag, marker="X", s=90,
                           color=_COLORS[l], edgecolor="k", lw=0.8, zorder=6)
            vp = volume(SUPPORTS[name], WEIGHTS)
            ax.set_title(rf"$v_p={vp:.3g}$,  $\widehat\sigma_0={r['sigma_hat']:.3f}$")
            ax.set_aspect("equal", adjustable="datalim")
            ax.set_xlabel(r"$\mathrm{Re}$")
        np.atleast_1d(axes)[0].set_ylabel(r"$\mathrm{Im}$")
        fig.suptitle(rf"Model M1, $\sigma_0={sigma0:g}$, $n={n}$: true support (stars, area "
                     r"$\propto\pi_l$) and estimates (crosses)", y=1.02, fontsize=11)
        fig.tight_layout()
        if path:
            fig.savefig(path, dpi=300, bbox_inches="tight")
    return fig
