---
title: "Lab: measuring and plotting signals"
heading: A scope's measurements, a design sweep and plots worth showing, all in NumPy
eyebrow: A4 · Lesson 34 · Lab: measuring and plotting signals
xp: 60
---

::: hook
A digital oscilloscope is mostly arithmetic on arrays: it captures a record of samples, then computes peak-to-peak, mean, RMS and frequency from them. Lessons 28 to 33 gave you the same tools: arrays, vectorized arithmetic and masks, two-dimensional grids, and plots that communicate. This lab builds a scope's measurements, sweeps a design over a grid, and makes the plots that would go in a report, with checks that the numbers are right and not merely plausible.
:::

::: predict
## A record holds 61.7 cycles of $0.4 + 2\sin(2\pi f t)$. Its plain `mean()` is which?

- [ ] Exactly 0.4
- [x] A little off 0.4, because the record isn't a whole number of cycles
- [ ] 0, the average of a sine
- [ ] 2.4, the peak

::: reveal
A little off: 0.407 for one such record. The extra 0.7 of a cycle adds part of a hump that doesn't cancel, biasing the mean and the RMS. Scopes fix this by measuring over a whole number of cycles, between the first and last crossings of the same edge, which brings the mean back to 0.400 within a few microvolts.
:::
:::

::: nameit
## Measurements on a record

- **Peak-to-peak:** `v.max() - v.min()`.
- **Crossings:** with `s = v - level`, the upward crossings are `np.nonzero((s[:-1] < 0) & (s[1:] >= 0))[0]`. Interpolating between the two samples around each one, $t_c = t_i - s_i/(s_{i+1} - s_i) \cdot \Delta t$, times it to a small fraction of a sample.
- **Frequency:** the number of whole cycles between the first and last upward crossings, divided by the time between them.
- **Mean and RMS:** over the samples from the first upward crossing to the last, a whole number of cycles. The AC RMS is the RMS of `v - mean`.

## Sweeps on a grid

Make one parameter a column and the other a row, and broadcasting fills the whole table in one expression; `argmax(axis=1)` then finds the best column in each row.

## Plots for a report

One idea per figure, labeled axes with units, a legend when there's more than one curve, log axes for quantities that span decades, and markers on the points that matter. Everything the reader needs should be on the figure itself.
:::

::: example
## A 100 kHz capture of 5000 samples holds $0.4 + 2\sin(2\pi \cdot 1234\,t)$ V. Measure its peak-to-peak, mean, AC RMS and frequency.

::: solution
1. **Build the capture and measure it.** Peak-to-peak from the extremes, the frequency from interpolated upward crossings, and the mean and RMS over whole cycles only.

```python
import numpy as np
fs = 100e3
t = np.arange(5000) / fs
v = 0.4 + 2.0 * np.sin(2 * np.pi * 1234 * t)

vpp = v.max() - v.min()                              # 4.000 V
s = v - v.mean()
up = np.nonzero((s[:-1] < 0) & (s[1:] >= 0))[0]
tc = t[up] - s[up] / (s[up + 1] - s[up]) / fs        # interpolated crossing times
f = (len(tc) - 1) / (tc[-1] - tc[0])                 # 1234.0000 Hz
seg = v[up[0] + 1:up[-1] + 1]                        # 61 whole cycles
mean = seg.mean()                                    # 0.400 V
rms = np.sqrt(np.mean((seg - mean)**2))              # 1.4143 V
```

2. **Peak-to-peak.** It is 4.000 V.
3. **Frequency.** From 61 cycles between interpolated crossings it is 1234.0000 Hz, far finer than the 100 kHz sample spacing suggests.
4. **Mean and RMS.** Over the whole record the mean would read 0.407 V and the RMS 1.4135 V; over the 61 whole cycles they're 0.400 V and 1.4143 V, against the true 0.4 V and
   $$\frac{2}{\sqrt2} = 1.4142\ \text{V}$$
5. **Why whole cycles.** Measuring over whole cycles is worth a factor of about a thousand in accuracy here.

**Answer:** 4.000 V peak-to-peak, a mean of 0.400 V, an AC RMS of 1.4143 V and a frequency of 1234.0000 Hz.
:::
:::

::: example
## A 1 V source with source resistance 50, 75, 100 or 600 Ω drives a load from 10 Ω to 1 kΩ. Find each source's best load and the power it delivers.

::: solution
1. **Lay out every source against every load.** Source resistances down a column and loads along a row give a (4, 201) table of powers.

