---
title: Instrument lab
heading: What a scope, a counter, a meter and a power analyzer compute, in Python
eyebrow: C11 · Lesson 20 · Instrument lab
xp: 50
---

::: hook
Modern instruments are computers that sample and calculate. The scope's rise-time readout interpolates between samples, the counter divides counts by times, the cheap meter scales an average and calls it RMS, the power analyzer averages a product, and a frequency standard's data sheet quotes an Allan deviation. In this lab you'll write each of those calculations and test them on signals whose answers are known.
:::

::: play
- The curve is the reading of an **average-responding** meter, which scales the average of |v| by the sine's form factor, $\pi/(2\sqrt2) = 1.1107$, divided by the true RMS, for a train of pulses that are on a fraction D of the time.
- For such pulses the average of |v| is D and the RMS is $\sqrt D$, so the ratio is $1.1107\sqrt D$: 11% high for steady DC, and only 35% of the truth at a 10% duty cycle.
- A sine gives exactly 1, which is the only waveform such a meter is right for. That's the difference between a meter labeled "true RMS" and one that isn't.
:::

```sim plot
view: graph
x: D = 0.01..1
y: r = 0..1.2
slider: d = 0.01..1 step 0.01 = 0.1
plot: pi/(2*sqrt(2))*sqrt(D) | label: average-responding ÷ true RMS
plot: 1 + 0*D | dashed | label: correct
readout: ratio at the slider's duty = pi/(2*sqrt(2))*sqrt(d) | digits: 4
```

::: predict
## A load draws a 5 A rms current from 230 V, lagging by 30°, plus a third harmonic. What does the harmonic add to the real power?

- [ ] About 5%
- [x] Nothing
- [ ] It doubles it
- [ ] It makes it negative

::: reveal
Nothing. Real power is the average of v·i, and a 150 Hz current against a 50 Hz voltage averages to zero over a cycle. It does increase the rms current, so the power factor falls: from 0.866 to 0.797 in the lab's test. Harmonic currents load the wiring without delivering energy.
:::
:::

::: nameit
## What each instrument computes

- **Rise time**: find the signal's low and high levels, then the times where it crosses 10% and 90% of the way between them, interpolating linearly between samples. For a first-order step it's $\tau\ln 9 = 2.197\tau$.
- **Reciprocal frequency**: take the rising-edge times inside a gate; the frequency is the number of whole periods between the first and last edge, divided by the time between them.
- **Average-responding meters**: compute $\frac{\pi}{2\sqrt2}\overline{\lvert v\rvert}$, which equals the RMS only for a sine.
- **Real power and power factor**: $P = \overline{v\,i}$, and $\text{PF} = P/(V_\text{rms}I_\text{rms})$.
- **Allan deviation**: average the fractional-frequency samples in blocks of m, then $\sigma_y = \sqrt{\tfrac12\overline{(\bar y_{k+1} - \bar y_k)^2}}$. It measures how much the frequency wanders between successive averages of that length.
:::

::: example
## A first-order system has τ = 1 ms. What rise time should the scope report?

::: solution
1. **10% crossing.** $v = 1 - e^{-t/\tau}$ crosses 10% at
   $$\begin{aligned} t_{10} &= \tau\ln(1/0.9) \\ &= 0.105\ \text{ms} \end{aligned}$$
2. **90% crossing.**
   $$\begin{aligned} t_{90} &= \tau\ln 10 \\ &= 2.303\ \text{ms} \end{aligned}$$
3. **Rise time.**
   $$\begin{aligned} t_r &= t_{90} - t_{10} \\ &= \tau\ln 9 \\ &= 2.197\ \text{ms} \end{aligned}$$
4. **Measuring it.** Sampling every microsecond and interpolating recovers it to better than 0.1%.

**Answer:** the scope should report a rise time of 2.197 ms.
:::
:::

::: example
## What does an average-responding meter read for a triangle wave of 1 V peak, and what is its true RMS?

