---
title: "Power-flow lab: Y-bus, injections and Gauss–Seidel"
heading: Writing the first half of a power-flow program in Python, a bus admittance matrix builder with line charging and off-nominal taps, a vectorized power-injection calculation, and a Gauss–Seidel solver checked against the two-bus case and a lossy three-bus network
eyebrow: S10 · Lesson 51 · Power-flow lab
xp: 60
---

::: hook
Every power-flow program, from a 1960s FORTRAN deck to the tools that run today's grids, is built from the same three pieces: assemble the bus admittance matrix from the branch list, compute the power each bus injects for a given set of voltages, and iterate the voltages until the injections match the specifications. In this lab you'll write all three, and the project that follows adds Newton–Raphson with generator buses, branch flows and fault calculations.
:::

::: predict
## Your Gauss–Seidel solver updates bus i with $V_i \leftarrow \frac{1}{Y_{ii}}\left[\left(\frac{S_i}{V_i}\right)^* - \sum_{j \ne i}Y_{ij}V_j\right]$. Where does that come from?

- [ ] It's the Newton step for one bus
- [x] It's bus i's own power equation, $S_i = V_i(\sum_jY_{ij}V_j)^*$, solved for the $V_i$ in the sum
- [ ] It's the DC power flow
- [ ] It's Kirchhoff's voltage law around a loop

::: reveal
Conjugating $S_i = V_i(\sum_jY_{ij}V_j)^*$ gives $S_i^*/V_i^* = \sum_jY_{ij}V_j$. Pull the j = i term out and solve for it. The $V_i^*$ on the left uses the old value, which is why the method needs iterating.
:::
:::

::: nameit
## The branch model

Each branch (i, j, r, x, b, a) is a series admittance $y = 1/(r + jx)$ with total charging b split between its ends, and an ideal transformer of ratio a:1 at bus i's end (a = 1 for lines). Its contribution to $Y_\text{bus}$:

$$Y_{ii} \mathrel{+}= \frac{y}{a^2} + j\frac{b}{2}, \quad Y_{jj} \mathrel{+}= y + j\frac{b}{2}, \quad Y_{ij} = Y_{ji} \mathrel{-}= \frac{y}{a}$$

## Injections

With all bus voltages in a complex vector V, the injections are $S = V \odot (YV)^*$, one line of NumPy.

## Gauss–Seidel

Bus 0 is the slack. Sweep buses 1 to n − 1 with the update above, using each new value at once, and stop when the largest change in a sweep is below the tolerance. Lesson 18 showed the two-bus case takes 12 sweeps to reach 10⁻⁶.
:::

::: example
## What should `build_ybus` produce for the network of lesson 10 (branches j0.1, j0.2 and j0.25 between buses 0–1, 0–2 and 1–2)?

::: solution
1. **The matrix.**
   $$Y = -j\begin{pmatrix} 15 & -10 & -5 \\ -10 & 14 & -4 \\ -5 & -4 & 9 \end{pmatrix}$$
2. **Diagonal entries.** Each diagonal sums the admittances of the branches at that bus.
3. **Off-diagonal entries.** Each off-diagonal is minus the admittance between the pair.
4. **The generator.** Lesson 10 also had the generator's −j5 at bus 0, a shunt added separately.

**Answer:** diagonal entries of −j15, −j14 and −j9, and off-diagonal entries of j10 (0–1), j5 (0–2) and j4 (1–2).
:::
:::

::: example
## Check `injections` on the two-bus solution of lesson 17.

::: solution
1. **The inputs.**
   $$Y = \begin{pmatrix} -j5 & j5 \\ j5 & -j5 \end{pmatrix}$$
   and V = (1, 0.8554∠−13.52°).
