← Physics-informed GNN course

Physics-informed GNN · Module 6

Physics-informed GNN · Microgrid N-1 Security

Balanced Power Flow defined the equations a voltage state must satisfy. GNN Preliminary showed how buses exchange information. This chapter connects them: a GNN predicts complex voltages, AC equations check whether those voltages explain the specified demands and network, and the resulting mismatch enters the training loss. After training, screen individual line outages using currents derived from predicted voltages.

Learning outcome. Derive differentiable AC residuals from specified PQ and topology; distinguish label loss, physics loss, and the reference boundary; train matched data-only and physics-informed models; separate a small residual, an accurate prediction, and an operating point within limits.

1. From voltage regression to physics constraints

The previous chapter used a linear voltage reference to explain message passing. Here labels come from full balanced AC power flow. Keep the five-bus microgrid: bus 1 is the sole external voltage source, bus 2 a junction with demand, buses 3 and 5 demand buses, and bus 4 demand plus fixed-PQ solar. Add a 1–3 backup line and close the 3–5 tie by default, so single outages can retain a supply path. Both paths lead to the same bus 1; no second voltage source is introduced.

① Specified caseP, Q, line r/x, and post-outage connections. Solved voltage labels are not inputs.
② GNN stateFour message layers → Re(V), Im(V) at PQ buses. Reference voltage is fixed.
③ AC residual → lossYbus V → I → S. Compare implied and specified power; backpropagate into θ.
④ Security screeningFix θ, infer each contingency, then check supply, voltage, and current limits.

Assumptions, units, and signs

  • Balanced three-phase steady state, series-only lines; no transformers, shunts, or regulators. Loads and inverters are specified constant PQ, with no PV voltage control.
  • Three-phase power base 1 MVA, line-to-line voltage base 0.4 kV; Zbase = 0.16 Ω and Ibase = 1443.376 A. Equations use pu; kW/kvar are converted at input.
  • Pnet and Qnet are positive for consumption: net demand = load − generation. Sinj is positive into the network, so specified PQ injection is −Pnet − jQnet.
  • Bus 1 is fixed at V₁ = 1 + j0. Input P = Q = 0 is a placeholder, not its solved supply. Solar has Q = 0 and cannot establish voltage in a disconnected island.
BusDemand at multiplier 1Generation / input convention
1External referenceV = 1∠0; placeholder P/Q = 0
280 kW / 30 kvarNone
3100 kW / 40 kvarNone
460 kW / 25 kvarDefault solar 50 kW, Q = 0
5Default 100 kW / 40 kvarAdjustable base kW, demand Q/P = 0.4

The multiplier scales all demand; solar is independent. At the default multiplier 1.2, bus 4 consumes net 22 kW / 30 kvar.

Liner pux puCurrent rating pu (A)
1–20.0400.0250.50 (721.69)
2–30.0600.0350.22 (317.54)
2–40.0500.0300.22 (317.54)
4–50.0550.0350.18 (259.81)
3–50.0800.0500.18 (259.81)
1–30.0700.0450.45 (649.52)

These are assumed teaching-case parameters and ratings. The impedance multiplier scales r/x; the rating multiplier independently scales current limits.

2. Derive AC residuals from complex voltage

Let c denote the base case or a single-line outage. Rebuild both computational arcs and Yᶜ for every case. Removing line i–j deletes two message arcs and removes its +yij contributions to Yii, Yjj and −yij contributions to Yij, Yji. Lowercase yij = 1/(rij + jxij) is a branch admittance; uppercase Yij is a bus-admittance matrix entry.

Voltage stateGNN outputs u, w: continuous differentiable predictions.
Network currentIr = Gu − Bw
Ii = Bu + Gw
Bus powerPcalc = u Ir + w Ii
Qcalc = w Ir − u Ii
Specified powerrP = Pcalc + Pnet
rQ = Qcalc + Qnet

For the PQ set ℒ = {2,3,4,5}:

A converged power-flow state makes these mismatches nearly zero; a GNN output generally does not. Exclude reference-bus P/Q from the residual, because its supply is not specified. Setting V̂₁ = 1 + j0 is a hard boundary. Penalizing PQ mismatch with a finite weight is a soft constraint.

Worked residual: check the signs

At multiplier 1.2, bus 2 consumes 0.096 + j0.036 pu. Suppose a predicted state implies injection −0.090 − j0.030 pu: rP,2 = +0.006 and rQ,2 = +0.006 pu. That state does not yet explain specified consumption. With sS = 0.2 pu, both normalized residuals equal 0.03. Averaging eight terms over four PQ buses, this bus contributes (0.03² + 0.03²)/8 = 0.000225. All currents and powers come from the same predicted voltages; no extra hidden label is required.

3. Add physics to the training loss

For one graph, the data term uses real and imaginary voltage errors; the physics term uses PQ mismatches. Fix sV = 0.05 pu and sS = 0.2 pu so quantities with different units and scales are normalized before addition.

