---
title: Problem set 11
heading: "Problem set 11: data"
eyebrow: A4 · Problem set 11
type: problems
---

::: hook
These labs use lessons 45 to 51: fitting, interpolation, reading text data, statistics of measurements, Monte Carlo, the FFT, and filtering. Each is a task you'd do on real bench data: calibrate a sensor, clean a log, report an uncertainty, predict a yield, find a hidden tone.
:::

::: pool
pick: 5

::: check
kind: python
given: k = 0..2 int

## The CSV in the starter is a sensor calibration: temperature in °C and output in V. Fit a straight line with `np.polyfit` and set `slope` (V per °C), `offset` (V at 0 °C), and `T_at` to the temperature that gives 1.0 V.

```python starter
import io
import numpy as np
text = ["T,v\n0,0.502\n25,0.748\n50,1.003\n75,1.251\n100,1.499",
        "T,v\n-20,0.301\n0,0.500\n20,0.702\n40,0.899\n60,1.101",
        "T,v\n10,0.598\n30,0.802\n50,0.999\n70,1.201"][k]
slope = offset = T_at = 0
print(slope, offset, T_at)
```

```python solution
import io
import numpy as np
text = ["T,v\n0,0.502\n25,0.748\n50,1.003\n75,1.251\n100,1.499",
        "T,v\n-20,0.301\n0,0.500\n20,0.702\n40,0.899\n60,1.101",
        "T,v\n10,0.598\n30,0.802\n50,0.999\n70,1.201"][k]
T, v = np.loadtxt(io.StringIO(text), delimiter=",", skiprows=1).T
slope, offset = np.polyfit(T, v, 1)
T_at = (1.0 - offset) / slope
print(slope, offset, T_at)
```

```python tests
import io
import numpy as np
text = ["T,v\n0,0.502\n25,0.748\n50,1.003\n75,1.251\n100,1.499", "T,v\n-20,0.301\n0,0.500\n20,0.702\n40,0.899\n60,1.101", "T,v\n10,0.598\n30,0.802\n50,0.999\n70,1.201"][k]
T, v = np.loadtxt(io.StringIO(text), delimiter=",", skiprows=1).T
m, b = np.polyfit(T, v, 1)
assert abs(slope - m) < 1e-12 and abs(offset - b) < 1e-12, "np.polyfit(T, v, 1) returns the slope then the intercept."
assert abs(T_at - (1.0 - b) / m) < 1e-9, "Solve slope·T + offset = 1.0 for T."
```
:::

::: check
kind: python
given: k = 0..2 int

## The log in the starter has gaps. Read it with `np.genfromtxt`, then for the `v` column set `n_good` (readings present), `m` (their mean) and `sem` (their standard error, with `ddof=1`).

```python starter
import io
import numpy as np
text = ["t,v\n0,3.31\n1,3.29\n2,\n3,3.30\n4,3.32\n5,\n6,3.28",
        "t,v\n0,5.01\n1,\n2,4.99\n3,5.02\n4,5.00",
        "t,v\n0,1.2\n1,1.1\n2,1.3\n3,\n4,1.2\n5,1.25\n6,1.15\n7,"][k]
n_good = 0
m = sem = 0
print(n_good, m, sem)
```

```python solution
import io
import numpy as np
text = ["t,v\n0,3.31\n1,3.29\n2,\n3,3.30\n4,3.32\n5,\n6,3.28",
        "t,v\n0,5.01\n1,\n2,4.99\n3,5.02\n4,5.00",
        "t,v\n0,1.2\n1,1.1\n2,1.3\n3,\n4,1.2\n5,1.25\n6,1.15\n7,"][k]
v = np.genfromtxt(io.StringIO(text), delimiter=",", skip_header=1)[:, 1]
good = v[~np.isnan(v)]
n_good = len(good)
m = good.mean()
sem = good.std(ddof=1) / np.sqrt(n_good)
print(n_good, m, sem)
```

