FilterOD#

class FilterOD(propagator: Propagator | MissionSequence, measurements: MeasurementSpec, settings: FilterSettings, traj_name: str | None = None, traj_dir: str | None = None, overwrite_traj: bool = True, verbose: bool = True)#

Bases: object

Parent class for orbit determination filters used for spacecraft state and parameter estimation from tracking measurements.

The framework supports single- and multi-object estimation problems through flexible dynamical and measurement model definitions. The class propagates a reference solution, constructs the linearized measurement sensitivity matrix, and estimates corrections to the reference trajectory, dynamical states, and model parameters.

Supported estimation problems include spacecraft translational dynamics, stochastic and deterministic parameters, multi-arc or mission-sequence configurations, and coupled dynamical systems.

Maximum-a-posteriori estimate

Every filter in this framework estimates the deviation \(\Delta x_0\) from the reference trajectory \(x^*(t)\) that minimises the weighted least-squares cost:

\[J(\Delta x_0) = \Delta x_0^T P_0^{-1} \Delta x_0 + \sum_k \Bigl[y_k - H_k \Phi_{k,0}\,\Delta x_0\Bigr]^T R_k^{-1} \Bigl[y_k - H_k \Phi_{k,0}\,\Delta x_0\Bigr]\]

where \(y_k = z_k - h(x^*(t_k))\) is the prefit residual and \(P_0^{-1}\) is the a-priori information matrix. Under Gaussian assumptions the minimiser is the maximum-a-posteriori (MAP) estimate \(\hat{x}_0 = x^*(t_0) + \widehat{\Delta x}_0\).

Iteration

Because the measurement model is linearised around \(x^*\), the single-pass estimate is only first-order accurate. The fit() method re-runs the filter iteratively: after each pass the reference is re-propagated from \(x^*(t_0) + \widehat{\Delta x}_0\) and the filter is re-applied on the updated reference. At convergence the accumulated deviation satisfies \(\widehat{\Delta x}_0 \approx 0\), meaning the current reference is the MAP estimate and the covariance is the true posterior covariance linearised around the solution.

Schmidt consider parameters

Parameters that affect measurements but are poorly constrained and should not be estimated can be declared as consider parameters (FilterSettings). Their uncertainty is propagated through the filter and inflates the covariance of the estimated state (Schmidt, 1966), but their values are never updated by measurements. This prevents over-confidence when unmodelled force parameters are present.

Parameters:
propagatorPropagator or MissionSequence

Propagator or mission sequence object that defines the reference trajectory and state transition matrices (STMs) for orbit determination.

measurementsMeasurementSpec

Measurement specification object.

settingsFilterSettings

Filter configuration settings. Its measurement_sigmas, keyed by dataset name, are set once, at construction and before the first editing pass, on the model behind each dataset they name (see set_measurement_sigmas()). They therefore win over the sigma the model was built with, model.sigma reports them, and the datasets of every later iteration are built with them. The model is the only source: a sigma set on it afterwards (through set_measurement_sigmas(), MeasurementSpec.edit or model.sigma = ..., e.g. from a fit() callback) takes over from the next iteration on. An ArrayWUnits value is converted to the dataset’s units; a bare float is taken to be in them already.

traj_namestr, optional

Name for the trajectory BSP file. fit() names the trajectories of later iterations after it.

traj_dirstr, optional

Directory to write trajectory, for this and every later iteration. Defaults to ./data/kernels/scenario/ under the current directory.

overwrite_trajbool

If True, overwrite existing trajectory file.

verbosebool, optional

If False, silence the printout of the propagation run at construction. Defaults to True.

Attributes:
DMC_flag

True when Dynamic Model Compensation (DMC) process noise is active.

SNC_flag

True when State Noise Compensation (SNC) process noise is active.

apriori_covariance_est

Apriori covariance restricted to the estimated parameter subspace.

cost_history

Weighted least-squares cost \(J = \sum_i (r_i/\sigma_i)^2\) of the post-fit residuals of every iteration performed by fit(), as [(J, n_residuals), ...].

covariance_analysis

True when running in covariance-analysis mode (no measurement updates).

covariance_consider_history

Consider-augmented covariance at each measurement epoch (when consider parameters are active).

covariance_history

Posterior covariance at each measurement epoch.

flag_sequence

True for multi-leg (mission-sequence) trajectories.

has_consider

True if consider parameters are present in the state vector.

measurement_data

Container for all measurement datasets, residuals, and editing flags.

measurements

Measurement specification object passed at construction time.

n

Dimension of the estimated state vector.

postfit_residuals

Post-update measurement residuals, keyed by epoch.

prefit_residuals

Pre-update measurement residuals, keyed by epoch.

propagator

