PyKalman

0.11.2 · active · verified Thu Apr 16

PyKalman is an active Python library providing robust implementations of the Kalman Filter, Kalman Smoother, and the Expectation-Maximization (EM) algorithm. It is designed for state estimation in linear dynamical systems and parameter learning, with recent updates ensuring compatibility with modern Python and NumPy versions. The library maintains a steady release cadence with regular bug fixes and maintenance updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the basic usage of `KalmanFilter` to estimate states from noisy measurements. It defines a simple linear system, generates synthetic data, and then applies the `filter` and `smooth` methods to estimate the underlying states.

import numpy as np
from pykalman import KalmanFilter

# Define the parameters of a simple linear system
transition_matrices = [[1, 1], [0, 1]] # State transition matrix
observation_matrices = [[1, 0]]       # Observation matrix (we observe position only)
transition_covariance = np.eye(2) * 0.1 # Small process noise
observation_covariance = np.eye(1) * 1.0 # Larger observation noise
initial_state_mean = [0, 1]           # Initial state (position=0, velocity=1)
initial_state_covariance = np.eye(2) * 1.0 # Initial uncertainty

# Create a Kalman Filter instance
kf = KalmanFilter(
    transition_matrices=transition_matrices,
    observation_matrices=observation_matrices,
    transition_covariance=transition_covariance,
    observation_covariance=observation_covariance,
    initial_state_mean=initial_state_mean,
    initial_state_covariance=initial_state_covariance
)

# Generate some noisy 'measurements' for a simple linear motion
n_timesteps = 50
true_states = np.zeros((n_timesteps, 2))
measurements = np.zeros((n_timesteps, 1))
true_states[0] = initial_state_mean
for t in range(1, n_timesteps):
    true_states[t] = np.dot(transition_matrices, true_states[t-1]) + np.random.multivariate_normal([0, 0], transition_covariance)
    measurements[t] = np.dot(observation_matrices, true_states[t]) + np.random.normal(0, np.sqrt(observation_covariance[0,0]))

# Use the Kalman Filter to estimate the states from measurements
(filtered_state_means, filtered_state_covariances) = kf.filter(measurements)
(smoothed_state_means, smoothed_state_covariances) = kf.smooth(measurements)

print("First 5 filtered state means (position, velocity):")
print(filtered_state_means[:5])
print("\nFirst 5 smoothed state means (position, velocity):")
print(smoothed_state_means[:5])

view raw JSON →