Model.java

  1. /* Copyright 2002-2018 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.errors.OrekitException;
  35. import org.orekit.errors.OrekitExceptionWrapper;
  36. import org.orekit.estimation.measurements.EstimatedMeasurement;
  37. import org.orekit.estimation.measurements.ObservedMeasurement;
  38. import org.orekit.orbits.Orbit;
  39. import org.orekit.propagation.Propagator;
  40. import org.orekit.propagation.PropagatorsParallelizer;
  41. import org.orekit.propagation.SpacecraftState;
  42. import org.orekit.propagation.conversion.NumericalPropagatorBuilder;
  43. import org.orekit.propagation.numerical.JacobiansMapper;
  44. import org.orekit.propagation.numerical.NumericalPropagator;
  45. import org.orekit.propagation.numerical.PartialDerivativesEquations;
  46. import org.orekit.propagation.sampling.MultiSatStepHandler;
  47. import org.orekit.time.AbsoluteDate;
  48. import org.orekit.time.ChronologicalComparator;
  49. import org.orekit.utils.ParameterDriver;
  50. import org.orekit.utils.ParameterDriversList;
  51. import org.orekit.utils.ParameterDriversList.DelegatingDriver;

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

  59.     /** Builders for propagators. */
  60.     private final NumericalPropagatorBuilder[] builders;

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

  63.     /** Estimated measurements parameters. */
  64.     private final ParameterDriversList estimatedMeasurementsParameters;

  65.     /** Measurements. */
  66.     private final List<ObservedMeasurement<?>> measurements;

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

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

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

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

  75.     /** Last evaluations. */
  76.     private final Map<ObservedMeasurement<?>, EstimatedMeasurement<?>> evaluations;

  77.     /** Observer to be notified at orbit changes. */
  78.     private final ModelObserver observer;

  79.     /** Counter for the evaluations. */
  80.     private Incrementor evaluationsCounter;

  81.     /** Counter for the iterations. */
  82.     private Incrementor iterationsCounter;

  83.     /** Date of the first enabled measurement. */
  84.     private AbsoluteDate firstDate;

  85.     /** Date of the last enabled measurement. */
  86.     private AbsoluteDate lastDate;

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

  89.     /** Mappers for Jacobians. */
  90.     private JacobiansMapper[] mappers;

  91.     /** Model function value. */
  92.     private RealVector value;

  93.     /** Model function Jacobian. */
  94.     private RealMatrix jacobian;

  95.     /** Simple constructor.
  96.      * @param builders builders to use for propagation
  97.      * @param measurements measurements
  98.      * @param estimatedMeasurementsParameters estimated measurements parameters
  99.      * @param observer observer to be notified at model calls
  100.      * @exception OrekitException if some propagator parameter cannot be set properly
  101.      */
  102.     Model(final NumericalPropagatorBuilder[] builders,
  103.           final List<ObservedMeasurement<?>> measurements, final ParameterDriversList estimatedMeasurementsParameters,
  104.           final ModelObserver observer)
  105.         throws OrekitException {

  106.         this.builders                        = builders;
  107.         this.measurements                    = measurements;
  108.         this.estimatedMeasurementsParameters = estimatedMeasurementsParameters;
  109.         this.measurementParameterColumns     = new HashMap<>(estimatedMeasurementsParameters.getDrivers().size());
  110.         this.estimatedPropagationParameters  = new ParameterDriversList[builders.length];
  111.         this.evaluations                     = new IdentityHashMap<>(measurements.size());
  112.         this.observer                        = observer;
  113.         this.mappers                         = new JacobiansMapper[builders.length];

  114.         // allocate vector and matrix
  115.         int rows = 0;
  116.         for (final ObservedMeasurement<?> measurement : measurements) {
  117.             rows += measurement.getDimension();
  118.         }

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

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


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

  155.         // Initialize point and value
  156.         value    = new ArrayRealVector(rows);
  157.         jacobian = MatrixUtils.createRealMatrix(rows, columns);

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

  162.         // Sort the measurement list chronologically
  163.         measurements.sort(new ChronologicalComparator());
  164.         firstDate = measurements.get(0).getDate();
  165.         lastDate  = measurements.get(measurements.size() - 1).getDate();

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

  175.     /** Set the counter for evaluations.
  176.      * @param evaluationsCounter counter for evaluations
  177.      */
  178.     void setEvaluationsCounter(final Incrementor evaluationsCounter) {
  179.         this.evaluationsCounter = evaluationsCounter;
  180.     }

  181.     /** Set the counter for iterations.
  182.      * @param iterationsCounter counter for iterations
  183.      */
  184.     void setIterationsCounter(final Incrementor iterationsCounter) {
  185.         this.iterationsCounter = iterationsCounter;
  186.     }

  187.     /** Return the forward propagation flag.
  188.      * @return the forward propagation flag
  189.      */
  190.     boolean isForwardPropagation() {
  191.         return forwardPropagation;
  192.     }

  193.     /** {@inheritDoc} */
  194.     @Override
  195.     public Pair<RealVector, RealMatrix> value(final RealVector point)
  196.         throws OrekitExceptionWrapper {
  197.         try {

  198.             // Set up the propagators parallelizer
  199.             final NumericalPropagator[] propagators = createPropagators(point);
  200.             final Orbit[] orbits = new Orbit[propagators.length];
  201.             for (int i = 0; i < propagators.length; ++i) {
  202.                 mappers[i] = configureDerivatives(propagators[i]);
  203.                 orbits[i]  = propagators[i].getInitialState().getOrbit();
  204.             }
  205.             final PropagatorsParallelizer parallelizer =
  206.                             new PropagatorsParallelizer(Arrays.asList(propagators), configureMeasurements(point));

  207.             // Reset value and Jacobian
  208.             evaluations.clear();
  209.             value.set(0.0);
  210.             for (int i = 0; i < jacobian.getRowDimension(); ++i) {
  211.                 for (int j = 0; j < jacobian.getColumnDimension(); ++j) {
  212.                     jacobian.setEntry(i, j, 0.0);
  213.                 }
  214.             }

  215.             // Run the propagation, gathering residuals on the fly
  216.             if (forwardPropagation) {
  217.                 // Propagate forward from firstDate
  218.                 parallelizer.propagate(firstDate.shiftedBy(-1.0), lastDate.shiftedBy(+1.0));
  219.             } else {
  220.                 // Propagate backward from lastDate
  221.                 parallelizer.propagate(lastDate.shiftedBy(+1.0), firstDate.shiftedBy(-1.0));
  222.             }

  223.             observer.modelCalled(orbits, evaluations);

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

  225.         } catch (OrekitException oe) {
  226.             throw new OrekitExceptionWrapper(oe);
  227.         }
  228.     }

  229.     /** Get the iterations count.
  230.      * @return iterations count
  231.      */
  232.     public int getIterationsCount() {
  233.         return iterationsCounter.getCount();
  234.     }

  235.     /** Get the evaluations count.
  236.      * @return evaluations count
  237.      */
  238.     public int getEvaluationsCount() {
  239.         return evaluationsCounter.getCount();
  240.     }

  241.     /** Get the selected propagation drivers for a propagatorBuilder.
  242.      * @param iBuilder index of the builder in the builders' array
  243.      * @return the list of selected propagation drivers for propagatorBuilder of index iBuilder
  244.      * @exception OrekitException if orbit cannot be created with the current point
  245.      */
  246.     public ParameterDriversList getSelectedPropagationDriversForBuilder(final int iBuilder)
  247.         throws OrekitException {

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

  250.             // Gather the drivers
  251.             final ParameterDriversList selectedPropagationDrivers = new ParameterDriversList();
  252.             for (final DelegatingDriver delegating : builders[iBuilder].getPropagationParametersDrivers().getDrivers()) {
  253.                 if (delegating.isSelected()) {
  254.                     for (final ParameterDriver driver : delegating.getRawDrivers()) {
  255.                         selectedPropagationDrivers.add(driver);
  256.                     }
  257.                 }
  258.             }

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

  262.             // Add the list of selected propagation drivers to the array
  263.             estimatedPropagationParameters[iBuilder] = selectedPropagationDrivers;
  264.         }
  265.         return estimatedPropagationParameters[iBuilder];
  266.     }

  267.     /** Create the propagators and parameters corresponding to an evaluation point.
  268.      * @param point evaluation point
  269.      * @return an array of new propagators
  270.      * @exception OrekitException if orbit cannot be created with the current point
  271.      */
  272.     public NumericalPropagator[] createPropagators(final RealVector point)
  273.         throws OrekitException {

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

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

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

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

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

  284.             // Add the orbital drivers normalized values
  285.             for (int j = 0; j < nbOrb; ++j) {
  286.                 propagatorArray[j] = point.getEntry(orbitsStartColumns[i] + j);
  287.             }

  288.             // Add the propagation drivers normalized values
  289.             for (int j = 0; j < nbParams; ++j) {
  290.                 propagatorArray[nbOrb + j] =
  291.                                 point.getEntry(propagationParameterColumns.get(selectedPropagationDrivers.getDrivers().get(j).getName()));
  292.             }

  293.             // Build the propagator
  294.             propagators[i] = builders[i].buildPropagator(propagatorArray);
  295.         }

  296.         return propagators;

  297.     }

  298.     /** Configure the multi-satellites handler to handle measurements.
  299.      * @param point evaluation point
  300.      * @return multi-satellites handler to handle measurements
  301.      * @exception OrekitException if measurements parameters cannot be set with the current point
  302.      */
  303.     private MultiSatStepHandler configureMeasurements(final RealVector point)
  304.         throws OrekitException {

  305.         // Set up the measurement parameters
  306.         int index = orbitsEndColumns[builders.length - 1] + propagationParameterColumns.size();
  307.         for (final ParameterDriver parameter : estimatedMeasurementsParameters.getDrivers()) {
  308.             parameter.setNormalizedValue(point.getEntry(index++));
  309.         }

  310.         // Set up measurements handler
  311.         final List<PreCompensation> precompensated = new ArrayList<>();
  312.         for (final ObservedMeasurement<?> measurement : measurements) {
  313.             if (measurement.isEnabled()) {
  314.                 precompensated.add(new PreCompensation(measurement, evaluations.get(measurement)));
  315.             }
  316.         }
  317.         precompensated.sort(new ChronologicalComparator());

  318.         // Assign first and last date
  319.         firstDate = precompensated.get(0).getDate();
  320.         lastDate  = precompensated.get(precompensated.size() - 1).getDate();

  321.         // Reverse the list in case of backward propagation
  322.         if (!forwardPropagation) {
  323.             Collections.reverse(precompensated);
  324.         }

  325.         return new MeasurementHandler(this, precompensated);

  326.     }

  327.     /** Configure the propagator to compute derivatives.
  328.      * @param propagator {@link Propagator} to configure
  329.      * @return mapper for this propagator
  330.      * @exception OrekitException if orbit cannot be created with the current point
  331.      */
  332.     private JacobiansMapper configureDerivatives(final NumericalPropagator propagator)
  333.         throws OrekitException {

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

  336.         // add the derivatives to the initial state
  337.         final SpacecraftState rawState = propagator.getInitialState();
  338.         final SpacecraftState stateWithDerivatives = partials.setInitialJacobians(rawState);
  339.         propagator.resetInitialState(stateWithDerivatives);

  340.         return partials.getMapper();

  341.     }

  342.     /** Fetch a measurement that was evaluated during propagation.
  343.      * @param index index of the measurement first component
  344.      * @param evaluation measurement evaluation
  345.      * @exception OrekitException if Jacobians cannot be computed
  346.      */
  347.     void fetchEvaluatedMeasurement(final int index, final EstimatedMeasurement<?> evaluation)
  348.         throws OrekitException {

  349.         // States and observed measurement
  350.         final SpacecraftState[]      evaluationStates    = evaluation.getStates();
  351.         final ObservedMeasurement<?> observedMeasurement = evaluation.getObservedMeasurement();

  352.         evaluations.put(observedMeasurement, evaluation);

  353.         if (evaluation.getStatus() == EstimatedMeasurement.Status.REJECTED) {
  354.             return;
  355.         }

  356.         // compute weighted residuals
  357.         final double[] evaluated = evaluation.getEstimatedValue();
  358.         final double[] observed  = observedMeasurement.getObservedValue();
  359.         final double[] sigma     = observedMeasurement.getTheoreticalStandardDeviation();
  360.         final double[] weight    = evaluation.getObservedMeasurement().getBaseWeight();
  361.         for (int i = 0; i < evaluated.length; ++i) {
  362.             value.setEntry(index + i, weight[i] * (evaluated[i] - observed[i]) / sigma[i]);
  363.         }

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

  365.             final int p = observedMeasurement.getPropagatorsIndices().get(k);

  366.             // partial derivatives of the current Cartesian coordinates with respect to current orbital state
  367.             final double[][] aCY = new double[6][6];
  368.             final Orbit currentOrbit = evaluationStates[k].getOrbit();
  369.             currentOrbit.getJacobianWrtParameters(builders[p].getPositionAngle(), aCY);
  370.             final RealMatrix dCdY = new Array2DRowRealMatrix(aCY, false);

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

  374.             // Jacobian of the measurement with respect to initial orbital state
  375.             final double[][] aYY0 = new double[6][6];
  376.             mappers[p].getStateJacobian(evaluationStates[k], aYY0);
  377.             final RealMatrix dYdY0 = new Array2DRowRealMatrix(aYY0, false);
  378.             final RealMatrix dMdY0 = dMdY.multiply(dYdY0);
  379.             for (int i = 0; i < dMdY0.getRowDimension(); ++i) {
  380.                 int jOrb = orbitsStartColumns[p];
  381.                 for (int j = 0; j < dMdY0.getColumnDimension(); ++j) {
  382.                     final ParameterDriver driver = builders[p].getOrbitalParametersDrivers().getDrivers().get(j);
  383.                     if (driver.isSelected()) {
  384.                         jacobian.setEntry(index + i, jOrb++,
  385.                                           weight[i] * dMdY0.getEntry(i, j) / sigma[i] * driver.getScale());
  386.                     }
  387.                 }
  388.             }

  389.             // Jacobian of the measurement with respect to propagation parameters
  390.             final ParameterDriversList selectedPropagationDrivers = getSelectedPropagationDriversForBuilder(p);
  391.             final int nbParams = selectedPropagationDrivers.getNbParams();
  392.             if (nbParams > 0) {
  393.                 final double[][] aYPp  = new double[6][nbParams];
  394.                 mappers[p].getParametersJacobian(evaluationStates[k], aYPp);
  395.                 final RealMatrix dYdPp = new Array2DRowRealMatrix(aYPp, false);
  396.                 final RealMatrix dMdPp = dMdY.multiply(dYdPp);
  397.                 for (int i = 0; i < dMdPp.getRowDimension(); ++i) {
  398.                     for (int j = 0; j < nbParams; ++j) {
  399.                         final ParameterDriver delegating = selectedPropagationDrivers.getDrivers().get(j);
  400.                         jacobian.addToEntry(index + i, propagationParameterColumns.get(delegating.getName()),
  401.                                             weight[i] * dMdPp.getEntry(i, j) / sigma[i] * delegating.getScale());
  402.                     }
  403.                 }
  404.             }

  405.         }

  406.         // Jacobian of the measurement with respect to measurements parameters
  407.         for (final ParameterDriver driver : observedMeasurement.getParametersDrivers()) {
  408.             if (driver.isSelected()) {
  409.                 final double[] aMPm = evaluation.getParameterDerivatives(driver);
  410.                 for (int i = 0; i < aMPm.length; ++i) {
  411.                     jacobian.setEntry(index + i, measurementParameterColumns.get(driver.getName()),
  412.                                       weight[i] * aMPm[i] / sigma[i] * driver.getScale());
  413.                 }
  414.             }
  415.         }

  416.     }

  417. }