"""silab · 科学篇 00：科研 Python —— 数组、画图、读数据
需要：pip install numpy matplotlib torch；同一个文件夹里要有 sim/heat.py。
运行：python s00_scipy.py，逐行对照注释里的应得输出。全部跑完不到 10 秒。
会生成三个文件：loss.png、rod.png、data/rod.csv。
"""
import os, time
import numpy as np

# ═══ 第 1 步：数组和列表差在哪 ══════════════════════════════════
xs = np.array([1.0, 2.0, 3.0, 4.0])
print(xs * 2, [1, 2, 3, 4] * 2)
# 应得：[2. 4. 6. 8.] [1, 2, 3, 4, 1, 2, 3, 4]   ← 数组乘 2 是每个数乘 2；列表乘 2 是重复一遍
print(xs[0], xs[-1], xs[1:3], xs.sum(), xs.mean())
# 应得：1.0 4.0 [2. 3.] 10.0 2.5                 ← 下标、切片和列表一样：从 0 数，不含末尾

A = np.array([[1.0, 2.0], [3.0, 4.0]])
print(A * A)       # 应得：[[ 1.  4.] [ 9. 16.]]   ← * 是对应位置相乘（MATLAB 的 .*）
print(A @ A)       # 应得：[[ 7. 10.] [15. 22.]]   ← @ 才是矩阵乘法（MATLAB 的 *）
B = A              # 没有复制：B 和 A 是同一份数据
B[0, 0] = 99.0
print(A[0, 0])     # 应得：99.0                    ← 改 B，A 也变了。要复制写 B = A.copy()

# ═══ 第 2 步：形状与广播 ═══════════════════════════════════════
a = np.arange(3)                    # 0, 1, 2
col = a.reshape(3, 1)               # 竖着排的 3 个数
print(a.shape, col.shape, (col + np.arange(4)).shape)
# 应得：(3,) (3, 1) (3, 4)          ← (3,1) 和 (4,) 相加，两边各自“撑开”成 3 行 4 列
print(col + np.arange(4))
# 应得：[[0 1 2 3] [1 2 3 4] [2 3 4 5]]

# ═══ 第 3 步：画图 ════════════════════════════════════════════
import matplotlib
matplotlib.use("Agg")               # 不弹窗口，直接存成文件
import matplotlib.pyplot as plt

step = np.array([0, 1, 2, 5, 10, 20, 30])                                   # 基础篇 01 打印过的 7 行
loss = np.array([29.7250, 14.5776, 7.1554, 0.8632, 0.0479, 0.0243, 0.0242])
plt.figure(figsize=(5, 3.2))
plt.plot(step, loss, "o-", label="lr = 0.02")
plt.yscale("log")                   # 纵轴用对数：前面降得快、后面降得慢，都看得清
plt.xlabel("step")
plt.ylabel("loss (yuan^2)")
plt.legend()
plt.tight_layout()
plt.savefig("loss.png", dpi=150)
plt.close()
print("已保存 loss.png")

# ═══ 第 4 步：写一个模拟器 —— 一根棒子怎么变凉 ═════════════════════
from sim.heat import grid, simulate, exact_sine

x = grid(51)                        # 51 个点，间隔 Δx = 0.02
dx = x[1] - x[0]
u0 = np.sin(np.pi * x)              # 初始温度：中间热，两头是 0
r = 0.4
dt = r * dx ** 2                    # α = 1 时，Δt = r·Δx²
steps = 312
u = simulate(u0, r, steps)
t = steps * dt
print(f"Δx = {dx:.2f}  Δt = {dt:.5f}  走 {steps} 步，t = {t:.5f}")
print(f"中点温度：模拟 {u[25]:.4f}  解析解 {exact_sine(x, t)[25]:.4f}  全棒最大误差 {np.abs(u - exact_sine(x, t)).max():.2e}")
# 应得：Δx = 0.02  Δt = 0.00016  走 312 步，t = 0.04992
#       中点温度：模拟 0.6108  解析解 0.6110  全棒最大误差 1.39e-04

def simulate_loop(u0, r, steps):
    """同一件事，不用切片，一个点一个点地算。"""
    u = np.array(u0, dtype=float)
    for _ in range(steps):
        new = u.copy()
        for i in range(1, len(u) - 1):
            new[i] = u[i] + r * (u[i + 1] - 2 * u[i] + u[i - 1])
        u = new
    return u

