pythonbayesiankalman-filterpykalmanpyro.ai

Kalman Filterin with changing known variance over time?


I have a simple Kalman model:

y_1_t = (1 + phi) * alpha_t + e_1_t 

y_2_t = (1 - phi) * alpha_t + e_2_t 

alpha_t+1 = alpha_t + s_t

Now I know the variances over time for e_1_t and e_2_t - they are not constant. Is there a python package that I could use to estimate this model?

The parameter phi is unknown. It would be great if the model could estimate if. If not it also could be provided since approximate estimations exists.

Thanks a lot for any hint.

PS: I also checked the liabrary pykalman. https://pykalman.github.io/#mathematical-formulation. It seems that here the variance is assumed to be constant over time.


Solution

  • If you need to change either the transition covariance (matrix Q) or the measurement covariance (matrix R) during the estimation you can still use the pykalman library you've mentioned in your question.

    Have a look at the function filter_update(). It is useful if you want to change some filter parameters (especially the covariance matrices) from one call to another.

    The function call looks like this:

    filter_update(filtered_state_mean, filtered_state_covariance, observation=None, transition_matrix=None, transition_offset=None, transition_covariance=None, observation_matrix=None, observation_offset=None, observation_covariance=None)

    to modify the covariance matrices you just need to put the customized values into transition_covariance and observation_covariance

    Have a look at my post here: Kalman filter with varying timesteps

    In this example I modified the observation covariance on the fly depending on the sensor the measurement came from:

        if Sensor[t] == 0:
            obs = None
            obs_cov = None
        else:
            obs = [X[t], Y[t]]
    
            if Sensor[t] == 1:
                obs_cov = np.asarray(R_1)
            else:
                obs_cov = np.asarray(R_2)
    
        filtered_state_means[t], filtered_state_covariances[t] = (
        kf.filter_update(
            filtered_state_means[t-1],
            filtered_state_covariances[t-1],
            observation = obs,
            observation_covariance = obs_cov)
        )
    

    For some reason one has to cast the observation covariance to np.asarray, otherwise the library does not work.