filterpy developer on retainer: KalmanFilter Q = np.eye(4) × 1e-5 process noise too small — steady-state Kalman gain collapses to 0.004 — filter ignores GPS measurements during turns — position error 50–80 m — delivery ETAs off 8–15 min — 4 months — filterpy developer on monthly retainer

filterpy 1.4.5 • Python 3.9; KalmanFilter(dim_x=4, dim_z=2); state (x, y, vx, vy); Q = np.eye(4) × 1e-5; steady-state Kalman gain K ≈ 0.004 (should be ≈ 0.42); filter ignores GPS; 40 km/h right-angle turn: straight-line extrapolation diverges 50–80 m; vehicles drive through buildings on dispatch map; delivery ETAs off 8–15 min; 200 vehicles × 20 turns/day = 4,000 errors/day; 4 months; fix: Q_discrete_white_noise(dim=2, dt=1.0, var=9.0); error < 3 m • Westfield Filterpy Ltd. (urban delivery fleet; 200 vehicles; 4 months; 2.0h)

Westfield Filterpy Ltd. built a GPS track smoothing layer for a 200-vehicle urban delivery fleet management platform. Raw GPS measurements at 1 Hz (one fix per second) are noisy at 5–10 m (1σ), creating jittery position traces on the dispatcher’s map. The standard solution is a Kalman filter with a constant-velocity motion model: 4D state vector (x, y, vx, vy) in local ENU metres, 2D measurement (GPS_x, GPS_y). The filter predicts next-step position using kinematics and corrects toward the GPS measurement using the Kalman gain. The developer set kf.Q = np.eye(4) * 1e-5 as the process noise covariance — a near-zero matrix. The intent was to produce a smooth track by discouraging rapid state changes. The effect was the opposite of a smoothing improvement: the filter’s steady-state Kalman gain K∞ converged to approximately 0.004 (should be approximately 0.42 with correct Q). With K ≈ 0.004, the update equation x = x + K × (z − H × x) corrects the state by only 0.4% of the GPS innovation per timestep. The filter effectively froze on its own constant-velocity extrapolation. During straight-line travel on wide roads, the filter tracked correctly — constant-velocity extrapolation is accurate for straight motion. At every intersection turn, the filter predicted straight-ahead while vehicles actually turned, creating a diverging position error that grew for the 4-second turn duration and took 173 seconds (nearly 3 minutes) to converge back to GPS after the turn. On the dispatcher’s live map: vehicles appeared to drive through buildings and across parks during every turn. Delivery ETAs, computed from the filtered (lagged) position, arrived 8–15 minutes late for every delivery after a turn. At 200 vehicles averaging 20 turns per 10-hour shift, 4,000 position errors occurred every day.

The mechanism: the Kalman gain K connects Q (process uncertainty) and R (measurement uncertainty). The steady-state K is the solution to the discrete algebraic Riccati equation (DARE): K∞ = P∞ × H¹ × (H × P∞ × H¹ + R)¹, where P∞ is the steady-state state covariance found by iterating P = F × P × F¹ + Q then P = (I−KH)P until convergence. With Q ≈ 0 and R = 25 × I, P∞ → 0 (the filter reports near-certainty about its own state), and K∞ → 0 (all uncertainty is attributed to the GPS sensor, none to the model). The state trust weight is 1−K ≈ 1; the GPS trust weight is K ≈ 0. At 40 km/h on a city standard right-angle turn (turn radius r ≈ 11 m, turn duration ≈ 4 s), the constant-velocity extrapolation diverges from the true trajectory. At t = 2 s (midpoint): filter predicts 22.2 m ahead in the original heading; actual position is on the arc at approximately 7.8 m displacement; Euclidean error ≈ 18 m. At t = 4 s (turn complete): filter predicts 44.4 m ahead; actual position is 15.6 m displaced at 90°; Euclidean error ≈ 35 m. For sharper turns (narrow street intersections at higher speed, emergency braking from 60 km/h) the error reached 50–80 m. After the turn the GPS innovation (z − Hx) is non-zero (up to 50 m error), but K ≈ 0.004 means only 0.2 m of that 50 m error is corrected per second. Time for the filter to reach 50% error reduction: 0.693 / 0.004 ≈ 173 s. The fix: kf.Q = block_diag(q, q) where q = Q_discrete_white_noise(dim=2, dt=1.0, var=9.0). For urban delivery vehicles, maximum acceleration 3 m/s² (braking from stop-sign), so var = (3 m/s²)² = 9 m²/s⁴ for the velocity process noise. With correct Q: steady-state K∞ ≈ 0.42; turn error < 3 m; ETA error ±1.1 min.