::: solution
1. **Mean absolute value.** A triangle's mean absolute value is half its peak, 0.5 V.
2. **What the meter reads.**
   $$1.1107 \times 0.5\ \text{V} = 0.555\ \text{V}$$
3. **True RMS.**
   $$\frac{1\ \text{V}}{\sqrt3} = 0.577\ \text{V}$$
4. **The error.** The meter is 3.8% low, and it's worse on pulses and noise.

**Answer:** the meter reads 0.555 V, and the true RMS is 0.577 V.
:::
:::

::: check
given: t = 0.1 | 1 | 50
answer: t*ln(9)
unit: µs
tolerance: 0.5%

## What is the 10–90% rise time of a first-order step with τ = {t} µs?

::: right
Right: {answer} µs.
:::

::: misses
- [any] Not yet. $\tau\ln 9$.
:::
:::

::: check
kind: python

## Write `rise_time(t, v)`: the 10–90% rise time of a rising step, sampled at times t, interpolating linearly between samples.

```python starter
def rise_time(t, v):
    return t[-1] - t[0]
```

```python solution
def rise_time(t, v):
    lo, hi = min(v), max(v)
    def cross(level):
        for k in range(1, len(v)):
            if v[k - 1] < level <= v[k]:
                return t[k - 1] + (level - v[k - 1]) * (t[k] - t[k - 1]) / (v[k] - v[k - 1])
    return cross(lo + 0.9 * (hi - lo)) - cross(lo + 0.1 * (hi - lo))
```

```python tests
import math
t = [i * 1e-3 for i in range(10001)]
v = [1 - math.exp(-x) for x in t]
assert abs(rise_time(t, v) - math.log(9)) < 1e-3, f"A first-order step with τ = 1: ln 9 = 2.197, got {rise_time(t, v):.5f}."
t2 = [i * 0.01 for i in range(301)]
v2 = [min(1, max(0, x - 1)) for x in t2]
assert abs(rise_time(t2, v2) - 0.8) < 1e-9, "A linear ramp from 0 to 1 over 1 s rises 10 to 90% in 0.8 s."
assert abs(rise_time(t, [3 + 2 * x for x in v]) - math.log(9)) < 1e-3, "Offset and gain don't change the rise time."
```

::: right
Right. Interpolation lets the rise time be resolved far more finely than the sample spacing.
:::
:::

::: check
kind: python

## Write `reciprocal_frequency(edges, gate)`: given rising-edge times, use the edges from the first one up to `gate` seconds later, and return the number of whole periods between the first and last used edge divided by the time between them.

```python starter
def reciprocal_frequency(edges, gate):
    return len(edges) / gate
```

```python solution
def reciprocal_frequency(edges, gate):
    first = edges[0]
    inside = [e for e in edges if e - first <= gate]
    return (len(inside) - 1) / (inside[-1] - first)
```

```python tests
edges = [k / 1000.37 for k in range(2000)]
assert abs(reciprocal_frequency(edges, 1.0) - 1000.37) < 1e-6, f"A 1000.37 Hz signal over 1 s, got {reciprocal_frequency(edges, 1.0)}."
edges = [0.5e-6 + k / 7.3e6 for k in range(100000)]
assert abs(reciprocal_frequency(edges, 0.01) - 7.3e6) < 1e-3, "7.3 MHz with an offset start."
assert abs(len([1, 2, 3]) / 1.0 - 3) < 1e-12 and abs(reciprocal_frequency([0, 0.25, 0.5, 0.75, 1.0, 1.25], 1.0) - 4) < 1e-12, "Edges every 0.25 s inside a 1 s gate: 4 Hz."
```

::: right
Right. Timing whole periods, rather than counting edges in a fixed gate, keeps the resolution independent of frequency.
:::
:::

::: check
kind: python

## Write `average_responding(v)`: what an average-responding meter, calibrated for sines, reads for the samples v.

```python starter
def average_responding(v):
    return max(v) / 2 ** 0.5
```

```python solution
import math

def average_responding(v):
    return math.pi / (2 * math.sqrt(2)) * sum(abs(x) for x in v) / len(v)
```

