{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5d6f1945",
   "metadata": {},
   "source": [
    "# 第 16 课 · 时序秩与动态模态分解\n",
    "\n",
    "修改第四段的预测步数 H，再运行最后两段，比较不同截断秩的外推误差。\n",
    "\n",
    "按 **Shift + Enter** 由上至下运行，或选择 **Run → Run All Cells** 运行整份配套脚本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a92a32c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "rng = np.random.default_rng(20261201)\n",
    "\n",
    "\n",
    "def header(t):\n",
    "    print(\"\\n\" + \"=\" * 74)\n",
    "    print(\"  \" + t)\n",
    "    print(\"=\" * 74)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8dffd4f",
   "metadata": {},
   "source": [
    "## 16.1 构造已知低秩时间的动力系统"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6e18ca37",
   "metadata": {},
   "outputs": [],
   "source": [
    "header(\"16.1 合成动力系统：r0 个模态驱动的时间演化\")\n",
    "n, r0, T = 60, 3, 40                       # 状态维 / 真实时序秩 / 时间步\n",
    "Phi = np.linalg.qr(rng.normal(size=(n, r0)))[0]   # 正交模态基\n",
    "lam = np.array([0.97, 0.99 * np.exp(0.15j), 0.95 * np.exp(-0.1j)])\n",
    "# 用实块实现复特征值：A 在模态坐标中是 r0×r0 的实矩阵\n",
    "A_small = np.array([[0.97, 0, 0],\n",
    "                    [0, 0.99 * np.cos(0.15), -0.99 * np.sin(0.15)],\n",
    "                    [0, 0.99 * np.sin(0.15), 0.99 * np.cos(0.15)]])\n",
    "A_true = Phi @ A_small @ Phi.T             # 全空间动力学 (n×n)，但秩仅 r0\n",
    "z0 = rng.normal(size=r0)\n",
    "X = np.zeros((n, T))\n",
    "z = z0.copy()\n",
    "for t in range(T):\n",
    "    X[:, t] = Phi @ z\n",
    "    z = A_small @ z\n",
    "Xp = np.zeros_like(X)\n",
    "z = z0.copy()\n",
    "for t in range(T):\n",
    "    z = A_small @ z\n",
    "    Xp[:, t] = Phi @ z\n",
    "rank_true = np.linalg.matrix_rank(X, tol=1e-8)\n",
    "print(f\"状态维 n={n}, 真实时序秩 r0={r0}, 实测 rank(X)={rank_true}\")\n",
    "print(f\"奇异值前6: {np.round(np.linalg.svd(X, compute_uv=False)[:6], 4)}\")\n",
    "assert rank_true == r0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0de180b3",
   "metadata": {},
   "source": [
    "## 16.2 DMD：从快照求低秩演化算子"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03b34dae",
   "metadata": {},
   "outputs": [],
   "source": [
    "header(\"16.2 DMD：Ã = Uᵀ X' V Σ⁻¹，谱给出时间模态\")\n",
    "U, S, Vt = np.linalg.svd(X, full_matrices=False)\n",
    "r = r0\n",
    "Ur, Sr, Vr = U[:, :r], S[:r], Vt[:r, :]\n",
    "A_tilde = Ur.T @ Xp @ Vr.T @ np.diag(1.0 / Sr)\n",
    "eig = np.linalg.eigvals(A_tilde)\n",
    "print(f\"截断秩 r={r}, Ã 的特征值 |λ| = {np.round(np.abs(eig), 4)}\")\n",
    "print(f\"理论 |λ| = {np.round(np.abs(np.linalg.eigvals(A_small)), 4)}\")\n",
    "assert np.allclose(np.sort(np.abs(eig)), np.sort(np.abs(np.linalg.eigvals(A_small))), atol=1e-6)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c11a6caf",
   "metadata": {},
   "source": [
    "## 16.3 Eckart–Young：最优低秩逼近误差 = 被丢弃的奇异值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e2fe46fb",
   "metadata": {},
   "outputs": [],
   "source": [
    "header(\"16.3 Eckart–Young：截断秩 r 的 Frobenius 误差 = √(Σ_{i>r} σ_i²)\")\n",
    "sv = np.linalg.svd(X, compute_uv=False)\n",
    "for rr in [1, 2, 3, 5, 10]:\n",
    "    Ur2, Sr2, Vr2 = U[:, :rr], S[:rr], Vt[:rr, :]\n",
    "    Xr = Ur2 @ np.diag(Sr2) @ Vr2\n",
    "    err = np.linalg.norm(X - Xr, 'fro')\n",
    "    theory = np.sqrt(np.sum(sv[rr:] ** 2))\n",
    "    print(f\"r={rr}: 实测误差={err:.4e}, 理论={theory:.4e}, 差={abs(err-theory):.2e}\")\n",
    "    assert abs(err - theory) < 1e-8\n",
    "print(\"→ r=r0=3 后误差≈0：再多模态不再降误差（时序秩饱和）\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67376e80",
   "metadata": {},
   "source": [
    "## 16.4 DMD 重建与外推预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dde22718",
   "metadata": {},
   "outputs": [],
   "source": [
    "header(\"16.4 低秩重建 + 未来帧外推（DMD 的真正价值）\")\n",
    "A_full = Ur @ A_tilde @ Ur.T\n",
    "# A_full 是\"一步转移\"算子：把 X[:,t] 映到 Xp[:,t]，故重建误差应与 Xp 比\n",
    "X_rec = A_full @ X\n",
    "rec_err = np.linalg.norm(Xp - X_rec, 'fro') / np.linalg.norm(Xp, 'fro')\n",
    "# 外推 H 步：真值必须从最后一帧 X[:,-1]（即 z_{T-1}）继续，而非从 z0 重来\n",
    "H = 10\n",
    "zT = z0.copy()\n",
    "for t in range(T):                     # 推进到 z_T\n",
    "    zT = A_small @ zT\n",
    "X_pred_true = np.zeros((n, H))\n",
    "for h in range(H):                     # z_T ... z_{T+H-1}\n",
    "    X_pred_true[:, h] = Phi @ zT\n",
    "    zT = A_small @ zT\n",
    "zhat = Ur.T @ X[:, -1]                 # 模态坐标初值，对应 X[:,-1]=Phi@z_{T-1}\n",
    "X_pred_hat = np.zeros((n, H))\n",
    "for h in range(H):\n",
    "    zhat = A_tilde @ zhat\n",
    "    X_pred_hat[:, h] = Ur @ zhat\n",
    "pred_err = np.linalg.norm(X_pred_true - X_pred_hat, 'fro') / np.linalg.norm(X_pred_true, 'fro')\n",
    "print(f\"一步转移重建相对误差 = {rec_err:.3e}\")\n",
    "print(f\"{H} 步外推相对误差 = {pred_err:.3e}\")\n",
    "assert rec_err < 1e-8 and pred_err < 1e-6"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8c3f1a77",
   "metadata": {},
   "source": [
    "## 16.5 秩误判的代价：真实秩 > 假设秩时外推发散"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "877ccaea",
   "metadata": {},
   "outputs": [],
   "source": [
    "header(\"16.5 时序秩欠估 ⇒ 外推误差随时步指数放大\")\n",
    "for rr in [1, 2, 3]:\n",
    "    Ur2 = U[:, :rr]\n",
    "    Sr2 = S[:rr]\n",
    "    Vr2 = Vt[:rr, :]\n",
    "    At2 = Ur2.T @ Xp @ Vr2.T @ np.diag(1.0 / Sr2)\n",
    "    zh2 = Ur2.T @ X[:, -1]\n",
    "    for h in range(H):\n",
    "        zh2 = At2 @ zh2\n",
    "    pred2 = Ur2 @ zh2\n",
    "    err = np.linalg.norm(pred2 - X_pred_true[:, -1]) / np.linalg.norm(X_pred_true[:, -1])\n",
    "    print(f\"假设秩 r={rr}（真实={r0}）: {H}步外推相对误差={err:.3f}\")\n",
    "    if rr == r0:\n",
    "        assert err < 1e-6\n",
    "\n",
    "print(\"\\n全部断言通过。第16课 5 段验证完成。\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python (Pyodide)",
   "language": "python",
   "name": "python"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
