Documentation

econsieve.tenkf

class econsieve.tenkf.TEnKF(N, dim_x=None, dim_z=None, fx=None, hx=None, rule=None, seed=None)

Bases: object

batch_filter(Z, init_states=None, seed=None, store=False, calc_ll=False, verbose=False)

Batch filter.

Runs the TEnKF on the full dataset.

name = 'TEnKF'
npas(func=None, X=None, init_states=None, vals=None, covs=None, nsamples=False, bound_sigma=4, frtol=1e-05, seed=0, verbose=True, **cmaes_args)

Nonlinear Path-Adjustment Smoother.

Assumes that either X (a time series of ensembles) is given (or can be taken from the filter self object), or that the time series vals and covs are given. From the filter object, also Q (the covariance matrix of shocks) and the transition function t_func(state, shock_innovations) must be provided. …

Parameters:
  • X (array, optional) – a time series of ensembles. Either this, or vals and covs have to be provided
  • vals (array, optional) – the series of ensemble values, probably you want the means. Either this together with the covs, or X has to be provided
  • covs (array, optional) – the series of ensemble covariances. Either this together with vals, or X has to be provided
  • bound_sigma (int, optional) – the number of standard deviations included in the box constraint of the global optimizer
Returns:

  • X (array) – the smoothed vals
  • covs (array) – the covariances
  • res (array) – the smoothed/estimated exogenous innovations
  • flag (bool) – an error flag of the transition function

rts_smoother(means=None, covs=None, rcond=1e-14)
econsieve.tenkf.init_mv_normal(self, loc=[0, 0], scale=[[1, 0.5], [0.5, 1]])
econsieve.tenkf.multivariate_dispatch(rule)

econsieve.ukf

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

class econsieve.ukf.UnscentedKalmanFilter(dim_x, dim_z, hx, fx, points, instant_warning=False)

Bases: object

batch_filter(zs, Rs=None)

Performs the UKF filter over the list of measurement in zs.

compute_process_sigmas(fx=None, **fx_args)

computes the values of sigmas_f. Normally a user would not call this, but it is useful if you need to call update more than once between calls to predict (to update for multiple simultaneous measurements), so the sigmas correctly reflect the updated state x, P.

predict(fx=None, **fx_args)

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:
  • fx (callable f(x, **fx_args), optional) – State transition function. If not provided, the default function passed in during construction will be used.
  • **fx_args (keyword arguments) – optional keyword arguments to be passed into f(x).
rts_smoother(Xs, Ps, Qs=None)

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().

econsieve.ukf.cross_variance(Wc, x, z, sigmas_f, sigmas_h)

Compute cross variance of the state x and measurement z.

econsieve.ukf.unscented_transform(sigmas, Wm, Wc, noise_cov=0)

Computes unscented transform of a set of sigma points and weights.

econsieve.ukf.update(z, P, x, Wc, Wm, sigmas_f, sigmas_h)

Update the UKF with the given measurements. On return, x and P contain the new mean and covariance of the filter.

econsieve.stats

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

econsieve.stats.NESS(xs, est_xs, ps)

Computes the normalized estimated error squared test on a sequence of estimates. The estimates are optimal if the mean error is zero and the covariance matches the Kalman filter’s covariance. If this holds, then the mean of the NESS should be equal to or less than the dimension of x.

Examples

Parameters:
  • xs (list-like) – sequence of true values for the state x
  • est_xs (list-like) – sequence of estimates from an estimator (such as Kalman filter)
  • ps (list-like) – sequence of covariance matrices from the estimator
Returns:

ness – list of NESS computed for each estimate

Return type:

list of floats

econsieve.stats.add(mean1, var1, mean2, var2)

Add the Gaussians (mean1, var1) with (mean2, var2) and return the results as a tuple (mean,var).

var1 and var2 are variances - sigma squared in the usual parlance.

econsieve.stats.covariance_ellipse(P, deviations=1)

Returns a tuple defining the ellipse representing the 2 dimensional covariance matrix P.

