---
title: Mini-project: a grid-frequency log
heading: What an hour of grid frequency says about the power system
eyebrow: A4 · Lesson 53 · Mini-project
xp: 60
---

::: hook
The frequency of the power grid isn't exactly 50 or 60 Hz. It wanders by a few hundredths of a hertz all day, because generation and demand never match exactly, and when a large power station trips offline it drops sharply and then recovers. Grid operators watch this number second by second. In this project you'll analyze an hour of it, using everything from this course.
:::

::: predict
## A large generator trips offline and the frequency drops. Why does it drop, rather than rise?

- [ ] The remaining generators speed up to compensate
- [x] Demand now exceeds generation, so the energy comes out of the spinning machines, which slow down
- [ ] Frequency is set by the load, which suddenly increases
- [ ] It doesn't drop; it rises

::: reveal
When generation falls short of demand, the difference is supplied from the kinetic energy stored in every synchronous machine on the grid, which all spin in step. Giving up energy slows them down, and their speed is the frequency. Controls then raise the output of other plants, which stops the fall within seconds and brings the frequency back over minutes.
:::
:::

::: nameit
## The data, and the plan

The log for this project is **simulated**, built to behave like a 50 Hz grid: a slow random wander with a spread of about 0.04 Hz, sampled once a second for an hour, and one event, a generator trip half an hour in. Real logs look much like it, and you'd load one with `np.loadtxt` exactly as in lesson 45. Each lab starts with the same few lines that build the log; don't change them.

```
import numpy as np
rng = np.random.default_rng(2024)
t = np.arange(3600)                     # seconds
dev = np.zeros(3600)
for k in range(1, 3600):                # a slow random wander
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)          # time since the trip
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event                    # the frequency, in Hz
```

The tools you'll use:

- **Statistics:** `f.mean()`, `f.std()`, `f.min()` and `np.argmin(f)` for when the minimum happened.
- **Thresholds:** a comparison like `f < 49.8` gives True or False at every second; `np.mean` of it is the fraction of time it's true, and `np.argmax` of it is the first second it's true.
- **Plots:** two stacked panels, the full hour and a zoom on the event.

Grid operators work with bands. Here, take the normal operating band as 50 ± 0.2 Hz.
:::

::: check
kind: python

## Set `f_mean` to the hour's average frequency, `f_std` to its standard deviation, `f_min` to its lowest value and `t_min` to the time in seconds when that lowest value happened.

```python starter
import numpy as np
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

f_mean = 0
f_std = 0
f_min = 0
t_min = 0
print(f_mean, f_std, f_min, t_min)
```

```python solution
import numpy as np
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

f_mean = f.mean()
f_std = f.std()
f_min = f.min()
t_min = t[np.argmin(f)]
print(f_mean, f_std, f_min, t_min)
```

```python tests
import numpy as np
assert abs(f_mean - f.mean()) < 1e-9, "f_mean should be f.mean()."
assert abs(f_std - f.std()) < 1e-9, "f_std should be f.std()."
assert abs(f_min - f.min()) < 1e-9, "f_min should be f.min()."
assert t_min == t[np.argmin(f)], "t_min should be the time of the lowest value: t[np.argmin(f)]."
assert 1800 <= t_min <= 1900, "The lowest point should fall just after the trip at 1800 s. Check you're using np.argmin, the index of the minimum."
```

::: right
Right. The lowest point comes a few seconds after the trip, once the machines' slowing has been arrested.
:::
:::

::: check
kind: python

## Set `out_frac` to the fraction of the hour that the frequency spends outside the band 50 ± 0.2 Hz, and `t_first` to the first second at which it drops below 49.8 Hz.

```python starter
import numpy as np
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

out_frac = 0
t_first = 0
print(out_frac, t_first)
```

```python solution
import numpy as np
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

out_frac = np.mean(np.abs(f - 50) > 0.2)
t_first = t[np.argmax(f < 49.8)]
print(out_frac, t_first)
```

```python tests
import numpy as np
assert abs(out_frac - np.mean(np.abs(f - 50) > 0.2)) < 1e-12, "out_frac should count both sides of the band: np.mean(np.abs(f - 50) > 0.2)."
assert t_first == t[np.argmax(f < 49.8)], "t_first should be the first time f < 49.8: t[np.argmax(f < 49.8)]."
```

::: right
Right. The grid spends only a small share of the hour outside its band, and almost all of it right after the trip.
:::
:::

::: check
kind: python

## Plot the log in two stacked panels: the full hour on top, and the ten minutes from 1750 s to 2350 s below. Draw the band limits, 49.8 and 50.2 Hz, as dashed lines in both. Label the axes.

