Functions
Mathematical functions used within Stone Soup
- stonesoup.functions.block_diag(*arrays)[source]
Create a block diagonal matrix from the provided 2-D (or lower) arrays.
A lightweight, drop-in replacement for
scipy.linalg.block_diag()for the plainnumpy.ndarrayinputs Stone Soup calls it with (no batching, no array-API dispatch), which is substantially faster for the small matrices typical of combined transition/measurement models.- Parameters:
*arrays (numpy.ndarray) – Input arrays, treated as 2-D (scalar and 1-D inputs are promoted, as per
numpy.atleast_2d()).- Returns:
Array with the inputs arranged on the diagonal.
- Return type:
- stonesoup.functions.grid_creation(xp_aux, Pp_aux, sFactor, nx, Npa)[source]
Grid for point mass filter
Create a PMF grid based on center, covariance matrix, and sigma probability
- Parameters:
xp_aux (numpy.ndarray) – nx by 1 center of the grid
Pp_aux (numpy.ndarray) – ‘nx’ by ‘nx’ covariance matrix
sFactor (int) – Parameter for the size of the grid
nx (int) – Dimension of the grid
Npa (numpy.ndarray) – ‘nx’ by ‘’ number of points per axis of the grid
- Returns:
predGrid (numpy.ndarray) – ‘nx’ by prod(Npa) predictive grid
predGridDelta (list) – grid step per dimension
gridDim (list of numpy.ndarrays) – grid coordinates per dimension before rotation and translation
xp_aux (numpy.ndarray) – grid center
eigVect (numpy.ndarray) – eigenvectors describing the rotation of the grid
- stonesoup.functions.tria(matrix)[source]
Square Root Matrix Triangularization
Given a rectangular square root matrix obtain a square lower-triangular square root matrix
- Parameters:
matrix (numpy.ndarray) – A n by m matrix that is generally not square.
- Returns:
A square lower-triangular matrix.
- Return type:
- stonesoup.functions.cholesky_eps(A, lower=False)[source]
Perform a Cholesky decomposition on a nearly positive-definite matrix.
This should return similar results to NumPy/SciPy Cholesky decompositions, but compromises for cases for non positive-definite matrix.
- Parameters:
A (numpy.ndarray) – Symmetric positive-definite matrix.
lower (bool) – Whether to return lower or upper triangular decomposition. Default False which returns upper.
- Returns:
L – Upper/lower triangular Cholesky decomposition.
- Return type:
- stonesoup.functions.jacobian(fun, x, **kwargs)[source]
Compute Jacobian through finite difference calculation
- Parameters:
fun (function handle) – A (non-linear) transition function Must be of the form “y = fun(x)”, where y can be a scalar or
numpy.ndarrayof shape (Nd, 1) or (Nd,)x (
State) – A state with state vector of shape (Ns, 1)
- Returns:
jac – The computed Jacobian
- Return type:
numpy.ndarrayof shape (Nd, Ns)
- stonesoup.functions.gauss2sigma(state, alpha=1.0, beta=2.0, kappa=None)[source]
Approximate a given distribution to a Gaussian, using a deterministically selected set of sigma points.
- Parameters:
state (
State) – A state object capable of returning aStateVectorof shape (Ns, 1) representing the Gaussian mean and aCovarianceMatrixof shape (Ns, Ns) which is the covariance of the distributionalpha (float, optional) – Spread of the sigma points. Typically 1e-3. (default is 1)
beta (float, optional) – Used to incorporate prior knowledge of the distribution 2 is optimal if the state is normally distributed. (default is 2)
kappa (float, optional) – Secondary spread scaling parameter (default is calculated as 3-Ns)
- Returns:
Statewith state vector of shape (Ns, 2*Ns+1) – An State containing the locations of the sigma points. Note that only thestate_vectorattribute in these States will be meaningful. Other quantities, likecovarwill be inherited from the input and don’t really make sense for a sigma point.numpy.ndarrayof shape (2*Ns+1,) – An array containing the sigma point mean weightsnumpy.ndarrayof shape (2*Ns+1,) – An array containing the sigma point covariance weights
- stonesoup.functions.sigma2gauss(sigma_points, mean_weights, covar_weights, covar_noise=None)[source]
Calculate estimated mean and covariance from a given set of sigma points
- Parameters:
sigma_points (
StateVectorsof shape (Ns, 2*Ns+1)) – An array containing the locations of the sigma pointsmean_weights (
numpy.ndarrayof shape (2*Ns+1,)) – An array containing the sigma point mean weightscovar_weights (
numpy.ndarrayof shape (2*Ns+1,)) – An array containing the sigma point covariance weightscovar_noise (
CovarianceMatrixof shape (Ns, Ns), optional) – Additive noise covariance matrix (default is None)
- Returns:
StateVectorof shape (Ns, 1) – Calculated meanCovarianceMatrixof shape (Ns, Ns) – Calculated covariance
- stonesoup.functions.unscented_transform(sigma_points_states, mean_weights, covar_weights, fun, points_noise=None, covar_noise=None)[source]
Apply the Unscented Transform to a set of sigma points
Apply f to points (with secondary argument points_noise, if available), then approximate the resulting mean and covariance. If sigma_noise is available, treat it as additional variance due to additive noise.
- Parameters:
sigma_points_states (
Statewith state vector of shape (Ns, 2*Ns+1)) – A state containing the locations of the sigma pointsmean_weights (
numpy.ndarrayof shape (2*Ns+1,)) – An array containing the sigma point mean weightscovar_weights (
numpy.ndarrayof shape (2*Ns+1,)) – An array containing the sigma point covariance weightsfun (function handle) – A (non-linear) transition function Must be of the form “y = fun(x,w)”, where y can be a scalar or
numpy.ndarrayof shape (Ns, 1) or (Ns,)covar_noise (
CovarianceMatrixof shape (Ns, Ns), optional) – Additive noise covariance matrix (default is None)points_noise (
numpy.ndarrayof shape (Ns, 2*Ns+1,), optional) – points to pass into f’s second argument (default is None)
- Returns:
StateVectorof shape (Ns, 1) – Transformed meanCovarianceMatrixof shape (Ns, Ns) – Transformed covarianceCovarianceMatrixof shape (Ns,Nm) – Calculated cross-covariance matrixStateVectorsof shape (Ns, 2*Ns+1) – An array containing the locations of the transformed sigma pointsnumpy.ndarrayof shape (2*Ns+1,) – An array containing the transformed sigma point mean weightsnumpy.ndarrayof shape (2*Ns+1,) – An array containing the transformed sigma point covariance weights
- stonesoup.functions.cart2az_el_rg(x, y, z)[source]
Convert Cartesian to azimuth (phi), elevation(theta), and range(rho)
- stonesoup.functions.az_el_rg2cart(phi, theta, rho)[source]
Convert azimuth (phi), elevation(theta), and range(rho) to Cartesian
- stonesoup.functions.rotx(theta)[source]
Rotation matrix for rotations around x-axis
For a given rotation angle: \(\theta\), this function evaluates and returns the rotation matrix:
(1)\[\begin{split}R_{x}(\theta) = \begin{bmatrix} 1 & 0 & 0 \\ 0 & cos(\theta) & -sin(\theta) \\ 0 & sin(\theta) & cos(\theta) \end{bmatrix}\end{split}\]- Parameters:
theta (Union[float, np.ndarray]) – Rotation angle specified as a real-valued number or an
np.ndarrayof reals. The rotation angle is positive if the rotation is in the clockwise direction when viewed by an observer looking down the x-axis towards the origin. Angle units are in radians.- Returns:
Rotation matrix around x-axis of the form (1).
- Return type:
numpy.ndarrayof shape (3, 3) or (3, 3, n) for array input
- stonesoup.functions.roty(theta)[source]
Rotation matrix for rotations around y-axis
For a given rotation angle: \(\theta\), this function evaluates and returns the rotation matrix:
(2)\[\begin{split}R_{y}(\theta) = \begin{bmatrix} cos(\theta) & 0 & sin(\theta) \\ 0 & 1 & 0 \\ - sin(\theta) & 0 & cos(\theta) \end{bmatrix}\end{split}\]- Parameters:
theta (Union[float, np.ndarray]) – Rotation angle specified as a real-valued number or an
np.ndarrayof reals. The rotation angle is positive if the rotation is in the clockwise direction when viewed by an observer looking down the y-axis towards the origin. Angle units are in radians.- Returns:
Rotation matrix around y-axis of the form (2).
- Return type:
numpy.ndarrayof shape (3, 3) or (3, 3, n) for array input
- stonesoup.functions.rotz(theta)[source]
Rotation matrix for rotations around z-axis
For a given rotation angle: \(\theta\), this function evaluates and returns the rotation matrix:
(3)\[\begin{split}R_{z}(\theta) = \begin{bmatrix} cos(\theta) & -sin(\theta) & 0 \\ sin(\theta) & cos(\theta) & 0 \\ 0 & 0 & 1 \end{bmatrix}\end{split}\]- Parameters:
theta (Union[float, np.ndarray]) – Rotation angle specified as a real-valued number or an
np.ndarrayof reals. The rotation angle is positive if the rotation is in the clockwise direction when viewed by an observer looking down the z-axis towards the origin. Angle units are in radians.- Returns:
Rotation matrix around z-axis of the form (3).
- Return type:
numpy.ndarrayof shape (3, 3) or (3, 3, n) for array input
- stonesoup.functions.gm_sample(means, covars, size, weights=None, random_state=None)[source]
Sample from a mixture of multi-variate Gaussians
- Parameters:
means (
StateVector,StateVectors,np.ndarrayof shape (num_dims, num_components)) – The means of GM componentscovars (
np.ndarrayof shape (num_components, num_dims, num_dims) or list ofnp.ndarrayof shape (num_dims, num_dims)) – Covariance matrices of the GM componentssize (int) – Number of samples to return.
weights (
np.ndarrayof shape (num_components, ), optional) – The weights of the GM components. If not defined, assumed equal.
- Return type:
StateVectorsof shape (num_dims,size)
- stonesoup.functions.gm_reduce_single(means, covars, weights)[source]
Reduce mixture of multi-variate Gaussians to single Gaussian
- Parameters:
means (
StateVectors) – The means of the GM componentscovars (
numpy.ndarrayof shape (num_dims, num_dims, num_components)) – The covariance matrices of the GM componentsweights (
numpy.ndarrayof shape (num_components,)) – The weights of the GM components
- Returns:
StateVector– The mean of the reduced/single GaussianCovarianceMatrix– The covariance of the reduced/single Gaussian
- stonesoup.functions.mod_bearing(x)[source]
Calculates the modulus of a bearing. Bearing angles are within the range \(-\pi\) to \(\pi\).
- stonesoup.functions.mod_elevation(x)[source]
Calculates the modulus of an elevation angle. Elevation angles are within the range \(-\pi/2\) to \(\pi/2\).
- Parameters:
x (float) – elevation angle in radians
- Returns:
Angle in radians in the range math: \(-\pi/2\) to \(+\pi/2\)
- Return type:
Note
Uses the identity \(\arcsin(\sin(x))\), which folds any angle into \([-\pi/2, \pi/2]\) with the same symmetry as elevation wrapping.
- stonesoup.functions.build_rotation_matrix(angle_vector: ndarray)[source]
Calculates and returns the (3D) axis rotation matrix given a vector of three angles: [roll, pitch/elevation, yaw/azimuth] Order of rotations is in reverse: yaw, pitch, roll (z, y, x) This is the rotation matrix that implements the rotations that convert the input angle_vector to match the x-axis.
- Parameters:
angle_vector (
numpy.ndarrayof shape (3, 1)) – the rotations about the :math:’x, y, z’ axes. In aircraft/radar terms these correspond to [roll, pitch/elevation, yaw/azimuth]- Returns:
The model (3D) rotation matrix.
- Return type:
numpy.ndarrayof shape (3, 3)
- stonesoup.functions.build_rotation_matrix_xyz(angle_vector: ndarray)[source]
Calculates and returns the (3D) axis rotation matrix given a vector of three angles: [roll, pitch/elevation, yaw/azimuth] Order of rotations is roll, pitch, yaw (x, y, z) This is the rotation matrix that implements the rotations that convert a vector aligned to the x-axis to the input angle_vector.
- Parameters:
angle_vector (
numpy.ndarrayof shape (3, 1)) – the rotations about the :math:’x, y, z’ axes. In aircraft/radar terms these correspond to [roll, pitch/elevation, yaw/azimuth]- Returns:
The model (3D) rotation matrix.
- Return type:
numpy.ndarrayof shape (3, 3)
- stonesoup.functions.dotproduct(a, b)[source]
Returns the dot (or scalar) product of two StateVectors or two sets of StateVectors.
The result for vectors of length \(n\) is \(\Sigma_i^n a_i b_i\).
- Parameters:
a (StateVector, StateVectors) – A (set of) state vector(s)
b (StateVector, StateVectors) – A state vector(s) object of equal dimension to \(a\)
- Returns:
A (set of) scalar value(s) representing the dot product of the vectors.
- Return type:
float, numpy.array
- stonesoup.functions.sde_euler_maruyama_integration(fun, t_values, state_x0)[source]
Perform SDE Euler Maruyama Integration
Performs Stochastic Differential Equation Integration using the Euler Maruyama method.
- Parameters:
- Returns:
Final value for the time in last value in
t_values- Return type:
- stonesoup.functions.gauss2cubature(state, alpha=1.0)[source]
Evaluate the cubature points for an input Gaussian state. This is done under the assumption that the input state is \(\mathcal{N}(\mathbf{\mu}, \Sigma)\) of dimension \(n\). We calculate the square root of the covariance (via Cholesky factorization), and find the cubature points, \(X\), as,
\[ \begin{align}\begin{aligned}\Sigma &= S S^T\\X_i &= S \xi_i + \mathbf{\mu}\end{aligned}\end{align} \]for \(i = 1,...,2n\), where \(\xi_i = \sqrt{ \alpha n} [\pm \mathbf{1}]_i\) and \([\pm \mathbf{1}]_i\) are the positive and negative unit vectors in each dimension. We include a scaling parameter \(\alpha\) to allow the selection of cubature points closer to the mean or more in the tails, as a potentially useful free parameter.
- Parameters:
state (
GaussianState) – A Gaussian state with mean and covariancealpha (float, optional) – scaling parameter allowing the selection of cubature points closer to the mean (lower values) or further from the mean (higher values)
- Returns:
Cubature points (as a
StateVectorsof dimension \(n \times 2n\))- Return type:
- stonesoup.functions.cubature2gauss(cubature_points, covar_noise=None, alpha=1.0)[source]
Get the predicted Gaussian mean and covariance from the cubature points. For dimension \(n\) there are \(m = 2n\) cubature points. The mean is,
\[\mu = \frac{1}{m} \sum\limits_{i=1}^{m} X_i\]and the covariance
\[\Sigma = \frac{1}{\alpha}\left(\frac{1}{m} \sum\limits_{i=1}^{m} X_i X_i^T - \mathbf{\mu}\mathbf{\mu}^T\right) + Q\]where \(Q\) is an optional additive noise matrix. The scaling parameter \(\alpha\) allow the for cubature points closer to the mean or more in the tails,
- Parameters:
cubature_points (
StateVectors) – Cubature points (as aStateVectorsof dimension \(n \times 2n\))covar_noise (
CovarianceMatrixof shape (Ns, Ns), optional) – Additive noise covariance matrix (default is None)alpha (float, optional) – scaling parameter allowing the nomination of cubature points closer to the mean (lower values) or further from the mean (higher values)
- Returns:
A Gaussian state with mean and covariance
- Return type:
- stonesoup.functions.cubature_transform(state, fun, points_noise=None, covar_noise=None, alpha=1.0)[source]
Undertakes the cubature transform as described in [1]
Given a Gaussian distribution, calculates the set of cubature points using
gauss2cubature(), then passes these through the given function and reconstructs the Gaussian usingcubature2gauss(). Returns the mean, covariance, cross covariance and transformed cubature points. This instance includes a scaling parameter \(\alpha\), not included in the reference detailed above, which allows for the selection of cubature points closer to, or further from, tne mean.- Parameters:
state (
GaussianState) – A Gaussian state with mean and covariancefun (function handle) – A (non-linear) transition function Must be of the form “y = fun(x,w)”, where y can be a scalar or
numpy.ndarrayof shape (Ns, 1) or (Ns,)covar_noise (
CovarianceMatrixof shape (Ns, Ns), optional) – Additive noise covariance matrix (default is None)points_noise (
numpy.ndarrayof shape (Ns, 2*Ns+1,), optional) – points to pass into f’s second argument (default is None)alpha (float, optional) – scaling parameter allowing the selection of cubature points closer to the mean (lower values) or further from the mean (higher values)
- Returns:
StateVectorof shape (Ns, 1) – Transformed meanCovarianceMatrixof shape (Ns, Ns) – Transformed covarianceCovarianceMatrixof shape (Ns,Nm) – Calculated cross-covariance matrixStateVectorsof shape (Ns, 2*Ns) – An array containing the locations of the transformed cubature points
References
- stonesoup.functions.stochastic_cubature_rule_points(nx, order)[source]
Computation of cubature points and weights for the stochastic integration.
- Parameters:
- Returns:
Tuple of sigma points and weights
- Return type:
- stonesoup.functions.cub_points_and_tf(nx, order, sqrtCov, mean, transFunct, state)[source]
Calculates cubature points for stochastic integration filter and puts them through given function (measurement/dynamics)
- Parameters:
nx (int) – Dimension for cubature points, equivalent to state dimension.
order (int) – Order for Stochastic Integration. Only orders 1, 3, and 5 are supported
sqrtCov (np.ndarray) – Matrix square root array of shape (nx, nx) of the covariance matrix
mean (np.ndarray) – An array of shape (nx, 1) of the state mean
transFunct (Callable) – A function to transfer state vectors
state (
State) – State object used to save function output to
- Returns:
points (numpy.ndarray) – Array of shape (nx, number of points) of cubature points
w (numpy.ndarray) – Array of shape (number of points) of weights
trsfPoints (numpy.ndarray) – Array of shape (nx, number of points) (based on order and dim) of cubature transformed points
- stonesoup.functions.find_nearest_positive_definite(matrix, max_iterations=20)[source]
Find the nearest positive definite matrix usable for cholesky factorization.
The nearest measure is in terms of Frobenius norm.
- Parameters:
matrix (numpy.ndarray) – Base matrix to find the nearest positive definite from
- Returns:
The nearest positive definite matrix
- Return type:
- stonesoup.functions.is_cholesky_decomposable(matrix)[source]
Test if given matrix is usable for cholesky decomposition.
- Parameters:
matrix (numpy.ndarray) – Matrix to test
- Returns:
An indication whether given matrix is usable for chelesky decomposition
- Return type:
- stonesoup.functions.batch_multivariate_normal_logpdf(vectors, states)[source]
Vectorised calculation for the multi-variate normal logpdf of N
StateVectorobjects to NGaussianStateobjects.The logpdf of vectors[m] will be calculated from the distribution states[m].
- Parameters:
vectors (list of
StateVector) – Sequence of NStateVectorobjects.states (list of
GaussianState) – Sequence of NGaussianStateobjects.
- Returns:
Numpy array of shape (N,) of logpdf values.
- Return type:
Interpolation
- stonesoup.functions.interpolate.time_range(start_time: datetime, end_time: datetime, timestep: timedelta = datetime.timedelta(seconds=1)) Iterable[datetime][source]
Produces a range of datetime object between
start_time(inclusive) andend_time(inclusive)- Parameters:
start_time (datetime.datetime time range start (inclusive))
end_time (datetime.datetime time range end (inclusive))
timestep (datetime.timedelta default value is 1 second)
- Return type:
Generator[datetime.datetime]
- stonesoup.functions.interpolate.interpolate_state_mutable_sequence(sms: StateMutableSequence, times: datetime | list[datetime]) StateMutableSequence | State[source]
This function performs linear interpolation on a
StateMutableSequence. The function has two slightly different forms:If an individual
datetimeis inputted for the variabletimesthen aStateis returned corresponding totimes.If a list of
datetimeis inputted for the variabletimesthen aStateMutableSequenceis returned with the states in the sequence corresponding totimes.When interpolating the previous state is used to create the interpolated state. This means properties from that previous state are also copied but will not be interpolated e.g. covariance.
- Parameters:
sms (StateMutableSequence) – A
StateMutableSequencethat should be interpolatedtimes (Union[datetime.datetime, list[datetime.datetime]]) – a time, or a list of times for
smsto be interpolated to.
- Returns:
If a single time is provided then a single state is returned. If a list of times is provided then a
StateMutableSequencewith the same type assmsis returned- Return type:
Union[StateMutableSequence, State]
Note
This function does not extrapolate. Times outside the range of the time range of
smsare discarded and warning is given. If alltimesvalues are outside the time range ofsmsthen anIndexErroris raised.Unique states for each time are required for interpolation. If there are multiple states with the same time in
smsthe later state in the sequence is used.For
Trackinputs the metadatas is removed as it can’t be interpolated.