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:
objectParent 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 (seeset_measurement_sigmas()). They therefore win over the sigma the model was built with,model.sigmareports them, and the datasets of every later iteration are built with them. The model is the only source: a sigma set on it afterwards (throughset_measurement_sigmas(),MeasurementSpec.editormodel.sigma = ..., e.g. from afit()callback) takes over from the next iteration on. AnArrayWUnitsvalue 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_flagTruewhen Dynamic Model Compensation (DMC) process noise is active.SNC_flagTruewhen State Noise Compensation (SNC) process noise is active.apriori_covariance_estApriori covariance restricted to the estimated parameter subspace.
cost_historyWeighted 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_analysisTruewhen running in covariance-analysis mode (no measurement updates).covariance_consider_historyConsider-augmented covariance at each measurement epoch (when consider parameters are active).
covariance_historyPosterior covariance at each measurement epoch.
flag_sequenceTruefor multi-leg (mission-sequence) trajectories.has_considerTrueif consider parameters are present in the state vector.measurement_dataContainer for all measurement datasets, residuals, and editing flags.
measurementsMeasurement specification object passed at construction time.
nDimension of the estimated state vector.
postfit_residualsPost-update measurement residuals, keyed by epoch.
prefit_residualsPre-update measurement residuals, keyed by epoch.
propagatorPropagator or ScenarioSetup used to build the reference trajectory.
settingsFilter configuration (covariance, process noise, output options).
state_deviation_historyState deviation at each measurement epoch.
trajectoryPropagated 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.LKFLinearized Kalman Filter (sequential, covariance form).
scarabaeus.SRIFSquare Root Information Filter (sequential, square-root form).
scarabaeus.LSBBatch Least-Squares estimator.
scarabaeus.SRIFBBatch Square Root Information Filter.
scarabaeus.SolutionODContainer for the estimated state history and covariance.
Notes
This class is not instantiated directly; use a concrete subclass (
LKF,SRIF,LSB, orSRIFB). Callfit()to run the filter and retrieve results viaSolutionOD.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_criterionselects 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(), ormodel.sigma = ...) or an outlier flagged throughMeasurementSpec.flagtakes 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_criterionis not one of the accepted values.- NotImplementedError
If
if_sequential_smooth=Trueon 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 ascost_history, and the outcome of the last convergence test asconvergence_info. Every iteration’s test is kept in_convergence_hist, whichSolutionOD.save()writes to eachiter_<k>block.Reweighting the data from
callbackchanges the scale of the cost, so the cost test of the next iteration compares two differently weighted costs; preferconvergence_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
mis 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.sigmareports it and the datasets of every later iteration are built with it, and is written to the dataset’s currentsigmacolumn as well. The construction appliessettings.measurement_sigmasthis way; call it between iterations, from afit()callback, to reweight the data.- Parameters:
- sigmasdict
{dataset_name: sigma}. AnArrayWUnitssigma 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 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#
Truewhen 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 measurement_data#
Container for all measurement datasets, residuals, and editing flags.
- property measurements#
Measurement specification object passed at construction time.
- 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
ScenarioSetupwhen aMissionSequenceis 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:
ValueErrorRaised when an
extra_apriori_sigmasentry cannot be expressed in the units of the state element it initialises.
- exception ConvergenceCriterionError#
Bases:
ValueErrorRaised when an unknown convergence criterion is requested.
- exception CovarianceNotPSDWarning#
Bases:
RuntimeWarningIssued when a covariance mapped back across a sequence is not positive semi-definite beyond round-off.
- exception DuplicateProcessNoiseBodyError#
Bases:
ValueErrorRaised when two process noise settings drive the same body.
- exception InitialCovarianceSizeError#
Bases:
ValueErrorRaised when the initial covariance does not match the size of the initial state (the first leg’s on a sequence).
- exception MeasurementSigmaUnitsError#
Bases:
ValueErrorRaised when a measurement sigma cannot be expressed in the units of the dataset it is given for.
- exception MissingAprioriSigmaError#
Bases:
ValueErrorRaised when a newly augmented state has no
extra_apriori_sigmasentry.
- exception MissingGaussMarkovModelError#
Bases:
ValueErrorRaised when DMC process noise is used on a leg whose dynamics do not integrate the first-order Gauss-Markov acceleration it drives.
Bases:
ValueErrorRaised 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:
ValueErrorRaised when the DMC
betagiven in the settings differs from the decay rates of the Gauss-Markov acceleration in the dynamics.
- exception SequenceStateDroppedWarning#
Bases:
UserWarningIssued 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).
Bases:
ValueErrorRaised 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:
ValueErrorRaised when a measurement sigma names a dataset the filter does not have.
- exception UnnoisedBodyWarning#
Bases:
UserWarningIssued 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).