"""silab · 科学篇 08：PINN —— 把热传导方程写进损失
不需要数据文件。运行：python s08_pinn.py，逐行对照注释里的应得输出。
一共训练 5 次，每次半分钟左右，全部跑完约三分半钟。
会生成：s08_pinn.png（你自己画的图）。
"""
import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
from sim.heat import simulate
torch.set_num_threads(1)        # 只用一个线程：每次运行结果都一样，和课里的数对得上

# ═══ 第 1 步：问题 ═════════════════════════════════════════════════
# 一维热传导 u_t = α·u_xx，棒长 1，时间从 0 到 1，α = 0.1，两端温度为 0。
# 初始温度 sin(πx) + 0.5·sin(3πx)：每个正弦波各自按 e^(−αk²π²t) 变矮（科学篇 07），所以有准确答案可以核对。
ALPHA = 0.1
def exact(x, t):
    return np.exp(-ALPHA * np.pi ** 2 * t) * np.sin(np.pi * x) + 0.5 * np.exp(-9 * ALPHA * np.pi ** 2 * t) * np.sin(3 * np.pi * x)
def ic_wave(x): return torch.sin(np.pi * x) + 0.5 * torch.sin(3 * np.pi * x)
def ic_spot(x): return torch.exp(-0.5 * ((x - 0.4) / 0.03) ** 2)        # 第 6 步：很窄的热点
XG, TG = np.meshgrid(np.linspace(0, 1, 41), np.linspace(0, 1, 41))        # 画图、算误差用的 41×41 网格
def rel(a, b): return float(np.sqrt(((a - b) ** 2).mean() / (b ** 2).mean()))

# ═══ 第 2 步：网络和“方程差多少” ═══════════════════════════════════
def make_net():
    return nn.Sequential(nn.Linear(2, 32), nn.Tanh(), nn.Linear(32, 32), nn.Tanh(),
                         nn.Linear(32, 32), nn.Tanh(), nn.Linear(32, 1))  # 吃进 (x, t)，吐出温度

def residual(net, x, t, alpha):
    """在一批点上算 u_t − α·u_xx。网络要是处处满足方程，它就处处是 0。"""
    x = x.clone().requires_grad_(True); t = t.clone().requires_grad_(True)
    u = net(torch.stack([x, t], -1))[..., 0]
    ut, ux = torch.autograd.grad(u.sum(), [t, x], create_graph=True)     # 一阶导（基础篇第 3 课的自动求导）
    uxx = torch.autograd.grad(ux.sum(), x, create_graph=True)[0]          # 对 u_x 再求一次导，得二阶导
    return ut - alpha * uxx

# ═══ 第 3 步：训练（损失 = 方程 + 初始温度 + 两端） ══════════════════
def run(use_ic=True, use_bc=True, ic=ic_wave, data=None, seed=0, steps=6000):
    torch.manual_seed(seed)
    net = make_net()
    loga = nn.Parameter(torch.tensor(np.log(0.3), dtype=torch.float32))  # 反问题时：α 也当成旋钮，从 0.3 猜起
    g = torch.Generator().manual_seed(seed)
    xc, tc = torch.rand(1000, generator=g), torch.rand(1000, generator=g)  # 1000 个检查方程的点
    x0 = torch.linspace(0, 1, 101); tb = torch.linspace(0, 1, 101)         # t = 0 的 101 个点；两端各 101 个点
    params = list(net.parameters()) + ([loga] if data else [])
    opt = torch.optim.Adam(params, 1e-3)
    u = lambda x, t: net(torch.stack([x, t], -1))[..., 0]
    for k in range(steps):
        alpha = torch.exp(loga) if data else ALPHA
        l_pde = (residual(net, xc, tc, alpha) ** 2).mean()
        l_ic = ((u(x0, torch.zeros_like(x0)) - ic(x0)) ** 2).mean() if use_ic else 0
        l_bc = ((u(torch.zeros_like(tb), tb) ** 2).mean() + (u(torch.ones_like(tb), tb) ** 2).mean()) if use_bc else 0
        if data:                                                           # 反问题：不给初始温度，换成 12 个测量
            xs, ts, ys = data
            l_ic = ((u(xs, ts) - ys) ** 2).mean()
        loss = l_pde + l_ic + l_bc
        opt.zero_grad(); loss.backward(); opt.step()
    with torch.no_grad():
        U = u(torch.tensor(XG, dtype=torch.float32), torch.tensor(TG, dtype=torch.float32)).numpy()
    return net, U, float(torch.exp(loga).detach())