```python starter
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

plt.subplot(2, 1, 1)
plt.plot(t, f)
# add the band lines and labels, then the second panel
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

for panel, (a, b) in enumerate([(0, 3600), (1750, 2350)], start=1):
    plt.subplot(2, 1, panel)
    keep = (t >= a) & (t <= b)
    plt.plot(t[keep], f[keep])
    plt.axhline(49.8, linestyle='--')
    plt.axhline(50.2, linestyle='--')
    plt.xlabel('t (s)')
    plt.ylabel('f (Hz)')
plt.tight_layout()
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
axes = plt.gcf().get_axes()
assert len(axes) >= 2, "Make two panels: plt.subplot(2, 1, 1) for the hour and plt.subplot(2, 1, 2) for the zoom."
def bands(ax):
    ys = [float(np.asarray(l.get_ydata(), float)[0]) for l in ax.get_lines() if len(l.get_ydata()) == 2]
    return any(abs(y - 49.8) < 1e-9 for y in ys) and any(abs(y - 50.2) < 1e-9 for y in ys)
assert all(bands(ax) for ax in axes[:2]), "Draw both band limits in each panel with plt.axhline(49.8, linestyle='--') and plt.axhline(50.2, linestyle='--')."
lo, hi = axes[1].get_xlim()
assert lo >= 1700 and hi <= 2400, "The second panel should show only 1750 s to 2350 s: plot just that slice, or set plt.xlim(1750, 2350)."
assert all(ax.get_xlabel() and ax.get_ylabel() for ax in axes[:2]), "Label the axes of both panels."
```

::: right
Right. The zoom shows the event's shape: a fast fall, arrested within seconds, then a slow climb back.
:::
:::

::: explain
## Looking at your two panels, describe what happens to the grid frequency during the event, and what it tells you about how the grid responds.

::: model
Before the trip the frequency wanders by a few hundredths of a hertz around 50 Hz. At the trip it falls quickly, by about a quarter of a hertz within fifteen seconds or so, dipping below the 49.8 Hz band, as the spinning machines give up energy to cover the missing generation. The fall is arrested within seconds, showing that fast automatic controls raised other plants' output, and then the frequency climbs back toward 50 Hz over a couple of minutes as slower controls restore the balance.
:::
:::

::: practice

::: check
kind: python
given: b = 0.05 | 0.08 | 0.1 | 0.15 | 0.2

## Set `out_frac` to the fraction of the hour the frequency spends more than {b} Hz away from 50 Hz.

```python starter
import numpy as np
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

out_frac = 0
print(out_frac)
```

```python solution
import numpy as np
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

out_frac = np.mean(np.abs(f - 50) > b)
print(out_frac)
```

```python tests
import numpy as np
assert abs(out_frac - np.mean(np.abs(f - 50) > b)) < 1e-12, "out_frac should be the mean of the test np.abs(f - 50) > b, which is True outside the band."
```
:::

::: check
kind: python
given: d = 1 | 2 | 5 | 10

## Set `f_avg` to the hour's {d}-minute averages: an array with one mean for each block of {d} × 60 seconds.

```python starter
import numpy as np
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

f_avg = f
print(f_avg[:5])
```

```python solution
import numpy as np
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

f_avg = f.reshape(-1, 60 * d).mean(axis=1)
print(f_avg[:5])
```

```python tests
import numpy as np
want = f.reshape(-1, 60 * d).mean(axis=1)
assert np.shape(f_avg) == want.shape, f"f_avg should hold one value per block: {want.size} of them."
assert np.allclose(f_avg, want, atol=1e-12), "Each value should be the mean of one block. f.reshape(-1, 60 * d) puts each block in a row."
```
:::

::: check
kind: python
given: L = 49.85 | 49.9 | 49.95

## Set `n_below` to the number of seconds in the hour when the frequency is below {L} Hz.

```python starter
import numpy as np
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

n_below = 0
print(n_below)
```

```python solution
import numpy as np
rng = np.random.default_rng(2024)
t = np.arange(3600)
dev = np.zeros(3600)
for k in range(1, 3600):
    dev[k] = 0.995 * dev[k - 1] + rng.normal(0, 0.004)
s = np.clip(t - 1800, 0, None)
event = -0.25 * (1 - np.exp(-s / 3)) * np.exp(-s / 120)
f = 50 + dev + event

n_below = int(np.sum(f < L))
print(n_below)
```

```python tests
import numpy as np
assert n_below == int(np.sum(f < L)), "Count the True values of f < L with np.sum."
```
:::
:::
