"""Concept figures for the mathematics text; called by math_foundations.py.

All illustrations are original, generated with PyTorch and Matplotlib.
"""

from __future__ import annotations

from pathlib import Path

import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch, FancyBboxPatch
import torch
import torch.nn.functional as F


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


def arr(x):
    return x.detach().cpu().numpy()


def canvas(width=10, height=4, xlim=(0, 10), ylim=(0, 4)):
    fig, ax = plt.subplots(figsize=(width, height), layout="constrained")
    ax.set(xlim=xlim, ylim=ylim)
    ax.axis("off")
    return fig, ax


def box(ax, center, label, width=1.3, height=0.7, color=TEAL, size=11):
    x, y = center
    ax.add_patch(FancyBboxPatch((x-width/2, y-height/2), width, height,
                                boxstyle="round,pad=0.05,rounding_size=0.08",
                                edgecolor=color, facecolor="#f8faf9", linewidth=1.4, zorder=3))
    ax.text(x, y, label, ha="center", va="center", fontsize=size, zorder=4)


def arrow(ax, start, end, label=None, color=TEAL, offset=(0, 0.12), curved=0):
    ax.add_patch(FancyArrowPatch(start, end, arrowstyle="-|>", mutation_scale=13,
                                 linewidth=1.5, color=color,
                                 connectionstyle=f"arc3,rad={curved}", zorder=2))
    if label:
        ax.text((start[0]+end[0])/2+offset[0], (start[1]+end[1])/2+offset[1], label,
                color=color, ha="center", va="center", fontsize=10,
                bbox={"facecolor":"white", "edgecolor":"none", "pad":1}, zorder=5)


def emit(fig, folder, name, figures):
    fig.savefig(folder/f"{name}.png", dpi=160, bbox_inches="tight")
    fig.savefig(folder/f"{name}.svg", bbox_inches="tight")
    plt.close(fig)
    figures.append(name)


def composition(folder, figures, checks):
    fig, ax = canvas(11, 3.8, xlim=(-.3,10), ylim=(0, 4))
    ax.text(0.3, 3.6, r"$f(x)=(x^2+1)^3$：按函数依赖逐步计算", fontsize=14)
    centers=[(0.8,2.45),(3.5,2.45),(6.2,2.45),(9.0,2.45)]
    labels=["输入 x\nx = 1", "平方 u = x²\nu = 1", "平移 v = u + 1\nv = 2", "立方 f = v³\nf = 8"]
    for c,label in zip(centers,labels):box(ax,c,label,width=1.7,height=0.85,size=11)
    derivatives=[r"$du/dx=2x=2$",r"$dv/du=1$",r"$df/dv=3v^2=12$"]
    for i,label in enumerate(derivatives):
        arrow(ax,(centers[i][0]+0.9,2.45),(centers[i+1][0]-0.9,2.45))
        ax.text((centers[i][0]+centers[i+1][0])/2,1.45,label,ha="center",color=ORANGE,fontsize=12)
    ax.text(5,0.55,r"$\Delta f\ \approx\ 12\times1\times2\,\Delta x=24\,\Delta x$",ha="center",fontsize=15,color=ORANGE)
    emit(fig,folder,"function_composition",figures)
    x=torch.tensor(1.,dtype=DTYPE,requires_grad=True)
    f=(x*x+1)**3
    (gradient,)=torch.autograd.grad(f,x)
    torch.testing.assert_close(gradient,torch.tensor(24.,dtype=DTYPE))
    checks["composition_derivative_at_one"]=float(gradient)