```python tests
import io
import numpy as np
text = ["t,v\n0,3.31\n1,3.29\n2,\n3,3.30\n4,3.32\n5,\n6,3.28", "t,v\n0,5.01\n1,\n2,4.99\n3,5.02\n4,5.00", "t,v\n0,1.2\n1,1.1\n2,1.3\n3,\n4,1.2\n5,1.25\n6,1.15\n7,"][k]
v = np.genfromtxt(io.StringIO(text), delimiter=",", skip_header=1)[:, 1]
g = v[~np.isnan(v)]
assert n_good == len(g), "Count the readings that aren't nan."
assert abs(m - g.mean()) < 1e-12 and abs(sem - g.std(ddof=1) / np.sqrt(len(g))) < 1e-12, "Use only the good readings for the mean and the standard error."
```
:::

::: check
kind: python
given: V = 3.3 | 5; uV = 0.01 | 0.02; I = 0.010 | 0.022; uI = 0.0001 | 0.0003

## A resistance is measured as $R = V/I$ with `V` = {V} ± {uV} V and `I` = {I} ± {uI} A, independent. Set `R` and `uR` (absolute, in ohms), combining the relative uncertainties in quadrature.

```python starter
R = V / I
uR = 0
print(R, uR)
```

```python solution
R = V / I
uR = R * ((uV / V)**2 + (uI / I)**2) ** 0.5
print(R, uR)
```

```python tests
want = V / I * ((uV / V)**2 + (uI / I)**2) ** 0.5
assert abs(uR - want) < 1e-9 * want, "For a quotient, add the relative uncertainties in quadrature, then multiply by R."
```
:::

::: check
kind: python
given: tR = 1 | 5; tC = 5 | 20

## Model `R` = 4.7 kΩ ±`tR`% and `C` = 33 nF ±`tC`% as uniform. With `rng = np.random.default_rng(7)` and 100,000 draws (R first), set `yld` to the fraction of RC filters whose corner is within ±10% of nominal, and `p5`, `p95` to the 5th and 95th percentiles of the corner.

```python starter
import numpy as np
yld = p5 = p95 = 0
print(yld, p5, p95)
```

```python solution
import numpy as np
rng = np.random.default_rng(7)
N = 100000
R = 4.7e3 * rng.uniform(1 - tR / 100, 1 + tR / 100, N)
C = 33e-9 * rng.uniform(1 - tC / 100, 1 + tC / 100, N)
fc = 1 / (2 * np.pi * R * C)
f0 = 1 / (2 * np.pi * 4.7e3 * 33e-9)
yld = np.mean(np.abs(fc / f0 - 1) <= 0.10)
p5, p95 = np.percentile(fc, [5, 95])
print(yld, p5, p95)
```

```python tests
import numpy as np
rng = np.random.default_rng(7)
R = 4.7e3 * rng.uniform(1 - tR / 100, 1 + tR / 100, 100000)
C = 33e-9 * rng.uniform(1 - tC / 100, 1 + tC / 100, 100000)
fc = 1 / (2 * np.pi * R * C)
f0 = 1 / (2 * np.pi * 4.7e3 * 33e-9)
assert abs(yld - np.mean(np.abs(fc / f0 - 1) <= 0.10)) < 1e-15, "yld is the fraction within ±10% of the nominal corner."
q = np.percentile(fc, [5, 95])
assert abs(p5 - q[0]) < 1e-6 and abs(p95 - q[1]) < 1e-6, "Use np.percentile(fc, [5, 95])."
```
:::

::: check
kind: python
given: f0 = 137 | 220 | 333; s = 1 | 2

## The starter makes a noisy record with one hidden tone, sampled at 2 kHz for 4000 samples. Set `f_peak` to the frequency of the largest FFT bin, skipping DC, and `amp` to that bin's amplitude estimate, `2 * |X| / N`.

```python starter
import numpy as np
rng = np.random.default_rng(s)
fs, N = 2000, 4000
t = np.arange(N) / fs
x = 0.3 * np.sin(2 * np.pi * f0 * t) + rng.normal(0, 1, N)
f_peak = amp = 0
print(f_peak, amp)
```

```python solution
import numpy as np
rng = np.random.default_rng(s)
fs, N = 2000, 4000
t = np.arange(N) / fs
x = 0.3 * np.sin(2 * np.pi * f0 * t) + rng.normal(0, 1, N)
A = 2 * np.abs(np.fft.rfft(x)) / N
f = np.fft.rfftfreq(N, 1 / fs)
k = np.argmax(A[1:]) + 1
f_peak, amp = f[k], A[k]
print(f_peak, amp)
```