E = exact(XG, TG)
net, U, _ = run()
print(f"三项都有：和准确答案差 {rel(U, E) * 100:.2f}%")
# 应得输出：三项都有：和准确答案差 0.23%

# ═══ 第 4 步：少一项会怎样 ═════════════════════════════════════════
_, U_noic, _ = run(use_ic=False)
_, U_nobc, _ = run(use_bc=False)
print(f"不给初始温度：差 {rel(U_noic, E) * 100:.1f}%，网络里最大的数 {np.abs(U_noic).max():.4f}")
print(f"不给两端：差 {rel(U_nobc, E) * 100:.1f}%")
# 应得输出：
# 不给初始温度：差 100.0%，网络里最大的数 0.0002 左右（几乎全是 0）
# 不给两端：差 40.0%

# ═══ 第 5 步：反问题 —— α 不知道，只有 12 个带噪声的测量 ═══════════
xs = torch.tensor([0.2, 0.4, 0.6, 0.8]).repeat(3)
ts = torch.tensor([0.25] * 4 + [0.5] * 4 + [0.75] * 4)
noise = 0.01 * torch.randn(12, generator=torch.Generator().manual_seed(100))
ys = torch.tensor(exact(xs.numpy(), ts.numpy()), dtype=torch.float32) + noise
_, U_inv, a = run(data=(xs, ts, ys))
late = TG >= 0.25
print(f"猜出 α = {a:.4f}（真值 0.1）；t ≥ 0.25 差 {rel(U_inv[late], E[late]) * 100:.1f}%，t < 0.25 差 {rel(U_inv[~late], E[~late]) * 100:.1f}%")
# 应得输出：猜出 α = 0.1007（真值 0.1）；t ≥ 0.25 差 2.8%，t < 0.25 差 27.2%
# 换 5 组噪声（把 manual_seed(100) 和 run 的 seed 一起换）：α = 0.1007、0.1012、0.0989、0.1040、0.0961

# ═══ 第 6 步：很窄的热点 ═══════════════════════════════════════════
_, U_spot, _ = run(ic=ic_spot)
n = 401; x = np.linspace(0, 1, n); dx = x[1] - x[0]                       # 用模拟器算准确答案
u = np.exp(-0.5 * ((x - 0.4) / 0.03) ** 2); u[0] = u[-1] = 0
steps = int(np.ceil(ALPHA / 40 / (0.4 * dx * dx))); r = ALPHA / 40 / (steps * dx * dx)
rows = [np.interp(np.linspace(0, 1, 41), x, u)]
for k in range(40):
    u = simulate(u, r, steps); rows.append(np.interp(np.linspace(0, 1, 41), x, u))
S = np.array(rows)
print(f"窄热点：网络和模拟器差 {rel(U_spot, S) * 100:.1f}%")
# 应得输出：窄热点：网络和模拟器差 56.9%

# ═══ 第 7 步：画图 ═════════════════════════════════════════════════
fig, ax = plt.subplots(1, 2, figsize=(10, 3.8))
for j, t in enumerate([0, 10, 20, 40]):
    c = f"C{j}"
    ax[0].plot(XG[0], E[t], color=c, lw=1.5, label=f"t = {t / 40:.2f}"); ax[0].plot(XG[0], U[t], "--", color=c, lw=2)
    ax[1].plot(XG[0], S[t], color=c, lw=1.5); ax[1].plot(XG[0], U_spot[t], "--", color=c, lw=2)
ax[0].set_title("sine start: exact (solid) vs PINN (dashed)", fontsize=10); ax[0].legend(fontsize=8)
ax[1].set_title("narrow hot spot: simulator (solid) vs PINN (dashed)", fontsize=10)
for a_ in ax: a_.set_xlabel("position on the rod")
plt.tight_layout(); plt.savefig("s08_pinn.png", dpi=110)
print("已保存 s08_pinn.png")