def neuron_graphs(folder, figures, checks):
    x=torch.tensor(2.,dtype=DTYPE,requires_grad=True)
    w=torch.tensor(1.,dtype=DTYPE,requires_grad=True)
    b=torch.tensor(-1.,dtype=DTYPE,requires_grad=True)
    z=w*x+b
    a=z.tanh()
    r=a-.5
    loss=.5*r*r
    loss.backward()
    delta=r.detach()*(1-a.detach()**2)
    torch.testing.assert_close(w.grad,2*delta)
    torch.testing.assert_close(b.grad,delta)
    checks["neuron_forward_backward"]={"activation":float(a.detach()),"loss":float(loss.detach()),
                                        "dw":float(w.grad),"db":float(b.grad),"dx":float(x.grad)}

    fig,ax=canvas(12,4.4,xlim=(0,12),ylim=(0,4.4))
    ax.text(.2,4.05,"前向：由输入与参数计算预测，再计算损失",fontsize=14)
    box(ax,(.8,2.9),"x = 2",width=1.1)
    box(ax,(.8,1.65),"w = 1",width=1.1,color=ORANGE)
    box(ax,(3,1.1),"b = −1",width=1.1,color=ORANGE)
    box(ax,(2.9,2.9),"m = wx\nm = 2",width=1.45,height=.85)
    box(ax,(5.15,2.9),"z = m + b\nz = 1",width=1.5,height=.85)
    box(ax,(7.5,2.9),"a = tanh(z)\na ≈ 0.7616",width=1.6,height=.85)
    box(ax,(9.7,2.9),"r = a − y\nr ≈ 0.2616",width=1.6,height=.85)
    box(ax,(9.7,1.1),"y = 0.5",width=1.1,color=BLUE)
    for s,e in [((1.4,2.9),(2.1,2.9)),((1.4,1.75),(2.35,2.5)),((3.6,1.1),(4.85,2.45)),
                ((3.7,2.9),(4.35,2.9)),((5.95,2.9),(6.65,2.9)),((8.35,2.9),(8.85,2.9)),
                ((9.7,1.5),(9.7,2.4))]:arrow(ax,s,e)
    box(ax,(11.15,1.65),"L = ½r²\n≈ 0.03422",width=1.5,height=.85)
    arrow(ax,(10.5,2.65),(11.15,2.15))
    ax.text(.3,.2,"节点存中间值；每条边表示下游运算使用了上游变量。",fontsize=11,color="#596462")
    emit(fig,folder,"neuron_forward",figures)

    fig,ax=canvas(12,4.3,xlim=(0,12),ylim=(0,4.3))
    ax.text(.25,3.95,"反向：最终损失的敏感性 × 每一步的局部导数",fontsize=14)
    nodes=[(.9,2.5),(3.5,2.5),(6.15,2.5),(8.8,2.5)]
    labels=["z = 1","a = 0.7616","r = 0.2616","L = 0.03422"]
    for c,label in zip(nodes,labels):box(ax,c,label,width=1.65,height=.8,size=11)
    ax.text(11.1,2.5,"从损失开始\n设置反向种子",ha="center",va="center",fontsize=11,color=ORANGE)
    arrow(ax,(10.2,2.5),(9.65,2.5),r"$\bar L=1$",color=ORANGE,offset=(0,.65))
    arrow(ax,(7.95,2.5),(7.0,2.5),r"$\partial L/\partial r=r$",color=ORANGE,offset=(0,.65))
    arrow(ax,(5.3,2.5),(4.35,2.5),r"$\partial r/\partial a=1$",color=ORANGE,offset=(0,.65))
    arrow(ax,(2.65,2.5),(1.75,2.5),r"$\partial a/\partial z=1-a^2$",color=ORANGE,offset=(0,.65))
    ax.text(.9,1.55,r"$\bar z\approx0.10986$",ha="center",color=ORANGE,fontsize=12)
    ax.text(3.5,1.55,r"$\bar a\approx0.26159$",ha="center",color=ORANGE,fontsize=12)
    ax.text(6.15,1.55,r"$\bar r\approx0.26159$",ha="center",color=ORANGE,fontsize=12)
    ax.text(.3,.55,r"$\bar z\to \partial L/\partial w=\bar z\,x\approx0.21973,\quad"
                         r"\partial L/\partial b=\bar z\approx0.10986,\quad"
                         r"\partial L/\partial x=\bar z\,w$",fontsize=12)
    emit(fig,folder,"neuron_backward",figures)