```python
Rs = np.array([50, 75, 100, 600])[:, None]       # a column
RL = np.logspace(1, 3, 201)[None, :]             # a row
P = 1.0**2 * RL / (Rs + RL)**2                   # shape (4, 201)
best = RL[0, np.argmax(P, axis=1)]
print(best, P.max(axis=1))
```

2. **The best loads.** They come out at 50.1, 75.9, 100 and 602.6 Ω, the grid points nearest each source resistance.
3. **The powers.** They are 5.000, 3.333, 2.500 and 0.417 mW, which is
   $$P_{max} = \frac{V^2}{4R_s}$$
   Each source delivers the most power into a load equal to its own resistance.
4. **The grid limit.** The grid's spacing, 2.3% from one point to the next, sets how close `argmax` can land.

**Answer:** each source does best into a load equal to its own resistance (50.1, 75.9, 100 and 602.6 Ω on the grid), delivering 5.000, 3.333, 2.500 and 0.417 mW.
:::
:::

::: check
kind: python
given: f = 50 | 440 | 1234 | 3000; A = 1 | 2.5; dc = 0 | 0.4 | -1.2

## The starter captures `v` = {dc} + {A}·sin(2π·{f}·t) at 100 kHz for 5000 samples. Using the lesson's recipe, set `vpp`, `freq` (from interpolated upward crossings of `v - v.mean()`), and `mean` and `rms` (AC RMS) over the whole cycles between the first and last upward crossings.

```python starter
import numpy as np
fs = 100e3
t = np.arange(5000) / fs
v = dc + A * np.sin(2 * np.pi * f * t + 0.3)
vpp = v.max() - v.min()
freq = 0
mean = v.mean()
rms = np.sqrt(np.mean(v**2))
print(vpp, freq, mean, rms)
```

```python solution
import numpy as np
fs = 100e3
t = np.arange(5000) / fs
v = dc + A * np.sin(2 * np.pi * f * t + 0.3)
vpp = v.max() - v.min()
s = v - v.mean()
up = np.nonzero((s[:-1] < 0) & (s[1:] >= 0))[0]
tc = t[up] - s[up] / (s[up + 1] - s[up]) / fs
freq = (len(tc) - 1) / (tc[-1] - tc[0])
seg = v[up[0] + 1:up[-1] + 1]
mean = seg.mean()
rms = np.sqrt(np.mean((seg - mean)**2))
print(vpp, freq, mean, rms)
```

```python tests
import numpy as np
assert abs(freq - f) < 1e-3 * f, f"freq should be {f} Hz to within 0.1%: count whole cycles between the first and last interpolated upward crossings."
assert abs(mean - dc) < 2e-3 * A + 1e-9, f"Over whole cycles the mean should be {dc} V."
assert abs(rms - A / np.sqrt(2)) < 2e-3 * A, f"The AC RMS over whole cycles should be {A / np.sqrt(2):.4f} V."
assert abs(vpp - 2 * A) < 1e-2 * A, "vpp is max minus min."
```

::: right
Right. Each measurement uses only whole cycles, so the leftover fraction of a cycle at the end of the record can't bias it. That's what a scope's "cycle" measurement mode does.
:::
:::

::: check
kind: python
given: V = 1 | 5 | 12

## A source of `V` = {V} V with internal resistance `Rs` drives a load `RL`. With `Rs` from the starter as a column and `RL = np.logspace(0, 4, 401)` as a row, compute the load power on the whole grid with broadcasting (no loops). Set `P` (shape `(4, 401)`), `best` to each row's best load and `Pmax` to each row's largest power.

```python starter
import numpy as np
Rs = np.array([4, 8, 50, 600])
RL = np.logspace(0, 4, 401)
P = V**2 * RL / (Rs + RL)**2
best = Pmax = None
print(best, Pmax)
```

```python solution
import numpy as np
Rs = np.array([4, 8, 50, 600])
RL = np.logspace(0, 4, 401)
P = V**2 * RL[None, :] / (Rs[:, None] + RL[None, :])**2
best = RL[np.argmax(P, axis=1)]
Pmax = P.max(axis=1)
print(best, Pmax)
```