Propagator or ScenarioSetup used to build the reference trajectory.

settings

Filter configuration (covariance, process noise, output options).

state_deviation_history

State deviation at each measurement epoch.

trajectory

Propagated reference trajectory stored in a SPICE BSP kernel with a companion JSON file for STMs and estimated parameters.

Methods

fit([traj_name, traj_dir, overwrite_traj, ...])

Perform iterative orbit determination with automatic convergence checking.

observability_test([print_obs, threshold, ...])

Compute the observability and information matrices for the current filter setup.

set_measurement_sigmas(sigmas)

Set the measurement sigma of datasets by name, through their models.

See also

scarabaeus.LKF

Linearized Kalman Filter (sequential, covariance form).

scarabaeus.SRIF

Square Root Information Filter (sequential, square-root form).

scarabaeus.LSB

Batch Least-Squares estimator.

scarabaeus.SRIFB

Batch Square Root Information Filter.

scarabaeus.SolutionOD

Container for the estimated state history and covariance.

Notes

This class is not instantiated directly; use a concrete subclass (LKF, SRIF, LSB, or SRIFB). Call fit() to run the filter and retrieve results via SolutionOD.

References

[1]

Tapley, B. D., Schutz, B. E., & Born, G. H. (2004). Statistical Orbit Determination. Elsevier Academic Press. ISBN 978-0-12-683630-1.

fit(traj_name: str | None = None, traj_dir: str | None = None, overwrite_traj: bool = True, max_iterations: int = 10, convergence_threshold: float = 1e-06, convergence_threshold_cost: float = 0.001, convergence_criterion: str = 'any', verbose: bool = True, if_sequential_smooth: bool = False, callback: Callable | None = None)#

Perform iterative orbit determination with automatic convergence checking.

Runs the filter iteratively, applying state corrections from each solution to the next iteration until convergence or maximum iterations is reached.

Two convergence tests are evaluated at every iteration:

  • State deviation — RMS of the estimated deviation mapped back to the epoch, compared against convergence_threshold. This is the strict test: it declares convergence only when the reference trajectory stops moving.

  • Cost function — relative change of the normalised weighted least-squares cost \(J/n = \sum_i (r_i/\sigma_i)^2 / n\) between consecutive iterations, compared against convergence_threshold_cost. When the problem is weakly observable the deviation keeps wandering along the unobservable directions while the measurement fit no longer improves; the run has converged as far as the data can tell, and only this test detects it.

convergence_criterion selects how the two are combined. The cost is normalised by the number of residuals so that measurement editing (which changes that number between iterations) is not mistaken for a cost change.

Parameters:
traj_namestr, optional

Base name for trajectory files. Iteration number will be appended. If None, the name the filter was built with is the base. Defaults to None.

traj_dirstr, optional

Directory for trajectory files. If None, the directory the filter was built with. Defaults to None.

overwrite_trajbool, optional

Whether to overwrite existing trajectories. Defaults to True.

max_iterationsint, optional

Maximum number of iterations. Defaults to 10.

convergence_thresholdfloat, optional

RMS deviation threshold for convergence. Defaults to 1e-6.

convergence_threshold_costfloat, optional

Threshold on the relative change of the normalised weighted cost \(|\Delta (J/n)| / (J/n)\) between consecutive iterations. Defaults to 1e-3.

convergence_criterionstr, optional

How the two tests are combined:

  • 'any' — converged as soon as either test passes (default).

  • 'deviation' — RMS deviation only (pre-cost-test behaviour).

  • 'cost' — cost-function stagnation only; the criterion of choice for weakly observable problems.

  • 'both' — both tests must pass.

verbosebool, optional

If True, prints iteration progress. Defaults to True.

if_sequential_smoothbool, optional

If True, applies sequential smoothing after filtering. Defaults to False.

callbackcallable, optional

Called as callback(filter, iteration, solution) after every iteration, once its convergence test is done (its outcome is the last entry of _convergence_hist) and before the filter is reinitialized for the next one. Its return value is ignored. It is the place to reweight or edit the data between iterations: a sigma set on a model (set_measurement_sigmas(), or model.sigma = ...) or an outlier flagged through MeasurementSpec.flag takes effect when the datasets are rebuilt for the next iteration, so one made after the last iteration does nothing within this call. Other settings are not guaranteed to be picked up mid-run. Defaults to None.

Returns:
solutionSolutionOD

Final filter solution from the last iteration.

iteration_countint

Number of iterations performed.

convergedbool

Whether convergence was achieved.

Raises:
ConvergenceCriterionError

If convergence_criterion is not one of the accepted values.

NotImplementedError

If if_sequential_smooth=True on a batch filter (LSB, SRIFB).

Notes

