SemiAnalyticalKalmanModel.java

  1. /* Copyright 2002-2023 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 java.util.ArrayList;
  19. import java.util.Comparator;
  20. import java.util.HashMap;
  21. import java.util.List;
  22. import java.util.Map;

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

  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 builder.buildPropagator(builder.getSelectedNormalizedParameters());
  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 = (DSSTHarvester) 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<ShortPeriodTerms>();
  558.         for (final DSSTForceModel force :  builder.getAllForceModels()) {
  559.             shortPeriodTerms.addAll(force.initializeShortPeriodTerms(new AuxiliaryElements(meanState.getOrbit(), 1), PropagationType.OSCULATING, force.getParameters(meanState.getDate())));
  560.         }
  561.         dsstPropagator.setShortPeriodTerms(shortPeriodTerms);
  562.     }

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

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

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

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

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

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

  605.         // Update PhiS
  606.         phiS = new QRDecomposition(dYdY0).getSolver().getInverse();

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

  609.             final int nbProp = getNumberSelectedPropagationDriversValuesToEstimate();
  610.             final RealMatrix dYdPp = harvester.getB3(nominalMeanSpacecraftState);

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

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

  619.             // Update PsiS
  620.             psiS = dYdPp;

  621.         }

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

  629.         // Return the error state transition matrix
  630.         return stm;

  631.     }

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

  638.         // Observed measurement characteristics
  639.         final SpacecraftState        evaluationState     = predictedMeasurement.getStates()[0];
  640.         final ObservedMeasurement<?> observedMeasurement = predictedMeasurement.getObservedMeasurement();
  641.         final double[] sigma  = predictedMeasurement.getObservedMeasurement().getTheoreticalStandardDeviation();

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

  648.         // Predicted orbit
  649.         final Orbit predictedOrbit = evaluationState.getOrbit();

  650.         // Measurement matrix's columns related to orbital and propagation parameters
  651.         // ----------------------------------------------------------

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

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

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

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

  664.         // B1
  665.         final RealMatrix B1 = harvester.getB1();

  666.         // I + B1
  667.         final RealMatrix I = MatrixUtils.createRealIdentityMatrix(nbOrb);
  668.         final RealMatrix IpB1 = I.add(B1);
  669.         IpB1B4.setSubMatrix(IpB1.getData(), 0, 0);

  670.         // If there are not propagation parameters, B4 is null
  671.         if (psiS != null) {
  672.             final RealMatrix B4 = harvester.getB4();
  673.             IpB1B4.setSubMatrix(B4.getData(), 0, nbOrb);
  674.         }

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

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

  682.             int col = 0;
  683.             for (int j = 0; j < nbProp; j++) {
  684.                 final double driverScale = estimatedPropagationParameters.getDrivers().get(j).getScale();
  685.                 for (Span<Double> span = estimatedPropagationParameters.getDrivers().get(j).getValueSpanMap().getFirstSpan();
  686.                                   span != null; span = span.next()) {

  687.                     measurementMatrix.setEntry(i, col + nbOrb,
  688.                                                dMdY.getEntry(i, col + nbOrb) / sigma[i] * driverScale);
  689.                     col++;
  690.                 }
  691.             }
  692.         }

  693.         // Normalized measurement matrix's columns related to measurement parameters
  694.         // --------------------------------------------------------------

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

  702.                     // Check that the measurement parameter is managed by the filter
  703.                     if (measurementParameterColumns.get(span.getData()) != null) {
  704.                         // Column of the driver in the measurement matrix
  705.                         final int driverColumn = measurementParameterColumns.get(span.getData());

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

  714.         return measurementMatrix;
  715.     }

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

  724.     /** Compute the predicted osculating elements.
  725.      * @param filterCorrection kalman filter correction
  726.      * @return the predicted osculating element
  727.      */
  728.     private double[] computeOsculatingElements(final RealVector filterCorrection) {

  729.         // Number of estimated orbital parameters
  730.         final int nbOrb = getNumberSelectedOrbitalDrivers();

  731.         // B1
  732.         final RealMatrix B1 = harvester.getB1();

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

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

  740.         // B1 * physicalCorrection
  741.         final RealVector B1Correction = B1.operate(physicalFilterCorrection);

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

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

  753.         // Return
  754.         return osculatingElements;

  755.     }

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

  763.     /** Get the number of estimated orbital parameters.
  764.      * @return the number of estimated orbital parameters
  765.      */
  766.     private int getNumberSelectedOrbitalDrivers() {
  767.         return estimatedOrbitalParameters.getNbParams();
  768.     }

  769.     /** Get the number of estimated propagation parameters.
  770.      * @return the number of estimated propagation parameters
  771.      */
  772.     private int getNumberSelectedPropagationDrivers() {
  773.         return estimatedPropagationParameters.getNbParams();
  774.     }

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

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

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

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

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

  840. }