Providing minimal Kalman filter example
I'm delivering a concise Python snippet implementing a Kalman filter for smoothing noisy 2D GPS coordinates using position and velocity, with placeholders for GPS input and notes on tuning noise parameters.
Below is a minimal Python example of using a Kalman filter to smooth 2D GPS coordinates for a fitness-tracking scenario. It models state as position and velocity (x, y, vx, vy), predicts each next position based on velocity, and corrects using noisy GPS measurements.
import numpy as np
# Example GPS measurements (lat/long). Replace with your data.
# Shape: (num_samples, 2) => [ [x1, y1], [x2, y2], ... ]
gps_measurements = np.array([
[10.0, 5.0],
[10.5, 5.1],
[11.0, 5.2],
[11.5, 5.4],
[12.0, 5.45], # etc...
])
dt = 1.0 # time step in seconds (adjust if your sampling rate is different)
# State vector: [x, y, vx, vy]
state = np.array([gps_measurements[0,0], gps_measurements[0,1], 0.0, 0.0])
# State transition model (assuming constant velocity)
F = np.array([
[1, 0, dt, 0 ],
[0, 1, 0, dt],
[0, 0, 1, 0 ],
[0, 0, 0, 1 ]
])
# Measurement model (we measure position only)
H = np.array([
[1, 0, 0, 0],
[0, 1, 0, 0]
])
# Process noise covariance (tune as needed)
q = 0.01
Q = np.array([
[q, 0, 0, 0],
[0, q, 0, 0],
[0, 0, q, 0],
[0, 0, 0, q]
])
# Measurement noise covariance (tune based on GPS accuracy)
r = 0.1
R = np.array([
[r, 0],
[0, r]
])
# Initial covariance matrix
P = np.eye(4) * 1.0
smoothed_positions = []
for z in gps_measurements:
# 1) Predict
state = F @ state
P = F @ P @ F.T + Q
# 2) Update
z = np.array(z)
y = z - (H @ state) # measurement residual
S = H @ P @ H.T + R # residual covariance
K = P @ H.T @ np.linalg.inv(S) # Kalman gain
state = state + (K @ y)
P = (np.eye(4) - K @ H) @ P
smoothed_positions.append(state[:2]) # store just x, y
smoothed_positions = np.array(smoothed_positions)
print("Smoothed path:\n", smoothed_positions)
How it works:
- Initialize the state as the first GPS point with zero velocity.
- Predict the next state using the constant-velocity model (
F).
- Correct with the incoming noisy measurement (
z) via Kalman update.
- The
smoothed_positions array contains the filtered coordinates, which should yield a smoother path on a map.
Tune Q and R based on the characteristics of your sensor noise and movement. You can also incorporate altitude or other signals by extending the state and measurement models accordingly.