The cost is always evaluated on the filter post-fit residuals, also when if_sequential_smooth=True, so the iterations are compared on a like-for-like basis. Its per-iteration history is available as cost_history, and the outcome of the last convergence test as convergence_info. Every iteration’s test is kept in _convergence_hist, which SolutionOD.save() writes to each iter_<k> block.

Reweighting the data from callback changes the scale of the cost, so the cost test of the next iteration compares two differently weighted costs; prefer convergence_criterion='deviation' across a change of sigmas.

Examples

>>> # Automatic iteration with convergence checking
>>> lkf = LKF(propagator, covariance, measurements)
>>> solution, n_iters, converged = lkf.fit(
...     max_iterations=5,
...     convergence_threshold=1e-6
... )
>>> print(f"Converged in {n_iters} iterations: {converged}")
>>> # Weakly observable problem: stop when the fit stops improving
>>> solution, n_iters, converged = lkf.fit(
...     max_iterations=10,
...     convergence_threshold_cost=1e-3,
...     convergence_criterion="cost",
... )
>>> # Loosen the range sigma after the first iteration
>>> def reweight(filt, iteration, solution):
...     if iteration == 1:
...         filt.set_measurement_sigmas({"GS1 Range": ArrayWUnits(5.0, m)})
>>> solution, n_iters, converged = lkf.fit(callback=reweight)
observability_test(print_obs=False, threshold=0.1, meas_corr=None)#

Compute the observability and information matrices for the current filter setup.

The observability matrix \(\mathcal{O}\) is formed by stacking the measurement sensitivity matrices mapped back to the reference epoch \(t_0\) via the State Transition Matrix (STM):

\[\begin{split}\mathcal{O} = \begin{bmatrix} H_1\,\Phi_{1,0} \\ H_2\,\Phi_{2,0} \\ \vdots \\ H_k\,\Phi_{k,0} \end{bmatrix}\end{split}\]

where \(H_k\) is the measurement Jacobian at epoch \(t_k\) and \(\Phi_{k,0}\) is the STM from \(t_0\) to \(t_k\). The system is observable if and only if \(\mathcal{O}\) has full column rank \(n\) (the state dimension).

The information matrix (Fisher information / weighted normal matrix) \(\Lambda\) accumulates the measurement information across all epochs:

\[\Lambda = \sum_{k} H_{k0}^T\, R_k^{-1}\, H_{k0}\]

where \(H_{k0} = H_k\,\Phi_{k,0}\) and \(R_k\) is the measurement noise covariance at epoch \(k\). The system is observable if and only if \(\Lambda\) is positive definite, i.e. all its eigenvalues exceed threshold.

Parameters:
print_obsbool, optional

If True, prints the state dimension, rank of \(\Lambda\), and whether it is strictly positive definite.

thresholdfloat, optional

Minimum eigenvalue threshold used to assess positive definiteness of \(\Lambda\). Defaults to 1e-1.

meas_corrlist, optional

Off-diagonal correlation coefficients for the per-epoch measurement noise covariance \(R_k\). Must be a flat list of \(n_m (n_m - 1) / 2\) values covering the upper triangular part of the correlation matrix in row-major order, where \(n_m\) is the number of simultaneous measurements at each epoch. When None, \(R_k\) is diagonal (measurements assumed uncorrelated).

Returns:
info_matrix, obs_matrixtuple[numpy.ndarray, numpy.ndarray]

A tuple with the following values corresponding to their respective indices:

  • [0] = info_matrixnumpy.ndarray of shape (n, n)

    The information matrix \(\Lambda\).

  • [1] = obs_matrixnumpy.ndarray of shape (m, n)

    The observability matrix \(\mathcal{O}\), where m is the total number of measurements across all epochs.

set_measurement_sigmas(sigmas: Dict[str, ArrayWUnits | float]) → None#

Set the measurement sigma of datasets by name, through their models.

Each sigma is set on the model that built the dataset, so model.sigma reports it and the datasets of every later iteration are built with it, and is written to the dataset’s current sigma column as well. The construction applies settings.measurement_sigmas this way; call it between iterations, from a fit() callback, to reweight the data.

Parameters:
sigmasdict

{dataset_name: sigma}. An ArrayWUnits sigma is converted to the dataset’s units; a bare float is taken to be in them already. One model has one sigma, so the datasets it builds – the components of a two-component measurement, or the entries of a spec that reuse it – share it. A component left out keeps its current sigma; any other dataset of that model must be given the same sigma.

Raises:
UnknownSigmaDatasetError

If a name is not one of the filter’s datasets.

MeasurementSigmaUnitsError

If a sigma cannot be converted to its dataset’s units.

SharedSigmaModelError

If the datasets of one model would be given different sigmas.

Examples

