"""Reproduce the ShivasNotes filter figures. Python 3 + Matplotlib (includes NumPy). python -m pip install matplotlib python drone_filters.py python drone_filters.py --signal step --window 5 --alpha 0.5 --out step-plots Each run writes nine SVG figures, samples.csv, two-sensor.csv and imu-bench.csv. """ import argparse import csv from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np BENCH = [4.2, 2.6, 3.8, 4.6, 2.9, 3.7, 4.1, 2.7, 3.2, 4.4, 3.3, 3.8] STEP = [2., 2., 2.] + [5.] * 9 INK, RAW, MEAN, WINDOW, LOW = "#23394a", "#99531c", "#555b9b", "#007b70", "#21649b" def smooth(readings, window=3, alpha=.25): running, moving, low = [], [], [] # A 1D input has one reading per time. For (time, channel), operate per column. readings = np.asarray(readings, dtype=float) mean = filtered = readings[0] for i, reading in enumerate(readings): mean = mean + (reading - mean) / (i + 1) active = readings[max(0, i + 1 - window):i + 1] filtered = filtered + alpha * (reading - filtered) running.append(mean) moving.append(sum(active) / len(active)) low.append(filtered) return np.array([running, moving, low]) def scalar(readings, sensor_variance): height, variance = 0., 4. estimates = [] for reading in readings: variance += .08 gain = variance / (variance + sensor_variance) height += gain * (reading - height) variance *= 1 - gain estimates.append(height) return estimates def save(fig, path, title): fig.suptitle(title, x=.085, ha="left", fontsize=16, weight="bold", color=INK) fig.savefig(path, format="svg", metadata={"Date": None}, bbox_inches="tight", pad_inches=.18) plt.close(fig) def height_and_climb(path): # A single prediction and correction, exactly as in the article. Units are m and m/s. F = np.array([[1., 1.], [0., 1.]]) # dt = 1 s x = F @ np.array([0., 1.]) P = F @ np.eye(2) @ F.T # Q = 0 for this worked step H = np.array([1., 0.]) K = P @ H / (H @ P @ H + 1.) # R = 1 square metre updated = x + K * (2.5 - H @ x) fig, axes = plt.subplots(1, 2, figsize=(7.5, 3.1), layout="constrained") for j, ax in enumerate(axes): bars = ax.bar(["Predicted", "Corrected"], [x[j], updated[j]], color=[MEAN, WINDOW], width=.57) ax.bar_label(bars, fmt="%.1f", padding=3) ax.set(ylabel=["Height (m)", "Climb rate (m/s)"][j], ylim=(0, 2.6)) save(fig, path, "One range reading updates two state entries") def nonlinear(path): # One scalar observation update, fixed 3 m height above a beacon, positive-x prior. h = lambda x: np.hypot(3., x) x, P, z, R = 4., 4., 6., .25 slope = x / h(x) ekf = x + P * slope / (slope**2 * P + R) * (z - h(x)) points = np.array([x, x - np.sqrt(P), x + np.sqrt(P)]) mean_w, cov_w = np.array([0., .5, .5]), np.array([2., .5, .5]) ranges = h(points) pred = mean_w @ ranges cov = cov_w @ ((points - x) * (ranges - pred)) ukf = x + cov / (cov_w @ (ranges - pred)**2 + R) * (z - pred) fig, ax = plt.subplots(figsize=(7.5, 3.6), layout="constrained") xs = np.linspace(0, 7, 120) ax.plot(xs, h(xs), color=INK, label="Range to beacon") ax.plot(xs[30:105], h(x) + slope*(xs[30:105]-x), "--", color=RAW, label="EKF tangent") ax.scatter(points, ranges, color=WINDOW, zorder=4, label="UKF sigma points") ax.set(xlabel="Horizontal displacement (m)", ylabel="Range (m)", title=f"Corrected horizontal position: EKF {ekf:.3f} m · UKF {ukf:.3f} m") ax.legend() save(fig, path, "Two ways to carry uncertainty through a curve") def complementary(previous, gyro_rate, dt, tilt, beta): """One local roll/pitch step in degrees; inputs may also be single angles.""" predicted = previous + dt * gyro_rate return predicted + beta * (tilt - predicted) def two_sensors(out, window, alpha): # A level, flat-pad example. Both height channels already use the same datum and clock. z = np.column_stack((BENCH[:4], [4.0, 4.2, 4.0, 4.2])) estimates = smooth(z, window, alpha) # shape (3 filters, 4 timestamps, 2 sensors) fig, axes = plt.subplots(1, 2, figsize=(8, 3.3), layout="constrained", sharey=True) for j, (ax, name) in enumerate(zip(axes, ["Rangefinder", "Barometric height"])): ax.plot(range(1,5), z[:, j], ".:", color=RAW, label="Reading") for arr, label, style, ink in zip(estimates, ["Mean","Window","Low-pass"], ["--","-.","-"], [MEAN,WINDOW,LOW]): ax.plot(range(1,5), arr[:,j], style, color=ink, label=label) ax.set(title=name, xticks=[1,2,3,4], xlabel="Sample") axes[0].set_ylabel("Height (m)") axes[0].legend(fontsize=8, ncol=2) save(fig, out/"two-sensor.svg", "One clock, two height channels") # Each row contains measurements from one instant. Preserve the sensor identity. columns = np.column_stack((np.arange(1,5), z, *estimates)) np.savetxt(out/"two-sensor.csv", columns, fmt="%.6f", delimiter=",", comments="", header="sample,range,baro,mean_range,mean_baro,window_range,window_baro,low_range,low_baro") raw_angles = np.array([12., -1.5]) fused = complementary(np.array([9., -3.]), np.array([10., 5.]), .1, raw_angles, .02) print("Complementary roll and pitch (degrees):", fused.round(2)) def attitude(path): # Repeatable small-angle bench simulation: no translational acceleration or angle wrapping. t = np.arange(201) / 10 truth = 10*np.sin(.45*t) gyro = np.r_[0., np.diff(truth)/.1] + .45 # deg/s, with injected constant bias tilt = truth + np.random.default_rng(61).normal(0, 2.5, len(t)) fused = [truth[0]] for rate, reading in zip(gyro[1:], tilt[1:]): fused.append(complementary(fused[-1], rate, .1, reading, .02)) fig, ax = plt.subplots(figsize=(7.5, 3.6), layout="constrained") ax.scatter(t, tilt, color=RAW, s=6, alpha=.55, label="Accelerometer tilt") ax.plot(t, truth, "--", color=INK, label="Simulated bank") ax.plot(t, np.r_[0., np.cumsum(gyro[1:])*.1], ":", color=MEAN, label="Gyro alone") ax.plot(t, fused, color=WINDOW, label="Complementary") ax.set(xlabel="Time (s)", ylabel="Bank (degrees)") ax.legend(ncol=2, fontsize=9) save(fig, path, "A gravity reference checks gyro drift") def imu_bench(out): """Synthetic roll fixture. Body x forward, y right, z down; angles in degrees.""" rng = np.random.default_rng(6068) dt = 0.1 t = np.arange(61) * dt truth = np.clip(12 * (t - 2), 0, 12) # Gyro averages the interval ending at t. Accelerometer samples its endpoint. rates = np.zeros((len(t), 3)) rates[:, 0] = np.r_[0., np.diff(truth) / dt] + 0.6 rates += rng.normal(0, 0.4, rates.shape) angle = np.deg2rad(truth) force = -9.81 * np.column_stack((np.zeros_like(t), np.sin(angle), np.cos(angle))) force += rng.normal(0, 0.25, force.shape) tilt = np.rad2deg(np.arctan2(-force[:, 1], -force[:, 2])) mean, moving, low = smooth(tilt, window=5, alpha=.25) comp = np.empty_like(t) comp[0] = tilt[0] # States: roll in degrees, gyro bias in degrees/second. One measurement: tilt. x = np.array([tilt[0], 0.]) R = np.rad2deg(.25 / 9.81)**2 P = np.diag([R, 1.]) F = np.array([[1., -dt], [0., 1.]]) H = np.array([1., 0.]) Q = np.diag([(.4*dt)**2, .05**2 * dt]) kf = np.empty_like(t) kf[0] = x[0] for i in range(1, len(t)): rate = rates[i, 0] comp[i] = complementary(comp[i-1], rate, dt, tilt[i], .08) x = F @ x + np.array([rate*dt, 0.]) P = F @ P @ F.T + Q gain = P @ H / (H @ P @ H + R) x += gain * (tilt[i] - H @ x) residual_map = np.eye(2) - np.outer(gain, H) P = residual_map @ P @ residual_map.T + R * np.outer(gain, gain) kf[i] = x[0] series = [tilt, mean, moving, low, comp, kf] names = ['Raw tilt', 'Running mean', '5-sample mean', 'Low-pass', 'Complementary', 'Kalman'] samples = np.column_stack([t, truth, rates, force, *series]) np.savetxt(out/'imu-bench.csv', samples, delimiter=',', fmt='%.8f', comments='', header='t_s,truth_deg,gx_dps,gy_dps,gz_dps,fx_mps2,fy_mps2,fz_mps2,tilt_deg,mean_deg,moving_deg,low_deg,comp_deg,kf_deg') fig, axes = plt.subplots(2, 1, figsize=(7.6, 5.1), sharex=True, layout='constrained') for ax, indices in zip(axes, [[0, 1, 2, 3], [0, 4, 5]]): ax.plot(t, truth, color=INK, lw=2, label='Fixture angle') for j in indices: ax.plot(t, series[j], ['.', ':', '-.', '--', '--', '-'][j], color=[RAW,MEAN,WINDOW,LOW,LOW,WINDOW][j], ms=3, lw=1.5, label=names[j]) ax.set(ylabel='Roll (degrees)', ylim=(-4, 17)) ax.legend(loc='upper left', ncol=3, fontsize=8) axes[1].set_xlabel('Time (s)') save(fig, out/'imu-bench.svg', 'Same board tilt, same clock, two ways to use the sensors') def roll_bias_covariance(path): # A separate one-second thought experiment. Hold the input fixed and add no noise. prior = np.diag([0.5**2, 1.0]) F = np.array([[1., -1.], [0., 1.]]) circle = np.vstack((np.cos(np.linspace(0, 2*np.pi, 181)), np.sin(np.linspace(0, 2*np.pi, 181)))) fig, axes = plt.subplots(1, 2, figsize=(7.6, 3.5), sharex=True, sharey=True, layout='constrained') for ax, P, title in zip(axes, [prior, F @ prior @ F.T], ['Before the gyro step', 'One second later']): ellipse = np.linalg.cholesky(P) @ circle for radius in (2, 1): a, b = radius * ellipse ax.fill(a, b, color=WINDOW, alpha=.12) ax.plot(a, b, color=WINDOW, lw=1) ax.axhline(0, lw=.7, color=INK) ax.axvline(0, lw=.7, color=INK) ax.set(title=title, xlabel='Roll error (degrees)', xlim=(-2.6, 2.6), ylim=(-2.4, 2.4)) axes[0].set_ylabel('Bias error (degrees/s)') save(fig, path, 'Subtracting gyro bias tilts the joint error distribution') def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--signal", choices=["bench", "step"], default="bench") parser.add_argument("--window", type=int, choices=range(1, 9), default=3) parser.add_argument("--alpha", type=float, default=.25) parser.add_argument("--out", type=Path, default=Path("drone-filter-plots")) args = parser.parse_args() if not 0 < args.alpha <= 1: parser.error("alpha must be greater than zero and at most one") args.out.mkdir(parents=True, exist_ok=True) readings = BENCH if args.signal == "bench" else STEP samples = np.arange(1, len(readings)+1) running, moving, low = smooth(readings, args.window, args.alpha) residual = readings - low plt.rcParams.update({"axes.spines.top": False, "axes.spines.right": False, "axes.axisbelow": True, "axes.grid": True, "grid.alpha": .17, "axes.labelcolor": INK, "svg.fonttype": "none"}) fig, ax = plt.subplots(figsize=(7.5, 3.8), layout="constrained") ax.plot(samples, readings, ".:", color=RAW, label="Reading") ax.plot(samples, running, "--", color=MEAN, label="Running mean") ax.plot(samples, moving, "-.", color=WINDOW, label=f"Window ({args.window})") ax.plot(samples, low, color=LOW, label=f"Low-pass (α={args.alpha:g})") ax.set(xlabel="Sample", ylabel="Height (m)", xticks=[1,4,8,12]) ax.legend(ncol=2, fontsize=9) save(fig, args.out/"smoothing.svg", "Three filters, one rangefinder") with (args.out/"samples.csv").open("w", newline="") as out: writer = csv.writer(out) writer.writerow(["sample","reading_m","running_m","moving_m","low_pass_m","high_pass_m"]) writer.writerows(zip(samples, readings, running, moving, low, residual)) fig, ax = plt.subplots(figsize=(7.5, 3.5), layout="constrained") ax.plot(samples, readings, ".:", color=RAW, label="Reading") ax.plot(samples, scalar(readings, 1.), color=WINDOW, label="R = 1 m²") ax.plot(samples, scalar(readings, 9.), "--", color=MEAN, label="R = 9 m²") ax.legend(ncol=3, fontsize=9) ax.set(xlabel="Sample", ylabel="Height (m)", xticks=[1,4,8,12]) save(fig, args.out/"scalar.svg", "How much weight does the reading get?") fig, ax = plt.subplots(figsize=(7.5, 3.5), layout="constrained") ax.plot(samples, readings, ".:", color=RAW, label="Input") ax.plot(samples, low, color=LOW, label="Low-pass") ax.plot(samples, residual, "--", color=WINDOW, label="High-pass remainder") ax.axhline(0, color=INK, lw=.8) ax.set(xlabel="Sample", ylabel="Metres", xticks=[1,4,8,12]) ax.legend(ncol=3, fontsize=9) save(fig, args.out/"high-pass.svg", "Two branches add back to the reading") height_and_climb(args.out/"state.svg") nonlinear(args.out/"beacon.svg") attitude(args.out/"attitude.svg") two_sensors(args.out, args.window, args.alpha) imu_bench(args.out) roll_bias_covariance(args.out/"roll-bias-covariance.svg") print(f"Wrote nine SVG figures, samples.csv, two-sensor.csv and imu-bench.csv to {args.out}") if __name__ == "__main__": main()