{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "76d63f79",
   "metadata": {},
   "source": [
    "# DCT Laboratory — Volume I, Chapter 16\n",
    "## Synthesis, Future Directions, and Transition to Volume II\n",
    "**Seed `26116`** · Companion to the chapter and AXIOM Module **AXIOM-16**\n",
    "\n",
    "**The capstone: one integrated run reusing the volume's own instruments.**\n",
    "The GEOP's allocation (Ch. 15) is recalled and re-verified; the unified dynamics\n",
    "(Chs. 13–14) run under an invariant gate; a **digital twin** (Def., §16.10)\n",
    "tracks the \"actual\" enterprise and a drift monitor catches their divergence; and\n",
    "the **Optimization Readiness Theorem** is scored as an executable checklist.\n",
    "Mirrored in `DCT_V1_Ch16_Lab.xlsx`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "051611af",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-07-13T23:27:21.671256Z",
     "iopub.status.busy": "2026-07-13T23:27:21.671035Z",
     "iopub.status.idle": "2026-07-13T23:27:22.536281Z",
     "shell.execute_reply": "2026-07-13T23:27:22.535168Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "plt.rcParams['figure.dpi']=110\n",
    "\n",
    "import numpy as np\n",
    "SEED = 26116\n",
    "# --- Ch. 15 recall: the GEOP's corner optimum ---\n",
    "K0c, DELTAc, ALPHAc = np.array([40.,30.,20.]), np.array([.02,.06,.10]), np.array([.3,.4,.3])\n",
    "BASEc = (1-DELTAc)*K0c\n",
    "def Y(I): return float(10*np.prod((BASEc+np.asarray(I))**ALPHAc))\n",
    "S2 = BASEc[1]+BASEc[2]+6.0\n",
    "Kp = ALPHAc[1:]/ALPHAc[1:].sum()*S2\n",
    "I_STAR = np.array([0.0, Kp[0]-BASEc[1], Kp[1]-BASEc[2]])\n",
    "\n",
    "# --- Chs. 13-14 recall: integrated (K, p) dynamics, g = 0.06 ---\n",
    "A = np.array([[0.90,0.20],[0.06,0.80]]); Bv = np.array([4.0,2.0])\n",
    "Z0, N, FLOOR = np.array([40.0,50.0]), 16, 25.0\n",
    "def twin_path(n=N):\n",
    "    z=np.empty((n+1,2)); z[0]=Z0\n",
    "    for k in range(n): z[k+1]=A@z[k]+Bv\n",
    "    return z\n",
    "\n",
    "# --- Ch. 16: the digital twin vs the 'actual' enterprise ---\n",
    "NOISE_P = np.array([1.1735, -2.1226, 2.1835, -0.1833, -2.0614, 2.2657,\n",
    "                    1.0514, 0.6913, 1.2287, -0.3311, -0.9874, 0.7519,\n",
    "                    -0.0573, 0.7441, -1.55, 1.855])   # frozen: rng(26116).normal(0,1.5,16)   # frozen seed-26116 draws, sigma=1.5\n",
    "def actual_path(n=N):\n",
    "    z=np.empty((n+1,2)); z[0]=Z0\n",
    "    for k in range(n):\n",
    "        z[k+1]=A@z[k]+Bv\n",
    "        z[k+1,1]+=NOISE_P[k]\n",
    "    return z\n",
    "\n",
    "def reference_values():\n",
    "    tw, ac = twin_path(), actual_path()\n",
    "    diff = ac[1:,1]-tw[1:,1]\n",
    "    rmse = float(np.sqrt(np.mean(diff**2)))\n",
    "    drift = int(np.argmax(np.abs(diff)>3.0))+1 if (np.abs(diff)>3.0).any() else 0\n",
    "    rho = float(max(abs(np.linalg.eigvals(A))))\n",
    "    minK = float(tw[:,0].min())\n",
    "    viol = int((tw[:,0]<FLOOR).sum())\n",
    "    marg = (ALPHAc[1]/(BASEc[1]+I_STAR[1]))/(ALPHAc[2]/(BASEc[2]+I_STAR[2]))\n",
    "    ready = int(rho<1)+int(minK>=FLOOR)+int(abs(ALPHAc.sum()-1)<1e-9)+int(abs(marg-1)<1e-6)\n",
    "    return {\n",
    "        \"Y_star_recall\": round(Y(I_STAR),4),\n",
    "        \"rho_integrated\": round(rho,4),\n",
    "        \"minK_16\": round(minK,4),\n",
    "        \"invariant_violations\": viol,\n",
    "        \"twin_rmse\": round(rmse,4),\n",
    "        \"drift_quarter\": drift,\n",
    "        \"max_abs_gap\": round(float(np.abs(diff).max()),4),\n",
    "        \"readiness_score\": ready,\n",
    "    }\n",
    "if __name__ == \"__main__\":\n",
    "    [print(f\"{k:22s} {v}\") for k,v in reference_values().items()]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49b96dd3",
   "metadata": {},
   "source": [
    "## Panel 1 — The readiness checklist, executable\n",
    "The Enterprise Optimization Readiness Theorem asks four questions of any\n",
    "enterprise claiming to be ready for Volume II. Each is a computation the volume\n",
    "built: dynamics certified ($\\rho < 1$, Ch. 14), invariants held (Ch. 13's gate),\n",
    "objective declared (weights sum to 1, Ch. 11), optimality conditions verified\n",
    "(marginal ratio 1, Ch. 15). Score: **4 of 4** — this enterprise may proceed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "292dd6b9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-07-13T23:27:22.539030Z",
     "iopub.status.busy": "2026-07-13T23:27:22.538169Z",
     "iopub.status.idle": "2026-07-13T23:27:22.547006Z",
     "shell.execute_reply": "2026-07-13T23:27:22.545900Z"
    }
   },
   "outputs": [],
   "source": [
    "tw = twin_path()\n",
    "rho = float(max(abs(np.linalg.eigvals(A))))\n",
    "minK = tw[:,0].min()\n",
    "marg = (ALPHAc[1]/(BASEc[1]+I_STAR[1]))/(ALPHAc[2]/(BASEc[2]+I_STAR[2]))\n",
    "checks = [\n",
    " (\"dynamics certified: rho < 1 (Ch. 14)\", rho, rho < 1),\n",
    " (\"invariant held: min K >= 25 (Ch. 13)\", minK, minK >= FLOOR),\n",
    " (\"objective declared: sum(alpha) = 1 (Ch. 11)\", ALPHAc.sum(), abs(ALPHAc.sum()-1)<1e-9),\n",
    " (\"optimality verified: marginal ratio = 1 (Ch. 15)\", marg, abs(marg-1)<1e-6)]\n",
    "for name, val, ok in checks:\n",
    "    print(f\"{'READY' if ok else 'NOT READY':>9s}  {name:46s} value = {val:.4f}\")\n",
    "print(f\"\\nreadiness score: {sum(ok for _,_,ok in checks)} / 4\")\n",
    "print(f\"GEOP value recalled and re-verified: Y* = {Y(I_STAR):.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "411117e9",
   "metadata": {},
   "source": [
    "## Panel 2 — The digital twin and its drift monitor\n",
    "The **twin** is the deterministic core; the **actual** enterprise is the same\n",
    "system with frozen seed-`26116` disturbances on performance. The twin tracks\n",
    "well (RMSE 1.68 over 16 quarters) until quarter **9**, when the gap first\n",
    "exceeds the declared tolerance of 3.0 — the drift monitor fires, and §16.10's\n",
    "lifecycle says: re-estimate, re-validate, re-deploy. A model is an instrument\n",
    "under maintenance (Ch. 4), and the twin is that sentence industrialized."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "744b0c0e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-07-13T23:27:22.549567Z",
     "iopub.status.busy": "2026-07-13T23:27:22.548611Z",
     "iopub.status.idle": "2026-07-13T23:27:23.072491Z",
     "shell.execute_reply": "2026-07-13T23:27:23.071159Z"
    }
   },
   "outputs": [],
   "source": [
    "tw, ac = twin_path(), actual_path()\n",
    "t = np.arange(N+1)\n",
    "diff = ac[1:,1]-tw[1:,1]\n",
    "drift = int(np.argmax(np.abs(diff)>3.0))+1\n",
    "fig, axes = plt.subplots(1,2, figsize=(10.2,4.0))\n",
    "axes[0].plot(t, tw[:,1], c=\"#0B3D2E\", lw=2.2, label=\"digital twin p\")\n",
    "axes[0].plot(t, ac[:,1], \"o-\", c=\"#C8A24B\", lw=1.6, ms=4, label=\"actual p (seed 26116)\")\n",
    "axes[0].axvline(drift, c=\"#B0532F\", ls=\":\", lw=1.4)\n",
    "axes[0].set(xlabel=\"quarter\", title=\"Twin vs actual\"); axes[0].legend(frameon=False, fontsize=9); axes[0].grid(alpha=.25)\n",
    "axes[1].plot(range(1,N+1), np.abs(diff), \"o-\", c=\"#1B6B52\", lw=2, ms=4)\n",
    "axes[1].axhline(3.0, c=\"#B0532F\", ls=\"--\", lw=1.2, label=\"tolerance 3.0\")\n",
    "axes[1].axvline(drift, c=\"#B0532F\", ls=\":\", lw=1.4, label=f\"drift fires: q{drift}\")\n",
    "axes[1].set(xlabel=\"quarter\", ylabel=\"|gap|\", title=\"The drift monitor\")\n",
    "axes[1].legend(frameon=False, fontsize=9); axes[1].grid(alpha=.25)\n",
    "plt.tight_layout(); plt.show()\n",
    "print(f\"twin RMSE: {np.sqrt(np.mean(diff**2)):.4f}   max |gap|: {np.abs(diff).max():.4f}   drift quarter: {drift}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf10b986",
   "metadata": {},
   "source": [
    "## Panel 3 — The volume in one run\n",
    "Sixteen quarters of the integrated enterprise, with every layer's instrument\n",
    "annotated where it acts: the GEOP chose the allocation, the certified dynamics\n",
    "carried it, the invariant gate stayed green (zero violations, min K = 40), and\n",
    "the twin watched. This panel is Volume I's table of contents, executed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b189483a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-07-13T23:27:23.074159Z",
     "iopub.status.busy": "2026-07-13T23:27:23.073966Z",
     "iopub.status.idle": "2026-07-13T23:27:23.326064Z",
     "shell.execute_reply": "2026-07-13T23:27:23.325323Z"
    }
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize=(8.6,4.4))\n",
    "ax.plot(t, tw[:,0], c=\"#0B3D2E\", lw=2.4, label=\"capital K\")\n",
    "ax.plot(t, tw[:,1], c=\"#C8A24B\", lw=2.4, label=\"performance p\")\n",
    "ax.axhline(FLOOR, c=\"#B0532F\", ls=\"--\", lw=1.2, label=\"invariant K ≥ 25 (Ch. 13-14)\")\n",
    "ax.annotate(\"GEOP allocation applied (Ch. 15)\", (0.2, tw[0,0]+3), fontsize=9, color=\"#0B3D2E\")\n",
    "ax.annotate(f\"drift monitor fires q{drift} (Ch. 16)\", (drift+0.2, 30), fontsize=9, color=\"#B0532F\")\n",
    "ax.set(xlabel=\"quarter\", ylabel=\"level\", title=\"One integrated run — seeds 26101→26116 behind it\")\n",
    "ax.legend(frameon=False, fontsize=9); ax.grid(alpha=.25); plt.tight_layout(); plt.show()\n",
    "print(f\"invariant violations: {int((tw[:,0]<FLOOR).sum())}   min K: {tw[:,0].min():.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "428b2e91",
   "metadata": {},
   "source": [
    "## Validation — agrees with `DCT_V1_Ch16_Lab.xlsx`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d38ef31d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-07-13T23:27:23.328162Z",
     "iopub.status.busy": "2026-07-13T23:27:23.327965Z",
     "iopub.status.idle": "2026-07-13T23:27:23.335406Z",
     "shell.execute_reply": "2026-07-13T23:27:23.334340Z"
    }
   },
   "outputs": [],
   "source": [
    "ref = reference_values()\n",
    "expected = {\"Y_star_recall\":296.9935,\"rho_integrated\":0.9704,\"minK_16\":40.0,\n",
    " \"invariant_violations\":0,\"twin_rmse\":1.678,\"drift_quarter\":9,\n",
    " \"max_abs_gap\":3.109,\"readiness_score\":4}\n",
    "for k,v in expected.items():\n",
    "    assert abs(ref[k]-v)<5e-4, f\"MISMATCH {k}\"\n",
    "    print(f\"PASS  {k:22s} {ref[k]}\")\n",
    "print(\"\\nAll checkpoints agree — seed 26116. Volume I's laboratory line is complete.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea77b282",
   "metadata": {},
   "source": [
    "**Next**: the midterm sits at this boundary — Exercises 16.1–16.21 are the volume's review set. Volume II's laboratories begin at seed `26201`. Solutions: IM Ch. 16."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
