"""Figures and tables for docs/fbp_report.md (analysis of the FBP method).

Run from the repository root::

    python docs/fbp_figures/make_figures.py

The PNG files are written next to this script, the tables (Markdown) to
``tables.md``. The real data part needs the untracked ``streamlit_data/Jičín_*``
datasets and is skipped without them.
"""
import time
from pathlib import Path

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage

import tomotree as tomo
from tomotree import analysis

OUT = Path(__file__).parent
ROOT = OUT.parent.parent
RNG = np.random.default_rng(1)
V_WOOD, V_HOLE = 1500.0, 500.0
CMAP = 'RdYlGn'
TABLES = []

plt.rcParams.update({'figure.dpi': 110, 'font.size': 9, 'axes.titlesize': 9})


# --------------------------------------------------------------------------
# Synthetic trees
# --------------------------------------------------------------------------

def circle_nodes(n=12, r=0.3):
    phi = np.linspace(0, 2 * np.pi, n, endpoint=False)
    return np.column_stack((r * np.cos(phi), r * np.sin(phi)))


def ellipse_nodes(n=12, a=0.36, b=0.24):
    phi = np.linspace(0, 2 * np.pi, n, endpoint=False)
    return np.column_stack((a * np.cos(phi), b * np.sin(phi)))


def disc(cx, cy, r, v=V_HOLE):
    return lambda x, y: np.where((x - cx) ** 2 + (y - cy) ** 2 < r ** 2, v, np.nan)


PHANTOMS = {
    'central': ('centrální dutina r = 10 cm', [disc(0, 0, 0.10)]),
    'offcenter': ('mimostředová dutina r = 8 cm', [disc(0.12, 0.05, 0.08)]),
    'two': ('dvě dutiny r = 6 cm', [disc(-0.12, 0.06, 0.06), disc(0.10, -0.08, 0.06)]),
    'small': ('malá dutina r = 4 cm', [disc(0.05, 0.0, 0.04)]),
    'crack': ('radiální trhlina 3 × 20 cm',
              [lambda x, y: np.where((np.abs(y) < 0.015) & (x > 0.05) & (x < 0.25), 400.0, np.nan)]),
    'ring': ('hniloba v prstenci 12–20 cm',
             [lambda x, y: np.where((np.hypot(x, y) > 0.12) & (np.hypot(x, y) < 0.20), 800.0, np.nan)]),
    'bark': ('hniloba u kůry',
             [disc(0.0, -0.27, 0.09, 600.0)]),
    'none': ('zdravý strom', []),
}


def speed_field(name):
    """Return f(x, y) -> velocity of the phantom ``name``."""
    parts = PHANTOMS[name][1]

    def f(x, y):
        v = np.full(np.broadcast(x, y).shape, V_WOOD)
        for p in parts:
            pv = p(x, y)
            v = np.where(np.isnan(pv), v, pv)
        return v
    return f


def times_of_flight(nodes, field, k=4000):
    """Exact times (integral of the slowness along straight rays)."""
    n = len(nodes)
    times = np.full((n, n), np.nan)
    s = (np.arange(k) + 0.5) / k
    for i in range(n):
        for j in range(i + 1, n):
            p = nodes[i] + s[:, None] * (nodes[j] - nodes[i])
            L = np.linalg.norm(nodes[j] - nodes[i])
            times[i, j] = times[j, i] = L * np.mean(1 / field(p[:, 0], p[:, 1]))
    return times


def make_tomo(nodes, times, n=41):
    return tomo.Tomo(nodes, times=times, nx=n, ny=n, symmetric=True, boundary='polygon')


def velocity(t):
    return t.grid.velocity.reshape(-1).copy()


def truth_on_grid(t, field):
    c = t.grid.cell_centers()
    v = field(c[:, 0], c[:, 1]).astype(float)
    v[~t.compute_inside_mask(c)] = np.nan
    return v


def metrics(t, field, threshold=1000.0):
    """Errors of a tomogram against the phantom."""
    v = velocity(t)
    truth = truth_on_grid(t, field)
    ok = np.isfinite(truth)
    v_ok = np.where(np.isfinite(v), v, np.nan)
    defect = ok & (truth < V_WOOD)
    sound = ok & (truth == V_WOOD)
    rmse = np.sqrt(np.nanmean((v_ok[ok] - truth[ok]) ** 2))
    det = ok & (v_ok < threshold)
    iou = (det & defect).sum() / max((det | defect).sum(), 1)
    return {
        'defect': np.nanmean(v_ok[defect]) if defect.any() else np.nan,
        'sound': np.nanmean(v_ok[sound]),
        'rmse': rmse,
        'iou': iou if defect.any() else np.nan,
        'false': (det & sound).sum() / max(sound.sum(), 1),
    }


def thin_system(t):
    """Thin ray matrix over all cells inside, independent of the method."""
    s = t._ray_cell_system(True, None, 0.12)
    return s['A'].toarray(), s['b'], s['idx']


def thin_residual(t, sys):
    A, b, idx = sys
    v = velocity(t)[idx]
    x = np.where(np.isfinite(v), 1 / v, b.sum() / np.array([r.length for r in t.rays]).sum())
    return np.linalg.norm(A @ x - b) / np.linalg.norm(b)


def show(ax, t, title='', vmin=300, vmax=1600, nodes=True, values=None):
    g = t.grid
    v = t.grid.velocity if values is None else values.reshape(g.velocity.shape)
    im = ax.imshow(v.T, origin='lower', extent=(g.x[0], g.x[-1], g.y[0], g.y[-1]),
                   cmap=CMAP, vmin=vmin, vmax=vmax, interpolation='nearest')
    if nodes:
        xy = np.array([nd.coordinates for nd in t.nodes])
        ax.plot(xy[:, 0], xy[:, 1], 'k.', ms=4)
    ax.set_title(title)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_aspect('equal')
    return im