```python tests
import numpy as np
R = np.array([4, 8, 50, 600]); L = np.logspace(0, 4, 401)
W = V**2 * L[None, :] / (R[:, None] + L[None, :])**2
assert np.shape(P) == (4, 401) and np.allclose(P, W), "Make Rs a column with Rs[:, None] and RL a row with RL[None, :]."
assert np.allclose(best, L[np.argmax(W, axis=1)]), "best is RL at the argmax of each row: axis=1."
assert np.allclose(Pmax, V**2 / (4 * R), rtol=1e-3), "Each source's best power should be close to V²/(4 Rs)."
```

::: right
Right. The whole 4 × 401 table comes from one expression, and the best power in each row lands on $V^2/(4R_s)$ to within the grid's spacing, the maximum power theorem seen as data.
:::
:::

::: check
kind: python
given: f0 = 100 | 200 | 500 | 1000 | 2000

## On one figure, plot the gain in dB of a second-order low-pass, $|H| = 1/\left|1 - (f/f_0)^2 + j\,f/(Qf_0)\right|$, with `f0` = {f0} Hz, for $Q$ = 0.5, 0.707 and 2, over `f = np.logspace(np.log10(f0) - 2, np.log10(f0) + 2, 400)`. Use a log frequency axis, label both axes with units, and give each curve a legend label containing its Q, such as `"Q = 0.707"`.

```python starter
import numpy as np
import matplotlib.pyplot as plt
f = np.logspace(np.log10(f0) - 2, np.log10(f0) + 2, 400)
for Q in [0.5, 0.707, 2]:
    H = 1 / np.abs(1 - (f / f0)**2 + 1j * f / (Q * f0))
    plt.plot(f, H)
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
f = np.logspace(np.log10(f0) - 2, np.log10(f0) + 2, 400)
for Q in [0.5, 0.707, 2]:
    H = 1 / np.abs(1 - (f / f0)**2 + 1j * f / (Q * f0))
    plt.semilogx(f, 20 * np.log10(H), label=f"Q = {Q}")
plt.xlabel("f (Hz)")
plt.ylabel("gain (dB)")
plt.legend()
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
ax = plt.gca()
assert ax.get_xscale() == "log", "Use a log frequency axis: plt.semilogx."
lines = [l for l in ax.get_lines() if len(l.get_xdata()) > 2]
assert len(lines) == 3, "Plot one curve for each Q."
for Q in [0.5, 0.707, 2]:
    match = [l for l in lines if str(Q) in l.get_label()]
    assert match, f"Label the Q = {Q} curve with its Q."
    x = np.asarray(match[0].get_xdata(), float); y = np.asarray(match[0].get_ydata(), float)
    assert np.allclose(y, 20 * np.log10(1 / np.abs(1 - (x / f0)**2 + 1j * x / (Q * f0))), atol=1e-9), f"The Q = {Q} curve should be the gain in dB."
assert ax.get_xlabel() and ax.get_ylabel() and ax.get_legend() is not None, "Label the axes and add a legend."
```

::: right
Right. In decibels on a log axis the three curves share the −40 dB per decade slope far above $f_0$ and differ only near it, where $Q$ = 2 peaks by 6 dB and $Q$ = 0.5 sags by 6 dB. The labels make that comparison readable at a glance.
:::
:::

::: check
kind: python
given: k = 1..5 int; s = 0.5 | 1 | 2

## The starter makes 10 000 readings with noise of standard deviation `s` = {s} mV around 1.000 V. Set `counts, edges = np.histogram(err_mV, bins=50)` for the errors in millivolts, `within1` to the fraction of errors within one sample standard deviation of zero, and `within3` to the fraction within three.

```python starter
import numpy as np
x = 1.0 + np.random.default_rng(k).normal(0, s / 1000, 10000)
err_mV = x
counts, edges = np.histogram(err_mV, bins=50)
within1 = within3 = 0
print(within1, within3)
```

```python solution
import numpy as np
x = 1.0 + np.random.default_rng(k).normal(0, s / 1000, 10000)
err_mV = (x - 1.0) * 1000
counts, edges = np.histogram(err_mV, bins=50)
sd = err_mV.std(ddof=1)
within1 = np.mean(np.abs(err_mV) <= sd)
within3 = np.mean(np.abs(err_mV) <= 3 * sd)
print(within1, within3)
```

