Python Kalman filtering and optimal estimation library. Implements Kalman filter, particle filter, Extended Kalman filter, Unscented Kalman filter, g-h (alpha-beta), least squares, H Infinity, smoothers, and more. Has companion book 'Kalman and Bayesian Filters in Python'.


FilterPy - Kalman filters and other optimal and non-optimal estimation filters in Python.

NOTE: Imminent drop of support of Python 2.7, 3.4. See section below for details.

This library provides Kalman filtering and various related optimal and non-optimal filtering software written in Python. It contains Kalman filters, Extended Kalman filters, Unscented Kalman filters, Kalman smoothers, Least Squares filters, fading memory filters, g-h filters, discrete Bayes, and more.

This is code I am developing in conjunction with my book Kalman and Bayesian Filter in Python, which you can read/download at

My aim is largely pedalogical - I opt for clear code that matches the equations in the relevant texts on a 1-to-1 basis, even when that has a performance cost. There are places where this tradeoff is unclear - for example, I find it somewhat clearer to write a small set of equations using linear algebra, but numpy's overhead on small matrices makes it run slower than writing each equation out by hand. Furthermore, books such Zarchan present the written out form, not the linear algebra form. It is hard for me to choose which presentation is 'clearer' - it depends on the audience. In that case I usually opt for the faster implementation.

I use NumPy and SciPy for all of the computations. I have experimented with Numba and it yields impressive speed ups with minimal costs, but I am not convinced that I want to add that requirement to my project. It is still on my list of things to figure out, however.

Sphinx generated documentation lives at Generation is triggered by git when I do a check in, so this will always be bleeding edge development version - it will often be ahead of the released version.

Plan for dropping Python 2.7 support

I haven't finalized my decision on this, but NumPy is dropping Python 2.7 support in December 2018. I will certainly drop Python 2.7 support by then; I will probably do it much sooner.

At the moment FilterPy is on version 1.x. I plan to fork the project to version 2.0, and support only Python 3.5+. The 1.x version will still be available, but I will not support it. If I add something amazing to 2.0 and someone really begs, I might backport it; more likely I would accept a pull request with the feature backported to 1.x. But to be honest I don't forsee this happening.

Why 3.5+, and not 3.4+? 3.5 introduced the matrix multiply symbol, and I want my code to take advantage of it. Plus, to be honest, I'm being selfish. I don't want to spend my life supporting this package, and moving as far into the present as possible means a few extra years before the Python version I choose becomes hopelessly dated and a liability. I recognize this makes people running the default Python in their linux distribution more painful. All I can say is I did not decide to do the Python 3 fork, and I don't have the time to support the bifurcation any longer.

I am making edits to the package now in support of my book; once those are done I'll probably create the 2.0 branch. I'm contemplating a SLAM addition to the book, and am not sure if I will do this in 3.5+ only or not.


The most general installation is just to use pip, which should come with any modern Python distribution.

pip install filterpy

If you prefer to download the source yourself

cd <directory you want to install to>
git clone
python install

If you use Anaconda, you can install from the conda-forge channel. You will need to add the conda-forge channel if you haven't already done so:

conda config --add channels conda-forge

and then install with:

conda install filterpy

And, if you want to install from the bleeding edge git version

pip install git+

Note: I make no guarantees that everything works if you install from here. I'm the only developer, and so I don't worry about dev/release branches and the like. Unless I fix a bug for you and tell you to get this version because I haven't made a new release yet, I strongly advise not installing from git.

Basic use

Full documentation is at

First, import the filters and helper functions.

import numpy as np
from filterpy.kalman import KalmanFilter
from filterpy.common import Q_discrete_white_noise

Now, create the filter

my_filter = KalmanFilter(dim_x=2, dim_z=1)

Initialize the filter's matrices.

my_filter.x = np.array([[2.],
                [0.]])       # initial state (location and velocity)

