---
title: "Project: a Newton–Raphson power-flow program"
heading: Finishing the power-flow program with polar Newton–Raphson including generator (PV) buses, branch flows and losses from the solved voltages, and three-phase fault currents and voltages from the bus impedance matrix
eyebrow: S10 · Lesson 52 · Project
xp: 80
---

::: hook
With the admittance matrix and injections from the lab, you have what you need for a real power-flow program. This project adds the three parts that make it useful: a Newton–Raphson solver that handles generator buses holding their voltage, a branch-flow report that shows how power actually moves and where it's lost, and a fault calculator built on the bus impedance matrix. The test network is small enough to check by hand and lossy enough that shortcuts show.
:::

::: predict
## The three-bus test case has a slack at 1.05 pu and a generator bus held at 1.02 pu delivering 0.5 pu, feeding a 1 + j0.4 pu load. Will the generator at 1.02 pu supply vars or absorb them?

- [ ] Supply them: generators always do
- [x] Absorb them: holding 1.02 pu next to a 1.05 pu slack means pulling the voltage down
- [ ] Neither: a PV bus has zero Q
- [ ] It depends only on the load's power factor

::: reveal
Reactive power flows from higher voltage magnitude to lower (lesson 7). With the slack at 1.05 and its neighbor held at 1.02, the generator must absorb vars to keep its voltage that low: the solution has $Q_2$ = −0.153 pu, while the slack supplies 0.622 pu. Moving the setpoint to 1.05 would turn the generator into a var source.
:::
:::

::: nameit
## The test network

Bus 0 is the slack at 1.05∠0°; bus 1 is PV with P = 0.5 pu and |V| = 1.02; bus 2 is PQ with a load of 1 + j0.4 pu. Branches: 0–1 with 0.02 + j0.10, 0–2 with 0.03 + j0.15 and 0.02 of charging, 1–2 with 0.025 + j0.12 (all per unit).

## Newton–Raphson in polar form

Unknowns: the angles of PV and PQ buses and the magnitudes of PQ buses. With $I = YV$, the derivatives of the injections are compact in matrix form:

$$\frac{\partial S}{\partial\theta} = j\,\text{diag}(V)\left(\text{diag}(I) - Y\,\text{diag}(V)\right)^*, \qquad \frac{\partial S}{\partial|V|} = \text{diag}(V)\left(Y\,\text{diag}(V/|V|)\right)^* + \text{diag}(I)^*\text{diag}(V/|V|)$$

Their real and imaginary parts, restricted to the right rows and columns, are the four Jacobian blocks. Solve, update, repeat until the largest mismatch is below 10⁻¹⁰.

## Branch flows

For branch (i, j, r, x, b, a), the currents leaving each end are $I_i = (y/a^2 + jb/2)V_i - (y/a)V_j$ and $I_j = (y + jb/2)V_j - (y/a)V_i$, and the flows are $S_{ij} = V_iI_i^*$, $S_{ji} = V_jI_j^*$. Their sum is the branch's loss, real and reactive.

## Faults

With each generator's subtransient admittance added to its bus's diagonal, $Z_\text{bus} = Y^{-1}$, $I_f = 1/Z_{kk}$ and $V_i = 1 - Z_{ik}I_f$ (lesson 36).
:::

::: example
## What does the solution look like?

::: solution
1. **Convergence.** It takes four Newton steps from a flat start.
2. **Bus voltages.** They are 1.05∠0°, 1.02∠0.0957° and 0.99149∠−3.3835°.
3. **Power balance.** The slack supplies 0.5183 + j0.6220 pu, the generator 0.5 − j0.1527, the load takes 1 + j0.4, and the network loses 0.01833 pu of real power (1.8 MW on 100 MVA).
4. **Cross-check.** An independent Gauss–Seidel with PV handling agrees to ten digits.

**Answer:** after four Newton steps the voltages are 1.05∠0°, 1.02∠0.0957° and 0.99149∠−3.3835°, and the network loses 0.01833 pu (1.8 MW).
:::
:::

::: example
## How can you check a branch-flow routine without another program?

::: solution
1. **At every bus.** The flows leaving into its branches must add up to its injection.
2. **Over the whole network.** The sum over all branches of $S_{ij} + S_{ji}$ must equal the sum of all injections, which is the total loss.
3. **What they catch.** Both checks catch the common mistakes, a missing half of the charging or a tap applied on the wrong end.

**Answer:** check conservation: at each bus the branch flows must add up to the injection, and the branch losses, summed, must equal the sum of all injections.
:::
:::

::: check
kind: python

## Step 1. Write `newton(Y, types, P, Q, Vm, Va)`: polar Newton–Raphson with PV buses.

```python starter
import numpy as np

def newton(Y, types, P, Q, Vm, Va, tol=1e-10, maxit=20):
    # types[i] is 'slack', 'PV' or 'PQ'. P, Q are specified injections (Q used only at PQ buses);
    # Vm, Va are the starting magnitudes and angles (radians), with the slack's and PV buses'
    # magnitudes as specified. Solve the polar Newton–Raphson power flow; return (V, iterations),
    # where iterations counts Newton steps taken before the largest mismatch fell below tol.
    return np.array(Vm*np.exp(1j*np.asarray(Va)), dtype=complex), 0
```

