common¶
A collection of functions used throughout FilterPy, and/or functions that you will find useful when you build your filters.
Copyright 2014 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.
-
filterpy.common.
Q_discrete_white_noise
(dim, dt=1.0, var=1.0)[source]¶ Returns the Q matrix for the Discrete Constant White Noise Model. dim may be either 2 or 3, dt is the time step, and sigma is the variance in the noise.
Q is computed as the G * G^T * variance, where G is the process noise per time step. In other words, G = [[.5dt^2][dt]]^T for the constant velocity model.
Paramaeters
- dim : int (2 or 3)
- dimension for Q, where the final dimension is (dim x dim)
- dt : float, default=1.0
- time step in whatever units your filter is using for time. i.e. the amount of time between innovations
- var : float, default=1.0
- variance in the noise
-
filterpy.common.
Q_continuous_white_noise
(dim, dt=1.0, spectral_density=1.0)[source]¶ Returns the Q matrix for the Discretized Continuous White Noise Model. dim may be either 2 or 3, dt is the time step, and sigma is the variance in the noise.
Paramaeters
- dim : int (2 or 3)
- dimension for Q, where the final dimension is (dim x dim)
- dt : float, default=1.0
- time step in whatever units your filter is using for time. i.e. the amount of time between innovations
- spectral_density : float, default=1.0
- spectral density for the continuous process
-
filterpy.common.
van_loan_discretization
(F, G, dt)[source]¶ Discretizes a linear differential equation which includes white noise according to the method of C. F. van Loan [1]. Given the continuous model
x’ = Fx + Guwhere u is the unity white noise, we compute and return the sigma and Q_k that discretizes that equation.
Example:
Given y'' + y = 2u(t), we create the continuous state model of x' = | 0 1| * x + |0|*u(t) |-1 0| |2| and a time step of 0.1: >>> F = np.array([[0,1],[-1,0]], dtype=float) >>> G = np.array([[0.],[2.]]) >>> phi, Q = van_loan_discretization(F, G, 0.1) >>> phi array([[ 0.99500417, 0.09983342], [-0.09983342, 0.99500417]]) >>> Q array([[ 0.00133067, 0.01993342], [ 0.01993342, 0.39866933]]) (example taken from Brown[2])
References
- [1] C. F. van Loan. “Computing Integrals Involving the Matrix Exponential.”
- IEEE Trans. Automomatic Control, AC-23 (3): 395-404 (June 1978)
- [2] Robert Grover Brown. “Introduction to Random Signals and Applied
- Kalman Filtering.” Forth edition. John Wiley & Sons. p. 126-7. (2012)
-
filterpy.common.
runge_kutta4
(y, x, dx, f)[source]¶ computes 4th order Runge-Kutta for dy/dx.
Parameters
- y : scalar
- Initial/current value for y
- x : scalar
- Initial/current value for x
- dx : scalar
- difference in x (e.g. the time step)
- f : ufunc(y,x)
- Callable function (y, x) that you supply to compute dy/dx for the specified values.
-
filterpy.common.
gaussian
(x, mean, var)[source]¶ 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
- The value for which we compute the probability
- mean : scalar
- Mean of the Gaussian
- var : scalar
- Variance of the Gaussian
Returns
- probability : float
- probability of x for the Gaussian (mean, var). E.g. 0.101 denotes 10.1%.
-
filterpy.common.
mul
(mean1, var1, mean2, var2)[source]¶ multiply 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.
-
filterpy.common.
add
(mean1, var1, mean2, var2)[source]¶ 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.
-
filterpy.common.
multivariate_gaussian
(x, mu, cov)[source]¶ 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 : float
- probability for x for the Gaussian (mu,cov)
-
filterpy.common.
multivariate_multiply
(m1, c1, m2, c2)[source]¶ Multiplies the two multivariate Gaussians together and returns the results as the tuple (mean, covariance).
example
- 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
- Mean 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
- Mean 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
-
filterpy.common.
plot_gaussian
(mean, variance, mean_line=False, xlim=None, xlabel=None, ylabel=None)[source]¶ plots the normal distribution with the given mean and variance. x-axis contains the mean, the y-axis shows the probability.
parameters
- mean_line : boolean
- draws a line at x=mean
- xlim: (float,float), optional
- specify the limits for the x 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
-
filterpy.common.
covariance_ellipse
(P, deviations=1)[source]¶ 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.
Returns (angle_radians, width_radius, height_radius)
-
filterpy.common.
plot_covariance_ellipse
(mean, cov=None, variance=1.0, std=None, ellipse=None, title=None, axis_equal=True, facecolor=u'none', edgecolor=u'#004080', alpha=1.0, xlim=None, ylim=None)[source]¶ plots the covariance ellipse where
mean is a (x,y) tuple for the mean of the covariance (center of ellipse)
cov is a 2x2 covariance matrix.
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.
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.
plt.show() is not called, allowing you to plot multiple things on the same figure.
-
filterpy.common.
norm_cdf
(x_range, mu, var=1, std=None)[source]¶ computes the probability that a Gaussian distribution lies within a range of values.
Paramateters
- 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 : float
- probability that Gaussian is within x_range. E.g. .1 means 10%.
-
filterpy.common.
rand_student_t
(df, mu=0, std=1)[source]¶ return random number distributed by student’s t distribution with df degrees of freedom with the specified mean and standard deviation.