my_filter.F = np.array([[1.,1.],
                [0.,1.]])    # state transition matrix

my_filter.H = np.array([[1.,0.]])    # Measurement function
my_filter.P *= 1000.                 # covariance matrix
my_filter.R = 5                      # state uncertainty
my_filter.Q = Q_discrete_white_noise(2, dt, .1) # process uncertainty

Finally, run the filter.

while True:

    # do something with the output
    x = my_filter.x

Sorry, that is the extent of the documentation here. However, the library is broken up into subdirectories: gh, kalman, memory, leastsq, and so on. Each subdirectory contains python files relating to that form of filter. The functions and methods contain pretty good docstrings on use.

My book uses this library, and is the place to go if you are trying to learn about Kalman filtering and/or this library. These two are not exactly in sync - my normal development cycle is to add files here, test them, figure out how to present them pedalogically, then write the appropriate section or chapter in the book. So there is code here that is not discussed yet in the book.


This library uses NumPy, SciPy, Matplotlib, and Python.

I haven't extensively tested backwards compatibility - I use the Anaconda distribution, and so I am on Python 3.6 and 2.7.14, along with whatever version of NumPy, SciPy, and matplotlib they provide. But I am using pretty basic Python - numpy.array, maybe a list comprehension in my tests.

I import from __future__ to ensure the code works in Python 2 and 3.


All tests are written to work with py.test. Just type py.test at the command line.

As explained above, the tests are not robust. I'm still at the stage where visual plots are the best way to see how things are working. Apologies, but I think it is a sound choice for development. It is easy for a filter to perform within theoretical limits (which we can write a non-visual test for) yet be 'off' in some way. The code itself contains tests in the form of asserts and properties that ensure that arrays are of the proper dimension, etc.


I use three main texts as my refererence, though I do own the majority of the Kalman filtering literature. First is Paul Zarchan's 'Fundamentals of Kalman Filtering: A Practical Approach'. I think it by far the best Kalman filtering book out there if you are interested in practical applications more than writing a thesis. The second book I use is Eli Brookner's 'Tracking and Kalman Filtering Made Easy'. This is an astonishingly good book; its first chapter is actually readable by the layperson! Brookner starts from the g-h filter, and shows how all other filters - the Kalman filter, least squares, fading memory, etc., all derive from the g-h filter. It greatly simplifies many aspects of analysis and/or intuitive understanding of your problem. In contrast, Zarchan starts from least squares, and then moves on to Kalman filtering. I find that he downplays the predict-update aspect of the algorithms, but he has a wealth of worked examples and comparisons between different methods. I think both viewpoints are needed, and so I can't imagine discarding one book. Brookner also focuses on issues that are ignored in other books - track initialization, detecting and discarding noise, tracking multiple objects, an so on.

I said three books. I also like and use Bar-Shalom's Estimation with Applications to Tracking and Navigation. Much more mathematical than the previous two books, I would not recommend it as a first text unless you already have a background in control theory or optimal estimation. Once you have that experience, this book is a gem. Every sentence is crystal clear, his language is precise, but each abstract mathematical statement is followed with something like "and this means...".


The MIT License (MIT)