```python tests
assert abs(f_peak - f0) < 1e-9, f"The tone is at {f0} Hz, even though it's buried in noise in the time record. Skip bin 0 and take the argmax."
assert 0.2 < amp < 0.4, "amp should be close to the tone's 0.3 amplitude: 2|X|/N."
```
:::

::: check
kind: python
given: fs = 8000 | 10000 | 11025 | 12000 | 16000

## Tones at 1, 3.5, 6, 9.2 and 13 kHz reach an ADC sampling at `fs` = {fs} Hz with no filter. Set `aliases` to the list of the frequencies (in Hz) where each appears, and `clean` to the list of input tones that appear at their true frequency.

```python starter
tones = [1000, 3500, 6000, 9200, 13000]
aliases = tones
clean = tones
print(aliases, clean)
```

```python solution
tones = [1000, 3500, 6000, 9200, 13000]
aliases = [abs(f - fs * round(f / fs)) for f in tones]
clean = [f for f, a in zip(tones, aliases) if f == a]
print(aliases, clean)
```

```python tests
tones = [1000, 3500, 6000, 9200, 13000]
want = [abs(f - fs * round(f / fs)) for f in tones]
assert aliases == want, f"aliases should be {want}."
assert clean == [f for f in tones if f <= fs / 2], "Only tones below fs/2 appear at their true frequency."
```
:::

::: check
kind: python
given: tau = 2 | 5 | 8; s = 3 | 9

## The starter makes a noisy exponential decay $v = 5e^{-t/\tau}$ (with $t$ in ms). Fit a straight line to $\ln v$ against $t$ with `np.polyfit`, and set `tau_est` from its slope and `V0_est` from its intercept.

```python starter
import numpy as np
rng = np.random.default_rng(s)
t = np.linspace(0, 3 * tau, 40)
v = 5 * np.exp(-t / tau) * (1 + 0.01 * rng.normal(size=40))
tau_est = V0_est = 0
print(tau_est, V0_est)
```

```python solution
import numpy as np
rng = np.random.default_rng(s)
t = np.linspace(0, 3 * tau, 40)
v = 5 * np.exp(-t / tau) * (1 + 0.01 * rng.normal(size=40))
slope, icpt = np.polyfit(t, np.log(v), 1)
tau_est = -1 / slope
V0_est = np.exp(icpt)
print(tau_est, V0_est)
```

```python tests
import numpy as np
rng = np.random.default_rng(s)
t = np.linspace(0, 3 * tau, 40)
v = 5 * np.exp(-t / tau) * (1 + 0.01 * rng.normal(size=40))
m, b = np.polyfit(t, np.log(v), 1)
assert abs(tau_est + 1 / m) < 1e-9 and abs(V0_est - np.exp(b)) < 1e-9, "ln v = ln V0 − t/τ, so τ = −1/slope and V0 = e^intercept."
assert abs(tau_est - tau) < 0.05 * tau, "tau_est should be close to the true τ."
```
:::

::: check
kind: python
given: k = 0..3 int

## A pressure sensor's calibration table maps pressure (kPa) to output voltage: 0 → 0.20, 20 → 0.95, 50 → 1.90, 100 → 3.10, 150 → 3.95, 200 → 4.60 V. Using `np.interp` on the inverted table, set `p` to the pressures for the starter's readings, with `np.nan` for any reading outside the table's voltage range, and `n_out` to how many readings were outside.

```python starter
import numpy as np
P = np.array([0, 20, 50, 100, 150, 200.0])
V = np.array([0.20, 0.95, 1.90, 3.10, 3.95, 4.60])
readings = [np.array([0.5, 2.2, 4.1, 4.8]), np.array([0.1, 1.0, 3.0]), np.array([0.2, 4.6, 2.5, 3.6, 1.4]), np.array([5.0, 0.0, 2.0])][k]
p = np.interp(readings, P, V)
n_out = 0
print(p, n_out)
```