def branch_graph(folder,figures,checks):
    fig,ax=canvas(10,4.5,ylim=(0,4.5))
    box(ax,(1,2.25),"x = 2",width=1.2)
    box(ax,(4.2,3.3),"u = x² = 4",width=1.8)
    box(ax,(4.2,1.2),"v = 3x = 6",width=1.8)
    box(ax,(8.3,2.25),"L = u + v = 10",width=2)
    arrow(ax,(1.65,2.5),(3.25,3.2),r"$du/dx=4$",offset=(0,.2))
    arrow(ax,(1.65,2.0),(3.25,1.3),r"$dv/dx=3$",offset=(0,-.2))
    arrow(ax,(5.15,3.3),(7.25,2.5),r"$\bar u=1$",offset=(0,.2))
    arrow(ax,(5.15,1.2),(7.25,2.0),r"$\bar v=1$",offset=(0,-.2))
    ax.text(1,3.8,r"$\bar x=4+3=7$",ha="center",fontsize=13,color=ORANGE)
    ax.text(5,.18,"共享输入的反向贡献相加；每条路径内部的局部导数相乘。",ha="center",fontsize=11)
    emit(fig,folder,"gradient_branches",figures)
    x=torch.tensor(2.,dtype=DTYPE,requires_grad=True)
    ((x*x)+3*x).backward()
    torch.testing.assert_close(x.grad,torch.tensor(7.,dtype=DTYPE))
    checks["branched_total_derivative"]=float(x.grad)


def layer_graph(folder,figures,checks):
    fig,ax=canvas(11,4.8,xlim=(0,11),ylim=(0,4.8))
    centers=[(1,2.8),(3.7,2.8),(6.9,2.8),(10,2.8)]
    for c,label in zip(centers,["输入 x","z = Wx + b","a = φ(z)","损失 L"]):
        box(ax,c,label,width=1.65,height=.85)
    for a,b in zip(centers,centers[1:]):arrow(ax,(a[0]+.9,2.8),(b[0]-.9,2.8))
    for start,end,label in [((9.1,1.65),(7.8,1.65),r"$\bar a$"),
                             ((6.0,1.65),(4.6,1.65),r"$\delta=\bar a\odot\phi'(z)$"),
                             ((2.8,1.65),(1.9,1.65),r"$\bar x=W^\top\delta$")]:
        arrow(ax,start,end,label,color=ORANGE,offset=(0,-.3))
    ax.text(5.5,4.1,"同一层的两个方向：表示向右，损失梯度向左",ha="center",fontsize=14)
    ax.text(5.5,.4,r"$\nabla_W L=\delta x^\top,\qquad\nabla_b L=\delta$",ha="center",fontsize=15,color=ORANGE)
    emit(fig,folder,"layer_forward_backward",figures)
    g=torch.Generator().manual_seed(31)
    x=torch.randn(3,dtype=DTYPE,generator=g,requires_grad=True)
    W=torch.randn(2,3,dtype=DTYPE,generator=g,requires_grad=True)
    b=torch.randn(2,dtype=DTYPE,generator=g,requires_grad=True)
    upstream=torch.tensor([.4,-.7],dtype=DTYPE)
    a=torch.tanh(W@x+b)
    loss=upstream@a
    loss.backward()
    delta=upstream*(1-a.detach()**2)
    torch.testing.assert_close(W.grad,delta[:,None]*x.detach()[None,:])
    torch.testing.assert_close(x.grad,W.detach().T@delta)
    torch.testing.assert_close(b.grad,delta)
    checks["layer_outer_product_gradient"]="agrees with autograd for W, x and b"


def depth(folder,figures,checks):
    layers=torch.arange(31,dtype=DTYPE)
    fig,ax=plt.subplots(figsize=(7.3,3.6),layout="constrained")
    for value in [.7,1.,1.3]:ax.semilogy(arr(layers),arr(value**layers),label=f"局部导数恒为 {value}")
    ax.set(xlabel="复合层数",ylabel="总导数绝对值（对数轴）",title="简化标量模型：连乘会改变梯度尺度")
    ax.legend()
    emit(fig,folder,"gradient_depth",figures)


def broadcast(folder,figures,checks):
    fig,axes=plt.subplots(1,2,figsize=(9,3.5),layout="constrained")
    prediction=torch.tensor([[1.],[2.],[3.]])
    target=torch.tensor([1.,2.,3.])
    values=[prediction-target,(prediction.squeeze(-1)-target)[:,None]]
    for ax,values,title in zip(axes,values,["[3,1] − [3] → [3,3]","先对齐形状 → 逐样本差值"]):
        ax.imshow(arr(values),cmap="RdBu_r",vmin=-2,vmax=2,aspect="equal")
        for i in range(values.shape[0]):
            for j in range(values.shape[1]):ax.text(j,i,f"{float(values[i,j]):g}",ha="center",va="center",fontsize=13)
        ax.set(title=title,xlabel="比较的标签位置",ylabel="预测样本位置",yticks=range(3),xticks=range(values.shape[1]))
    emit(fig,folder,"broadcast_comparison",figures)


