{
 "nbformat": 4,
 "nbformat_minor": 5,
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Physics-informed GNN / 物理信息图神经网络\n",
    "## Balanced AC states and microgrid N-1 security screening\n",
    "\n",
    "Run top to bottom with Python 3.9+. This notebook contains every model function;\n",
    "no external data, pretrained weights, PyG, pandapower, or GPU is required.\n",
    "Only plotting needs Matplotlib (`python -m pip install matplotlib`).\n",
    "The two 400-epoch CPU training runs can take tens of seconds.\n",
    "\n",
    "学习路径：GNN 预测复电压 → AC 失配 → 归一化联合 loss → 对照训练 → N-1 判据。\n",
    "Scope: balanced, series-only, constant PQ, one source, static line outages,\n",
    "without redispatch or dynamics. This is a small teaching model, not an operational\n",
    "security certificate. Soft physics loss does not guarantee limit satisfaction."
   ],
   "id": "physics-informed-gnn-00"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Complete source / 完整源码\n",
    "\n",
    "`build_graph` creates node features, two arcs per active line, and the same\n",
    "post-outage Ybus. `predict` only runs a four-layer, six-channel GNN with 146\n",
    "parameters. `residual` computes AC PQ mismatch; `objective` normalizes loss.\n",
    "`backward` and `train_model` update every parameter, including tied-layer weights.\n",
    "`solve_ac` generates separate AC references. `screen` enumerates contingencies;\n",
    "`refine` is one optional, separate Newton correction, never hidden in inference."
   ],
   "id": "physics-informed-gnn-01"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "\"\"\"Balanced AC + rectangular-voltage GNN + physics-informed training.\n",
    "\n",
    "Pure Python standard library. Three-phase 1 MVA / 0.4 kV LL bases; PQ net\n",
    "consumption is positive. Series-only lines; one fixed V=1+j0 reference. The\n",
    "inverter is fixed PQ. The learner predicts V without calling solve_ac().\n",
    "Thermal/voltage limits classify states; they are NOT penalties in the loss.\n",
    "\"\"\"\n",
    "import math\n",
    "\n",
    "H, K, V_SCALE, S_SCALE = 6, 4, 0.05, 0.2\n",
    "I_BASE = 1000/(math.sqrt(3)*0.4)\n",
    "DEFAULTS = dict(load_scale=1.2, bus5_kw=100., pv4_kw=50., z_scale=1.,\n",
    "                topology=\"looped\", rating_scale=1., vmin=.95, vmax=1.05)\n",
    "TRAINING_DEFAULTS = dict(epochs=400, lr=.003, **{\"lambda\": 1.}, label_fraction=.25, noise=.002)\n",
    "SIZES = dict(Win=H*3, bin=H, Ws=H*H, Wn=H*H, Wskip=H*3, bh=H, We=H*2, Wo=2*H, bo=2)\n",
    "KEYS = list(SIZES)\n",
    "\n",
    "\n",
    "def zeros():\n",
    "    return {key: [0.]*n for key, n in SIZES.items()}\n",
    "\n",
    "\n",
    "def copy_weights(theta):\n",
    "    return {key: theta[key][:] for key in KEYS}\n",
    "\n",
    "\n",
    "class Random:\n",
    "    \"\"\"Same seeded 32-bit LCG and Box-Muller transform as the browser.\"\"\"\n",
    "    def __init__(self, seed):\n",
    "        self.state = int(seed) & 0xffffffff\n",
    "\n",
    "    def uniform(self):\n",
    "        self.state = (1664525*self.state+1013904223) & 0xffffffff\n",
    "        return (self.state+0.5)/4294967296\n",
    "\n",
    "    def normal(self):\n",
    "        return math.sqrt(-2*math.log(self.uniform()))*math.cos(2*math.pi*self.uniform())\n",
    "\n",
    "\n",
    "def initialize():\n",
    "    rng, theta = Random(7), zeros()\n",
    "    scales = dict(Win=.3, Ws=.04, Wn=.04, Wskip=.08, We=.02, Wo=.04)\n",
    "    for key in (\"Win\", \"Ws\", \"Wn\", \"Wskip\", \"We\", \"Wo\"):\n",
    "        theta[key] = [rng.normal()*scales[key] for _ in theta[key]]\n",
    "    for j in range(H):\n",
    "        theta[\"Ws\"][j*H+j] += .5\n",
    "        theta[\"Wn\"][j*H+j] += .3\n",
    "    return theta\n",
    "\n",
    "\n",
    "def check_weights(theta):\n",
    "    if not theta or not all(key in theta and len(theta[key]) == n\n",
    "                            and all(math.isfinite(v) and abs(v) < 100 for v in theta[key])\n",
    "                            for key, n in SIZES.items()):\n",
    "        raise ValueError(\"Invalid model weights\")\n",
    "    return theta\n",
    "\n",
    "\n",
    "def config(parameters=None):\n",
    "    c = dict(DEFAULTS, **(parameters or {}))\n",
    "    for key, lo, hi in ((\"load_scale\", 0, 2.5), (\"bus5_kw\", 0, 300), (\"pv4_kw\", 0, 300),\n",
    "                        (\"z_scale\", .3, 2), (\"rating_scale\", .3, 2), (\"vmin\", .8, 1), (\"vmax\", 1, 1.2)):\n",
    "        if not math.isfinite(c[key]) or not lo <= c[key] <= hi:\n",
    "            raise ValueError(\"Invalid \" + key)\n",
    "    if c[\"topology\"] not in (\"looped\", \"feeder\", \"radial\") or c[\"vmin\"] >= c[\"vmax\"]:\n",
    "        raise ValueError(\"Invalid topology or voltage bounds\")\n",
    "    return c\n",
    "\n",
    "\n",
    "def build_graph(parameters=None, outage=\"base\"):\n",
    "    \"\"\"Rebuild active arcs AND Ybus after every operating/topology change.\n",
    "\n",
    "    Relative to the preceding five-bus lesson, line 1-3 adds a second path to\n",
    "    the same external reference. 'looped' closes both 1-3 and 3-5; 'feeder'\n",
    "    opens 1-3; 'radial' opens both. Only base-case active lines are N-1 candidates.\n",
    "    \"\"\"\n",
    "    c = config(parameters)\n",
    "    p = [0., .08*c[\"load_scale\"], .1*c[\"load_scale\"],\n",
    "         .06*c[\"load_scale\"]-c[\"pv4_kw\"]/1000, c[\"bus5_kw\"]/1000*c[\"load_scale\"]]\n",
    "    q = [0., .03*c[\"load_scale\"], .04*c[\"load_scale\"],\n",
    "         .025*c[\"load_scale\"], .4*c[\"bus5_kw\"]/1000*c[\"load_scale\"]]\n",
    "    nodes = [dict(id=i+1, p=p[i], q=q[i], ref=i == 0,\n",
    "                  x=[p[i]/.2, q[i]/.1, 1 if i == 0 else 0]) for i in range(5)]\n",
    "    raw = [(\"12\", 0, 1, .04, .025, .5, True), (\"23\", 1, 2, .06, .035, .22, True),\n",
    "           (\"24\", 1, 3, .05, .03, .22, True), (\"45\", 3, 4, .055, .035, .18, True),\n",
    "           (\"35\", 2, 4, .08, .05, .18, c[\"topology\"] != \"radial\"),\n",
    "           (\"13\", 0, 2, .07, .045, .45, c[\"topology\"] == \"looped\")]\n",
    "    edges = [dict(id=name, **{\"from\": f, \"to\": t}, r=r*c[\"z_scale\"], x=x*c[\"z_scale\"],\n",
    "                  limit=limit*c[\"rating_scale\"], base_active=active, active=active and name != outage)\n",
    "             for name, f, t, r, x, limit, active in raw]\n",
    "    if outage != \"base\" and not any(e[\"id\"] == outage and e[\"base_active\"] for e in edges):\n",
    "        raise ValueError(\"Outage must be an in-service base-case line\")\n",
    "    g, b, links, degree = [[0.]*5 for _ in range(5)], [[0.]*5 for _ in range(5)], [], [0]*5\n",
    "    for e in edges:\n",
    "        den = e[\"r\"]**2+e[\"x\"]**2\n",
    "        e[\"g\"], e[\"b\"] = e[\"r\"]/den, -e[\"x\"]/den\n",
    "        if not e[\"active\"]:\n",
    "            continue\n",
    "        f, t = e[\"from\"], e[\"to\"]\n",
    "        for i, j, sign in ((f, f, 1), (t, t, 1), (f, t, -1), (t, f, -1)):\n",
    "            g[i][j] += sign*e[\"g\"]\n",
    "            b[i][j] += sign*e[\"b\"]\n",
    "        for source, target in ((f, t), (t, f)):\n",
    "            links.append(dict(source=source, target=target,\n",
    "                              gate=1/(1+math.hypot(e[\"r\"], e[\"x\"])/.05), e=[e[\"r\"]/.05, e[\"x\"]/.05]))\n",
    "            degree[target] += 1\n",
    "    seen = {0}\n",
    "    for _ in range(5):\n",
    "        for e in edges:\n",
    "            if e[\"active\"] and (e[\"from\"] in seen or e[\"to\"] in seen):\n",
    "                seen.update((e[\"from\"], e[\"to\"]))\n",
    "    return dict(case=c, outage=outage, nodes=nodes, edges=edges, g=g, b=b, links=links,\n",
    "                degree=degree, unsupplied=[v[\"id\"] for i, v in enumerate(nodes) if i not in seen])\n",
    "\n",
    "\n",
    "def power(graph, voltage):\n",
    "    \"\"\"S_inj = V * conjugate(YV), using real/imaginary scalar arithmetic.\"\"\"\n",
    "    ir, ii = [0.]*5, [0.]*5\n",
    "    for i in range(5):\n",
    "        for j in range(5):\n",
    "            ir[i] += graph[\"g\"][i][j]*voltage[j][0]-graph[\"b\"][i][j]*voltage[j][1]\n",
    "            ii[i] += graph[\"b\"][i][j]*voltage[j][0]+graph[\"g\"][i][j]*voltage[j][1]\n",
    "    return dict(ir=ir, ii=ii, p=[u*ir[i]+w*ii[i] for i, (u, w) in enumerate(voltage)],\n",
    "                q=[w*ir[i]-u*ii[i] for i, (u, w) in enumerate(voltage)])\n",
    "\n",
    "\n",
    "def residual(graph, voltage, with_jacobian=False):\n",
    "    \"\"\"PQ residuals only: reference P/Q supply is unknown, not forced to zero.\"\"\"\n",
    "    calculated = power(graph, voltage)\n",
    "    rp = [calculated[\"p\"][i]+graph[\"nodes\"][i][\"p\"] for i in range(1, 5)]\n",
    "    rq = [calculated[\"q\"][i]+graph[\"nodes\"][i][\"q\"] for i in range(1, 5)]\n",
    "    values = rp+rq\n",
    "    out = dict(rp=rp, rq=rq, values=values, max_pu=max(map(abs, values)),\n",
    "               rms_pu=math.sqrt(sum(v*v for v in values)/8),\n",
    "               loss=sum((v/S_SCALE)**2 for v in values)/8)\n",
    "    if with_jacobian:\n",
    "        jacobian = [[0.]*10 for _ in range(8)]\n",
    "        for i in range(1, 5):\n",
    "            for j in range(5):\n",
    "                G, B = graph[\"g\"][i][j], graph[\"b\"][i][j]\n",
    "                u, w, delta = *voltage[i], int(i == j)\n",
    "                jacobian[i-1][j] = delta*calculated[\"ir\"][i]+u*G+w*B\n",
    "                jacobian[i-1][5+j] = delta*calculated[\"ii\"][i]-u*B+w*G\n",
    "                jacobian[4+i-1][j] = -delta*calculated[\"ii\"][i]+w*G-u*B\n",
    "                jacobian[4+i-1][5+j] = delta*calculated[\"ir\"][i]-w*B-u*G\n",
    "        out[\"jacobian\"] = jacobian\n",
    "    return out\n",
    "\n",
    "\n",
    "def linear_solve(matrix, rhs):\n",
    "    a, n = [list(row)+[v] for row, v in zip(matrix, rhs)], len(rhs)\n",
    "    for k in range(n):\n",
    "        pivot = max(range(k, n), key=lambda i: abs(a[i][k]))\n",
    "        if abs(a[pivot][k]) < 1e-12:\n",
    "            raise ArithmeticError(\"Singular Jacobian\")\n",
    "        a[k], a[pivot] = a[pivot], a[k]\n",
    "        for i in range(k+1, n):\n",
    "            factor = a[i][k]/a[k][k]\n",
    "            for j in range(k, n+1):\n",
    "                a[i][j] -= factor*a[k][j]\n",
    "    answer = [0.]*n\n",
    "    for i in range(n-1, -1, -1):\n",
    "        answer[i] = (a[i][n]-sum(a[i][j]*answer[j] for j in range(i+1, n)))/a[i][i]\n",
    "    return answer\n",
    "\n",
    "\n",
    "def newton_direction(r):\n",
    "    return linear_solve([row[1:5]+row[6:10] for row in r[\"jacobian\"]], [-v for v in r[\"values\"]])\n",
    "\n",
    "\n",
    "def trial_step(voltage, step, alpha):\n",
    "    return [[1., 0.]]+[[voltage[i][0]+alpha*step[i-1], voltage[i][1]+alpha*step[4+i-1]] for i in range(1, 5)]\n",
    "\n",
    "\n",
    "def solve_ac(graph, max_iterations=30):\n",
    "    \"\"\"Damped rectangular Newton reference. A failure returns unknown, not unsafe.\"\"\"\n",
    "    if graph[\"unsupplied\"]:\n",
    "        return dict(ok=False, reason=\"unsupplied\", unsupplied=graph[\"unsupplied\"], v=None)\n",
    "    voltage = [[1., 0.] for _ in range(5)]\n",
    "    for k in range(max_iterations+1):\n",
    "        r = residual(graph, voltage, True)\n",
    "        if r[\"max_pu\"] < 1e-10:\n",
    "            return dict(ok=True, v=voltage, residual_pu=r[\"max_pu\"], iterations=k)\n",
    "        if k == max_iterations:\n",
    "            break\n",
    "        try:\n",
    "            step = newton_direction(r)\n",
    "        except ArithmeticError:\n",
    "            break\n",
    "        accepted, alpha = False, 1.\n",
    "        while alpha >= 1/128:\n",
    "            trial = trial_step(voltage, step, alpha)\n",
    "            if all(math.hypot(*u) > .1 for u in trial) and residual(graph, trial)[\"max_pu\"] < r[\"max_pu\"]:\n",
    "                voltage, accepted = trial, True\n",
    "                break\n",
    "            alpha /= 2\n",
    "        if not accepted:\n",
    "            break\n",
    "    return dict(ok=False, reason=\"nonconvergence\", unsupplied=[], v=None)\n",
    "\n",
    "\n",
    "def diagnostics(graph, voltage):\n",
    "    vm = [math.hypot(*u) for u in voltage]\n",
    "    angles = [math.atan2(u[1], u[0])*180/math.pi for u in voltage]\n",
    "    branches = []\n",
    "    for e in graph[\"edges\"]:\n",
    "        if not e[\"active\"]:\n",
    "            branches.append(dict(id=e[\"id\"], active=False, current_pu=0., current_a=0., loading_pct=0., loss_pu=0.))\n",
    "            continue\n",
    "        dr = voltage[e[\"from\"]][0]-voltage[e[\"to\"]][0]\n",
    "        di = voltage[e[\"from\"]][1]-voltage[e[\"to\"]][1]\n",
    "        current = math.hypot(e[\"g\"]*dr-e[\"b\"]*di, e[\"b\"]*dr+e[\"g\"]*di)\n",
    "        branches.append(dict(id=e[\"id\"], active=True, current_pu=current, current_a=current*I_BASE,\n",
    "                             loading_pct=current/e[\"limit\"]*100, loss_pu=e[\"r\"]*current*current))\n",
    "    violations = [dict(kind=\"voltage\", id=i+1) for i, value in enumerate(vm)\n",
    "                  if value < graph[\"case\"][\"vmin\"]-1e-9 or value > graph[\"case\"][\"vmax\"]+1e-9]\n",
    "    violations += [dict(kind=\"current\", id=e[\"id\"]) for e in branches if e[\"active\"] and e[\"loading_pct\"] > 100+1e-7]\n",
    "    return dict(v=voltage, vm=vm, angles=angles, branches=branches, min_v=min(vm),\n",
    "                max_loading=max(e[\"loading_pct\"] for e in branches), residual=residual(graph, voltage),\n",
    "                violations=violations, status=\"unsafe\" if violations else \"safe\")\n",
    "\n",
    "\n",
    "def refine(graph, input_voltage):\n",
    "    \"\"\"Optional ONE accepted Newton correction, explicitly separate from the GNN.\"\"\"\n",
    "    voltage = [u[:] for u in input_voltage]\n",
    "    r = residual(graph, voltage, True)\n",
    "    before = r[\"max_pu\"]\n",
    "    if before < 1e-10:\n",
    "        return dict(v=voltage, accepted=True, before_pu=before, after_pu=before)\n",
    "    try:\n",
    "        step = newton_direction(r)\n",
    "    except ArithmeticError:\n",
    "        return dict(v=voltage, accepted=False, before_pu=before, after_pu=before)\n",
    "    alpha = 1.\n",
    "    while alpha >= 1/128:\n",
    "        trial = trial_step(voltage, step, alpha)\n",
    "        after = residual(graph, trial)[\"max_pu\"]\n",
    "        if all(math.hypot(*u) > .1 for u in trial) and after < before:\n",
    "            return dict(v=trial, accepted=True, before_pu=before, after_pu=after)\n",
    "        alpha /= 2\n",
    "    return dict(v=voltage, accepted=False, before_pu=before, after_pu=before)\n",
    "\n",
    "\n",
    "def predict(graph, theta, cache=False):\n",
    "    \"\"\"Feature/edge -> four tied message layers -> complex voltage; no AC solve.\n",
    "\n",
    "    h0=tanh(Win*x+bin), m=gate*h_sender+We*[r/.05,x/.05]\n",
    "    h_new=tanh(Ws*h+Wn*mean(messages)+Wskip*x+bh)\n",
    "    V_PQ=[1+.05*y0, .05*y1], y=Wo*hK+bo; reference V=1+j0 is imposed exactly.\n",
    "    Matrix rows are flattened to lists for transparent cross-language parity.\n",
    "    \"\"\"\n",
    "    check_weights(theta)\n",
    "    features = [v[\"x\"] for v in graph[\"nodes\"]]\n",
    "    layers = [[[math.tanh(theta[\"bin\"][a]+sum(theta[\"Win\"][a*3+f]*x for f, x in enumerate(row)))\n",
    "                for a in range(H)] for row in features]]\n",
    "    aggregates = []\n",
    "    for k in range(K):\n",
    "        old, agg = layers[k], [[0.]*H for _ in range(5)]\n",
    "        for edge in graph[\"links\"]:\n",
    "            for a in range(H):\n",
    "                agg[edge[\"target\"]][a] += (edge[\"gate\"]*old[edge[\"source\"]][a]\n",
    "                    + theta[\"We\"][a*2]*edge[\"e\"][0]+theta[\"We\"][a*2+1]*edge[\"e\"][1])/graph[\"degree\"][edge[\"target\"]]\n",
    "        aggregates.append(agg)\n",
    "        new = []\n",
    "        for i, row in enumerate(old):\n",
    "            state = []\n",
    "            for a in range(H):\n",
    "                z = theta[\"bh\"][a]\n",
    "                for f in range(H):\n",
    "                    z += theta[\"Ws\"][a*H+f]*row[f]+theta[\"Wn\"][a*H+f]*agg[i][f]\n",
    "                for f in range(3):\n",
    "                    z += theta[\"Wskip\"][a*3+f]*features[i][f]\n",
    "                state.append(math.tanh(z))\n",
    "            new.append(state)\n",
    "        layers.append(new)\n",
    "    voltage = [[1., 0.]]\n",
    "    for row in layers[K][1:]:\n",
    "        voltage.append([1+V_SCALE*(theta[\"bo\"][0]+sum(theta[\"Wo\"][f]*x for f, x in enumerate(row))),\n",
    "                        V_SCALE*(theta[\"bo\"][1]+sum(theta[\"Wo\"][H+f]*x for f, x in enumerate(row)))])\n",
    "    return dict(v=voltage, layers=layers, aggregates=aggregates) if cache else voltage\n",
    "\n",
    "\n",
    "def objective(graph, voltage, observed=None, physics_weight=1., with_gradient=False):\n",
    "    \"\"\"Dimensionless supervised and AC residual MSE, with explicit voltage gradients.\n",
    "\n",
    "    P/Q mask excludes the reference. Data mask excludes unlabeled graphs.\n",
    "    Limits do not appear here: unsafe operating points still obey AC equations.\n",
    "    \"\"\"\n",
    "    r = residual(graph, voltage, with_gradient and physics_weight != 0)\n",
    "    data, dv = 0., [[0., 0.] for _ in range(5)]\n",
    "    if observed is not None:\n",
    "        for i in range(1, 5):\n",
    "            for f in range(2):\n",
    "                error = (voltage[i][f]-observed[i][f])/V_SCALE\n",
    "                data += error*error/8\n",
    "                if with_gradient:\n",
    "                    dv[i][f] += (voltage[i][f]-observed[i][f])/(4*V_SCALE*V_SCALE)\n",
    "    if with_gradient and physics_weight:\n",
    "        for i in range(8):\n",
    "            coefficient = physics_weight*r[\"values\"][i]/(4*S_SCALE*S_SCALE)\n",
    "            for j in range(1, 5):\n",
    "                dv[j][0] += coefficient*r[\"jacobian\"][i][j]\n",
    "                dv[j][1] += coefficient*r[\"jacobian\"][i][5+j]\n",
    "    return dict(data=data, physics=r[\"loss\"], total=data+physics_weight*r[\"loss\"], gradient=dv, residual=r)\n",
    "\n",
    "\n",
    "def backward(graph, theta, passed, dv):\n",
    "    \"\"\"Chain rule: dL/dV -> readout -> every message layer -> input encoder.\"\"\"\n",
    "    grad, dh = zeros(), [[0.]*H for _ in range(5)]\n",
    "    for i in range(1, 5):\n",
    "        for f in range(2):\n",
    "            d = V_SCALE*dv[i][f]\n",
    "            grad[\"bo\"][f] += d\n",
    "            for a in range(H):\n",
    "                grad[\"Wo\"][f*H+a] += d*passed[\"layers\"][K][i][a]\n",
    "                dh[i][a] += d*theta[\"Wo\"][f*H+a]\n",
    "    for k in reversed(range(K)):\n",
    "        previous, da = [[0.]*H for _ in range(5)], [[0.]*H for _ in range(5)]\n",
    "        for i in range(5):\n",
    "            for a in range(H):\n",
    "                d = dh[i][a]*(1-passed[\"layers\"][k+1][i][a]**2)\n",
    "                grad[\"bh\"][a] += d\n",
    "                for f in range(H):\n",
    "                    grad[\"Ws\"][a*H+f] += d*passed[\"layers\"][k][i][f]\n",
    "                    grad[\"Wn\"][a*H+f] += d*passed[\"aggregates\"][k][i][f]\n",
    "                    previous[i][f] += d*theta[\"Ws\"][a*H+f]\n",
    "                    da[i][f] += d*theta[\"Wn\"][a*H+f]\n",
    "                for f in range(3):\n",
    "                    grad[\"Wskip\"][a*3+f] += d*graph[\"nodes\"][i][\"x\"][f]\n",
    "        for edge in graph[\"links\"]:\n",
    "            for a in range(H):\n",
    "                d = da[edge[\"target\"]][a]/graph[\"degree\"][edge[\"target\"]]\n",
    "                previous[edge[\"source\"]][a] += edge[\"gate\"]*d\n",
    "                grad[\"We\"][a*2] += d*edge[\"e\"][0]\n",
    "                grad[\"We\"][a*2+1] += d*edge[\"e\"][1]\n",
    "        dh = previous\n",
    "    for i in range(5):\n",
    "        for a in range(H):\n",
    "            d = dh[i][a]*(1-passed[\"layers\"][0][i][a]**2)\n",
    "            grad[\"bin\"][a] += d\n",
    "            for f in range(3):\n",
    "                grad[\"Win\"][a*3+f] += d*graph[\"nodes\"][i][\"x\"][f]\n",
    "    return grad\n",
    "\n",
    "\n",
    "def loss_gradient(sample, theta, physics_weight=1., data_weight=1.):\n",
    "    passed = predict(sample[\"graph\"], theta, True)\n",
    "    data = objective(sample[\"graph\"], passed[\"v\"], sample[\"observed\"], 0., True)\n",
    "    physics = objective(sample[\"graph\"], passed[\"v\"], None, physics_weight, True)\n",
    "    dv = [[data_weight*v+physics[\"gradient\"][i][f] for f, v in enumerate(row)]\n",
    "          for i, row in enumerate(data[\"gradient\"])]\n",
    "    return dict(data=data[\"data\"], physics=physics[\"physics\"], loss=data_weight*data[\"data\"]+physics_weight*physics[\"physics\"],\n",
    "                gradient=backward(sample[\"graph\"], theta, passed, dv))\n",
    "\n",
    "\n",
    "def dataset(groups, seed, options=None, training=False):\n",
    "    c = dict(TRAINING_DEFAULTS, **(options or {}))\n",
    "    rng, noise_rng, samples, failed = Random(seed), Random(seed ^ 0x9e3779b9), [], 0\n",
    "    labeled_groups = math.floor(groups*c[\"label_fraction\"]+0.5)\n",
    "    for group in range(groups):\n",
    "        operating = dict(load_scale=.6+.9*rng.uniform(), bus5_kw=60+100*rng.uniform(),\n",
    "                         pv4_kw=100*rng.uniform(), z_scale=.8+.4*rng.uniform())\n",
    "        base = build_graph(operating)\n",
    "        outages = [\"base\"]+[e[\"id\"] for e in base[\"edges\"] if e[\"base_active\"]]\n",
    "        for outage in outages:\n",
    "            graph = build_graph(operating, outage)\n",
    "            labeled = not training or group < labeled_groups\n",
    "            truth = solve_ac(graph) if labeled else None\n",
    "            if truth and not truth[\"ok\"]:\n",
    "                failed += 1\n",
    "                continue\n",
    "            observed = [[v+c[\"noise\"]*noise_rng.normal() if i and training else v for v in u]\n",
    "                        for i, u in enumerate(truth[\"v\"])] if labeled else None\n",
    "            samples.append(dict(group=group, graph=graph, truth=truth[\"v\"] if truth else None, observed=observed))\n",
    "    return dict(samples=samples, groups=groups, labeled_groups=labeled_groups if training else groups, failed=failed)\n",
    "\n",
    "\n",
    "def evaluate(data, theta):\n",
    "    mae, physics, unsafe, false_safe, correct = 0., 0., 0, 0, 0\n",
    "    for sample in data[\"samples\"]:\n",
    "        pred = predict(sample[\"graph\"], theta)\n",
    "        ref, out = diagnostics(sample[\"graph\"], sample[\"truth\"]), diagnostics(sample[\"graph\"], pred)\n",
    "        mae += sum(abs(out[\"vm\"][i]-ref[\"vm\"][i]) for i in range(1, 5))\n",
    "        physics += out[\"residual\"][\"loss\"]\n",
    "        if ref[\"status\"] == \"unsafe\":\n",
    "            unsafe += 1\n",
    "            false_safe += out[\"status\"] == \"safe\"\n",
    "        correct += ref[\"status\"] == out[\"status\"]\n",
    "    n = len(data[\"samples\"])\n",
    "    return dict(voltage_mae_pu=mae/(4*n), physics_mse=physics/n,\n",
    "                residual_rms_pu=S_SCALE*math.sqrt(physics/n), false_safe=false_safe,\n",
    "                unsafe=unsafe, correct=correct, cases=n)\n",
    "\n",
    "\n",
    "def train_model(options=None, progress=None):\n",
    "    \"\"\"Matched Adam experiments; labeled graphs and collocation graphs have separate means.\n",
    "\n",
    "    Train/validation split operating groups BEFORE expanding each into base +\n",
    "    six outages. Unlabeled clean voltages are not consumed by loss_gradient.\n",
    "    Gradient norm is clipped at 10; Adam beta1=.9, beta2=.999, epsilon=1e-8.\n",
    "    \"\"\"\n",
    "    c = dict(TRAINING_DEFAULTS, **(options or {}))\n",
    "    if (not isinstance(c[\"epochs\"], int) or not 0 <= c[\"epochs\"] <= 1200\n",
    "            or not math.isfinite(c[\"lr\"]) or not 0 < c[\"lr\"] <= .02\n",
    "            or c[\"label_fraction\"] not in (0, .25, .5, 1)\n",
    "            or not math.isfinite(c[\"lambda\"]) or not 0 <= c[\"lambda\"] <= 10\n",
    "            or not math.isfinite(c[\"noise\"]) or not 0 <= c[\"noise\"] <= .01):\n",
    "        raise ValueError(\"Invalid training settings\")\n",
    "    training, validation = dataset(8, 17, c, True), dataset(3, 83, c, False)\n",
    "    n = len(training[\"samples\"])\n",
    "    nlabel = sum(s[\"observed\"] is not None for s in training[\"samples\"])\n",
    "    theta, moment, variance, history = initialize(), zeros(), zeros(), []\n",
    "\n",
    "    def record(epoch):\n",
    "        data, physics = 0., 0.\n",
    "        for sample in training[\"samples\"]:\n",
    "            loss = objective(sample[\"graph\"], predict(sample[\"graph\"], theta), sample[\"observed\"], c[\"lambda\"])\n",
    "            if sample[\"observed\"] is not None:\n",
    "                data += loss[\"data\"]/(nlabel or 1)\n",
    "            physics += loss[\"physics\"]/n\n",
    "        history.append(dict(epoch=epoch, data=data, physics=physics, total=data+c[\"lambda\"]*physics,\n",
    "                            validation=evaluate(validation, theta)))\n",
    "\n",
    "    record(0)\n",
    "    for epoch in range(1, c[\"epochs\"]+1):\n",
    "        grad = zeros()\n",
    "        for sample in training[\"samples\"]:\n",
    "            if c[\"lambda\"] == 0 and sample[\"observed\"] is None:\n",
    "                continue\n",
    "            out = loss_gradient(sample, theta, c[\"lambda\"], n/nlabel if nlabel else 0)\n",
    "            for key, size in SIZES.items():\n",
    "                for j in range(size):\n",
    "                    grad[key][j] += out[\"gradient\"][key][j]/n\n",
    "        norm = math.sqrt(sum(sum(x*x for x in grad[key]) for key in KEYS))\n",
    "        clip = min(1., 10/(norm or 1))\n",
    "        for key, size in SIZES.items():\n",
    "            for j in range(size):\n",
    "                g = grad[key][j]*clip\n",
    "                moment[key][j] = .9*moment[key][j]+.1*g\n",
    "                variance[key][j] = .999*variance[key][j]+.001*g*g\n",
    "                theta[key][j] -= c[\"lr\"]*(moment[key][j]/(1-.9**epoch))/(math.sqrt(variance[key][j]/(1-.999**epoch))+1e-8)\n",
    "        check_weights(theta)\n",
    "        if epoch % 20 == 0 or epoch == c[\"epochs\"]:\n",
    "            record(epoch)\n",
    "            if progress:\n",
    "                progress(epoch, c[\"epochs\"])\n",
    "    return dict(ok=True, weights=theta, config=c, history=history, validation=evaluate(validation, theta),\n",
    "                training_cases=n, labeled_cases=nlabel, training_groups=8, validation_groups=3,\n",
    "                failed_labels=training[\"failed\"]+validation[\"failed\"], parameter_count=sum(SIZES.values()),\n",
    "                trained=c[\"lambda\"] > 0 or nlabel > 0)\n",
    "\n",
    "\n",
    "def screen(parameters=None, models=None, include_reference=True, correct_physics=False):\n",
    "    \"\"\"Enumerate base + each active line outage. No redispatch or dynamics.\n",
    "\n",
    "    Unsafe: known unsupplied buses or a violated voltage/current criterion.\n",
    "    Unknown: failed AC reference or missing learned weights. Low residual alone\n",
    "    is not a safety certificate. The optional Newton correction is reported.\n",
    "    \"\"\"\n",
    "    c = config(parameters)\n",
    "    base = build_graph(c)\n",
    "    outages = [\"base\"]+[e[\"id\"] for e in base[\"edges\"] if e[\"base_active\"]]\n",
    "    cases = []\n",
    "    for outage in outages:\n",
    "        graph = build_graph(c, outage)\n",
    "        row = dict(outage=outage, unsupplied=graph[\"unsupplied\"], graph=graph)\n",
    "        if graph[\"unsupplied\"]:\n",
    "            for kind in (\"reference\", \"data\", \"physics\"):\n",
    "                row[kind] = dict(status=\"unsafe\", reason=\"unsupplied\")\n",
    "        else:\n",
    "            ref = solve_ac(graph) if include_reference else None\n",
    "            row[\"reference\"] = (diagnostics(graph, ref[\"v\"]) if ref[\"ok\"] else dict(status=\"unknown\", reason=ref[\"reason\"])) if ref else None\n",
    "            for kind in (\"data\", \"physics\"):\n",
    "                if not models or not models.get(kind) or models[kind].get(\"trained\") is False:\n",
    "                    row[kind] = dict(status=\"unknown\", reason=\"untrained\")\n",
    "                    continue\n",
    "                model = models[kind]\n",
    "                raw = predict(graph, model.get(\"weights\", model))\n",
    "                if kind == \"physics\" and correct_physics:\n",
    "                    correction = refine(graph, raw)\n",
    "                    row[kind] = dict(diagnostics(graph, correction[\"v\"]), raw_v=raw, correction=correction)\n",
    "                else:\n",
    "                    row[kind] = diagnostics(graph, raw)\n",
    "        cases.append(row)\n",
    "\n",
    "    def summarize(kind):\n",
    "        if any(row.get(kind) and row[kind][\"status\"] == \"unsafe\" for row in cases):\n",
    "            return \"unsafe\"\n",
    "        return \"unknown\" if any(not row.get(kind) or row[kind][\"status\"] == \"unknown\" for row in cases) else \"safe\"\n",
    "\n",
    "    return dict(ok=True, case=c, cases=cases,\n",
    "                summary={kind: summarize(kind) for kind in (\"reference\", \"data\", \"physics\")})"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-02"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Specified inputs and graph / 输入与图\n",
    "\n",
    "P/Q are positive net consumption (load minus generation). Three-phase base\n",
    "1 MVA, line-to-line 0.4 kV; Zbase=0.16 ohm and Ibase=1443.376 A.\n",
    "Bus 1 is the sole source: V1=1+j0, input P/Q=0 placeholders, not solved supply.\n",
    "Bus 4 solar is fixed PQ (Q=0), not a voltage-forming island source.\n",
    "The 1-3 backup and 3-5 tie give alternate paths to the SAME bus 1."
   ],
   "id": "physics-informed-gnn-03"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "operating = dict(DEFAULTS)\n",
    "# operating.update(load_scale=1.5, pv4_kw=80)\n",
    "graph = build_graph(operating)\n",
    "truth = solve_ac(graph)\n",
    "assert truth[\"ok\"]\n",
    "print(\"Node features [P/0.2, Q/0.1, ref]:\")\n",
    "for node in graph[\"nodes\"]:\n",
    "    print(node[\"id\"], node[\"x\"])\n",
    "print(\"Active physical lines / computational arcs:\",\n",
    "      sum(e[\"active\"] for e in graph[\"edges\"]), len(graph[\"links\"]))\n",
    "print(\"Source injection pu:\", power(graph, truth[\"v\"])[\"p\"][0],\n",
    "      power(graph, truth[\"v\"])[\"q\"][0])"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-04"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "positions = [(0, 0), (1, 0), (2, .8), (2, -.8), (3, 0)]\n",
    "fig, ax = plt.subplots(figsize=(8, 4))\n",
    "for e in graph[\"edges\"]:\n",
    "    a, b = positions[e[\"from\"]], positions[e[\"to\"]]\n",
    "    ax.annotate(\"\", xy=b, xytext=a, arrowprops=dict(arrowstyle=\"-\",\n",
    "                color=\"teal\", connectionstyle=\"arc3,rad=-.4\" if e[\"id\"] == \"13\" else \"arc3,rad=0\"))\n",
    "    ax.text((a[0]+b[0])/2, (a[1]+b[1])/2+.12, e[\"id\"])\n",
    "for i, (x, y) in enumerate(positions):\n",
    "    ax.scatter(x, y, s=650, facecolor=\"white\", edgecolor=\"teal\", zorder=3)\n",
    "    ax.text(x, y, str(i+1), ha=\"center\", va=\"center\", zorder=4)\n",
    "ax.set(xlim=(-.4, 3.4), ylim=(-1.2, 1.7), title=\"Two supply paths, one reference source\")\n",
    "ax.axis(\"off\"); plt.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-05"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. A voltage perturbation exposes the residual / 电压扰动与物理残差\n",
    "\n",
    "I=YV, S_inj=V*conj(I), rP=P_calc+P_net, rQ=Q_calc+Q_net at PQ buses 2..5.\n",
    "Reference P/Q are unknown and excluded. V1 is hard fixed, not loss-penalized.\n",
    "Single-graph losses average 8 terms; voltage scale .05 pu, power scale .2 pu.\n",
    "The physical loss needs specified PQ, topology, and predicted V, not a label."
   ],
   "id": "physics-informed-gnn-06"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "outage = \"24\"\n",
    "post = build_graph(operating, outage)\n",
    "ref = solve_ac(post)[\"v\"]\n",
    "altered = [v[:] for v in ref]\n",
    "altered[4][0] += .01\n",
    "loss = objective(post, altered, ref, physics_weight=1., with_gradient=True)\n",
    "print(\"Ldata / Lphys / total:\", loss[\"data\"], loss[\"physics\"], loss[\"total\"])\n",
    "print(\"Correct Y RMS pu:\", loss[\"residual\"][\"rms_pu\"])\n",
    "print(\"Stale base Y RMS pu:\", residual(build_graph(operating), altered)[\"rms_pu\"])\n",
    "print(\"dL/dRe(V5), dL/dIm(V5):\", loss[\"gradient\"][4])\n",
    "assert residual(post, ref)[\"max_pu\"] < 1e-9\n",
    "assert residual(build_graph(operating), ref)[\"max_pu\"] > 1e-3\n",
    "fig, ax = plt.subplots(figsize=(8, 3.5))\n",
    "ax.bar([i-.16 for i in range(2, 6)], loss[\"residual\"][\"rp\"], .3, label=\"Delta P\")\n",
    "ax.bar([i+.16 for i in range(2, 6)], loss[\"residual\"][\"rq\"], .3, label=\"Delta Q\")\n",
    "ax.axhline(0, color=\"gray\", linewidth=.7)\n",
    "ax.set(xlabel=\"PQ bus\", ylabel=\"Power mismatch pu\", xticks=range(2, 6))\n",
    "ax.legend(); fig.tight_layout(); plt.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-07"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Split by operating group, then expand outages / 先分组再扩展故障\n",
    "\n",
    "8 train groups x 7 cases=56 graphs; 3 validation groups x 7=21.\n",
    "Each group contains base + the same six known single-line outages.\n",
    "This evaluates new operating VALUES, not unseen contingency types/topologies.\n",
    "Only 2/8 training groups have voltage labels by default; the other 42 graphs\n",
    "never solve or store clean AC targets. Noise is independent of operating RNG.\n",
    "Ldata is averaged over labeled graphs; Lphys is averaged over all graphs."
   ],
   "id": "physics-informed-gnn-08"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "training = dataset(8, 17, TRAINING_DEFAULTS, training=True)\n",
    "validation = dataset(3, 83)\n",
    "assert len(training[\"samples\"]) == 56 and len(validation[\"samples\"]) == 21\n",
    "unlabeled = [s for s in training[\"samples\"] if s[\"observed\"] is None]\n",
    "assert len(unlabeled) == 42 and all(s[\"truth\"] is None for s in unlabeled)\n",
    "train_inputs = {tuple(sorted(s[\"graph\"][\"case\"].items())) for s in training[\"samples\"]}\n",
    "assert all(tuple(sorted(s[\"graph\"][\"case\"].items())) not in train_inputs\n",
    "           for s in validation[\"samples\"])\n",
    "sample = unlabeled[0]\n",
    "print(\"Unlabeled data term:\", loss_gradient(sample, initialize())[\"data\"])\n",
    "assert loss_gradient(sample, initialize())[\"data\"] == 0"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-09"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Train matched models from scratch / 从零进行对照训练\n",
    "\n",
    "Identical initialization (seed 7), inputs (seed 17), validation (seed 83), labels,\n",
    "noise, epochs, Adam settings; only lambda differs. Six hidden channels, four\n",
    "tied message layers, all 146 parameters updated. No inequality loss: genuinely\n",
    "unsafe states must remain unsafe, rather than being pushed inside limits."
   ],
   "id": "physics-informed-gnn-10"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "options = dict(TRAINING_DEFAULTS)  # 400 epochs, lr=.003, labels=.25, noise=.002\n",
    "models = {}\n",
    "for kind, weight in ((\"data\", 0.), (\"physics\", options[\"lambda\"])):\n",
    "    models[kind] = train_model(dict(options, **{\"lambda\": weight}))\n",
    "    print(kind, models[kind][\"validation\"])\n",
    "assert models[\"data\"][\"parameter_count\"] == models[\"physics\"][\"parameter_count\"] == 146\n",
    "assert all(m[\"labeled_cases\"] == 14 for m in models.values())"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-11"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig, axes = plt.subplots(1, 2, figsize=(11, 4))\n",
    "for kind, color in ((\"data\", \"#b76819\"), (\"physics\", \"#187568\")):\n",
    "    history = models[kind][\"history\"]\n",
    "    for ax, key in zip(axes, (\"voltage_mae_pu\", \"residual_rms_pu\")):\n",
    "        ax.plot([v[\"epoch\"] for v in history], [v[\"validation\"][key] for v in history],\n",
    "                color=color, label=kind)\n",
    "axes[0].set(title=\"Raw GNN validation voltage MAE\", ylabel=\"pu\", xlabel=\"Epoch\")\n",
    "axes[1].set(title=\"Raw GNN validation power residual RMS\", ylabel=\"pu\", xlabel=\"Epoch\")\n",
    "for ax in axes: ax.legend()\n",
    "fig.tight_layout(); plt.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-12"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The default PI model lowers residual RMS (~.04217 -> .02441 pu), but worsens\n",
    "voltage MAE (~.00445 -> .00577 pu). Both miss all 3 unsafe validation cases.\n",
    "18/21 total correctness conceals zero unsafe recall. Record this tradeoff;\n",
    "do not assume physics loss always improves accuracy or certifies security."
   ],
   "id": "physics-informed-gnn-13"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. N-1 inference and independent reference / N-1 推理与参考\n",
    "\n",
    "Fix weights; each outage starts separately from the base. Compute line current\n",
    "(Vi-Vj)/(r+jx), then voltage/current limits. Known loss of supply fails;\n",
    "numerical failure is unknown. Only active base lines are candidates."
   ],
   "id": "physics-informed-gnn-14"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "operating[\"load_scale\"] = 1.5\n",
    "answer = screen(operating, models, include_reference=True)\n",
    "print(\"case   AC       data     physics   PI residual RMS\")\n",
    "for entry in answer[\"cases\"]:\n",
    "    print(entry[\"outage\"], *(entry[k][\"status\"] for k in (\"reference\", \"data\", \"physics\")),\n",
    "          entry[\"physics\"].get(\"residual\", {}).get(\"rms_pu\"))\n",
    "print(\"Aggregate:\", answer[\"summary\"])\n",
    "chosen = next(e for e in answer[\"cases\"] if e[\"outage\"] == \"24\")\n",
    "fig, axes = plt.subplots(1, 2, figsize=(11, 4))\n",
    "for kind, color in ((\"reference\", \"black\"), (\"data\", \"#b76819\"), (\"physics\", \"#187568\")):\n",
    "    d = chosen[kind]\n",
    "    axes[0].plot(range(1, 6), d[\"vm\"], \"o-\", label=kind, color=color)\n",
    "    axes[1].plot(range(6), [b[\"loading_pct\"] for b in d[\"branches\"]], \"o-\", label=kind, color=color)\n",
    "axes[0].axhline(.95, color=\"crimson\", linestyle=\"--\")\n",
    "axes[0].set(xlabel=\"Bus\", ylabel=\"Voltage pu\", xticks=range(1, 6))\n",
    "axes[1].axhline(100, color=\"crimson\", linestyle=\"--\")\n",
    "axes[1].set(xlabel=\"Line\", ylabel=\"Current / rating %\", xticks=range(6),\n",
    "            xticklabels=[e[\"id\"] for e in chosen[\"graph\"][\"edges\"]])\n",
    "for ax in axes: ax.legend()\n",
    "fig.suptitle(\"Outage 2-4, demand multiplier 1.5\"); fig.tight_layout(); plt.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-15"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "island = screen(dict(operating, topology=\"feeder\"), models)\n",
    "failed = next(e for e in island[\"cases\"] if e[\"outage\"] == \"12\")\n",
    "assert failed[\"unsupplied\"] == [2, 3, 4, 5]\n",
    "assert failed[\"physics\"][\"status\"] == \"unsafe\" and \"v\" not in failed[\"physics\"]\n",
    "assert solve_ac(build_graph(), max_iterations=0)[\"reason\"] == \"nonconvergence\"\n",
    "assert screen(operating, None, include_reference=False)[\"summary\"][\"reference\"] == \"unknown\"\n",
    "print(\"Known unsupplied buses:\", failed[\"unsupplied\"])"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-16"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Optional numerical correction / 单独的一次 Newton 校正\n",
    "\n",
    "This is a separate solver step, not part of raw GNN accuracy. It can reduce\n",
    "physical mismatch without making a genuinely unsafe case safe. One accepted\n",
    "step (with backtracking) is not a convergence or safety proof."
   ],
   "id": "physics-informed-gnn-17"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "g = build_graph(operating, \"24\")\n",
    "raw = predict(g, models[\"physics\"][\"weights\"])\n",
    "corrected = refine(g, raw)\n",
    "print(\"Maximum power mismatch pu before/after:\", corrected[\"before_pu\"], corrected[\"after_pu\"])\n",
    "print(\"Criteria before/after:\", diagnostics(g, raw)[\"status\"], diagnostics(g, corrected[\"v\"])[\"status\"])\n",
    "assert corrected[\"after_pu\"] <= corrected[\"before_pu\"]\n",
    "assert corrected[\"v\"][0] == [1., 0.]"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-18"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Check all 146 gradients / 检查全部参数梯度\n",
    "\n",
    "Central finite differences independently check the joint data-plus-AC loss.\n",
    "The label averaging weight is included; the source boundary remains hard."
   ],
   "id": "physics-informed-gnn-19"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "theta = initialize()\n",
    "g = build_graph({}, \"12\")\n",
    "sample = dict(graph=g, observed=solve_ac(g)[\"v\"])\n",
    "analytic = loss_gradient(sample, theta, physics_weight=.7, data_weight=4)[\"gradient\"]\n",
    "def total(t):\n",
    "    r = objective(g, predict(g, t), sample[\"observed\"], physics_weight=.7)\n",
    "    return 4*r[\"data\"]+.7*r[\"physics\"]\n",
    "epsilon, errors = 1e-6, []\n",
    "for key, size in SIZES.items():\n",
    "    for j in range(size):\n",
    "        plus, minus = copy_weights(theta), copy_weights(theta)\n",
    "        plus[key][j] += epsilon; minus[key][j] -= epsilon\n",
    "        numeric = (total(plus)-total(minus))/(2*epsilon)\n",
    "        errors.append(abs(numeric-analytic[key][j]))\n",
    "print(\"Maximum gradient discrepancy:\", max(errors))\n",
    "assert len(errors) == 146 and max(errors) < 1e-6"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-20"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 9. Held-out test groups / 留出测试工况组\n",
    "\n",
    "Freeze the selected settings before reading test metrics. A new seed (149)\n",
    "generates 3 held-out groups with the same six known contingencies. This is still\n",
    "an operating-value test, not a claim of unseen-topology generalization. Repeated\n",
    "tuning on these results turns them into validation; reserve new test data then."
   ],
   "id": "physics-informed-gnn-21"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "test_data = dataset(3, 149)\n",
    "val_inputs = {tuple(sorted(s[\"graph\"][\"case\"].items())) for s in validation[\"samples\"]}\n",
    "assert all(tuple(sorted(s[\"graph\"][\"case\"].items())) not in train_inputs | val_inputs\n",
    "           for s in test_data[\"samples\"])\n",
    "for kind in (\"data\", \"physics\"):\n",
    "    print(\"Frozen model test:\", kind, evaluate(test_data, models[kind][\"weights\"]))\n",
    "if not evaluate(test_data, models[\"physics\"][\"weights\"])[\"unsafe\"]:\n",
    "    print(\"This test split has no AC-unsafe cases; unsafe recall cannot be estimated.\")"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "physics-informed-gnn-22"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercises / 练习\n",
    "\n",
    "- Sweep lambda with fixed data; report voltage MAE, residual RMS and false-safe\n",
    "  counts separately. Adjust current ratings only: inferred voltage must not move.\n",
    "- Distinguish four message layers, 400 training epochs, and seven N-1 cases.\n",
    "- Do not force unsafe targets into safe limits with an unconditional inequality\n",
    "  loss. How would the formulation change if dispatch were a decision variable?\n",
    "- Design held-out outage types and entire networks. Which split tests which claim?\n",
    "- For unbalanced systems replace outputs and residuals with phase/neutral\n",
    "  quantities; sequence decomposition can analyze predicted three-phase voltages.\n",
    "\n",
    "References: [MATPOWER AC](https://matpower.app/manual/matpower/ACPowerFlow.html),\n",
    "[original PINNs (PDE context)](https://maziarraissi.github.io/PINNs/),\n",
    "[PyG message passing](https://pytorch-geometric.readthedocs.io/en/latest/tutorial/create_gnn.html)."
   ],
   "id": "physics-informed-gnn-23"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11"
  }
 }
}
