Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
96129 views
�
�g�Uc@`s�dZddlmZmZmZmZddlmZddlm	Z	ddl
Zddl
mZm
Z
mZmZmZddlmZmZdefd	��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_literals(tdot3(tunscented_transformN(teyetzerostdottisscalartouter(tinvtcholeskytUnscentedKalmanFiltercB`skeZdZdddddd�Zdddd�Zdddd�Zdddd�Zddd�ZRS(	u� Implements the Scaled Unscented Kalman filter (UKF) as defined by
    Simon Julier in [1], using the formulation provided by Wan and Merle
    in [2]. This filter scales the sigma points to avoid strong nonlinearities.


    You will have to set the following attributes after constructing this
    object for the filter to perform properly.

    **Attributes**

    x : numpy.array(dim_x)
        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


    You may read the following attributes.

    **Readable Attributes**

    xp : numpy.array(dim_x)
        predicted state (result of predict())

    Pp : numpy.array(dim_x, dim_x)
        predicted covariance matrix (result of predict())


    **References**

    .. [1] Julier, Simon J. "The scaled unscented transformation,"
        American Control Converence, 2002, pp 4555-4559, vol 6.

        Online copy:
        https://www.cs.unc.edu/~welch/kalman/media/pdf/ACC02-IEEE1357.PDF


    .. [2] E. A. Wan and R. Van der Merwe, “The unscented Kalman filter for
        nonlinear estimation,” in Proc. Symp. Adaptive Syst. Signal
        Process., Commun. Contr., Lake Louise, AB, Canada, Oct. 2000.

        Online Copy:
        https://www.seas.harvard.edu/courses/cs281/papers/unscented.pdf
    cC`s[t|�|_t|�|_t|�|_t|�|_||_||_||_d|d|_	||_
||_||_||_
|	|_|dkr�t|_n	||_|jj�\|_|_|
dkr�tj|_n	|
|_|dkrtj|_n	||_td|jd|jf�|_t|j	|jf�|_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 filter. For example, if
            you are tracking the position and velocity of an object in two
            dimensions, dim_x would be 4.


        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.

        dt : float
            Time between steps in seconds.

        hx : function(x)
            Measurement function. Converts state vector x into a measurement
            vector of shape (dim_z).

        fx : function(x,dt)
            function that returns the state x transformed by the
            state transistion function. dt is the time step in seconds.

        points : class
            Class which computes the sigma points and weights for a UKF
            algorithm. You can vary the UKF implementation by changing this
            class. For example, MerweScaledSigmaPoints implements the alpha,
            beta, kappa parameterization of Van der Merwe, and
            JulierSigmaPoints implements Julier's original kappa
            parameterization. See either of those for the required
            signature of this class if you want to implement your own.

        sqrt_fn : callable(ndarray), default = scipy.linalg.cholesky
            Defines how we compute the square root of a matrix, which has
            no unique answer. Cholesky is the default choice due to its
            speed. Typically your alternative choice will be
            scipy.linalg.sqrtm. Different choices affect how the sigma points
            are arranged relative to the eigenvectors of the covariance matrix.
            Usually this will not matter to you; if so the default cholesky()
            yields maximal performance. As of van der Merwe's dissertation of
            2004 [6] this was not a well reseached area so I have no advice
            to give you.

            If your method returns a triangular matrix it must be upper
            triangular. Do not use numpy.linalg.cholesky - for historical
            reasons it returns a lower triangular matrix. The SciPy version
            does the right thing.

        x_mean_fn : callable  (sigma_points, weights), optional
            Function that computes the mean of the provided sigma points
            and weights. Use this if your state variable contains nonlinear
            values such as angles which cannot be summed.

            .. code-block:: Python

                def state_mean(sigmas, Wm):
                    x = np.zeros(3)
                    sum_sin, sum_cos = 0., 0.

                    for i in range(len(sigmas)):
                        s = sigmas[i]
                        x[0] += s[0] * Wm[i]
                        x[1] += s[1] * Wm[i]
                        sum_sin += sin(s[2])*Wm[i]
                        sum_cos += cos(s[2])*Wm[i]
                    x[2] = atan2(sum_sin, sum_cos)
                    return x

        z_mean_fn : callable  (sigma_points, weights), optional
            Same as x_mean_fn, except it is called for sigma points which
            form the measurements after being passed through hx().

        residual_x : callable (x, y), optional
        residual_z : callable (x, y), optional
            Function that computes the residual (difference) between x and y.
            You will have to supply this if your state variable cannot support
            subtraction, such as angles (359-1 degreees is 2, not 358). x and y
            are state vectors, not scalars. One is for the state variable,
            the other is for the measurement state.

            .. code-block:: Python

                def residual(a, b):
                    y = a[0] - b[0]
                    if y > np.pi:
                        y -= 2*np.pi
                    if y < -np.pi:
                        y = 2*np.pi
                    return y

        **References**

        .. [3] S. Julier, J. Uhlmann, and H. Durrant-Whyte. "A new method for
               the nonlinear transformation of means and covariances in filters
               and estimators," IEEE Transactions on Automatic Control, 45(3),
               pp. 477-482 (March 2000).

        .. [4] E. A. Wan and R. Van der Merwe, “The Unscented Kalman filter for
               Nonlinear Estimation,” in Proc. Symp. Adaptive Syst. Signal
               Process., Commun. Contr., Lake Louise, AB, Canada, Oct. 2000.

               https://www.seas.harvard.edu/courses/cs281/papers/unscented.pdf

        .. [5] Wan, Merle "The Unscented Kalman Filter," chapter in *Kalman
               Filtering and Neural Networks*, John Wiley & Sons, Inc., 2001.

        .. [6] R. Van der Merwe "Sigma-Point Kalman Filters for Probabilitic
               Inference in Dynamic State-Space Models" (Doctoral dissertation)
        iiN(RtQtRRtxtPt_dim_xt_dim_zt_dtt_num_sigmasthxtfxt	points_fntx_meantz_meantNoneRtmsqrttweightstWmtWctnptsubtractt
residual_xt
residual_ztsigmas_ftsigmas_h(tselftdim_xtdim_ztdtRRtpointstsqrt_fnt	x_mean_fnt	z_mean_fnR"R#((s./filterpy/kalman/UKF.pyt__init__Qs2v											#cC`s�|dkr|j}nt|t�s3|f}n|dkrHt}n|jj|j|j�}x7t	|j
�D]&}|j||||�|j|<qsW||j|j
|j|j|j|j�\|_|_dS(u} Performs the predict step of the UKF. On return, self.x and
        self.P contain the predicted state (x) and covariance (P). '

        Important: this MUST be called before update() is called for the first
        time.

        **Parameters**

        dt : double, optional
            If specified, the time step to be used for this prediction.
            self._dt is used if this is not provided.

        UT : function(sigmas, Wm, Wc, noise_cov), optional
            Optional function to compute the unscented transform for the sigma
            points passed through hx. Typically the default function will
            work - you can use x_mean_fn and z_mean_fn to alter the behavior
            of the unscented transform.

        fx_args : tuple, optional, default (,)
            optional arguments to be passed into fx() after the required state
            variable.

        N(RRt
isinstancettupleRRtsigma_pointsRRtrangeRRR$RRRRR"(R&R)tUTtfx_argstsigmasti((s./filterpy/kalman/UKF.pytpredict�s	$c
C`s�|dkrdSt|t�s+|f}n|dkr@t}n|dkrX|j}n"t|�rzt|j�|}nx7t|j	�D]&}|j
|j||�|j|<q�W||j|j
|j||j|j�\}}t|j|jf�}xjt|j	�D]Y}|j|j||j�}	|j|j||�}
||j|t|	|
�7}qWt|t|��}|j||�}|jt||�|_|jt|||j�|_dS(u� Update the UKF with the given measurements. On return,
        self.x and self.P contain the new mean and covariance of the filter.

        **Parameters**

        z : numpy.array of shape (dim_z)
            measurement vector

        R : numpy.array((dim_z, dim_z)), optional
            Measurement noise. If provided, overrides self.R for
            this function call.

        UT : function(sigmas, Wm, Wc, noise_cov), optional
            Optional function to compute the unscented transform for the sigma
            points passed through hx. Typically the default function will
            work - you can use x_mean_fn and z_mean_fn to alter the behavior
            of the unscented transform.

        hx_args : tuple, optional, default (,)
            arguments to be passed into Hx function after the required state
            variable.

        residual_x : function (x, x2), optional
            Optional function that computes the residual (difference) between
            the two state vectors. If you do not provide this, then the
            built in minus operator will be used. You will normally want to use
            the built in unless your residual computation is nonlinear (for
            example, if they are angles)

        residual_h : function (z, z2), optional
            Optional function that computes the residual (difference) between
            the two measurement vectors. If you do not provide this, then the
            built in minus operator will be used.
        N(RR/R0RRR	RRR2RRR$R%RRRR#RRR"RR
RRRRtT(
R&tzRR3thx_argsR6tzptPztPxztdxtdztKty((s./filterpy/kalman/UKF.pytupdates,$	$0"cC`s�y|d}Wn t|�s1td��nX|jdkr|t|�s�|jdkrmt|�dks�td��n-t|�|jks�tdj|j���|dkr�tj}ntj	|d�}|dkr�dg|}n|j
jdkrt||jf�}nt||jdf�}t||j|jf�}x~t
t||��D]g\}	\}}
|j�|j||
�|j
||	dd�f<|j||	dd�dd�f<qbW||fS(uc Performs the UKF filter over the list of measurement in `zs`.


        **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.

        residual : function (z, z2), optional
            Optional function that computes the residual (difference) between
            the two measurement vectors. If you do not provide this, then the
            built in minus operator will be used. You will normally want to use
            the built in unless your residual computation is nonlinear (for
            example, if they are angles)

        UT : function(sigmas, Wm, Wc, noise_cov), optional
            Optional function to compute the unscented transform for the sigma
            points passed through hx. Typically the default function will
            work - you can use x_mean_fn and z_mean_fn to alter the behavior
            of the unscented transform.

        **Returns**

        means: ndarray((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: ndarray((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`.

        iuzs must be list-likeiu4zs must be a list of scalars or 1D, 1 element arraysu1each element in zs must be a1D array of length {}N(R	tAssertionErrorRtndimtlentformatRR R!tsizeRRRt	enumeratetzipR7RBR(R&tzstRstresidualR3R9tz_ntmeanstcovariancesR6tr((s./filterpy/kalman/UKF.pytbatch_filter^s0)0(
&c	C`s�t|�t|�kst�|j\}}|dkrL|jg|}nt|�rh|g|}n|dkr�|jg|}nt|||f�}d|d}|j�|j�}	}
t||f�}x�t	|ddd�D]�}|j
j|	||
|�}
x2t	|�D]$}|j|
|||�||<qWt
|j|�}d}||}x@t	|�D]2}|||}||j|t||�7}qsW|||7}d}xRt	|�D]D}|
|||}|||}||j|t||�7}q�Wt
|t|��}|	|ct
||	|d|�7<|
|ct||
|d||j�7<|||<q�W|	|
|fS(uU Runs the Rauch-Tung-Striebal Kalman smoother on a set of
        means and covariances computed by the UKF. The usual input
        would come from the output of `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.

        Qs: 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

        dt : optional, float or array-like of float
            If provided, specifies the time step of each step of the filter.
            If float, then the same time step is used for all steps. If
            an array, then each element k contains the time  at step k.
            Units are seconds.

        **Returns**

        x : numpy.ndarray
           smoothed means

        P : numpy.ndarray
           smoothed state covariances

        K : numpy.ndarray
            smoother gain at each step


        **Example**

        .. code-block:: Python

            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)

        iii����iN(RERCtshapeRRR	RRtcopyR2RR1RRRR
RRR8(R&tXstPstQsR)tnR'tKst
num_sigmastxstpsR$tkR5R6txbtPbRRAtPxbR9R@((s./filterpy/kalman/UKF.pytrts_smoother�sB."
""%+N(((	t__name__t
__module__t__doc__RR.R7RBRQR`(((s./filterpy/kalman/UKF.pyR
s4	�+EP(Rct
__future__RRRRtfilterpy.commonRtfilterpy.kalmanRtnumpyR RRRR	R
tscipy.linalgRRtobjectR
(((s./filterpy/kalman/UKF.pyt<module>s"(