def basis_and_svd(folder,figures,checks):
    fig,axes=plt.subplots(1,2,figsize=(9,3.8),layout="constrained")
    theta=torch.tensor(torch.pi/5,dtype=DTYPE)
    Q=torch.stack([torch.stack([theta.cos(),-theta.sin()]),torch.stack([theta.sin(),theta.cos()])])
    point=torch.tensor([1.5,1.],dtype=DTYPE)
    for ax,basis,title in zip(axes,[torch.eye(2,dtype=DTYPE),Q],["标准正交基","旋转后的正交基"]):
        for k,color in enumerate([TEAL,ORANGE]):ax.arrow(0,0,float(basis[0,k]),float(basis[1,k]),width=.02,color=color,length_includes_head=True)
        ax.scatter([float(point[0])],[float(point[1])],color=BLUE,s=35)
        coordinates=basis.T@point
        ax.text(.1,1.8,f"同一点；坐标 ({float(coordinates[0]):.2f}, {float(coordinates[1]):.2f})",fontsize=10)
        ax.set(xlim=(-1,2.2),ylim=(-.8,2.1),aspect="equal",xlabel="物理平面横轴",ylabel="物理平面纵轴",title=title)
        ax.axhline(0,color="#dddddd");ax.axvline(0,color="#dddddd")
    emit(fig,folder,"basis_coordinates",figures)

    t=torch.linspace(0,2*torch.pi,250,dtype=DTYPE)
    # Nonuniformly spaced boundary points make the first rotation visible.
    t=t+.2*t.sin()
    points=torch.stack([t.cos(),t.sin()])
    D=torch.diag(torch.tensor([1.8,.55],dtype=DTYPE))
    U=torch.tensor([[.8,-.6],[.6,.8]],dtype=DTYPE)
    stages=[points,Q.T@points,D@Q.T@points,U@D@Q.T@points]
    fig,axes=plt.subplots(1,4,figsize=(11,3),layout="constrained")
    for ax,p,title in zip(axes,stages,["输入圆","Vᵀ：改变正交方向","Σ：各方向缩放","U：映射到输出方向"]):
        ax.scatter(arr(p[0]),arr(p[1]),c=arr(t),cmap="viridis",s=5)
        ax.set(aspect="equal",xlim=(-2,2),ylim=(-2,2),xlabel="坐标 1",ylabel="坐标 2",title=title)
    emit(fig,folder,"svd_stages",figures)


def joint_and_covariance(folder,figures,checks):
    axis=torch.linspace(-3,3,151,dtype=DTYPE)
    yy,xx=torch.meshgrid(axis,axis,indexing="ij")
    fig,axes=plt.subplots(1,3,figsize=(10,3.3),layout="constrained")
    for ax,rho in zip(axes,[-.8,0,.8]):
        density=torch.exp(-(xx**2-2*rho*xx*yy+yy**2)/(2*(1-rho*rho)))/(2*torch.pi*(1-rho*rho)**.5)
        ax.contour(arr(xx),arr(yy),arr(density),levels=7)
        ax.set(aspect="equal",xlabel="X",ylabel="Y",title=f"联合高斯；相关系数 {rho:g}")
    emit(fig,folder,"covariance_ellipses",figures)

    # Rows index X, columns index Y; all probabilities sum to one.
    joint=torch.tensor([[.36,.04],[.12,.48]],dtype=DTYPE)
    conditional=joint/joint.sum(1,keepdim=True)
    fig,axes=plt.subplots(1,3,figsize=(10,3.3),layout="constrained")
    for ax,matrix,title in zip(axes[:2],[joint,conditional],["联合概率 P(X,Y)","逐行条件化 P(Y|X)"]):
        ax.imshow(arr(matrix),cmap="YlGnBu",vmin=0,vmax=1)
        for i in range(2):
            for j in range(2):ax.text(j,i,f"{float(matrix[i,j]):.2f}",ha="center",va="center",fontsize=14,
                                    color="white" if matrix[i,j]>.6 else "black")
        ax.set(xticks=[0,1],yticks=[0,1],xlabel="Y",ylabel="X",title=title)
    axes[2].bar([0,1],arr(joint.sum(0)),color=[TEAL,ORANGE])
    axes[2].set(xticks=[0,1],xlabel="Y",ylabel="边缘概率",ylim=(0,1),title="对 X 求和得到 P(Y)")
    emit(fig,folder,"joint_conditionals",figures)
    torch.testing.assert_close(conditional.sum(1),torch.ones(2,dtype=DTYPE))
    checks["joint_conditional_normalization"]=conditional.tolist()


