Fusing a 5 Hz position fix into a 100 Hz filter¶
A navigation filter runs at the rate of its fastest sensor, here an accelerometer read 100 times a second, while its position fix arrives only five times a second. On the filter's ticks between two fixes there is nothing new to correct with: the fix must correct the estimate once, on the tick it arrives, and be left out on the 19 ticks after it.
Two flags say this to the filter:
Sensor(..., fresh_output=True)adds the outputfresh, true only on the tick a new measurement arrives;KalmanFilter(..., enable_validity=True)adds the inputvalid, and leaves a measurement channel whose flag is false out of that step's correction.
This example builds the loop, runs it, and then runs it again with the sensor's
valid output in place of fresh. valid is held between the sensor's ticks, as
its measurement is, so the filter then takes each fix as 20 independent ones.
import matplotlib.pyplot as plt
import numpy as np
import jaxonomy
from jaxonomy import library as lib
from jaxonomy import logging
from jaxonomy.simulation import ResultsMode, ResultsOptions
logging.set_log_level(logging.ERROR)
DT_FILTER = 0.01 # s: the accelerometer and the filter, 100 Hz
DT_FIX = 0.2 # s: the position fix, 5 Hz
ACCEL_NOISE = 0.05 # m/s^2: the accelerometer's noise, per sample
FIX_NOISE = 1.5 # m: the fix's noise, per fix
T_END = 60.0 # s
WARM_UP = 10.0 # s: the error statistics leave out the start
The model¶
The truth is a cart on a line whose acceleration is a sum of two sines, integrated twice; it starts at 1 m/s, and the filter's initial estimate says it is at rest.
Each sensor samples the truth at its own rate with the noise of its datasheet:
noise_density is the white noise's density, so a sample's standard deviation is
noise_density / sqrt(dt). The fix crosses from its 5 Hz rate to the filter's
100 Hz through an explicit RateTransition, which holds it between fixes; the flag
that says when it is new goes to the filter directly.
The filter's state is position and velocity, driven by the measured acceleration:
its process noise is the accelerometer's, entering as the acceleration does
(G = B), and its measurement noise is the fix's. Its model is the sensors' own,
so the covariance it reports is the one its errors should show.
def fusion(flag):
"""The loop, with the filter's ``valid`` input fed by the fix's ``flag``:
"fresh", "valid", or "none" (no fix at all)."""
b = jaxonomy.DiagramBuilder()
a1 = b.add(lib.Sine(amplitude=0.5, frequency=0.4, name="a1"))
a2 = b.add(lib.Sine(amplitude=0.3, frequency=1.1, name="a2"))
accel = b.add(lib.Adder(2, name="accel"))
velocity = b.add(lib.Integrator(1.0, name="velocity"))
position = b.add(lib.Integrator(0.0, name="position"))
b.connect(a1.output_ports[0], accel.input_ports[0])
b.connect(a2.output_ports[0], accel.input_ports[1])
b.connect(accel.output_ports[0], velocity.input_ports[0])
b.connect(velocity.output_ports[0], position.input_ports[0])
imu = b.add(lib.Sensor(DT_FILTER, noise_density=ACCEL_NOISE * np.sqrt(DT_FILTER),
seed=1, name="imu"))
fix = b.add(lib.Sensor(DT_FIX, noise_density=FIX_NOISE * np.sqrt(DT_FIX), seed=2,
fresh_output=True, name="fix"))
b.connect(accel.output_ports[0], imu.input_ports[0])
b.connect(position.output_ports[0], fix.input_ports[0])
fix_at_100hz = b.add(lib.RateTransition(DT_FIX, DT_FILTER, name="fix_at_100hz"))
b.connect(fix.output_ports[0], fix_at_100hz.input_ports[0])
A = np.array([[1.0, DT_FILTER], [0.0, 1.0]])
B = np.array([[0.5 * DT_FILTER**2], [DT_FILTER]])
kf = b.add(lib.KalmanFilter(
DT_FILTER, A, B, C=np.array([[1.0, 0.0]]), G=B,
Q=np.array([[ACCEL_NOISE**2]]), R=np.array([[FIX_NOISE**2]]),
x_hat_0=np.array([0.0, 0.0]), P_hat_0=np.diag([FIX_NOISE**2, 1.0]),
enable_validity=True, enable_output_innovation=True,
enable_output_state_covariance=True, name="kf",
))
b.connect(imu.output_ports[0], kf.input_ports[0])
b.connect(fix_at_100hz.output_ports[0], kf.input_ports[1])
if flag == "none":
b.connect(b.add(lib.Constant(False, name="no_fix")).output_ports[0], kf.input_ports[2])
else:
b.connect(fix.get_output_port(flag), kf.input_ports[2])
return b.build(name="fusion")
Three runs¶
The same seeds, so the three runs see the same noise: the fix flagged fresh, the
fix flagged with the held valid, and no fix. One row is recorded per filter tick.
A correction leaves the filter's innovation (the fix less the predicted position)
finite; a step that leaves the fix out makes it NaN, so counting the finite ones
counts the corrections.
def run(flag):
d = fusion(flag)
kf = d["kf"]
res = jaxonomy.simulate(
d, d.create_context(), (0.0, T_END),
results_options=ResultsOptions(mode=ResultsMode.fixed_interval,
fixed_results_interval=DT_FILTER),
recorded_signals={
"position": d["position"].output_ports[0],
"velocity": d["velocity"].output_ports[0],
"fix": d["fix_at_100hz"].output_ports[0],
"x_hat": kf.output_ports[0],
"innovation": kf.get_output_port("innovation"),
"P_hat": kf.get_output_port("P_hat"),
},
)
out = {k: np.asarray(v) for k, v in res.outputs.items()}
out["t"] = np.asarray(res.time)
return out
runs = {flag: run(flag) for flag in ("fresh", "valid", "none")}
def summary(out):
late = out["t"] >= WARM_UP
error = out["x_hat"][:, 0] - out["position"]
sigma = np.sqrt(out["P_hat"][:, 0, 0])
return {
"corrections": int(np.sum(np.isfinite(out["innovation"]))),
"rms_error_m": float(np.sqrt(np.mean(error[late] ** 2))),
"reported_sigma_m": float(np.median(sigma[late])),
"within_2_sigma": float(np.mean(np.abs(error[late]) <= 2.0 * sigma[late])),
"velocity_rms_error": float(np.sqrt(np.mean((out["x_hat"][late, 1] - out["velocity"][late]) ** 2))),
}
stats = {flag: summary(out) for flag, out in runs.items()}
late = runs["fresh"]["t"] >= WARM_UP
fix_rms = float(np.sqrt(np.mean((runs["fresh"]["fix"].ravel() - runs["fresh"]["position"])[late] ** 2)))
print(f"the fix alone: rms error {fix_rms:.3f} m\n")
print(f"{'flag':6} {'corrections':>11} {'rms error':>10} {'reported':>9} {'within 2σ':>10} {'velocity rms':>13}")
for flag, s in stats.items():
print(f"{flag:6} {s['corrections']:11d} {s['rms_error_m']:9.3f}m {s['reported_sigma_m']:8.3f}m "
f"{s['within_2_sigma']:10.1%} {s['velocity_rms_error']:10.3f}m/s")
the fix alone: rms error 1.530 m flag corrections rms error reported within 2σ velocity rms fresh 301 0.282m 0.245m 99.2% 0.050m/s valid 6001 0.372m 0.076m 22.2% 0.051m/s none 0 38.978m 35.037m 100.0% 1.023m/s
With fresh the filter corrects five times a second, once per fix, and its
position error is a fraction of the fix's own. Its reported standard deviation
is honest: about 95 % of its errors or more lie within twice it.
With the held valid flag it corrects on every tick, 20 times per fix. It takes
each repetition as new information, so its reported uncertainty shrinks far below
its actual error, and the estimate follows the fix's noise more closely than the
two sensors justify: its error is larger, and most of it lies outside the band the
filter claims. A filter that believes such a covariance also weighs the next
sensor, and any gate on its innovations, wrongly.
Without a fix the initial velocity error is never corrected, and the position drifts by it.
fresh, held, none = stats["fresh"], stats["valid"], stats["none"]
# The run's instants include both ends, t = 0 and t = T_END.
n_fixes = int(round(T_END / DT_FIX)) + 1
assert fresh["corrections"] == n_fixes
assert held["corrections"] == len(runs["valid"]["t"])
assert none["corrections"] == 0
assert fresh["rms_error_m"] < 0.3 * fix_rms
assert fresh["within_2_sigma"] >= 0.9
assert held["rms_error_m"] > fresh["rms_error_m"]
assert held["within_2_sigma"] < 0.5 and held["reported_sigma_m"] < 0.5 * fresh["reported_sigma_m"]
assert none["rms_error_m"] > 10 * fresh["rms_error_m"]
fig, axes = plt.subplots(2, 1, figsize=(9, 6), sharex=True, sharey=True)
for ax, flag in zip(axes, ("fresh", "valid")):
out = runs[flag]
error = out["x_hat"][:, 0] - out["position"]
sigma = np.sqrt(out["P_hat"][:, 0, 0])
ax.fill_between(out["t"], -2 * sigma, 2 * sigma, color="tab:blue", alpha=0.2,
label="the filter's ±2σ")
ax.plot(out["t"], error, color="tab:blue", lw=0.8, label="position error")
ax.set_title(f"valid ← fix.{flag}")
ax.set_ylabel("m")
ax.set_ylim(-1.5, 1.5)
ax.legend(loc="upper right")
axes[-1].set_xlabel("time (s)")
fig.tight_layout()
What to take from it¶
- A sensor slower than the filter feeds its measurement through a
RateTransitionand itsfreshflag straight to the filter'svalidinput: the filter reads the flag on its own ticks, true once per measurement. - The held
validflag is the right input only for a filter that runs at the sensor's own rate; faster, it fuses each measurement as many times as the filter ticks between two of them.