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.     }

  530.     /** Update the reference trajectories using the propagator as input.
  531.      * @param propagator The new propagator to use
  532.      */
  533.     public void updateReferenceTrajectory(final DSSTPropagator propagator) {

  534.         dsstPropagator = propagator;

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

  537.         // Mean state
  538.         final SpacecraftState meanState = dsstPropagator.initialIsOsculating() ?
  539.                        DSSTPropagator.computeMeanState(dsstPropagator.getInitialState(), dsstPropagator.getAttitudeProvider(), dsstPropagator.getAllForceModels()) :
  540.                        dsstPropagator.getInitialState();

  541.         // Update the jacobian harvester
  542.         dsstPropagator.setInitialState(meanState, PropagationType.MEAN);
  543.         harvester = dsstPropagator.setupMatricesComputation(equationName, null, null);

  544.     }

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

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

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

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

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

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

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

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

  609.         // Update PhiS
  610.         phiS = new QRDecomposition(dYdY0).getSolver().getInverse();

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

  613.             final int nbProp = getNumberSelectedPropagationDriversValuesToEstimate();
  614.             final RealMatrix dYdPp = harvester.getB3(nominalMeanSpacecraftState);

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

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

  623.             // Update PsiS
  624.             psiS = dYdPp;

  625.         }

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

  633.         // Return the error state transition matrix
  634.         return stm;

  635.     }

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

  642.         // Observed measurement characteristics
  643.         final SpacecraftState        evaluationState     = predictedMeasurement.getStates()[0];
  644.         final ObservedMeasurement<?> observedMeasurement = predictedMeasurement.getObservedMeasurement();
  645.         final double[] sigma  = predictedMeasurement.getObservedMeasurement().getTheoreticalStandardDeviation();

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

  652.         // Predicted orbit
  653.         final Orbit predictedOrbit = evaluationState.getOrbit();

  654.         // Measurement matrix's columns related to orbital and propagation parameters
  655.         // ----------------------------------------------------------

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

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

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

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

  668.         // B1
  669.         final RealMatrix B1 = harvester.getB1();

  670.         // I + B1
  671.         final RealMatrix I = MatrixUtils.createRealIdentityMatrix(nbOrb);
  672.         final RealMatrix IpB1 = I.add(B1);
  673.         IpB1B4.setSubMatrix(IpB1.getData(), 0, 0);

  674.         // If there are not propagation parameters, B4 is null
  675.         if (psiS != null) {
  676.             final RealMatrix B4 = harvester.getB4();
  677.             IpB1B4.setSubMatrix(B4.getData(), 0, nbOrb);
  678.         }

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

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

  686.             int col = 0;
  687.             for (int j = 0; j < nbProp; j++) {
  688.                 final double driverScale = estimatedPropagationParameters.getDrivers().get(j).getScale();
  689.                 for (Span<Double> span = estimatedPropagationParameters.getDrivers().get(j).getValueSpanMap().getFirstSpan();
  690.                                   span != null; span = span.next()) {

  691.                     measurementMatrix.setEntry(i, col + nbOrb,
  692.                                                dMdY.getEntry(i, col + nbOrb) / sigma[i] * driverScale);
  693.                     col++;
  694.                 }
  695.             }
  696.         }

  697.         // Normalized measurement matrix's columns related to measurement parameters
  698.         // --------------------------------------------------------------

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

  706.                     // Check that the measurement parameter is managed by the filter
  707.                     if (measurementParameterColumns.get(span.getData()) != null) {
  708.                         // Column of the driver in the measurement matrix
  709.                         final int driverColumn = measurementParameterColumns.get(span.getData());

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

  718.         return measurementMatrix;
  719.     }

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

  728.     /** Compute the predicted osculating elements.
  729.      * @param filterCorrection kalman filter correction
  730.      * @return the predicted osculating element
  731.      */
  732.     private double[] computeOsculatingElements(final RealVector filterCorrection) {

  733.         // Number of estimated orbital parameters
  734.         final int nbOrb = getNumberSelectedOrbitalDrivers();

  735.         // B1
  736.         final RealMatrix B1 = harvester.getB1();

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

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

  744.         // B1 * physicalCorrection
  745.         final RealVector B1Correction = B1.operate(physicalFilterCorrection);

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

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

  757.         // Return
  758.         return osculatingElements;

  759.     }

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

  767.     /** Get the number of estimated orbital parameters.
  768.      * @return the number of estimated orbital parameters
  769.      */
  770.     private int getNumberSelectedOrbitalDrivers() {
  771.         return estimatedOrbitalParameters.getNbParams();
  772.     }

  773.     /** Get the number of estimated propagation parameters.
  774.      * @return the number of estimated propagation parameters
  775.      */
  776.     private int getNumberSelectedPropagationDrivers() {
  777.         return estimatedPropagationParameters.getNbParams();
  778.     }

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

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

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

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

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

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

  844. }