FilterPy: Kalman Filtering and Optimal Estimation
FilterPy is a Python library for Kalman filtering and optimal estimation, including Kalman Filters, Extended Kalman Filters, and Unscented Kalman Filters. It provides a robust and well-documented framework for state estimation. The current version is 1.4.5, which has been stable since 2017, indicating a very mature but not actively developed codebase.
Warnings
- gotcha Incorrect matrix dimensions or initialization for state vector (x), covariance matrices (P, Q, R) are very common. This leads to `ValueError` during matrix operations or, more subtly, poor filter performance and divergence. Ensure `dim_x`, `dim_z` match your matrix shapes.
- gotcha Defining the process noise covariance matrix (Q) is often challenging and misunderstood. An inappropriate `Q` can lead to filter divergence or sluggish response. While the library provides `Q_discrete_white_noise`, users often use overly simplistic or incorrect `Q` matrices.
- gotcha FilterPy version 1.4.5 has not been updated since 2017. While functional and stable, it is not actively maintained. This means no new features, bug fixes for new Python versions/dependencies, or performance improvements are expected. Users should be aware of this for long-term project planning.
Install
-
pip install filterpy
Imports
- KalmanFilter
from filterpy.kalman import KalmanFilter
- ExtendedKalmanFilter
from filterpy.kalman import ExtendedKalmanFilter
- UnscentedKalmanFilter
from filterpy.kalman import UnscentedKalmanFilter
- Q_discrete_white_noise
from filterpy.common import Q_discrete_white_noise
Quickstart
import numpy as np
from filterpy.kalman import KalmanFilter
# Create a KalmanFilter object
kf = KalmanFilter(dim_x=2, dim_z=1)
# Initialize state vector x (position, velocity)
kf.x = np.array([[0.], [0.]])
# State transition matrix F
kf.F = np.array([[1., 1.],
[0., 1.]])
# Measurement function H
kf.H = np.array([[1., 0.]])
# State covariance matrix P
kf.P *= 1000.
# Measurement noise covariance R
kf.R = 5 # Measurement noise
# Process noise covariance Q
kf.Q = np.diag([0.01, 0.01]) # Simple process noise
# Simulate some measurements
z = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# Run the filter
estimates = []
for measurement in z:
kf.predict()
kf.update(measurement)
estimates.append(kf.x.T[0].tolist())
# print(estimates)
# Expected output for first few: [[...], [...]]