KalmanModel.java

  1. /* Copyright 2002-2024 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.estimation.sequential;

  18. import org.hipparchus.filtering.kalman.ProcessEstimate;
  19. import org.hipparchus.filtering.kalman.extended.NonLinearEvolution;
  20. import org.hipparchus.filtering.kalman.extended.NonLinearProcess;
  21. import org.hipparchus.linear.Array2DRowRealMatrix;
  22. import org.hipparchus.linear.MatrixUtils;
  23. import org.hipparchus.linear.RealMatrix;
  24. import org.hipparchus.linear.RealVector;
  25. import org.orekit.estimation.measurements.EstimatedMeasurement;
  26. import org.orekit.estimation.measurements.ObservedMeasurement;
  27. import org.orekit.orbits.Orbit;
  28. import org.orekit.propagation.MatricesHarvester;
  29. import org.orekit.propagation.Propagator;
  30. import org.orekit.propagation.SpacecraftState;
  31. import org.orekit.propagation.conversion.PropagatorBuilder;
  32. import org.orekit.time.AbsoluteDate;
  33. import org.orekit.utils.ParameterDriver;
  34. import org.orekit.utils.ParameterDriversList;
  35. import org.orekit.utils.ParameterDriversList.DelegatingDriver;

  36. import java.util.List;
  37. import java.util.Map;

  38. /** Class defining the process model dynamics to use with a {@link KalmanEstimator}.
  39.  * @author Romain Gerbaud
  40.  * @author Maxime Journot
  41.  * @since 9.2
  42.  */
  43. public class KalmanModel extends KalmanEstimationCommon implements NonLinearProcess<MeasurementDecorator> {


  44.     /** Harvesters for extracting Jacobians from integrated states. */
  45.     private MatricesHarvester[] harvesters;

  46.     /** Propagators for the reference trajectories, up to current date. */
  47.     private Propagator[] referenceTrajectories;

  48.     /** Kalman process model constructor.
  49.      * @param propagatorBuilders propagators builders used to evaluate the orbits.
  50.      * @param covarianceMatricesProviders providers for covariance matrices
  51.      * @param estimatedMeasurementParameters measurement parameters to estimate
  52.      * @param measurementProcessNoiseMatrix provider for measurement process noise matrix
  53.      */
  54.     public KalmanModel(final List<PropagatorBuilder> propagatorBuilders,
  55.                        final List<CovarianceMatrixProvider> covarianceMatricesProviders,
  56.                        final ParameterDriversList estimatedMeasurementParameters,
  57.                        final CovarianceMatrixProvider measurementProcessNoiseMatrix) {
  58.         super(propagatorBuilders, covarianceMatricesProviders, estimatedMeasurementParameters, measurementProcessNoiseMatrix);
  59.         // Build the reference propagators and add their partial derivatives equations implementation
  60.         updateReferenceTrajectories(getEstimatedPropagators());
  61.     }

  62.     /** Update the reference trajectories using the propagators as input.
  63.      * @param propagators The new propagators to use
  64.      */
  65.     protected void updateReferenceTrajectories(final Propagator[] propagators) {

  66.         // Update the reference trajectory propagator
  67.         setReferenceTrajectories(propagators);

  68.         // Jacobian harvesters
  69.         harvesters = new MatricesHarvester[propagators.length];

  70.         for (int k = 0; k < propagators.length; ++k) {
  71.             // Link the partial derivatives to this new propagator
  72.             final String equationName = KalmanEstimator.class.getName() + "-derivatives-" + k;
  73.             harvesters[k] = getReferenceTrajectories()[k].setupMatricesComputation(equationName, null, null);
  74.         }

  75.     }

  76.     /** Get the normalized error state transition matrix (STM) from previous point to current point.
  77.      * The STM contains the partial derivatives of current state with respect to previous state.
  78.      * The  STM is an mxm matrix where m is the size of the state vector.
  79.      * m = nbOrb + nbPropag + nbMeas
  80.      * @return the normalized error state transition matrix
  81.      */
  82.     private RealMatrix getErrorStateTransitionMatrix() {

  83.         /* The state transition matrix is obtained as follows, with:
  84.          *  - Y  : Current state vector
  85.          *  - Y0 : Initial state vector
  86.          *  - Pp : Current propagation parameter
  87.          *  - Pp0: Initial propagation parameter
  88.          *  - Mp : Current measurement parameter
  89.          *  - Mp0: Initial measurement parameter
  90.          *
  91.          *       |        |         |         |   |        |        |   .    |
  92.          *       | dY/dY0 | dY/dPp  | dY/dMp  |   | dY/dY0 | dY/dPp | ..0..  |
  93.          *       |        |         |         |   |        |        |   .    |
  94.          *       |--------|---------|---------|   |--------|--------|--------|
  95.          *       |        |         |         |   |   .    | 1 0 0..|   .    |
  96.          * STM = | dP/dY0 | dP/dPp0 | dP/dMp  | = | ..0..  | 0 1 0..| ..0..  |
  97.          *       |        |         |         |   |   .    | 0 0 1..|   .    |
  98.          *       |--------|---------|---------|   |--------|--------|--------|
  99.          *       |        |         |         |   |   .    |   .    | 1 0 0..|
  100.          *       | dM/dY0 | dM/dPp0 | dM/dMp0 |   | ..0..  | ..0..  | 0 1 0..|
  101.          *       |        |         |         |   |   .    |   .    | 0 0 1..|
  102.          */

  103.         // Initialize to the proper size identity matrix
  104.         final RealMatrix stm = MatrixUtils.createRealIdentityMatrix(getCorrectedEstimate().getState().getDimension());

  105.         // loop over all orbits
  106.         final SpacecraftState[] predictedSpacecraftStates = getPredictedSpacecraftStates();
  107.         final int[][] covarianceIndirection = getCovarianceIndirection();
  108.         final ParameterDriversList[] estimatedOrbitalParameters = getEstimatedOrbitalParametersArray();
  109.         final ParameterDriversList[] estimatedPropagationParameters = getEstimatedPropagationParametersArray();
  110.         final double[] scale = getScale();
  111.         for (int k = 0; k < predictedSpacecraftStates.length; ++k) {

  112.             // Indexes
  113.             final int[] indK = covarianceIndirection[k];

  114.             // Derivatives of the state vector with respect to initial state vector
  115.             final int nbOrbParams = estimatedOrbitalParameters[k].getNbParams();
  116.             if (nbOrbParams > 0) {

  117.                 // Reset reference (for example compute short periodic terms in DSST)
  118.                 harvesters[k].setReferenceState(predictedSpacecraftStates[k]);

  119.                 final RealMatrix dYdY0 = harvesters[k].getStateTransitionMatrix(predictedSpacecraftStates[k]);

  120.                 // Fill upper left corner (dY/dY0)
  121.                 for (int i = 0; i < dYdY0.getRowDimension(); ++i) {
  122.                     for (int j = 0; j < nbOrbParams; ++j) {
  123.                         stm.setEntry(indK[i], indK[j], dYdY0.getEntry(i, j));
  124.                     }
  125.                 }
  126.             }

  127.             // Derivatives of the state vector with respect to propagation parameters
  128.             final int nbParams = estimatedPropagationParameters[k].getNbParams();
  129.             if (nbParams > 0) {
  130.                 final RealMatrix dYdPp = harvesters[k].getParametersJacobian(predictedSpacecraftStates[k]);

  131.                 // Fill 1st row, 2nd column (dY/dPp)
  132.                 for (int i = 0; i < dYdPp.getRowDimension(); ++i) {
  133.                     for (int j = 0; j < nbParams; ++j) {
  134.                         stm.setEntry(indK[i], indK[j + 6], dYdPp.getEntry(i, j));
  135.                     }
  136.                 }

  137.             }

  138.         }

  139.         // Normalization of the STM
  140.         // normalized(STM)ij = STMij*Sj/Si
  141.         for (int i = 0; i < scale.length; i++) {
  142.             for (int j = 0; j < scale.length; j++ ) {
  143.                 stm.setEntry(i, j, stm.getEntry(i, j) * scale[j] / scale[i]);
  144.             }
  145.         }

  146.         // Return the error state transition matrix
  147.         return stm;

  148.     }

  149.     /** Get the normalized measurement matrix H.
  150.      * H contains the partial derivatives of the measurement with respect to the state.
  151.      * H is an nxm matrix where n is the size of the measurement vector and m the size of the state vector.
  152.      * @return the normalized measurement matrix H
  153.      */
  154.     private RealMatrix getMeasurementMatrix() {

  155.         // Observed measurement characteristics
  156.         final EstimatedMeasurement<?> predictedMeasurement = getPredictedMeasurement();
  157.         final SpacecraftState[]      evaluationStates    = predictedMeasurement.getStates();
  158.         final ObservedMeasurement<?> observedMeasurement = predictedMeasurement.getObservedMeasurement();
  159.         final double[] sigma  = observedMeasurement.getTheoreticalStandardDeviation();

  160.         // Initialize measurement matrix H: nxm
  161.         // n: Number of measurements in current measurement
  162.         // m: State vector size
  163.         final RealMatrix measurementMatrix = MatrixUtils.
  164.                         createRealMatrix(observedMeasurement.getDimension(),
  165.                                          getCorrectedEstimate().getState().getDimension());

  166.         // loop over all orbits involved in the measurement
  167.         final int[] orbitsStartColumns = getOrbitsStartColumns();
  168.         final ParameterDriversList[] estimatedPropagationParameters = getEstimatedPropagationParametersArray();
  169.         final Map<String, Integer> propagationParameterColumns = getPropagationParameterColumns();
  170.         final Map<String, Integer> measurementParameterColumns = getMeasurementParameterColumns();
  171.         for (int k = 0; k < evaluationStates.length; ++k) {
  172.             final int p = observedMeasurement.getSatellites().get(k).getPropagatorIndex();

  173.             // Predicted orbit
  174.             final Orbit predictedOrbit = evaluationStates[k].getOrbit();

  175.             // Measurement matrix's columns related to orbital parameters
  176.             // ----------------------------------------------------------

  177.             // Partial derivatives of the current Cartesian coordinates with respect to current orbital state
  178.             final double[][] aCY = new double[6][6];
  179.             predictedOrbit.getJacobianWrtParameters(getBuilders().get(p).getPositionAngleType(), aCY);   //dC/dY
  180.             final RealMatrix dCdY = new Array2DRowRealMatrix(aCY, false);

  181.             // Jacobian of the measurement with respect to current Cartesian coordinates
  182.             final RealMatrix dMdC = new Array2DRowRealMatrix(predictedMeasurement.getStateDerivatives(k), false);

  183.             // Jacobian of the measurement with respect to current orbital state
  184.             final RealMatrix dMdY = dMdC.multiply(dCdY);

  185.             // Fill the normalized measurement matrix's columns related to estimated orbital parameters
  186.             for (int i = 0; i < dMdY.getRowDimension(); ++i) {
  187.                 int jOrb = orbitsStartColumns[p];
  188.                 for (int j = 0; j < dMdY.getColumnDimension(); ++j) {
  189.                     final ParameterDriver driver = getBuilders().get(p).getOrbitalParametersDrivers().getDrivers().get(j);
  190.                     if (driver.isSelected()) {
  191.                         measurementMatrix.setEntry(i, jOrb++,
  192.                                                    dMdY.getEntry(i, j) / sigma[i] * driver.getScale());
  193.                     }
  194.                 }
  195.             }

  196.             // Normalized measurement matrix's columns related to propagation parameters
  197.             // --------------------------------------------------------------

  198.             // Jacobian of the measurement with respect to propagation parameters
  199.             final int nbParams = estimatedPropagationParameters[p].getNbParams();
  200.             if (nbParams > 0) {
  201.                 final RealMatrix dYdPp = harvesters[p].getParametersJacobian(evaluationStates[k]);
  202.                 final RealMatrix dMdPp = dMdY.multiply(dYdPp);
  203.                 for (int i = 0; i < dMdPp.getRowDimension(); ++i) {
  204.                     for (int j = 0; j < nbParams; ++j) {
  205.                         final ParameterDriver delegating = estimatedPropagationParameters[p].getDrivers().get(j);
  206.                         measurementMatrix.setEntry(i, propagationParameterColumns.get(delegating.getName()),
  207.                                                    dMdPp.getEntry(i, j) / sigma[i] * delegating.getScale());
  208.                     }
  209.                 }
  210.             }

  211.             // Normalized measurement matrix's columns related to measurement parameters
  212.             // --------------------------------------------------------------

  213.             // Jacobian of the measurement with respect to measurement parameters
  214.             // Gather the measurement parameters linked to current measurement
  215.             for (final ParameterDriver driver : observedMeasurement.getParametersDrivers()) {
  216.                 if (driver.isSelected()) {
  217.                     // Derivatives of current measurement w/r to selected measurement parameter
  218.                     final double[] aMPm = predictedMeasurement.getParameterDerivatives(driver);

  219.                     // Check that the measurement parameter is managed by the filter
  220.                     if (measurementParameterColumns.get(driver.getName()) != null) {
  221.                         // Column of the driver in the measurement matrix
  222.                         final int driverColumn = measurementParameterColumns.get(driver.getName());

  223.                         // Fill the corresponding indexes of the measurement matrix
  224.                         for (int i = 0; i < aMPm.length; ++i) {
  225.                             measurementMatrix.setEntry(i, driverColumn,
  226.                                                        aMPm[i] / sigma[i] * driver.getScale());
  227.                         }
  228.                     }
  229.                 }
  230.             }
  231.         }

  232.         // Return the normalized measurement matrix
  233.         return measurementMatrix;

  234.     }

  235.     /** {@inheritDoc} */
  236.     @Override
  237.     public NonLinearEvolution getEvolution(final double previousTime, final RealVector previousState,
  238.                                            final MeasurementDecorator measurement) {

  239.         // Set a reference date for all measurements parameters that lack one (including the not estimated ones)
  240.         final ObservedMeasurement<?> observedMeasurement = measurement.getObservedMeasurement();
  241.         for (final ParameterDriver driver : observedMeasurement.getParametersDrivers()) {
  242.             if (driver.getReferenceDate() == null) {
  243.                 driver.setReferenceDate(getBuilders().get(0).getInitialOrbitDate());
  244.             }
  245.         }

  246.         incrementCurrentMeasurementNumber();
  247.         setCurrentDate(measurement.getObservedMeasurement().getDate());

  248.         // Note:
  249.         // - n = size of the current measurement
  250.         //  Example:
  251.         //   * 1 for Range, RangeRate and TurnAroundRange
  252.         //   * 2 for Angular (Azimuth/Elevation or Right-ascension/Declination)
  253.         //   * 6 for Position/Velocity
  254.         // - m = size of the state vector. n = nbOrb + nbPropag + nbMeas

  255.         // Predict the state vector (mx1)
  256.         final RealVector predictedState = predictState(observedMeasurement.getDate());

  257.         // Get the error state transition matrix (mxm)
  258.         final RealMatrix stateTransitionMatrix = getErrorStateTransitionMatrix();

  259.         // Predict the measurement based on predicted spacecraft state
  260.         // Compute the innovations (i.e. residuals of the predicted measurement)
  261.         // ------------------------------------------------------------

  262.         // Predicted measurement
  263.         // Note: here the "iteration/evaluation" formalism from the batch LS method
  264.         // is twisted to fit the need of the Kalman filter.
  265.         // The number of "iterations" is actually the number of measurements processed by the filter
  266.         // so far. We use this to be able to apply the OutlierFilter modifiers on the predicted measurement.
  267.         setPredictedMeasurement(observedMeasurement.estimate(getCurrentMeasurementNumber(),
  268.                                                              getCurrentMeasurementNumber(),
  269.                                                              KalmanEstimatorUtil.filterRelevant(observedMeasurement, getPredictedSpacecraftStates())));

  270.         // Normalized measurement matrix (nxm)
  271.         final RealMatrix measurementMatrix = getMeasurementMatrix();

  272.         // compute process noise matrix
  273.         final RealMatrix normalizedProcessNoise = getNormalizedProcessNoise(previousState.getDimension());

  274.         return new NonLinearEvolution(measurement.getTime(), predictedState,
  275.                                       stateTransitionMatrix, normalizedProcessNoise, measurementMatrix);

  276.     }


  277.     /** {@inheritDoc} */
  278.     @Override
  279.     public RealVector getInnovation(final MeasurementDecorator measurement, final NonLinearEvolution evolution,
  280.                                     final RealMatrix innovationCovarianceMatrix) {

  281.         // Apply the dynamic outlier filter, if it exists
  282.         final EstimatedMeasurement<?> predictedMeasurement = getPredictedMeasurement();
  283.         KalmanEstimatorUtil.applyDynamicOutlierFilter(predictedMeasurement, innovationCovarianceMatrix);
  284.         // Compute the innovation vector
  285.         return KalmanEstimatorUtil.computeInnovationVector(predictedMeasurement, predictedMeasurement.getObservedMeasurement().getTheoreticalStandardDeviation());
  286.     }

  287.     /** Finalize estimation.
  288.      * @param observedMeasurement measurement that has just been processed
  289.      * @param estimate corrected estimate
  290.      */
  291.     public void finalizeEstimation(final ObservedMeasurement<?> observedMeasurement,
  292.                                    final ProcessEstimate estimate) {
  293.         // Update the parameters with the estimated state
  294.         // The min/max values of the parameters are handled by the ParameterDriver implementation
  295.         setCorrectedEstimate(estimate);
  296.         updateParameters();

  297.         // Get the estimated propagator (mirroring parameter update in the builder)
  298.         // and the estimated spacecraft state
  299.         final Propagator[] estimatedPropagators = getEstimatedPropagators();
  300.         for (int k = 0; k < estimatedPropagators.length; ++k) {
  301.             setCorrectedSpacecraftState(estimatedPropagators[k].getInitialState(), k);
  302.         }

  303.         // Compute the estimated measurement using estimated spacecraft state
  304.         setCorrectedMeasurement(observedMeasurement.estimate(getCurrentMeasurementNumber(),
  305.                                                              getCurrentMeasurementNumber(),
  306.                                                              KalmanEstimatorUtil.filterRelevant(observedMeasurement, getCorrectedSpacecraftStates())));
  307.         // Update the trajectory
  308.         // ---------------------
  309.         updateReferenceTrajectories(estimatedPropagators);

  310.     }

  311.     /** Set the predicted normalized state vector.
  312.      * The predicted/propagated orbit is used to update the state vector
  313.      * @param date prediction date
  314.      * @return predicted state
  315.      */
  316.     private RealVector predictState(final AbsoluteDate date) {

  317.         // Predicted state is initialized to previous estimated state
  318.         final RealVector predictedState = getCorrectedEstimate().getState().copy();

  319.         // Orbital parameters counter
  320.         int jOrb = 0;

  321.         for (int k = 0; k < getPredictedSpacecraftStates().length; ++k) {

  322.             // Propagate the reference trajectory to measurement date
  323.             final SpacecraftState predictedSpacecraftState = referenceTrajectories[k].propagate(date);
  324.             setPredictedSpacecraftState(predictedSpacecraftState, k);

  325.             // Update the builder with the predicted orbit
  326.             // This updates the orbital drivers with the values of the predicted orbit
  327.             getBuilders().get(k).resetOrbit(predictedSpacecraftState.getOrbit());

  328.             // The orbital parameters in the state vector are replaced with their predicted values
  329.             // The propagation & measurement parameters are not changed by the prediction (i.e. the propagation)
  330.             // As the propagator builder was previously updated with the predicted orbit,
  331.             // the selected orbital drivers are already up to date with the prediction
  332.             for (DelegatingDriver orbitalDriver : getBuilders().get(k).getOrbitalParametersDrivers().getDrivers()) {
  333.                 if (orbitalDriver.isSelected()) {
  334.                     predictedState.setEntry(jOrb++, orbitalDriver.getNormalizedValue());
  335.                 }
  336.             }

  337.         }

  338.         return predictedState;

  339.     }

  340.     /** Update the estimated parameters after the correction phase of the filter.
  341.      * The min/max allowed values are handled by the parameter themselves.
  342.      */
  343.     private void updateParameters() {
  344.         final RealVector correctedState = getCorrectedEstimate().getState();
  345.         int i = 0;
  346.         for (final DelegatingDriver driver : getEstimatedOrbitalParameters().getDrivers()) {
  347.             // let the parameter handle min/max clipping
  348.             driver.setNormalizedValue(correctedState.getEntry(i));
  349.             correctedState.setEntry(i++, driver.getNormalizedValue());
  350.         }
  351.         for (final DelegatingDriver driver : getEstimatedPropagationParameters().getDrivers()) {
  352.             // let the parameter handle min/max clipping
  353.             driver.setNormalizedValue(correctedState.getEntry(i));
  354.             correctedState.setEntry(i++, driver.getNormalizedValue());
  355.         }
  356.         for (final DelegatingDriver driver : getEstimatedMeasurementsParameters().getDrivers()) {
  357.             // let the parameter handle min/max clipping
  358.             driver.setNormalizedValue(correctedState.getEntry(i));
  359.             correctedState.setEntry(i++, driver.getNormalizedValue());
  360.         }
  361.     }

  362.     /** Getter for the reference trajectories.
  363.      * @return the referencetrajectories
  364.      */
  365.     public Propagator[] getReferenceTrajectories() {
  366.         return referenceTrajectories.clone();
  367.     }

  368.     /** Setter for the reference trajectories.
  369.      * @param referenceTrajectories the reference trajectories to be setted
  370.      */
  371.     public void setReferenceTrajectories(final Propagator[] referenceTrajectories) {
  372.         this.referenceTrajectories = referenceTrajectories.clone();
  373.     }

  374. }