Copyright (c) 2015 Roger R. Labbe Jr

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.


  • EKF and UKF differ on linear problem with linear measurement

    EKF and UKF differ on linear problem with linear measurement

    Hey, I was testing some of the filters to figure out if I am doing something wrong in my own implementation. Namely, I am interested in the covariance in both filters. From my understanding, this should be equal in a linear problem with a linear measurement.

    The example ( demonstrates that there is a difference between the two, i.e. P is larger in the UKF Is there a different meaning of P in the two filters? (The error in the position tends to zero in the trivial problem)


    opened by vhartman 16
  • 2 D measurements, 3 D state

    2 D measurements, 3 D state

    first, thanks $1M for such an incredible book and set of tools - I had despaired of using Kalman filtering until I discovered them. Second, I am a lapsed C programmer, last active 10 years ago, and have been recently learning Python so as to use this library. Sorry if my inexperience is the cause of my issue.

    I am trying to implement the following KF: dim x = 3 (pos, vel, acc), dim z = 2 (pos, acc) - (PS- tried to attach file but it failed):

    x dim 3- spot, vel and acc,

    z dim = 2, spot and acc

    f = KalmanFilter (dim_x=3, dim_z=2) f.x = np.array([[1.58], # init position [0.01], # init velocity [0.0]]) # init acceleration f.F = np.array([[1.,1., 0.5], # 1, delta T, delta T^2/2 timestep = 1 [0.,1., 1.], # 0, 1, delta T [0.,0., 1.]]) # 0, 0, 1 f.H = np.array([[1.,0., 0.], # dim_z by dim_x, i.e. 2 x 3 [0.,0., 1.]]) # measure position, and acc, but not vel f.P = np.array([[1.,0., 0.], # covariance dim_x dim_x, i.e. 3 x 3 [0.,1., 0.], [0.,0., 1.]]) f.R = np.array([[1.,0.], # measurement noise dim_z dim_z, i.e 2 x 2 [0.,1.]])
    f.B = 0 # no control inputs f.Q = Q_discrete_white_noise(dim=3, dt=1, var=0.5)

    my measurements are stored in a .csv file as follows: pos1, acc1, pos 2, acc2, etc

    it actually runs for one cycle, then gives a dimensional error. the first estimate is quite incorrect Thanks for any guidance

    opened by PaulStafford1 16
  • conda install issue

    conda install issue

    I am on a Mac version 10.11.6 . This is the output of running your conda command:

    Phil@MacBook-Pro~/anaconda/envs $ conda install -c rabbi filterpy
    Fetching package metadata: ......
    Solving package specifications: .
    Error:  Package missing in current osx-64 channels: 
      - filterpy
    You can search for this package on with
        anaconda search -t condo filterpy
    opened by pjvalla 14
  • Bug in LeastSquaresFilter.update (

    Bug in LeastSquaresFilter.update (

    It looks like something is wrong with the code below. self.n should not be incremented 'cos for relatively large amount of data (more than several thousand elements) there is a tendency for increasing divergence between source data and filter's output.

         def update(self, z):
             """ Update filter with new measurement `z` """
             self.n += 1
    opened by Prokhozhijj 10
  • MerweScaledSigmaPoints weights do not sum to 1, documentation says it should

    MerweScaledSigmaPoints weights do not sum to 1, documentation says it should

    For example:

    import numpy as np
    from filterpy.kalman import MerweScaledSigmaPoints as SigmaPoints
    sigma_points = SigmaPoints(n=9, alpha=0.001, beta=2, kappa=-6)
    Wm, Wc = sigma_points.weights()
    print np.sum(Wm)
    print np.sum(Wc)

    Which returns


    While Wm is small enough to be rounding error, Wc seems to go against notes in the documentation. Now, I'm not saying MerweScaledSigmaPoints is set wrong -- as far as I can tell all the equations are right. However, the book and documentation both say that Wc "must sum to 1".

    So what's the deal?

    opened by peter-moran 9
  • KF and UKF smoother give different result on linear problem

    KF and UKF smoother give different result on linear problem


    I am using the UKF to estimate a series of shocks in some time series data using a nonlinear model with a large state space. To become familiar with the tool, I was playing around with a small linear state model with an exogenous AR(1) shock where the state of the AR(1) process is unknown to the observer. For testing I set the observation cov to near-zero. While both filters and the KF-smother gave correct estimates of both the system state and the hidden AR(1) state, the UKF-smoother is only relatively close.

    Is this a bug or did I do something wrong?

    I uploaded a stylized testing file here:

    Thanks for the great work!

    opened by gboehl 8
  • difficulty generalizing examples

    difficulty generalizing examples

    I'm really loving your book and library 👍

    I just wanted to comment that I'm having some trouble making the jump from the examples given in the book to applying tools from the filterpy library. Specifically, I've been reading the chapter on adaptive filtering and tracking, and I'm finding that it's not always easy for me to follow what's going on in the examples. There is a lot of copy/pasted code and functions that are either redefined a lot or not used from one cell to the next... then, suddenly they're used again.

    Don't get me wrong, I'm learning a lot from this chapter! But I tried lifting in my own data by adapting the generate_data function to spit out data formatted in the exact same way as the sample data, and it just didn't work out very well. The initialize_filter function makes the assumption that the first data point is going to be 0, which wasn't the case for my data, and my data was a time series, which is technically two dimensional, but it didn't fit well with the way that the filters are being applied.

    I think the main thing is that at the moment is that the book is the best documentation for some of the more adaptive filtering tools in the filterpy library, and it'd be nice to have some more generic working examples for how to use the IMM and MMAE tools.

    Thanks a lot for doing this... It's really helpful!

    opened by micahscopes 6
  • Problem while implementing Kalman Filter

    Problem while implementing Kalman Filter

    Hi, I have created a dictionary of Kalman Filters. I'm having an issue in the update function. AssertionError: shape of z should be (), but it is (1,) I have a 1D Kalman Filter, here it is the declaration.

    K = KalmanFilter (dim_x=1, dim_z=1)
    #State space model used
    K.F= np.array([1.])
     #Initial State
    #Measurement Matrix                         
    #Covariance Matrix
    #Process Noise          
    #Measurement Noise
    #Add KF to the dictionary when a new UUID is detected

    Hope you can help me, thanks.

    opened by aeyuxi 6
  • Using UKF for sensor fusion

    Using UKF for sensor fusion


    I'd like to use filterpy's UKF for sensor fusion. However I have two different measurement sources with different sizes, how can I setup the filter to make this work?

    Thanks, Carlos

    opened by cmassera 6
  • Installation issue

    Installation issue

    git clone cd filterpy sudo python install (same with python3)

    Traceback (most recent call last): File "", line 4, in import filterpy ImportError: No module named filterpy

    opened by ghost 6
  • Enhancement - check all matrices and sample y input in KalmanFilter.test_matrix_dimensions()

    Enhancement - check all matrices and sample y input in KalmanFilter.test_matrix_dimensions()

    Currently it looks like test_matrix_dimensions only checks x, P, and Q. The docs indicate it checks the size of everything, which is misleading since it doesn't check F, H, R, or a sample input. I would prefer it to check all of those in such a way that the state of the filter is not altered. Running down mismatched sizes is one of my least favorite things to debug and it could be streamlined.

    Said slightly differently, in order to fully check the size of inputs, you need to run it, but in order to run it you need to have (mostly) correct inputs, which results in some awkward circular logic.

    I think the signature could be test_matrix_dimensions(sample_input=None), where if sample_input is supplied it is additionally checked. That would not change the previous api.

    Thank you

    opened by mattharrigan 5
  • Example: Quaternion in UKF

    Example: Quaternion in UKF

    Does anyone have an example of using a gyroscope (or other rotation sensor) to drive the estimation of a quaternion in the state? I understand that a quaternion has issues with the covariance due to the overparameterization of 3 dimensions in 4 values. Also that we cannot simply add quaternions for averaging.

    Any example of a quaternion with filterpy (UKF) would be great. Thanks.

    opened by DylanWhite2 0
  • Release latest changes?

    Release latest changes?


    Hi! It seems the last release of Filterpy was 4 years ago. There are many changes after that including bug fixes. Is there any plan to release them?

    opened by sjiang17 0
  • Bug in Cubature Kalman Filter : residual_x not used

    Bug in Cubature Kalman Filter : residual_x not used


    It seems that there is an bug in the Cubature Kalman Filter : the constructor's argument residual_x is not used, and must be used here :

    opened by veylonni 0
  • Fix process noise handling in UKF

    Fix process noise handling in UKF

    Two minor changes to UnscentedKalmanFilter:

    1. Allow passing Q to predict step, for consistency with R in update step. It's also pretty much required if you have uneven dt.
    2. Fix a bug in the RTS smoother where passed-in Qs were not used at all.
    opened by ashtuchkin 0
  • Error in RTS equations

    Error in RTS equations

    Thanks for the useful repository.

    It seems there is an error in the RTS smoother equations which causes errors for systems with varying state transition matrices (i.e. EKF).

    Replacing it with the formulation using a-priori state and covariance estimates produces the correct solution. I.e., minimal example:

    def rts_smoother(x_s, P_s, x_prs, P_prs, F_s):                                                                                                                                                                                                                                                                                                     
        x_rts = [None]*n                                                                                                                                                                                                         
        P_rts = [None]*n                                                                                                                                                                                                         
        x_rts[-1] = x_s[-1]                                                                                                                                                                                                       
        P_rts[-1] = P_s[-1]                                                                                                                                                                                                       
        for k in range(n-2, -1, -1):                                                                                                                                                                                                                                                                                                                                                                                                                         
            C = P_s[k]@(F_s[k+1].T)@np.linalg.inv(P_prs[k+1])                                                                                                                                                                      
            x_rts[k] = x_s[k] + C@(x_rts[k+1] - x_prs[k+1])                                                                                                                                                                       
            P_rts[k] = P_s[k] + C@(P_rts[k+1] - P_prs[k+1])@(C.T)                                                                                                                                                                                                                                                                                                                                                                                                return x_rts, P_rts    

    where for an EKF the state transition $F_k( \hat{x}_{k/k-1})$ is calculated for timestep $k$ using the a-priori state estimate of that timestep. This produces the expected RTS smoothing result for me.

    Source: Wikipedia

    opened by andrewjlock 0
  • 0.0.15(Jan 31, 2015)

    A bunch of small changes and bug fixes. Documentation improvements.

    Note: Dumbness with git caused me to blow away all of my tags. I had a tag for each release, but did not realize pushing the project did not push the tags. A bit of hard drive stupidity, and poof. So, no good history for past releases.

    These tag numbers correspond to the version number of the project on pypi. If you do pip install filterpy you will (as of now) get version 0.0.15 - this tag.

    Source code(tar.gz)
    Source code(zip)
Roger Labbe
Roger Labbe
Additional tools for particle accelerator data analysis and machine information

PyLHC Tools This package is a collection of useful scripts and tools for the Optics Measurements and Corrections group (OMC) at CERN. Documentation Au

PyLHC 3 Apr 13, 2022
Performance analysis of predictive (alpha) stock factors

Alphalens Alphalens is a Python Library for performance analysis of predictive (alpha) stock factors. Alphalens works great with the Zipline open sour

Quantopian, Inc. 2.5k Jan 9, 2023
Python beta calculator that retrieves stock and market data and provides linear regressions.

Stock and Index Beta Calculator Python script that calculates the beta (β) of a stock against the chosen index. The script retrieves the data and resa

sammuhrai 4 Jul 29, 2022
Python Library for learning (Structure and Parameter) and inference (Statistical and Causal) in Bayesian Networks.

pgmpy pgmpy is a python library for working with Probabilistic Graphical Models. Documentation and list of algorithms supported is at our official sit

pgmpy 2.2k Dec 25, 2022
A probabilistic programming library for Bayesian deep learning, generative models, based on Tensorflow

ZhuSuan is a Python probabilistic programming library for Bayesian deep learning, which conjoins the complimentary advantages of Bayesian methods and

Tsinghua Machine Learning Group 2.2k Dec 28, 2022
Analyse the limit order book in seconds. Zoom to tick level or get yourself an overview of the trading day.

Analyse the limit order book in seconds. Zoom to tick level or get yourself an overview of the trading day. Correlate the market activity with the Apple Keynote presentations.

null 2 Jan 4, 2022
Probabilistic Programming in Python: Bayesian Modeling and Probabilistic Machine Learning with Theano

PyMC3 is a Python package for Bayesian statistical modeling and Probabilistic Machine Learning focusing on advanced Markov chain Monte Carlo (MCMC) an

PyMC 7.2k Dec 30, 2022
A Python package for Bayesian forecasting with object-oriented design and probabilistic models under the hood.

Disclaimer This project is stable and being incubated for long-term support. It may contain new experimental code, for which APIs are subject to chang

Uber Open Source 1.6k Dec 29, 2022
BAyesian Model-Building Interface (Bambi) in Python.

Bambi BAyesian Model-Building Interface in Python Overview Bambi is a high-level Bayesian model-building interface written in Python. It's built on to

null 861 Dec 29, 2022
pyhsmm MITpyhsmm - Bayesian inference in HSMMs and HMMs. MIT

Bayesian inference in HSMMs and HMMs This is a Python library for approximate unsupervised inference in Bayesian Hidden Markov Models (HMMs) and expli

Matthew Johnson 527 Dec 4, 2022
Statistical Rethinking: A Bayesian Course Using CmdStanPy and Plotnine

Statistical Rethinking: A Bayesian Course Using CmdStanPy and Plotnine Intro This repo contains the python/stan version of the Statistical Rethinking

Andrés Suárez 3 Nov 8, 2022
Using approximate bayesian posteriors in deep nets for active learning

Bayesian Active Learning (BaaL) BaaL is an active learning library developed at ElementAI. This repository contains techniques and reusable components

ElementAI 687 Dec 25, 2022
PostQF is a user-friendly Postfix queue data filter which operates on data produced by postqueue -j.

PostQF Copyright © 2022 Ralph Seichter PostQF is a user-friendly Postfix queue data filter which operates on data produced by postqueue -j. See the ma

Ralph Seichter 11 Nov 24, 2022
Pandas-based utility to calculate weighted means, medians, distributions, standard deviations, and more.

weightedcalcs weightedcalcs is a pandas-based Python library for calculating weighted means, medians, standard deviations, and more. Features Plays we

Jeremy Singer-Vine 98 Dec 31, 2022
Used for data processing in machine learning, and help us to construct ML model more easily from scratch

Used for data processing in machine learning, and help us to construct ML model more easily from scratch. Can be used in linear model, logistic regression model, and decision tree.

ShawnWang 0 Jul 5, 2022
Larch: Applications and Python Library for Data Analysis of X-ray Absorption Spectroscopy (XAS, XANES, XAFS, EXAFS), X-ray Fluorescence (XRF) Spectroscopy and Imaging

Larch: Data Analysis Tools for X-ray Spectroscopy and More Documentation: Code: L

xraypy 95 Dec 13, 2022
Sensitivity Analysis Library in Python (Numpy). Contains Sobol, Morris, Fractional Factorial and FAST methods.

Sensitivity Analysis Library (SALib) Python implementations of commonly used sensitivity analysis methods. Useful in systems modeling to calculate the

SALib 663 Jan 5, 2023
CleanX is an open source python library for exploring, cleaning and augmenting large datasets of X-rays, or certain other types of radiological images.

cleanX CleanX is an open source python library for exploring, cleaning and augmenting large datasets of X-rays, or certain other types of radiological

Candace Makeda Moore, MD 20 Jan 5, 2023
yt is an open-source, permissively-licensed Python library for analyzing and visualizing volumetric data.

The yt Project yt is an open-source, permissively-licensed Python library for analyzing and visualizing volumetric data. yt supports structured, varia

The yt project 367 Dec 25, 2022