```python tests
import math
n = 10000
sine = [math.sin(2 * math.pi * k / n) for k in range(n)]
assert abs(average_responding(sine) - 1 / math.sqrt(2)) < 1e-6, "For a sine it reads the true RMS."
square = [1 if k < n / 2 else -1 for k in range(n)]
assert abs(average_responding(square) - 1.11072) < 1e-4, "For a ±1 square wave it reads 1.111, 11% high."
saw = [2 * k / n - 1 for k in range(n)]
assert abs(average_responding(saw) - 0.55536) < 1e-4, "For a ±1 sawtooth it reads 0.555, against a true 0.577."
```

::: right
Right. The scale factor is only right for the waveform it was chosen for.
:::
:::

::: check
kind: python

## Write `power(v, i)`: return `(P, PF)`, the real power and the power factor of sampled voltage and current covering whole cycles.

```python starter
def power(v, i):
    return (max(v) * max(i) / 2, 1.0)
```

```python solution
import math

def power(v, i):
    P = sum(a * b for a, b in zip(v, i)) / len(v)
    vr = math.sqrt(sum(a * a for a in v) / len(v))
    ir = math.sqrt(sum(b * b for b in i) / len(i))
    return (P, P / (vr * ir))
```

```python tests
import math
n = 10000
v = [325 * math.sin(2 * math.pi * k / n) for k in range(n)]
i = [7.07 * math.sin(2 * math.pi * k / n - math.pi / 6) for k in range(n)]
P, pf = power(v, i)
assert abs(P - 994.95) < 0.1 and abs(pf - 0.86603) < 1e-4, f"230 V, 5 A, 30° lag: 995 W at PF 0.866; got {P:.2f}, {pf:.5f}."
i3 = [i[k] + 3 * math.sin(3 * 2 * math.pi * k / n) for k in range(n)]
P3, pf3 = power(v, i3)
assert abs(P3 - P) < 1e-6 and abs(pf3 - 0.79722) < 1e-4, f"A third harmonic adds no power but lowers PF to 0.797; got {P3:.2f}, {pf3:.5f}."
```

::: right
Right. Averaging the product is what separates real power from merely flowing current.
:::
:::

::: check
kind: python

## Write `allan(y, m)`: the non-overlapping Allan deviation of fractional-frequency samples y for an averaging factor m.

```python starter
import statistics

def allan(y, m):
    return statistics.pstdev(y)
```

```python solution
import math

def allan(y, m):
    blocks = [sum(y[k:k + m]) / m for k in range(0, len(y) - m + 1, m)]
    d = [(b - a) ** 2 for a, b in zip(blocks, blocks[1:])]
    return math.sqrt(sum(d) / (2 * len(d)))
```

```python tests
import math
assert abs(allan([1, -1] * 50, 1) - math.sqrt(2)) < 1e-12, "Alternating ±1 with m = 1: √2."
assert abs(allan([1, -1] * 50, 2)) < 1e-12, "Averaged in pairs, the alternation vanishes: 0."
assert abs(allan([0.001 * k for k in range(100)], 10) - 0.01 / math.sqrt(2)) < 1e-12, "A steady drift of 0.001 per sample, m = 10: 0.01/√2."
```

::: right
Right. Noise averages away as m grows; drift grows with m. The Allan deviation's shape against m tells them apart.
:::
:::

::: explain
## Why do stability specifications use the Allan deviation instead of the ordinary standard deviation of frequency readings?

::: model
An oscillator's frequency usually drifts, and many oscillators also have noise whose power grows at low frequencies. For such signals the ordinary standard deviation doesn't settle as more data is collected; it keeps growing with the length of the record, so it doesn't describe the oscillator. The Allan deviation compares each average only with the next one, so slow drift contributes only through the change between neighboring blocks, and the result converges. Plotting it against the averaging time shows which process dominates at each time scale: white noise falls as $\tau^{-1/2}$, flicker noise flattens out, and drift rises, which tells a designer how long to average and where a better reference would help.
:::
:::
