Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
96129 views
�
�g�Uc@`s�dZddlmZmZmZmZddlZddlj	Z	ddlm
Z
mZmZm
Z
ddlmZmZmZmZdefd��YZdS(u4Copyright 2015 Roger R Labbe Jr.

FilterPy library.
http://github.com/rlabbe/filterpy

Documentation at:
https://filterpy.readthedocs.org

Supporting book at:
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python

This is licensed under an MIT license. See the readme.MD file
for more information.
i(tabsolute_importtdivisiontprint_functiontunicode_literalsN(tdottzerosteyetisscalar(tsettert	setter_1dt
setter_scalartdot3tKalmanFiltercB`sjeZdZdd�Zddd�Zd�Zdd�Zded�Z	dd�Z
dd�Zd	�Zd
�Z
ed��Zejd��Zed
��Zejd��Zed��Zejd��Zed��Zejd��Zed��Zejd��Zed��Zejd��Zed��Zed��Zed��ZRS(ui Implements a Kalman filter. You are responsible for setting the
    various state variables to reasonable values; the defaults  will
    not give you a functional filter.

    You will have to set the following attributes after constructing this
    object for the filter to perform properly. Please note that there are
    various checks in place to ensure that you have made everything the
    'correct' size. However, it is possible to provide incorrectly sized
    arrays such that the linear algebra can not perform an operation.
    It can also fail silently - you can end up with matrices of a size that
    allows the linear algebra to work, but are the wrong shape for the problem
    you are trying to solve.

    **Attributes**

    x : numpy.array(dim_x, 1)
        state estimate vector

    P : numpy.array(dim_x, dim_x)
        covariance estimate matrix

    R : numpy.array(dim_z, dim_z)
        measurement noise matrix

    Q : numpy.array(dim_x, dim_x)
        process noise matrix

    F : numpy.array()
        State Transition matrix

    H : numpy.array(dim_x, dim_x)


    You may read the following attributes.

    **Readable Attributes**

    y : numpy.array
        Residual of the update step.

    K : numpy.array(dim_x, dim_z)
        Kalman gain of the update step

    S :  numpy.array
        Systen uncertaintly projected to measurement space

    icC`s�|dkst�|dks$t�|dks6t�||_||_||_t|df�|_t|�|_t|�|_d|_	d|_
d|_t|�|_d|_
d|_t|df�|_d|_tj|�|_dS(u" Create a Kalman filter. You are responsible for setting the
        various state variables to reasonable values; the defaults below will
        not give you a functional filter.

        **Parameters**

        dim_x : int
            Number of state variables for the Kalman filter. For example, if
            you are tracking the position and velocity of an object in two
            dimensions, dim_x would be 4.

            This is used to set the default size of P, Q, and u

        dim_z : int
            Number of of measurement inputs. For example, if the sensor
            provides you with position in (x,y), dim_z would be 2.

        dim_u : int (optional)
            size of the control input, if it is being used.
            Default value of 0 indicates it is not used.
        iig�?N(tAssertionErrortdim_xtdim_ztdim_uRt_xRt_Pt_Qt_Bt_FtHtRt	_alpha_sqt_Kt_yt_Stnpt_I(tselfRRR((s"./filterpy/kalman/kalman_filter.pyt__init__Ns$									c	C`s1|dkrdS|dkr(|j}n"t|�rJt|j�|}n|dkrb|j}n|j}|j}|t||�|_	t
|||j�|}t
||jtj
|��}|t||j	�|_|jt||�}t
|||j�t
|||j�|_||_||_dS(uk
        Add a new measurement (z) to the kalman filter. If z is None, nothing
        is changed.

        **Parameters**

        z : np.array
            measurement for this update.

        R : np.array, scalar, or None
            Optionally provide R to override the measurement noise for this
            one call, otherwise  self.R will be used.
        N(tNoneRRRRRRRRRRtTtlinalgtinvRRR(	RtzRRtPtxtStKtI_KH((s"./filterpy/kalman/kalman_filter.pytupdate�s$		+	cC`s�|jj|jdfks?tdj|jd|jj���|jj|j|jfks�tdj|j|j|jj���|jj|j|jfks�tdj|j|j|jj���dS(u Performs a series of asserts to check that the size of everything
        is what it should be. This can help you debug problems in your design.

        This is only a test; you do not need to use it while filtering.
        However, to use you will want to perform at least one predict() and
        one update() before calling; some bad designs will cause the shapes
        of x and P to change in a silent and bad way. For example, if you
        pass in a badly dimensioned z into update that can cause x to be
        misshapen.iu%Shape of x must be ({},{}), but is {}u%Shape of P must be ({},{}), but is {}N(RtshapeRR
tformatRR(R((s"./filterpy/kalman/kalman_filter.pyttest_matrix_dimensions�s!!cC`s[t|j|j�t|j|�|_|jt|j|j|jj�|j	|_dS(u� Predict next position.

        **Parameters**

        u : np.array
            Optional control vector. If non-zero, it is multiplied by B
            to create the control input into the system.
        N(
RRR&RRRRRR!R(Rtu((s"./filterpy/kalman/kalman_filter.pytpredict�s(cC`sy|d}Wn t|�s1td��nX|jdkr|t|�s�|jdkrmt|�dks�td��n1t|�|jks�td��dj|j�tj|d�}|dkr�dg|}n|j	jdkrt
||jf�}t
||jf�}n0t
||jdf�}t
||jdf�}t
||j|jf�}t
||j|jf�}	|rExxtt
||��D]�\}
\}}|j||�|j||
dd�f<|j||
dd�dd�f<|j�|j||
dd�f<|j|	|
dd�dd�f<q�Wn�x�tt
||��D]�\}
\}}|j�|j||
dd�f<|j|	|
dd�dd�f<|j||�|j||
dd�f<|j||
dd�dd�f<q[W||||	fS(u� Batch processes a sequences of measurements.

        **Parameters**

        zs : list-like
            list of measurements at each time step `self.dt` Missing
            measurements must be represented by 'None'.

        Rs : list-like, optional
            optional list of values to use for the measurement error
            covariance; a value of None in any position will cause the filter
            to use `self.R` for that time step.

        update_first : bool, optional,
            controls whether the order of operations is update followed by
            predict, or predict followed by update. Default is predict->update.

        **Returns**


        means: np.array((n,dim_x,1))
            array of the state for each time step after the update. Each entry
            is an np.array. In other words `means[k,:]` is the state at step
            `k`.

        covariance: np.array((n,dim_x,dim_x))
            array of the covariances for each time step after the update.
            In other words `covariance[k,:,:]` is the covariance at step `k`.

        means_predictions: np.array((n,dim_x,1))
            array of the state for each time step after the predictions. Each
            entry is an np.array. In other words `means[k,:]` is the state at
            step `k`.

        covariance_predictions: np.array((n,dim_x,dim_x))
            array of the covariances for each time step after the prediction.
            In other words `covariance[k,:,:]` is the covariance at step `k`.
        iuzs must be list-likeiu4zs must be a list of scalars or 1D, 1 element arraysueach element in zs must be au1D array of length {}N(RR
RtndimtlenR,RtsizeR R&RRt	enumeratetzipR*RRR/(RtzstRstupdate_firstR$tntmeanstmeans_ptcovariancest
covariances_ptitr((s"./filterpy/kalman/kalman_filter.pytbatch_filter�sF(0!("
)(
"&c
C`sit|�t|�kst�|j}|d}|d}|j}|s]|jg|}nt|||f�}|j�|j�}	}
x�t|ddd�D]�}t||
||j	�||}t|
||j	t
j|��||<|	|ct|||	|dt||	|��7<|
|ct|||
|d|||j	�7<q�W|	|
|fS(u" Runs the Rauch-Tung-Striebal Kalman smoother on a set of
        means and covariances computed by a Kalman filter. The usual input
        would come from the output of `KalmanFilter.batch_filter()`.

        **Parameters**

        Xs : numpy.array
           array of the means (state variable x) of the output of a Kalman
           filter.

        Ps : numpy.array
            array of the covariances of the output of a kalman filter.

        Q : list-like collection of numpy.array, optional
            Process noise of the Kalman filter at each time step. Optional,
            if not provided the filter's self.Q will be used


        **Returns**

        'x' : numpy.ndarray
           smoothed means

        'P' : numpy.ndarray
           smoothed state covariances

        'K' : numpy.ndarray
            smoother gain at each step


        **Example**::

            zs = [t + random.randn()*4 for t in range (40)]

            (mu, cov, _, _) = kalman.batch_filter(zs)
            (x, P, K) = rts_smoother(mu, cov, fk.F, fk.Q)

        iiii����(
R1R
R+RtQRtcopytrangeRR!R"R#R(
RtXstPstQsR+R8RtFR(R&R%tktP_pred((s"./filterpy/kalman/kalman_filter.pytrts_smoother;s(	

	!&67cC`s[t|j|j�t|j|�}|jt|j|j|jj�|j}||fS(u& Predicts the next state of the filter and returns it. Does not
        alter the state of the filter.

        **Parameters**

        u : np.array
            optional control input

        **Returns**

        (x, P)
            State vector and covariance array of the prediction.
        (	RRRRRRRR!R(RR.R&R%((s"./filterpy/kalman/kalman_filter.pytget_prediction{s%,cC`s|t|j|j�S(um returns the residual for the given measurement (z). Does not alter
        the state of the filter.
        (RRR(RR$((s"./filterpy/kalman/kalman_filter.pytresidual_of�scC`st|j|�S(u� Helper function that converts a state into a measurement.

        **Parameters**

        x : np.array
            kalman state vector

        **Returns**

        z : np.array
            measurement corresponding to the given state
        (RR(RR&((s"./filterpy/kalman/kalman_filter.pytmeasurement_of_state�scC`s|jdS(u� Fading memory setting. 1.0 gives the normal Kalman filter, and
        values slightly larger than 1.0 (such as 1.02) give a fading
        memory effect - previous measurements have less influence on the
        filter's estimates. This formulation of the Fading memory filter
        (there are many) is due to Dan Simon [1].

        ** References **

        [1] Dan Simon. "Optimal State Estimation." John Wiley & Sons.
            p. 208-212. (2006)
        g�?(R(R((s"./filterpy/kalman/kalman_filter.pytalpha�scC`s8tj|�st�|dks't�|d|_dS(Nii(RRR
R(Rtvalue((s"./filterpy/kalman/kalman_filter.pyRM�scC`s|jS(u Process uncertainty(R(R((s"./filterpy/kalman/kalman_filter.pyR@�scC`st||j�|_dS(N(R
RR(RRN((s"./filterpy/kalman/kalman_filter.pyR@�scC`s|jS(u covariance matrix(R(R((s"./filterpy/kalman/kalman_filter.pyR%�scC`st||j�|_dS(N(R
RR(RRN((s"./filterpy/kalman/kalman_filter.pyR%�scC`s|jS(u state transition matrix(R(R((s"./filterpy/kalman/kalman_filter.pyRF�scC`st||j|j�|_dS(N(RRR(RRN((s"./filterpy/kalman/kalman_filter.pyRF�scC`s|jS(u control transition matrix(R(R((s"./filterpy/kalman/kalman_filter.pytB�scC`s:tj|�r||_nt||j|j�|_dS(u control transition matrixN(RRRRRR(RRN((s"./filterpy/kalman/kalman_filter.pyRO�scC`s|jS(u filter state vector.(R(R((s"./filterpy/kalman/kalman_filter.pyR&�scC`st||j�|_dS(N(R	RR(RRN((s"./filterpy/kalman/kalman_filter.pyR&�scC`s|jS(u
 Kalman gain (R(R((s"./filterpy/kalman/kalman_filter.pyR(�scC`s|jS(u# measurement residual (innovation) (R(R((s"./filterpy/kalman/kalman_filter.pyty�scC`s|jS(u) system uncertainty in measurement space (R(R((s"./filterpy/kalman/kalman_filter.pyR'sN(t__name__t
__module__t__doc__RR R*R-R/tFalseR?RIRJRKRLtpropertyRMRR@R%RFROR&R(RPR'(((s"./filterpy/kalman/kalman_filter.pyRs2/35	\@			(RSt
__future__RRRRtnumpyRtscipy.linalgR"RRRRtfilterpy.commonRR	R
RtobjectR(((s"./filterpy/kalman/kalman_filter.pyt<module>s"""