FilterPy Documentation

repository·master·Indexed 26 days ago

https://github.com/rlabbe/filterpy

A Python library providing Kalman filtering and various other optimal and non-optimal estimation filters, including Extended Kalman filters, Unscented Kalman filters, and Kalman smoothers. Designed to be pedagogical, the library includes modules for discrete Bayes filtering, H-infinity filters, g-h filters, and ensemble Kalman filters, as well as utilities for noise generation, discretization of continuous systems, and numerical integration.

Tokens
5.4K
Snippets
6
Records
57
Agent score
86%

What's inside FilterPy

  1. Use the FadingMemoryFilter for polynomial fading memory filtering

    master
    The FadingMemoryFilter implements a polynomial fading memory filter. While similar results can be achieved using the more general KalmanFilter class, this class provides a specific implementation of the fading memory filter often found in literature. It is intended for users who require this specific form of filtering or prefer its interface over the standard Kalman filter.
  2. Use filterpy.common utilities

    master
    The filterpy.common module provides a collection of helper functions used throughout the library and useful for building custom filters. It includes utilities for noise generation, discretization of continuous systems, numerical integration, and state transition modeling.
  3. Explore FilterPy modules

    master

    FilterPy is organized into several submodules based on the type of estimation filter or statistical method required:

    • filterpy.kalman: Implements various Kalman filters (Linear, Extended, Unscented, and Ensemble) and includes smoother methods like rts_smoother within the filter classes.
    • filterpy.common: Provides utility functions, such as computing the process noise matrix Q and Van Loan discretization of linear differential equations.
    • filterpy.stats: Contains statistical tools like multivariate Gaussian multiplication, log-likelihood computation, NESS, Mahalanobis distance, and plotting routines for Gaussians (CDFs, PDFs, and covariance ellipses).
    • filterpy.monte_carlo: Includes routines for Markov Chain Monte Carlo (MCMC) computation, primarily for particle filtering (e.g., resampling).
    • filterpy.discrete_bayes: Provides routines for discrete Bayes filtering.
    • filterpy.gh: Implements various g-h filters and helper functions for setting g and h parameters.
    • filterpy.memory: Implements a polynomial fading memory filter (FadingMemoryFilter).
    • filterpy.hinfinity: Implements H-infinity filters.
    • filterpy.leastsq: Implements least squares filters.
  4. Initialize and configure an ExtendedKalmanFilter

    master

    To use the ExtendedKalmanFilter, you must first instantiate it by specifying the dimensions of your state and measurement vectors.

    1. Initialization: Provide dim_x (size of the state vector) and dim_z (size of the measurement vector) to the constructor. These dimensions are used to perform size checks on matrices assigned later.
    2. Matrix Assignment: After construction, the filter contains default matrices. You should overwrite these matrices with your specific values using numpy.array objects. Common matrices include R (measurement noise matrix).
    3. Bypassing Size Checks: If you need to change the dimensions of a matrix mid-stream (which would normally trigger an assertion error), you can bypass the size checks by assigning directly to the underscore-prefixed version of the matrix (e.g., _R).
  5. Resample particles using filterpy.monte_carlo routines

    master

    The filterpy.monte_carlo module provides routines for resampling particles from particle filters based on their current weights.

    Important Note: These functions do not perform the actual resampling of the particle data. Instead, they take a list of normalized weights as input and return a list of indices representing which weights should be chosen. The caller is responsible for using these indices to select the actual particles from their original set.

  6. Install FilterPy from GitHub

    master

    If you want the latest development version (the master branch), you can install directly from GitHub. Note that the master branch may contain unreleased code.

    Use --depth=1 to perform a shallow clone to keep the repository size small.

    $ git clone --depth=1 https://github.com/rlabbe/filterpy.git
    $ cd filterpy
    $ python setup.py install
  7. Install FilterPy via pip

    master

    The recommended way to install FilterPy is using pip. This will install the stable version hosted on PyPI.

    To verify your installation, import the library in a Python REPL and check the version.

    $ pip install filterpy
    >>> import filterpy
    >>> filterpy.__version__
  8. Basic usage of FilterPy

    master

    To use FilterPy, import the specific classes or functions you need from the appropriate submodules. For example, to use a Kalman Filter, import KalmanFilter from filterpy.kalman and initialize it with the dimensions of your state (dim_x) and measurement (dim_z).

    from filterpy.kalman import KalmanFilter
    kf = KalmanFilter(dim_x=3, dim_z=1)
  9. Install FilterPy

    master

    You can install FilterPy using several methods depending on your environment:

    Using pip

    For most modern Python distributions:

    pip install filterpy

    To install the bleeding edge version directly from GitHub:

    pip install git+https://github.com/rlabbe/filterpy.git

    Using Anaconda

    Install from the conda-forge channel:

    conda config --add channels conda-forge
    conda install filterpy

    From Source

    Clone the repository and run the setup script:

    git clone http://github.com/rlabbe/filterpy
    cd filterpy
    python setup.py install
  10. Understand FilterPy's naming conventions

    master

    FilterPy uses mathematical notation for internal variable names to maintain readability with standard Kalman filter literature.

    Key mathematical symbols used in the library:

    • F: State transition matrix
    • G: Control input matrix
    • P: State covariance
    • R: Measurement noise covariance
    • H: Measurement function
    • K: Kalman gain

    Best Practices for Users:

    • Library/Math Code: It is acceptable to use mathematical symbols (e.g., KalmanFilter.P) to ensure the code reads like the underlying equations.
    • Calling/Application Code: When using the library in your own application, use descriptive names (e.g., sensor_noise or gps_sensor_noise) instead of single letters like R to improve clarity in your specific context.
  11. Use the deprecated Saver class to save Kalman filter states

    master

    The Saver class in filterpy.kalman is a helper designed to record the state of a KalmanFilter object at each epoch. When save() is called, all instance variables of the Kalman filter are stored in lists.

    Warning: This class is deprecated as of version 1.3.2 and will be deleted soon. Use filterpy.common.Saver instead, which is more versatile and works with any class.

    To use the deprecated Saver:

    1. Initialize it with your Kalman filter instance: saver = Saver(kf).
    2. Call saver.save() at the end of each prediction/update cycle.
    3. Use saver.to_array() to convert the collected states into NumPy arrays for analysis or plotting.
    saver = Saver(kf)
    for i in range(N):
        kf.predict()
        kf.update(zs[i])
        saver.save()
        
    saver.to_array() # convert all to np.array
    
    # plot the 0th element of kf.x over all epoches
    plot(saver.xs[:, 0])
  12. Use the MMAEFilterBank for multiple model estimation

    master

    The MMAEFilterBank (Multiple Model Adaptive Estimation) allows you to maintain a bank of different filters (e.g., Constant Velocity vs. Constant Acceleration) and estimate the probability of each model being correct based on incoming measurements.

    To use it:

    1. Initialize a list of filter instances.
    2. Define the initial probabilities for each model (must sum to 1).
    3. Define the measurement matrices H for each model.
    4. Iterate through measurements by calling .predict() and .update(z) on the bank object.
    5. Access the combined state or individual model properties via the bank instance.