def outline(ax, name, color='k'):
    for p in PHANTOMS[name][1]:
        x, y = np.meshgrid(np.linspace(-0.4, 0.4, 400), np.linspace(-0.4, 0.4, 400))
        ax.contour(x, y, np.isfinite(p(x, y)).astype(float), [0.5], colors=color,
                   linewidths=0.8, linestyles='--')


def colorbar(fig, im, axes, label='rychlost (m/s)'):
    fig.colorbar(im, ax=axes, shrink=0.8, label=label)


def table(title, header, rows, fmt=None):
    lines = [f'### {title}', '', '| ' + ' | '.join(header) + ' |',
             '|' + '---|' * len(header)]
    for r in rows:
        cells = []
        for c in r:
            if isinstance(c, float):
                f = fmt or ('{:.0f}' if abs(c) >= 100 else '{:.3g}')
                cells.append('–' if np.isnan(c) else f.format(c).replace('.', ','))
            else:
                cells.append(str(c))
        lines.append('| ' + ' | '.join(cells) + ' |')
    TABLES.append('\n'.join(lines))
    print(TABLES[-1], '\n')


def n_clipped(report):
    """Number of cells clipped to the maximum and to the minimum, from the report line
    ``Cells clipped: N to the maximum X, M to the minimum Y.``"""
    line = [s for s in report.splitlines() if s.startswith('Cells clipped')][0]
    return f"{line.split(':')[1].split()[0]} / {line.split(',')[1].split()[0]}"


def fbp(t, **kw):
    t.do_FBP_method(**kw)
    return t


# --------------------------------------------------------------------------
# 1. Classical FBP on a dense parallel-beam sinogram
# --------------------------------------------------------------------------

def radon(img, angles):
    return np.array([ndimage.rotate(img, -a, reshape=False, order=1).sum(axis=0)
                     for a in angles])


def backproject(sino, angles, n):
    out = np.zeros((n, n))
    for row, a in zip(sino, angles):
        out += ndimage.rotate(np.tile(row, (n, 1)), a, reshape=False, order=1)
    return out * np.pi / len(angles)


def ramp(sino):
    n = sino.shape[1]
    pad = 2 ** int(np.ceil(np.log2(2 * n)))
    f = np.abs(np.fft.fftfreq(pad))
    F = np.fft.fft(sino, pad, axis=1) * f
    return np.real(np.fft.ifft(F, axis=1))[:, :n]


def fig_classical():
    n = 128
    y, x = np.mgrid[-1:1:n * 1j, -1:1:n * 1j]
    img = np.where(x ** 2 + y ** 2 < 0.8 ** 2, 1 / V_WOOD, 0.0)
    img = np.where((x - 0.25) ** 2 + (y - 0.1) ** 2 < 0.25 ** 2, 1 / V_HOLE, img)
    img *= 1000
    fig, axs = plt.subplots(2, 4, figsize=(11, 5.6))
    angles = np.linspace(0, 180, 180, endpoint=False)
    sino = radon(img, angles)
    axs[0, 0].imshow(img, cmap='magma', origin='lower')
    axs[0, 0].set_title('fantom (pomalost)')
    axs[0, 1].imshow(sino.T, cmap='magma', aspect='auto', origin='lower',
                     extent=(0, 180, -1, 1))
    axs[0, 1].set_title('sinogram, 180 směrů')
    axs[0, 1].set_xlabel('úhel θ (°)')
    axs[0, 1].set_ylabel('poloha s')
    axs[0, 2].imshow(backproject(sino, angles, n), cmap='magma', origin='lower')
    axs[0, 2].set_title('prostá zpětná projekce (180 směrů)')
    axs[0, 3].imshow(backproject(ramp(sino), angles, n), cmap='magma', origin='lower',
                     vmin=0, vmax=img.max())
    axs[0, 3].set_title('FBP s rampovým filtrem (180 směrů)')
    # point source
    pt = np.zeros((n, n))
    pt[n // 2 + 20, n // 2 - 15] = 1
    ps = radon(pt, angles)
    zoom = (slice(n // 2 + 20 - 24, n // 2 + 20 + 25), slice(n // 2 - 15 - 24, n // 2 - 15 + 25))
    bp = backproject(ps, angles, n)[zoom]
    axs[1, 0].imshow(bp / bp.max(), cmap='magma', origin='lower', vmin=0, vmax=0.3)
    axs[1, 0].set_title('bod: prostá zpětná proj. (výřez, 1/r)')
    fb = backproject(ramp(ps), angles, n)[zoom]
    axs[1, 1].imshow(fb / fb.max(), cmap='magma', origin='lower', vmin=0, vmax=0.3)
    axs[1, 1].set_title('bod: FBP (výřez, ostrý)')
    for k, na in ((2, 12), (3, 6)):
        a = np.linspace(0, 180, na, endpoint=False)
        axs[1, k].imshow(backproject(ramp(radon(img, a)), a, n), cmap='magma',
                         origin='lower', vmin=0, vmax=img.max())
        axs[1, k].set_title(f'FBP s rampovým filtrem, jen {na} směrů')
    for ax in axs.flat:
        if ax is not axs[0, 1]:
            ax.set_xticks([])
            ax.set_yticks([])
    fig.tight_layout()
    fig.savefig(OUT / 'fbp_01_classical.png')
    plt.close(fig)

    # ramp filter in frequency and space
    fig, axs = plt.subplots(1, 2, figsize=(8, 2.8))
    w = np.linspace(-0.5, 0.5, 401)
    axs[0].plot(w, np.abs(w), label='rampa |ω|')
    axs[0].plot(w, np.abs(w) * np.sinc(w), label='Shepp–Logan')
    axs[0].plot(w, np.abs(w) * (0.54 + 0.46 * np.cos(2 * np.pi * w)), label='Hamming')
    axs[0].set_xlabel('frekvence ω')
    axs[0].set_title('filtr ve Fourierově prostoru')
    axs[0].legend()
    k = np.arange(-8, 9)
    with np.errstate(divide='ignore'):
        h = np.where(k == 0, 0.25, np.where(k % 2 == 1, -1 / (np.pi * k) ** 2, 0.0))
    axs[1].stem(k, h)
    axs[1].set_title('rampový filtr v prostoru (Ram–Lak, diskrétní)')
    axs[1].set_xlabel('posun (počet vzorků)')
    fig.tight_layout()
    fig.savefig(OUT / 'fbp_02_ramp.png')
    plt.close(fig)


# --------------------------------------------------------------------------
# 2. Geometry and coverage
# --------------------------------------------------------------------------

def fig_geometry():
    nodes = circle_nodes()
    field = speed_field('offcenter')
    t = make_tomo(nodes, times_of_flight(nodes, field))
    fig, axs = plt.subplots(1, 4, figsize=(13, 3.4))
    truth = truth_on_grid(t, field)
    show(axs[0], t, 'fantom: mimostředová dutina', values=truth)
    for r in t.rays:
        a, b = r.start.coordinates, r.end.coordinates
        axs[0].plot([a[0], b[0]], [a[1], b[1]], color='0.3', lw=0.4)
    for i, xy in enumerate(nodes):
        axs[0].annotate(str(i + 1), xy * 1.12, ha='center', va='center', fontsize=7)
    thin = t._ray_cell_system(True, None, 0.12)
    fat = t._ray_cell_system(True, 'auto', 0.12)
    for ax, sys, name in ((axs[1], thin, 'tenké'), (axs[2], fat, 'tlusté (12 %)')):
        cov = np.full(len(t.grid.all_cells), np.nan)
        A = sys['A'].toarray()
        cov[sys['idx']] = (A > 1e-3 * A.max()).sum(axis=0)
        g = t.grid
        im = ax.imshow(cov.reshape(g.velocity.shape).T, origin='lower', cmap='viridis',
                       extent=(g.x[0], g.x[-1], g.y[0], g.y[-1]), interpolation='nearest')
        ax.set_title(f'počet paprsků v buňce, {name}')
        ax.set_xticks([])
        ax.set_yticks([])
        fig.colorbar(im, ax=ax, shrink=0.8)
    # a single fat ray
    A = fat['A'].toarray()
    row = np.full(len(t.grid.all_cells), np.nan)
    i = 3
    row[fat['idx']] = A[i]
    row[row < 1e-6] = np.nan
    g = t.grid
    im = axs[3].imshow(row.reshape(g.velocity.shape).T, origin='lower', cmap='Blues',
                       extent=(g.x[0], g.x[-1], g.y[0], g.y[-1]), interpolation='nearest')
    r = t.rays[i]
    a, b = r.start.coordinates, r.end.coordinates
    axs[3].plot([a[0], b[0]], [a[1], b[1]], 'r-', lw=0.8)
    axs[3].set_title('váhy jednoho tlustého paprsku (řádek A)')
    axs[3].set_xticks([])
    axs[3].set_yticks([])
    fig.colorbar(im, ax=axs[3], shrink=0.8, label='délka v buňce (m)')
    fig.tight_layout()
    fig.savefig(OUT / 'fbp_03_geometry.png')
    plt.close(fig)
    print('rays', len(t.rays), 'unknowns thin', thin['A'].shape, 'fat nnz',
          fat['A'].nnz, 'thin nnz', thin['A'].nnz)


# --------------------------------------------------------------------------
# 3. Plain vs filtered, thin vs fat
# --------------------------------------------------------------------------

def fig_variants():
    nodes = circle_nodes()
    rows = []
    fig, axs = plt.subplots(2, 5, figsize=(14, 5.6))
    for k, name in enumerate(('central', 'offcenter')):
        field = speed_field(name)
        times = times_of_flight(nodes, field)
        t = make_tomo(nodes, times)
        sys = thin_system(t)
        truth = truth_on_grid(t, field)
        im = show(axs[k, 0], t, 'skutečnost', values=truth)
        variants = [
            ('prostá ZP, tenké', dict(filtered=False, ray_width=None)),
            ('prostá ZP, tlusté', dict(filtered=False)),
            ('FBP, tenké, λ = 0,1', dict(ray_width=None, damping=0.1)),
            ('FBP, tlusté, λ = 1', dict()),
        ]
        for j, (label, kw) in enumerate(variants):
            t = make_tomo(nodes, times)
            fbp(t, **kw)
            show(axs[k, j + 1], t, label)
            outline(axs[k, j + 1], name)
            m = metrics(t, field)
            rows.append((PHANTOMS[name][0], label, m['defect'], m['sound'], m['rmse'],
                         m['iou'], thin_residual(t, sys)))
    colorbar(fig, im, axs)
    fig.savefig(OUT / 'fbp_04_variants.png', bbox_inches='tight')
    plt.close(fig)
    table('Prostá a filtrovaná zpětná projekce, tenké a tlusté paprsky',
          ['fantom', 'varianta', 'dutina (m/s)', 'zdravé dřevo (m/s)', 'RMSE (m/s)',
           'IoU dutiny', 'reziduum'], rows)


# --------------------------------------------------------------------------
# 4. Profile through the defect
# --------------------------------------------------------------------------

def fig_profile():
    nodes = circle_nodes()
    field = speed_field('offcenter')
    times = times_of_flight(nodes, field)
    fig, ax = plt.subplots(figsize=(7, 3.2))
    xs = np.linspace(-0.3, 0.3, 300)
    ax.plot(xs, field(xs, 0.05 + 0 * xs), 'k-', lw=2, label='skutečnost')
    for label, kw in (('prostá ZP, tenké', dict(filtered=False, ray_width=None)),
                      ('FBP, tenké, λ = 0,1', dict(ray_width=None, damping=0.1)),
                      ('FBP, tlusté, λ = 0,3', dict(damping=0.3)),
                      ('FBP, tlusté, λ = 1', dict()),
                      ('FBP, tlusté, λ = 3', dict(damping=3))):
        t = make_tomo(nodes, times, n=61)
        fbp(t, **kw)
        g = t.grid
        iy = np.searchsorted(g.y, 0.05) - 1
        xc = g.x[:-1] + g.dx / 2
        ax.plot(xc, t.grid.velocity[:, iy], label=label)
    ax.set_xlabel('x (m), řez y = 5 cm')
    ax.set_ylabel('rychlost (m/s)')
    ax.legend(fontsize=7, ncol=2)
    ax.set_ylim(300, 1800)
    fig.tight_layout()
    fig.savefig(OUT / 'fbp_05_profile.png')
    plt.close(fig)


# --------------------------------------------------------------------------
# 5. Damping
# --------------------------------------------------------------------------

def fig_damping():
    nodes = circle_nodes()
    field = speed_field('offcenter')
    times = times_of_flight(nodes, field)
    lams = [0.01, 0.1, 0.3, 1, 3, 10, 100]
    fig, axs = plt.subplots(2, len(lams), figsize=(15, 4.6))
    rows = []
    curves = {}
    for k, rw in enumerate(('auto', None)):
        for j, lam in enumerate(lams):
            t = make_tomo(nodes, times)
            rep = t.do_FBP_method(damping=lam, ray_width=rw)
            im = show(axs[k, j], t, f"{'tlusté' if rw else 'tenké'}, λ = {lam:g}".replace('.', ','))
            outline(axs[k, j], 'offcenter')
            m = metrics(t, field)
            clipped = n_clipped(rep)
            rows.append(('tlusté' if rw else 'tenké', f'{lam:g}'.replace('.', ','),
                         m['defect'], m['sound'], m['rmse'], thin_residual(t, thin_system(t)),
                         clipped))
    colorbar(fig, im, axs)
    fig.savefig(OUT / 'fbp_06_damping.png', bbox_inches='tight')
    plt.close(fig)
    table('Vliv tlumení λ (mimostředová dutina, přesná data)',
          ['paprsky', 'λ', 'dutina (m/s)', 'zdravé dřevo (m/s)', 'RMSE (m/s)', 'reziduum',
           'oříznuto nahoru / dolů'], rows)

    # curves: residual and errors vs lambda, exact and noisy data
    lam_grid = np.logspace(-3, 2.5, 30)
    fig, axs = plt.subplots(1, 3, figsize=(13, 3.4))
    for noise, ls in ((0.0, '-'), (0.03, '--')):
        tn = times.copy()
        if noise:
            e = RNG.normal(0, noise, tn.shape)
            e = np.triu(e, 1) + np.triu(e, 1).T
            tn = tn * (1 + e)
        for rw, color in (('auto', 'C0'), (None, 'C1')):
            res, rmse, norm = [], [], []
            t = make_tomo(nodes, tn, n=31)
            sys = t._ray_cell_system(True, rw, 0.12)
            A, b = sys['A'].toarray(), sys['b']
            s0 = b.sum() / np.array([r.length for r in t.rays]).sum()
            for lam in lam_grid:
                # unclipped solution for the residual and the norm
                x = t._fbp_filter(A, b, np.full(A.shape[1], s0), lam)
                res.append(np.linalg.norm(A @ x - b) / np.linalg.norm(b))
                norm.append(np.linalg.norm(x - s0) / (s0 * np.sqrt(len(x))))
                # the image as shown (default bounds)
                t.do_FBP_method(damping=lam, ray_width=rw)
                rmse.append(metrics(t, field)['rmse'])
            lab = f"{'tlusté' if rw else 'tenké'}, šum {int(noise * 100)} %"
            axs[0].loglog(lam_grid, res, ls, color=color, label=lab)
            axs[1].semilogx(lam_grid, rmse, ls, color=color, label=lab)
            axs[2].loglog(res, norm, ls, color=color, label=lab)
    axs[0].set_xlabel('λ')
    axs[0].set_title('relativní reziduum ‖Ax − b‖/‖b‖')
    axs[1].set_xlabel('λ')
    axs[1].set_title('RMSE rychlosti proti skutečnosti (m/s)')
    axs[1].set_ylim(0, 600)
    axs[2].set_xlabel('reziduum')
    axs[2].set_title('L-křivka: RMS(x − s₀)/s₀ vs reziduum')
    for ax in axs:
        ax.legend(fontsize=7)
        ax.axvline(1, color='0.7', lw=0.6) if ax is not axs[2] else None
    fig.tight_layout()
    fig.savefig(OUT / 'fbp_07_damping_curves.png')
    plt.close(fig)


# --------------------------------------------------------------------------
# 6. Singular values, filter factors, resolution
# --------------------------------------------------------------------------

def fig_svd():
    nodes = circle_nodes()
    t = make_tomo(nodes, times_of_flight(nodes, speed_field('none')))
    fig, axs = plt.subplots(1, 3, figsize=(13, 3.4))
    for rw, color, name in ((None, 'C1', 'tenké'), ('auto', 'C0', 'tlusté 12 %')):
        A = t._ray_cell_system(True, rw, 0.12)['A'].toarray()
        sv = np.linalg.svd(A, compute_uv=False)
        mu = np.trace(A @ A.T) / len(A)
        axs[0].semilogy(np.arange(1, len(sv) + 1), sv ** 2, 'o-', ms=3, color=color,
                        label=f'σ², {name}')
        axs[0].axhline(mu, color=color, ls=':', lw=1)
        print(name, 'cond(AA^T)=%.3g' % (sv[0] ** 2 / sv[-1] ** 2), 'mu=%.3g' % mu,
              'sv2 first/last', sv[0] ** 2, sv[-1] ** 2,
              'n above mu', int((sv ** 2 > mu).sum()))
        for lam, ls in ((0.1, '--'), (1, '-'), (10, ':')):
            f = sv ** 2 / (sv ** 2 + lam * mu)
            axs[1].plot(np.arange(1, len(sv) + 1), f, ls, color=color,
                        label=f'{name}, λ = {lam:g}'.replace('.', ','))
    axs[0].set_title('vlastní čísla AAᵀ (σ²), tečkovaně μ pro λ = 1')
    axs[0].set_xlabel('index')
    axs[0].legend(fontsize=7)
    axs[1].set_title('filtrační faktory σ²/(σ² + μ)')
    axs[1].set_xlabel('index singulární hodnoty')
    axs[1].legend(fontsize=6, ncol=2)
    # effective number of parameters (trace of resolution) vs lambda
    lam_grid = np.logspace(-3, 3, 40)
    for rw, color, name in ((None, 'C1', 'tenké'), ('auto', 'C0', 'tlusté 12 %')):
        A = t._ray_cell_system(True, rw, 0.12)['A'].toarray()
        sv = np.linalg.svd(A, compute_uv=False)
        mu = np.trace(A @ A.T) / len(A)
        axs[2].semilogx(lam_grid, [np.sum(sv ** 2 / (sv ** 2 + l * mu)) for l in lam_grid],
                        color=color, label=name)
    axs[2].set_title('počet „využitých“ stupňů volnosti tr(R)')
    axs[2].set_xlabel('λ')
    axs[2].axvline(1, color='0.7', lw=0.6)
    axs[2].legend(fontsize=7)
    fig.tight_layout()
    fig.savefig(OUT / 'fbp_08_svd.png')
    plt.close(fig)


def fig_psf():
    """Point spread functions: columns of the resolution matrix."""
    nodes = circle_nodes()
    t = make_tomo(nodes, times_of_flight(nodes, speed_field('none')))
    centers = t.grid.cell_centers()
    points = [(0.0, 0.0), (0.12, 0.05), (0.22, -0.1)]
    fig, axs = plt.subplots(3, 4, figsize=(12, 8.2))
    rows = []
    for k, (label, rw, lam, filt) in enumerate((
            ('prostá ZP, tenké', None, 1, False),
            ('FBP, tenké, λ = 0,1', None, 0.1, True),
            ('FBP, tlusté, λ = 1', 'auto', 1, True),
            ('FBP, tlusté, λ = 0,3', 'auto', 0.3, True))):
        sys = t._ray_cell_system(True, rw, 0.12)
        A = sys['A'].toarray()
        idx = sys['idx']
        G = A @ A.T
        mu = lam * np.trace(G) / len(A)
        for j, p in enumerate(points):
            c = int(np.argmin(np.linalg.norm(centers[idx] - p, axis=1)))
            e = np.zeros(A.shape[1])
            e[c] = 1
            if filt:
                resp = A.T @ np.linalg.solve(G + mu * np.eye(len(A)), A @ e)
            else:
                col = A.sum(axis=0)
                resp = np.zeros(A.shape[1])
                resp[col > 0] = (A.T @ ((A @ e) / np.array([r.length for r in t.rays])))[col > 0] / col[col > 0]
            full = np.full(len(t.grid.all_cells), np.nan)
            full[idx] = resp / max(resp.max(), 1e-12)
            g = t.grid
            axs[j, k].imshow(full.reshape(g.velocity.shape).T, origin='lower', cmap='RdBu_r',
                             vmin=-1, vmax=1, extent=(g.x[0], g.x[-1], g.y[0], g.y[-1]),
                             interpolation='nearest')
            axs[j, k].plot(*p, 'k+', ms=8)
            axs[j, k].set_xticks([])
            axs[j, k].set_yticks([])
            if j == 0:
                axs[j, k].set_title(label)
            # width: area where response > half max
            area = np.sum(resp > 0.5 * resp.max()) * g.dx * g.dy
            rows.append((label, f'({p[0]:g}, {p[1]:g})', resp[c] if filt else np.nan,
                         2 * np.sqrt(area / np.pi) * 100, resp.min() / resp.max()))
    fig.tight_layout()
    fig.savefig(OUT / 'fbp_09_psf.png')
    plt.close(fig)
    table('Odezva na bodovou poruchu (sloupec rozlišovací matice)',
          ['varianta', 'bod (m)', 'R_jj', 'průměr poloviční výšky (cm)', 'min/max (záporný překmit)'],
          rows)


# --------------------------------------------------------------------------
# 7. Ray width
# --------------------------------------------------------------------------

def fig_ray_width():
    nodes = circle_nodes()
    widths = [0, 0.04, 0.08, 0.12, 0.2, 0.3]
    names = ['offcenter', 'two', 'small']
    fig, axs = plt.subplots(len(names), len(widths), figsize=(14, 7))
    rows = []
    for i, name in enumerate(names):
        field = speed_field(name)
        times = times_of_flight(nodes, field)
        for j, w in enumerate(widths):
            t = make_tomo(nodes, times)
            t.do_FBP_method(ray_width='auto' if w else None, ray_width_ratio=w,
                            damping=1 if w else 0.1)
            im = show(axs[i, j], t, f'šířka {int(w * 100)} %' + (' (λ = 0,1)' if not w else ''))
            outline(axs[i, j], name)
            m = metrics(t, field)
            rows.append((PHANTOMS[name][0], f'{int(w * 100)} %', m['defect'], m['sound'],
                         m['rmse'], m['iou']))
    colorbar(fig, im, axs)
    fig.savefig(OUT / 'fbp_10_ray_width.png', bbox_inches='tight')
    plt.close(fig)
    table('Vliv šířky tlustého paprsku (λ = 1, pro tenké 0,1)',
          ['fantom', 'šířka', 'defekt (m/s)', 'zdravé dřevo (m/s)', 'RMSE (m/s)', 'IoU'], rows)


# --------------------------------------------------------------------------
# 8. Phantom gallery and comparison of methods
# --------------------------------------------------------------------------

def reconstruct(nodes, times, method, **kw):
    data = {'nodes': nodes, 'times': times}
    return analysis.reconstruct(data, method=method, nx=41, ny=41, anisotropy=False,
                                boundary='polygon', alignment='origin in the pith', **kw)


def fig_methods():
    nodes = circle_nodes()
    names = ['central', 'offcenter', 'two', 'crack', 'ring', 'bark']
    methods = [('Rays', {}), ('EBSI', dict(rescale=False)), ('ERSM', dict(rescale=False)),
               ('ERSM', dict(rescale=False, fbp_correction=True)),
               ('SIRT', {}), ('FBP', {})]
    labels = ['Rays', 'EBSI', 'ERSM', 'ERSM + korekce ZP', 'SIRT', 'FBP']
    fig, axs = plt.subplots(len(names), len(methods) + 1, figsize=(14, 13.5))
    rows = []
    for i, name in enumerate(names):
        field = speed_field(name)
        times = times_of_flight(nodes, field)
        sys = None
        for j, ((method, kw), label) in enumerate(zip(methods, labels)):
            start = time.perf_counter()
            t = reconstruct(nodes, times, method, **kw)
            dt = time.perf_counter() - start
            if j == 0:
                show(axs[i, 0], t, PHANTOMS[name][0], values=truth_on_grid(t, field))
                sys = thin_system(make_tomo(nodes, times))
            im = show(axs[i, j + 1], t, label if i == 0 else '')
            outline(axs[i, j + 1], name)
            m = metrics(t, field)
            rows.append((PHANTOMS[name][0], label, m['defect'], m['sound'], m['rmse'],
                         m['iou'], m['false'], dt * 1000))
    colorbar(fig, im, axs)
    fig.savefig(OUT / 'fbp_11_methods.png', bbox_inches='tight')
    plt.close(fig)
    table('Srovnání metod na fantomech (12 senzorů, mřížka 41×41, přesná data)',
          ['fantom', 'metoda', 'defekt (m/s)', 'zdravé (m/s)', 'RMSE (m/s)', 'IoU',
           'falešně pomalé', 'čas (ms)'], rows)


# --------------------------------------------------------------------------
# 9. Noise
# --------------------------------------------------------------------------

def fig_noise():
    nodes = circle_nodes()
    field = speed_field('offcenter')
    times = times_of_flight(nodes, field)
    levels = [0.0, 0.02, 0.05, 0.10]
    lams = [0.1, 0.3, 1, 3]
    fig, axs = plt.subplots(len(levels), len(lams) + 1, figsize=(13, 10.5))
    rows = []
    for i, noise in enumerate(levels):
        stats = {lam: [] for lam in lams}
        stats['SIRT'] = []
        for rep in range(10):
            rng = np.random.default_rng(rep)
            e = np.triu(rng.normal(0, noise, times.shape), 1)
            tn = times * (1 + e + e.T)
            for j, lam in enumerate(lams):
                t = make_tomo(nodes, tn)
                t.do_FBP_method(damping=lam)
                stats[lam].append(metrics(t, field))
                if rep == 0:
                    im = show(axs[i, j], t, f'šum {int(noise * 100)} %, λ = {lam:g}'.replace('.', ','))
                    outline(axs[i, j], 'offcenter')
            t = make_tomo(nodes, tn)
            t.do_SIRT_method()
            stats['SIRT'].append(metrics(t, field))
            if rep == 0:
                show(axs[i, -1], t, f'SIRT, šum {int(noise * 100)} %')
                outline(axs[i, -1], 'offcenter')
        for key, ms in stats.items():
            label = 'SIRT' if key == 'SIRT' else f'FBP λ = {key:g}'.replace('.', ',')
            rows.append((f'{int(noise * 100)} %', label,
                         np.mean([m['defect'] for m in ms]),
                         np.mean([m['sound'] for m in ms]),
                         np.mean([m['rmse'] for m in ms]),
                         np.std([m['rmse'] for m in ms]),
                         np.mean([m['iou'] for m in ms])))
    colorbar(fig, im, axs)
    fig.savefig(OUT / 'fbp_12_noise.png', bbox_inches='tight')
    plt.close(fig)
    table('Vliv šumu v dobách průletu (mimostředová dutina, průměr 10 realizací)',
          ['šum', 'metoda', 'dutina (m/s)', 'zdravé (m/s)', 'RMSE (m/s)', 'sm. odch. RMSE',
           'IoU'], rows)


# --------------------------------------------------------------------------
# 10. Number of sensors and tree shape
# --------------------------------------------------------------------------

def fig_sensors():
    counts = [6, 8, 12, 16, 24]
    field = speed_field('offcenter')
    fig, axs = plt.subplots(2, len(counts), figsize=(14, 5.6))
    rows = []
    for j, n in enumerate(counts):
        nodes = circle_nodes(n)
        times = times_of_flight(nodes, field)
        for i, (label, kw) in enumerate((('prostá ZP', dict(filtered=False)), ('FBP', {}))):
            t = make_tomo(nodes, times)
            start = time.perf_counter()
            t.do_FBP_method(**kw)
            dt = time.perf_counter() - start
            im = show(axs[i, j], t, f'{n} senzorů, {len(t.rays)} paprsků, {label}')
            outline(axs[i, j], 'offcenter')
            m = metrics(t, field)
            rows.append((n, len(t.rays), label, m['defect'], m['sound'], m['rmse'], m['iou'],
                         dt * 1000))
    colorbar(fig, im, axs)
    fig.savefig(OUT / 'fbp_13_sensors.png', bbox_inches='tight')
    plt.close(fig)
    table('Vliv počtu senzorů (mimostředová dutina, tlusté paprsky, λ = 1)',
          ['senzorů', 'paprsků', 'varianta', 'dutina (m/s)', 'zdravé (m/s)', 'RMSE (m/s)',
           'IoU', 'čas (ms)'], rows)


def fig_ellipse():
    nodes = ellipse_nodes()
    field = speed_field('offcenter')
    times = times_of_flight(nodes, field)
    fig, axs = plt.subplots(1, 4, figsize=(12, 2.9))
    t = make_tomo(nodes, times)
    show(axs[0], t, 'eliptický kmen 72 × 48 cm', values=truth_on_grid(t, field))
    rows = []
    for ax, (label, method, kw) in zip(axs[1:], (('ERSM', 'ERSM', dict(rescale=False)),
                                                 ('SIRT', 'SIRT', {}),
                                                 ('FBP', 'FBP', {}))):
        t = reconstruct(nodes, times, method, **kw)
        im = show(ax, t, label)
        outline(ax, 'offcenter')
        m = metrics(t, field)
        rows.append((label, m['defect'], m['sound'], m['rmse'], m['iou']))
    colorbar(fig, im, axs)
    fig.savefig(OUT / 'fbp_14_ellipse.png', bbox_inches='tight')
    plt.close(fig)
    table('Eliptický kmen, mimostředová dutina',
          ['metoda', 'dutina (m/s)', 'zdravé (m/s)', 'RMSE (m/s)', 'IoU'], rows)


# --------------------------------------------------------------------------
# 11. Grid independence and timing
# --------------------------------------------------------------------------

def tab_grid():
    nodes = circle_nodes()
    field = speed_field('offcenter')
    times = times_of_flight(nodes, field)
    rows = []
    for n in (21, 31, 41, 61, 81):
        for rw in ('auto', None):
            t = make_tomo(nodes, times, n=n)
            start = time.perf_counter()
            rep = t.do_FBP_method(ray_width=rw, damping=1 if rw else 0.1)
            dt = time.perf_counter() - start
            m = metrics(t, field)
            cells = int(rep.split(' cells')[0].split()[-1])
            rows.append((f'{n}×{n}', 'tlusté' if rw else 'tenké (λ = 0,1)', cells,
                         m['defect'], m['sound'], m['rmse'], dt * 1000))
    table('Nezávislost na mřížce a výpočetní čas (mimostředová dutina)',
          ['mřížka', 'paprsky', 'neznámých', 'dutina (m/s)', 'zdravé (m/s)', 'RMSE (m/s)',
           'čas (ms)'], rows)


# --------------------------------------------------------------------------
# 12. Straight ray assumption: bent rays around the cavity
# --------------------------------------------------------------------------

def tab_bent_rays():
    """Measured times are the fastest path, not the straight line: the wave
    goes around a slow cavity. Simulate the first arrival with a fast marching
    like Dijkstra on a fine grid and reconstruct with straight rays."""
    from scipy.sparse import csgraph, lil_matrix
    nodes = circle_nodes()
    rows = []
    for name in ('central', 'offcenter'):
        field = speed_field(name)
        n = 121
        xs = np.linspace(-0.31, 0.31, n)
        X, Y = np.meshgrid(xs, xs, indexing='ij')
        slow = 1 / field(X, Y)
        h = xs[1] - xs[0]
        G = lil_matrix((n * n, n * n))
        steps = [(1, 0), (0, 1), (1, 1), (1, -1), (2, 1), (1, 2), (2, -1), (1, -2)]
        for di, dj in steps:
            d = h * np.hypot(di, dj)
            for i in range(n):
                for j in range(n):
                    i2, j2 = i + di, j + dj
                    if 0 <= i2 < n and 0 <= j2 < n:
                        w = d * 0.5 * (slow[i, j] + slow[i2, j2])
                        G[i * n + j, i2 * n + j2] = w
                        G[i2 * n + j2, i * n + j] = w
        G = G.tocsr()
        src = [int(np.argmin(np.abs(xs - p[0]))) * n + int(np.argmin(np.abs(xs - p[1])))
               for p in nodes]
        D = csgraph.dijkstra(G, indices=src)
        bent = np.array([[D[i, src[j]] for j in range(len(nodes))] for i in range(len(nodes))])
        bent = 0.5 * (bent + bent.T)
        np.fill_diagonal(bent, np.nan)
        straight = times_of_flight(nodes, field)
        # scale bent times so that the healthy tree gives the exact times (grid bias)
        ref = times_of_flight(nodes, speed_field('none'))
        Dh = csgraph.dijkstra(_healthy_graph(n, xs, steps, h), indices=src)
        bh = np.array([[Dh[i, src[j]] for j in range(len(nodes))] for i in range(len(nodes))])
        np.fill_diagonal(bh, np.nan)
        bent = bent * ref / bh
        shortening = np.nanmax(1 - bent / straight) * 100
        if name == 'central':
            fig, axs = plt.subplots(1, 6, figsize=(15, 2.7))
            t = make_tomo(nodes, straight)
            show(axs[0], t, 'skutečnost', values=truth_on_grid(t, field))
        for k, (label, tt, method, kw) in enumerate((
                ('přímé dráhy, FBP', straight, 'FBP', {}),
                ('nejrychlejší dráha, FBP', bent, 'FBP', {}),
                ('nejrychlejší dráha, FBP λ = 0,3', bent, 'FBP', dict(fbp_damping=0.3)),
                ('nejrychlejší dráha, SIRT', bent, 'SIRT', {}),
                ('nejrychlejší dráha, ERSM + rescale', bent, 'ERSM', dict(rescale=True)))):
            t = reconstruct(nodes, tt, method, **kw)
            m = metrics(t, field)
            rows.append((PHANTOMS[name][0], label, shortening if tt is bent else 0.0,
                         m['defect'], m['sound'], m['rmse'], m['iou']))
            if name == 'central':
                im = show(axs[k + 1], t, label.replace(', ', ',\n', 1))
                outline(axs[k + 1], name)
        if name == 'central':
            colorbar(fig, im, axs)
            fig.savefig(OUT / 'fbp_17_bent.png', bbox_inches='tight')
            plt.close(fig)
    table('Ohyb paprsků kolem dutiny (doby průletu jako nejrychlejší dráha)',
          ['fantom', 'data a metoda', 'max. zkrácení času (%)', 'dutina (m/s)', 'zdravé (m/s)',
           'RMSE (m/s)', 'IoU'], rows)


def _healthy_graph(n, xs, steps, h):
    from scipy.sparse import lil_matrix
    G = lil_matrix((n * n, n * n))
    for di, dj in steps:
        d = h * np.hypot(di, dj) / V_WOOD
        for i in range(n):
            for j in range(n):
                i2, j2 = i + di, j + dj
                if 0 <= i2 < n and 0 <= j2 < n:
                    G[i * n + j, i2 * n + j2] = d
                    G[i2 * n + j2, i * n + j] = d
    return G.tocsr()


# --------------------------------------------------------------------------
# 13. Back projection correction of ERSM
# --------------------------------------------------------------------------

def fig_correction():
    nodes = circle_nodes()
    field = speed_field('two')
    times = times_of_flight(nodes, field)
    lams = [0.3, 1, 3, 10]
    fig, axs = plt.subplots(1, len(lams) + 2, figsize=(14, 2.8))
    t = reconstruct(nodes, times, 'ERSM', rescale=False)
    im = show(axs[0], t, 'ERSM')
    outline(axs[0], 'two')
    rows = [('ERSM', '–') + tuple(metrics(t, field)[k] for k in ('defect', 'sound', 'rmse', 'iou'))]
    for ax, lam in zip(axs[1:], lams):
        t = reconstruct(nodes, times, 'ERSM', rescale=False, fbp_correction=True,
                        fbp_correction_damping=lam)
        show(ax, t, f'ERSM + korekce, λ = {lam:g}'.replace('.', ','))
        outline(ax, 'two')
        rows.append(('ERSM + korekce', f'{lam:g}'.replace('.', ','))
                    + tuple(metrics(t, field)[k] for k in ('defect', 'sound', 'rmse', 'iou')))
    t = reconstruct(nodes, times, 'FBP')
    show(axs[-1], t, 'FBP (samotná)')
    outline(axs[-1], 'two')
    rows.append(('FBP', '1') + tuple(metrics(t, field)[k] for k in ('defect', 'sound', 'rmse', 'iou')))
    colorbar(fig, im, axs)
    fig.savefig(OUT / 'fbp_15_correction.png', bbox_inches='tight')
    plt.close(fig)
    table('Korekce ERSM zpětnou projekcí (dvě dutiny)',
          ['varianta', 'λ', 'dutiny (m/s)', 'zdravé (m/s)', 'RMSE (m/s)', 'IoU'], rows)


# --------------------------------------------------------------------------
# 14. Real data
# --------------------------------------------------------------------------

def fig_real():
    from tomotree.dataset import load_dataset
    names = ['Jičín_05', 'Jičín_08', 'Jičín_14', 'Jičín_15']
    names = [n for n in names if (ROOT / 'streamlit_data' / n).exists()]
    if not names:
        print('real datasets missing, skipped')
        return
    variants = [('prostá ZP', 'FBP', dict(fbp_filtered=False)),
                ('FBP λ = 0,3', 'FBP', dict(fbp_damping=0.3)),
                ('FBP λ = 1', 'FBP', {}),
                ('FBP λ = 3', 'FBP', dict(fbp_damping=3)),
                ('FBP tenké λ = 0,1', 'FBP', dict(fbp_ray_width=0, fbp_damping=0.1)),
                ('SIRT', 'SIRT', {}),
                ('ERSM + rescale', 'ERSM', dict(rescale=True))]
    fig, axs = plt.subplots(len(names), len(variants), figsize=(15, 2.5 * len(names) + 0.6))
    axs = np.atleast_2d(axs)
    rows = []
    for i, name in enumerate(names):
        _, data = load_dataset(ROOT / 'streamlit_data' / name)
        vals = []
        ts = []
        for label, method, kw in variants:
            t = analysis.reconstruct(data, method=method, nx=41, ny=41, anisotropy=True,
                                     boundary='spline', alignment='origin in the pith', **kw)
            ts.append(t)
            v = velocity(t)
            vals.append(v[np.isfinite(v)])
        lo = np.percentile(np.concatenate(vals), 2)
        hi = np.percentile(np.concatenate(vals), 98)
        sys = thin_system(ts[2])
        for j, ((label, method, kw), t) in enumerate(zip(variants, ts)):
            im = show(axs[i, j], t, (name + ', ' if j == 0 else '') + label, vmin=lo, vmax=hi)
            v = velocity(t)
            rep = getattr(t, 'fbp_report', '') or ''
            clipped = n_clipped(rep) if 'clipped' in rep else np.nan
            rows.append((name, label, np.nanpercentile(v, 5), np.nanmedian(v),
                         np.nanpercentile(v, 95), thin_residual(t, sys), clipped))
        fig.colorbar(im, ax=axs[i, :], shrink=0.9, label='m/s')
    fig.savefig(OUT / 'fbp_16_real.png', bbox_inches='tight')
    plt.close(fig)
    table('Reálná data (mřížka 41×41, korekce anizotropie, obvod spline)',
          ['dataset', 'varianta', '5. percentil (m/s)', 'medián (m/s)', '95. percentil (m/s)',
           'reziduum', 'oříznuto nahoru / dolů'], rows)


def main():
    steps = [fig_classical, fig_geometry, fig_variants, fig_profile, fig_damping, fig_svd,
             fig_psf, fig_ray_width, fig_methods, fig_noise, fig_sensors, fig_ellipse,
             tab_grid, tab_bent_rays, fig_correction, fig_real]
    for step in steps:
        start = time.time()
        step()
        print(f'{step.__name__}: {time.time() - start:.1f} s')
    (OUT / 'tables.md').write_text('\n\n'.join(TABLES) + '\n', encoding='utf-8')


if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        for name in sys.argv[1:]:
            globals()[name]()
        (OUT / 'tables_partial.md').write_text('\n\n'.join(TABLES) + '\n', encoding='utf-8')
    else:
        main()
