"""silab · 科学篇 07：FNO · 算子学习 —— 一条温度曲线进，一条温度曲线出
需要：sim/heat.py（科学篇 00 写的模拟器）。数据由这个脚本现场生成。
运行：python s07_operator.py，逐行对照注释里的应得输出。全部跑完二十秒左右。
会生成：s07_grids.png（你自己画的图）。
"""
import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from sim.heat import grid, simulate

# ═══ 第 1 步：造数据 ═══════════════════════════════════════════════
# 初始温度：随机放 1 到 3 个冷热斑点（高斯形，宽 0.03–0.12，高 0.3–1，有正有负），两端为 0。
# 答案：热扩散系数 1，过 T = 0.005 之后的温度，用模拟器算。
ALPHA, T = 1.0, 0.005
rng = np.random.default_rng(0)
def make_params(m):
    P = []
    for _ in range(m):
        k = rng.integers(1, 4)
        P.append([(rng.uniform(0.1, 0.9), rng.uniform(0.03, 0.12), rng.uniform(0.3, 1.0) * rng.choice([1, 1, -1])) for _ in range(k)])
    return P
def u0_of(p, x):
    u = sum(a * np.exp(-0.5 * ((x - c) / w) ** 2) for c, w, a in p)
    u = np.asarray(u, float).copy(); u[0] = u[-1] = 0
    return u
def solve(u0, n):
    dx = 1 / (n - 1)
    steps = int(np.ceil(ALPHA * T / (0.4 * dx * dx)))     # r 不超过 0.4
    r = ALPHA * T / (steps * dx * dx)
    return simulate(u0, r, steps)
TR, TE = make_params(500), make_params(100)               # 500 条训练，100 条考试
def data(P, n):
    x = grid(n)
    U0 = np.array([u0_of(p, x) for p in P]); UT = np.array([solve(u, n) for u in U0])
    return torch.tensor(U0, dtype=torch.float32), torch.tensor(UT, dtype=torch.float32)
NS = [33, 65, 129, 257]
D = {n: data(TE, n) for n in NS}                          # 同样 100 条考题，记成 4 种疏密
Xtr, Ytr = data(TR, 65)                                   # 训练只用 65 个点
def err(p, y): return float(((p - y) ** 2).mean().sqrt() / (y ** 2).mean().sqrt())
print("照抄初始温度：", "  ".join(f"{n} 点 {err(D[n][0], D[n][1]) * 100:.1f}%" for n in NS))
# 应得输出：照抄初始温度： 33 点 46.0%  65 点 45.7%  129 点 45.6%  257 点 45.6%

# ═══ 第 2 步：三种网络 ═════════════════════════════════════════════
K = 16                                                    # 谱层只用前 K 个正弦波
def sinmat(n):
    x = torch.linspace(0, 1, n)
    k = torch.arange(1, K + 1)[:, None].float()
    return torch.sin(np.pi * k * x[None])                 # 正弦表：(K, n)，第 k 行是 sin(kπx)

class Spec(nn.Module):
    """谱层：拆成 K 个正弦波，每个波乘一个学出来的数，再拼回去。"""
    def __init__(self):
        super().__init__()
        self.w = nn.Parameter(torch.ones(K))
    def forward(self, u):                                 # u：(张数, 点数)，点数随便
        n = u.shape[-1]; S = sinmat(n)
        b = 2 / (n - 1) * u @ S.T                         # 拆
        return (b * self.w) @ S                           # 乘、拼

class CNN(nn.Module):
    """三层一维卷积，核长 5。输出 = 输入 + 网络算出的变化。"""
    def __init__(self, c=16):
        super().__init__()
        self.f = nn.Sequential(nn.Conv1d(1, c, 5, padding=2), nn.ReLU(), nn.Conv1d(c, c, 5, padding=2), nn.ReLU(), nn.Conv1d(c, 1, 5, padding=2))
    def forward(self, u): return u + self.f(u[:, None])[:, 0]

class MLP(nn.Module):
    """全连接：输入正好 65 个数。"""
    def __init__(self, n=65, h=128):
        super().__init__()
        self.f = nn.Sequential(nn.Linear(n, h), nn.ReLU(), nn.Linear(h, h), nn.ReLU(), nn.Linear(h, n))
    def forward(self, u): return self.f(u)

def train(net, steps=3000):
    torch.manual_seed(0)
    opt = torch.optim.Adam(net.parameters(), 2e-3)
    sch = torch.optim.lr_scheduler.StepLR(opt, steps // 3, 0.3)
    for k in range(steps):
        i = torch.randint(0, len(Xtr), (32,))
        loss = ((net(Xtr[i]) - Ytr[i]) ** 2).mean()
        opt.zero_grad(); loss.backward(); opt.step(); sch.step()
    return net

# ═══ 第 3 步：训练，换疏密考试 ═════════════════════════════════════
nets = {}
for name, make in [("mlp", MLP), ("cnn", CNN), ("spec", Spec)]:
    torch.manual_seed(0); net = train(make()); nets[name] = net
    n_par = sum(p.numel() for p in net.parameters())
    row = []
    with torch.no_grad():
        for n in NS:
            try: row.append(f"{n} 点 {err(net(D[n][0]), D[n][1]) * 100:.2f}%")
            except RuntimeError: row.append(f"{n} 点 接不上")       # 全连接网络：输入个数对不上
    print(f"{name:5s} {n_par:6d} 个旋钮  " + "  ".join(row))
# 应得输出：
# mlp    33345 个旋钮  33 点 接不上  65 点 2.28%  129 点 接不上  257 点 接不上
# cnn     1473 个旋钮  33 点 39.65%  65 点 7.92%  129 点 25.05%  257 点 34.16%
# spec      16 个旋钮  33 点 0.38%  65 点 0.03%  129 点 0.09%  257 点 0.11%

# ═══ 第 4 步：谱层学到的 16 个数，和公式比 ═════════════════════════
exact = np.exp(-ALPHA * np.pi ** 2 * np.arange(1, K + 1) ** 2 * T)
print("学出来的", np.round(nets["spec"].w.detach().numpy(), 4))
print("公式算的", np.round(exact, 4))
# 应得输出（前 10 个）：
# 学出来的 [0.9518 0.8207 0.6407 0.4525 0.2887 0.1663 0.0866 0.041  0.0178 0.0078 ...]
# 公式算的 [0.9518 0.8209 0.6414 0.454  0.2912 0.1692 0.0891 0.0425 0.0184 0.0072 ...]

# ═══ 第 5 步：画图 ═════════════════════════════════════════════════
p = [(0.3, 0.05, 0.9), (0.7, 0.08, -0.5)]                  # 一冷一热
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
for a, n in zip(ax, [33, 257]):
    x = grid(n); u0 = u0_of(p, x); uT = solve(u0, n)
    with torch.no_grad():
        t = torch.tensor(u0, dtype=torch.float32)[None]
        pc, ps = nets["cnn"](t)[0].numpy(), nets["spec"](t)[0].numpy()
    a.plot(x, u0, color="#b9c0c8", lw=1.2, label="initial")
    a.plot(x, uT, color="black", lw=1.6, label="true (simulator)")
    a.plot(x, pc, color="#c8781a", lw=1.6, label="CNN")
    a.plot(x, ps, "--", color="#1a7f6b", lw=2, label="spectral layer")
    a.set_title(f"{n} points (both nets trained on 65)", fontsize=10); a.set_xlabel("position on the rod")
ax[0].legend(fontsize=8)
plt.tight_layout(); plt.savefig("s07_grids.png", dpi=110)
print("已保存 s07_grids.png")