```python solution
import numpy as np

def newton(Y, types, P, Q, Vm, Va, tol=1e-10, maxit=20):
    Vm = np.array(Vm, float); Va = np.array(Va, float)
    P = np.asarray(P, float); Q = np.asarray(Q, float)
    n = len(types)
    pv = [i for i in range(n) if types[i] == 'PV']
    pq = [i for i in range(n) if types[i] == 'PQ']
    ang = pv + pq
    for it in range(maxit + 1):
        V = Vm*np.exp(1j*Va)
        I = Y @ V
        S = V*np.conj(I)
        mis = np.concatenate([P[ang] - S.real[ang], Q[pq] - S.imag[pq]])
        if np.max(np.abs(mis)) < tol:
            return V, it
        dVa = 1j*np.diag(V) @ np.conj(np.diag(I) - Y @ np.diag(V))
        dVm = np.diag(V) @ np.conj(Y @ np.diag(V/Vm)) + np.conj(np.diag(I)) @ np.diag(V/Vm)
        J = np.block([[dVa.real[np.ix_(ang, ang)], dVm.real[np.ix_(ang, pq)]],
                      [dVa.imag[np.ix_(pq, ang)], dVm.imag[np.ix_(pq, pq)]]])
        dx = np.linalg.solve(J, mis)
        Va[ang] += dx[:len(ang)]
        Vm[pq] += dx[len(ang):]
    return Vm*np.exp(1j*Va), maxit
```

```python tests
import numpy as np
Y = np.zeros((3, 3), dtype=complex)
for (i, j, r, x, b) in [(0, 1, 0.02, 0.10, 0.0), (0, 2, 0.03, 0.15, 0.02), (1, 2, 0.025, 0.12, 0.0)]:
    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
V, it = newton(Y, ['slack', 'PV', 'PQ'], np.array([0, 0.5, -1.0]), np.array([0, 0, -0.4]), [1.05, 1.02, 1.0], [0, 0, 0])
assert abs(abs(V[1]) - 1.02) < 1e-12, "The PV bus must hold its specified magnitude, 1.02."
assert abs(abs(V[2]) - 0.9914940316) < 1e-8, f"The load bus settles at 0.9914940 pu; got {abs(V[2]):.10f}."
assert abs(np.degrees(np.angle(V[1])) - 0.0956717505) < 1e-6 and abs(np.degrees(np.angle(V[2])) + 3.3835041105) < 1e-6, f"Angles should be 0.0957° and −3.3835°; got {np.degrees(np.angle(V[1])):.6f}° and {np.degrees(np.angle(V[2])):.6f}°."
assert it <= 6, f"Newton should converge in a handful of steps; it took {it}."
S = V*np.conj(Y @ V)
assert abs(S[1].real - 0.5) < 1e-9 and abs(S[2] - (-1 - 0.4j)) < 1e-9, "At the solution the specified injections must be met."
Y2 = np.array([[-5j, 5j], [5j, -5j]])
V2, it2 = newton(Y2, ['slack', 'PQ'], np.array([0, -1.0]), np.array([0, -0.5]), [1, 1], [0, 0])
assert abs(abs(V2[1]) - 0.8553727135) < 1e-9 and it2 <= 6, "The two-bus case of lesson 19: 0.8553727 in four or five steps."
```

::: right
Right. Four steps to 10⁻¹⁰, the generator bus held at 1.02 pu, and the two-bus case of lesson 19 reproduced.
:::
:::

::: check
kind: python

## Step 2. Write `branch_flows(V, branches)`: power at both ends of every branch.

```python starter
import numpy as np

def branch_flows(V, branches):
    # For each branch (i, j, r, x, b, a), return the complex power leaving bus i into it (S_ij)
    # and leaving bus j into it (S_ji), as two numpy arrays, using the same model as build_ybus.
    m = len(branches)
    return np.zeros(m, dtype=complex), np.zeros(m, dtype=complex)
```

```python solution
import numpy as np

def branch_flows(V, branches):
    Sij = np.zeros(len(branches), dtype=complex); Sji = np.zeros(len(branches), dtype=complex)
    for k, (i, j, r, x, b, a) in enumerate(branches):
        y = 1/complex(r, x)
        Ii = (y/a**2 + 0.5j*b)*V[i] - (y/a)*V[j]
        Ij = (y + 0.5j*b)*V[j] - (y/a)*V[i]
        Sij[k] = V[i]*np.conj(Ii); Sji[k] = V[j]*np.conj(Ij)
    return Sij, Sji
```