```python solution
import numpy as np
P = np.array([0, 20, 50, 100, 150, 200.0])
V = np.array([0.20, 0.95, 1.90, 3.10, 3.95, 4.60])
readings = [np.array([0.5, 2.2, 4.1, 4.8]), np.array([0.1, 1.0, 3.0]), np.array([0.2, 4.6, 2.5, 3.6, 1.4]), np.array([5.0, 0.0, 2.0])][k]
p = np.interp(readings, V, P)
out = (readings < V[0]) | (readings > V[-1])
p[out] = np.nan
n_out = int(out.sum())
print(p, n_out)
```

```python tests
import numpy as np
Vt = np.array([0.20, 0.95, 1.90, 3.10, 3.95, 4.60]); Pt = np.array([0, 20, 50, 100, 150, 200.0])
w = np.interp(readings, Vt, Pt)
o = (readings < Vt[0]) | (readings > Vt[-1])
w[o] = np.nan
assert np.shape(p) == np.shape(readings) and np.allclose(p, w, equal_nan=True), "Interpolate pressure against voltage (voltage as the x values), and set out-of-range readings to np.nan."
assert n_out == int(o.sum()), f"{int(o.sum())} readings are outside 0.20 to 4.60 V."
```

::: right
Right. `np.interp` would clamp an out-of-range reading to 0 or 200 kPa, a believable wrong number; marking it `nan` makes the problem visible. The table's ends are the edge of what the calibration knows.
:::
:::

::: check
kind: python
given: k = 1..5 int; N = 5 | 9

## The starter has a slow signal `clean`, and `x`, the same signal with noise and occasional large glitches. Set `ma` to an `N`-point moving average of `x` ({N} points, `"same"` mode), `med_ma` to the same moving average applied after a 5-point median filter (pad the median's output back to full length by repeating its first and last values twice), and `err_ma`, `err_med` to each one's RMS error against `clean` over samples 20 to 479.

```python starter
import numpy as np
rng = np.random.default_rng(k)
t = np.arange(500)
clean = np.sin(2 * np.pi * t / 250)
x = clean + rng.normal(0, 0.05, 500)
x[rng.choice(np.arange(10, 490, 15), 10, replace=False)] += rng.choice([-3.0, 3.0], 10)
ma = med_ma = x
err_ma = err_med = 0
print(err_ma, err_med)
```

```python solution
import numpy as np
rng = np.random.default_rng(k)
t = np.arange(500)
clean = np.sin(2 * np.pi * t / 250)
x = clean + rng.normal(0, 0.05, 500)
x[rng.choice(np.arange(10, 490, 15), 10, replace=False)] += rng.choice([-3.0, 3.0], 10)
box = np.ones(N) / N
ma = np.convolve(x, box, mode="same")
med = np.array([np.median(x[i:i + 5]) for i in range(len(x) - 4)])
med = np.concatenate([[med[0]] * 2, med, [med[-1]] * 2])
med_ma = np.convolve(med, box, mode="same")
sl = slice(20, 480)
err_ma = np.sqrt(np.mean((ma[sl] - clean[sl])**2))
err_med = np.sqrt(np.mean((med_ma[sl] - clean[sl])**2))
print(err_ma, err_med)
```

```python tests
import numpy as np
b = np.ones(N) / N
m1 = np.convolve(x, b, mode="same")
md = np.array([np.median(x[i:i + 5]) for i in range(len(x) - 4)])
md = np.concatenate([[md[0]] * 2, md, [md[-1]] * 2])
m2 = np.convolve(md, b, mode="same")
s = slice(20, 480)
assert np.allclose(ma, m1) and np.allclose(med_ma, m2), "Median first (window 5, padded back to 500 samples), then the moving average in 'same' mode."
assert abs(err_ma - np.sqrt(np.mean((m1[s] - clean[s])**2))) < 1e-12 and abs(err_med - np.sqrt(np.mean((m2[s] - clean[s])**2))) < 1e-12, "Each error is the RMS of (filtered - clean) over samples 20 to 479."
assert err_med < err_ma / 2, "Removing the glitches first should cut the error by more than half."
```

::: right
Right. The moving average alone smears each glitch into a bump {N} samples wide; the median removes the glitches first, so the average only has the small noise left to smooth. Order matters: nonlinear cleanup first, linear smoothing after.
:::
:::
:::
