Model.java

  1. /* Copyright 2002-2019 CS Systèmes d'Information
  2.  * Licensed to CS Systèmes d'Information (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.leastsquares;

  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.IdentityHashMap;
  23. import java.util.List;
  24. import java.util.Map;

  25. import org.hipparchus.linear.Array2DRowRealMatrix;
  26. import org.hipparchus.linear.ArrayRealVector;
  27. import org.hipparchus.linear.MatrixUtils;
  28. import org.hipparchus.linear.RealMatrix;
  29. import org.hipparchus.linear.RealVector;
  30. import org.hipparchus.optim.nonlinear.vector.leastsquares.MultivariateJacobianFunction;
  31. import org.hipparchus.util.FastMath;
  32. import org.hipparchus.util.Incrementor;
  33. import org.hipparchus.util.Pair;
  34. import org.orekit.estimation.measurements.EstimatedMeasurement;
  35. import org.orekit.estimation.measurements.ObservedMeasurement;
  36. import org.orekit.orbits.Orbit;
  37. import org.orekit.propagation.Propagator;
  38. import org.orekit.propagation.PropagatorsParallelizer;
  39. import org.orekit.propagation.SpacecraftState;
  40. import org.orekit.propagation.conversion.NumericalPropagatorBuilder;
  41. import org.orekit.propagation.numerical.JacobiansMapper;
  42. import org.orekit.propagation.numerical.NumericalPropagator;
  43. import org.orekit.propagation.numerical.PartialDerivativesEquations;
  44. import org.orekit.propagation.sampling.MultiSatStepHandler;
  45. import org.orekit.time.AbsoluteDate;
  46. import org.orekit.time.ChronologicalComparator;
  47. import org.orekit.utils.ParameterDriver;
  48. import org.orekit.utils.ParameterDriversList;
  49. import org.orekit.utils.ParameterDriversList.DelegatingDriver;

  50. /** Bridge between {@link ObservedMeasurement measurements} and {@link
  51.  * org.hipparchus.fitting.leastsquares.LeastSquaresProblem
  52.  * least squares problems}.
  53.  * @author Luc Maisonobe
  54.  * @since 8.0
  55.  */
  56. class Model implements MultivariateJacobianFunction {

  57.     /** Builders for propagators. */
  58.     private final NumericalPropagatorBuilder[] builders;

  59.     /** Array of each builder's selected propagation drivers. */
  60.     private final ParameterDriversList[] estimatedPropagationParameters;

  61.     /** Estimated measurements parameters. */
  62.     private final ParameterDriversList estimatedMeasurementsParameters;

  63.     /** Measurements. */
  64.     private final List<ObservedMeasurement<?>> measurements;

  65.     /** Start columns for each estimated orbit. */
  66.     private final int[] orbitsStartColumns;

  67.     /** End columns for each estimated orbit. */
  68.     private final int[] orbitsEndColumns;

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

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

  73.     /** Last evaluations. */
  74.     private final Map<ObservedMeasurement<?>, EstimatedMeasurement<?>> evaluations;

  75.     /** Observer to be notified at orbit changes. */
  76.     private final ModelObserver observer;

  77.     /** Counter for the evaluations. */
  78.     private Incrementor evaluationsCounter;

  79.     /** Counter for the iterations. */
  80.     private Incrementor iterationsCounter;

  81.     /** Date of the first enabled measurement. */
  82.     private AbsoluteDate firstDate;

  83.     /** Date of the last enabled measurement. */
  84.     private AbsoluteDate lastDate;

  85.     /** Boolean indicating if the propagation will go forward or backward. */
  86.     private final boolean forwardPropagation;

  87.     /** Mappers for Jacobians. */
  88.     private JacobiansMapper[] mappers;

  89.     /** Model function value. */
  90.     private RealVector value;

  91.     /** Model function Jacobian. */
  92.     private RealMatrix jacobian;

  93.     /** Simple constructor.
  94.      * @param builders builders to use for propagation
  95.      * @param measurements measurements
  96.      * @param estimatedMeasurementsParameters estimated measurements parameters
  97.      * @param observer observer to be notified at model calls
  98.      */
  99.     Model(final NumericalPropagatorBuilder[] builders,
  100.           final List<ObservedMeasurement<?>> measurements, final ParameterDriversList estimatedMeasurementsParameters,
  101.           final ModelObserver observer) {

  102.         this.builders                        = builders;
  103.         this.measurements                    = measurements;
  104.         this.estimatedMeasurementsParameters = estimatedMeasurementsParameters;
  105.         this.measurementParameterColumns     = new HashMap<>(estimatedMeasurementsParameters.getDrivers().size());
  106.         this.estimatedPropagationParameters  = new ParameterDriversList[builders.length];
  107.         this.evaluations                     = new IdentityHashMap<>(measurements.size());
  108.         this.observer                        = observer;
  109.         this.mappers                         = new JacobiansMapper[builders.length];

  110.         // allocate vector and matrix
  111.         int rows = 0;
  112.         for (final ObservedMeasurement<?> measurement : measurements) {
  113.             rows += measurement.getDimension();
  114.         }

  115.         this.orbitsStartColumns = new int[builders.length];
  116.         this.orbitsEndColumns   = new int[builders.length];
  117.         int columns = 0;
  118.         for (int i = 0; i < builders.length; ++i) {
  119.             this.orbitsStartColumns[i] = columns;
  120.             for (final ParameterDriver driver : builders[i].getOrbitalParametersDrivers().getDrivers()) {
  121.                 if (driver.isSelected()) {
  122.                     ++columns;
  123.                 }
  124.             }
  125.             this.orbitsEndColumns[i] = columns;
  126.         }

  127.         // Gather all the propagation drivers names in a list
  128.         final List<String> estimatedPropagationParametersNames = new ArrayList<>();
  129.         for (int i = 0; i < builders.length; ++i) {
  130.             // The index i in array estimatedPropagationParameters (attribute of the class) is populated
  131.             // when the first call to getSelectedPropagationDriversForBuilder(i) is made
  132.             for (final DelegatingDriver delegating : getSelectedPropagationDriversForBuilder(i).getDrivers()) {
  133.                 final String driverName = delegating.getName();
  134.                 // Add the driver name if it has not been added yet
  135.                 if (!estimatedPropagationParametersNames.contains(driverName)) {
  136.                     estimatedPropagationParametersNames.add(driverName);
  137.                 }
  138.             }
  139.         }
  140.         // Populate the map of propagation drivers' columns and update the total number of columns
  141.         propagationParameterColumns = new HashMap<>(estimatedPropagationParametersNames.size());
  142.         for (final String driverName : estimatedPropagationParametersNames) {
  143.             propagationParameterColumns.put(driverName, columns);
  144.             ++columns;
  145.         }


  146.         // Populate the map of measurement drivers' columns and update the total number of columns
  147.         for (final ParameterDriver parameter : estimatedMeasurementsParameters.getDrivers()) {
  148.             measurementParameterColumns.put(parameter.getName(), columns);
  149.             ++columns;
  150.         }

  151.         // Initialize point and value
  152.         value    = new ArrayRealVector(rows);
  153.         jacobian = MatrixUtils.createRealMatrix(rows, columns);

  154.         // Decide whether the propagation will be done forward or backward.
  155.         // Minimize the duration between first measurement treated and orbit determination date
  156.         // Propagator builder number 0 holds the reference date for orbit determination
  157.         final AbsoluteDate refDate = builders[0].getInitialOrbitDate();

  158.         // Sort the measurement list chronologically
  159.         measurements.sort(new ChronologicalComparator());
  160.         firstDate = measurements.get(0).getDate();
  161.         lastDate  = measurements.get(measurements.size() - 1).getDate();

  162.         // Decide the direction of propagation
  163.         if (FastMath.abs(refDate.durationFrom(firstDate)) <= FastMath.abs(refDate.durationFrom(lastDate))) {
  164.             // Propagate forward from firstDate
  165.             forwardPropagation = true;
  166.         } else {
  167.             // Propagate backward from lastDate
  168.             forwardPropagation = false;
  169.         }
  170.     }

  171.     /** Set the counter for evaluations.
  172.      * @param evaluationsCounter counter for evaluations
  173.      */
  174.     void setEvaluationsCounter(final Incrementor evaluationsCounter) {
  175.         this.evaluationsCounter = evaluationsCounter;
  176.     }

  177.     /** Set the counter for iterations.
  178.      * @param iterationsCounter counter for iterations
  179.      */
  180.     void setIterationsCounter(final Incrementor iterationsCounter) {
  181.         this.iterationsCounter = iterationsCounter;
  182.     }

  183.     /** Return the forward propagation flag.
  184.      * @return the forward propagation flag
  185.      */
  186.     boolean isForwardPropagation() {
  187.         return forwardPropagation;
  188.     }

  189.     /** {@inheritDoc} */
  190.     @Override
  191.     public Pair<RealVector, RealMatrix> value(final RealVector point) {

  192.         // Set up the propagators parallelizer
  193.         final NumericalPropagator[] propagators = createPropagators(point);
  194.         final Orbit[] orbits = new Orbit[propagators.length];
  195.         for (int i = 0; i < propagators.length; ++i) {
  196.             mappers[i] = configureDerivatives(propagators[i]);
  197.             orbits[i]  = propagators[i].getInitialState().getOrbit();
  198.         }
  199.         final PropagatorsParallelizer parallelizer =
  200.                         new PropagatorsParallelizer(Arrays.asList(propagators), configureMeasurements(point));

  201.         // Reset value and Jacobian
  202.         evaluations.clear();
  203.         value.set(0.0);
  204.         for (int i = 0; i < jacobian.getRowDimension(); ++i) {
  205.             for (int j = 0; j < jacobian.getColumnDimension(); ++j) {
  206.                 jacobian.setEntry(i, j, 0.0);
  207.             }
  208.         }

  209.         // Run the propagation, gathering residuals on the fly
  210.         if (forwardPropagation) {
  211.             // Propagate forward from firstDate
  212.             parallelizer.propagate(firstDate.shiftedBy(-1.0), lastDate.shiftedBy(+1.0));
  213.         } else {
  214.             // Propagate backward from lastDate
  215.             parallelizer.propagate(lastDate.shiftedBy(+1.0), firstDate.shiftedBy(-1.0));
  216.         }

  217.         observer.modelCalled(orbits, evaluations);

  218.         return new Pair<RealVector, RealMatrix>(value, jacobian);

  219.     }

  220.     /** Get the iterations count.
  221.      * @return iterations count
  222.      */
  223.     public int getIterationsCount() {
  224.         return iterationsCounter.getCount();
  225.     }

  226.     /** Get the evaluations count.
  227.      * @return evaluations count
  228.      */
  229.     public int getEvaluationsCount() {
  230.         return evaluationsCounter.getCount();
  231.     }

  232.     /** Get the selected propagation drivers for a propagatorBuilder.
  233.      * @param iBuilder index of the builder in the builders' array
  234.      * @return the list of selected propagation drivers for propagatorBuilder of index iBuilder
  235.      */
  236.     public ParameterDriversList getSelectedPropagationDriversForBuilder(final int iBuilder) {

  237.         // Lazy evaluation, create the list only if it hasn't been created yet
  238.         if (estimatedPropagationParameters[iBuilder] == null) {

  239.             // Gather the drivers
  240.             final ParameterDriversList selectedPropagationDrivers = new ParameterDriversList();
  241.             for (final DelegatingDriver delegating : builders[iBuilder].getPropagationParametersDrivers().getDrivers()) {
  242.                 if (delegating.isSelected()) {
  243.                     for (final ParameterDriver driver : delegating.getRawDrivers()) {
  244.                         selectedPropagationDrivers.add(driver);
  245.                     }
  246.                 }
  247.             }

  248.             // List of propagation drivers are sorted in the BatchLSEstimator class.
  249.             // Hence we need to sort this list so the parameters' indexes match
  250.             selectedPropagationDrivers.sort();

  251.             // Add the list of selected propagation drivers to the array
  252.             estimatedPropagationParameters[iBuilder] = selectedPropagationDrivers;
  253.         }
  254.         return estimatedPropagationParameters[iBuilder];
  255.     }

  256.     /** Create the propagators and parameters corresponding to an evaluation point.
  257.      * @param point evaluation point
  258.      * @return an array of new propagators
  259.      */
  260.     public NumericalPropagator[] createPropagators(final RealVector point) {

  261.         final NumericalPropagator[] propagators = new NumericalPropagator[builders.length];

  262.         // Set up the propagators
  263.         for (int i = 0; i < builders.length; ++i) {

  264.             // Get the number of selected orbital drivers in the builder
  265.             final int nbOrb    = orbitsEndColumns[i] - orbitsStartColumns[i];

  266.             // Get the list of selected propagation drivers in the builder and its size
  267.             final ParameterDriversList selectedPropagationDrivers = getSelectedPropagationDriversForBuilder(i);
  268.             final int nbParams = selectedPropagationDrivers.getNbParams();

  269.             // Init the array of normalized parameters for the builder
  270.             final double[] propagatorArray = new double[nbOrb + nbParams];

  271.             // Add the orbital drivers normalized values
  272.             for (int j = 0; j < nbOrb; ++j) {
  273.                 propagatorArray[j] = point.getEntry(orbitsStartColumns[i] + j);
  274.             }

  275.             // Add the propagation drivers normalized values
  276.             for (int j = 0; j < nbParams; ++j) {
  277.                 propagatorArray[nbOrb + j] =
  278.                                 point.getEntry(propagationParameterColumns.get(selectedPropagationDrivers.getDrivers().get(j).getName()));
  279.             }

  280.             // Build the propagator
  281.             propagators[i] = builders[i].buildPropagator(propagatorArray);
  282.         }

  283.         return propagators;

  284.     }

  285.     /** Configure the multi-satellites handler to handle measurements.
  286.      * @param point evaluation point
  287.      * @return multi-satellites handler to handle measurements
  288.      */
  289.     private MultiSatStepHandler configureMeasurements(final RealVector point) {

  290.         // Set up the measurement parameters
  291.         int index = orbitsEndColumns[builders.length - 1] + propagationParameterColumns.size();
  292.         for (final ParameterDriver parameter : estimatedMeasurementsParameters.getDrivers()) {
  293.             parameter.setNormalizedValue(point.getEntry(index++));
  294.         }

  295.         // Set up measurements handler
  296.         final List<PreCompensation> precompensated = new ArrayList<>();
  297.         for (final ObservedMeasurement<?> measurement : measurements) {
  298.             if (measurement.isEnabled()) {
  299.                 precompensated.add(new PreCompensation(measurement, evaluations.get(measurement)));
  300.             }
  301.         }
  302.         precompensated.sort(new ChronologicalComparator());

  303.         // Assign first and last date
  304.         firstDate = precompensated.get(0).getDate();
  305.         lastDate  = precompensated.get(precompensated.size() - 1).getDate();

  306.         // Reverse the list in case of backward propagation
  307.         if (!forwardPropagation) {
  308.             Collections.reverse(precompensated);
  309.         }

  310.         return new MeasurementHandler(this, precompensated);

  311.     }

  312.     /** Configure the propagator to compute derivatives.
  313.      * @param propagator {@link Propagator} to configure
  314.      * @return mapper for this propagator
  315.      */
  316.     private JacobiansMapper configureDerivatives(final NumericalPropagator propagator) {

  317.         final String equationName = Model.class.getName() + "-derivatives";
  318.         final PartialDerivativesEquations partials = new PartialDerivativesEquations(equationName, propagator);

  319.         // add the derivatives to the initial state
  320.         final SpacecraftState rawState = propagator.getInitialState();
  321.         final SpacecraftState stateWithDerivatives = partials.setInitialJacobians(rawState);
  322.         propagator.resetInitialState(stateWithDerivatives);

  323.         return partials.getMapper();

  324.     }

  325.     /** Fetch a measurement that was evaluated during propagation.
  326.      * @param index index of the measurement first component
  327.      * @param evaluation measurement evaluation
  328.      */
  329.     void fetchEvaluatedMeasurement(final int index, final EstimatedMeasurement<?> evaluation) {

  330.         // States and observed measurement
  331.         final SpacecraftState[]      evaluationStates    = evaluation.getStates();
  332.         final ObservedMeasurement<?> observedMeasurement = evaluation.getObservedMeasurement();

  333.         evaluations.put(observedMeasurement, evaluation);

  334.         if (evaluation.getStatus() == EstimatedMeasurement.Status.REJECTED) {
  335.             return;
  336.         }

  337.         // compute weighted residuals
  338.         final double[] evaluated = evaluation.getEstimatedValue();
  339.         final double[] observed  = observedMeasurement.getObservedValue();
  340.         final double[] sigma     = observedMeasurement.getTheoreticalStandardDeviation();
  341.         final double[] weight    = evaluation.getObservedMeasurement().getBaseWeight();
  342.         for (int i = 0; i < evaluated.length; ++i) {
  343.             value.setEntry(index + i, weight[i] * (evaluated[i] - observed[i]) / sigma[i]);
  344.         }

  345.         for (int k = 0; k < evaluationStates.length; ++k) {

  346.             final int p = observedMeasurement.getSatellites().get(k).getPropagatorIndex();

  347.             // partial derivatives of the current Cartesian coordinates with respect to current orbital state
  348.             final double[][] aCY = new double[6][6];
  349.             final Orbit currentOrbit = evaluationStates[k].getOrbit();
  350.             currentOrbit.getJacobianWrtParameters(builders[p].getPositionAngle(), aCY);
  351.             final RealMatrix dCdY = new Array2DRowRealMatrix(aCY, false);

  352.             // Jacobian of the measurement with respect to current orbital state
  353.             final RealMatrix dMdC = new Array2DRowRealMatrix(evaluation.getStateDerivatives(k), false);
  354.             final RealMatrix dMdY = dMdC.multiply(dCdY);

  355.             // Jacobian of the measurement with respect to initial orbital state
  356.             final double[][] aYY0 = new double[6][6];
  357.             mappers[p].getStateJacobian(evaluationStates[k], aYY0);
  358.             final RealMatrix dYdY0 = new Array2DRowRealMatrix(aYY0, false);
  359.             final RealMatrix dMdY0 = dMdY.multiply(dYdY0);
  360.             for (int i = 0; i < dMdY0.getRowDimension(); ++i) {
  361.                 int jOrb = orbitsStartColumns[p];
  362.                 for (int j = 0; j < dMdY0.getColumnDimension(); ++j) {
  363.                     final ParameterDriver driver = builders[p].getOrbitalParametersDrivers().getDrivers().get(j);
  364.                     if (driver.isSelected()) {
  365.                         jacobian.setEntry(index + i, jOrb++,
  366.                                           weight[i] * dMdY0.getEntry(i, j) / sigma[i] * driver.getScale());
  367.                     }
  368.                 }
  369.             }

  370.             // Jacobian of the measurement with respect to propagation parameters
  371.             final ParameterDriversList selectedPropagationDrivers = getSelectedPropagationDriversForBuilder(p);
  372.             final int nbParams = selectedPropagationDrivers.getNbParams();
  373.             if (nbParams > 0) {
  374.                 final double[][] aYPp  = new double[6][nbParams];
  375.                 mappers[p].getParametersJacobian(evaluationStates[k], aYPp);
  376.                 final RealMatrix dYdPp = new Array2DRowRealMatrix(aYPp, false);
  377.                 final RealMatrix dMdPp = dMdY.multiply(dYdPp);
  378.                 for (int i = 0; i < dMdPp.getRowDimension(); ++i) {
  379.                     for (int j = 0; j < nbParams; ++j) {
  380.                         final ParameterDriver delegating = selectedPropagationDrivers.getDrivers().get(j);
  381.                         jacobian.addToEntry(index + i, propagationParameterColumns.get(delegating.getName()),
  382.                                             weight[i] * dMdPp.getEntry(i, j) / sigma[i] * delegating.getScale());
  383.                     }
  384.                 }
  385.             }

  386.         }

  387.         // Jacobian of the measurement with respect to measurements parameters
  388.         for (final ParameterDriver driver : observedMeasurement.getParametersDrivers()) {
  389.             if (driver.isSelected()) {
  390.                 final double[] aMPm = evaluation.getParameterDerivatives(driver);
  391.                 for (int i = 0; i < aMPm.length; ++i) {
  392.                     jacobian.setEntry(index + i, measurementParameterColumns.get(driver.getName()),
  393.                                       weight[i] * aMPm[i] / sigma[i] * driver.getScale());
  394.                 }
  395.             }
  396.         }

  397.     }

  398. }