{
 "nbformat": 4,
 "nbformat_minor": 5,
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# GNN Preliminary / GNN 入门\n",
    "## Graphs, features, and message passing on a five-bus microgrid\n",
    "\n",
    "Run cells top to bottom. Complete model code is included; only figures need\n",
    "Matplotlib (`python -m pip install matplotlib`). No PyG, pretrained weights,\n",
    "external data, account, GPU, or hidden helper module is needed. Python 3.9+.\n",
    "\n",
    "学习路径：图 → 节点与边特征 → 消息、聚合、更新 → 训练 → 检查拓扑变化。\n",
    "The reference is a first-order balanced-voltage approximation, not full AC\n",
    "power flow. Training/validation cases share the fixed radial topology; topology\n",
    "changes are exploratory inference, not an established N-1 generalization result."
   ],
   "id": "gnn-preliminary-00"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Complete graph and GNN source / 完整图与模型源码\n",
    "\n",
    "`build_graph`: physical inputs → node X and line records.\n",
    "`arcs`: active physical lines → two directed computational arcs.\n",
    "`forward`: synchronous message/aggregate/update, then a shared node readout.\n",
    "`reference`: flat-voltage linearization Y_LL ΔV = -conj(S_load).\n",
    "`loss_gradient`, `train_model`: backpropagate through all tied layers; train all\n",
    "seven parameters (α, β, γ, three readout weights, and a bias)."
   ],
   "id": "gnn-preliminary-01"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "\"\"\"Five-bus graph, explicit message passing, and a seven-parameter GNN.\n",
    "\n",
    "Only the standard library is used. A flat-voltage linearization generates\n",
    "voltage labels; it is not full nonlinear AC power flow. All P/Q values are\n",
    "three-phase totals on a 1 MVA base; impedances use a 0.4 kV LL voltage base.\n",
    "Positive node P/Q denote net consumption. PV at bus 4 is fixed PQ, Q=0.\n",
    "\"\"\"\n",
    "import math\n",
    "\n",
    "DEFAULTS = dict(load_scale=1., bus5_kw=100., pv4_kw=50., z_scale=1.,\n",
    "                steps=3, aggregation=\"mean\", edge_aware=True,\n",
    "                open12=False, open23=False, open24=False, open45=False, tie35=False)\n",
    "INITIAL_THETA = dict(alpha=0.5, beta=0.6, gamma=0.4, w=[0.2, 0.2, -0.1], b=0.)\n",
    "\n",
    "\n",
    "def copy_theta(theta):\n",
    "    return dict(theta, w=theta[\"w\"][:])\n",
    "\n",
    "\n",
    "def config(parameters=None):\n",
    "    c = dict(DEFAULTS, **(parameters or {}))\n",
    "    for key, lo, hi in ((\"load_scale\", 0, 3), (\"bus5_kw\", 0, 300),\n",
    "                        (\"pv4_kw\", 0, 300), (\"z_scale\", 0.1, 3)):\n",
    "        if not math.isfinite(c[key]) or not lo <= c[key] <= hi:\n",
    "            raise ValueError(\"Invalid \" + key)\n",
    "    if (not isinstance(c[\"steps\"], int) or isinstance(c[\"steps\"], bool)\n",
    "            or not 1 <= c[\"steps\"] <= 4 or c[\"aggregation\"] not in (\"sum\", \"mean\")):\n",
    "        raise ValueError(\"Invalid message-passing configuration\")\n",
    "    for key in (\"edge_aware\", \"open12\", \"open23\", \"open24\", \"open45\", \"tie35\"):\n",
    "        if not isinstance(c[key], bool):\n",
    "            raise ValueError(\"Expected a boolean: \" + key)\n",
    "    return c\n",
    "\n",
    "\n",
    "def check_theta(theta):\n",
    "    values = [theta[\"alpha\"], theta[\"beta\"], theta[\"gamma\"], theta[\"b\"], *theta[\"w\"]]\n",
    "    if len(theta[\"w\"]) != 3 or not all(math.isfinite(v) and abs(v) <= 100 for v in values):\n",
    "        raise ValueError(\"Invalid GNN weights\")\n",
    "    return copy_theta(theta)\n",
    "\n",
    "\n",
    "def build_graph(parameters=None):\n",
    "    \"\"\"Encode specified net PQ, reference flag, and physical line parameters.\n",
    "\n",
    "    Bus labels 1..5 map to indices 0..4. Solved voltages and bus IDs are not\n",
    "    features. Slack P/Q=0 are placeholders, not its solved supply.\n",
    "    \"\"\"\n",
    "    c = config(parameters)\n",
    "    p = [v/1000 for v in (0, 80*c[\"load_scale\"], 100*c[\"load_scale\"],\n",
    "                          60*c[\"load_scale\"]-c[\"pv4_kw\"], c[\"bus5_kw\"]*c[\"load_scale\"])]\n",
    "    q = [v/1000 for v in (0, 30*c[\"load_scale\"], 40*c[\"load_scale\"],\n",
    "                          25*c[\"load_scale\"], 0.4*c[\"bus5_kw\"]*c[\"load_scale\"])]\n",
    "    nodes = [dict(id=i+1, p_pu=p[i], q_pu=q[i], reference=int(i == 0),\n",
    "                  x=[p[i]/0.2, q[i]/0.1, int(i == 0)]) for i in range(5)]\n",
    "    raw = [(\"12\", 0, 1, .04, .025, not c[\"open12\"]),\n",
    "           (\"23\", 1, 2, .06, .035, not c[\"open23\"]),\n",
    "           (\"24\", 1, 3, .05, .03, not c[\"open24\"]),\n",
    "           (\"45\", 3, 4, .055, .035, not c[\"open45\"]),\n",
    "           (\"35\", 2, 4, .08, .05, c[\"tie35\"])]\n",
    "    edges = [dict(id=name, **{\"from\": f, \"to\": t}, r=r*c[\"z_scale\"],\n",
    "                  x=x*c[\"z_scale\"], active=active) for name, f, t, r, x, active in raw]\n",
    "    return dict(nodes=nodes, edges=edges)\n",
    "\n",
    "\n",
    "def arcs(graph, edge_aware):\n",
    "    \"\"\"Two computational directions per active undirected line; no self-loops.\"\"\"\n",
    "    result = []\n",
    "    for e in graph[\"edges\"]:\n",
    "        if e[\"active\"]:\n",
    "            gate = 1/(1+math.hypot(e[\"r\"], e[\"x\"])/0.05) if edge_aware else 1.\n",
    "            for source, target in ((e[\"from\"], e[\"to\"]), (e[\"to\"], e[\"from\"])):\n",
    "                result.append(dict(edge=e[\"id\"], source=source, target=target, gate=gate))\n",
    "    return result\n",
    "\n",
    "\n",
    "def distances(graph, source):\n",
    "    d = [None]*len(graph[\"nodes\"])\n",
    "    d[source] = 0\n",
    "    for _ in graph[\"nodes\"]:\n",
    "        for e in graph[\"edges\"]:\n",
    "            if not e[\"active\"]:\n",
    "                continue\n",
    "            for u, v in ((e[\"from\"], e[\"to\"]), (e[\"to\"], e[\"from\"])):\n",
    "                if d[u] is not None and (d[v] is None or d[v] > d[u]+1):\n",
    "                    d[v] = d[u]+1\n",
    "    return d\n",
    "\n",
    "\n",
    "def forward(graph, parameters=None, theta=None):\n",
    "    \"\"\"Synchronous layers: every message reads the previous layer only.\n",
    "\n",
    "    m[j->i] = gate[e] * h[j]\n",
    "    aggregate = incoming sum or mean (zero for an empty neighborhood)\n",
    "    h_new[i] = tanh(alpha*h[i] + beta*aggregate[i] + gamma*x[i])\n",
    "    alpha/beta/gamma and the 3-channel readout are tied across all layers/nodes.\n",
    "    \"\"\"\n",
    "    c, theta = config(parameters), check_theta(theta or INITIAL_THETA)\n",
    "    n, links = len(graph[\"nodes\"]), arcs(graph, c[\"edge_aware\"])\n",
    "    degree = [0]*n\n",
    "    for a in links:\n",
    "        degree[a[\"target\"]] += 1\n",
    "    features = [v[\"x\"][:] for v in graph[\"nodes\"]]\n",
    "    layers, messages, aggregates = [features], [], []\n",
    "    for k in range(c[\"steps\"]):\n",
    "        old, agg, msg = layers[k], [[0.]*3 for _ in range(n)], []\n",
    "        for a in links:\n",
    "            value = [a[\"gate\"]*v for v in old[a[\"source\"]]]\n",
    "            for f in range(3):\n",
    "                agg[a[\"target\"]][f] += value[f]\n",
    "            msg.append(dict(a, value=value))\n",
    "        if c[\"aggregation\"] == \"mean\":\n",
    "            agg = [[v/degree[i] if degree[i] else 0. for v in row] for i, row in enumerate(agg)]\n",
    "        layers.append([[math.tanh(theta[\"alpha\"]*v + theta[\"beta\"]*agg[i][f]\n",
    "                                  + theta[\"gamma\"]*features[i][f])\n",
    "                        for f, v in enumerate(row)] for i, row in enumerate(old)])\n",
    "        messages.append(msg)\n",
    "        aggregates.append(agg)\n",
    "    output = [theta[\"b\"]+sum(w*h for w, h in zip(theta[\"w\"], row)) for row in layers[-1]]\n",
    "    return dict(layers=layers, messages=messages, aggregates=aggregates, degree=degree,\n",
    "                output=output, raw_voltage=[1. if graph[\"nodes\"][i][\"reference\"] else 1.-0.05*v\n",
    "                                           for i, v in enumerate(output)])\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 linear reference\")\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 reference(graph):\n",
    "    \"\"\"Y_LL * deltaV = -conj(S_load), flat source V=1 and magnitude ≈1+Re(deltaV).\n",
    "\n",
    "    Series lines only; losses and second-order terms are omitted. The connected\n",
    "    graph may have loops. If any bus is unsupplied, the whole comparison pauses.\n",
    "    This is not a voltage reference for a sustained island with its own source.\n",
    "    \"\"\"\n",
    "    source = next(i for i, v in enumerate(graph[\"nodes\"]) if v[\"reference\"])\n",
    "    reachable = distances(graph, source)\n",
    "    unsupplied = [v[\"id\"] for i, v in enumerate(graph[\"nodes\"]) if reachable[i] is None]\n",
    "    if unsupplied:\n",
    "        return dict(ok=False, unsupplied=unsupplied, voltage=None, reason=\"island\")\n",
    "    pq = [i for i in range(len(graph[\"nodes\"])) if i != source]\n",
    "    index, n = {v: i for i, v in enumerate(pq)}, len(pq)\n",
    "    g, b = [[0.]*n for _ in pq], [[0.]*n for _ in pq]\n",
    "    for e in graph[\"edges\"]:\n",
    "        if not e[\"active\"]:\n",
    "            continue\n",
    "        den = e[\"r\"]**2+e[\"x\"]**2\n",
    "        gr, bi = e[\"r\"]/den, -e[\"x\"]/den\n",
    "        f, t = e[\"from\"], e[\"to\"]\n",
    "        for u, v, sign in ((f, f, 1), (t, t, 1), (f, t, -1), (t, f, -1)):\n",
    "            if u in index and v in index:\n",
    "                g[index[u]][index[v]] += sign*gr\n",
    "                b[index[u]][index[v]] += sign*bi\n",
    "    matrix = [g[i]+[-v for v in b[i]] for i in range(n)]+[b[i]+g[i] for i in range(n)]\n",
    "    rhs = [-graph[\"nodes\"][i][\"p_pu\"] for i in pq]+[graph[\"nodes\"][i][\"q_pu\"] for i in pq]\n",
    "    delta = linear_solve(matrix, rhs)\n",
    "    voltage = [1.]*len(graph[\"nodes\"])\n",
    "    for i, bus in enumerate(pq):\n",
    "        voltage[bus] = 1+delta[i]\n",
    "    return dict(ok=True, unsupplied=[], voltage=voltage, delta_re=delta[:n], delta_im=delta[n:], pq=pq)\n",
    "\n",
    "\n",
    "def solve(parameters=None):\n",
    "    c = config(parameters)\n",
    "    graph, theta = build_graph(c), check_theta(c.get(\"theta\", INITIAL_THETA))\n",
    "    passed, ref = forward(graph, c, theta), reference(graph)\n",
    "    adjacency = [[int(any(e[\"active\"] and ((e[\"from\"] == i and e[\"to\"] == j)\n",
    "                      or (e[\"to\"] == i and e[\"from\"] == j)) for e in graph[\"edges\"]))\n",
    "                  for j in range(5)] for i in range(5)]\n",
    "    links = arcs(graph, c[\"edge_aware\"])\n",
    "    mae = sum(abs(a-b) for i, (a, b) in enumerate(zip(passed[\"raw_voltage\"], ref[\"voltage\"]))\n",
    "              if not graph[\"nodes\"][i][\"reference\"])/4 if ref[\"ok\"] else None\n",
    "    return dict(ok=True, case=c, graph=graph, theta=theta, **passed, reference=ref,\n",
    "                adjacency=adjacency, edge_index=[[a[\"source\"] for a in links], [a[\"target\"] for a in links]],\n",
    "                prediction=passed[\"raw_voltage\"] if ref[\"ok\"] else None, mae_pu=mae)\n",
    "\n",
    "\n",
    "def dataset(count, seed):\n",
    "    state = int(seed) & 0xffffffff\n",
    "\n",
    "    def random():\n",
    "        nonlocal state\n",
    "        state = (1664525*state+1013904223) & 0xffffffff\n",
    "        return (state+0.5)/4294967296\n",
    "\n",
    "    result = []\n",
    "    for _ in range(count):\n",
    "        c = dict(load_scale=0.6+0.8*random(), bus5_kw=60+100*random(),\n",
    "                 pv4_kw=100*random(), z_scale=0.8+0.4*random())\n",
    "        graph = build_graph(c)\n",
    "        result.append(dict(graph=graph, target=reference(graph)[\"voltage\"]))\n",
    "    return result\n",
    "\n",
    "\n",
    "def loss_gradient(graph, target, parameters, theta):\n",
    "    \"\"\"Backpropagate through readout and ALL message-passing layers.\n",
    "\n",
    "    Seven learned scalars: alpha, beta, gamma, w[0:3], b. Contributions to tied\n",
    "    parameters sum over every node, edge, and layer where they were used.\n",
    "    Loss excludes the reference bus; voltage drops are scaled by 0.05 pu.\n",
    "    \"\"\"\n",
    "    c, passed = config(parameters), forward(graph, parameters, theta)\n",
    "    n, count = len(graph[\"nodes\"]), len(graph[\"nodes\"])-1\n",
    "    g, loss, dh = dict(alpha=0., beta=0., gamma=0., w=[0.]*3, b=0.), 0., [[0.]*3 for _ in range(n)]\n",
    "    for i in range(n):\n",
    "        if graph[\"nodes\"][i][\"reference\"]:\n",
    "            continue\n",
    "        error = passed[\"output\"][i]-(1-target[i])/0.05\n",
    "        d = 2*error/count\n",
    "        loss += error*error/count\n",
    "        g[\"b\"] += d\n",
    "        for f in range(3):\n",
    "            g[\"w\"][f] += d*passed[\"layers\"][-1][i][f]\n",
    "            dh[i][f] = d*theta[\"w\"][f]\n",
    "    for k in reversed(range(c[\"steps\"])):\n",
    "        previous = [[0.]*3 for _ in range(n)]\n",
    "        dz = [[v*(1-passed[\"layers\"][k+1][i][f]**2) for f, v in enumerate(row)] for i, row in enumerate(dh)]\n",
    "        for i in range(n):\n",
    "            for f in range(3):\n",
    "                g[\"alpha\"] += dz[i][f]*passed[\"layers\"][k][i][f]\n",
    "                g[\"beta\"] += dz[i][f]*passed[\"aggregates\"][k][i][f]\n",
    "                g[\"gamma\"] += dz[i][f]*graph[\"nodes\"][i][\"x\"][f]\n",
    "                previous[i][f] += theta[\"alpha\"]*dz[i][f]\n",
    "        for a in passed[\"messages\"][k]:\n",
    "            divisor = passed[\"degree\"][a[\"target\"]] if c[\"aggregation\"] == \"mean\" else 1\n",
    "            for f in range(3):\n",
    "                previous[a[\"source\"]][f] += theta[\"beta\"]*a[\"gate\"]*dz[a[\"target\"]][f]/divisor\n",
    "        dh = previous\n",
    "    return dict(loss=loss, gradient=g)\n",
    "\n",
    "\n",
    "def evaluate(data, parameters, theta):\n",
    "    loss, mae = 0., 0.\n",
    "    for sample in data:\n",
    "        passed = forward(sample[\"graph\"], parameters, theta)\n",
    "        for i, node in enumerate(sample[\"graph\"][\"nodes\"]):\n",
    "            if not node[\"reference\"]:\n",
    "                error = passed[\"raw_voltage\"][i]-sample[\"target\"][i]\n",
    "                loss += (error/0.05)**2\n",
    "                mae += abs(error)\n",
    "    n = len(data)*(len(data[0][\"graph\"][\"nodes\"])-1)\n",
    "    return dict(mse=loss/n, mae_pu=mae/n)\n",
    "\n",
    "\n",
    "def train_model(parameters=None):\n",
    "    \"\"\"Train all 7 parameters on 32 radial cases; validate on 16 new cases.\n",
    "\n",
    "    The data distribution is fixed and independent of the current lab operating\n",
    "    controls. Hyperparameters steps/aggregation/edge_aware select the model.\n",
    "    Topology-changing cases are not part of this training/validation distribution.\n",
    "    \"\"\"\n",
    "    c = config(parameters)\n",
    "    epochs, lr = c.get(\"epochs\", 400), c.get(\"lr\", 0.03)\n",
    "    if not isinstance(epochs, int) or not 0 <= epochs <= 1000 or not math.isfinite(lr) or not 0 < lr <= .2:\n",
    "        raise ValueError(\"Invalid training settings\")\n",
    "    training, validation = dataset(32, 17), dataset(16, 83)\n",
    "    theta, history = copy_theta(INITIAL_THETA), []\n",
    "\n",
    "    def record(epoch):\n",
    "        history.append(dict(epoch=epoch, train=evaluate(training, c, theta), validation=evaluate(validation, c, theta)))\n",
    "\n",
    "    record(0)\n",
    "    for epoch in range(1, epochs+1):\n",
    "        g = dict(alpha=0., beta=0., gamma=0., w=[0.]*3, b=0.)\n",
    "        for sample in training:\n",
    "            d = loss_gradient(sample[\"graph\"], sample[\"target\"], c, theta)[\"gradient\"]\n",
    "            for key in (\"alpha\", \"beta\", \"gamma\", \"b\"):\n",
    "                g[key] += d[key]/len(training)\n",
    "            for f in range(3):\n",
    "                g[\"w\"][f] += d[\"w\"][f]/len(training)\n",
    "        for key in (\"alpha\", \"beta\", \"gamma\", \"b\"):\n",
    "            theta[key] -= lr*g[key]\n",
    "        for f in range(3):\n",
    "            theta[\"w\"][f] -= lr*g[\"w\"][f]\n",
    "        check_theta(theta)\n",
    "        if epoch % 10 == 0 or epoch == epochs:\n",
    "            record(epoch)\n",
    "    return dict(ok=True, theta=theta, history=history, training_count=32, validation_count=16,\n",
    "                epochs=epochs, lr=lr, config={key: c[key] for key in (\"steps\", \"aggregation\", \"edge_aware\")}, parameter_count=7)"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "gnn-preliminary-02"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Inputs and main / 输入与主程序\n",
    "\n",
    "Consumption is positive. All P/Q are three-phase totals on a 1 MVA base;\n",
    "voltage base is 0.4 kV line-to-line. X=[P/0.2 pu, Q/0.1 pu, reference flag].\n",
    "Bus 1 has known V=1 and placeholder P=Q=0, not its solved supply. The bus-4\n",
    "solar inverter is fixed PQ with Q=0. Node IDs and solved voltages are not features."
   ],
   "id": "gnn-preliminary-03"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "case = dict(DEFAULTS, theta=copy_theta(INITIAL_THETA))\n",
    "# case.update(bus5_kw=160, pv4_kw=100, tie35=True)\n",
    "\n",
    "def main():\n",
    "    parameters = dict(case)\n",
    "    answer = solve(parameters)\n",
    "    print(\"Node X:\", [v[\"x\"] for v in answer[\"graph\"][\"nodes\"]])\n",
    "    print(\"edge_index (zero-based):\", answer[\"edge_index\"])\n",
    "    print(\"Active physical lines:\", len(answer[\"edge_index\"][0])//2)\n",
    "    print(\"Reference status:\", answer[\"reference\"][\"ok\"])\n",
    "    return answer\n",
    "\n",
    "result = main()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "gnn-preliminary-04"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Graph and embeddings / 图与节点表示\n",
    "\n",
    "Each layer reads only the previous layer. The arrows in the website are\n",
    "computational messages, not current or power-flow directions. Layer 0 has\n",
    "normalized inputs; later channels are latent features, not physical voltages."
   ],
   "id": "gnn-preliminary-05"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "layer = 1\n",
    "positions = [(0, 0), (1, 0), (2, 0.8), (2, -0.8), (3, 0)]\n",
    "fig, axes = plt.subplots(1, 2, figsize=(11, 4))\n",
    "for edge in result[\"graph\"][\"edges\"]:\n",
    "    u, v = edge[\"from\"], edge[\"to\"]\n",
    "    axes[0].plot([positions[u][0], positions[v][0]], [positions[u][1], positions[v][1]],\n",
    "                 \"-\" if edge[\"active\"] else \"--\", color=\"teal\" if edge[\"active\"] else \"silver\")\n",
    "for i, (x, y) in enumerate(positions):\n",
    "    axes[0].scatter(x, y, s=600, facecolor=\"white\", edgecolor=\"teal\", zorder=3)\n",
    "    axes[0].text(x, y, str(i+1), ha=\"center\", va=\"center\", zorder=4)\n",
    "axes[0].set(title=\"Five-bus microgrid\", xlim=(-0.3, 3.3), ylim=(-1.1, 1.1))\n",
    "axes[0].axis(\"off\")\n",
    "for f in range(3):\n",
    "    axes[1].bar([i+1+(f-1)*0.22 for i in range(5)],\n",
    "                [row[f] for row in result[\"layers\"][layer]], width=0.2, label=f\"channel {f+1}\")\n",
    "axes[1].set(xlabel=\"Bus\", ylabel=\"Feature value\", title=f\"Embeddings after layer {layer}\", xticks=range(1, 6))\n",
    "axes[1].legend(); fig.tight_layout(); plt.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "gnn-preliminary-06"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Trace incoming messages / 逐条检查消息\n",
    "\n",
    "Inspect bus 2 (index 1). Gate a_e = 1/(1+sqrt(r²+x²)/0.05) is a chosen feature\n",
    "transform, not electrical admittance. Mean divides by active incoming degree;\n",
    "an empty neighborhood returns zero. α and γ retain self information separately."
   ],
   "id": "gnn-preliminary-07"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "node, layer = 1, 1\n",
    "for a in result[\"messages\"][layer-1]:\n",
    "    if a[\"target\"] == node:\n",
    "        print(f\"{a['source']+1} -> {node+1}: gate={a['gate']:.6f}, message={a['value']}\")\n",
    "print(\"Aggregate:\", result[\"aggregates\"][layer-1][node])\n",
    "print(\"Old state:\", result[\"layers\"][layer-1][node])\n",
    "print(\"New state:\", result[\"layers\"][layer][node])"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "gnn-preliminary-08"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Train all seven parameters / 训练全部七个参数\n",
    "\n",
    "32 training graphs and 16 validation graphs use separate fixed seeds. Load\n",
    "multiplier 0.6..1.4, bus-5 base load 60..160 kW, solar 0..100 kW, impedance\n",
    "multiplier 0.8..1.2. Both sets use the default radial topology. Training MSE uses\n",
    "voltage drops scaled by 0.05 pu; voltage MAE is reported in actual pu.\n",
    "Reference bus 1 is pinned to 1 pu and excluded from loss and MAE."
   ],
   "id": "gnn-preliminary-09"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fitted = train_model(dict(case, epochs=400, lr=0.03))\n",
    "trained_case = dict(case, theta=fitted[\"theta\"])\n",
    "trained_result = solve(trained_case)\n",
    "print(\"All learned parameters:\", fitted[\"theta\"])\n",
    "print(\"Initial validation:\", fitted[\"history\"][0][\"validation\"])\n",
    "print(\"Final validation:\", fitted[\"history\"][-1][\"validation\"])\n",
    "print(\"Current-case MAE pu:\", trained_result[\"mae_pu\"])\n",
    "assert fitted[\"history\"][-1][\"validation\"][\"mse\"] < fitted[\"history\"][0][\"validation\"][\"mse\"]"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "gnn-preliminary-10"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "fig, axes = plt.subplots(1, 2, figsize=(11, 4))\n",
    "if trained_result[\"reference\"][\"ok\"]:\n",
    "    axes[0].plot(range(1, 6), trained_result[\"reference\"][\"voltage\"], \"ko--\", label=\"linear reference\")\n",
    "    axes[0].plot(range(1, 6), trained_result[\"prediction\"], \"o-\", label=\"trained GNN\")\n",
    "    axes[0].set(xlabel=\"Bus ID (not a physical path)\", ylabel=\"Voltage pu\", xticks=range(1, 6))\n",
    "    axes[0].legend()\n",
    "for key, label in ((\"train\", \"training\"), (\"validation\", \"validation\")):\n",
    "    axes[1].semilogy([v[\"epoch\"] for v in fitted[\"history\"]],\n",
    "                     [v[key][\"mse\"] for v in fitted[\"history\"]], label=label)\n",
    "axes[1].set(xlabel=\"Training epoch\", ylabel=\"Scaled voltage-drop MSE\")\n",
    "axes[1].legend(); fig.tight_layout(); plt.show()"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "gnn-preliminary-11"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Locality check / 局部性检查\n",
    "\n",
    "The default path 5–4–2–1 has three hops. A bus-5 feature perturbation cannot\n",
    "reach bus 1 before layer 3. Inspect the embedding, because the source voltage\n",
    "readout is pinned regardless of hidden-state changes. K layers ≠ K epochs."
   ],
   "id": "gnn-preliminary-12"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "a = solve(dict(case, steps=4))\n",
    "b = solve(dict(case, steps=4, bus5_kw=180))\n",
    "differences = [max(abs(x-y) for x, y in zip(ha[0], hb[0]))\n",
    "               for ha, hb in zip(a[\"layers\"], b[\"layers\"])]\n",
    "print(\"Bus-1 embedding change at layers 0..4:\", differences)\n",
    "assert all(v == 0 for v in differences[:3])\n",
    "assert differences[3] > 1e-5"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "gnn-preliminary-13"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Permutation equivariance / 节点重编号\n",
    "\n",
    "Reorder rows AND edge endpoints consistently. The reference flag stays with\n",
    "its physical bus. The model sees no numerical bus ID or drawing coordinate.\n",
    "The outputs should follow the same row permutation; this does not say that\n",
    "arbitrarily changing physical topology leaves outputs unchanged."
   ],
   "id": "gnn-preliminary-14"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "graph = build_graph(case)\n",
    "order = [4, 1, 0, 3, 2]  # new row -> old row\n",
    "inverse = {old: new for new, old in enumerate(order)}\n",
    "permuted = dict(nodes=[dict(graph[\"nodes\"][i]) for i in order],\n",
    "                edges=[dict(e, **{\"from\": inverse[e[\"from\"]], \"to\": inverse[e[\"to\"]]}) for e in graph[\"edges\"]])\n",
    "original = forward(graph, case, fitted[\"theta\"])\n",
    "reordered = forward(permuted, case, fitted[\"theta\"])\n",
    "error = max(abs(reordered[\"output\"][i]-original[\"output\"][old]) for i, old in enumerate(order))\n",
    "print(\"Permutation error:\", error)\n",
    "assert error < 1e-10"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "gnn-preliminary-15"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Gradient check / 梯度检查\n",
    "\n",
    "Compare backpropagation through all three tied layers with a central finite\n",
    "difference for every parameter. A valid gradient is necessary for optimization;\n",
    "it does not by itself establish predictive accuracy or physical feasibility."
   ],
   "id": "gnn-preliminary-16"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "graph = build_graph()\n",
    "target_voltage = reference(graph)[\"voltage\"]\n",
    "c, theta = config(), copy_theta(INITIAL_THETA)\n",
    "analytic = loss_gradient(graph, target_voltage, c, theta)[\"gradient\"]\n",
    "epsilon, errors = 1e-6, []\n",
    "for key in (\"alpha\", \"beta\", \"gamma\", \"w\", \"b\"):\n",
    "    for j in (range(3) if key == \"w\" else [None]):\n",
    "        plus, minus = copy_theta(theta), copy_theta(theta)\n",
    "        if j is None:\n",
    "            plus[key] += epsilon; minus[key] -= epsilon\n",
    "            expected = analytic[key]\n",
    "        else:\n",
    "            plus[key][j] += epsilon; minus[key][j] -= epsilon\n",
    "            expected = analytic[key][j]\n",
    "        numeric = (loss_gradient(graph, target_voltage, c, plus)[\"loss\"]\n",
    "                   - loss_gradient(graph, target_voltage, c, minus)[\"loss\"])/(2*epsilon)\n",
    "        errors.append(abs(numeric-expected))\n",
    "print(\"Maximum gradient error:\", max(errors))\n",
    "assert max(errors) < 1e-7"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "gnn-preliminary-17"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 9. A line outage and an alternate path / 线路退出与替代路径\n",
    "\n",
    "Trip 2–4 with the tie open, then close 3–5. Message passing continues on any\n",
    "remaining component, but a finite embedding is not an energized operating\n",
    "point. The app pauses voltage comparison when any bus loses the sole source.\n",
    "The fixed-PQ solar inverter does not automatically become grid-forming."
   ],
   "id": "gnn-preliminary-18"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "outage = solve(dict(trained_case, open24=True, tie35=False))\n",
    "restored_path = solve(dict(trained_case, open24=True, tie35=True))\n",
    "print(\"Outage reference:\", outage[\"reference\"])\n",
    "print(\"Alternate path connected:\", restored_path[\"reference\"][\"ok\"])\n",
    "assert outage[\"prediction\"] is None\n",
    "assert outage[\"reference\"][\"unsupplied\"] == [4, 5]\n",
    "assert restored_path[\"reference\"][\"ok\"]"
   ],
   "execution_count": null,
   "outputs": [],
   "id": "gnn-preliminary-19"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Exercises and next steps / 练习与后续\n",
    "\n",
    "- Reproduce bus 2's first layer; switch mean to sum. Explain the degree factor.\n",
    "- Set β=0 and inspect locality; disable impedance gating and vary line impedance.\n",
    "- Separate one forward pass, K message layers, and training epochs.\n",
    "- Define node-level, edge-level, and graph-level prediction tasks for a microgrid.\n",
    "- Plan train/validation/test groups for unseen contingencies. This notebook\n",
    "  validates new operating values on a fixed radial graph, not unseen topologies.\n",
    "- Replace the teaching labels with accurately audited AC / three-phase results,\n",
    "  define security criteria and status handling, then evaluate errors near limits.\n",
    "\n",
    "Read: [Gilmer et al. MPNNs](https://proceedings.mlr.press/v70/gilmer17a.html),\n",
    "[PyG message passing](https://pytorch-geometric.readthedocs.io/en/latest/tutorial/create_gnn.html),\n",
    "[Distill GNN introduction](https://distill.pub/2021/gnn-intro/)."
   ],
   "id": "gnn-preliminary-20"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11"
  }
 }
}