Parameters:
  • P (nd.array shape (2,2)) – covariance matrix
  • deviations (int (optional, default = 1)) – # of standard deviations. Default is 1.
  • (angle_radians, width_radius, height_radius) (Returns) –
econsieve.stats.gaussian(x, mean, var, normed=True)

returns normal distribution (pdf) for x given a Gaussian with the specified mean and variance. All must be scalars.

gaussian (1,2,3) is equivalent to scipy.stats.norm(2,math.sqrt(3)).pdf(1) It is quite a bit faster albeit much less flexible than the latter.

Parameters:
  • x (scalar or array-like) – The value for which we compute the probability
  • mean (scalar) – Mean of the Gaussian
  • var (scalar) – Variance of the Gaussian
  • norm (bool, default True) – Normalize the output if the input is an array of values.
Returns:

probability – probability of x for the Gaussian (mean, var). E.g. 0.101 denotes 10.1%.

Return type:

float

Examples

>>> gaussian(8, 1, 2)
1.3498566943461957e-06
>>> gaussian([8, 7, 9], 1, 2)
array([1.34985669e-06, 3.48132630e-05, 3.17455867e-08])
econsieve.stats.likelihood(z, x, P, H, R)

Returns likelihood of the measurement z given the Gaussian posterior (x, P) using measurement function H and measurement covariance error R

econsieve.stats.log_likelihood(z, x, P, H, R)

Returns log-likelihood of the measurement z given the Gaussian posterior (x, P) using measurement function H and measurement covariance error R

econsieve.stats.mahalanobis(x, mean, cov)

Computes the Mahalanobis distance between the state vector x from the Gaussian mean with covariance cov. This can be thought as the number of standard deviations x is from the mean, i.e. a return value of 3 means x is 3 std from mean.

Parameters:
  • x ((N,) array_like, or float) – Input state vector
  • mean ((N,) array_like, or float) – mean of multivariate Gaussian
  • cov ((N, N) array_like or float) – covariance of the multivariate Gaussian
Returns:

mahalanobis – The Mahalanobis distance between vectors x and mean

Return type:

double

Examples

>>> mahalanobis(x=3., mean=3.5, cov=4.**2) # univariate case
0.125
>>> mahalanobis(x=3., mean=6, cov=1) # univariate, 3 std away
3.0
>>> mahalanobis([1., 2], [1.1, 3.5], [[1., .1],[.1, 13]])
0.42533327058913922
econsieve.stats.mul(mean1, var1, mean2, var2)

Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var).

Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gaussian PDF, so it is safe to treat the output as a PDF for any filter using Bayes equation, which normalizes the result anyway.

Parameters:
  • mean1 (scalar) – mean of first Gaussian
  • var1 (scalar) – variance of first Gaussian
  • mean2 (scalar) – mean of second Gaussian
  • var2 (scalar) – variance of second Gaussian
Returns:

  • mean (scalar) – mean of product
  • var (scalar) – variance of product

Examples

>>> mul(1, 2, 3, 4)
(1.6666666666666667, 1.3333333333333333)

References

Bromily. “Products and Convolutions of Gaussian Probability Functions”, Tina Memo No. 2003-003. http://www.tina-vision.net/docs/memos/2003-003.pdf

econsieve.stats.mul_pdf(mean1, var1, mean2, var2)

Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var, scale_factor).

Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gaussian PDF. scale_factor provides this proportionality constant

Parameters:
  • mean1 (scalar) – mean of first Gaussian
  • var1 (scalar) – variance of first Gaussian
  • mean2 (scalar) – mean of second Gaussian
  • var2 (scalar) – variance of second Gaussian
Returns:

  • mean (scalar) – mean of product
  • var (scalar) – variance of product
  • scale_factor (scalar) – proportionality constant

Examples

>>> mul(1, 2, 3, 4)
(1.6666666666666667, 1.3333333333333333)

References

Bromily. “Products and Convolutions of Gaussian Probability Functions”, Tina Memo No. 2003-003. http://www.tina-vision.net/docs/memos/2003-003.pdf

econsieve.stats.multivariate_gaussian(x, mu, cov)

This is designed to replace scipy.stats.multivariate_normal which is not available before version 0.14. You may either pass in a multivariate set of data:

multivariate_gaussian (array([1,1]), array([3,4]), eye(2)*1.4)
multivariate_gaussian (array([1,1,1]), array([3,4,5]), 1.4)

or unidimensional data:

multivariate_gaussian(1, 3, 1.4)

In the multivariate case if cov is a scalar it is interpreted as eye(n)*cov

The function gaussian() implements the 1D (univariate)case, and is much faster than this function.

equivalent calls:

multivariate_gaussian(1, 2, 3)
scipy.stats.multivariate_normal(2,3).pdf(1)
Parameters:
  • x (float, or np.array-like) – Value to compute the probability for. May be a scalar if univariate, or any type that can be converted to an np.array (list, tuple, etc). np.array is best for speed.
  • mu (float, or np.array-like) – mean for the Gaussian . May be a scalar if univariate, or any type that can be converted to an np.array (list, tuple, etc).np.array is best for speed.
  • cov (float, or np.array-like) – Covariance for the Gaussian . May be a scalar if univariate, or any type that can be converted to an np.array (list, tuple, etc).np.array is best for speed.
Returns:

probability – probability for x for the Gaussian (mu,cov)

Return type:

float

econsieve.stats.multivariate_multiply(m1, c1, m2, c2)

Multiplies the two multivariate Gaussians together and returns the results as the tuple (mean, covariance).

Examples

m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]],
                             [3.2, 0], [[8.0, 1.1], [1.1,8.0]])
Parameters:
  • m1 (array-like) – Mean of first Gaussian. Must be convertable to an 1D array via numpy.asarray(), For example 6, [6], [6, 5], np.array([3, 4, 5, 6]) are all valid.
  • c1 (matrix-like) –
    Covariance of first Gaussian. Must be convertable to an 2D array via
    numpy.asarray().
    m2 : array-like
    Mean of second Gaussian. Must be convertable to an 1D array via numpy.asarray(), For example 6, [6], [6, 5], np.array([3, 4, 5, 6]) are all valid.
  • c2 (matrix-like) – Covariance of second Gaussian. Must be convertable to an 2D array via numpy.asarray().
Returns:

  • m (ndarray) – mean of the result
  • c (ndarray) – covariance of the result

econsieve.stats.norm_cdf(x_range, mu, var=1, std=None)

Computes the probability that a Gaussian distribution lies within a range of values.

Parameters:
  • x_range ((float, float)) – tuple of range to compute probability for
  • mu (float) – mean of the Gaussian
  • var (float, optional) – variance of the Gaussian. Ignored if std is provided
  • std (float, optional) – standard deviation of the Gaussian. This overrides the var parameter
Returns:

probability – probability that Gaussian is within x_range. E.g. .1 means 10%.

Return type:

float

econsieve.stats.plot_3d_covariance(mean, cov, std=1.0, ax=None, title=None, color=None, alpha=1.0, label_xyz=True, N=60, shade=True, limit_xyz=True, **kwargs)

Plots a covariance matrix cov as a 3D ellipsoid centered around the mean.

Parameters:
  • mean (3-vector) – mean in x, y, z. Can be any type convertable to a row vector.
  • cov (ndarray 3x3) – covariance matrix
  • std (double, default=1) – standard deviation of ellipsoid
  • ax (matplotlib.axes._subplots.Axes3DSubplot, optional) – Axis to draw on. If not provided, a new 3d axis will be generated for the current figure
  • title (str, optional) – If provided, specifies the title for the plot
  • color (any value convertible to a color) – if specified, color of the ellipsoid.
  • alpha (float, default 1.) – Alpha value of the ellipsoid. <1 makes is semi-transparent.
  • label_xyz (bool, default True) – Gives labels ‘X’, ‘Y’, and ‘Z’ to the axis.
  • N (int, default=60) – Number of segments to compute ellipsoid in u,v space. Large numbers can take a very long time to plot. Default looks nice.
  • shade (bool, default=True) – Use shading to draw the ellipse
  • limit_xyz (bool, default=True) – Limit the axis range to fit the ellipse
  • **kwargs (optional) – keyword arguments to supply to the call to plot_surface()