2. **The injections.** The load bus injects −1 − j0.5 (the load) and the slack 1 + j0.842 (the load plus the line's 0.342 pu of vars).
3. **A common bug.** If your conjugate is in the wrong place, the second number comes out with the wrong sign.

**Answer:** −1 − j0.5 at the load bus and 1 + j0.842 at the slack.
:::
:::

::: check
kind: python

## Step 1. Write `build_ybus(n, branches)`: series admittances, line charging and off-nominal taps.

```python starter
import numpy as np

def build_ybus(n, branches):
    # branches: list of (i, j, r, x, b, a) with buses numbered from 0, series impedance r + jx,
    # total charging susceptance b (half at each end), and off-nominal tap a on bus i's side
    # (a = 1 for a line). Return the n x n complex bus admittance matrix.
    return np.zeros((n, n), dtype=complex)

print(build_ybus(2, [(0, 1, 0.0, 0.2, 0.0, 1.0)]))
```

```python solution
import numpy as np

def build_ybus(n, branches):
    Y = np.zeros((n, n), dtype=complex)
    for (i, j, r, x, b, a) in branches:
        y = 1/complex(r, x)
        Y[i, i] += y/a**2 + 1j*b/2
        Y[j, j] += y + 1j*b/2
        Y[i, j] -= y/a
        Y[j, i] -= y/a
    return Y

print(build_ybus(2, [(0, 1, 0.0, 0.2, 0.0, 1.0)]))
```

```python tests
import numpy as np
Y = build_ybus(3, [(0, 1, 0, 0.1, 0, 1.0), (0, 2, 0, 0.2, 0, 1.0), (1, 2, 0, 0.25, 0, 1.0)])
want = -1j*np.array([[15, -10, -5], [-10, 14, -4], [-5, -4, 9]])
assert Y.shape == (3, 3) and np.allclose(Y, want), f"The lesson 10 network gives Y = −j[[15, −10, −5], [−10, 14, −4], [−5, −4, 9]]; got\n{np.round(Y, 3)}"
Y = build_ybus(2, [(0, 1, 0.02, 0.1, 0.2, 1.0)])
y = 1/(0.02 + 0.1j)
assert np.isclose(Y[0, 0], y + 0.1j) and np.isclose(Y[1, 1], y + 0.1j) and np.isclose(Y[0, 1], -y), "Half the line's charging (j0.1) goes on each diagonal; the off-diagonal is −y."
Y = build_ybus(2, [(0, 1, 0, 0.08, 0, 1.05)])
y = 1/0.08j
assert np.isclose(Y[0, 0], y/1.05**2) and np.isclose(Y[1, 1], y) and np.isclose(Y[0, 1], -y/1.05), "A tap a on bus i's side gives y/a² at i, y at j and −y/a off the diagonal."
```

::: right
Right. Your matrix matches lesson 10's network and handles charging and taps.
:::
:::

::: check
kind: python

## Step 2. Write `injections(Y, V)`: the complex power injected at every bus.

```python starter
import numpy as np

def injections(Y, V):
    # Complex power injected at every bus, S_i = V_i (sum_j Y_ij V_j)*.
    return np.zeros(len(V), dtype=complex)

print(injections(np.array([[5j, -5j], [-5j, 5j]]), np.array([1, 0.9])))
```

```python solution
import numpy as np

def injections(Y, V):
    return V*np.conj(Y @ V)

print(injections(np.array([[5j, -5j], [-5j, 5j]]), np.array([1, 0.9])))
```

```python tests
import numpy as np
Y = np.array([[-5j, 5j], [5j, -5j]])
V = np.array([1.0, 0.8553727135205681*np.exp(-1j*np.radians(13.521852269411097))])
S = injections(Y, V)
assert np.allclose(S[1], -1 - 0.5j, atol=1e-9), f"At the two-bus solution of lesson 17 the load bus must inject −1 − j0.5; got {S[1]:.6f}."
assert np.isclose(S[0].real, 1, atol=1e-9) and np.isclose(S[0].imag, 0.8416876, atol=1e-6), "The slack supplies 1 + j0.842 there: the load plus the line's vars."
rng = np.random.default_rng(2)
Y = rng.normal(size=(4, 4)) + 1j*rng.normal(size=(4, 4)); V = rng.normal(size=4) + 1j*rng.normal(size=4)
ref = np.array([V[i]*np.conj(sum(Y[i, j]*V[j] for j in range(4))) for i in range(4)])
assert np.allclose(injections(Y, V), ref), "Check the conjugate: S = V (YV)*."
```

::: right
Right. The two-bus solution balances exactly: the load gets 1 + j0.5 and the slack supplies the line's vars too.
:::
:::

::: check
kind: python

## Step 3. Write `gauss_seidel(Y, S, V0)`: the slack held fixed, every other bus PQ.

```python starter
import numpy as np

def gauss_seidel(Y, S, V0, tol=1e-6, maxit=500):
    # Bus 0 is the slack (held at V0[0]); every other bus is PQ with specified injection S[i].
    # Sweep the buses in order, using new values at once, until no voltage changes by more than tol.
    # Return (V, iterations).
    return np.array(V0, dtype=complex), 0
```

```python solution
import numpy as np

def gauss_seidel(Y, S, V0, tol=1e-6, maxit=500):
    V = np.array(V0, dtype=complex)
    n = len(V)
    for k in range(1, maxit + 1):
        change = 0.0
        for i in range(1, n):
            s = Y[i] @ V - Y[i, i]*V[i]
            new = (np.conj(S[i]/V[i]) - s)/Y[i, i]
            change = max(change, abs(new - V[i]))
            V[i] = new
        if change < tol:
            return V, k
    return V, maxit
```

```python tests
import numpy as np
Y = np.array([[-5j, 5j], [5j, -5j]])
V, k = gauss_seidel(Y, np.array([0, -1 - 0.5j]), [1, 1])
assert abs(abs(V[1]) - 0.8553727) < 1e-5 and abs(np.degrees(np.angle(V[1])) + 13.5218523) < 1e-3, f"The two-bus case converges to 0.855∠−13.52°; got {abs(V[1]):.6f}∠{np.degrees(np.angle(V[1])):.4f}°."
assert k == 12, f"From a flat start with tol 1e-6 it takes 12 sweeps; got {k}."
br = [(0, 1, 0.02, 0.1, 0, 1), (0, 2, 0.03, 0.15, 0.02, 1), (1, 2, 0.025, 0.12, 0, 1)]
Y = np.zeros((3, 3), dtype=complex)
for (i, j, r, x, b, a) in br:
    y = 1/complex(r, x); Y[i, i] += y + 0.5j*b; Y[j, j] += y + 0.5j*b; Y[i, j] -= y; Y[j, i] -= y
S = np.array([0, -0.5 - 0.2j, -1 - 0.4j])
V, k = gauss_seidel(Y, S, [1.05, 1, 1], tol=1e-9)
mis = (V*np.conj(Y @ V) - S)[1:]
assert np.max(np.abs(mis)) < 1e-7, f"At convergence the PQ buses' injections must match their specifications; the mismatch is {np.max(np.abs(mis)):.2e}."
assert abs(V[0] - 1.05) < 1e-12, "Never change the slack bus."
```

::: right
Right. Twelve sweeps for the two-bus case, as in lesson 18, and a lossy three-bus network solved to 10⁻⁷ mismatch.
:::
:::

::: explain
## Why does the slack bus never get updated in the Gauss–Seidel sweep?

::: model
The slack bus's voltage magnitude and angle are specified: it's the reference for every angle in the system and the bus that balances generation, load and losses, which aren't known until the solution is found. So its voltage is an input, not an unknown, and the equations being solved are those of the other buses. Its injection is whatever comes out at the end, computed from the converged voltages with the same injection formula. Updating it would remove the angle reference and leave the problem with one more unknown than equations.
:::
:::

::: practice

::: check
given: x = 0.05 | 0.2; a = 0.95 | 1.05
answer: 1/(a^2*x)
tolerance: 0.5%

## What does a transformer of reactance j{x} with tap {a} on bus i's side add to $|Y_{ii}|$?

::: misses
- [any] $|y|/a^2$.
:::
:::

::: check
given: b = 0.04 | 0.4; x = 0.05 | 0.3
answer: 1/x - b/2
tolerance: 0.5%

## Net susceptance magnitude on each end's diagonal: j{x} line, charging {b}?

::: misses
- [any] $1/x - b/2$.
:::
:::

::: check
given: X = 0.1 | 0.25; P = 0.5 | 1.2; Q = 0.1 | 0.5
answer: sqrt((1 - X*Q)^2 + (X*P)^2)
tolerance: 0.5%

## First Gauss–Seidel iterate's magnitude for the two-bus case: X = {X}, load {P} + j{Q}?

::: misses
- [any] $|(1 - XQ) - jXP|$.
:::
:::
:::