def posterior(folder,figures,checks):
    theta=torch.linspace(.001,.999,700,dtype=DTYPE)
    prior=torch.distributions.Beta(torch.tensor(2.,dtype=DTYPE),torch.tensor(2.,dtype=DTYPE))
    post=torch.distributions.Beta(torch.tensor(9.,dtype=DTYPE),torch.tensor(5.,dtype=DTYPE))
    likelihood=theta**7*(1-theta)**3
    likelihood=likelihood/torch.trapezoid(likelihood,theta)
    fig,ax=plt.subplots(figsize=(7.5,3.7),layout="constrained")
    ax.plot(arr(theta),arr(prior.log_prob(theta).exp()),label="先验 Beta(2,2)")
    ax.plot(arr(theta),arr(likelihood),"--",label="似然（缩放到单位面积，仅便于比较）")
    ax.plot(arr(theta),arr(post.log_prob(theta).exp()),label="后验 Beta(9,5)")
    ax.set(xlabel="未知成功率 θ",ylabel="密度 / 缩放曲线",title="观测 10 次，其中成功 7 次")
    ax.legend(fontsize=9)
    emit(fig,folder,"likelihood_posterior",figures)


def bias_variance(folder,figures,checks):
    g=torch.Generator().manual_seed(19)
    x=torch.linspace(-1,1,16,dtype=DTYPE)
    grid=torch.linspace(-1,1,160,dtype=DTYPE)
    fig,axes=plt.subplots(1,3,figsize=(10.5,3.5),layout="constrained")
    for ax,degree in zip(axes,[1,3,10]):
        for _ in range(12):
            y=torch.sin(3*x)+.25*torch.randn(len(x),dtype=DTYPE,generator=g)
            powers=torch.arange(degree+1,dtype=DTYPE)
            fit=torch.linalg.lstsq(x[:,None]**powers,y).solution
            ax.plot(arr(grid),arr((grid[:,None]**powers)@fit),color=TEAL,alpha=.23,lw=.8)
        ax.plot(arr(grid),arr(torch.sin(3*grid)),color=ORANGE,label="真实回归函数")
        ax.set(xlabel="x",ylabel="预测",ylim=(-2,2),title=f"{degree} 次多项式；重复抽样拟合")
    axes[-1].legend(fontsize=8)
    emit(fig,folder,"bias_variance",figures)


def information_and_convexity(folder,figures,checks):
    fig,axes=plt.subplots(1,3,figsize=(10,3.2),layout="constrained")
    for ax,counts,title in zip(axes,[[4,4],[4,0],[0,4]],["分裂前：两类各半","左分支：纯类别 A","右分支：纯类别 B"]):
        ax.bar([0,1],counts,color=[TEAL,ORANGE])
        ax.set(xticks=[0,1],xticklabels=["A","B"],ylim=(0,5),ylabel="样本数",title=title)
        entropy=1 if counts[0]==counts[1] else 0
        ax.text(.5,4.5,f"标签熵 = {entropy} bit",ha="center",fontsize=11)
    emit(fig,folder,"information_gain",figures)

    x=torch.linspace(-2,2,400,dtype=DTYPE)
    fig,axes=plt.subplots(1,2,figsize=(9,3.6),layout="constrained")
    for ax,values,title in zip(axes,[x*x,x**4-2*x*x],["凸：弦不低于函数曲线","非凸：存在违反条件的弦"]):
        ax.plot(arr(x),arr(values))
        ends=torch.tensor([-1.3,1.3],dtype=DTYPE)
        fends=ends**2 if title.startswith("凸") else ends**4-2*ends**2
        ax.plot(arr(ends),arr(fends),"o--",color=ORANGE,label="连接两端点的弦")
        ax.set(xlabel="x",ylabel="f(x)",title=title)
        ax.legend(fontsize=8)
    emit(fig,folder,"convexity",figures)


def convolution_and_density(folder,figures,checks):
    x=torch.tensor([0.,0.,0.,1.,1.,1.,0.,0.,0.],dtype=DTYPE)
    kernel=torch.ones(1,1,3,dtype=DTYPE)/3
    output=F.conv1d(x[None,None,:],kernel,padding=1).squeeze()
    fig,axes=plt.subplots(1,3,figsize=(10.5,3.3),layout="constrained")
    for ax,data,title in zip(axes,[x,kernel.flatten(),output],["输入：突变边界","核：三个位置取平均","输出：平滑也改变边界"]):
        ax.stem(range(len(data)),arr(data),basefmt=" ")
        ax.set(xlabel="离散位置",ylabel="值",ylim=(-.1,1.2),title=title)
    emit(fig,folder,"convolution",figures)
    grid=torch.linspace(-4,4,500,dtype=DTYPE)
    normal=torch.distributions.Normal(0.,1.)
    px=normal.log_prob(grid).exp()
    py=normal.log_prob(grid/2).exp()/2
    fig,axes=plt.subplots(1,2,figsize=(9,3.4),layout="constrained")
    axes[0].plot(arr(grid),arr(px),label="X ~ N(0,1)")
    axes[1].plot(arr(grid*2),arr(px/2),color=ORANGE,label="Y=2X 的密度")
    for ax in axes:ax.set(xlabel="数值",ylabel="密度",ylim=(0,.45));ax.legend()
    axes[0].set_title("原分布：宽度较小、密度较高")
    axes[1].set_title("坐标放大两倍，密度缩小一半")
    emit(fig,folder,"density_transform",figures)


def first_steps(folder, figures, checks):
    time = torch.tensor([1., 2.], dtype=DTYPE)
    target = torch.tensor([3., 5.], dtype=DTYPE)
    prediction = time+1
    per_item = (prediction-target).square()
    mean_loss = per_item.mean()
    torch.testing.assert_close(mean_loss, torch.tensor(2.5, dtype=DTYPE))
    fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), layout="constrained")
    axes[0].scatter(arr(time), arr(target), color=TEAL, label="实际记录 y", zorder=4)
    axes[0].scatter(arr(time), arr(prediction), marker="x", s=65, color=ORANGE,
                    label="预测：时间 × 1 + 1", zorder=4)
    for t, truth, pred in zip(time, target, prediction):
        axes[0].plot([float(t),float(t)], [float(pred),float(truth)], "--", color=BLUE)
        axes[0].annotate(f"相差 {float(truth-pred):.0f}",
                         (float(t)+.07,float((truth+pred)/2)), fontsize=11)
    axes[0].set(xlabel="时间（小时）", ylabel="路程（千米）", xlim=(.5,2.6),
                ylim=(0,6), xticks=[1,2], title="先比较同一次步行")
    axes[0].legend(fontsize=9, loc="upper left")
    axes[1].bar([1,2],arr(per_item),color=[TEAL,ORANGE],width=.5)
    axes[1].axhline(float(mean_loss),color=BLUE,ls="--",label="平均损失 = (1+4)/2 = 2.5")
    axes[1].set(xlabel="记录编号",ylabel="平方误差（千米²）",xticks=[1,2],ylim=(0,5),
                title="再将误差平方并平均")
    for i,v in enumerate(per_item,1):
        axes[1].text(i,float(v)+.1,f"{float(v):.0f}",ha="center")
    axes[1].legend(fontsize=9,loc="upper left")
    emit(fig,folder,"loss_first_steps",figures)
    checks["first_prediction_loss"]={"prediction":prediction.tolist(),
                                     "squared_errors":per_item.tolist(),"mean_loss":float(mean_loss)}

    fig, ax = canvas(12, 4.3, xlim=(0,12),ylim=(0,4.3))
    panels = [
        (.35,"标量：一个数","25","形状 []；0 条轴"),
        (3.35,"向量：一组数","[80, 90]","形状 [2]；1 条轴"),
        (6.35,"矩阵：一张表","80     90\n70    100","形状 [2, 2]；2 条轴"),
        (9.35,"张量：两天的表","第 0 天：2 × 2 表\n第 1 天：2 × 2 表","形状 [2, 2, 2]；3 条轴")]
    for left,title,content,shape in panels:
        ax.text(left,3.7,title,fontsize=12,ha="left")
        box(ax,(left+1.05,2.35),content,width=2.15,height=1.45,size=12)
        ax.text(left+1.05,1.15,shape,ha="center",fontsize=11)
    ax.text(6,.35,"每增加一条轴，就多一个定位数字的编号：例如 日期 → 同学 → 科目。",
             ha="center",fontsize=12,color=TEAL)
    emit(fig,folder,"tensor_first_steps",figures)
    table=torch.tensor([[80.,90.],[70.,100.]],dtype=DTYPE)
    torch.testing.assert_close(table.mean(0),torch.tensor([75.,95.],dtype=DTYPE))
    checks["tensor_table_means"]={"by_subject":table.mean(0).tolist(),
                                 "by_student":table.mean(1).tolist()}