assert np.allclose(simulate_loop(u0, r, 20), simulate(u0, r, 20))   # 两种写法结果一样
for n in (51, 1001):
    xx = grid(n); uu = np.sin(np.pi * xx)
    t0 = time.perf_counter(); simulate(uu, 0.4, 100); a_ = time.perf_counter() - t0
    t0 = time.perf_counter(); simulate_loop(uu, 0.4, 100); b_ = time.perf_counter() - t0
    print(f"{n:5d} 个点走 100 步：切片 {a_ * 1000:6.2f} 毫秒  逐点循环 {b_ * 1000:7.1f} 毫秒  相差 {b_ / a_:.0f} 倍")
# 应得（每台电脑不同，量级如此）：51 个点相差约 7 倍；1001 个点相差约 100 倍

rng = np.random.default_rng(0)
u0n = u0 + 1e-6 * rng.standard_normal(51)        # 加一点点测量噪声：百万分之一
u0n[0] = u0n[-1] = 0.0
print(f"r = 0.5 走 312 步：最大 {np.abs(simulate(u0n, 0.5, 312)).max():.2f}")
print(f"r = 0.6 走 100 步：最大 {np.abs(simulate(u0n, 0.6, 100)).max():.3g}")
print(f"r = 0.6 走 312 步：最大 {np.abs(simulate(u0n, 0.6, 312)).max():.3g}")
# 应得：0.54 / 1.06e+08 / 7.42e+38      ← r 超过 0.5，算出来的不再是温度，是被一步步放大的误差

plt.figure(figsize=(5, 3.2))
plt.plot(x, u0, "--", color="gray", label="t = 0")
plt.plot(x, u, label=f"simulated, t = {t:.3f}")
plt.plot(x[::5], exact_sine(x, t)[::5], "o", ms=4, label="exact")
plt.xlabel("x (position)")
plt.ylabel("u (temperature)")
plt.legend()
plt.tight_layout()
plt.savefig("rod.png", dpi=150)
plt.close()
print("已保存 rod.png")

# ═══ 第 5 步：把数据留下来 ══════════════════════════════════════
os.makedirs("data", exist_ok=True)
np.savetxt("data/rod.csv", np.column_stack([x, u0, u]), delimiter=",", header="x,u0,u", comments="", fmt="%.6f")
back = np.loadtxt("data/rod.csv", delimiter=",", skiprows=1)
print(back.shape, back[25])
# 应得：(51, 3) [0.5      1.       0.610842]     ← 51 行 3 列；第 25 行就是中点

np.savez("data/rod.npz", x=x, u0=u0, u=u)        # 一个文件装多个数组，不丢精度
z = np.load("data/rod.npz")
print(list(z.keys()), z["u"][25])
# 应得：['x', 'u0', 'u'] 0.6108415081138125

# ═══ 第 6 步：数组 ↔ 张量，精度，GPU ═════════════════════════════
import torch
import torch.nn as nn

tx = torch.from_numpy(u)            # 数组变张量：不复制数据，类型跟着数组走
print(tx.dtype, torch.tensor([1.0]).dtype)
# 应得：torch.float64 torch.float32   ← NumPy 默认 64 位小数，PyTorch 默认 32 位
torch.manual_seed(0)
net = nn.Linear(51, 1)
try:
    net(tx)
except RuntimeError as e:
    print("RuntimeError:", e)
# 应得：RuntimeError: mat1 and mat2 must have the same dtype, but got Double and Float
print(net(tx.float()).shape, tx.float().numpy().dtype)
# 应得：torch.Size([1]) float32       ← .float() 转成 32 位就能喂给网络；.numpy() 再变回数组

print(np.float32(0.1) + np.float32(0.2), 0.1 + 0.2)
print(np.float32(16777216) + np.float32(1))
# 应得：0.3 0.30000000000000004       ← 两种精度都不是“精确”的，只是有效数字一个约 7 位、一个约 16 位
#       1.6777216e+07                 ← 32 位装不下 16777217：加 1 等于没加

device = "cuda" if torch.cuda.is_available() else "cpu"
net = net.to(device)
print(device, net(tx.float().to(device)).shape)
# 应得：有显卡时是 cuda，没有就是 cpu；后面一项都是 torch.Size([1])
