rlabbe / filterpy

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'.
MIT License
3.23k stars 614 forks source link

KF with missing measurements #205

Closed kvnsng closed 4 years ago

kvnsng commented 4 years ago

Hi, thanks for making this great package available. I have a quick question.

I tried looking through the issues but had a hard time finding how to deal with missing measurements. Just wondering if anyone could point me towards a way to use filterpy KF on a dataset with missing measurements. Thanks!

nourani commented 4 years ago

Hi Kevin, What is exactly the issue? What do you mean when you say you have missing measurements? What kind of measurements do you have? How are they sampled / how frequently do you read them? Are all missing or just some missing (at times)? Some more information can help me. Cheers

kvnsng commented 4 years ago

Hi, thanks for responding. I have a series of x,y coordinates of a moving object and at certain times, I have missing measurements. I found in the documentation that we can insert None for missing measurements, but not sure how I need to structure the data now.

here's my function for running Kalman Filter and smoothing:

def kalman_filter_smooth(data, r_noise=5.):
    cols = data.shape[1]
    f1 = KalmanFilter(dim_x=cols*2, dim_z=cols)
    f2 = KalmanFilter(dim_x=cols*2, dim_z=cols)

    initData = []
    for i in range(data.shape[1]):
        initData.append(data[0,i])
        initData.append(data[1,i]-data[0,i])
    f1.x=np.array(initData)

    # for matrix H
    Hmat = np.zeros((cols, cols*2))
    for r in range(Hmat.shape[0]):
        c = r*2
        Hmat[r,c] = 1.

    # for matrix F
    Fmat = np.eye(cols*2)
    for r in range(Fmat.shape[1]):
        if r % 2 == 0:
            Fmat[r,r+1] = 1
    f1.F = Fmat
    f1.H = Hmat
    f1.P *= 50.
    f1.R *= r_noise

    xs0,ps0,_,_ = f1.batch_filter(data)
    xs1, ps1, ks, _  = f1.rts_smoother(xs0, ps0)

I feed in a data with (n,2) shape. If I have missing measurements at certain times, do I need to insert a row with [None, None]?

kvnsng commented 4 years ago

I figured it out. Just realized you have to put in None instead of [None, None].

RoyLarson commented 4 years ago

Is there a way to have just some of the measurements missing per update?

Say I am tracking something where I get a position from one set of instruments and a velocity from another
set of instruments, with different update frequencies. So my measurement timeseries might look like

t z_pos z_vel
0 1 1
1 2 None
2 4 None
3 6 1.5

All of the KF matrices would be standard for a 1-d kinematic problem

Is there something that automatically takes care of the Nones or do I have to make something that makes an H matrix for each situation?

Thanks

Thanks