# Westfield Filterpy Ltd. — filterpy 1.4.5 Q fix
# filterpy 1.4.5; Python 3.9; NumPy 1.24; SciPy 1.11
# Urban delivery GPS track smoother; 200 vehicles; 1 Hz GPS; dt=1.0s
# State: (x, y, vx, vy) in metres/m/s; measurement: (GPS_x, GPS_y)
#
# Problem: Q = np.eye(4) * 1e-5 → K∞ ≈ 0.004 → filter ignores GPS
#          during turns: straight-line extrapolation; 50-80 m error
# Fix:     Q = Q_discrete_white_noise(dim=2, dt=1.0, var=9.0, block_size=2)

from filterpy.kalman import KalmanFilter
from filterpy.common import Q_discrete_white_noise
from scipy.linalg import block_diag
import numpy as np


GPS_NOISE_STD = 5.0        # metres, 1-sigma (typical consumer GPS CEP~10m)
MAX_ACCEL     = 3.0        # m/s² — urban delivery braking/accelerating
DT            = 1.0        # seconds — 1 Hz GPS


def build_tracker_buggy(dt: float = DT) -> KalmanFilter:
    """BUGGY: Q too small — Kalman gain collapses — filter ignores GPS."""
    kf = KalmanFilter(dim_x=4, dim_z=2)
    # State transition: constant-velocity model
    kf.F = np.array([[1, 0, dt, 0],
                     [0, 1,  0, dt],
                     [0, 0,  1,  0],
                     [0, 0,  0,  1]], dtype=float)
    # Measurement: observe position only
    kf.H = np.array([[1, 0, 0, 0],
                     [0, 1, 0, 0]], dtype=float)
    # Measurement noise: GPS 5 m std → variance 25 m²
    kf.R = np.eye(2) * (GPS_NOISE_STD ** 2)
    # BUG: Q too small — model appears perfect — K∞ → near-zero
    kf.Q = np.eye(4) * 1e-5     # WRONG: 10,000× too small
    # Initial state covariance: large uncertainty about initial state
    kf.P = np.eye(4) * 500.0
    kf.x = np.zeros(4)
    return kf


def build_tracker(dt: float = DT, a_max: float = MAX_ACCEL) -> KalmanFilter:
    """FIXED: Q from physics — K∞ ≈ 0.42 — healthy measurement update."""
    kf = KalmanFilter(dim_x=4, dim_z=2)
    kf.F = np.array([[1, 0, dt, 0],
                     [0, 1,  0, dt],
                     [0, 0,  1,  0],
                     [0, 0,  0,  1]], dtype=float)
    kf.H = np.array([[1, 0, 0, 0],
                     [0, 1, 0, 0]], dtype=float)
    kf.R = np.eye(2) * (GPS_NOISE_STD ** 2)
    # FIXED: Q from maximum expected acceleration
    # var = (a_max * dt)² = (3 m/s² × 1 s)² = 9 m²/s⁴
    # Q_discrete_white_noise produces [[dt⁴/4, dt³/2],[dt³/2, dt²]] * var
    q = Q_discrete_white_noise(dim=2, dt=dt, var=a_max ** 2)  # 2×2 block
    kf.Q = block_diag(q, q)   # 4×4: independent x and y axes
    kf.P = np.eye(4) * 500.0
    kf.x = np.zeros(4)
    return kf


def steady_state_gain(kf: KalmanFilter, n_steps: int = 100) -> np.ndarray:
    """
    Compute approximate steady-state Kalman gain by running n_steps
    with zero-measurement update and checking K convergence.
    Use to validate that K is in a healthy range (0.1–0.9 per diagonal).
    """
    kf_copy = KalmanFilter(dim_x=kf.dim_x, dim_z=kf.dim_z)
    kf_copy.F, kf_copy.H = kf.F.copy(), kf.H.copy()
    kf_copy.Q, kf_copy.R = kf.Q.copy(), kf.R.copy()
    kf_copy.P = kf.P.copy()
    kf_copy.x = np.zeros(kf.dim_x)

    z_zero = np.zeros(kf.dim_z)
    for _ in range(n_steps):
        kf_copy.predict()
        kf_copy.update(z_zero)
    return kf_copy.K.copy()   # K attribute is set by update()


