Kalman Filters with FilterPy
Turn a jittery AIS track into a smooth path and a running velocity estimate with a constant-velocity Kalman filter in FilterPy, then flag GPS outliers with the filter's innovation.
Raw AIS positions jitter, drop out, and arrive on an uneven clock, so a plotted track shows saw-tooth zig-zags no vessel ever sailed. In this tutorial you build a constant-velocity Kalman filter with FilterPy, run it over a real NOAA track pulled through AISdb, and get back a smoothed path, a speed estimate at every report, and a statistical test that flags spurious GPS fixes before they reach a chart or a downstream model.
What you will learn
Select a steady transit out of thousands of tracks using
delta_knotsSet up a four-state constant-velocity filter and read
H,R,P,F, andQHandle AIS's irregular reporting clock by rebuilding
FandQfrom each time gapFlag GPS outliers with the filter's innovation instead of hand-tuned distance rules
Prerequisites
pip install aisdb filterpy matplotlibOne data file, the open NOAA day AIS_2020_01_01.zip, decoded to ./data/ais_2020_01_01.db via aisdb.decode_msgs exactly as in step 1 of the clustering tutorial. Every number and figure below is the output of running this page end to end on AISdb 1.8.0-alpha.
1. Query the day and generate tracks
With the database in place, query the Gulf of Mexico window. decimate=False matters here, curve decimation would throw away exactly the irregular spacing the filter is designed to handle.
from datetime import datetime
import numpy as np
import aisdb
from aisdb import SQLiteDBConn, DBQuery
from aisdb.database import sqlfcn_callbacks
from aisdb.gis import delta_knots
dbpath = './data/ais_2020_01_01.db' # built in the clustering tutorial
with SQLiteDBConn(dbpath=dbpath) as dbconn:
qry = DBQuery(dbconn=dbconn,
start=datetime(2020, 1, 1), end=datetime(2020, 1, 2),
xmin=-98, xmax=-80, ymin=24, ymax=31, # Gulf of Mexico
callback=sqlfcn_callbacks.in_bbox_time_validmmsi)
tracks = list(aisdb.track_gen.TrackGen(qry.gen_qry(), decimate=False))
n_positions = sum(t['time'].size for t in tracks)
print(f"loaded {len(tracks)} vessel tracks ({n_positions:,} positions)")2. Pick one steady vessel
A constant-velocity model is easiest to read on a vessel that holds a course, so keep only genuine transits, 150 to 600 reports, no inter-report speed above 60 knots (GPS teleports), a median speed of 8 to 18 knots (cruising pace, not drifting or docked), at least 5 hours long, and take the longest survivor. delta_knots doubles as the teleport check (its maximum) and the cruising check (its median).
3. Build the constant-velocity filter
The state is [x, y, vx, vy] in local meters (an equirectangular projection is accurate over one track's extent, and meters keep velocity physical). H picks position out of the state because AIS observes position, not velocity; R encodes trust in each fix; P starts wide on velocity because it is initialized at zero with no evidence yet. Since reports arrive on an uneven clock, F and Q are functions of each elapsed gap rather than fixed matrices, with Q growing in the gap because a longer blind stretch leaves more room for the vessel to have turned.
accel_std is the one knob worth tuning, expected velocity change in meters per second squared. A steady cargo-style transit earns 0.1, letting the filter smooth through jitter; a maneuvering tug or fishing vessel needs closer to 0.5 so it does not fight real turns.
4. Run the filter over the track
Loop through the reports in order, predict forward by the elapsed gap, update with the new fix, and record the state. Speed comes from the velocity components, and the inverse projection puts the smoothed path back into degrees for mapping.
5. Flag GPS outliers with the innovation
The innovation is the gap between a measurement and the filter's prediction, judged against the uncertainty the filter already computed. A fix landing more than four sigma out is exactly the spurious jump denoising code hunts for, so reset the filter and make a second pass that tests each fix before accepting it.
Zero flags is the right answer here, not a bug, this vessel was selected for its steadiness. Run the identical pass over the day's loitering vessels and the flags land where they should. A stationary vessel with a 41-knot teleport in an otherwise clean track flagged 3 of 405 reports, and a corrupted transceiver whose fixes jump at up to 1352 knots flagged 153 of 646. Four sigma is conservative on purpose; tighten it to catch subtler drift at the cost of false positives on legitimate sharp turns.
Results

The ringing over the first two hours looks alarming and is not. The state begins with vx = vy = 0, so the earliest steps show the filter swinging toward the true speed as evidence arrives; seed the initial velocity from the first two positions if you need a clean series from the first sample. From then on the estimate and the vessel's own SOG track each other closely, including through the stop, where the estimate floors near half a knot because anchored GPS jitter never quite reads as zero motion.

The two lines separate exactly where they should, at tight maneuvers, long reporting gaps, and any fix that reads far from its neighbors. Remember the filter smooths noise but not bias, a transceiver reporting a consistently offset position produces a faithfully smoothed offset track, so cross-check persistent lane divergences against other data.
Takeaway
A constant-velocity Kalman filter turns jittery, unevenly timed AIS reports into a smooth track plus a velocity estimate at every step.
Rebuilding
FandQfrom each report gap is what makes the filter native to AIS's irregular clock.accel_stdis the single knob that trades smoothness against responsiveness; match it to the vessel's maneuvering style.The innovation test gives a principled GPS-outlier flag for free, no hand-tuned distance thresholds required.
Next, seq2seq in PyTorch learns to predict where a denoised, velocity-bearing track goes next.
References
FilterPy documentation: https://filterpy.readthedocs.io/
Roger Labbe, "Kalman and Bayesian Filters in Python": https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python
AISdb repository: https://github.com/MAPS-Lab/AISdb
Last updated