DSSTPropagator.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.propagation.semianalytical.dsst;

  18. import java.io.NotSerializableException;
  19. import java.io.Serializable;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Collection;
  23. import java.util.Collections;
  24. import java.util.HashMap;
  25. import java.util.HashSet;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Set;

  29. import org.hipparchus.ode.ODEIntegrator;
  30. import org.hipparchus.ode.ODEStateAndDerivative;
  31. import org.hipparchus.ode.sampling.ODEStateInterpolator;
  32. import org.hipparchus.ode.sampling.ODEStepHandler;
  33. import org.hipparchus.util.FastMath;
  34. import org.hipparchus.util.MathUtils;
  35. import org.orekit.attitudes.Attitude;
  36. import org.orekit.attitudes.AttitudeProvider;
  37. import org.orekit.errors.OrekitException;
  38. import org.orekit.errors.OrekitMessages;
  39. import org.orekit.frames.Frame;
  40. import org.orekit.orbits.EquinoctialOrbit;
  41. import org.orekit.orbits.Orbit;
  42. import org.orekit.orbits.OrbitType;
  43. import org.orekit.orbits.PositionAngle;
  44. import org.orekit.propagation.SpacecraftState;
  45. import org.orekit.propagation.events.EventDetector;
  46. import org.orekit.propagation.integration.AbstractIntegratedPropagator;
  47. import org.orekit.propagation.integration.StateMapper;
  48. import org.orekit.propagation.numerical.NumericalPropagator;
  49. import org.orekit.propagation.semianalytical.dsst.forces.DSSTForceModel;
  50. import org.orekit.propagation.semianalytical.dsst.forces.ShortPeriodTerms;
  51. import org.orekit.propagation.semianalytical.dsst.utilities.AuxiliaryElements;
  52. import org.orekit.propagation.semianalytical.dsst.utilities.FixedNumberInterpolationGrid;
  53. import org.orekit.propagation.semianalytical.dsst.utilities.InterpolationGrid;
  54. import org.orekit.propagation.semianalytical.dsst.utilities.MaxGapInterpolationGrid;
  55. import org.orekit.time.AbsoluteDate;

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

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

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

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

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

  137.     /** State mapper holding the force models. */
  138.     private MeanPlusShortPeriodicMapper mapper;

  139.     /** Generator for the interpolation grid. */
  140.     private InterpolationGrid interpolationgrid;

  141.     /** Create a new instance of DSSTPropagator.
  142.      *  <p>
  143.      *  After creation, there are no perturbing forces at all.
  144.      *  This means that if {@link #addForceModel addForceModel}
  145.      *  is not called after creation, the integrated orbit will
  146.      *  follow a Keplerian evolution only.
  147.      *  </p>
  148.      *  @param integrator numerical integrator to use for propagation.
  149.      *  @param meanOnly output only the mean orbits.
  150.      */
  151.     public DSSTPropagator(final ODEIntegrator integrator, final boolean meanOnly) {
  152.         super(integrator, meanOnly);
  153.         forceModels = new ArrayList<DSSTForceModel>();
  154.         initMapper();
  155.         // DSST uses only equinoctial orbits and mean longitude argument
  156.         setOrbitType(OrbitType.EQUINOCTIAL);
  157.         setPositionAngleType(PositionAngle.MEAN);
  158.         setAttitudeProvider(DEFAULT_LAW);
  159.         setInterpolationGridToFixedNumberOfPoints(INTERPOLATION_POINTS_PER_STEP);
  160.     }


  161.     /** Create a new instance of DSSTPropagator.
  162.      *  <p>
  163.      *  After creation, there are no perturbing forces at all.
  164.      *  This means that if {@link #addForceModel addForceModel}
  165.      *  is not called after creation, the integrated orbit will
  166.      *  follow a Keplerian evolution only. Only the mean orbits
  167.      *  will be generated.
  168.      *  </p>
  169.      *  @param integrator numerical integrator to use for propagation.
  170.      */
  171.     public DSSTPropagator(final ODEIntegrator integrator) {
  172.         super(integrator, true);
  173.         forceModels = new ArrayList<DSSTForceModel>();
  174.         initMapper();
  175.         // DSST uses only equinoctial orbits and mean longitude argument
  176.         setOrbitType(OrbitType.EQUINOCTIAL);
  177.         setPositionAngleType(PositionAngle.MEAN);
  178.         setAttitudeProvider(DEFAULT_LAW);
  179.         setInterpolationGridToFixedNumberOfPoints(INTERPOLATION_POINTS_PER_STEP);
  180.     }

  181.     /** Set the initial state with osculating orbital elements.
  182.      *  @param initialState initial state (defined with osculating elements)
  183.      */
  184.     public void setInitialState(final SpacecraftState initialState) {
  185.         setInitialState(initialState, true);
  186.     }

  187.     /** Set the initial state.
  188.      *  @param initialState initial state
  189.      *  @param isOsculating true if the orbital state is defined with osculating elements
  190.      */
  191.     public void setInitialState(final SpacecraftState initialState,
  192.                                 final boolean isOsculating) {
  193.         initialIsOsculating = isOsculating;
  194.         resetInitialState(initialState);
  195.     }

  196.     /** Reset the initial state.
  197.      *
  198.      *  @param state new initial state
  199.      */
  200.     @Override
  201.     public void resetInitialState(final SpacecraftState state) {
  202.         super.setStartDate(state.getDate());
  203.         super.resetInitialState(state);
  204.     }

  205.     /** Set the selected short periodic coefficients that must be stored as additional states.
  206.      * @param selectedCoefficients short periodic coefficients that must be stored as additional states
  207.      * (null means no coefficients are selected, empty set means all coefficients are selected)
  208.      */
  209.     public void setSelectedCoefficients(final Set<String> selectedCoefficients) {
  210.         mapper.setSelectedCoefficients(selectedCoefficients == null ?
  211.                                        null : new HashSet<String>(selectedCoefficients));
  212.     }

  213.     /** Get the selected short periodic coefficients that must be stored as additional states.
  214.      * @return short periodic coefficients that must be stored as additional states
  215.      * (null means no coefficients are selected, empty set means all coefficients are selected)
  216.      */
  217.     public Set<String> getSelectedCoefficients() {
  218.         final Set<String> set = mapper.getSelectedCoefficients();
  219.         return set == null ? null : Collections.unmodifiableSet(set);
  220.     }

  221.     /** Check if the initial state is provided in osculating elements.
  222.      * @return true if initial state is provided in osculating elements
  223.      */
  224.     public boolean initialIsOsculating() {
  225.         return initialIsOsculating;
  226.     }

  227.     /** Set the interpolation grid generator.
  228.      * <p>
  229.      * The generator will create an interpolation grid with a fixed
  230.      * number of points for each mean element integration step.
  231.      * </p>
  232.      * <p>
  233.      * If neither {@link #setInterpolationGridToFixedNumberOfPoints(int)}
  234.      * nor {@link #setInterpolationGridToMaxTimeGap(double)} has been called,
  235.      * by default the propagator is set as to 3 interpolations points per step.
  236.      * </p>
  237.      * @param interpolationPoints number of interpolation points at
  238.      * each integration step
  239.      * @see #setInterpolationGridToMaxTimeGap(double)
  240.      * @since 7.1
  241.      */
  242.     public void setInterpolationGridToFixedNumberOfPoints(final int interpolationPoints) {
  243.         interpolationgrid = new FixedNumberInterpolationGrid(interpolationPoints);
  244.     }

  245.     /** Set the interpolation grid generator.
  246.      * <p>
  247.      * The generator will create an interpolation grid with a maximum
  248.      * time gap between interpolation points.
  249.      * </p>
  250.      * <p>
  251.      * If neither {@link #setInterpolationGridToFixedNumberOfPoints(int)}
  252.      * nor {@link #setInterpolationGridToMaxTimeGap(double)} has been called,
  253.      * by default the propagator is set as to 3 interpolations points per step.
  254.      * </p>
  255.      * @param maxGap maximum time gap between interpolation points (seconds)
  256.      * @see #setInterpolationGridToFixedNumberOfPoints(int)
  257.      * @since 7.1
  258.      */
  259.     public void setInterpolationGridToMaxTimeGap(final double maxGap) {
  260.         interpolationgrid = new MaxGapInterpolationGrid(maxGap);
  261.     }

  262.     /** Add a force model to the global perturbation model.
  263.      *  <p>
  264.      *  If this method is not called at all,
  265.      *  the integrated orbit will follow a Keplerian evolution only.
  266.      *  </p>
  267.      *  @param force perturbing {@link DSSTForceModel force} to add
  268.      *  @see #removeForceModels()
  269.      */
  270.     public void addForceModel(final DSSTForceModel force) {
  271.         forceModels.add(force);
  272.         force.registerAttitudeProvider(getAttitudeProvider());
  273.     }

  274.     /** Remove all perturbing force models from the global perturbation model.
  275.      *  <p>
  276.      *  Once all perturbing forces have been removed (and as long as no new force model is added),
  277.      *  the integrated orbit will follow a Keplerian evolution only.
  278.      *  </p>
  279.      *  @see #addForceModel(DSSTForceModel)
  280.      */
  281.     public void removeForceModels() {
  282.         forceModels.clear();
  283.     }

  284.     /** Conversion from mean to osculating orbit.
  285.      * <p>
  286.      * Compute osculating state <b>in a DSST sense</b>, corresponding to the
  287.      * mean SpacecraftState in input, and according to the Force models taken
  288.      * into account.
  289.      * </p><p>
  290.      * Since the osculating state is obtained by adding short-periodic variation
  291.      * of each force model, the resulting output will depend on the
  292.      * force models parameterized in input.
  293.      * </p>
  294.      * @param mean Mean state to convert
  295.      * @param forces Forces to take into account
  296.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  297.      * like atmospheric drag, radiation pressure or specific user-defined models)
  298.      * @return osculating state in a DSST sense
  299.      */
  300.     public static SpacecraftState computeOsculatingState(final SpacecraftState mean,
  301.                                                          final AttitudeProvider attitudeProvider,
  302.                                                          final Collection<DSSTForceModel> forces) {

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

  305.         // Set the force models
  306.         final List<ShortPeriodTerms> shortPeriodTerms = new ArrayList<ShortPeriodTerms>();
  307.         for (final DSSTForceModel force : forces) {
  308.             force.registerAttitudeProvider(attitudeProvider);
  309.             shortPeriodTerms.addAll(force.initialize(aux, false));
  310.             force.updateShortPeriodTerms(mean);
  311.         }

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

  313.         return new SpacecraftState(osculatingOrbit, mean.getAttitude(), mean.getMass(),
  314.                                    mean.getAdditionalStates());

  315.     }

  316.     /** Conversion from osculating to mean orbit.
  317.      * <p>
  318.      * Compute mean state <b>in a DSST sense</b>, corresponding to the
  319.      * osculating SpacecraftState in input, and according to the Force models
  320.      * taken into account.
  321.      * </p><p>
  322.      * Since the osculating state is obtained with the computation of
  323.      * short-periodic variation of each force model, the resulting output will
  324.      * depend on the force models parameterized in input.
  325.      * </p><p>
  326.      * The computation is done through a fixed-point iteration process.
  327.      * </p>
  328.      * @param osculating Osculating state to convert
  329.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  330.      * like atmospheric drag, radiation pressure or specific user-defined models)
  331.      * @param forceModels Forces to take into account
  332.      * @return mean state in a DSST sense
  333.      */
  334.     public static SpacecraftState computeMeanState(final SpacecraftState osculating,
  335.                                                    final AttitudeProvider attitudeProvider,
  336.                                                    final Collection<DSSTForceModel> forceModels) {
  337.         final Orbit meanOrbit = computeMeanOrbit(osculating, attitudeProvider, forceModels);
  338.         return new SpacecraftState(meanOrbit, osculating.getAttitude(), osculating.getMass(), osculating.getAdditionalStates());
  339.     }

  340.      /** Override the default value of the parameter.
  341.      *  <p>
  342.      *  By default, if the initial orbit is defined as osculating,
  343.      *  it will be averaged over 2 satellite revolutions.
  344.      *  This can be changed by using this method.
  345.      *  </p>
  346.      *  @param satelliteRevolution number of satellite revolutions to use for converting osculating to mean
  347.      *                             elements
  348.      */
  349.     public void setSatelliteRevolution(final int satelliteRevolution) {
  350.         mapper.setSatelliteRevolution(satelliteRevolution);
  351.     }

  352.     /** Get the number of satellite revolutions to use for converting osculating to mean elements.
  353.      *  @return number of satellite revolutions to use for converting osculating to mean elements
  354.      */
  355.     public int getSatelliteRevolution() {
  356.         return mapper.getSatelliteRevolution();
  357.     }

  358.     /** {@inheritDoc} */
  359.     @Override
  360.     public void setAttitudeProvider(final AttitudeProvider attitudeProvider) {
  361.         super.setAttitudeProvider(attitudeProvider);

  362.         //Register the attitude provider for each force model
  363.         for (final DSSTForceModel force : forceModels) {
  364.             force.registerAttitudeProvider(attitudeProvider);
  365.         }
  366.     }

  367.     /** Method called just before integration.
  368.      * <p>
  369.      * The default implementation does nothing, it may be specialized in subclasses.
  370.      * </p>
  371.      * @param initialState initial state
  372.      * @param tEnd target date at which state should be propagated
  373.      */
  374.     @Override
  375.     protected void beforeIntegration(final SpacecraftState initialState,
  376.                                      final AbsoluteDate tEnd) {

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

  379.         // check if only mean elements must be used
  380.         final boolean meanOnly = isMeanOrbit();

  381.         // initialize all perturbing forces
  382.         final List<ShortPeriodTerms> shortPeriodTerms = new ArrayList<ShortPeriodTerms>();
  383.         for (final DSSTForceModel force : forceModels) {
  384.             shortPeriodTerms.addAll(force.initialize(aux, meanOnly));
  385.         }
  386.         mapper.setShortPeriodTerms(shortPeriodTerms);

  387.         // if required, insert the special short periodics step handler
  388.         if (!meanOnly) {
  389.             final ShortPeriodicsHandler spHandler = new ShortPeriodicsHandler(forceModels);
  390.             final Collection<ODEStepHandler> stepHandlers = new ArrayList<ODEStepHandler>();
  391.             stepHandlers.add(spHandler);
  392.             final ODEIntegrator integrator = getIntegrator();
  393.             final Collection<ODEStepHandler> existing = integrator.getStepHandlers();
  394.             stepHandlers.addAll(existing);

  395.             integrator.clearStepHandlers();

  396.             // add back the existing handlers after the short periodics one
  397.             for (final ODEStepHandler sp : stepHandlers) {
  398.                 integrator.addStepHandler(sp);
  399.             }
  400.         }
  401.     }

  402.     /** {@inheritDoc} */
  403.     @Override
  404.     protected void afterIntegration() {
  405.         // remove the special short periodics step handler if added before
  406.         if (!isMeanOrbit()) {
  407.             final List<ODEStepHandler> preserved = new ArrayList<ODEStepHandler>();
  408.             final ODEIntegrator integrator = getIntegrator();
  409.             for (final ODEStepHandler sp : integrator.getStepHandlers()) {
  410.                 if (!(sp instanceof ShortPeriodicsHandler)) {
  411.                     preserved.add(sp);
  412.                 }
  413.             }

  414.             // clear the list
  415.             integrator.clearStepHandlers();

  416.             // add back the step handlers that were important for the user
  417.             for (final ODEStepHandler sp : preserved) {
  418.                 integrator.addStepHandler(sp);
  419.             }
  420.         }
  421.     }

  422.     /** Compute mean state from osculating state.
  423.      * <p>
  424.      * Compute in a DSST sense the mean state corresponding to the input osculating state.
  425.      * </p><p>
  426.      * The computing is done through a fixed-point iteration process.
  427.      * </p>
  428.      * @param osculating initial osculating state
  429.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  430.      * like atmospheric drag, radiation pressure or specific user-defined models)
  431.      * @param forceModels force models
  432.      * @return mean state
  433.      */
  434.     private static Orbit computeMeanOrbit(final SpacecraftState osculating,
  435.                                           final AttitudeProvider attitudeProvider,
  436.                                           final Collection<DSSTForceModel> forceModels) {

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

  439.         // threshold for each parameter
  440.         final double epsilon    = 1.0e-13;
  441.         final double thresholdA = epsilon * (1 + FastMath.abs(meanOrbit.getA()));
  442.         final double thresholdE = epsilon * (1 + meanOrbit.getE());
  443.         final double thresholdI = epsilon * (1 + meanOrbit.getI());
  444.         final double thresholdL = epsilon * FastMath.PI;

  445.         // ensure all Gaussian force models can rely on attitude
  446.         for (final DSSTForceModel force : forceModels) {
  447.             force.registerAttitudeProvider(attitudeProvider);
  448.         }

  449.         int i = 0;
  450.         while (i++ < 200) {

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

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

  454.             // Set the force models
  455.             final List<ShortPeriodTerms> shortPeriodTerms = new ArrayList<ShortPeriodTerms>();
  456.             for (final DSSTForceModel force : forceModels) {
  457.                 shortPeriodTerms.addAll(force.initialize(aux, false));
  458.                 force.updateShortPeriodTerms(meanState);
  459.             }

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

  462.             // adapted parameters residuals
  463.             final double deltaA  = osculating.getA() - rebuilt.getA();
  464.             final double deltaEx = osculating.getEquinoctialEx() - rebuilt.getEquinoctialEx();
  465.             final double deltaEy = osculating.getEquinoctialEy() - rebuilt.getEquinoctialEy();
  466.             final double deltaHx = osculating.getHx() - rebuilt.getHx();
  467.             final double deltaHy = osculating.getHy() - rebuilt.getHy();
  468.             final double deltaLv = MathUtils.normalizeAngle(osculating.getLv() - rebuilt.getLv(), 0.0);

  469.             // check convergence
  470.             if (FastMath.abs(deltaA)  < thresholdA &&
  471.                 FastMath.abs(deltaEx) < thresholdE &&
  472.                 FastMath.abs(deltaEy) < thresholdE &&
  473.                 FastMath.abs(deltaHx) < thresholdI &&
  474.                 FastMath.abs(deltaHy) < thresholdI &&
  475.                 FastMath.abs(deltaLv) < thresholdL) {
  476.                 return meanOrbit;
  477.             }

  478.             // update mean parameters
  479.             meanOrbit = new EquinoctialOrbit(meanOrbit.getA() + deltaA,
  480.                                              meanOrbit.getEquinoctialEx() + deltaEx,
  481.                                              meanOrbit.getEquinoctialEy() + deltaEy,
  482.                                              meanOrbit.getHx() + deltaHx,
  483.                                              meanOrbit.getHy() + deltaHy,
  484.                                              meanOrbit.getLv() + deltaLv,
  485.                                              PositionAngle.TRUE, meanOrbit.getFrame(),
  486.                                              meanOrbit.getDate(), meanOrbit.getMu());
  487.         }

  488.         throw new OrekitException(OrekitMessages.UNABLE_TO_COMPUTE_DSST_MEAN_PARAMETERS, i);
  489.     }

  490.     /** Compute osculating state from mean state.
  491.      * <p>
  492.      * Compute and add the short periodic variation to the mean {@link SpacecraftState}.
  493.      * </p>
  494.      * @param meanState initial mean state
  495.      * @param shortPeriodTerms short period terms
  496.      * @return osculating state
  497.      */
  498.     private static EquinoctialOrbit computeOsculatingOrbit(final SpacecraftState meanState,
  499.                                                            final List<ShortPeriodTerms> shortPeriodTerms) {

  500.         final double[] mean = new double[6];
  501.         final double[] meanDot = new double[6];
  502.         OrbitType.EQUINOCTIAL.mapOrbitToArray(meanState.getOrbit(), PositionAngle.MEAN, mean, meanDot);
  503.         final double[] y = mean.clone();
  504.         for (final ShortPeriodTerms spt : shortPeriodTerms) {
  505.             final double[] shortPeriodic = spt.value(meanState.getOrbit());
  506.             for (int i = 0; i < shortPeriodic.length; i++) {
  507.                 y[i] += shortPeriodic[i];
  508.             }
  509.         }
  510.         return (EquinoctialOrbit) OrbitType.EQUINOCTIAL.mapArrayToOrbit(y, meanDot,
  511.                                                                         PositionAngle.MEAN, meanState.getDate(),
  512.                                                                         meanState.getMu(), meanState.getFrame());
  513.     }

  514.     /** {@inheritDoc} */
  515.     @Override
  516.     protected SpacecraftState getInitialIntegrationState() {
  517.         if (initialIsOsculating) {
  518.             // the initial state is an osculating state,
  519.             // it must be converted to mean state
  520.             return computeMeanState(getInitialState(), getAttitudeProvider(), forceModels);
  521.         } else {
  522.             // the initial state is already a mean state
  523.             return getInitialState();
  524.         }
  525.     }

  526.     /** {@inheritDoc}
  527.      * <p>
  528.      * Note that for DSST, orbit type is hardcoded to {@link OrbitType#EQUINOCTIAL}
  529.      * and position angle type is hardcoded to {@link PositionAngle#MEAN}, so
  530.      * the corresponding parameters are ignored.
  531.      * </p>
  532.      */
  533.     @Override
  534.     protected StateMapper createMapper(final AbsoluteDate referenceDate, final double mu,
  535.                                        final OrbitType ignoredOrbitType, final PositionAngle ignoredPositionAngleType,
  536.                                        final AttitudeProvider attitudeProvider, final Frame frame) {

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

  540.         // copy the specific settings from the existing mapper
  541.         if (mapper != null) {
  542.             newMapper.setSatelliteRevolution(mapper.getSatelliteRevolution());
  543.             newMapper.setSelectedCoefficients(mapper.getSelectedCoefficients());
  544.             newMapper.setShortPeriodTerms(mapper.getShortPeriodTerms());
  545.         }

  546.         mapper = newMapper;
  547.         return mapper;

  548.     }

  549.     /** Internal mapper using mean parameters plus short periodic terms. */
  550.     private static class MeanPlusShortPeriodicMapper extends StateMapper implements Serializable {

  551.         /** Serializable UID. */
  552.         private static final long serialVersionUID = 20151104L;

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

  555.         /** Number of satellite revolutions in the averaging interval. */
  556.         private int                        satelliteRevolution;

  557.         /** Short period terms. */
  558.         private List<ShortPeriodTerms>     shortPeriodTerms;

  559.         /** Simple constructor.
  560.          * @param referenceDate reference date
  561.          * @param mu central attraction coefficient (m³/s²)
  562.          * @param attitudeProvider attitude provider
  563.          * @param frame inertial frame
  564.          */
  565.         MeanPlusShortPeriodicMapper(final AbsoluteDate referenceDate, final double mu,
  566.                                     final AttitudeProvider attitudeProvider, final Frame frame) {

  567.             super(referenceDate, mu, OrbitType.EQUINOCTIAL, PositionAngle.MEAN, attitudeProvider, frame);

  568.             this.selectedCoefficients = null;

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

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

  572.         }

  573.         /** {@inheritDoc} */
  574.         @Override
  575.         public SpacecraftState mapArrayToState(final AbsoluteDate date,
  576.                                                final double[] y, final double[] yDot,
  577.                                                final boolean meanOnly) {

  578.             // add short periodic variations to mean elements to get osculating elements
  579.             // (the loop may not be performed if there are no force models and in the
  580.             //  case we want to remain in mean parameters only)
  581.             final double[] elements = y.clone();
  582.             final Map<String, double[]> coefficients;
  583.             if (meanOnly) {
  584.                 coefficients = null;
  585.             } else {
  586.                 final Orbit meanOrbit = OrbitType.EQUINOCTIAL.mapArrayToOrbit(elements, yDot, PositionAngle.MEAN, date, getMu(), getFrame());
  587.                 coefficients = selectedCoefficients == null ? null : new HashMap<String, double[]>();
  588.                 for (final ShortPeriodTerms spt : shortPeriodTerms) {
  589.                     final double[] shortPeriodic = spt.value(meanOrbit);
  590.                     for (int i = 0; i < shortPeriodic.length; i++) {
  591.                         elements[i] += shortPeriodic[i];
  592.                     }
  593.                     if (selectedCoefficients != null) {
  594.                         coefficients.putAll(spt.getCoefficients(date, selectedCoefficients));
  595.                     }
  596.                 }
  597.             }

  598.             final double mass = elements[6];
  599.             if (mass <= 0.0) {
  600.                 throw new OrekitException(OrekitMessages.SPACECRAFT_MASS_BECOMES_NEGATIVE, mass);
  601.             }

  602.             final Orbit orbit       = OrbitType.EQUINOCTIAL.mapArrayToOrbit(elements, yDot, PositionAngle.MEAN, date, getMu(), getFrame());
  603.             final Attitude attitude = getAttitudeProvider().getAttitude(orbit, date, getFrame());

  604.             if (coefficients == null) {
  605.                 return new SpacecraftState(orbit, attitude, mass);
  606.             } else {
  607.                 return new SpacecraftState(orbit, attitude, mass, coefficients);
  608.             }

  609.         }

  610.         /** {@inheritDoc} */
  611.         @Override
  612.         public void mapStateToArray(final SpacecraftState state, final double[] y, final double[] yDot) {

  613.             OrbitType.EQUINOCTIAL.mapOrbitToArray(state.getOrbit(), PositionAngle.MEAN, y, yDot);
  614.             y[6] = state.getMass();

  615.         }

  616.         /** Set the number of satellite revolutions to use for converting osculating to mean elements.
  617.          *  <p>
  618.          *  By default, if the initial orbit is defined as osculating,
  619.          *  it will be averaged over 2 satellite revolutions.
  620.          *  This can be changed by using this method.
  621.          *  </p>
  622.          *  @param satelliteRevolution number of satellite revolutions to use for converting osculating to mean
  623.          *                             elements
  624.          */
  625.         public void setSatelliteRevolution(final int satelliteRevolution) {
  626.             this.satelliteRevolution = satelliteRevolution;
  627.         }

  628.         /** Get the number of satellite revolutions to use for converting osculating to mean elements.
  629.          *  @return number of satellite revolutions to use for converting osculating to mean elements
  630.          */
  631.         public int getSatelliteRevolution() {
  632.             return satelliteRevolution;
  633.         }

  634.         /** Set the selected short periodic coefficients that must be stored as additional states.
  635.          * @param selectedCoefficients short periodic coefficients that must be stored as additional states
  636.          * (null means no coefficients are selected, empty set means all coefficients are selected)
  637.          */
  638.         public void setSelectedCoefficients(final Set<String> selectedCoefficients) {
  639.             this.selectedCoefficients = selectedCoefficients;
  640.         }

  641.         /** Get the selected short periodic coefficients that must be stored as additional states.
  642.          * @return short periodic coefficients that must be stored as additional states
  643.          * (null means no coefficients are selected, empty set means all coefficients are selected)
  644.          */
  645.         public Set<String> getSelectedCoefficients() {
  646.             return selectedCoefficients;
  647.         }

  648.         /** Set the short period terms.
  649.          * @param shortPeriodTerms short period terms
  650.          * @since 7.1
  651.          */
  652.         public void setShortPeriodTerms(final List<ShortPeriodTerms> shortPeriodTerms) {
  653.             this.shortPeriodTerms = shortPeriodTerms;
  654.         }

  655.         /** Get the short period terms.
  656.          * @return shortPeriodTerms short period terms
  657.          * @since 7.1
  658.          */
  659.         public List<ShortPeriodTerms> getShortPeriodTerms() {
  660.             return shortPeriodTerms;
  661.         }

  662.         /** Replace the instance with a data transfer object for serialization.
  663.          * @return data transfer object that will be serialized
  664.          * @exception NotSerializableException if one of the force models cannot be serialized
  665.          */
  666.         private Object writeReplace() throws NotSerializableException {
  667.             return new DataTransferObject(getReferenceDate(), getMu(), getAttitudeProvider(), getFrame(),
  668.                                           satelliteRevolution, selectedCoefficients, shortPeriodTerms);
  669.         }

  670.         /** Internal class used only for serialization. */
  671.         private static class DataTransferObject implements Serializable {

  672.             /** Serializable UID. */
  673.             private static final long serialVersionUID = 20151106L;

  674.             /** Reference date. */
  675.             private final AbsoluteDate referenceDate;

  676.             /** Central attraction coefficient (m³/s²). */
  677.             private final double mu;

  678.             /** Attitude provider. */
  679.             private final AttitudeProvider attitudeProvider;

  680.             /** Inertial frame. */
  681.             private final Frame frame;

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

  684.             /** Number of satellite revolutions in the averaging interval. */
  685.             private final int satelliteRevolution;

  686.             /** Short period terms. */
  687.             private final List<ShortPeriodTerms> shortPeriodTerms;

  688.             /** Simple constructor.
  689.              * @param referenceDate reference date
  690.              * @param mu central attraction coefficient (m³/s²)
  691.              * @param attitudeProvider attitude provider
  692.              * @param frame inertial frame
  693.              * @param satelliteRevolution number of satellite revolutions in the averaging interval
  694.              * @param selectedCoefficients short periodic coefficients that must be stored as additional states
  695.              * @param shortPeriodTerms short period terms
  696.              */
  697.             DataTransferObject(final AbsoluteDate referenceDate, final double mu,
  698.                                       final AttitudeProvider attitudeProvider, final Frame frame,
  699.                                       final int satelliteRevolution,
  700.                                       final Set<String> selectedCoefficients,
  701.                                       final List<ShortPeriodTerms> shortPeriodTerms) {
  702.                 this.referenceDate        = referenceDate;
  703.                 this.mu                   = mu;
  704.                 this.attitudeProvider     = attitudeProvider;
  705.                 this.frame                = frame;
  706.                 this.satelliteRevolution  = satelliteRevolution;
  707.                 this.selectedCoefficients = selectedCoefficients;
  708.                 this.shortPeriodTerms     = shortPeriodTerms;
  709.             }

  710.             /** Replace the deserialized data transfer object with a {@link MeanPlusShortPeriodicMapper}.
  711.              * @return replacement {@link MeanPlusShortPeriodicMapper}
  712.              */
  713.             private Object readResolve() {
  714.                 final MeanPlusShortPeriodicMapper mapper =
  715.                         new MeanPlusShortPeriodicMapper(referenceDate, mu, attitudeProvider, frame);
  716.                 mapper.setSatelliteRevolution(satelliteRevolution);
  717.                 mapper.setSelectedCoefficients(selectedCoefficients);
  718.                 mapper.setShortPeriodTerms(shortPeriodTerms);
  719.                 return mapper;
  720.             }

  721.         }

  722.     }

  723.     /** {@inheritDoc} */
  724.     @Override
  725.     protected MainStateEquations getMainStateEquations(final ODEIntegrator integrator) {
  726.         return new Main(integrator);
  727.     }

  728.     /** Internal class for mean parameters integration. */
  729.     private class Main implements MainStateEquations {

  730.         /** Derivatives array. */
  731.         private final double[] yDot;

  732.         /** Simple constructor.
  733.          * @param integrator numerical integrator to use for propagation.
  734.          */
  735.         Main(final ODEIntegrator integrator) {
  736.             yDot = new double[7];

  737.             for (final DSSTForceModel forceModel : forceModels) {
  738.                 final EventDetector[] modelDetectors = forceModel.getEventsDetectors();
  739.                 if (modelDetectors != null) {
  740.                     for (final EventDetector detector : modelDetectors) {
  741.                         setUpEventDetector(integrator, detector);
  742.                     }
  743.                 }
  744.             }

  745.         }

  746.         /** {@inheritDoc} */
  747.         @Override
  748.         public double[] computeDerivatives(final SpacecraftState state) {

  749.             // compute common auxiliary elements
  750.             final AuxiliaryElements aux = new AuxiliaryElements(state.getOrbit(), I);

  751.             // initialize all perturbing forces
  752.             for (final DSSTForceModel force : forceModels) {
  753.                 force.initializeStep(aux);
  754.             }

  755.             Arrays.fill(yDot, 0.0);

  756.             // compute the contributions of all perturbing forces
  757.             for (final DSSTForceModel forceModel : forceModels) {
  758.                 final double[] daidt = forceModel.getMeanElementRate(state);
  759.                 for (int i = 0; i < daidt.length; i++) {
  760.                     yDot[i] += daidt[i];
  761.                 }
  762.             }

  763.             // finalize derivatives by adding the Kepler contribution
  764.             final EquinoctialOrbit orbit = (EquinoctialOrbit) OrbitType.EQUINOCTIAL.convertType(state.getOrbit());
  765.             orbit.addKeplerContribution(PositionAngle.MEAN, getMu(), yDot);

  766.             return yDot.clone();
  767.         }

  768.     }

  769.     /** Estimate tolerance vectors for an AdaptativeStepsizeIntegrator.
  770.      *  <p>
  771.      *  The errors are estimated from partial derivatives properties of orbits,
  772.      *  starting from a scalar position error specified by the user.
  773.      *  Considering the energy conservation equation V = sqrt(mu (2/r - 1/a)),
  774.      *  we get at constant energy (i.e. on a Keplerian trajectory):
  775.      *
  776.      *  <pre>
  777.      *  V² r |dV| = mu |dr|
  778.      *  </pre>
  779.      *
  780.      *  <p> So we deduce a scalar velocity error consistent with the position error. From here, we apply
  781.      *  orbits Jacobians matrices to get consistent errors on orbital parameters.
  782.      *
  783.      *  <p>
  784.      *  The tolerances are only <em>orders of magnitude</em>, and integrator tolerances are only
  785.      *  local estimates, not global ones. So some care must be taken when using these tolerances.
  786.      *  Setting 1mm as a position error does NOT mean the tolerances will guarantee a 1mm error
  787.      *  position after several orbits integration.
  788.      *  </p>
  789.      *
  790.      * @param dP user specified position error (m)
  791.      * @param orbit reference orbit
  792.      * @return a two rows array, row 0 being the absolute tolerance error
  793.      *                       and row 1 being the relative tolerance error
  794.      */
  795.     public static double[][] tolerances(final double dP, final Orbit orbit) {

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

  797.     }

  798.     /** Step handler used to compute the parameters for the short periodic contributions.
  799.      * @author Lucian Barbulescu
  800.      */
  801.     private class ShortPeriodicsHandler implements ODEStepHandler {

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

  804.         /** Constructor.
  805.          * @param forceModels force models
  806.          */
  807.         ShortPeriodicsHandler(final List<DSSTForceModel> forceModels) {
  808.             this.forceModels = forceModels;
  809.         }

  810.         /** {@inheritDoc} */
  811.         @Override
  812.         public void init(final ODEStateAndDerivative initialState, final double finalTime) {
  813.             // Build the mean state interpolated at initial point
  814.             final SpacecraftState meanStates = mapper.mapArrayToState(0.0,
  815.                                                                       initialState.getPrimaryState(),
  816.                                                                       initialState.getPrimaryDerivative(),
  817.                                                                       true);

  818.             // Compute short periodic coefficients for this point
  819.             for (DSSTForceModel forceModel : forceModels) {
  820.                 forceModel.updateShortPeriodTerms(meanStates);

  821.             }
  822.         }

  823.         /** {@inheritDoc} */
  824.         @Override
  825.         public void handleStep(final ODEStateInterpolator interpolator, final boolean isLast) {

  826.             // Get the grid points to compute
  827.             final double[] interpolationPoints =
  828.                     interpolationgrid.getGridPoints(interpolator.getPreviousState().getTime(),
  829.                                                     interpolator.getCurrentState().getTime());

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

  832.                 // Build the mean state interpolated at grid point
  833.                 final double time = interpolationPoints[i];
  834.                 final ODEStateAndDerivative sd = interpolator.getInterpolatedState(time);
  835.                 meanStates[i] = mapper.mapArrayToState(time,
  836.                                                        sd.getPrimaryState(),
  837.                                                        sd.getPrimaryDerivative(),
  838.                                                        true);

  839.             }

  840.             // Computate short periodic coefficients for this step
  841.             for (DSSTForceModel forceModel : forceModels) {
  842.                 forceModel.updateShortPeriodTerms(meanStates);
  843.             }
  844.         }
  845.     }
  846. }