>>> def reweight(filt, iteration, solution):
...     if iteration == 1:
...         filt.set_measurement_sigmas({"GS1 Range": ArrayWUnits(5.0, m)})
>>> solution, n_iters, converged = lkf.fit(callback=reweight)
property DMC_flag: bool#

True when Dynamic Model Compensation (DMC) process noise is active.

property SNC_flag: bool#

True when State Noise Compensation (SNC) process noise is active.

property apriori_covariance_est: ndarray#

Apriori covariance restricted to the estimated parameter subspace.

Returns the (n_est x n_est) block of the full initial covariance matrix corresponding to estimated (non-considered) state variables. When no consider parameters are present the full matrix is returned.

Returns:
np.ndarray

Square apriori covariance of shape (n_est, n_est).

property cost_history: list#

Weighted least-squares cost \(J = \sum_i (r_i/\sigma_i)^2\) of the post-fit residuals of every iteration performed by fit(), as [(J, n_residuals), ...].

property covariance_analysis: bool#

True when running in covariance-analysis mode (no measurement updates).

property covariance_consider_history: list#

Consider-augmented covariance at each measurement epoch (when consider parameters are active). Populated after calling fit().

property covariance_history: list#

Posterior covariance at each measurement epoch. Populated after calling fit().

property flag_sequence: bool#

True for multi-leg (mission-sequence) trajectories.

property has_consider: bool#

True if consider parameters are present in the state vector.

property measurement_data#

Container for all measurement datasets, residuals, and editing flags.

property measurements#

Measurement specification object passed at construction time.

property n: int#

Dimension of the estimated state vector.

property postfit_residuals: dict#

Post-update measurement residuals, keyed by epoch. Populated after calling fit().

property prefit_residuals: dict#

Pre-update measurement residuals, keyed by epoch. Populated after calling fit().

property propagator#

Propagator or ScenarioSetup used to build the reference trajectory. Replaced by a ScenarioSetup when a MissionSequence is provided.

property settings#

Filter configuration (covariance, process noise, output options).

property state_deviation_history: list#

State deviation at each measurement epoch. Populated after calling fit().

property trajectory#

Propagated reference trajectory stored in a SPICE BSP kernel with a companion JSON file for STMs and estimated parameters.

exception AprioriSigmaUnitsError#

Bases: ValueError

Raised when an extra_apriori_sigmas entry cannot be expressed in the units of the state element it initialises.

exception ConvergenceCriterionError#

Bases: ValueError

Raised when an unknown convergence criterion is requested.

exception CovarianceNotPSDWarning#

Bases: RuntimeWarning

Issued when a covariance mapped back across a sequence is not positive semi-definite beyond round-off.

exception DuplicateProcessNoiseBodyError#

Bases: ValueError

Raised when two process noise settings drive the same body.

exception InitialCovarianceSizeError#

Bases: ValueError

Raised when the initial covariance does not match the size of the initial state (the first leg’s on a sequence).

exception MeasurementSigmaUnitsError#

Bases: ValueError

Raised when a measurement sigma cannot be expressed in the units of the dataset it is given for.

exception MissingAprioriSigmaError#

Bases: ValueError

Raised when a newly augmented state has no extra_apriori_sigmas entry.

exception MissingGaussMarkovModelError#

Bases: ValueError

Raised when DMC process noise is used on a leg whose dynamics do not integrate the first-order Gauss-Markov acceleration it drives.

exception NoiseReferenceUnavailableError#

Bases: ValueError

Raised when an RTN process noise drives a body whose reference trajectory is not in the trajectory SPK: on a sequence, any body other than the primary body of each leg.

exception ProcessNoiseBetaMismatchError#

Bases: ValueError

Raised when the DMC beta given in the settings differs from the decay rates of the Gauss-Markov acceleration in the dynamics.

exception SequenceStateDroppedWarning#

Bases: UserWarning

Issued when a sequence leg drops a state the previous leg carried.

Dropping is supported (the state is marginalised at the node and recovered when mapping back), so this is informational; silence it with warnings.filterwarnings("ignore", category=FilterOD.SequenceStateDroppedWarning).

exception SharedSigmaModelError#

Bases: ValueError

Raised when measurement sigmas would give one model two sigmas: the datasets one model builds (its components, or the entries that reuse it) share its sigma, so a sigma given for one of them must hold for all of them.

exception UnknownSigmaDatasetError#

Bases: ValueError

Raised when a measurement sigma names a dataset the filter does not have.

exception UnnoisedBodyWarning#

Bases: UserWarning

Issued when process noise is configured but an estimated, propagated body has none.

Leaving a body noise-free is legitimate, so this is informational; silence it with warnings.filterwarnings("ignore", category=FilterOD.UnnoisedBodyWarning).