def monte_carlo_introduction(folder, figures, checks):
    generator=torch.Generator().manual_seed(31)
    points=torch.rand(600,2,dtype=DTYPE,generator=generator)
    inside=points[:,1] < points[:,0].square()
    grid=torch.linspace(0,1,250,dtype=DTYPE)
    fig,axes=plt.subplots(1,2,figsize=(10,4.1),layout="constrained")
    axes[0].fill_between(arr(grid),0,arr(grid.square()),color=TEAL,alpha=.15)
    axes[0].plot(arr(grid),arr(grid.square()),color=TEAL,label="曲线 y = x²")
    for flag,color,label in [(True,TEAL,"曲线下方：命中"),(False,ORANGE,"其他位置：未命中")]:
        axes[1].scatter(arr(points[inside==flag,0]),arr(points[inside==flag,1]),
                         color=color,s=9,alpha=.65,label=label)
    axes[1].plot(arr(grid),arr(grid.square()),color=BLUE,lw=1.5)
    for ax in axes:
        ax.set(xlim=(0,1),ylim=(0,1),xlabel="横坐标 x",ylabel="纵坐标 y")
        ax.set_aspect("equal")
        ax.legend(fontsize=8,loc="upper left")
    axes[0].set_title("正方形面积为 1，阴影面积待估计")
    count=int(inside.sum())
    axes[1].set_title(f"{count} / 600 个点命中，面积估计 {count/600:.3f}")
    emit(fig,folder,"monte_carlo_area",figures)

    nmax=10000
    sizes=torch.tensor([10,30,100,300,1000,3000,nmax])
    trials=torch.rand(12,nmax,2,dtype=DTYPE,generator=generator)
    hits=(trials[:,:,1] < trials[:,:,0].square()).to(DTYPE)
    running=hits.cumsum(1)/torch.arange(1,nmax+1,dtype=DTYPE)
    estimates=running[:,sizes-1]
    fig,ax=plt.subplots(figsize=(8,3.8),layout="constrained")
    for row in estimates:
        ax.plot(arr(sizes),arr(row),color=TEAL,alpha=.35,marker="o",markersize=3,lw=.9)
    ax.axhline(1/3,color=ORANGE,ls="--",label="已知答案：1/3")
    ax.set(xscale="log",xlabel="抽样点数（对数刻度）",ylabel="曲线下方面积估计",
            title="12 次独立重新抽样：波动会缩小，单次结果仍会起伏")
    ax.legend()
    emit(fig,folder,"monte_carlo_repeats",figures)

    hand_points=torch.tensor([[.2,.1],[.4,.1],[.6,.5],[.8,.5],[.9,.9]],dtype=DTYPE)
    hand_hits=hand_points[:,1] < hand_points[:,0].square()
    assert hand_hits.tolist() == [False,True,False,True,False]
    # For a hit indicator with p=1/3, the exact SE of a mean is sqrt(p(1-p)/N).
    expected_se=(torch.tensor((1/3)*(2/3),dtype=DTYPE)/sizes).sqrt()
    torch.testing.assert_close(expected_se[2]/expected_se[-1],torch.tensor(10.,dtype=DTYPE))
    checks["monte_carlo_hand_points"]={"hits":hand_hits.tolist(),"mean":float(hand_hits.to(DTYPE).mean())}
    checks["monte_carlo_repeated_sampling"]={
        "sizes":sizes.tolist(),"repetitions":12,"mean_last":float(estimates[:,-1].mean()),
        "theoretical_se_last":float(expected_se[-1]),
        "observed_sd_last":float(estimates[:,-1].std())}


def render_concept_diagrams(folder:Path,figures:list[str],checks:dict)->None:
    for draw in [composition,neuron_graphs,branch_graph,layer_graph,depth,broadcast,
                 basis_and_svd,joint_and_covariance,posterior,bias_variance,
                 information_and_convexity,convolution_and_density,first_steps,monte_carlo_introduction]:
        draw(folder,figures,checks)