econsieve.stats.plot_covariance(mean, cov=None, variance=1.0, std=None, interval=None, ellipse=None, title=None, axis_equal=True, show_semiaxis=False, show_center=True, facecolor=None, edgecolor=None, fc='none', ec='#004080', alpha=1.0, xlim=None, ylim=None, ls='solid')

Plots the covariance ellipse for the 2D normal defined by (mean, cov)

variance is the normal sigma^2 that we want to plot. If list-like, ellipses for all ellipses will be ploted. E.g. [1,2] will plot the sigma^2 = 1 and sigma^2 = 2 ellipses. Alternatively, use std for the standard deviation, in which case variance will be ignored.

ellipse is a (angle,width,height) tuple containing the angle in radians, and width and height radii.

You may provide either cov or ellipse, but not both.

Parameters:
  • mean (row vector like (2x1)) – The mean of the normal
  • cov (ndarray-like) – 2x2 covariance matrix
  • variance (float, default 1, or iterable float, optional) – Variance of the plotted ellipse. May specify std or interval instead. If iterable, such as (1, 2**2, 3**2), then ellipses will be drawn for all in the list.
std : float, or iterable float, optional

Standard deviation of the plotted ellipse. If specified, variance is ignored, and interval must be None.

If iterable, such as (1, 2, 3), then ellipses will be drawn for all in the list.

interval : float range [0,1), or iterable float, optional

Confidence interval for the plotted ellipse. For example, .68 (for 68%) gives roughly 1 standand deviation. If specified, variance is ignored and std must be None

If iterable, such as (.68, .95), then ellipses will be drawn for all in the list.

ellipse: (float, float, float)
Instead of a covariance, plots an ellipse described by (angle, width, height), where angle is in radians, and the width and height are the minor and major sub-axis radii. cov must be None.
title: str, optional
title for the plot
axis_equal: bool, default=True
Use the same scale for the x-axis and y-axis to ensure the aspect ratio is correct.
show_semiaxis: bool, default=False
Draw the semiaxis of the ellipse
show_center: bool, default=True
Mark the center of the ellipse with a cross
facecolor, fc: color, default=None
If specified, fills the ellipse with the specified color. fc is an allowed abbreviation
edgecolor, ec: color, default=None
If specified, overrides the default color sequence for the edge color of the ellipse. ec is an allowed abbreviation
alpha: float range [0,1], default=1.
alpha value for the ellipse
xlim: float or (float,float), default=None
specifies the limits for the x-axis
ylim: float or (float,float), default=None
specifies the limits for the y-axis
ls: str, default=’solid’:
line style for the edge of the ellipse
econsieve.stats.plot_covariance_ellipse(mean, cov=None, variance=1.0, std=None, ellipse=None, title=None, axis_equal=True, show_semiaxis=False, facecolor=None, edgecolor=None, fc='none', ec='#004080', alpha=1.0, xlim=None, ylim=None, ls='solid')

Deprecated function to plot a covariance ellipse. Use plot_covariance instead.

econsieve.stats.plot_discrete_cdf(xs, ys, ax=None, xlabel=None, ylabel=None, label=None)

Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-axis shows the cumulative probability.

Parameters:
  • xs (list-like of scalars) – x values corresponding to the values in y`s. Can be `None, in which case range(len(ys)) will be used.
  • ys (list-like of scalars) – list of probabilities to be plotted which should sum to 1.
  • ax (matplotlib axes object, optional) – If provided, the axes to draw on, otherwise plt.gca() is used.
  • ylim (xlim,) – specify the limits for the x or y axis as tuple (low,high). If not specified, limits will be automatically chosen to be ‘nice’
  • xlabel (str,optional) – label for the x-axis
  • ylabel (str, optional) – label for the y-axis
  • label (str, optional) – label for the legend
Returns:

Return type:

axis of plot

econsieve.stats.plot_gaussian(mean=0.0, variance=1.0, ax=None, mean_line=False, xlim=None, ylim=None, xlabel=None, ylabel=None, label=None)

DEPRECATED. Use plot_gaussian_pdf() instead. This is poorly named, as there are multiple ways to plot a Gaussian.

