SemiAnalyticalKalmanModel.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.exception.MathRuntimeException;
  19. import org.hipparchus.filtering.kalman.ProcessEstimate;
  20. import org.hipparchus.filtering.kalman.extended.ExtendedKalmanFilter;
  21. import org.hipparchus.filtering.kalman.extended.NonLinearEvolution;
  22. import org.hipparchus.filtering.kalman.extended.NonLinearProcess;
  23. import org.hipparchus.linear.Array2DRowRealMatrix;
  24. import org.hipparchus.linear.ArrayRealVector;
  25. import org.hipparchus.linear.MatrixUtils;
  26. import org.hipparchus.linear.QRDecomposition;
  27. import org.hipparchus.linear.RealMatrix;
  28. import org.hipparchus.linear.RealVector;
  29. import org.hipparchus.util.FastMath;
  30. import org.orekit.errors.OrekitException;
  31. import org.orekit.estimation.measurements.EstimatedMeasurement;
  32. import org.orekit.estimation.measurements.ObservedMeasurement;
  33. import org.orekit.orbits.Orbit;
  34. import org.orekit.orbits.OrbitType;
  35. import org.orekit.propagation.PropagationType;
  36. import org.orekit.propagation.SpacecraftState;
  37. import org.orekit.propagation.conversion.DSSTPropagatorBuilder;
  38. import org.orekit.propagation.semianalytical.dsst.DSSTHarvester;
  39. import org.orekit.propagation.semianalytical.dsst.DSSTPropagator;
  40. import org.orekit.propagation.semianalytical.dsst.forces.DSSTForceModel;
  41. import org.orekit.propagation.semianalytical.dsst.forces.ShortPeriodTerms;
  42. import org.orekit.propagation.semianalytical.dsst.utilities.AuxiliaryElements;
  43. import org.orekit.time.AbsoluteDate;
  44. import org.orekit.time.ChronologicalComparator;
  45. import org.orekit.utils.ParameterDriver;
  46. import org.orekit.utils.ParameterDriversList;
  47. import org.orekit.utils.ParameterDriversList.DelegatingDriver;
  48. import org.orekit.utils.TimeSpanMap.Span;

  49. import java.util.ArrayList;
  50. import java.util.Comparator;
  51. import java.util.HashMap;
  52. import java.util.List;
  53. import java.util.Map;

  54. /** Process model to use with a {@link SemiAnalyticalKalmanEstimator}.
  55.  *
  56.  * @see "Folcik Z., Orbit Determination Using Modern Filters/Smoothers and Continuous Thrust Modeling,
  57.  *       Master of Science Thesis, Department of Aeronautics and Astronautics, MIT, June, 2008."
  58.  *
  59.  * @see "Cazabonne B., Bayard J., Journot M., and Cefola P. J., A Semi-analytical Approach for Orbit
  60.  *       Determination based on Extended Kalman Filter, AAS Paper 21-614, AAS/AIAA Astrodynamics
  61.  *       Specialist Conference, Big Sky, August 2021."
  62.  *
  63.  * @author Julie Bayard
  64.  * @author Bryan Cazabonne
  65.  * @author Maxime Journot
  66.  * @since 11.1
  67.  */
  68. public  class SemiAnalyticalKalmanModel implements KalmanEstimation, NonLinearProcess<MeasurementDecorator>, SemiAnalyticalProcess {

  69.     /** Builders for DSST propagator. */
  70.     private final DSSTPropagatorBuilder builder;

  71.     /** Estimated orbital parameters. */
  72.     private final ParameterDriversList estimatedOrbitalParameters;

  73.     /** Per-builder estimated propagation drivers. */
  74.     private final ParameterDriversList estimatedPropagationParameters;

  75.     /** Estimated measurements parameters. */
  76.     private final ParameterDriversList estimatedMeasurementsParameters;

  77.     /** Map for propagation parameters columns. */
  78.     private final Map<String, Integer> propagationParameterColumns;

  79.     /** Map for measurements parameters columns. */
  80.     private final Map<String, Integer> measurementParameterColumns;

  81.     /** Scaling factors. */
  82.     private final double[] scale;

  83.     /** Provider for covariance matrix. */
  84.     private final CovarianceMatrixProvider covarianceMatrixProvider;

  85.     /** Process noise matrix provider for measurement parameters. */
  86.     private final CovarianceMatrixProvider measurementProcessNoiseMatrix;

  87.     /** Harvester between two-dimensional Jacobian matrices and one-dimensional additional state arrays. */
  88.     private DSSTHarvester harvester;

  89.     /** Propagators for the reference trajectories, up to current date. */
  90.     private DSSTPropagator dsstPropagator;

  91.     /** Observer to retrieve current estimation info. */
  92.     private KalmanObserver observer;

  93.     /** Current number of measurement. */
  94.     private int currentMeasurementNumber;

  95.     /** Current date. */
  96.     private AbsoluteDate currentDate;

  97.     /** Predicted mean element filter correction. */
  98.     private RealVector predictedFilterCorrection;

  99.     /** Corrected mean element filter correction. */
  100.     private RealVector correctedFilterCorrection;

  101.     /** Predicted measurement. */
  102.     private EstimatedMeasurement<?> predictedMeasurement;

  103.     /** Corrected measurement. */
  104.     private EstimatedMeasurement<?> correctedMeasurement;

  105.     /** Nominal mean spacecraft state. */
  106.     private SpacecraftState nominalMeanSpacecraftState;

  107.     /** Previous nominal mean spacecraft state. */
  108.     private SpacecraftState previousNominalMeanSpacecraftState;

  109.     /** Current corrected estimate. */
  110.     private ProcessEstimate correctedEstimate;

  111.     /** Inverse of the orbital part of the state transition matrix. */
  112.     private RealMatrix phiS;

  113.     /** Propagation parameters part of the state transition matrix. */
  114.     private RealMatrix psiS;

  115.     /** Kalman process model constructor (package private).
  116.      * @param propagatorBuilder propagators builders used to evaluate the orbits.
  117.      * @param covarianceMatrixProvider provider for covariance matrix
  118.      * @param estimatedMeasurementParameters measurement parameters to estimate
  119.      * @param measurementProcessNoiseMatrix provider for measurement process noise matrix
  120.      */
  121.     protected SemiAnalyticalKalmanModel(final DSSTPropagatorBuilder propagatorBuilder,
  122.                                         final CovarianceMatrixProvider covarianceMatrixProvider,
  123.                                         final ParameterDriversList estimatedMeasurementParameters,
  124.                                         final CovarianceMatrixProvider measurementProcessNoiseMatrix) {

  125.         this.builder                         = propagatorBuilder;
  126.         this.estimatedMeasurementsParameters = estimatedMeasurementParameters;
  127.         this.measurementParameterColumns     = new HashMap<>(estimatedMeasurementsParameters.getDrivers().size());
  128.         this.observer                        = null;
  129.         this.currentMeasurementNumber        = 0;
  130.         this.currentDate                     = propagatorBuilder.getInitialOrbitDate();
  131.         this.covarianceMatrixProvider        = covarianceMatrixProvider;
  132.         this.measurementProcessNoiseMatrix   = measurementProcessNoiseMatrix;

  133.         // Number of estimated parameters
  134.         int columns = 0;

  135.         // Set estimated orbital parameters
  136.         estimatedOrbitalParameters = new ParameterDriversList();
  137.         for (final ParameterDriver driver : builder.getOrbitalParametersDrivers().getDrivers()) {

  138.             // Verify if the driver reference date has been set
  139.             if (driver.getReferenceDate() == null) {
  140.                 driver.setReferenceDate(currentDate);
  141.             }

  142.             // Verify if the driver is selected
  143.             if (driver.isSelected()) {
  144.                 estimatedOrbitalParameters.add(driver);
  145.                 columns++;
  146.             }

  147.         }

  148.         // Set estimated propagation parameters
  149.         estimatedPropagationParameters = new ParameterDriversList();
  150.         final List<String> estimatedPropagationParametersNames = new ArrayList<>();
  151.         for (final ParameterDriver driver : builder.getPropagationParametersDrivers().getDrivers()) {

  152.             // Verify if the driver reference date has been set
  153.             if (driver.getReferenceDate() == null) {
  154.                 driver.setReferenceDate(currentDate);
  155.             }

  156.             // Verify if the driver is selected
  157.             if (driver.isSelected()) {
  158.                 estimatedPropagationParameters.add(driver);
  159.                 // Add the driver name if it has not been added yet
  160.                 for (Span<String> span = driver.getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {

  161.                     if (!estimatedPropagationParametersNames.contains(span.getData())) {
  162.                         estimatedPropagationParametersNames.add(span.getData());
  163.                     }
  164.                 }
  165.             }

  166.         }
  167.         estimatedPropagationParametersNames.sort(Comparator.naturalOrder());

  168.         // Populate the map of propagation drivers' columns and update the total number of columns
  169.         propagationParameterColumns = new HashMap<>(estimatedPropagationParametersNames.size());
  170.         for (final String driverName : estimatedPropagationParametersNames) {
  171.             propagationParameterColumns.put(driverName, columns);
  172.             ++columns;
  173.         }

  174.         // Set the estimated measurement parameters
  175.         for (final ParameterDriver parameter : estimatedMeasurementsParameters.getDrivers()) {
  176.             if (parameter.getReferenceDate() == null) {
  177.                 parameter.setReferenceDate(currentDate);
  178.             }
  179.             for (Span<String> span = parameter.getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {
  180.                 measurementParameterColumns.put(span.getData(), columns);
  181.                 ++columns;
  182.             }
  183.         }

  184.         // Compute the scale factors
  185.         this.scale = new double[columns];
  186.         int index = 0;
  187.         for (final ParameterDriver driver : estimatedOrbitalParameters.getDrivers()) {
  188.             scale[index++] = driver.getScale();
  189.         }
  190.         for (final ParameterDriver driver : estimatedPropagationParameters.getDrivers()) {
  191.             for (Span<String> span = driver.getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {
  192.                 scale[index++] = driver.getScale();
  193.             }
  194.         }
  195.         for (final ParameterDriver driver : estimatedMeasurementsParameters.getDrivers()) {
  196.             for (Span<String> span = driver.getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {
  197.                 scale[index++] = driver.getScale();
  198.             }
  199.         }

  200.         // Build the reference propagator and add its partial derivatives equations implementation
  201.         updateReferenceTrajectory(getEstimatedPropagator());
  202.         this.nominalMeanSpacecraftState = dsstPropagator.getInitialState();
  203.         this.previousNominalMeanSpacecraftState = nominalMeanSpacecraftState;

  204.         // Initialize "field" short periodic terms
  205.         harvester.initializeFieldShortPeriodTerms(nominalMeanSpacecraftState);

  206.         // Initialize the estimated normalized mean element filter correction (See Ref [1], Eq. 3.2a)
  207.         this.predictedFilterCorrection = MatrixUtils.createRealVector(columns);
  208.         this.correctedFilterCorrection = predictedFilterCorrection;

  209.         // Initialize propagation parameters part of the state transition matrix (See Ref [1], Eq. 3.2c)
  210.         this.psiS = null;
  211.         if (estimatedPropagationParameters.getNbParams() != 0) {
  212.             this.psiS = MatrixUtils.createRealMatrix(getNumberSelectedOrbitalDriversValuesToEstimate(),
  213.                                                      getNumberSelectedPropagationDriversValuesToEstimate());
  214.         }

  215.         // Initialize inverse of the orbital part of the state transition matrix (See Ref [1], Eq. 3.2d)
  216.         this.phiS = MatrixUtils.createRealIdentityMatrix(getNumberSelectedOrbitalDriversValuesToEstimate());

  217.         // Number of estimated measurement parameters
  218.         final int nbMeas = getNumberSelectedMeasurementDriversValuesToEstimate();

  219.         // Number of estimated dynamic parameters (orbital + propagation)
  220.         final int nbDyn  = getNumberSelectedOrbitalDriversValuesToEstimate() + getNumberSelectedPropagationDriversValuesToEstimate();

  221.         // Covariance matrix
  222.         final RealMatrix noiseK = MatrixUtils.createRealMatrix(nbDyn + nbMeas, nbDyn + nbMeas);
  223.         final RealMatrix noiseP = covarianceMatrixProvider.getInitialCovarianceMatrix(nominalMeanSpacecraftState);
  224.         noiseK.setSubMatrix(noiseP.getData(), 0, 0);
  225.         if (measurementProcessNoiseMatrix != null) {
  226.             final RealMatrix noiseM = measurementProcessNoiseMatrix.getInitialCovarianceMatrix(nominalMeanSpacecraftState);
  227.             noiseK.setSubMatrix(noiseM.getData(), nbDyn, nbDyn);
  228.         }

  229.         // Verify dimension
  230.         KalmanEstimatorUtil.checkDimension(noiseK.getRowDimension(),
  231.                                            builder.getOrbitalParametersDrivers(),
  232.                                            builder.getPropagationParametersDrivers(),
  233.                                            estimatedMeasurementsParameters);

  234.         final RealMatrix correctedCovariance = KalmanEstimatorUtil.normalizeCovarianceMatrix(noiseK, scale);

  235.         // Initialize corrected estimate
  236.         this.correctedEstimate = new ProcessEstimate(0.0, correctedFilterCorrection, correctedCovariance);

  237.     }

  238.     /** {@inheritDoc} */
  239.     @Override
  240.     public KalmanObserver getObserver() {
  241.         return observer;
  242.     }

  243.     /** Set the observer.
  244.      * @param observer the observer
  245.      */
  246.     public void setObserver(final KalmanObserver observer) {
  247.         this.observer = observer;
  248.     }

  249.     /** Get the current corrected estimate.
  250.      * @return current corrected estimate
  251.      */
  252.     public ProcessEstimate getEstimate() {
  253.         return correctedEstimate;
  254.     }

  255.     /** Process a single measurement.
  256.      * <p>
  257.      * Update the filter with the new measurements.
  258.      * </p>
  259.      * @param observedMeasurements the list of measurements to process
  260.      * @param filter Extended Kalman Filter
  261.      * @return estimated propagator
  262.      */
  263.     public DSSTPropagator processMeasurements(final List<ObservedMeasurement<?>> observedMeasurements,
  264.                                               final ExtendedKalmanFilter<MeasurementDecorator> filter) {
  265.         try {

  266.             // Sort the measurement
  267.             observedMeasurements.sort(new ChronologicalComparator());
  268.             final AbsoluteDate tStart             = observedMeasurements.get(0).getDate();
  269.             final AbsoluteDate tEnd               = observedMeasurements.get(observedMeasurements.size() - 1).getDate();
  270.             final double       overshootTimeRange = FastMath.nextAfter(tEnd.durationFrom(tStart),
  271.                                                     Double.POSITIVE_INFINITY);

  272.             // Initialize step handler and set it to the propagator
  273.             final SemiAnalyticalMeasurementHandler stepHandler = new SemiAnalyticalMeasurementHandler(this, filter, observedMeasurements, builder.getInitialOrbitDate());
  274.             dsstPropagator.getMultiplexer().add(stepHandler);
  275.             dsstPropagator.propagate(tStart, tStart.shiftedBy(overshootTimeRange));

  276.             // Return the last estimated propagator
  277.             return getEstimatedPropagator();

  278.         } catch (MathRuntimeException mrte) {
  279.             throw new OrekitException(mrte);
  280.         }
  281.     }

  282.     /** Get the propagator estimated with the values set in the propagator builder.
  283.      * @return propagator based on the current values in the builder
  284.      */
  285.     public DSSTPropagator getEstimatedPropagator() {
  286.         // Return propagator built with current instantiation of the propagator builder
  287.         return (DSSTPropagator) builder.buildPropagator();
  288.     }

  289.     /** {@inheritDoc} */
  290.     @Override
  291.     public NonLinearEvolution getEvolution(final double previousTime, final RealVector previousState,
  292.                                            final MeasurementDecorator measurement) {

  293.         // Set a reference date for all measurements parameters that lack one (including the not estimated ones)
  294.         final ObservedMeasurement<?> observedMeasurement = measurement.getObservedMeasurement();
  295.         for (final ParameterDriver driver : observedMeasurement.getParametersDrivers()) {
  296.             if (driver.getReferenceDate() == null) {
  297.                 driver.setReferenceDate(builder.getInitialOrbitDate());
  298.             }
  299.         }

  300.         // Increment measurement number
  301.         ++currentMeasurementNumber;

  302.         // Update the current date
  303.         currentDate = measurement.getObservedMeasurement().getDate();

  304.         // Normalized state transition matrix
  305.         final RealMatrix stm = getErrorStateTransitionMatrix();

  306.         // Predict filter correction
  307.         predictedFilterCorrection = predictFilterCorrection(stm);

  308.         // Short period term derivatives
  309.         analyticalDerivativeComputations(nominalMeanSpacecraftState);

  310.         // Calculate the predicted osculating elements
  311.         final double[] osculating = computeOsculatingElements(predictedFilterCorrection);
  312.         final Orbit osculatingOrbit = OrbitType.EQUINOCTIAL.mapArrayToOrbit(osculating, null, builder.getPositionAngleType(),
  313.                                                                             currentDate, nominalMeanSpacecraftState.getMu(),
  314.                                                                             nominalMeanSpacecraftState.getFrame());

  315.         // Compute the predicted measurements  (See Ref [1], Eq. 3.8)
  316.         predictedMeasurement = observedMeasurement.estimate(currentMeasurementNumber,
  317.                                                             currentMeasurementNumber,
  318.                                                             new SpacecraftState[] {
  319.                                                                 new SpacecraftState(osculatingOrbit,
  320.                                                                                     nominalMeanSpacecraftState.getAttitude(),
  321.                                                                                     nominalMeanSpacecraftState.getMass(),
  322.                                                                                     nominalMeanSpacecraftState.getAdditionalStatesValues(),
  323.                                                                                     nominalMeanSpacecraftState.getAdditionalStatesDerivatives())
  324.                                                             });

  325.         // Normalized measurement matrix
  326.         final RealMatrix measurementMatrix = getMeasurementMatrix();

  327.         // Number of estimated measurement parameters
  328.         final int nbMeas = getNumberSelectedMeasurementDriversValuesToEstimate();

  329.         // Number of estimated dynamic parameters (orbital + propagation)
  330.         final int nbDyn  = getNumberSelectedOrbitalDriversValuesToEstimate() + getNumberSelectedPropagationDriversValuesToEstimate();

  331.         // Covariance matrix
  332.         final RealMatrix noiseK = MatrixUtils.createRealMatrix(nbDyn + nbMeas, nbDyn + nbMeas);
  333.         final RealMatrix noiseP = covarianceMatrixProvider.getProcessNoiseMatrix(previousNominalMeanSpacecraftState, nominalMeanSpacecraftState);
  334.         noiseK.setSubMatrix(noiseP.getData(), 0, 0);
  335.         if (measurementProcessNoiseMatrix != null) {
  336.             final RealMatrix noiseM = measurementProcessNoiseMatrix.getProcessNoiseMatrix(previousNominalMeanSpacecraftState, nominalMeanSpacecraftState);
  337.             noiseK.setSubMatrix(noiseM.getData(), nbDyn, nbDyn);
  338.         }

  339.         // Verify dimension
  340.         KalmanEstimatorUtil.checkDimension(noiseK.getRowDimension(),
  341.                                            builder.getOrbitalParametersDrivers(),
  342.                                            builder.getPropagationParametersDrivers(),
  343.                                            estimatedMeasurementsParameters);

  344.         final RealMatrix normalizedProcessNoise = KalmanEstimatorUtil.normalizeCovarianceMatrix(noiseK, scale);

  345.         // Return
  346.         return new NonLinearEvolution(measurement.getTime(), predictedFilterCorrection, stm,
  347.                                       normalizedProcessNoise, measurementMatrix);
  348.     }

  349.     /** {@inheritDoc} */
  350.     @Override
  351.     public RealVector getInnovation(final MeasurementDecorator measurement, final NonLinearEvolution evolution,
  352.                                     final RealMatrix innovationCovarianceMatrix) {

  353.         // Apply the dynamic outlier filter, if it exists
  354.         KalmanEstimatorUtil.applyDynamicOutlierFilter(predictedMeasurement, innovationCovarianceMatrix);
  355.         // Compute the innovation vector
  356.         return KalmanEstimatorUtil.computeInnovationVector(predictedMeasurement, predictedMeasurement.getObservedMeasurement().getTheoreticalStandardDeviation());
  357.     }

  358.     /** {@inheritDoc} */
  359.     @Override
  360.     public void finalizeEstimation(final ObservedMeasurement<?> observedMeasurement,
  361.                                    final ProcessEstimate estimate) {
  362.         // Update the process estimate
  363.         correctedEstimate = estimate;
  364.         // Corrected filter correction
  365.         correctedFilterCorrection = estimate.getState();
  366.         // Update the previous nominal mean spacecraft state
  367.         previousNominalMeanSpacecraftState = nominalMeanSpacecraftState;
  368.         // Calculate the corrected osculating elements
  369.         final double[] osculating = computeOsculatingElements(correctedFilterCorrection);
  370.         final Orbit osculatingOrbit = OrbitType.EQUINOCTIAL.mapArrayToOrbit(osculating, null, builder.getPositionAngleType(),
  371.                                                                             currentDate, nominalMeanSpacecraftState.getMu(),
  372.                                                                             nominalMeanSpacecraftState.getFrame());

  373.         // Compute the corrected measurements
  374.         correctedMeasurement = observedMeasurement.estimate(currentMeasurementNumber,
  375.                                                             currentMeasurementNumber,
  376.                                                             new SpacecraftState[] {
  377.                                                                 new SpacecraftState(osculatingOrbit,
  378.                                                                                     nominalMeanSpacecraftState.getAttitude(),
  379.                                                                                     nominalMeanSpacecraftState.getMass(),
  380.                                                                                     nominalMeanSpacecraftState.getAdditionalStatesValues(),
  381.                                                                                     nominalMeanSpacecraftState.getAdditionalStatesDerivatives())
  382.                                                             });
  383.         // Call the observer if the user add one
  384.         if (observer != null) {
  385.             observer.evaluationPerformed(this);
  386.         }
  387.     }

  388.     /** {@inheritDoc} */
  389.     @Override
  390.     public void finalizeOperationsObservationGrid() {
  391.         // Update parameters
  392.         updateParameters();
  393.     }

  394.     /** {@inheritDoc} */
  395.     @Override
  396.     public ParameterDriversList getEstimatedOrbitalParameters() {
  397.         return estimatedOrbitalParameters;
  398.     }

  399.     /** {@inheritDoc} */
  400.     @Override
  401.     public ParameterDriversList getEstimatedPropagationParameters() {
  402.         return estimatedPropagationParameters;
  403.     }

  404.     /** {@inheritDoc} */
  405.     @Override
  406.     public ParameterDriversList getEstimatedMeasurementsParameters() {
  407.         return estimatedMeasurementsParameters;
  408.     }

  409.     /** {@inheritDoc} */
  410.     @Override
  411.     public SpacecraftState[] getPredictedSpacecraftStates() {
  412.         return new SpacecraftState[] {nominalMeanSpacecraftState};
  413.     }

  414.     /** {@inheritDoc} */
  415.     @Override
  416.     public SpacecraftState[] getCorrectedSpacecraftStates() {
  417.         return new SpacecraftState[] {getEstimatedPropagator().getInitialState()};
  418.     }

  419.     /** {@inheritDoc} */
  420.     @Override
  421.     public RealVector getPhysicalEstimatedState() {
  422.         // Method {@link ParameterDriver#getValue()} is used to get
  423.         // the physical values of the state.
  424.         // The scales'array is used to get the size of the state vector
  425.         final RealVector physicalEstimatedState = new ArrayRealVector(scale.length);
  426.         int i = 0;
  427.         for (final DelegatingDriver driver : getEstimatedOrbitalParameters().getDrivers()) {
  428.             for (Span<Double> span = driver.getValueSpanMap().getFirstSpan(); span != null; span = span.next()) {
  429.                 physicalEstimatedState.setEntry(i++, span.getData());
  430.             }
  431.         }
  432.         for (final DelegatingDriver driver : getEstimatedPropagationParameters().getDrivers()) {
  433.             for (Span<Double> span = driver.getValueSpanMap().getFirstSpan(); span != null; span = span.next()) {
  434.                 physicalEstimatedState.setEntry(i++, span.getData());
  435.             }
  436.         }
  437.         for (final DelegatingDriver driver : getEstimatedMeasurementsParameters().getDrivers()) {
  438.             for (Span<Double> span = driver.getValueSpanMap().getFirstSpan(); span != null; span = span.next()) {
  439.                 physicalEstimatedState.setEntry(i++, span.getData());
  440.             }
  441.         }

  442.         return physicalEstimatedState;
  443.     }

  444.     /** {@inheritDoc} */
  445.     @Override
  446.     public RealMatrix getPhysicalEstimatedCovarianceMatrix() {
  447.         // Un-normalize the estimated covariance matrix (P) from Hipparchus and return it.
  448.         // The covariance P is an mxm matrix where m = nbOrb + nbPropag + nbMeas
  449.         // For each element [i,j] of P the corresponding normalized value is:
  450.         // Pn[i,j] = P[i,j] / (scale[i]*scale[j])
  451.         // Consequently: P[i,j] = Pn[i,j] * scale[i] * scale[j]
  452.         return KalmanEstimatorUtil.unnormalizeCovarianceMatrix(correctedEstimate.getCovariance(), scale);
  453.     }

  454.     /** {@inheritDoc} */
  455.     @Override
  456.     public RealMatrix getPhysicalStateTransitionMatrix() {
  457.         //  Un-normalize the state transition matrix (φ) from Hipparchus and return it.
  458.         // φ is an mxm matrix where m = nbOrb + nbPropag + nbMeas
  459.         // For each element [i,j] of normalized φ (φn), the corresponding physical value is:
  460.         // φ[i,j] = φn[i,j] * scale[i] / scale[j]
  461.         return correctedEstimate.getStateTransitionMatrix() == null ?
  462.                 null : KalmanEstimatorUtil.unnormalizeStateTransitionMatrix(correctedEstimate.getStateTransitionMatrix(), scale);
  463.     }

  464.     /** {@inheritDoc} */
  465.     @Override
  466.     public RealMatrix getPhysicalMeasurementJacobian() {
  467.         // Un-normalize the measurement matrix (H) from Hipparchus and return it.
  468.         // H is an nxm matrix where:
  469.         //  - m = nbOrb + nbPropag + nbMeas is the number of estimated parameters
  470.         //  - n is the size of the measurement being processed by the filter
  471.         // For each element [i,j] of normalized H (Hn) the corresponding physical value is:
  472.         // H[i,j] = Hn[i,j] * σ[i] / scale[j]
  473.         return correctedEstimate.getMeasurementJacobian() == null ?
  474.                 null : KalmanEstimatorUtil.unnormalizeMeasurementJacobian(correctedEstimate.getMeasurementJacobian(),
  475.                                                                           scale,
  476.                                                                           correctedMeasurement.getObservedMeasurement().getTheoreticalStandardDeviation());
  477.     }

  478.     /** {@inheritDoc} */
  479.     @Override
  480.     public RealMatrix getPhysicalInnovationCovarianceMatrix() {
  481.         // Un-normalize the innovation covariance matrix (S) from Hipparchus and return it.
  482.         // S is an nxn matrix where n is the size of the measurement being processed by the filter
  483.         // For each element [i,j] of normalized S (Sn) the corresponding physical value is:
  484.         // S[i,j] = Sn[i,j] * σ[i] * σ[j]
  485.         return correctedEstimate.getInnovationCovariance() == null ?
  486.                 null : KalmanEstimatorUtil.unnormalizeInnovationCovarianceMatrix(correctedEstimate.getInnovationCovariance(),
  487.                                                                                  predictedMeasurement.getObservedMeasurement().getTheoreticalStandardDeviation());
  488.     }

  489.     /** {@inheritDoc} */
  490.     @Override
  491.     public RealMatrix getPhysicalKalmanGain() {
  492.         // Un-normalize the Kalman gain (K) from Hipparchus and return it.
  493.         // K is an mxn matrix where:
  494.         //  - m = nbOrb + nbPropag + nbMeas is the number of estimated parameters
  495.         //  - n is the size of the measurement being processed by the filter
  496.         // For each element [i,j] of normalized K (Kn) the corresponding physical value is:
  497.         // K[i,j] = Kn[i,j] * scale[i] / σ[j]
  498.         return correctedEstimate.getKalmanGain() == null ?
  499.                 null : KalmanEstimatorUtil.unnormalizeKalmanGainMatrix(correctedEstimate.getKalmanGain(),
  500.                                                                        scale,
  501.                                                                        correctedMeasurement.getObservedMeasurement().getTheoreticalStandardDeviation());
  502.     }

  503.     /** {@inheritDoc} */
  504.     @Override
  505.     public int getCurrentMeasurementNumber() {
  506.         return currentMeasurementNumber;
  507.     }

  508.     /** {@inheritDoc} */
  509.     @Override
  510.     public AbsoluteDate getCurrentDate() {
  511.         return currentDate;
  512.     }

  513.     /** {@inheritDoc} */
  514.     @Override
  515.     public EstimatedMeasurement<?> getPredictedMeasurement() {
  516.         return predictedMeasurement;
  517.     }

  518.     /** {@inheritDoc} */
  519.     @Override
  520.     public EstimatedMeasurement<?> getCorrectedMeasurement() {
  521.         return correctedMeasurement;
  522.     }

  523.     /** {@inheritDoc} */
  524.     @Override
  525.     public void updateNominalSpacecraftState(final SpacecraftState nominal) {
  526.         this.nominalMeanSpacecraftState = nominal;
  527.         // Update the builder with the nominal mean elements orbit
  528.         builder.resetOrbit(nominal.getOrbit(), PropagationType.MEAN);

  529.         // Additionally, update the builder with the predicted mass value.
  530.         // If any mass changes have occurred during this estimation step, such as maneuvers,
  531.         // the updated mass value must be carried over so that new Propagators from this builder start with the updated mass.
  532.         builder.setMass(nominal.getMass());
  533.     }

  534.     /** Update the reference trajectories using the propagator as input.
  535.      * @param propagator The new propagator to use
  536.      */
  537.     public void updateReferenceTrajectory(final DSSTPropagator propagator) {

  538.         dsstPropagator = propagator;

  539.         // Equation name
  540.         final String equationName = SemiAnalyticalKalmanEstimator.class.getName() + "-derivatives-";

  541.         // Mean state
  542.         final SpacecraftState meanState = dsstPropagator.initialIsOsculating() ?
  543.                        DSSTPropagator.computeMeanState(dsstPropagator.getInitialState(), dsstPropagator.getAttitudeProvider(), dsstPropagator.getAllForceModels()) :
  544.                        dsstPropagator.getInitialState();

  545.         // Update the jacobian harvester
  546.         dsstPropagator.setInitialState(meanState, PropagationType.MEAN);
  547.         harvester = dsstPropagator.setupMatricesComputation(equationName, null, null);

  548.     }

  549.     /** {@inheritDoc} */
  550.     @Override
  551.     public void updateShortPeriods(final SpacecraftState state) {
  552.         // Loop on DSST force models
  553.         for (final DSSTForceModel model : builder.getAllForceModels()) {
  554.             model.updateShortPeriodTerms(model.getParametersAllValues(), state);
  555.         }
  556.         harvester.updateFieldShortPeriodTerms(state);
  557.     }

  558.     /** {@inheritDoc} */
  559.     @Override
  560.     public void initializeShortPeriodicTerms(final SpacecraftState meanState) {
  561.         final List<ShortPeriodTerms> shortPeriodTerms = new ArrayList<>();
  562.         // initialize ForceModels in OSCULATING mode even if propagation is MEAN
  563.         final PropagationType type = PropagationType.OSCULATING;
  564.         for (final DSSTForceModel force :  builder.getAllForceModels()) {
  565.             shortPeriodTerms.addAll(force.initializeShortPeriodTerms(new AuxiliaryElements(meanState.getOrbit(), 1), type, force.getParameters(meanState.getDate())));
  566.         }
  567.         dsstPropagator.setShortPeriodTerms(shortPeriodTerms);
  568.         // also need to initialize the Field terms in the same mode
  569.         harvester.initializeFieldShortPeriodTerms(meanState, type);
  570.     }

  571.     /** Get the normalized state transition matrix (STM) from previous point to current point.
  572.      * The STM contains the partial derivatives of current state with respect to previous state.
  573.      * The  STM is an mxm matrix where m is the size of the state vector.
  574.      * m = nbOrb + nbPropag + nbMeas
  575.      * @return the normalized error state transition matrix
  576.      */
  577.     private RealMatrix getErrorStateTransitionMatrix() {

  578.         /* The state transition matrix is obtained as follows, with:
  579.          *  - Phi(k, k-1) : Transitional orbital matrix
  580.          *  - Psi(k, k-1) : Transitional propagation parameters matrix
  581.          *
  582.          *       |             |             |   .    |
  583.          *       | Phi(k, k-1) | Psi(k, k-1) | ..0..  |
  584.          *       |             |             |   .    |
  585.          *       |-------------|-------------|--------|
  586.          *       |      .      |    1 0 0    |   .    |
  587.          * STM = |    ..0..    |    0 1 0    | ..0..  |
  588.          *       |      .      |    0 0 1    |   .    |
  589.          *       |-------------|-------------|--------|
  590.          *       |      .      |      .      | 1 0 0..|
  591.          *       |    ..0..    |    ..0..    | 0 1 0..|
  592.          *       |      .      |      .      | 0 0 1..|
  593.          */

  594.         // Initialize to the proper size identity matrix
  595.         final RealMatrix stm = MatrixUtils.createRealIdentityMatrix(correctedEstimate.getState().getDimension());

  596.         // Derivatives of the state vector with respect to initial state vector
  597.         final int nbOrb = getNumberSelectedOrbitalDriversValuesToEstimate();
  598.         final RealMatrix dYdY0 = harvester.getB2(nominalMeanSpacecraftState);

  599.         // Calculate transitional orbital matrix (See Ref [1], Eq. 3.4a)
  600.         final RealMatrix phi = dYdY0.multiply(phiS);

  601.         // Fill the state transition matrix with the orbital drivers
  602.         final List<DelegatingDriver> drivers = builder.getOrbitalParametersDrivers().getDrivers();
  603.         for (int i = 0; i < nbOrb; ++i) {
  604.             if (drivers.get(i).isSelected()) {
  605.                 int jOrb = 0;
  606.                 for (int j = 0; j < nbOrb; ++j) {
  607.                     if (drivers.get(j).isSelected()) {
  608.                         stm.setEntry(i, jOrb++, phi.getEntry(i, j));
  609.                     }
  610.                 }
  611.             }
  612.         }

  613.         // Update PhiS
  614.         phiS = new QRDecomposition(dYdY0).getSolver().getInverse();

  615.         // Derivatives of the state vector with respect to propagation parameters
  616.         if (psiS != null) {

  617.             final int nbProp = getNumberSelectedPropagationDriversValuesToEstimate();
  618.             final RealMatrix dYdPp = harvester.getB3(nominalMeanSpacecraftState);

  619.             // Calculate transitional parameters matrix (See Ref [1], Eq. 3.4b)
  620.             final RealMatrix psi = dYdPp.subtract(phi.multiply(psiS));

  621.             // Fill 1st row, 2nd column (dY/dPp)
  622.             for (int i = 0; i < nbOrb; ++i) {
  623.                 for (int j = 0; j < nbProp; ++j) {
  624.                     stm.setEntry(i, j + nbOrb, psi.getEntry(i, j));
  625.                 }
  626.             }

  627.             // Update PsiS
  628.             psiS = dYdPp;

  629.         }

  630.         // Normalization of the STM
  631.         // normalized(STM)ij = STMij*Sj/Si
  632.         for (int i = 0; i < scale.length; i++) {
  633.             for (int j = 0; j < scale.length; j++ ) {
  634.                 stm.setEntry(i, j, stm.getEntry(i, j) * scale[j] / scale[i]);
  635.             }
  636.         }

  637.         // Return the error state transition matrix
  638.         return stm;

  639.     }

  640.     /** Get the normalized measurement matrix H.
  641.      * H contains the partial derivatives of the measurement with respect to the state.
  642.      * H is an nxm matrix where n is the size of the measurement vector and m the size of the state vector.
  643.      * @return the normalized measurement matrix H
  644.      */
  645.     private RealMatrix getMeasurementMatrix() {

  646.         // Observed measurement characteristics
  647.         final SpacecraftState        evaluationState     = predictedMeasurement.getStates()[0];
  648.         final ObservedMeasurement<?> observedMeasurement = predictedMeasurement.getObservedMeasurement();
  649.         final double[] sigma  = predictedMeasurement.getObservedMeasurement().getTheoreticalStandardDeviation();

  650.         // Initialize measurement matrix H: nxm
  651.         // n: Number of measurements in current measurement
  652.         // m: State vector size
  653.         final RealMatrix measurementMatrix = MatrixUtils.
  654.                 createRealMatrix(observedMeasurement.getDimension(),
  655.                                  correctedEstimate.getState().getDimension());

  656.         // Predicted orbit
  657.         final Orbit predictedOrbit = evaluationState.getOrbit();

  658.         // Measurement matrix's columns related to orbital and propagation parameters
  659.         // ----------------------------------------------------------

  660.         // Partial derivatives of the current Cartesian coordinates with respect to current orbital state
  661.         final int nbOrb  = getNumberSelectedOrbitalDrivers();
  662.         final int nbProp = getNumberSelectedPropagationDrivers();
  663.         final double[][] aCY = new double[nbOrb][nbOrb];
  664.         predictedOrbit.getJacobianWrtParameters(builder.getPositionAngleType(), aCY);
  665.         final RealMatrix dCdY = new Array2DRowRealMatrix(aCY, false);

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

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

  670.         // Compute factor dShortPeriod_dMeanState = I+B1 | B4
  671.         final RealMatrix IpB1B4 = MatrixUtils.createRealMatrix(nbOrb, nbOrb + nbProp);

  672.         // B1
  673.         final RealMatrix B1 = harvester.getB1();

  674.         // I + B1
  675.         final RealMatrix I = MatrixUtils.createRealIdentityMatrix(nbOrb);
  676.         final RealMatrix IpB1 = I.add(B1);
  677.         IpB1B4.setSubMatrix(IpB1.getData(), 0, 0);

  678.         // If there are not propagation parameters, B4 is null
  679.         if (psiS != null) {
  680.             final RealMatrix B4 = harvester.getB4();
  681.             IpB1B4.setSubMatrix(B4.getData(), 0, nbOrb);
  682.         }

  683.         // Ref [1], Eq. 3.10
  684.         dMdY = dMdY.multiply(IpB1B4);

  685.         for (int i = 0; i < dMdY.getRowDimension(); i++) {
  686.             for (int j = 0; j < nbOrb; j++) {
  687.                 final double driverScale = builder.getOrbitalParametersDrivers().getDrivers().get(j).getScale();
  688.                 measurementMatrix.setEntry(i, j, dMdY.getEntry(i, j) / sigma[i] * driverScale);
  689.             }

  690.             int col = 0;
  691.             for (int j = 0; j < nbProp; j++) {
  692.                 final double driverScale = estimatedPropagationParameters.getDrivers().get(j).getScale();
  693.                 for (Span<Double> span = estimatedPropagationParameters.getDrivers().get(j).getValueSpanMap().getFirstSpan();
  694.                                   span != null; span = span.next()) {

  695.                     measurementMatrix.setEntry(i, col + nbOrb,
  696.                                                dMdY.getEntry(i, col + nbOrb) / sigma[i] * driverScale);
  697.                     col++;
  698.                 }
  699.             }
  700.         }

  701.         // Normalized measurement matrix's columns related to measurement parameters
  702.         // --------------------------------------------------------------

  703.         // Jacobian of the measurement with respect to measurement parameters
  704.         // Gather the measurement parameters linked to current measurement
  705.         for (final ParameterDriver driver : observedMeasurement.getParametersDrivers()) {
  706.             if (driver.isSelected()) {
  707.                 for (Span<String> span = driver.getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {
  708.                     // Derivatives of current measurement w/r to selected measurement parameter
  709.                     final double[] aMPm = predictedMeasurement.getParameterDerivatives(driver, span.getStart());

  710.                     // Check that the measurement parameter is managed by the filter
  711.                     if (measurementParameterColumns.get(span.getData()) != null) {
  712.                         // Column of the driver in the measurement matrix
  713.                         final int driverColumn = measurementParameterColumns.get(span.getData());

  714.                         // Fill the corresponding indexes of the measurement matrix
  715.                         for (int i = 0; i < aMPm.length; ++i) {
  716.                             measurementMatrix.setEntry(i, driverColumn, aMPm[i] / sigma[i] * driver.getScale());
  717.                         }
  718.                     }
  719.                 }
  720.             }
  721.         }

  722.         return measurementMatrix;
  723.     }

  724.     /** Predict the filter correction for the new observation.
  725.      * @param stm normalized state transition matrix
  726.      * @return the predicted filter correction for the new observation
  727.      */
  728.     private RealVector predictFilterCorrection(final RealMatrix stm) {
  729.         // Ref [1], Eq. 3.5a and 3.5b
  730.         return stm.operate(correctedFilterCorrection);
  731.     }

  732.     /** Compute the predicted osculating elements.
  733.      * @param filterCorrection kalman filter correction
  734.      * @return the predicted osculating element
  735.      */
  736.     private double[] computeOsculatingElements(final RealVector filterCorrection) {

  737.         // Number of estimated orbital parameters
  738.         final int nbOrb = getNumberSelectedOrbitalDrivers();

  739.         // B1
  740.         final RealMatrix B1 = harvester.getB1();

  741.         // Short periodic terms
  742.         final double[] shortPeriodTerms = dsstPropagator.getShortPeriodTermsValue(nominalMeanSpacecraftState);

  743.         // Physical filter correction
  744.         final RealVector physicalFilterCorrection = MatrixUtils.createRealVector(nbOrb);
  745.         for (int index = 0; index < nbOrb; index++) {
  746.             physicalFilterCorrection.addToEntry(index, filterCorrection.getEntry(index) * scale[index]);
  747.         }

  748.         // B1 * physicalCorrection
  749.         final RealVector B1Correction = B1.operate(physicalFilterCorrection);

  750.         // Nominal mean elements
  751.         final double[] nominalMeanElements = new double[nbOrb];
  752.         OrbitType.EQUINOCTIAL.mapOrbitToArray(nominalMeanSpacecraftState.getOrbit(), builder.getPositionAngleType(), nominalMeanElements, null);

  753.         // Ref [1] Eq. 3.6
  754.         final double[] osculatingElements = new double[nbOrb];
  755.         for (int i = 0; i < nbOrb; i++) {
  756.             osculatingElements[i] = nominalMeanElements[i] +
  757.                                     physicalFilterCorrection.getEntry(i) +
  758.                                     shortPeriodTerms[i] +
  759.                                     B1Correction.getEntry(i);
  760.         }

  761.         // Return
  762.         return osculatingElements;

  763.     }

  764.     /** Analytical computation of derivatives.
  765.      * This method allow to compute analytical derivatives.
  766.      * @param state mean state used to calculate short period perturbations
  767.      */
  768.     private void analyticalDerivativeComputations(final SpacecraftState state) {
  769.         harvester.setReferenceState(state);
  770.     }

  771.     /** Get the number of estimated orbital parameters.
  772.      * @return the number of estimated orbital parameters
  773.      */
  774.     private int getNumberSelectedOrbitalDrivers() {
  775.         return estimatedOrbitalParameters.getNbParams();
  776.     }

  777.     /** Get the number of estimated propagation parameters.
  778.      * @return the number of estimated propagation parameters
  779.      */
  780.     private int getNumberSelectedPropagationDrivers() {
  781.         return estimatedPropagationParameters.getNbParams();
  782.     }

  783.     /** Get the number of estimated orbital parameters values (some parameter
  784.      * driver may have several values to estimate for different time range
  785.      * {@link ParameterDriver}.
  786.      * @return the number of estimated values for , orbital parameters
  787.      */
  788.     private int getNumberSelectedOrbitalDriversValuesToEstimate() {
  789.         int nbOrbitalValuesToEstimate = 0;
  790.         for (final ParameterDriver driver : estimatedOrbitalParameters.getDrivers()) {
  791.             nbOrbitalValuesToEstimate += driver.getNbOfValues();
  792.         }
  793.         return nbOrbitalValuesToEstimate;
  794.     }

  795.     /** Get the number of estimated propagation parameters values (some parameter
  796.      * driver may have several values to estimate for different time range
  797.      * {@link ParameterDriver}.
  798.      * @return the number of estimated values for propagation parameters
  799.      */
  800.     private int getNumberSelectedPropagationDriversValuesToEstimate() {
  801.         int nbPropagationValuesToEstimate = 0;
  802.         for (final ParameterDriver driver : estimatedPropagationParameters.getDrivers()) {
  803.             nbPropagationValuesToEstimate += driver.getNbOfValues();
  804.         }
  805.         return nbPropagationValuesToEstimate;
  806.     }

  807.     /** Get the number of estimated measurement parameters values (some parameter
  808.      * driver may have several values to estimate for different time range
  809.      * {@link ParameterDriver}.
  810.      * @return the number of estimated values for measurement parameters
  811.      */
  812.     private int getNumberSelectedMeasurementDriversValuesToEstimate() {
  813.         int nbMeasurementValuesToEstimate = 0;
  814.         for (final ParameterDriver driver : estimatedMeasurementsParameters.getDrivers()) {
  815.             nbMeasurementValuesToEstimate += driver.getNbOfValues();
  816.         }
  817.         return nbMeasurementValuesToEstimate;
  818.     }

  819.     /** Update the estimated parameters after the correction phase of the filter.
  820.      * The min/max allowed values are handled by the parameter themselves.
  821.      */
  822.     private void updateParameters() {
  823.         final RealVector correctedState = correctedEstimate.getState();
  824.         int i = 0;
  825.         // Orbital parameters
  826.         for (final DelegatingDriver driver : getEstimatedOrbitalParameters().getDrivers()) {
  827.             // let the parameter handle min/max clipping
  828.             for (Span<Double> span = driver.getValueSpanMap().getFirstSpan(); span != null; span = span.next()) {
  829.                 driver.setNormalizedValue(driver.getNormalizedValue(span.getStart()) + correctedState.getEntry(i++), span.getStart());
  830.             }
  831.         }

  832.         // Propagation parameters
  833.         for (final DelegatingDriver driver : getEstimatedPropagationParameters().getDrivers()) {
  834.             // let the parameter handle min/max clipping
  835.             // If the parameter driver contains only 1 value to estimate over the all time range
  836.             for (Span<Double> span = driver.getValueSpanMap().getFirstSpan(); span != null; span = span.next()) {
  837.                 driver.setNormalizedValue(driver.getNormalizedValue(span.getStart()) + correctedState.getEntry(i++), span.getStart());
  838.             }
  839.         }

  840.         // Measurements parameters
  841.         for (final DelegatingDriver driver : getEstimatedMeasurementsParameters().getDrivers()) {
  842.             // let the parameter handle min/max clipping
  843.             for (Span<Double> span = driver.getValueSpanMap().getFirstSpan(); span != null; span = span.next()) {
  844.                 driver.setNormalizedValue(driver.getNormalizedValue(span.getStart()) + correctedState.getEntry(i++), span.getStart());
  845.             }
  846.         }
  847.     }

  848. }