```python tests
import numpy as np
br = [(0, 1, 0.02, 0.10, 0.0, 1.0), (0, 2, 0.03, 0.15, 0.02, 1.0), (1, 2, 0.025, 0.12, 0.0, 1.0)]
V = np.array([1.05, 1.02*np.exp(1j*np.radians(0.0956717505)), 0.9914940316*np.exp(-1j*np.radians(3.3835041105))])
Sij, Sji = branch_flows(V, br)
assert len(Sij) == 3, "One flow per branch at each end."
loss = (Sij + Sji).real.sum()
assert abs(loss - 0.018332947) < 1e-7, f"The network's losses are 0.0183329 pu; got {loss:.7f}."
assert abs(Sij[0] + Sij[1] - (0.518332947 + 0.6219633016j)) < 1e-6, "The flows out of bus 0 must add up to the slack's injection."
assert abs(Sji[1] + Sji[2] - (-1 - 0.4j)) < 1e-6, "The flows out of bus 2 must add up to its injection, −1 − j0.4."
Sij, Sji = branch_flows(np.array([1.0, 0.98*np.exp(-0.05j)]), [(0, 1, 0, 0.1, 0, 1.05)])
y = 1/0.1j; V = np.array([1.0, 0.98*np.exp(-0.05j)])
assert abs(Sij[0] - V[0]*np.conj(y/1.05**2*V[0] - y/1.05*V[1])) < 1e-12, "Include the tap: the current leaving bus i is (y/a²)V_i − (y/a)V_j."
```

::: right
Right. Your flows balance at every bus and add up to the network's 0.0183 pu of losses.
:::
:::

::: check
kind: python

## Step 3. Write `fault(Y, k)`: three-phase fault current and bus voltages from the bus impedance matrix.

```python starter
import numpy as np

def fault(Y, k):
    # Y includes every generator's admittance to ground. For a bolted three-phase fault at bus k with
    # all prefault voltages 1 pu, return (If, Vf): the fault current magnitude and the array of bus
    # voltage magnitudes during the fault.
    return 0.0, np.ones(Y.shape[0])
```

```python solution
import numpy as np

def fault(Y, k):
    Z = np.linalg.inv(Y)
    If = 1/Z[k, k]
    Vf = 1 - Z[:, k]*If
    return abs(If), np.abs(Vf)
```

```python tests
import numpy as np
Y = -1j*np.array([[20, -10, -5], [-10, 14, -4], [-5, -4, 9]])
If, Vf = fault(Y, 2)
assert abs(If - 3.0555556) < 1e-6, f"Lesson 36's fault at bus 3 draws 3.056 pu; got {If:.6f}."
assert np.allclose(Vf, [0.3888889, 0.2777778, 0], atol=1e-6), f"The bus voltages during it are 0.389, 0.278 and 0; got {np.round(Vf, 6)}."
rng = np.random.default_rng(5)
A = rng.normal(size=(4, 4)); G = A @ A.T + 4*np.eye(4)
Y = (0.1*G - 1j*G)
If, Vf = fault(Y, 1)
e = np.zeros(4); e[1] = 1
dV = np.linalg.solve(Y, -e)
If_ref = 1/abs(-dV[1]); 
assert abs(If - If_ref) < 1e-9 and abs(Vf[1]) < 1e-9, "Check against superposition: the faulted bus must fall to zero and If = 1/|Z_kk|."
```

::: right
Right. Lesson 36's 3.06 pu fault and its bus voltages, and a lossy network checked by superposition.
:::
:::

::: explain
## Why does a PV bus contribute a row to the angle equations but not to the voltage-magnitude equations?

::: model
At a PV bus the generator's controls fix two things: the real power, set by its turbine, and the voltage magnitude, held by its exciter. The magnitude is therefore known, not an unknown, so there's no ΔQ equation to solve for it; the generator supplies whatever reactive power that voltage takes, which comes out of the solution. The angle, though, depends on how power flows through the network and must be solved for, using the real-power mismatch at that bus. Each PV bus thus contributes one unknown and one equation, compared with two of each at a PQ bus.
:::
:::

::: practice

::: check
given: n = 3 | 30 | 300; f = 0.1 | 0.3; let m = round(n*f)
answer: 2*(n - 1) - m
tolerance: 0

## Jacobian size for {n} buses with {m} PV?

::: misses
- [any] $2(n - 1) - n_{PV}$.
:::
:::

::: check
given: R = 0.01 | 0.04; P = 0.5 | 1.5; Q = 0.1 | 0.6; V = 0.97 | 1.03
answer: R*(P^2 + Q^2)/V^2
tolerance: 0.5%

## Branch loss: R = {R}, {P} + j{Q} at {V} pu?

::: misses
- [any] $R(P^2 + Q^2)/V^2$.
:::
:::

::: check
given: k = 0.2 | 0.4; i = 0.08 | 0.15
answer: 1 - i/k
tolerance: 0.5%

## Voltage at bus i during a fault at k: $Z_{kk}$ = {k}, $Z_{ik}$ = {i}?

::: misses
- [any] $1 - Z_{ik}/Z_{kk}$.
:::
:::
:::