Let 𝒟L contain labeled training graphs and 𝒟C all training input / collocation graphs. Unlabeled graphs still specify PQ and line parameters, enabling a physics loss without supervised targets.

Each term is averaged over its own sample count. Omit the data term if no labels exist. No labels and λ = 0 means no training signal; random initialization is not a trained model. λ balances normalized terms, not a probability of constraint satisfaction. Changing normalization also changes what a particular λ means.

Why not penalize every violation into a “safe” prediction?

Power-balance equations describe electrical states, including overloaded or undervoltage states. A security predictor must preserve the true state of dangerous operating points. Forcing every predicted state inside limits can make a real violation appear safe.

This objective therefore has no voltage or current inequality penalty; apply limits after inference. A dispatch optimizer can instead treat generation or load shedding as control decisions and handle inequalities conditionally. That is a different task from predicting the actual state at fixed PQ.

4. See the loss through a voltage perturbation

This workbench uses the contingency selected in section 8, initially outage 2–4. Start from unperturbed AC voltages: residuals should approach the solver tolerance. Then add 0.01 pu to Re(V₅). Ybus couples neighboring buses, so mismatch appears at bus 5 and its active neighbors. Compare the correct post-outage matrix with the stale base matrix.

Loss workbench · inspect the physics term at a fixed output

Use the selected contingency. Start from the AC reference and perturb bus 5's real voltage by +0.01 pu; inspect mismatch at that bus and its neighbors. Perturbations affect this panel only, not the security table.

Ldata—
Lphys—
λ Lphys—
Ldata + λ Lphys—

ΔP, ΔQ · pu

ΔPΔQ

Computed on the current topology

This panel uses a clean AC label to illustrate one-case Ldata; training applies its own label mask and noise. Changing λ immediately changes this fixed-output loss; retraining changes θ. The readout also evaluates stale base-case Ybus to check whether the contingency topology was rebuilt.

5. How does the GNN receive a physical gradient?

Retain inputs xᵢ = [Pnet/0.2 pu, Qnet/0.1 pu, ref] and two computational arcs per active line. Use six hidden channels and four synchronous message layers. The matrices below are shared across buses and message layers, with 146 trainable parameters in total.

The impedance gate is a chosen feature transform, not admittance. Empty-neighborhood means are zero. The readout does not clip voltages to the safe band. Numerical bus IDs, drawing coordinates, solved labels, and solved source power are excluded from inputs.

The equation above gives one graph’s gradient; training averages over collocation graphs. AC calculations use addition, multiplication, conjugation, and fixed Ybus; they are differentiable in u, w. Differentiate the residual with respect to voltage, then backpropagate through the readout, tanh, aggregation, and all four tied layers. No differentiation through the Newton solver is required. The source implements analytical derivatives and full backpropagation. All 146 joint-loss parameter gradients pass central finite differences; AC references are independently checked against pandapower.

6. Matched training and honest validation

Generate 8 training operating groups and 3 other validation groups with fixed seeds. Each group fixes demand, solar, and impedance, then expands into the base case and six known outages: 56 training and 21 validation graphs. Split operating groups before expanding contingencies, keeping variants of the same operating point on the same side.

Ranges: demand multiplier 0.6–1.5, bus-5 base load 60–160 kW, solar 0–100 kW, impedance multiplier 0.8–1.2; all start from the six-line base graph. By default only two training groups are labeled (14 graphs); 42 supply physics inputs only. Unlabeled graphs do not solve or retain AC voltage targets for training. Add independent Gaussian noise σ = 0.002 pu to labeled real and imaginary voltages. Validation uses clean AC targets and never contributes gradients.

Controlled experiment · data-only versus physics-informed GNN

Both runs share initialization, operating groups, labels, optimizer, and epochs; only the physics weight differs. Default snapshots generated with the complete Python source load for immediate use, or retrain in your browser.

Loading default course snapshots…

Validation metric · raw GNNData onlyPI-GNN

Validation voltage MAE (pu)

Validation power-residual RMS (pu)

Data-only GNNPI-GNN · raw

Validation uses three other operating groups (21 cases), with the same six outage types. It evaluates new operating values, not generalization to entirely new topologies. Metrics always use raw GNN outputs, excluding optional Newton correction. False-safe means AC violates a criterion while the GNN predicts no violation.

Current loss history, training settings, and complete weights
Download default model snapshots

Defaults: 400 epochs, Adam learning rate 0.003, identical inputs, initialization, and optimization settings; data-only λ = 0 versus PI λ = 1. In the supplied snapshots, validation power-residual RMS falls from about 0.04217 pu to 0.02441 pu, but voltage-magnitude MAE changes from 0.00445 pu to 0.00577 pu. The physics term improves equation consistency in this experiment, while voltage MAE worsens. Noisy labels, limited capacity, and finite optimization can create this tradeoff.

Both default models predict all three AC-unsafe validation cases as safe. Overall correctness is 18/21, yet unsafe-case recall is zero. Inspecting those errors is more informative than reporting average loss or accuracy alone. Vary λ, labeled fraction, noise, and epochs and record all metrics; PI is not guaranteed to win. Use validation for tuning and a separate final test set; the Notebook includes an illustrative held-out group split.

7. Convert predicted states into N-1 criteria

Hold learned θ fixed and enumerate the base case plus every in-service line removed individually. Each outage starts from the base; outages do not accumulate. For each c, first check reachability from the sole reference source, then derive branch current and check limits:

  • Known unsupplied buses fail by topology. Fixed-PQ solar does not become a voltage reference.
  • A supplied case fails when any bus voltage or in-service current violates limits. Default voltage band: 0.95–1.05 pu.
  • AC numerical failure is unknown, as are model criteria without trained weights. Loss of supply and numerical failure are different outcomes.
  • Any failed case fails the aggregate. If none fail but any are unknown, the aggregate is unknown. Only all passing cases show within limits. Learned columns are predictions, requiring AC or other trusted verification.

What is one physical correction?

Optionally start at the PI-GNN state and take one backtracked Newton step with the post-outage Jacobian, then check limits. This is a separate numerical step after inference, labeled “PI + 1 Newton.” Training metrics always use raw GNN outputs. One correction is not proof of convergence, and a low residual does not imply limits are satisfied.

The scope is balanced AC static screening at fixed PQ, without redispatch. It does not assess transient stability, frequency, protection, device control, or source capacity. To extend to three-phase unbalance, predict Vabc (and neutral if needed) and replace residuals with the phase / neutral equations from Unbalanced Power Flow. Sequence components help analyze outputs; they do not replace the applicable phase-domain model.

8. Interactive microgrid N-1 experiment

Choose light demand, then stressed demand; compare AC with both model columns. Every single outage remains connected in the default two-path network. “Loss of supply” opens the 1–3 backup in the base and selects outage 1–2. Changing ratings changes security boundaries, not inferred voltage or power mismatch. Demand, solar, and impedance change physical inputs.

Microgrid N-1 screening · balanced AC

Current base case + each in-service line outage

AC reference · aggregate N-1—
Data-only GNN · prediction—
PI-GNN—
Case (select)ACData onlyPI-GNNAC min |V|AC max I/ImaxPI RMS ΔS (pu)

The aggregate includes the base case and all current candidates. Known loss of supply fails; AC numerical failure is unknown, never a fabricated zero voltage or automatic unsafe label. Model columns are predicted criteria; a low residual alone does not establish safety.

Bus voltage magnitude

Branch current / rating

ACData-only GNNPI-GNN
Inspect voltage, angle, line, and security details
BusAC |V|Data |V|PI |V|AC θ°PI θ°
Linestatusr / x puImax AAC I API I A

9. Read, run, and edit complete Python

Folded model.py contains the graph, AC residuals, complete backpropagation, and training. main.py selects inputs, applies active weights, enumerates outages, and reports results. Inference does not require pandapower; separate solve_ac() calls generate references. The Python panel runs independently and plots its own returned values.

1 · Inputs, weights, and function sources

case.operating contains physical controls; case.models contains 146 parameters per active model. case.selected_outage and case.correct_physics select the displayed case and separate correction step. The compact preview omits weight values; expand them in the training panel.

2 · Expand model.py: complete AC, GNN, loss, and backpropagation

Only standard-library math is required. build_graph() rebuilds arcs and Ybus; predict() runs the GNN; objective() computes normalized losses and voltage gradients; backward() propagates to every parameter; train_model() trains. solve_ac() generates references, screen() enumerates contingencies, and refine() is an optional separate Newton step. No pandapower call is needed for inference.

3 · main(): predict states, then evaluate security criteria

Download complete model

The first run downloads Pyodide; computation runs in a separate worker. Python uses the active weights for inference and reference comparison; call train_model() explicitly to retrain. Code edits affect only the Python experiment and can be downloaded.

Ready to run.

10. Practice and downloads

  1. At AC voltages for outage 2–4, add 0.01 pu to Re(V₅). Which active neighbors show ΔP/ΔQ? What changes if you use stale base-case Ybus?
  2. At fixed predictions, move λ from 0 to 2. What changes immediately? What changes only after retraining?
  3. Train with 0% labels and λ = 0. Why must the data-only model remain unknown? What information does an unlabeled graph provide when λ > 0?
  4. Find a false-safe prediction at stressed demand. Compare voltage error, power mismatch, and distance to the violated limit.
  5. Enable one Newton correction; record before/after maximum power residual and criteria. Why must corrected results be reported separately from raw GNN performance?
  6. Design splits for unseen outages or unseen networks. Which question does the current operating-group split answer?