econsieve.stats.plot_gaussian_cdf(mean=0.0, variance=1.0, ax=None, xlim=None, ylim=(0.0, 1.0), xlabel=None, ylabel=None, label=None)

Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-axis shows the cumulative probability.

Parameters:
  • mean (scalar, default 0.) – mean for the normal distribution.
  • variance (scalar, default 0.) – variance for the normal distribution.
  • ax (matplotlib axes object, optional) – If provided, the axes to draw on, otherwise plt.gca() is used.
  • ylim (xlim,) – specify the limits for the x or y axis as tuple (low,high). If not specified, limits will be automatically chosen to be ‘nice’
  • xlabel (str,optional) – label for the x-axis
  • ylabel (str, optional) – label for the y-axis
  • label (str, optional) – label for the legend
Returns:

Return type:

axis of plot

econsieve.stats.plot_gaussian_pdf(mean=0.0, variance=1.0, std=None, ax=None, mean_line=False, xlim=None, ylim=None, xlabel=None, ylabel=None, label=None)

Plots a normal distribution PDF with the given mean and variance. x-axis contains the mean, the y-axis shows the probability density.

Parameters:
  • mean (scalar, default 0.) – mean for the normal distribution.
  • variance (scalar, default 1., optional) – variance for the normal distribution.
  • std (scalar, default=None, optional) – standard deviation of the normal distribution. Use instead of variance if desired
  • ax (matplotlib axes object, optional) – If provided, the axes to draw on, otherwise plt.gca() is used.
  • mean_line (boolean) – draws a line at x=mean
  • ylim (xlim,) – specify the limits for the x or y axis as tuple (low,high). If not specified, limits will be automatically chosen to be ‘nice’
  • xlabel (str,optional) – label for the x-axis
  • ylabel (str, optional) – label for the y-axis
  • label (str, optional) – label for the legend
Returns:

Return type:

axis of plot

econsieve.stats.rand_student_t(df, mu=0, std=1)

return random number distributed by student’s t distribution with df degrees of freedom with the specified mean and standard deviation.

econsieve.sigma_points

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

class econsieve.sigma_points.ScaledSigmaPoints(n, alpha, beta, subtract=None)

Bases: object

econsieve.sigma_points.sigma_points(x, P, alpha, beta)

econsieve.kalman_filter

class econsieve.kalman_filter.KalmanFilter(dim_x, dim_z)

Bases: object

batch_filter(zs, Fs=None, Qs=None, Hs=None, Rs=None, Bs=None, us=None, update_first=False, saver=None)
get_prediction(u=0)

Predicts the next state of the filter and returns it without altering the state of the filter.

Parameters:u (np.array) – optional control input
Returns:(x, P) – State vector and covariance array of the prediction.
Return type:tuple
get_update(z=None)

Computes the new estimate based on measurement z and returns it without altering the state of the filter.

Parameters:z ((dim_z, 1): array_like) – measurement for this update. z can be a scalar if dim_z is 1, otherwise it must be convertible to a column vector.
Returns:(x, P) – State vector and covariance array of the update.
Return type:tuple
guess(z, R=None, H=None)

Guess new state vector, but don’t do the update.

If z is None, nothing is computed. However, x_post and P_post are updated with the prior (x_prior, P_prior), and self.z is set to None.

Parameters:
  • z ((dim_z, 1): array_like) – measurement for this update. z can be a scalar if dim_z is 1, otherwise it must be convertible to a column vector.
  • R (np.array, scalar, or None) – Optionally provide R to override the measurement noise for this one call, otherwise self.R will be used.
  • H (np.array, or None) – Optionally provide H to override the measurement function for this one call, otherwise self.H will be used.
mahalanobis

” Mahalanobis distance of measurement. E.g. 3 means measurement was 3 standard deviations away from the predicted value.

Returns:mahalanobis
Return type:float
measurement_of_state(x)

Helper function that converts a state into a measurement.