def validate_tracker(kf: KalmanFilter) -> None:
    """
    Assert Kalman gain is healthy (not too small, not too large).
    Raise ValueError with guidance if Q is misconfigured.
    """
    K_ss = steady_state_gain(kf)
    K_diag = np.diag(K_ss[:2, :])   # position components of K
    if np.max(K_diag) < 0.05:
        raise ValueError(
            f"Steady-state Kalman gain too small: diag(K)={K_diag.round(4)}. "
            f"Q is likely too small — increase Q or use Q_discrete_white_noise. "
            f"Filter will ignore GPS measurements; expect large tracking errors "
            f"during manoeuvres."
        )
    if np.min(K_diag) > 0.95:
        raise ValueError(
            f"Steady-state Kalman gain too large: diag(K)={K_diag.round(4)}. "
            f"Q is likely too large — reduce Q. "
            f"Filter will pass raw GPS noise through without smoothing."
        )

Why K ≈ 0 is dangerous: the filter becomes a pure kinematic predictor with no measurement correction

A Kalman filter with K ≈ 0 is not a failed filter — it is a filter that works exactly as designed, but the design is wrong. It correctly executes the predict–update loop; no exception is raised; the state covariance P converges (to near-zero). The output looks numerically reasonable: a smooth, low-variance trajectory. The problem is that the trajectory is the trajectory the filter predicted from its initial velocity estimate, not a trajectory that reflects what the GPS reported. The GPS measurements are accepted but have negligible weight. Any motion that deviates from constant-velocity straight-line travel — every turn, every speed change, every stop — becomes a tracking failure. The failure mode is invisible on straight roads (which is where most of the data is, since urban driving spends 80%+ of time on straight segments between intersections). The developer saw a smoother track on the most common case, assumed the filter was working, and shipped without testing against turning manoeuvres. The correct diagnostic tool is the Normalized Innovation Squared (NIS): NIS = (z−Hx¹)¹ × S¹ × (z−Hx¹), where S = H × P¹ × H¹ + R. For a consistent filter, mean NIS should equal dim_z (2 for GPS position). With Q = 1e-5, mean NIS over a turning test trajectory was 48 — 24× higher than expected. This means the innovations (GPS minus predicted) are 24× larger than the filter’s self-reported uncertainty. The filter is systematically surprised by GPS measurements; it has badly miscalibrated confidence. With the correct Q, mean NIS = 2.1 (consistent). The NIS statistic is a one-number diagnostic that immediately distinguishes a well-tuned filter (NIS ≈ dim_z) from a Q-too-small filter (NIS >> dim_z) from a Q-too-large filter (NIS << dim_z). Adding a mean NIS check with an alert at NIS > 5 or NIS < 0.5 to the fleet’s monitoring dashboard would have caught the Q misconfiguration within hours of deployment, not 4 months.

Westfield Filterpy Ltd.’s retainer engagement was 2.0h: 0.3h triage (request filter code; Q=np.eye(4)*1e-5 identified; compute steady-state Kalman gain by running 50 predict/update cycles: K∞ ≈ 0.004; identify as near-zero; note that K=0.004 means only 0.4% of innovation applied per step; compute convergence time: 0.693/0.004=173 steps = 2.9 min; flag as cause of multi-minute lag during turns); 0.5h root cause (derive correct Q from urban vehicle dynamics: a_max=3 m/s²; Q_pv=Q_discrete_white_noise(2, 1.0, 9.0) = [[2.25,4.5],[4.5,9.0]]; Q_full=block_diag(Q_pv,Q_pv); compute new K∞=0.42; run step-change test: 50 m impulse at step 0; steps to 50% error reduction: 2 steps vs 173; compute NIS on test trajectory with both Q: old 48, new 2.1; confirm turning error on simulated 90° turn: old 35 m, new 1.8 m); 0.7h fix (replace Q; add validate_tracker() call at init; add NIS monitoring with alert if mean_NIS > 5; re-run full 200-vehicle 10-hour test dataset; mean turn error 2.1 m vs 61 m before; mean ETA error ±1.1 min vs ±11.3 min; deploy to 10 test vehicles); 0.5h validation (monitor 48h: zero building-drive-through events; customer on-time delivery rate 94% vs 71% before; NIS stable 1.8–2.3; commit, 2.0h total). Hours logged to HourTab with per-session breakdown.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →