"""Reproduce the mathematics figures and numerical checks with PyTorch on CPU.

Run: python examples/math_foundations.py
     python examples/math_foundations.py --output-dir docs/_static/figures/math

All input data are synthetic. No model/data download, GPU or remote computation.
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path
import platform
from time import perf_counter

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import font_manager
import torch
import torch.nn.functional as F


DTYPE = torch.float64
TEAL = "#15776e"
ORANGE = "#c46d2d"
BLUE = "#4d70ad"


def array(tensor: torch.Tensor):
    """NumPy conversion only at the plotting boundary."""
    return tensor.detach().cpu().numpy()


def configure_plots() -> str:
    available = {entry.name for entry in font_manager.fontManager.ttflist}
    for font in ["Microsoft YaHei", "Noto Sans CJK SC", "SimHei", "WenQuanYi Micro Hei"]:
        if font in available:
            plt.rcParams["font.family"] = [font, "DejaVu Sans"]
            break
    else:
        raise RuntimeError("Install a Chinese font (e.g. Noto Sans CJK SC) to reproduce the figures")
    plt.rcParams.update({"axes.unicode_minus": False, "font.size": 10,
                         "axes.spines.top": False, "axes.spines.right": False,
                         "axes.prop_cycle": matplotlib.cycler(color=[TEAL, ORANGE, BLUE]),
                         "savefig.facecolor": "white"})
    return font


def save(fig, folder: Path, name: str, figures: list[str]) -> None:
    fig.savefig(folder / f"{name}.png", dpi=150, bbox_inches="tight")
    fig.savefig(folder / f"{name}.svg", bbox_inches="tight")
    plt.close(fig)
    figures.append(name)


def tensor_demo(folder: Path, figures: list[str], checks: dict) -> None:
    axis = torch.linspace(0, 1, 32, dtype=DTYPE)
    yy, xx = torch.meshgrid(axis, axis, indexing="ij")
    image = torch.stack([xx, yy, (torch.sin(2*torch.pi*xx)*torch.cos(2*torch.pi*yy)+1)/2])
    fig, axes = plt.subplots(1, 4, figsize=(10.5, 2.7), layout="constrained")
    axes[0].imshow(array(image.permute(1, 2, 0)))
    axes[0].set_title("合成 RGB 图像 [H,W,C]")
    for index, name in enumerate(["红通道", "绿通道", "蓝通道"]):
        axes[index+1].imshow(array(image[index]), cmap="gray", vmin=0, vmax=1)
        axes[index+1].set_title(f"{name} [H,W]")
    for ax in axes:
        ax.set(xlabel="宽 W", ylabel="高 H")
    save(fig, folder, "tensor_axes", figures)
    prediction = torch.arange(3., dtype=DTYPE).unsqueeze(1)
    target = torch.arange(3., dtype=DTYPE)
    assert (prediction-target).shape == (3, 3)
    assert (prediction.squeeze(-1)-target).shape == (3,)
    checks["broadcast_shapes"] = {"wrong": [3, 3], "correct": [3]}


def calculus_demo(folder: Path, figures: list[str], checks: dict) -> None:
    x = torch.linspace(-1.0, 3.0, 500, dtype=DTYPE)
    x0 = torch.tensor(0.7, dtype=DTYPE)
    first = x0.sin() + x0.cos()*(x-x0)
    second = first - 0.5*x0.sin()*(x-x0)**2
    fig, axes = plt.subplots(1, 2, figsize=(10, 3.6), layout="constrained")
    axes[0].plot(array(x), array(x.sin()), label="sin(x)")
    axes[0].plot(array(x), array(first), "--", label="一阶近似")
    axes[0].plot(array(x), array(second), ":", label="二阶近似")
    axes[0].scatter([float(x0)], [float(x0.sin())], color="black", s=25)
    axes[0].set(xlabel="x", ylabel="函数值", title="在 x=0.7 附近展开")
    axes[0].legend()
    axes[1].plot(array(x), array((first-x.sin()).abs()), label="一阶绝对误差")
    axes[1].plot(array(x), array((second-x.sin()).abs()), label="二阶绝对误差")
    axes[1].set(xlabel="x", ylabel="绝对误差", title="近似需要注明有效邻域")
    axes[1].legend()
    save(fig, folder, "taylor", figures)

    grid = torch.linspace(-5, 5, 2001, dtype=DTYPE)
    density = torch.distributions.Normal(0., 1.).log_prob(grid).exp()
    middle = (grid >= -1) & (grid <= 1)
    mass = torch.trapezoid(density, grid)
    fig, ax = plt.subplots(figsize=(7, 3.5), layout="constrained")
    ax.plot(array(grid), array(density), label="标准正态密度")
    ax.fill_between(array(grid[middle]), array(density[middle]), alpha=0.3, color=TEAL,
                    label="-1 ≤ x ≤ 1 的概率面积")
    ax.set(xlabel="x", ylabel="概率密度", title="总面积约 1；曲线高度不是单点概率")
    ax.legend()
    save(fig, folder, "integral", figures)
    torch.testing.assert_close(mass, torch.tensor(1., dtype=DTYPE), atol=1e-5, rtol=0)
    checks["normal_integral_minus5_to5"] = float(mass)

    point = torch.tensor(0.7, dtype=DTYPE, requires_grad=True)
    value = point.sin()*point**2
    (automatic,) = torch.autograd.grad(value, point)
    analytical = point.detach().cos()*point.detach()**2 + 2*point.detach()*point.detach().sin()
    h = 1e-5
    f = lambda z: z.sin()*z**2
    finite = (f(point.detach()+h)-f(point.detach()-h))/(2*h)
    torch.testing.assert_close(automatic, analytical)
    torch.testing.assert_close(automatic, finite, atol=1e-8, rtol=1e-8)
    checks["derivative"] = {"autograd": float(automatic), "analytical": float(analytical),
                            "finite_difference": float(finite)}


def gradient_demo(folder: Path, figures: list[str], checks: dict) -> None:
    axis = torch.linspace(-3, 3, 100, dtype=DTYPE)
    yy, xx = torch.meshgrid(axis, axis, indexing="ij")
    zz = xx**2 + 3*yy**2 + xx*yy
    fig, ax = plt.subplots(figsize=(6, 4.5), layout="constrained")
    ax.contour(array(xx), array(yy), array(zz), levels=[0.5, 1, 2, 4, 8, 12, 20], colors="#b0b8b7")
    coarse = torch.linspace(-2.5, 2.5, 11, dtype=DTYPE)
    vy, vx = torch.meshgrid(coarse, coarse, indexing="ij")
    gx, gy = 2*vx+vy, 6*vy+vx
    scale = torch.sqrt(gx**2+gy**2).clamp_min(1)
    ax.quiver(array(vx), array(vy), array(-gx/scale), array(-gy/scale), color=TEAL, alpha=0.7)
    position = torch.tensor([2.5, 2.], dtype=DTYPE)
    trajectory = [position.clone()]
    for _ in range(25):
        position = position-0.15*torch.tensor([[2., 1.], [1., 6.]], dtype=DTYPE)@position
        trajectory.append(position.clone())
    trajectory = torch.stack(trajectory)
    ax.plot(array(trajectory[:, 0]), array(trajectory[:, 1]), "o-", color=ORANGE, markersize=3)
    ax.set(xlabel="参数 x₁", ylabel="参数 x₂", title="等高线、负梯度与下降路径", aspect="equal")
    save(fig, folder, "gradient_field", figures)
    def f(v):
        return v[0]**2+3*v[1]**2+v[0]*v[1]
    at = torch.tensor([1., 2.], dtype=DTYPE)
    torch.testing.assert_close(torch.func.grad(f)(at), torch.tensor([4., 13.], dtype=DTYPE))
    torch.testing.assert_close(torch.func.hessian(f)(at), torch.tensor([[2., 1.], [1., 6.]], dtype=DTYPE))
    checks["gradient_hessian"] = "matches analytic gradient and Hessian"


def linear_demo(folder: Path, figures: list[str], checks: dict) -> None:
    angle = torch.linspace(0, 2*torch.pi, 400, dtype=DTYPE)
    circle = torch.stack([angle.cos(), angle.sin()])
    matrix = torch.tensor([[1.5, 0.7], [0.2, 0.7]], dtype=DTYPE)
    mapped = matrix @ circle
    fig, axes = plt.subplots(1, 2, figsize=(9, 3.7), layout="constrained")
    for ax, points, basis, title in zip(axes, [circle, mapped], [torch.eye(2, dtype=DTYPE), matrix],
                                       ["原坐标与单位圆", "线性变换后的椭圆"]):
        ax.plot(array(points[0]), array(points[1]))
        for i, color in enumerate([ORANGE, BLUE]):
            ax.arrow(0, 0, float(basis[0, i]), float(basis[1, i]), color=color,
                     width=0.018, length_includes_head=True)
        ax.set(xlim=(-2, 2), ylim=(-1.6, 1.6), xlabel="x₁", ylabel="x₂", title=title, aspect="equal")
        ax.axhline(0, color="#dddddd", lw=0.6)
        ax.axvline(0, color="#dddddd", lw=0.6)
    save(fig, folder, "linear_map", figures)

    u = F.normalize(torch.tensor([2., 1.], dtype=DTYPE), dim=0)
    x = torch.tensor([1., 2.5], dtype=DTYPE)
    projected = (u@x)*u
    fig, ax = plt.subplots(figsize=(6, 4), layout="constrained")
    ax.plot([-1, 3], [-0.5, 1.5], "--", color="#999999", label="投影子空间")
    for endpoint, color, label in [(x, BLUE, "原向量 x"), (projected, TEAL, "正交投影")]:
        ax.arrow(0, 0, float(endpoint[0]), float(endpoint[1]), color=color,
                 width=0.02, length_includes_head=True, label=label)
    ax.plot([float(x[0]), float(projected[0])], [float(x[1]), float(projected[1])], ":",
            color=ORANGE, label="与子空间正交的残差")
    ax.set(xlim=(-0.6, 3), ylim=(-0.4, 3), xlabel="x₁", ylabel="x₂", aspect="equal", title="投影是最近点")
    ax.legend(fontsize=8)
    save(fig, folder, "projection", figures)
    design = torch.tensor([[1., 0.], [1., 1.], [1., 2.]], dtype=DTYPE)
    target = torch.tensor([1., 2., 2.], dtype=DTYPE)
    solution = torch.linalg.lstsq(design, target).solution
    residual = target-design@solution
    torch.testing.assert_close(design.T@residual, torch.zeros(2, dtype=DTYPE), atol=1e-12, rtol=0)
    checks["least_squares_orthogonality_max_error"] = float((design.T@residual).abs().max())


def matrix_demo(folder: Path, figures: list[str], checks: dict, generator: torch.Generator) -> None:
    axis = torch.linspace(-1, 1, 80, dtype=DTYPE)
    yy, xx = torch.meshgrid(axis, axis, indexing="ij")
    image = (torch.exp(-8*((xx+0.3)**2+(yy-0.2)**2))
             + 0.65*torch.exp(-14*((xx-0.4)**2+(yy+0.3)**2))
             + 0.18*torch.sin(25*xx*yy))
    image = (image-image.min())/(image.max()-image.min())
    U, s, Vh = torch.linalg.svd(image, full_matrices=False)
    torch.testing.assert_close((U*s)@Vh, image)
    fig, axes = plt.subplots(1, 5, figsize=(12, 2.8), layout="constrained")
    axes[0].imshow(array(image), cmap="gray", vmin=0, vmax=1)
    axes[0].set_title("合成原图")
    errors = {}
    for ax, rank in zip(axes[1:4], [1, 5, 15]):
        low = (U[:, :rank]*s[:rank])@Vh[:rank]
        error = ((image-low)**2).sum()
        torch.testing.assert_close(error, s[rank:].square().sum(), atol=1e-9, rtol=1e-9)
        errors[str(rank)] = float(error)
        ax.imshow(array(low), cmap="gray", vmin=0, vmax=1)
        ax.set_title(f"秩 {rank}；MSE={float(error/image.numel()):.4f}")
    for ax in axes[:4]:
        ax.set_axis_off()
    axes[4].semilogy(range(1, len(s)+1), array(s.clamp_min(1e-12)))
    axes[4].set(xlabel="奇异值编号", ylabel="奇异值", title="衰减与有效秩")
    save(fig, folder, "low_rank", figures)
    assert errors["1"]+1e-12 >= errors["5"] and errors["5"]+1e-12 >= errors["15"]
    checks["svd_squared_error_by_rank"] = errors

    raw = torch.randn(180, 2, dtype=DTYPE, generator=generator)
    data = raw@torch.tensor([[1.2, 0.8], [0.0, 0.25]], dtype=DTYPE) + torch.tensor([1., 1.])
    centered = data-data.mean(0)
    _, values, directions = torch.linalg.svd(centered, full_matrices=False)
    direction = directions[0]
    reconstructed = (centered@direction[:, None])@direction[None, :]
    fig, ax = plt.subplots(figsize=(6.5, 4), layout="constrained")
    ax.scatter(array(centered[:, 0]), array(centered[:, 1]), s=12, alpha=0.45, label="中心化样本")
    ax.scatter(array(reconstructed[:, 0]), array(reconstructed[:, 1]), s=8, alpha=0.5, color=ORANGE, label="秩 1 重构")
    line = torch.tensor([-4., 4.])[:, None]*direction[None, :]
    ax.plot(array(line[:, 0]), array(line[:, 1]), color=ORANGE)
    ax.set(xlabel="特征 1", ylabel="特征 2", aspect="equal", title="PCA：用一条直线保留主要变化")
    ax.legend()
    save(fig, folder, "pca_geometry", figures)
    covariance = centered.T@centered/(len(data)-1)
    torch.testing.assert_close(torch.linalg.eigvalsh(covariance).flip(0), values.square()/(len(data)-1))
    checks["covariance_min_eigenvalue"] = float(torch.linalg.eigvalsh(covariance).min())


def probability_demo(folder: Path, figures: list[str], checks: dict, generator: torch.Generator) -> None:
    prevalence = torch.linspace(0.001, 0.3, 300, dtype=DTYPE)
    posterior = 0.9*prevalence/(0.9*prevalence+0.05*(1-prevalence))
    fig, ax = plt.subplots(figsize=(6.5, 3.5), layout="constrained")
    ax.plot(array(prevalence*100), array(posterior*100))
    exact = 0.009/(0.009+0.0495)
    ax.scatter([1], [exact*100], color=ORANGE, zorder=3, label="故障率 1%：告警中约 15.4% 真故障")
    ax.set(xlabel="故障基准率（%）", ylabel="告警后的故障概率（%）", title="检出率 90%，正常误报率 5%")
    ax.legend(fontsize=8)
    save(fig, folder, "bayes_base_rate", figures)
    checks["bayes_posterior"] = exact

    x = torch.linspace(-2, 2, 600, dtype=DTYPE)
    noise = torch.randn(600, dtype=DTYPE, generator=generator)
    ys = [x+0.4*noise, x.square(), torch.randn(600, dtype=DTYPE, generator=generator)]
    fig, axes = plt.subplots(1, 3, figsize=(10, 3.1), layout="constrained")
    for ax, y, title in zip(axes, ys, ["线性相关", "非线性依赖", "独立生成"]):
        correlation = torch.corrcoef(torch.stack([x, y]))[0, 1]
        ax.scatter(array(x), array(y), s=5, alpha=0.5)
        ax.set(xlabel="X", ylabel="Y", title=f"{title}；r={float(correlation):.3f}")
    save(fig, folder, "dependence", figures)
    assert abs(float(torch.corrcoef(torch.stack([x, x.square()]))[0, 1])) < 1e-12
    checks["uncorrelated_dependent_example"] = "Y=X^2 with symmetric X"

    # Exponential(1) draws via inverse-CDF; independent replicates per sample size.
    fig, axes = plt.subplots(1, 4, figsize=(11, 3), layout="constrained")
    original = -torch.rand(10000, dtype=DTYPE, generator=generator).clamp_min(1e-15).log()
    axes[0].hist(array(original), bins=45, density=True, color=TEAL, alpha=0.7)
    axes[0].set(xlabel="原始样本", ylabel="密度", title="指数分布：偏斜")
    curve = torch.linspace(-4, 4, 400, dtype=DTYPE)
    standard_normal = torch.distributions.Normal(0., 1.).log_prob(curve).exp()
    for ax, n in zip(axes[1:], [2, 10, 50]):
        draws = -torch.rand(4000, n, dtype=DTYPE, generator=generator).clamp_min(1e-15).log()
        standardized = (draws.mean(1)-1)*n**0.5
        ax.hist(array(standardized), bins=45, density=True, alpha=0.6, color=TEAL)
        ax.plot(array(curve), array(standard_normal), color=ORANGE, label="标准正态")
        ax.set(xlim=(-4, 4), xlabel="√n × (均值−1)", title=f"每次取 n={n} 个")
    axes[-1].legend(fontsize=8)
    save(fig, folder, "central_limit", figures)


def statistics_demo(folder: Path, figures: list[str], checks: dict, generator: torch.Generator) -> None:
    data = 2+torch.randn(50, dtype=DTYPE, generator=generator)
    indices = torch.randint(len(data), (3000, len(data)), generator=generator)
    means = data[indices].mean(1)
    interval = torch.quantile(means, torch.tensor([0.025, 0.975], dtype=DTYPE))
    fig, ax = plt.subplots(figsize=(7, 3.7), layout="constrained")
    ax.hist(array(means), bins=45, density=True, alpha=0.7, color=TEAL)
    for endpoint in interval:
        ax.axvline(float(endpoint), color=ORANGE, linestyle="--")
    ax.axvline(float(data.mean()), color=BLUE, label="观测样本均值")
    ax.set(xlabel="重采样后的均值", ylabel="密度", title="同一批 50 个观测的 bootstrap（3000 次）")
    ax.legend()
    save(fig, folder, "bootstrap", figures)
    assert interval[0] < interval[1]
    checks["bootstrap_mean_percentile_interval"] = interval.tolist()


def information_demo(folder: Path, figures: list[str], checks: dict) -> None:
    p = torch.linspace(0.001, 0.999, 400, dtype=DTYPE)
    entropy = -p*p.log()-(1-p)*(1-p).log()
    truth = torch.tensor(0.7, dtype=DTYPE)
    h = -truth*truth.log()-(1-truth)*(1-truth).log()
    ce = -truth*p.log()-(1-truth)*(1-p).log()
    fig, axes = plt.subplots(1, 2, figsize=(10, 3.7), layout="constrained")
    axes[0].plot(array(p), array(entropy/torch.log(torch.tensor(2.))))
    axes[0].set(xlabel="Bernoulli 概率 p", ylabel="熵（bit）", title="p=0.5 时最不确定")
    axes[1].plot(array(p), array(ce), label="交叉熵 H(P,Q)")
    axes[1].plot(array(p), array(ce-h), label="KL(P||Q)")
    axes[1].axvline(0.7, linestyle=":", color="#777777")
    axes[1].set(xlabel="模型概率 q", ylabel="nat", title="真实概率固定为 0.7", ylim=(0, 3))
    axes[1].legend()
    save(fig, folder, "entropy_kl", figures)
    probabilities = torch.tensor([0.7, 0.3], dtype=DTYPE)
    log_q = F.log_softmax(torch.tensor([1., -0.5], dtype=DTYPE), dim=0)
    hp = -(probabilities*probabilities.log()).sum()
    cross = -(probabilities*log_q).sum()
    kl = (probabilities*(probabilities.log()-log_q)).sum()
    torch.testing.assert_close(cross, hp+kl)
    assert kl >= 0
    logits = torch.tensor([[2., 0., -1.], [0., 2., 1.]], dtype=DTYPE)
    labels = torch.tensor([0, 2])
    manual = -F.log_softmax(logits, 1)[torch.arange(2), labels].mean()
    torch.testing.assert_close(F.cross_entropy(logits, labels), manual)
    checks["information_identity"] = {"entropy": float(hp), "cross_entropy": float(cross), "kl": float(kl)}


def optimization_demo(folder: Path, figures: list[str], checks: dict, generator: torch.Generator) -> None:
    H = torch.diag(torch.tensor([1., 12.], dtype=DTYPE))
    fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), layout="constrained")
    axis = torch.linspace(-3.3, 3.3, 150, dtype=DTYPE)
    yy, xx = torch.meshgrid(axis, axis, indexing="ij")
    axes[0].contour(array(xx), array(yy), array((xx**2+12*yy**2)/2), levels=[0.1, 0.5, 2, 5, 10, 25, 50], colors="#c3c9c7")
    final_losses = {}
    for lr, title in [(0.02, "步长 0.02"), (0.15, "步长 0.15"), (0.19, "步长 0.19：发散")]:
        x = torch.tensor([3., 1.2], dtype=DTYPE)
        positions, losses = [x.clone()], []
        for _ in range(50):
            losses.append(float(0.5*x@H@x))
            x = x-lr*(H@x)
            positions.append(x.clone())
        positions = torch.stack(positions)
        axes[0].plot(array(positions[:, 0]), array(positions[:, 1]), ".-", markersize=2, label=title)
        axes[1].semilogy(losses, label=title)
        final_losses[str(lr)] = losses[-1]
        if lr < 2/12:
            assert all(b <= a+1e-12 for a, b in zip(losses, losses[1:]))
    axes[0].set(xlim=(-3.3, 3.3), ylim=(-2, 2), xlabel="x₁", ylabel="x₂", title="同一起点，不同步长")
    axes[1].set(xlabel="迭代", ylabel="目标值（对数轴）", title="理论上界：步长 < 2/12")
    axes[1].legend(fontsize=8)
    save(fig, folder, "optimization", figures)
    checks["quadratic_final_losses"] = final_losses

    x = torch.linspace(-1, 1, 16, dtype=DTYPE)
    y = torch.sin(3*x)+0.18*torch.randn(len(x), dtype=DTYPE, generator=generator)
    grid = torch.linspace(-1.05, 1.05, 350, dtype=DTYPE)
    powers = torch.arange(11, dtype=DTYPE)
    design, dense = x[:, None]**powers, grid[:, None]**powers
    penalty = torch.eye(11, dtype=DTYPE)
    penalty[0, 0] = 0
    fig, ax = plt.subplots(figsize=(7.5, 3.8), layout="constrained")
    ax.scatter(array(x), array(y), color="black", s=18, label="训练观测", zorder=3)
    ax.plot(array(grid), array(torch.sin(3*grid)), color="#aaaaaa", linestyle="--", label="合成真实函数")
    for regularizer in [1e-8, 0.01, 2.0]:
        # An augmented least-squares system avoids explicit normal equations.
        augmented = torch.cat([design, regularizer**0.5*penalty])
        target = torch.cat([y, torch.zeros(11, dtype=DTYPE)])
        weights = torch.linalg.lstsq(augmented, target).solution
        ax.plot(array(grid), array(dense@weights), label=f"λ={regularizer:g}")
    ax.set(xlabel="x", ylabel="预测", title="固定十次多项式，改变 L2 正则强度", ylim=(-1.7, 1.7))
    ax.legend(fontsize=8)
    save(fig, folder, "regularization", figures)


def numerical_demo(folder: Path, figures: list[str], checks: dict) -> None:
    steps = torch.logspace(-10, -1, 100, dtype=DTYPE)
    fig, ax = plt.subplots(figsize=(7, 3.6), layout="constrained")
    for dtype, name in [(torch.float32, "float32"), (torch.float64, "float64")]:
        x = torch.tensor(0.7, dtype=dtype)
        h = steps.to(dtype)
        finite = ((x+h).sin()-(x-h).sin())/(2*h)
        error = (finite.to(DTYPE)-torch.cos(torch.tensor(0.7, dtype=DTYPE))).abs()
        ax.loglog(array(steps), array(error.clamp_min(1e-16)), label=name)
    ax.set(xlabel="中心差分步长 h", ylabel="导数绝对误差", title="步长过小，舍入误差占主导")
    ax.legend()
    save(fig, folder, "stability", figures)
    z = torch.tensor([1000., 1001., 999.], dtype=DTYPE)
    naive = z.exp()/z.exp().sum()
    stable = z.softmax(0)
    assert not torch.isfinite(naive).all()
    assert torch.isfinite(stable).all()
    torch.testing.assert_close(stable.sum(), torch.tensor(1., dtype=DTYPE))
    checks["stable_softmax"] = {"naive_nonfinite": True, "stable_probabilities": stable.tolist()}


def signals_demo(folder: Path, figures: list[str], checks: dict) -> None:
    fine = torch.linspace(0, 0.01, 1000, dtype=DTYPE)
    samples = torch.arange(11, dtype=DTYPE)/1000
    low = torch.cos(2*torch.pi*100*samples)
    high = torch.cos(2*torch.pi*900*samples)
    torch.testing.assert_close(low, high, atol=1e-12, rtol=0)
    fig, ax = plt.subplots(figsize=(8, 3.5), layout="constrained")
    ax.plot(array(fine), array(torch.cos(2*torch.pi*100*fine)), label="100 Hz 余弦")
    ax.plot(array(fine), array(torch.cos(2*torch.pi*900*fine)), alpha=0.6, label="900 Hz 余弦")
    ax.scatter(array(samples), array(low), color="black", s=25, zorder=4, label="1000 Hz 采样点")
    ax.set(xlabel="时间（秒）", ylabel="幅值", title="不同连续信号，同一离散观测")
    ax.legend(fontsize=8)
    save(fig, folder, "aliasing", figures)
    checks["aliasing_max_sample_difference"] = float((low-high).abs().max())

    fs = 8000
    t = torch.arange(fs, dtype=DTYPE)/fs
    waveform = torch.where(t < 0.5, torch.sin(2*torch.pi*440*t), torch.sin(2*torch.pi*880*t))
    frequency = torch.fft.rfftfreq(len(waveform), d=1/fs)
    amplitude = 2*torch.fft.rfft(waveform).abs()/len(waveform)
    stft = torch.stft(waveform, n_fft=256, hop_length=64,
                      window=torch.hann_window(256, dtype=DTYPE), return_complex=True)
    power = stft.abs().square()
    db = 10*torch.log10(power.clamp_min(1e-12)/power.max())
    times = torch.arange(stft.shape[-1], dtype=DTYPE)*64/fs
    frequencies = torch.fft.rfftfreq(256, d=1/fs)
    fig, axes = plt.subplots(1, 3, figsize=(11.5, 3.3), layout="constrained")
    axes[0].plot(array(t[:400]), array(waveform[:400]), lw=0.8)
    axes[0].set(xlabel="秒", ylabel="幅值", title="波形局部：最初 0.05 秒")
    axes[1].plot(array(frequency), array(amplitude))
    axes[1].set(xlim=(0, 1500), xlabel="Hz", ylabel="单边幅度（未加窗）", title="全段 FFT：无法定位出现时间")
    mesh = axes[2].pcolormesh(array(times), array(frequencies), array(db), shading="auto", cmap="magma", vmin=-60, vmax=0)
    axes[2].set(xlabel="秒", ylabel="Hz", ylim=(0, 1500), title="STFT：前 440 Hz，后 880 Hz")
    fig.colorbar(mesh, ax=axes[2], label="相对最大功率（dB）")
    save(fig, folder, "signal_spectrum", figures)
    tone = torch.sin(2*torch.pi*440*t)
    peak = float(frequency[torch.fft.rfft(tone).abs().argmax()])
    assert abs(peak-440) < 1e-6
    checks["fft_peak_hz"] = peak


def attention_demo(folder: Path, figures: list[str], checks: dict, generator: torch.Generator) -> None:
    X = torch.randn(5, 8, dtype=DTYPE, generator=generator)
    scores = X@X.T/(X.shape[-1]**0.5)
    future = torch.triu(torch.ones(5, 5, dtype=torch.bool), diagonal=1)
    full = scores.softmax(-1)
    causal = scores.masked_fill(future, -torch.inf).softmax(-1)
    torch.testing.assert_close(causal.sum(-1), torch.ones(5, dtype=DTYPE))
    assert torch.count_nonzero(causal[future]) == 0
    fig, axes = plt.subplots(1, 2, figsize=(9, 3.8), layout="constrained")
    for ax, weights, title in zip(axes, [full, causal], ["无 mask：可看全部位置", "causal mask：不能看未来"]):
        mesh = ax.imshow(array(weights), vmin=0, vmax=1, cmap="YlGnBu")
        ax.set(xticks=range(5), yticks=range(5), xlabel="Key 位置", ylabel="Query 位置", title=title)
        for i in range(5):
            for j in range(5):
                ax.text(j, i, f"{float(weights[i,j]):.2f}", ha="center", va="center",
                        color="white" if weights[i,j] > 0.6 else "black", fontsize=8)
    fig.colorbar(mesh, ax=axes, label="权重", shrink=0.75)
    save(fig, folder, "attention", figures)
    checks["causal_attention"] = {"row_sums": causal.sum(-1).tolist(), "future_nonzero": 0,
                                  "output_shape": list((causal@X).shape)}


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output-dir", type=Path, default=Path("artifacts/math"))
    parser.add_argument("--seed", type=int, default=7)
    args = parser.parse_args()
    started = perf_counter()
    torch.set_num_threads(1)
    torch.manual_seed(args.seed)
    generator = torch.Generator(device="cpu").manual_seed(args.seed)
    args.output_dir.mkdir(parents=True, exist_ok=True)
    font = configure_plots()
    figures, checks = [], {}
    tensor_demo(args.output_dir, figures, checks)
    calculus_demo(args.output_dir, figures, checks)
    gradient_demo(args.output_dir, figures, checks)
    linear_demo(args.output_dir, figures, checks)
    matrix_demo(args.output_dir, figures, checks, generator)
    probability_demo(args.output_dir, figures, checks, generator)
    statistics_demo(args.output_dir, figures, checks, generator)
    information_demo(args.output_dir, figures, checks)
    optimization_demo(args.output_dir, figures, checks, generator)
    numerical_demo(args.output_dir, figures, checks)
    signals_demo(args.output_dir, figures, checks)
    attention_demo(args.output_dir, figures, checks, generator)
    from math_diagrams import render_concept_diagrams
    render_concept_diagrams(args.output_dir, figures, checks)
    result = {"environment": {"python": platform.python_version(), "platform": platform.platform(),
                              "torch": torch.__version__, "matplotlib": matplotlib.__version__,
                              "device": "cpu", "dtype": "float64 (except numerical comparison)",
                              "torch_threads": torch.get_num_threads(), "plot_font": font},
              "seed": args.seed, "figures": figures, "checks": checks,
              "elapsed_seconds": perf_counter()-started}
    (args.output_dir/"report.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"figures": len(figures), "checks": len(checks), "output": str(args.output_dir.resolve()),
                      "elapsed_seconds": round(result["elapsed_seconds"], 2),
                      "torch": torch.__version__}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