Parameters:x (np.array) – kalman state vector
Returns:z – measurement for this update. z can be a scalar if dim_z is 1, otherwise it must be convertible to a column vector.
Return type:(dim_z, 1): array_like
name = 'KalmanFilter'
predict(u=None, B=None, F=None, Q=None)

Predict next state (prior) using the Kalman filter state propagation equations.

Parameters:
  • u (np.array) – Optional control vector. If not None, it is multiplied by B to create the control input into the system.
  • B (np.array(dim_x, dim_z), or None) – Optional control transition matrix; a value of None will cause the filter to use self.B.
  • F (np.array(dim_x, dim_x), or None) – Optional state transition matrix; a value of None will cause the filter to use self.F.
  • Q (np.array(dim_x, dim_x), scalar, or None) – Optional process noise matrix; a value of None will cause the filter to use self.Q.
predict_steadystate(u=0, B=None)

Predict state (prior) using the Kalman filter state propagation equations. Only x is updated, P is left unchanged. See update_steadstate() for a longer explanation of when to use this method.

Parameters:
  • u (np.array) – Optional control vector. If non-zero, it is multiplied by B to create the control input into the system.
  • B (np.array(dim_x, dim_z), or None) – Optional control transition matrix; a value of None will cause the filter to use self.B.
residual_of(z)

Returns the residual for the given measurement (z). Does not alter the state of the filter.

rts_smoother(Xs, Ps, Fs=None, Qs=None, inv=<sphinx.ext.autodoc.importer._MockObject object>)

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.
  • Fs (list-like collection of numpy.array, optional) – State transition matrix of the Kalman filter at each time step. Optional, if not provided the filter’s self.F will be used
  • 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
  • inv (function, default numpy.linalg.inv) – If you prefer another inverse function, such as the Moore-Penrose pseudo inverse, set it to that instead: kf.inv = np.linalg.pinv
Returns:

  • x (numpy.ndarray) – smoothed means
  • P (numpy.ndarray) – smoothed state covariances
  • K (numpy.ndarray) – smoother gain at each step
  • Pp (numpy.ndarray) – Predicted state covariances

Examples

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

(mu, cov, _, _) = kalman.batch_filter(zs)
(x, P, K, Pp) = rts_smoother(mu, cov, kf.F, kf.Q)
update(z, R=None, H=None)

Add a new measurement (z) to the Kalman filter.

If z is None, nothing is computed. However, x_post and P_post are updated with the prior (x_prior, P_prior), and self.z is set to None.

Parameters:
  • z ((dim_z, 1): array_like) – measurement for this update. z can be a scalar if dim_z is 1, otherwise it must be convertible to a column vector.
  • R (np.array, scalar, or None) – Optionally provide R to override the measurement noise for this one call, otherwise self.R will be used.
  • H (np.array, or None) – Optionally provide H to override the measurement function for this one call, otherwise self.H will be used.
update_steadystate(z)

Add a new measurement (z) to the Kalman filter without recomputing the Kalman gain K, the state covariance P, or the system uncertainty S.

You can use this for LTI systems since the Kalman gain and covariance converge to a fixed value. Precompute these and assign them explicitly, or run the Kalman filter using the normal predict()/update(0 cycle until they converge.

The main advantage of this call is speed. We do significantly less computation, notably avoiding a costly matrix inversion.

Use in conjunction with predict_steadystate(), otherwise P will grow without bound.

Parameters:z ((dim_z, 1): array_like) – measurement for this update. z can be a scalar if dim_z is 1, otherwise it must be convertible to a column vector.

Examples

>>> cv = kinematic_kf(dim=3, order=2) # 3D const velocity filter
>>> # let filter converge on representative data, then save k and P
>>> for i in range(100):
>>>     cv.predict()
>>>     cv.update([i, i, i])
>>> saved_k = np.copy(cv.K)
>>> saved_P = np.copy(cv.P)

later on:

>>> cv = kinematic_kf(dim=3, order=2) # 3D const velocity filter
>>> cv.K = np.copy(saved_K)
>>> cv.P = np.copy(saved_P)
>>> for i in range(100):
econsieve.kalman_filter.reshape_z(z, dim_z, ndim)

ensure z is a (dim_z, 1) shaped vector