{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "051311c7",
   "metadata": {},
   "source": [
    "# DCT Laboratory — Volume II, Chapter 3\n",
    "## Convex Enterprise Optimization\n",
    "**Seed `26203`** · Companion to the chapter and AXIOM Module **AXIOM-03 (Vol. II)**\n",
    "\n",
    "Convexity's three dividends, computed: a **Hessian certificate** and the unique\n",
    "global optimum it guarantees, **strong duality** on a capacity-constrained cost\n",
    "problem — duality gap zero, and the multiplier revealed as the **shadow price**\n",
    "of capacity — and **Jensen's inequality** as the blends proposition made\n",
    "numerical. Mirrored in `DCT_V2_Ch03_Lab.xlsx`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34694870",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-07-13T23:49:16.506670Z",
     "iopub.status.busy": "2026-07-13T23:49:16.506495Z",
     "iopub.status.idle": "2026-07-13T23:49:16.998372Z",
     "shell.execute_reply": "2026-07-13T23:49:16.997045Z"
    }
   },
   "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 = 26203\n",
    "# --- Panel 1: certificate & global optimum ---\n",
    "# f(x,y) = (x-3)^2 + 2(y-2)^2 + x*y ; Hessian [[2,1],[1,4]]\n",
    "HESS = np.array([[2.0,1.0],[1.0,4.0]])\n",
    "def f2(x,y): return (x-3)**2 + 2*(y-2)**2 + x*y\n",
    "# grad = 0: 2x + y = 6 ; x + 4y = 8\n",
    "X_U, Y_U = 16/7, 10/7\n",
    "\n",
    "# --- Panel 2: duality & the shadow price ---\n",
    "# min (u-4)^2 s.t. u <= CAP ; dual g(lam) = 2*lam - lam^2/4 (CAP=2)\n",
    "CAP = 2.0\n",
    "def primal_star(cap): return (cap-4.0)**2 if cap < 4 else 0.0\n",
    "def dual_g(lam): return 2*lam - lam**2/4\n",
    "LAM_GRID = np.arange(0, 8.5, 0.5)\n",
    "\n",
    "# --- Panel 3: Jensen / blends ---\n",
    "X1, X2, TH = 1.0, 3.0, 0.5\n",
    "def fj(x): return x**2\n",
    "\n",
    "def reference_values():\n",
    "    lam_star = float(LAM_GRID[int(np.argmax([dual_g(l) for l in LAM_GRID]))])\n",
    "    fd_shadow = (primal_star(CAP+0.1)-primal_star(CAP))/0.1\n",
    "    blend = TH*X1+(1-TH)*X2\n",
    "    return {\n",
    "        \"hess_det\": round(float(np.linalg.det(HESS)),4),\n",
    "        \"hess_eig_min\": round(float(min(np.linalg.eigvals(HESS))),4),\n",
    "        \"x_uncon\": round(X_U,4), \"y_uncon\": round(Y_U,4),\n",
    "        \"f_uncon\": round(f2(X_U,Y_U),4),\n",
    "        \"primal_star\": round(primal_star(CAP),4),\n",
    "        \"lambda_star\": lam_star,\n",
    "        \"dual_max\": round(float(max(dual_g(l) for l in LAM_GRID)),4),\n",
    "        \"duality_gap\": round(float(primal_star(CAP)-max(dual_g(l) for l in LAM_GRID)),4),\n",
    "        \"fd_shadow\": round(float(fd_shadow),4),\n",
    "        \"jensen_lhs\": round(fj(blend),4), \"jensen_rhs\": round(TH*fj(X1)+(1-TH)*fj(X2),4),\n",
    "        \"jensen_gap\": round(TH*fj(X1)+(1-TH)*fj(X2)-fj(blend),4),\n",
    "    }\n",
    "if __name__ == \"__main__\":\n",
    "    [print(f\"{k:14s} {v}\") for k,v in reference_values().items()]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce31e9c2",
   "metadata": {},
   "source": [
    "## Panel 1 — The certificate, then the guarantee\n",
    "$f(x,y) = (x-3)^2 + 2(y-2)^2 + xy$. The Hessian is constant:\n",
    "$\\begin{pmatrix}2&1\\\\1&4\\end{pmatrix}$, determinant 7, minimum eigenvalue\n",
    "1.586 > 0 — **strongly convex**, certified in two numbers. The dividend\n",
    "(Strong Convexity: Existence, Uniqueness, and Quadratic Growth, Prop.): the\n",
    "optimum exists, is unique, and gradient = 0 finds it — $(16/7, 10/7)$, value\n",
    "4.4286. Local Optima of Convex Problems Are Global (Prop.): no second basin to\n",
    "fear."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a62875fb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-07-13T23:49:17.001039Z",
     "iopub.status.busy": "2026-07-13T23:49:17.000210Z",
     "iopub.status.idle": "2026-07-13T23:49:17.256065Z",
     "shell.execute_reply": "2026-07-13T23:49:17.254888Z"
    }
   },
   "outputs": [],
   "source": [
    "print(f\"Hessian det = {np.linalg.det(HESS):.4f}   eig_min = {min(np.linalg.eigvals(HESS)):.4f}  (>0: strongly convex)\")\n",
    "print(f\"unconstrained optimum: x = {X_U:.4f}, y = {Y_U:.4f}, f = {f2(X_U,Y_U):.4f}\")\n",
    "xs = np.linspace(0,4.5,120); ys = np.linspace(-0.5,3.5,120)\n",
    "X, Y = np.meshgrid(xs, ys)\n",
    "fig, ax = plt.subplots(figsize=(6.8,5.0))\n",
    "cs = ax.contour(X, Y, f2(X,Y), levels=14, colors=\"#1B6B52\", linewidths=1)\n",
    "ax.scatter([X_U],[Y_U], c=\"#C8A24B\", s=110, zorder=5, label=\"the one and only optimum\")\n",
    "ax.set(xlabel=\"x\", ylabel=\"y\", title=\"One basin, one bottom — convexity's promise (seed 26203)\")\n",
    "ax.legend(frameon=False); ax.grid(alpha=.2); plt.tight_layout(); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4edd0392",
   "metadata": {},
   "source": [
    "## Panel 2 — Strong duality, and the price of a wall\n",
    "Minimize $(u-4)^2$ subject to capacity $u \\le 2$. Primal optimum: $p^* = 4$ at\n",
    "the wall. The dual function $g(\\lambda) = 2\\lambda - \\lambda^2/4$ peaks at\n",
    "$\\lambda^* = 4$ with $d^* = 4$: **duality gap zero** (Strong Duality Theorem —\n",
    "convexity plus a strictly feasible point). And $\\lambda^*$ is not bookkeeping:\n",
    "relax the capacity and the optimal cost falls at rate $\\approx 4$ per unit —\n",
    "the multiplier IS the shadow price of the wall."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f8993ea4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-07-13T23:49:17.257951Z",
     "iopub.status.busy": "2026-07-13T23:49:17.257700Z",
     "iopub.status.idle": "2026-07-13T23:49:17.477330Z",
     "shell.execute_reply": "2026-07-13T23:49:17.475920Z"
    }
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize=(8.0,4.2))\n",
    "ax.plot(LAM_GRID, [dual_g(l) for l in LAM_GRID], \"o-\", c=\"#1B6B52\", lw=2, ms=4, label=\"dual g(λ)\")\n",
    "ax.axhline(primal_star(CAP), c=\"#C8A24B\", lw=2, ls=\"--\", label=f\"primal p* = {primal_star(CAP):.0f}\")\n",
    "ax.scatter([4],[dual_g(4)], c=\"#0B3D2E\", s=110, zorder=5, label=\"λ* = 4: gap closes\")\n",
    "ax.set(xlabel=\"λ\", ylabel=\"value\", title=\"Dual climbs to meet primal — strong duality (seed 26203)\")\n",
    "ax.legend(frameon=False); ax.grid(alpha=.25); plt.tight_layout(); plt.show()\n",
    "print(f\"duality gap: {primal_star(CAP)-max(dual_g(l) for l in LAM_GRID):.4f}\")\n",
    "print(f\"shadow-price check (fd, h=0.1): dp*/dcap ≈ {(primal_star(CAP+0.1)-primal_star(CAP))/0.1:.4f}  vs  −λ* = −4\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "253276c2",
   "metadata": {},
   "source": [
    "## Panel 3 — Jensen: blends are safe, and averages flatter costs\n",
    "Two feasible plans $x_1 = 1$, $x_2 = 3$; convex cost $f(x) = x^2$. The 50/50\n",
    "blend costs $f(2) = 4$; the average of the costs is 5. **Jensen's gap: 1.0** —\n",
    "blending convex costs never surprises upward (Convex Combinations of Feasible\n",
    "Enterprise Plans Remain Feasible, Prop., with the cost bound riding along).\n",
    "The enterprise reading: diversified plans are both feasible and cheaper than\n",
    "their components' average suggests — when, and only when, the cost is convex."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82ab6e8d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-07-13T23:49:17.479380Z",
     "iopub.status.busy": "2026-07-13T23:49:17.479182Z",
     "iopub.status.idle": "2026-07-13T23:49:17.485169Z",
     "shell.execute_reply": "2026-07-13T23:49:17.484221Z"
    }
   },
   "outputs": [],
   "source": [
    "blend = TH*X1+(1-TH)*X2\n",
    "print(f\"f(blend) = f({blend:.1f}) = {fj(blend):.4f}\")\n",
    "print(f\"blend of f = {TH:.1f}·f({X1:.0f}) + {1-TH:.1f}·f({X2:.0f}) = {TH*fj(X1)+(1-TH)*fj(X2):.4f}\")\n",
    "print(f\"Jensen gap (rhs − lhs): {TH*fj(X1)+(1-TH)*fj(X2)-fj(blend):.4f}  (≥ 0 always, for convex f)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7cf9e05",
   "metadata": {},
   "source": [
    "## Validation — agrees with `DCT_V2_Ch03_Lab.xlsx`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d4cc26d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-07-13T23:49:17.487391Z",
     "iopub.status.busy": "2026-07-13T23:49:17.486697Z",
     "iopub.status.idle": "2026-07-13T23:49:17.493495Z",
     "shell.execute_reply": "2026-07-13T23:49:17.492573Z"
    }
   },
   "outputs": [],
   "source": [
    "ref = reference_values()\n",
    "expected = {\"hess_det\":7.0,\"hess_eig_min\":1.5858,\"x_uncon\":2.2857,\"y_uncon\":1.4286,\"f_uncon\":4.4286,\n",
    " \"primal_star\":4.0,\"lambda_star\":4.0,\"dual_max\":4.0,\"duality_gap\":0.0,\"fd_shadow\":-3.9,\n",
    " \"jensen_lhs\":4.0,\"jensen_rhs\":5.0,\"jensen_gap\":1.0}\n",
    "for k,v in expected.items():\n",
    "    assert abs(ref[k]-v)<5e-4, f\"MISMATCH {k}\"\n",
    "    print(f\"PASS  {k:14s} {ref[k]}\")\n",
    "print(\"\\nAll checkpoints agree — seed 26203.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f215f78",
   "metadata": {},
   "source": [
    "**Next**: Exercises 3.9–3.12 (Part C) tighten the capacity and watch λ* move; AXIOM-03's duality dashboard prices every wall live. Solutions: IM Vol. II, Ch. 3."
   ]
  }
 ],
 "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
}
