DSSTPropagator.java

  1. /* Copyright 2002-2024 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.propagation.semianalytical.dsst;

  18. import org.hipparchus.linear.RealMatrix;
  19. import org.hipparchus.ode.ODEIntegrator;
  20. import org.hipparchus.ode.ODEStateAndDerivative;
  21. import org.hipparchus.ode.sampling.ODEStateInterpolator;
  22. import org.hipparchus.ode.sampling.ODEStepHandler;
  23. import org.hipparchus.util.FastMath;
  24. import org.hipparchus.util.MathUtils;
  25. import org.orekit.annotation.DefaultDataContext;
  26. import org.orekit.attitudes.Attitude;
  27. import org.orekit.attitudes.AttitudeProvider;
  28. import org.orekit.data.DataContext;
  29. import org.orekit.errors.OrekitException;
  30. import org.orekit.errors.OrekitInternalError;
  31. import org.orekit.errors.OrekitMessages;
  32. import org.orekit.frames.Frame;
  33. import org.orekit.orbits.EquinoctialOrbit;
  34. import org.orekit.orbits.Orbit;
  35. import org.orekit.orbits.OrbitType;
  36. import org.orekit.orbits.PositionAngleType;
  37. import org.orekit.propagation.MatricesHarvester;
  38. import org.orekit.propagation.PropagationType;
  39. import org.orekit.propagation.Propagator;
  40. import org.orekit.propagation.SpacecraftState;
  41. import org.orekit.propagation.integration.AbstractIntegratedPropagator;
  42. import org.orekit.propagation.integration.AdditionalDerivativesProvider;
  43. import org.orekit.propagation.integration.StateMapper;
  44. import org.orekit.propagation.numerical.NumericalPropagator;
  45. import org.orekit.propagation.semianalytical.dsst.forces.DSSTForceModel;
  46. import org.orekit.propagation.semianalytical.dsst.forces.DSSTNewtonianAttraction;
  47. import org.orekit.propagation.semianalytical.dsst.forces.ShortPeriodTerms;
  48. import org.orekit.propagation.semianalytical.dsst.utilities.AuxiliaryElements;
  49. import org.orekit.propagation.semianalytical.dsst.utilities.FixedNumberInterpolationGrid;
  50. import org.orekit.propagation.semianalytical.dsst.utilities.InterpolationGrid;
  51. import org.orekit.propagation.semianalytical.dsst.utilities.MaxGapInterpolationGrid;
  52. import org.orekit.time.AbsoluteDate;
  53. import org.orekit.utils.DoubleArrayDictionary;
  54. import org.orekit.utils.ParameterDriver;
  55. import org.orekit.utils.ParameterDriversList;
  56. import org.orekit.utils.ParameterDriversList.DelegatingDriver;
  57. import org.orekit.utils.ParameterObserver;
  58. import org.orekit.utils.TimeSpanMap;
  59. import org.orekit.utils.TimeSpanMap.Span;

  60. import java.util.ArrayList;
  61. import java.util.Arrays;
  62. import java.util.Collection;
  63. import java.util.Collections;
  64. import java.util.HashSet;
  65. import java.util.List;
  66. import java.util.Set;

  67. /**
  68.  * This class propagates {@link org.orekit.orbits.Orbit orbits} using the DSST theory.
  69.  * <p>
  70.  * Whereas analytical propagators are configured only thanks to their various
  71.  * constructors and can be used immediately after construction, such a semianalytical
  72.  * propagator configuration involves setting several parameters between construction
  73.  * time and propagation time, just as numerical propagators.
  74.  * </p>
  75.  * <p>
  76.  * The configuration parameters that can be set are:
  77.  * </p>
  78.  * <ul>
  79.  * <li>the initial spacecraft state ({@link #setInitialState(SpacecraftState)})</li>
  80.  * <li>the various force models ({@link #addForceModel(DSSTForceModel)},
  81.  * {@link #removeForceModels()})</li>
  82.  * <li>the discrete events that should be triggered during propagation (
  83.  * {@link #addEventDetector(org.orekit.propagation.events.EventDetector)},
  84.  * {@link #clearEventsDetectors()})</li>
  85.  * <li>the binding logic with the rest of the application ({@link #getMultiplexer()})</li>
  86.  * </ul>
  87.  * <p>
  88.  * From these configuration parameters, only the initial state is mandatory.
  89.  * The default propagation settings are in {@link OrbitType#EQUINOCTIAL equinoctial}
  90.  * parameters with {@link PositionAngleType#TRUE true} longitude argument.
  91.  * The central attraction coefficient used to define the initial orbit will be used.
  92.  * However, specifying only the initial state would mean the propagator would use
  93.  * only Keplerian forces. In this case, the simpler
  94.  * {@link org.orekit.propagation.analytical.KeplerianPropagator KeplerianPropagator}
  95.  * class would be more effective.
  96.  * </p>
  97.  * <p>
  98.  * The underlying numerical integrator set up in the constructor may also have
  99.  * its own configuration parameters. Typical configuration parameters for adaptive
  100.  * stepsize integrators are the min, max and perhaps start step size as well as
  101.  * the absolute and/or relative errors thresholds.
  102.  * </p>
  103.  * <p>
  104.  * The state that is seen by the integrator is a simple six elements double array.
  105.  * These six elements are:
  106.  * <ul>
  107.  * <li>the {@link org.orekit.orbits.EquinoctialOrbit equinoctial orbit parameters}
  108.  * (a, e<sub>x</sub>, e<sub>y</sub>, h<sub>x</sub>, h<sub>y</sub>, λ<sub>m</sub>)
  109.  * in meters and radians,</li>
  110.  * </ul>
  111.  *
  112.  * <p>By default, at the end of the propagation, the propagator resets the initial state to the final state,
  113.  * thus allowing a new propagation to be started from there without recomputing the part already performed.
  114.  * This behaviour can be chenged by calling {@link #setResetAtEnd(boolean)}.
  115.  * </p>
  116.  * <p>Beware the same instance cannot be used simultaneously by different threads, the class is <em>not</em>
  117.  * thread-safe.</p>
  118.  *
  119.  * @see SpacecraftState
  120.  * @see DSSTForceModel
  121.  * @author Romain Di Costanzo
  122.  * @author Pascal Parraud
  123.  */
  124. public class DSSTPropagator extends AbstractIntegratedPropagator {

  125.     /** Retrograde factor I.
  126.      *  <p>
  127.      *  DSST model needs equinoctial orbit as internal representation.
  128.      *  Classical equinoctial elements have discontinuities when inclination
  129.      *  is close to zero. In this representation, I = +1. <br>
  130.      *  To avoid this discontinuity, another representation exists and equinoctial
  131.      *  elements can be expressed in a different way, called "retrograde" orbit.
  132.      *  This implies I = -1. <br>
  133.      *  As Orekit doesn't implement the retrograde orbit, I is always set to +1.
  134.      *  But for the sake of consistency with the theory, the retrograde factor
  135.      *  has been kept in the formulas.
  136.      *  </p>
  137.      */
  138.     private static final int I = 1;

  139.     /** Default value for epsilon. */
  140.     private static final double EPSILON_DEFAULT = 1.0e-13;

  141.     /** Default value for maxIterations. */
  142.     private static final int MAX_ITERATIONS_DEFAULT = 200;

  143.     /** Number of grid points per integration step to be used in interpolation of short periodics coefficients.*/
  144.     private static final int INTERPOLATION_POINTS_PER_STEP = 3;

  145.     /** Flag specifying whether the initial orbital state is given with osculating elements. */
  146.     private boolean initialIsOsculating;

  147.     /** Force models used to compute short periodic terms. */
  148.     private final transient List<DSSTForceModel> forceModels;

  149.     /** State mapper holding the force models. */
  150.     private MeanPlusShortPeriodicMapper mapper;

  151.     /** Generator for the interpolation grid. */
  152.     private InterpolationGrid interpolationgrid;

  153.     /**
  154.      * Same as {@link org.orekit.propagation.AbstractPropagator#harvester} but with the
  155.      * more specific type. Saved to avoid a cast.
  156.      */
  157.     private DSSTHarvester harvester;

  158.     /** Create a new instance of DSSTPropagator.
  159.      *  <p>
  160.      *  After creation, there are no perturbing forces at all.
  161.      *  This means that if {@link #addForceModel addForceModel}
  162.      *  is not called after creation, the integrated orbit will
  163.      *  follow a Keplerian evolution only.
  164.      *  </p>
  165.      *
  166.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  167.      *
  168.      *  @param integrator numerical integrator to use for propagation.
  169.      *  @param propagationType type of orbit to output (mean or osculating).
  170.      * @see #DSSTPropagator(ODEIntegrator, PropagationType, AttitudeProvider)
  171.      */
  172.     @DefaultDataContext
  173.     public DSSTPropagator(final ODEIntegrator integrator, final PropagationType propagationType) {
  174.         this(integrator, propagationType,
  175.                 Propagator.getDefaultLaw(DataContext.getDefault().getFrames()));
  176.     }

  177.     /** Create a new instance of DSSTPropagator.
  178.      *  <p>
  179.      *  After creation, there are no perturbing forces at all.
  180.      *  This means that if {@link #addForceModel addForceModel}
  181.      *  is not called after creation, the integrated orbit will
  182.      *  follow a Keplerian evolution only.
  183.      *  </p>
  184.      * @param integrator numerical integrator to use for propagation.
  185.      * @param propagationType type of orbit to output (mean or osculating).
  186.      * @param attitudeProvider the attitude law.
  187.      * @since 10.1
  188.      */
  189.     public DSSTPropagator(final ODEIntegrator integrator,
  190.                           final PropagationType propagationType,
  191.                           final AttitudeProvider attitudeProvider) {
  192.         super(integrator, propagationType);
  193.         forceModels = new ArrayList<>();
  194.         initMapper();
  195.         // DSST uses only equinoctial orbits and mean longitude argument
  196.         setOrbitType(OrbitType.EQUINOCTIAL);
  197.         setPositionAngleType(PositionAngleType.MEAN);
  198.         setAttitudeProvider(attitudeProvider);
  199.         setInterpolationGridToFixedNumberOfPoints(INTERPOLATION_POINTS_PER_STEP);
  200.     }


  201.     /** Create a new instance of DSSTPropagator.
  202.      *  <p>
  203.      *  After creation, there are no perturbing forces at all.
  204.      *  This means that if {@link #addForceModel addForceModel}
  205.      *  is not called after creation, the integrated orbit will
  206.      *  follow a Keplerian evolution only. Only the mean orbits
  207.      *  will be generated.
  208.      *  </p>
  209.      *
  210.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  211.      *
  212.      *  @param integrator numerical integrator to use for propagation.
  213.      * @see #DSSTPropagator(ODEIntegrator, PropagationType, AttitudeProvider)
  214.      */
  215.     @DefaultDataContext
  216.     public DSSTPropagator(final ODEIntegrator integrator) {
  217.         this(integrator, PropagationType.MEAN);
  218.     }

  219.     /** Set the central attraction coefficient μ.
  220.      * <p>
  221.      * Setting the central attraction coefficient is
  222.      * equivalent to {@link #addForceModel(DSSTForceModel) add}
  223.      * a {@link DSSTNewtonianAttraction} force model.
  224.      * </p>
  225.     * @param mu central attraction coefficient (m³/s²)
  226.     * @see #addForceModel(DSSTForceModel)
  227.     * @see #getAllForceModels()
  228.     */
  229.     public void setMu(final double mu) {
  230.         addForceModel(new DSSTNewtonianAttraction(mu));
  231.     }

  232.     /** Set the central attraction coefficient μ only in upper class.
  233.      * @param mu central attraction coefficient (m³/s²)
  234.      */
  235.     private void superSetMu(final double mu) {
  236.         super.setMu(mu);
  237.     }

  238.     /** Check if Newtonian attraction force model is available.
  239.      * <p>
  240.      * Newtonian attraction is always the last force model in the list.
  241.      * </p>
  242.      * @return true if Newtonian attraction force model is available
  243.      */
  244.     private boolean hasNewtonianAttraction() {
  245.         final int last = forceModels.size() - 1;
  246.         return last >= 0 && forceModels.get(last) instanceof DSSTNewtonianAttraction;
  247.     }

  248.     /** Set the initial state with osculating orbital elements.
  249.      *  @param initialState initial state (defined with osculating elements)
  250.      */
  251.     public void setInitialState(final SpacecraftState initialState) {
  252.         setInitialState(initialState, PropagationType.OSCULATING);
  253.     }

  254.     /** Set the initial state.
  255.      *  @param initialState initial state
  256.      *  @param stateType defined if the orbital state is defined with osculating or mean elements
  257.      */
  258.     public void setInitialState(final SpacecraftState initialState,
  259.                                 final PropagationType stateType) {
  260.         switch (stateType) {
  261.             case MEAN:
  262.                 initialIsOsculating = false;
  263.                 break;
  264.             case OSCULATING:
  265.                 initialIsOsculating = true;
  266.                 break;
  267.             default:
  268.                 throw new OrekitInternalError(null);
  269.         }
  270.         resetInitialState(initialState);
  271.     }

  272.     /** Reset the initial state.
  273.      *
  274.      *  @param state new initial state
  275.      */
  276.     @Override
  277.     public void resetInitialState(final SpacecraftState state) {
  278.         super.resetInitialState(state);
  279.         if (!hasNewtonianAttraction()) {
  280.             // use the state to define central attraction
  281.             setMu(state.getMu());
  282.         }
  283.         super.setStartDate(state.getDate());
  284.     }

  285.     /** Set the selected short periodic coefficients that must be stored as additional states.
  286.      * @param selectedCoefficients short periodic coefficients that must be stored as additional states
  287.      * (null means no coefficients are selected, empty set means all coefficients are selected)
  288.      */
  289.     public void setSelectedCoefficients(final Set<String> selectedCoefficients) {
  290.         mapper.setSelectedCoefficients(selectedCoefficients == null ? null : new HashSet<>(selectedCoefficients));
  291.     }

  292.     /** Get the selected short periodic coefficients that must be stored as additional states.
  293.      * @return short periodic coefficients that must be stored as additional states
  294.      * (null means no coefficients are selected, empty set means all coefficients are selected)
  295.      */
  296.     public Set<String> getSelectedCoefficients() {
  297.         final Set<String> set = mapper.getSelectedCoefficients();
  298.         return set == null ? null : Collections.unmodifiableSet(set);
  299.     }

  300.     /** Get the names of the parameters in the matrix returned by {@link MatricesHarvester#getParametersJacobian}.
  301.      * @return names of the parameters (i.e. columns) of the Jacobian matrix
  302.      */
  303.     protected List<String> getJacobiansColumnsNames() {
  304.         final List<String> columnsNames = new ArrayList<>();
  305.         for (final DSSTForceModel forceModel : getAllForceModels()) {
  306.             for (final ParameterDriver driver : forceModel.getParametersDrivers()) {
  307.                 if (driver.isSelected() && !columnsNames.contains(driver.getNamesSpanMap().getFirstSpan().getData())) {
  308.                     // As driver with same name should have same NamesSpanMap we only check if the first span is present,
  309.                     // if not we add all span names to columnsNames
  310.                     for (Span<String> span = driver.getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {
  311.                         columnsNames.add(span.getData());
  312.                     }
  313.                 }
  314.             }
  315.         }
  316.         Collections.sort(columnsNames);
  317.         return columnsNames;
  318.     }

  319.     /** {@inheritDoc} */
  320.     @Override
  321.     public DSSTHarvester setupMatricesComputation(
  322.             final String stmName,
  323.             final RealMatrix initialStm,
  324.             final DoubleArrayDictionary initialJacobianColumns) {

  325.         if (stmName == null) {
  326.             throw new OrekitException(OrekitMessages.NULL_ARGUMENT, "stmName");
  327.         }
  328.         final DSSTHarvester dsstHarvester =
  329.                 createHarvester(stmName, initialStm, initialJacobianColumns);
  330.         return this.harvester = dsstHarvester;
  331.     }

  332.     /** {@inheritDoc} */
  333.     @Override
  334.     protected DSSTHarvester createHarvester(final String stmName, final RealMatrix initialStm,
  335.                                             final DoubleArrayDictionary initialJacobianColumns) {
  336.         final DSSTHarvester dsstHarvester =
  337.                 new DSSTHarvester(this, stmName, initialStm, initialJacobianColumns);
  338.         this.harvester = dsstHarvester;
  339.         return dsstHarvester;
  340.     }

  341.     /** {@inheritDoc} */
  342.     @Override
  343.     protected DSSTHarvester getHarvester() {
  344.         return harvester;
  345.     }

  346.     /** {@inheritDoc} */
  347.     @Override
  348.     protected void setUpStmAndJacobianGenerators() {

  349.         final DSSTHarvester dsstHarvester = getHarvester();
  350.         if (dsstHarvester != null) {

  351.             // set up the additional equations and additional state providers
  352.             final DSSTStateTransitionMatrixGenerator stmGenerator = setUpStmGenerator();
  353.             setUpRegularParametersJacobiansColumns(stmGenerator);

  354.             // as we are now starting the propagation, everything is configured
  355.             // we can freeze the names in the harvester
  356.             dsstHarvester.freezeColumnsNames();

  357.         }

  358.     }

  359.     /** Set up the State Transition Matrix Generator.
  360.      * @return State Transition Matrix Generator
  361.      * @since 11.1
  362.      */
  363.     private DSSTStateTransitionMatrixGenerator setUpStmGenerator() {

  364.         final DSSTHarvester dsstHarvester = getHarvester();

  365.         // add the STM generator corresponding to the current settings, and setup state accordingly
  366.         DSSTStateTransitionMatrixGenerator stmGenerator = null;
  367.         for (final AdditionalDerivativesProvider equations : getAdditionalDerivativesProviders()) {
  368.             if (equations instanceof DSSTStateTransitionMatrixGenerator &&
  369.                 equations.getName().equals(dsstHarvester.getStmName())) {
  370.                 // the STM generator has already been set up in a previous propagation
  371.                 stmGenerator = (DSSTStateTransitionMatrixGenerator) equations;
  372.                 break;
  373.             }
  374.         }
  375.         if (stmGenerator == null) {
  376.             // this is the first time we need the STM generate, create it
  377.             stmGenerator = new DSSTStateTransitionMatrixGenerator(dsstHarvester.getStmName(),
  378.                                                                   getAllForceModels(),
  379.                                                                   getAttitudeProvider(),
  380.                                                                   getPropagationType());
  381.             addAdditionalDerivativesProvider(stmGenerator);
  382.         }

  383.         if (!getInitialIntegrationState().hasAdditionalState(dsstHarvester.getStmName())) {
  384.             // add the initial State Transition Matrix if it is not already there
  385.             // (perhaps due to a previous propagation)
  386.             setInitialState(stmGenerator.setInitialStateTransitionMatrix(getInitialState(),
  387.                                                                          dsstHarvester.getInitialStateTransitionMatrix()),
  388.                             getPropagationType());
  389.         }

  390.         return stmGenerator;

  391.     }

  392.     /** Set up the Jacobians columns generator for regular parameters.
  393.      * @param stmGenerator generator for the State Transition Matrix
  394.      * @since 11.1
  395.      */
  396.     private void setUpRegularParametersJacobiansColumns(final DSSTStateTransitionMatrixGenerator stmGenerator) {

  397.         // first pass: gather all parameters (excluding trigger dates), binding similar names together
  398.         final ParameterDriversList selected = new ParameterDriversList();
  399.         for (final DSSTForceModel forceModel : getAllForceModels()) {
  400.             for (final ParameterDriver driver : forceModel.getParametersDrivers()) {
  401.                 selected.add(driver);
  402.             }
  403.         }

  404.         // second pass: now that shared parameter names are bound together,
  405.         // their selections status have been synchronized, we can filter them
  406.         selected.filter(true);

  407.         // third pass: sort parameters lexicographically
  408.         selected.sort();

  409.         // add the Jacobians column generators corresponding to parameters, and setup state accordingly
  410.         for (final DelegatingDriver driver : selected.getDrivers()) {

  411.             for (Span<String> span = driver.getNamesSpanMap().getFirstSpan(); span != null; span = span.next()) {
  412.                 DSSTIntegrableJacobianColumnGenerator generator = null;

  413.                 // check if we already have set up the providers
  414.                 for (final AdditionalDerivativesProvider provider : getAdditionalDerivativesProviders()) {
  415.                     if (provider instanceof DSSTIntegrableJacobianColumnGenerator &&
  416.                         provider.getName().equals(span.getData())) {
  417.                         // the Jacobian column generator has already been set up in a previous propagation
  418.                         generator = (DSSTIntegrableJacobianColumnGenerator) provider;
  419.                         break;
  420.                     }
  421.                 }

  422.                 if (generator == null) {
  423.                     // this is the first time we need the Jacobian column generator, create it
  424.                     generator = new DSSTIntegrableJacobianColumnGenerator(stmGenerator, span.getData());
  425.                     addAdditionalDerivativesProvider(generator);
  426.                 }

  427.                 if (!getInitialIntegrationState().hasAdditionalState(span.getData())) {
  428.                     // add the initial Jacobian column if it is not already there
  429.                     // (perhaps due to a previous propagation)
  430.                     setInitialState(getInitialState().addAdditionalState(span.getData(),
  431.                                                                          getHarvester().getInitialJacobianColumn(span.getData())),
  432.                                     getPropagationType());
  433.                 }
  434.             }

  435.         }

  436.     }

  437.     /** Check if the initial state is provided in osculating elements.
  438.      * @return true if initial state is provided in osculating elements
  439.      */
  440.     public boolean initialIsOsculating() {
  441.         return initialIsOsculating;
  442.     }

  443.     /** Set the interpolation grid generator.
  444.      * <p>
  445.      * The generator will create an interpolation grid with a fixed
  446.      * number of points for each mean element integration step.
  447.      * </p>
  448.      * <p>
  449.      * If neither {@link #setInterpolationGridToFixedNumberOfPoints(int)}
  450.      * nor {@link #setInterpolationGridToMaxTimeGap(double)} has been called,
  451.      * by default the propagator is set as to 3 interpolations points per step.
  452.      * </p>
  453.      * @param interpolationPoints number of interpolation points at
  454.      * each integration step
  455.      * @see #setInterpolationGridToMaxTimeGap(double)
  456.      * @since 7.1
  457.      */
  458.     public void setInterpolationGridToFixedNumberOfPoints(final int interpolationPoints) {
  459.         interpolationgrid = new FixedNumberInterpolationGrid(interpolationPoints);
  460.     }

  461.     /** Set the interpolation grid generator.
  462.      * <p>
  463.      * The generator will create an interpolation grid with a maximum
  464.      * time gap between interpolation points.
  465.      * </p>
  466.      * <p>
  467.      * If neither {@link #setInterpolationGridToFixedNumberOfPoints(int)}
  468.      * nor {@link #setInterpolationGridToMaxTimeGap(double)} has been called,
  469.      * by default the propagator is set as to 3 interpolations points per step.
  470.      * </p>
  471.      * @param maxGap maximum time gap between interpolation points (seconds)
  472.      * @see #setInterpolationGridToFixedNumberOfPoints(int)
  473.      * @since 7.1
  474.      */
  475.     public void setInterpolationGridToMaxTimeGap(final double maxGap) {
  476.         interpolationgrid = new MaxGapInterpolationGrid(maxGap);
  477.     }

  478.     /** Add a force model to the global perturbation model.
  479.      *  <p>
  480.      *  If this method is not called at all,
  481.      *  the integrated orbit will follow a Keplerian evolution only.
  482.      *  </p>
  483.      *  @param force perturbing {@link DSSTForceModel force} to add
  484.      *  @see #removeForceModels()
  485.      *  @see #setMu(double)
  486.      */
  487.     public void addForceModel(final DSSTForceModel force) {

  488.         if (force instanceof DSSTNewtonianAttraction) {
  489.             // we want to add the central attraction force model

  490.             // ensure we are notified of any mu change
  491.             force.getParametersDrivers().get(0).addObserver(new ParameterObserver() {
  492.                 /** {@inheritDoc} */
  493.                 @Override
  494.                 public void valueChanged(final double previousValue, final ParameterDriver driver, final AbsoluteDate date) {
  495.                     // mu PDriver should have only 1 span
  496.                     superSetMu(driver.getValue());
  497.                 }
  498.                 /** {@inheritDoc} */
  499.                 @Override
  500.                 public void valueSpanMapChanged(final TimeSpanMap<Double> previousValue, final ParameterDriver driver) {
  501.                     // mu PDriver should have only 1 span
  502.                     superSetMu(driver.getValue());
  503.                 }
  504.             });

  505.             if (hasNewtonianAttraction()) {
  506.                 // there is already a central attraction model, replace it
  507.                 forceModels.set(forceModels.size() - 1, force);
  508.             } else {
  509.                 // there are no central attraction model yet, add it at the end of the list
  510.                 forceModels.add(force);
  511.             }
  512.         } else {
  513.             // we want to add a perturbing force model
  514.             if (hasNewtonianAttraction()) {
  515.                 // insert the new force model before Newtonian attraction,
  516.                 // which should always be the last one in the list
  517.                 forceModels.add(forceModels.size() - 1, force);
  518.             } else {
  519.                 // we only have perturbing force models up to now, just append at the end of the list
  520.                 forceModels.add(force);
  521.             }
  522.         }

  523.         force.registerAttitudeProvider(getAttitudeProvider());

  524.     }

  525.     /** Remove all perturbing force models from the global perturbation model
  526.      *  (except central attraction).
  527.      *  <p>
  528.      *  Once all perturbing forces have been removed (and as long as no new force model is added),
  529.      *  the integrated orbit will follow a Keplerian evolution only.
  530.      *  </p>
  531.      *  @see #addForceModel(DSSTForceModel)
  532.      */
  533.     public void removeForceModels() {
  534.         final int last = forceModels.size() - 1;
  535.         if (hasNewtonianAttraction()) {
  536.             // preserve the Newtonian attraction model at the end
  537.             final DSSTForceModel newton = forceModels.get(last);
  538.             forceModels.clear();
  539.             forceModels.add(newton);
  540.         } else {
  541.             forceModels.clear();
  542.         }
  543.     }

  544.     /** Get all the force models, perturbing forces and Newtonian attraction included.
  545.      * @return list of perturbing force models, with Newtonian attraction being the
  546.      * last one
  547.      * @see #addForceModel(DSSTForceModel)
  548.      * @see #setMu(double)
  549.      */
  550.     public List<DSSTForceModel> getAllForceModels() {
  551.         return Collections.unmodifiableList(forceModels);
  552.     }

  553.     /** Get propagation parameter type.
  554.      * @return orbit type used for propagation
  555.      */
  556.     public OrbitType getOrbitType() {
  557.         return super.getOrbitType();
  558.     }

  559.     /** Get propagation parameter type.
  560.      * @return angle type to use for propagation
  561.      */
  562.     public PositionAngleType getPositionAngleType() {
  563.         return super.getPositionAngleType();
  564.     }

  565.     /** Conversion from mean to osculating orbit.
  566.      * <p>
  567.      * Compute osculating state <b>in a DSST sense</b>, corresponding to the
  568.      * mean SpacecraftState in input, and according to the Force models taken
  569.      * into account.
  570.      * </p><p>
  571.      * Since the osculating state is obtained by adding short-periodic variation
  572.      * of each force model, the resulting output will depend on the
  573.      * force models parameterized in input.
  574.      * </p>
  575.      * @param mean Mean state to convert
  576.      * @param forces Forces to take into account
  577.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  578.      * like atmospheric drag, radiation pressure or specific user-defined models)
  579.      * @return osculating state in a DSST sense
  580.      */
  581.     public static SpacecraftState computeOsculatingState(final SpacecraftState mean,
  582.                                                          final AttitudeProvider attitudeProvider,
  583.                                                          final Collection<DSSTForceModel> forces) {

  584.         //Create the auxiliary object
  585.         final AuxiliaryElements aux = new AuxiliaryElements(mean.getOrbit(), I);

  586.         // Set the force models
  587.         final List<ShortPeriodTerms> shortPeriodTerms = new ArrayList<>();
  588.         for (final DSSTForceModel force : forces) {
  589.             force.registerAttitudeProvider(attitudeProvider);
  590.             shortPeriodTerms.addAll(force.initializeShortPeriodTerms(aux, PropagationType.OSCULATING, force.getParameters(mean.getDate())));
  591.             force.updateShortPeriodTerms(force.getParametersAllValues(), mean);
  592.         }

  593.         final EquinoctialOrbit osculatingOrbit = computeOsculatingOrbit(mean, shortPeriodTerms);

  594.         return new SpacecraftState(osculatingOrbit, mean.getAttitude(), mean.getMass(),
  595.                                    mean.getAdditionalStatesValues(), mean.getAdditionalStatesDerivatives());

  596.     }

  597.     /** Conversion from osculating to mean orbit.
  598.      * <p>
  599.      * Compute mean state <b>in a DSST sense</b>, corresponding to the
  600.      * osculating SpacecraftState in input, and according to the Force models
  601.      * taken into account.
  602.      * </p><p>
  603.      * Since the osculating state is obtained with the computation of
  604.      * short-periodic variation of each force model, the resulting output will
  605.      * depend on the force models parameterized in input.
  606.      * </p><p>
  607.      * The computation is done through a fixed-point iteration process.
  608.      * </p>
  609.      * @param osculating Osculating state to convert
  610.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  611.      * like atmospheric drag, radiation pressure or specific user-defined models)
  612.      * @param forceModels Forces to take into account
  613.      * @return mean state in a DSST sense
  614.      */
  615.     public static SpacecraftState computeMeanState(final SpacecraftState osculating,
  616.                                                    final AttitudeProvider attitudeProvider,
  617.                                                    final Collection<DSSTForceModel> forceModels) {
  618.         return computeMeanState(osculating, attitudeProvider, forceModels, EPSILON_DEFAULT, MAX_ITERATIONS_DEFAULT);
  619.     }

  620.     /** Conversion from osculating to mean orbit.
  621.      * <p>
  622.      * Compute mean state <b>in a DSST sense</b>, corresponding to the
  623.      * osculating SpacecraftState in input, and according to the Force models
  624.      * taken into account.
  625.      * </p><p>
  626.      * Since the osculating state is obtained with the computation of
  627.      * short-periodic variation of each force model, the resulting output will
  628.      * depend on the force models parameterized in input.
  629.      * </p><p>
  630.      * The computation is done through a fixed-point iteration process.
  631.      * </p>
  632.      * @param osculating Osculating state to convert
  633.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  634.      * like atmospheric drag, radiation pressure or specific user-defined models)
  635.      * @param forceModels Forces to take into account
  636.      * @param epsilon convergence threshold for mean parameters conversion
  637.      * @param maxIterations maximum iterations for mean parameters conversion
  638.      * @return mean state in a DSST sense
  639.      * @since 10.1
  640.      */
  641.     public static SpacecraftState computeMeanState(final SpacecraftState osculating,
  642.                                                    final AttitudeProvider attitudeProvider,
  643.                                                    final Collection<DSSTForceModel> forceModels,
  644.                                                    final double epsilon,
  645.                                                    final int maxIterations) {
  646.         final Orbit meanOrbit = computeMeanOrbit(osculating, attitudeProvider, forceModels, epsilon, maxIterations);
  647.         return new SpacecraftState(meanOrbit, osculating.getAttitude(), osculating.getMass(),
  648.                                    osculating.getAdditionalStatesValues(), osculating.getAdditionalStatesDerivatives());
  649.     }

  650.      /** Override the default value of the parameter.
  651.      *  <p>
  652.      *  By default, if the initial orbit is defined as osculating,
  653.      *  it will be averaged over 2 satellite revolutions.
  654.      *  This can be changed by using this method.
  655.      *  </p>
  656.      *  @param satelliteRevolution number of satellite revolutions to use for converting osculating to mean
  657.      *                             elements
  658.      */
  659.     public void setSatelliteRevolution(final int satelliteRevolution) {
  660.         mapper.setSatelliteRevolution(satelliteRevolution);
  661.     }

  662.     /** Get the number of satellite revolutions to use for converting osculating to mean elements.
  663.      *  @return number of satellite revolutions to use for converting osculating to mean elements
  664.      */
  665.     public int getSatelliteRevolution() {
  666.         return mapper.getSatelliteRevolution();
  667.     }

  668.     /** Override the default value short periodic terms.
  669.     *  <p>
  670.     *  By default, short periodic terms are initialized before
  671.     *  the numerical integration of the mean orbital elements.
  672.     *  </p>
  673.     *  @param shortPeriodTerms short periodic terms
  674.     */
  675.     public void setShortPeriodTerms(final List<ShortPeriodTerms> shortPeriodTerms) {
  676.         mapper.setShortPeriodTerms(shortPeriodTerms);
  677.     }

  678.    /** Get the short periodic terms.
  679.     *  @return the short periodic terms
  680.     */
  681.     public List<ShortPeriodTerms> getShortPeriodTerms() {
  682.         return mapper.getShortPeriodTerms();
  683.     }

  684.     /** {@inheritDoc} */
  685.     @Override
  686.     public void setAttitudeProvider(final AttitudeProvider attitudeProvider) {
  687.         super.setAttitudeProvider(attitudeProvider);

  688.         //Register the attitude provider for each force model
  689.         for (final DSSTForceModel force : forceModels) {
  690.             force.registerAttitudeProvider(attitudeProvider);
  691.         }
  692.     }

  693.     /** Method called just before integration.
  694.      * <p>
  695.      * The default implementation does nothing, it may be specialized in subclasses.
  696.      * </p>
  697.      * @param initialState initial state
  698.      * @param tEnd target date at which state should be propagated
  699.      */
  700.     @Override
  701.     protected void beforeIntegration(final SpacecraftState initialState,
  702.                                      final AbsoluteDate tEnd) {
  703.         // If this method is updated also update DSSTStateTransitionMatrixGenerator.init(...)

  704.         // check if only mean elements must be used
  705.         final PropagationType type = getPropagationType();

  706.         // compute common auxiliary elements
  707.         final AuxiliaryElements aux = new AuxiliaryElements(initialState.getOrbit(), I);

  708.         // initialize all perturbing forces
  709.         final List<ShortPeriodTerms> shortPeriodTerms = new ArrayList<>();
  710.         for (final DSSTForceModel force : forceModels) {
  711.             shortPeriodTerms.addAll(force.initializeShortPeriodTerms(aux, type, force.getParameters(initialState.getDate())));
  712.         }
  713.         mapper.setShortPeriodTerms(shortPeriodTerms);

  714.         // if required, insert the special short periodics step handler
  715.         if (type == PropagationType.OSCULATING) {
  716.             final ShortPeriodicsHandler spHandler = new ShortPeriodicsHandler(forceModels);
  717.             // Compute short periodic coefficients for this point
  718.             for (DSSTForceModel forceModel : forceModels) {
  719.                 forceModel.updateShortPeriodTerms(forceModel.getParametersAllValues(), initialState);
  720.             }
  721.             final Collection<ODEStepHandler> stepHandlers = new ArrayList<>();
  722.             stepHandlers.add(spHandler);
  723.             final ODEIntegrator integrator = getIntegrator();
  724.             final Collection<ODEStepHandler> existing = integrator.getStepHandlers();
  725.             stepHandlers.addAll(existing);

  726.             integrator.clearStepHandlers();

  727.             // add back the existing handlers after the short periodics one
  728.             for (final ODEStepHandler sp : stepHandlers) {
  729.                 integrator.addStepHandler(sp);
  730.             }
  731.         }
  732.     }

  733.     /** {@inheritDoc} */
  734.     @Override
  735.     protected void afterIntegration() {
  736.         // remove the special short periodics step handler if added before
  737.         if (getPropagationType() == PropagationType.OSCULATING) {
  738.             final List<ODEStepHandler> preserved = new ArrayList<>();
  739.             final ODEIntegrator integrator = getIntegrator();
  740.             for (final ODEStepHandler sp : integrator.getStepHandlers()) {
  741.                 if (!(sp instanceof ShortPeriodicsHandler)) {
  742.                     preserved.add(sp);
  743.                 }
  744.             }

  745.             // clear the list
  746.             integrator.clearStepHandlers();

  747.             // add back the step handlers that were important for the user
  748.             for (final ODEStepHandler sp : preserved) {
  749.                 integrator.addStepHandler(sp);
  750.             }
  751.         }
  752.     }

  753.     /** Compute mean state from osculating state.
  754.      * <p>
  755.      * Compute in a DSST sense the mean state corresponding to the input osculating state.
  756.      * </p><p>
  757.      * The computing is done through a fixed-point iteration process.
  758.      * </p>
  759.      * @param osculating initial osculating state
  760.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  761.      * like atmospheric drag, radiation pressure or specific user-defined models)
  762.      * @param forceModels force models
  763.      * @param epsilon convergence threshold for mean parameters conversion
  764.      * @param maxIterations maximum iterations for mean parameters conversion
  765.      * @return mean state
  766.      */
  767.     private static Orbit computeMeanOrbit(final SpacecraftState osculating,
  768.                                           final AttitudeProvider attitudeProvider,
  769.                                           final Collection<DSSTForceModel> forceModels, final double epsilon, final int maxIterations) {

  770.         // rough initialization of the mean parameters
  771.         EquinoctialOrbit meanOrbit = (EquinoctialOrbit) OrbitType.EQUINOCTIAL.convertType(osculating.getOrbit());

  772.         // threshold for each parameter
  773.         final double thresholdA = epsilon * (1 + FastMath.abs(meanOrbit.getA()));
  774.         final double thresholdE = epsilon * (1 + meanOrbit.getE());
  775.         final double thresholdI = epsilon * (1 + meanOrbit.getI());
  776.         final double thresholdL = epsilon * FastMath.PI;

  777.         // ensure all Gaussian force models can rely on attitude
  778.         for (final DSSTForceModel force : forceModels) {
  779.             force.registerAttitudeProvider(attitudeProvider);
  780.         }

  781.         int i = 0;
  782.         while (i++ < maxIterations) {

  783.             final SpacecraftState meanState = new SpacecraftState(meanOrbit, osculating.getAttitude(), osculating.getMass());

  784.             //Create the auxiliary object
  785.             final AuxiliaryElements aux = new AuxiliaryElements(meanOrbit, I);

  786.             // Set the force models
  787.             final List<ShortPeriodTerms> shortPeriodTerms = new ArrayList<>();
  788.             for (final DSSTForceModel force : forceModels) {
  789.                 shortPeriodTerms.addAll(force.initializeShortPeriodTerms(aux, PropagationType.OSCULATING, force.getParameters(meanState.getDate())));
  790.                 force.updateShortPeriodTerms(force.getParametersAllValues(), meanState);
  791.             }

  792.             // recompute the osculating parameters from the current mean parameters
  793.             final EquinoctialOrbit rebuilt = computeOsculatingOrbit(meanState, shortPeriodTerms);

  794.             // adapted parameters residuals
  795.             final double deltaA  = osculating.getA() - rebuilt.getA();
  796.             final double deltaEx = osculating.getEquinoctialEx() - rebuilt.getEquinoctialEx();
  797.             final double deltaEy = osculating.getEquinoctialEy() - rebuilt.getEquinoctialEy();
  798.             final double deltaHx = osculating.getHx() - rebuilt.getHx();
  799.             final double deltaHy = osculating.getHy() - rebuilt.getHy();
  800.             final double deltaLM = MathUtils.normalizeAngle(osculating.getLM() - rebuilt.getLM(), 0.0);

  801.             // check convergence
  802.             if (FastMath.abs(deltaA)  < thresholdA &&
  803.                 FastMath.abs(deltaEx) < thresholdE &&
  804.                 FastMath.abs(deltaEy) < thresholdE &&
  805.                 FastMath.abs(deltaHx) < thresholdI &&
  806.                 FastMath.abs(deltaHy) < thresholdI &&
  807.                 FastMath.abs(deltaLM) < thresholdL) {
  808.                 return meanOrbit;
  809.             }

  810.             // update mean parameters
  811.             meanOrbit = new EquinoctialOrbit(meanOrbit.getA() + deltaA,
  812.                                              meanOrbit.getEquinoctialEx() + deltaEx,
  813.                                              meanOrbit.getEquinoctialEy() + deltaEy,
  814.                                              meanOrbit.getHx() + deltaHx,
  815.                                              meanOrbit.getHy() + deltaHy,
  816.                                              meanOrbit.getLM() + deltaLM,
  817.                                              PositionAngleType.MEAN, meanOrbit.getFrame(),
  818.                                              meanOrbit.getDate(), meanOrbit.getMu());
  819.         }

  820.         throw new OrekitException(OrekitMessages.UNABLE_TO_COMPUTE_DSST_MEAN_PARAMETERS, i);

  821.     }

  822.     /** Compute osculating state from mean state.
  823.      * <p>
  824.      * Compute and add the short periodic variation to the mean {@link SpacecraftState}.
  825.      * </p>
  826.      * @param meanState initial mean state
  827.      * @param shortPeriodTerms short period terms
  828.      * @return osculating state
  829.      */
  830.     private static EquinoctialOrbit computeOsculatingOrbit(final SpacecraftState meanState,
  831.                                                            final List<ShortPeriodTerms> shortPeriodTerms) {

  832.         final double[] mean = new double[6];
  833.         final double[] meanDot = new double[6];
  834.         OrbitType.EQUINOCTIAL.mapOrbitToArray(meanState.getOrbit(), PositionAngleType.MEAN, mean, meanDot);
  835.         final double[] y = mean.clone();
  836.         for (final ShortPeriodTerms spt : shortPeriodTerms) {
  837.             final double[] shortPeriodic = spt.value(meanState.getOrbit());
  838.             for (int i = 0; i < shortPeriodic.length; i++) {
  839.                 y[i] += shortPeriodic[i];
  840.             }
  841.         }
  842.         return (EquinoctialOrbit) OrbitType.EQUINOCTIAL.mapArrayToOrbit(y, meanDot,
  843.                                                                         PositionAngleType.MEAN, meanState.getDate(),
  844.                                                                         meanState.getMu(), meanState.getFrame());
  845.     }

  846.     /** {@inheritDoc} */
  847.     @Override
  848.     protected SpacecraftState getInitialIntegrationState() {
  849.         if (initialIsOsculating) {
  850.             // the initial state is an osculating state,
  851.             // it must be converted to mean state
  852.             return computeMeanState(getInitialState(), getAttitudeProvider(), forceModels);
  853.         } else {
  854.             // the initial state is already a mean state
  855.             return getInitialState();
  856.         }
  857.     }

  858.     /** {@inheritDoc}
  859.      * <p>
  860.      * Note that for DSST, orbit type is hardcoded to {@link OrbitType#EQUINOCTIAL}
  861.      * and position angle type is hardcoded to {@link PositionAngleType#MEAN}, so
  862.      * the corresponding parameters are ignored.
  863.      * </p>
  864.      */
  865.     @Override
  866.     protected StateMapper createMapper(final AbsoluteDate referenceDate, final double mu,
  867.                                        final OrbitType ignoredOrbitType, final PositionAngleType ignoredPositionAngleType,
  868.                                        final AttitudeProvider attitudeProvider, final Frame frame) {

  869.         // create a mapper with the common settings provided as arguments
  870.         final MeanPlusShortPeriodicMapper newMapper =
  871.                 new MeanPlusShortPeriodicMapper(referenceDate, mu, attitudeProvider, frame);

  872.         // copy the specific settings from the existing mapper
  873.         if (mapper != null) {
  874.             newMapper.setSatelliteRevolution(mapper.getSatelliteRevolution());
  875.             newMapper.setSelectedCoefficients(mapper.getSelectedCoefficients());
  876.             newMapper.setShortPeriodTerms(mapper.getShortPeriodTerms());
  877.         }

  878.         mapper = newMapper;
  879.         return mapper;

  880.     }


  881.     /** Get the short period terms value.
  882.      * @param meanState the mean state
  883.      * @return shortPeriodTerms short period terms
  884.      * @since 7.1
  885.      */
  886.     public double[] getShortPeriodTermsValue(final SpacecraftState meanState) {
  887.         final double[] sptValue = new double[6];

  888.         for (ShortPeriodTerms spt : mapper.getShortPeriodTerms()) {
  889.             final double[] shortPeriodic = spt.value(meanState.getOrbit());
  890.             for (int i = 0; i < shortPeriodic.length; i++) {
  891.                 sptValue[i] += shortPeriodic[i];
  892.             }
  893.         }
  894.         return sptValue;
  895.     }


  896.     /** Internal mapper using mean parameters plus short periodic terms. */
  897.     private static class MeanPlusShortPeriodicMapper extends StateMapper {

  898.         /** Short periodic coefficients that must be stored as additional states. */
  899.         private Set<String>                selectedCoefficients;

  900.         /** Number of satellite revolutions in the averaging interval. */
  901.         private int                        satelliteRevolution;

  902.         /** Short period terms. */
  903.         private List<ShortPeriodTerms>     shortPeriodTerms;

  904.         /** Simple constructor.
  905.          * @param referenceDate reference date
  906.          * @param mu central attraction coefficient (m³/s²)
  907.          * @param attitudeProvider attitude provider
  908.          * @param frame inertial frame
  909.          */
  910.         MeanPlusShortPeriodicMapper(final AbsoluteDate referenceDate, final double mu,
  911.                                     final AttitudeProvider attitudeProvider, final Frame frame) {

  912.             super(referenceDate, mu, OrbitType.EQUINOCTIAL, PositionAngleType.MEAN, attitudeProvider, frame);

  913.             this.selectedCoefficients = null;

  914.             // Default averaging period for conversion from osculating to mean elements
  915.             this.satelliteRevolution = 2;

  916.             this.shortPeriodTerms    = Collections.emptyList();

  917.         }

  918.         /** {@inheritDoc} */
  919.         @Override
  920.         public SpacecraftState mapArrayToState(final AbsoluteDate date,
  921.                                                final double[] y, final double[] yDot,
  922.                                                final PropagationType type) {

  923.             // add short periodic variations to mean elements to get osculating elements
  924.             // (the loop may not be performed if there are no force models and in the
  925.             //  case we want to remain in mean parameters only)
  926.             final double[] elements = y.clone();
  927.             final DoubleArrayDictionary coefficients;
  928.             if (type == PropagationType.MEAN) {
  929.                 coefficients = null;
  930.             } else {
  931.                 final Orbit meanOrbit = OrbitType.EQUINOCTIAL.mapArrayToOrbit(elements, yDot, PositionAngleType.MEAN, date, getMu(), getFrame());
  932.                 coefficients = selectedCoefficients == null ? null : new DoubleArrayDictionary();
  933.                 for (final ShortPeriodTerms spt : shortPeriodTerms) {
  934.                     final double[] shortPeriodic = spt.value(meanOrbit);
  935.                     for (int i = 0; i < shortPeriodic.length; i++) {
  936.                         elements[i] += shortPeriodic[i];
  937.                     }
  938.                     if (selectedCoefficients != null) {
  939.                         coefficients.putAll(spt.getCoefficients(date, selectedCoefficients));
  940.                     }
  941.                 }
  942.             }

  943.             final double mass = elements[6];
  944.             if (mass <= 0.0) {
  945.                 throw new OrekitException(OrekitMessages.NOT_POSITIVE_SPACECRAFT_MASS, mass);
  946.             }

  947.             final Orbit orbit       = OrbitType.EQUINOCTIAL.mapArrayToOrbit(elements, yDot, PositionAngleType.MEAN, date, getMu(), getFrame());
  948.             final Attitude attitude = getAttitudeProvider().getAttitude(orbit, date, getFrame());

  949.             if (coefficients == null) {
  950.                 return new SpacecraftState(orbit, attitude, mass);
  951.             } else {
  952.                 return new SpacecraftState(orbit, attitude, mass, coefficients);
  953.             }

  954.         }

  955.         /** {@inheritDoc} */
  956.         @Override
  957.         public void mapStateToArray(final SpacecraftState state, final double[] y, final double[] yDot) {

  958.             OrbitType.EQUINOCTIAL.mapOrbitToArray(state.getOrbit(), PositionAngleType.MEAN, y, yDot);
  959.             y[6] = state.getMass();

  960.         }

  961.         /** Set the number of satellite revolutions to use for converting osculating to mean elements.
  962.          *  <p>
  963.          *  By default, if the initial orbit is defined as osculating,
  964.          *  it will be averaged over 2 satellite revolutions.
  965.          *  This can be changed by using this method.
  966.          *  </p>
  967.          *  @param satelliteRevolution number of satellite revolutions to use for converting osculating to mean
  968.          *                             elements
  969.          */
  970.         public void setSatelliteRevolution(final int satelliteRevolution) {
  971.             this.satelliteRevolution = satelliteRevolution;
  972.         }

  973.         /** Get the number of satellite revolutions to use for converting osculating to mean elements.
  974.          *  @return number of satellite revolutions to use for converting osculating to mean elements
  975.          */
  976.         public int getSatelliteRevolution() {
  977.             return satelliteRevolution;
  978.         }

  979.         /** Set the selected short periodic coefficients that must be stored as additional states.
  980.          * @param selectedCoefficients short periodic coefficients that must be stored as additional states
  981.          * (null means no coefficients are selected, empty set means all coefficients are selected)
  982.          */
  983.         public void setSelectedCoefficients(final Set<String> selectedCoefficients) {
  984.             this.selectedCoefficients = selectedCoefficients;
  985.         }

  986.         /** Get the selected short periodic coefficients that must be stored as additional states.
  987.          * @return short periodic coefficients that must be stored as additional states
  988.          * (null means no coefficients are selected, empty set means all coefficients are selected)
  989.          */
  990.         public Set<String> getSelectedCoefficients() {
  991.             return selectedCoefficients;
  992.         }

  993.         /** Set the short period terms.
  994.          * @param shortPeriodTerms short period terms
  995.          * @since 7.1
  996.          */
  997.         public void setShortPeriodTerms(final List<ShortPeriodTerms> shortPeriodTerms) {
  998.             this.shortPeriodTerms = shortPeriodTerms;
  999.         }

  1000.         /** Get the short period terms.
  1001.          * @return shortPeriodTerms short period terms
  1002.          * @since 7.1
  1003.          */
  1004.         public List<ShortPeriodTerms> getShortPeriodTerms() {
  1005.             return shortPeriodTerms;
  1006.         }

  1007.     }

  1008.     /** {@inheritDoc} */
  1009.     @Override
  1010.     protected MainStateEquations getMainStateEquations(final ODEIntegrator integrator) {
  1011.         return new Main(integrator);
  1012.     }

  1013.     /** Internal class for mean parameters integration. */
  1014.     private class Main implements MainStateEquations {

  1015.         /** Derivatives array. */
  1016.         private final double[] yDot;

  1017.         /** Simple constructor.
  1018.          * @param integrator numerical integrator to use for propagation.
  1019.          */
  1020.         Main(final ODEIntegrator integrator) {
  1021.             yDot = new double[7];

  1022.             // Setup event detectors for each force model
  1023.             forceModels.forEach(dsstForceModel -> dsstForceModel.getEventDetectors().
  1024.                                 forEach(eventDetector -> setUpEventDetector(integrator, eventDetector)));
  1025.         }

  1026.         /** {@inheritDoc} */
  1027.         @Override
  1028.         public void init(final SpacecraftState initialState, final AbsoluteDate target) {
  1029.             forceModels.forEach(fm -> fm.init(initialState, target));
  1030.         }

  1031.         /** {@inheritDoc} */
  1032.         @Override
  1033.         public double[] computeDerivatives(final SpacecraftState state) {

  1034.             Arrays.fill(yDot, 0.0);

  1035.             // compute common auxiliary elements
  1036.             final AuxiliaryElements auxiliaryElements = new AuxiliaryElements(state.getOrbit(), I);

  1037.             // compute the contributions of all perturbing forces
  1038.             for (final DSSTForceModel forceModel : forceModels) {
  1039.                 final double[] daidt = elementRates(forceModel, state, auxiliaryElements, forceModel.getParameters(state.getDate()));
  1040.                 for (int i = 0; i < daidt.length; i++) {
  1041.                     yDot[i] += daidt[i];
  1042.                 }
  1043.             }

  1044.             return yDot.clone();
  1045.         }

  1046.         /** This method allows to compute the mean equinoctial elements rates da<sub>i</sub> / dt
  1047.          *  for a specific force model.
  1048.          *  @param forceModel force to take into account
  1049.          *  @param state current state
  1050.          *  @param auxiliaryElements auxiliary elements related to the current orbit
  1051.          *  @param parameters force model parameters at state date (only 1 value for
  1052.          *  each parameter
  1053.          *  @return the mean equinoctial elements rates da<sub>i</sub> / dt
  1054.          */
  1055.         private double[] elementRates(final DSSTForceModel forceModel,
  1056.                                       final SpacecraftState state,
  1057.                                       final AuxiliaryElements auxiliaryElements,
  1058.                                       final double[] parameters) {
  1059.             return forceModel.getMeanElementRate(state, auxiliaryElements, parameters);
  1060.         }

  1061.     }

  1062.     /** Estimate tolerance vectors for an AdaptativeStepsizeIntegrator.
  1063.      *  <p>
  1064.      *  The errors are estimated from partial derivatives properties of orbits,
  1065.      *  starting from a scalar position error specified by the user.
  1066.      *  Considering the energy conservation equation V = sqrt(mu (2/r - 1/a)),
  1067.      *  we get at constant energy (i.e. on a Keplerian trajectory):
  1068.      *
  1069.      *  <pre>
  1070.      *  V r² |dV| = mu |dr|
  1071.      *  </pre>
  1072.      *
  1073.      *  <p> So we deduce a scalar velocity error consistent with the position error. From here, we apply
  1074.      *  orbits Jacobians matrices to get consistent errors on orbital parameters.
  1075.      *
  1076.      *  <p>
  1077.      *  The tolerances are only <em>orders of magnitude</em>, and integrator tolerances are only
  1078.      *  local estimates, not global ones. So some care must be taken when using these tolerances.
  1079.      *  Setting 1mm as a position error does NOT mean the tolerances will guarantee a 1mm error
  1080.      *  position after several orbits integration.
  1081.      *  </p>
  1082.      *
  1083.      * @param dP user specified position error (m)
  1084.      * @param orbit reference orbit
  1085.      * @return a two rows array, row 0 being the absolute tolerance error
  1086.      *                       and row 1 being the relative tolerance error
  1087.      */
  1088.     public static double[][] tolerances(final double dP, final Orbit orbit) {

  1089.         return NumericalPropagator.tolerances(dP, orbit, OrbitType.EQUINOCTIAL);

  1090.     }

  1091.     /** Estimate tolerance vectors for an AdaptativeStepsizeIntegrator.
  1092.      *  <p>
  1093.      *  The errors are estimated from partial derivatives properties of orbits,
  1094.      *  starting from scalar position and velocity errors specified by the user.
  1095.      *  <p>
  1096.      *  The tolerances are only <em>orders of magnitude</em>, and integrator tolerances are only
  1097.      *  local estimates, not global ones. So some care must be taken when using these tolerances.
  1098.      *  Setting 1mm as a position error does NOT mean the tolerances will guarantee a 1mm error
  1099.      *  position after several orbits integration.
  1100.      *  </p>
  1101.      *
  1102.      * @param dP user specified position error (m)
  1103.      * @param dV user specified velocity error (m/s)
  1104.      * @param orbit reference orbit
  1105.      * @return a two rows array, row 0 being the absolute tolerance error
  1106.      *                       and row 1 being the relative tolerance error
  1107.      * @since 10.3
  1108.      */
  1109.     public static double[][] tolerances(final double dP, final double dV, final Orbit orbit) {

  1110.         return NumericalPropagator.tolerances(dP, dV, orbit, OrbitType.EQUINOCTIAL);

  1111.     }

  1112.     /** Step handler used to compute the parameters for the short periodic contributions.
  1113.      * @author Lucian Barbulescu
  1114.      */
  1115.     private class ShortPeriodicsHandler implements ODEStepHandler {

  1116.         /** Force models used to compute short periodic terms. */
  1117.         private final List<DSSTForceModel> forceModels;

  1118.         /** Constructor.
  1119.          * @param forceModels force models
  1120.          */
  1121.         ShortPeriodicsHandler(final List<DSSTForceModel> forceModels) {
  1122.             this.forceModels = forceModels;
  1123.         }

  1124.         /** {@inheritDoc} */
  1125.         @Override
  1126.         public void handleStep(final ODEStateInterpolator interpolator) {

  1127.             // Get the grid points to compute
  1128.             final double[] interpolationPoints =
  1129.                     interpolationgrid.getGridPoints(interpolator.getPreviousState().getTime(),
  1130.                                                     interpolator.getCurrentState().getTime());

  1131.             final SpacecraftState[] meanStates = new SpacecraftState[interpolationPoints.length];
  1132.             for (int i = 0; i < interpolationPoints.length; ++i) {

  1133.                 // Build the mean state interpolated at grid point
  1134.                 final double time = interpolationPoints[i];
  1135.                 final ODEStateAndDerivative sd = interpolator.getInterpolatedState(time);
  1136.                 meanStates[i] = mapper.mapArrayToState(time,
  1137.                                                        sd.getPrimaryState(),
  1138.                                                        sd.getPrimaryDerivative(),
  1139.                                                        PropagationType.MEAN);
  1140.             }

  1141.             // Computate short periodic coefficients for this step
  1142.             for (DSSTForceModel forceModel : forceModels) {
  1143.                 forceModel.updateShortPeriodTerms(forceModel.getParametersAllValues(), meanStates);
  1144.             }
  1145.         }
  1146.     }
  1147. }