```python tests
import numpy as np
e = (1.0 + np.random.default_rng(k).normal(0, s / 1000, 10000) - 1.0) * 1000
assert np.allclose(err_mV, e), "err_mV is (x - 1.0) * 1000."
assert counts.sum() == 10000 and len(edges) == 51, "np.histogram with bins=50 gives 50 counts and 51 edges."
sd = e.std(ddof=1)
assert abs(within1 - np.mean(np.abs(e) <= sd)) < 1e-12 and abs(within3 - np.mean(np.abs(e) <= 3 * sd)) < 1e-12, "Use masks: np.mean(np.abs(err_mV) <= sd)."
assert abs(within1 - 0.683) < 0.02 and abs(within3 - 0.997) < 0.003, "For Gaussian noise these should be near 68.3% and 99.7%."
```

::: right
Right. A mask's mean is the fraction of samples that pass, so one line answers "what fraction is within one standard deviation". The 68% and 99.7% that come out are the Gaussian's fingerprint.
:::
:::

::: check
kind: python
given: g = 2 | 3 | 5; L = 5 | 9

## An amplifier with gain `g` = {g} clips at ±`L` = {L} V. For an input of 3 V amplitude at 50 Hz over 40 ms (2000 samples), plot the output against time in ms as a line, then mark only the clipped samples with red dots (`'r.'`), using a mask. Label both axes. Set `frac` to the fraction of samples clipped.

```python starter
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0, 0.04, 2000)
vout = g * 3 * np.sin(2 * np.pi * 50 * t)
plt.plot(t * 1000, vout)
frac = 0
```

```python solution
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0, 0.04, 2000)
vout = np.clip(g * 3 * np.sin(2 * np.pi * 50 * t), -L, L)
clipped = np.abs(vout) >= L
plt.plot(t * 1000, vout)
plt.plot(t[clipped] * 1000, vout[clipped], "r.")
plt.xlabel("t (ms)")
plt.ylabel("v out (V)")
frac = clipped.mean()
```

```python tests
import numpy as np
import matplotlib.pyplot as plt
tt = np.linspace(0, 0.04, 2000)
vv = np.clip(g * 3 * np.sin(2 * np.pi * 50 * tt), -L, L)
mask = np.abs(vv) >= L
ax = plt.gca()
lines = ax.get_lines()
assert any(len(l.get_xdata()) == 2000 and np.allclose(np.asarray(l.get_ydata(), float), vv) for l in lines), "Plot the clipped output against time in ms: np.clip(g*vin, -L, L)."
dots = [l for l in lines if l.get_marker() == "." and l.get_linestyle() in ("None", "", " ")]
assert dots and len(dots[0].get_xdata()) == mask.sum(), "Mark only the clipped samples with plt.plot(t[mask]*1000, vout[mask], 'r.')."
assert abs(frac - mask.mean()) < 1e-12, "frac is the mean of the clipped mask."
assert ax.get_xlabel() and ax.get_ylabel(), "Label both axes."
```

::: right
Right. The mask picks out exactly the samples the amplifier couldn't follow, and drawing them as dots on top of the waveform shows where and how often it clips. With gain {g} and ±{L} V rails, that's the fraction `frac` of the time.
:::
:::

::: check
given: A = 2 | 5 | 10; r = 0.25 | 0.5 | 0.75 | 0.9
answer: (2/pi)*acos(r)
tolerance: 0.5%

## A sine of amplitude {A} V is sampled finely over whole cycles. What fraction of the samples exceed $\given{r} \times \given{A}$ V in size?

::: right
Right. $|\sin\theta| > \given{r}$ for the part of each half cycle between $\arcsin \given{r}$ and $\pi - \arcsin \given{r}$, which is $1 - \frac{2}{\pi}\arcsin \given{r} = \frac{2}{\pi}\arccos \given{r}$ of the time: {answer}.
:::

::: misses
- [1 - r] That assumes the sine spends equal time at every level. It lingers near its peaks and rushes through zero.
- [(1/pi)*acos(r)] That counts only the positive half. The size exceeds the level on both the positive and the negative humps.
- [any] Not yet. Find the angles where $|\sin\theta| = \given{r}$ and the fraction of a cycle between them.
:::
:::

::: explain
## Why does measuring a sine's mean and RMS over a whole number of cycles give a much better answer than using the whole record?

::: model
A sine averages to zero, and its square averages to exactly half its peak squared, only over whole cycles. A leftover fraction of a cycle adds a piece of a hump that has no matching piece to cancel it, so the mean picks up a bias and the RMS a small error, both of which shrink only slowly as the record gets longer. Cutting the record at the first and last crossings of the same edge keeps exactly whole cycles, so the cancellation is complete and the remaining error comes only from the sampling, which is far smaller.
:::
:::
