FieldDSSTPropagator.java

  1. /* Copyright 2002-2020 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 java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.HashMap;
  23. import java.util.HashSet;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Set;

  27. import org.hipparchus.Field;
  28. import org.hipparchus.RealFieldElement;
  29. import org.hipparchus.ode.FieldODEIntegrator;
  30. import org.hipparchus.ode.FieldODEStateAndDerivative;
  31. import org.hipparchus.ode.sampling.FieldODEStateInterpolator;
  32. import org.hipparchus.ode.sampling.FieldODEStepHandler;
  33. import org.hipparchus.util.FastMath;
  34. import org.hipparchus.util.MathArrays;
  35. import org.hipparchus.util.MathUtils;
  36. import org.orekit.annotation.DefaultDataContext;
  37. import org.orekit.attitudes.AttitudeProvider;
  38. import org.orekit.attitudes.FieldAttitude;
  39. import org.orekit.data.DataContext;
  40. import org.orekit.errors.OrekitException;
  41. import org.orekit.errors.OrekitInternalError;
  42. import org.orekit.errors.OrekitMessages;
  43. import org.orekit.frames.Frame;
  44. import org.orekit.orbits.FieldEquinoctialOrbit;
  45. import org.orekit.orbits.FieldOrbit;
  46. import org.orekit.orbits.OrbitType;
  47. import org.orekit.orbits.PositionAngle;
  48. import org.orekit.propagation.FieldSpacecraftState;
  49. import org.orekit.propagation.PropagationType;
  50. import org.orekit.propagation.Propagator;
  51. import org.orekit.propagation.SpacecraftState;
  52. import org.orekit.propagation.events.FieldEventDetector;
  53. import org.orekit.propagation.integration.FieldAbstractIntegratedPropagator;
  54. import org.orekit.propagation.integration.FieldStateMapper;
  55. import org.orekit.propagation.numerical.FieldNumericalPropagator;
  56. import org.orekit.propagation.semianalytical.dsst.forces.DSSTForceModel;
  57. import org.orekit.propagation.semianalytical.dsst.forces.DSSTNewtonianAttraction;
  58. import org.orekit.propagation.semianalytical.dsst.forces.FieldShortPeriodTerms;
  59. import org.orekit.propagation.semianalytical.dsst.utilities.FieldAuxiliaryElements;
  60. import org.orekit.propagation.semianalytical.dsst.utilities.FieldFixedNumberInterpolationGrid;
  61. import org.orekit.propagation.semianalytical.dsst.utilities.FieldInterpolationGrid;
  62. import org.orekit.propagation.semianalytical.dsst.utilities.FieldMaxGapInterpolationGrid;
  63. import org.orekit.time.FieldAbsoluteDate;
  64. import org.orekit.utils.ParameterDriver;
  65. import org.orekit.utils.ParameterObserver;

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

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

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

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

  146.     /** Default value for maxIterations. */
  147.     private static final int MAX_ITERATIONS_DEFAULT = 200;

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

  150.     /** Field used by this class.*/
  151.     private final Field<T> field;

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

  154.     /** State mapper holding the force models. */
  155.     private FieldMeanPlusShortPeriodicMapper mapper;

  156.     /** Generator for the interpolation grid. */
  157.     private FieldInterpolationGrid<T> interpolationgrid;

  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 field field used by default
  169.      *  @param integrator numerical integrator to use for propagation.
  170.      *  @param propagationType type of orbit to output (mean or osculating).
  171.      * @see #FieldDSSTPropagator(Field, FieldODEIntegrator, PropagationType,
  172.      * AttitudeProvider)
  173.      */
  174.     @DefaultDataContext
  175.     public FieldDSSTPropagator(final Field<T> field, final FieldODEIntegrator<T> integrator, final PropagationType propagationType) {
  176.         this(field, integrator, propagationType,
  177.                 Propagator.getDefaultLaw(DataContext.getDefault().getFrames()));
  178.     }

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

  206.     /** Create a new instance of DSSTPropagator.
  207.      *  <p>
  208.      *  After creation, there are no perturbing forces at all.
  209.      *  This means that if {@link #addForceModel addForceModel}
  210.      *  is not called after creation, the integrated orbit will
  211.      *  follow a Keplerian evolution only. Only the mean orbits
  212.      *  will be generated.
  213.      *  </p>
  214.      *
  215.      * <p>This constructor uses the {@link DataContext#getDefault() default data context}.
  216.      *
  217.      *  @param field fied used by default
  218.      *  @param integrator numerical integrator to use for propagation.
  219.      * @see #FieldDSSTPropagator(Field, FieldODEIntegrator, AttitudeProvider)
  220.      */
  221.     @DefaultDataContext
  222.     public FieldDSSTPropagator(final Field<T> field, final FieldODEIntegrator<T> integrator) {
  223.         this(field, integrator,
  224.                 Propagator.getDefaultLaw(DataContext.getDefault().getFrames()));
  225.     }

  226.     /** Create a new instance of DSSTPropagator.
  227.      *  <p>
  228.      *  After creation, there are no perturbing forces at all.
  229.      *  This means that if {@link #addForceModel addForceModel}
  230.      *  is not called after creation, the integrated orbit will
  231.      *  follow a Keplerian evolution only. Only the mean orbits
  232.      *  will be generated.
  233.      *  </p>
  234.      * @param field fied used by default
  235.      *  @param integrator numerical integrator to use for propagation.
  236.      * @param attitudeProvider attitude law to use.
  237.      * @since 10.1
  238.      */
  239.     public FieldDSSTPropagator(final Field<T> field,
  240.                                final FieldODEIntegrator<T> integrator,
  241.                                final AttitudeProvider attitudeProvider) {
  242.         super(field, integrator, PropagationType.MEAN);
  243.         this.field  = field;
  244.         forceModels = new ArrayList<DSSTForceModel>();
  245.         initMapper(field);
  246.         // DSST uses only equinoctial orbits and mean longitude argument
  247.         setOrbitType(OrbitType.EQUINOCTIAL);
  248.         setPositionAngleType(PositionAngle.MEAN);
  249.         setAttitudeProvider(attitudeProvider);
  250.         setInterpolationGridToFixedNumberOfPoints(INTERPOLATION_POINTS_PER_STEP);
  251.     }

  252.     /** Set the central attraction coefficient μ.
  253.      * <p>
  254.      * Setting the central attraction coefficient is
  255.      * equivalent to {@link #addForceModel(DSSTForceModel) add}
  256.      * a {@link DSSTNewtonianAttraction} force model.
  257.      * </p>
  258.     * @param mu central attraction coefficient (m³/s²)
  259.     * @see #addForceModel(DSSTForceModel)
  260.     * @see #getAllForceModels()
  261.     */
  262.     public void setMu(final T mu) {
  263.         addForceModel(new DSSTNewtonianAttraction(mu.getReal()));
  264.     }

  265.     /** Set the central attraction coefficient μ only in upper class.
  266.      * @param mu central attraction coefficient (m³/s²)
  267.      */
  268.     private void superSetMu(final T mu) {
  269.         super.setMu(mu);
  270.     }

  271.     /** Check if Newtonian attraction force model is available.
  272.      * <p>
  273.      * Newtonian attraction is always the last force model in the list.
  274.      * </p>
  275.      * @return true if Newtonian attraction force model is available
  276.      */
  277.     private boolean hasNewtonianAttraction() {
  278.         final int last = forceModels.size() - 1;
  279.         return last >= 0 && forceModels.get(last) instanceof DSSTNewtonianAttraction;
  280.     }

  281.     /** Set the initial state with osculating orbital elements.
  282.      *  @param initialState initial state (defined with osculating elements)
  283.      */
  284.     public void setInitialState(final FieldSpacecraftState<T> initialState) {
  285.         setInitialState(initialState, PropagationType.OSCULATING);
  286.     }

  287.     /** Set the initial state.
  288.      *  @param initialState initial state
  289.      *  @param stateType defined if the orbital state is defined with osculating or mean elements
  290.      */
  291.     public void setInitialState(final FieldSpacecraftState<T> initialState,
  292.                                 final PropagationType stateType) {
  293.         switch (stateType) {
  294.             case MEAN:
  295.                 initialIsOsculating = false;
  296.                 break;
  297.             case OSCULATING:
  298.                 initialIsOsculating = true;
  299.                 break;
  300.             default:
  301.                 throw new OrekitInternalError(null);
  302.         }
  303.         resetInitialState(initialState);
  304.     }

  305.     /** Reset the initial state.
  306.      *
  307.      *  @param state new initial state
  308.      */
  309.     @Override
  310.     public void resetInitialState(final FieldSpacecraftState<T> state) {
  311.         super.resetInitialState(state);
  312.         if (!hasNewtonianAttraction()) {
  313.             // use the state to define central attraction
  314.             setMu(state.getMu());
  315.         }
  316.         super.setStartDate(state.getDate());
  317.     }

  318.     /** Set the selected short periodic coefficients that must be stored as additional states.
  319.      * @param selectedCoefficients short periodic coefficients that must be stored as additional states
  320.      * (null means no coefficients are selected, empty set means all coefficients are selected)
  321.      */
  322.     public void setSelectedCoefficients(final Set<String> selectedCoefficients) {
  323.         mapper.setSelectedCoefficients(selectedCoefficients == null ?
  324.                                        null : new HashSet<String>(selectedCoefficients));
  325.     }

  326.     /** Get the selected short periodic coefficients that must be stored as additional states.
  327.      * @return short periodic coefficients that must be stored as additional states
  328.      * (null means no coefficients are selected, empty set means all coefficients are selected)
  329.      */
  330.     public Set<String> getSelectedCoefficients() {
  331.         final Set<String> set = mapper.getSelectedCoefficients();
  332.         return set == null ? null : Collections.unmodifiableSet(set);
  333.     }

  334.     /** Check if the initial state is provided in osculating elements.
  335.      * @return true if initial state is provided in osculating elements
  336.      */
  337.     public boolean initialIsOsculating() {
  338.         return initialIsOsculating;
  339.     }

  340.     /** Set the interpolation grid generator.
  341.      * <p>
  342.      * The generator will create an interpolation grid with a fixed
  343.      * number of points for each mean element integration step.
  344.      * </p>
  345.      * <p>
  346.      * If neither {@link #setInterpolationGridToFixedNumberOfPoints(int)}
  347.      * nor {@link #setInterpolationGridToMaxTimeGap(RealFieldElement)} has been called,
  348.      * by default the propagator is set as to 3 interpolations points per step.
  349.      * </p>
  350.      * @param interpolationPoints number of interpolation points at
  351.      * each integration step
  352.      * @see #setInterpolationGridToMaxTimeGap(RealFieldElement)
  353.      * @since 7.1
  354.      */
  355.     public void setInterpolationGridToFixedNumberOfPoints(final int interpolationPoints) {
  356.         interpolationgrid = new FieldFixedNumberInterpolationGrid<>(field, interpolationPoints);
  357.     }

  358.     /** Set the interpolation grid generator.
  359.      * <p>
  360.      * The generator will create an interpolation grid with a maximum
  361.      * time gap between interpolation points.
  362.      * </p>
  363.      * <p>
  364.      * If neither {@link #setInterpolationGridToFixedNumberOfPoints(int)}
  365.      * nor {@link #setInterpolationGridToMaxTimeGap(RealFieldElement)} has been called,
  366.      * by default the propagator is set as to 3 interpolations points per step.
  367.      * </p>
  368.      * @param maxGap maximum time gap between interpolation points (seconds)
  369.      * @see #setInterpolationGridToFixedNumberOfPoints(int)
  370.      * @since 7.1
  371.      */
  372.     public void setInterpolationGridToMaxTimeGap(final T maxGap) {
  373.         interpolationgrid = new FieldMaxGapInterpolationGrid<>(field, maxGap);
  374.     }

  375.     /** Add a force model to the global perturbation model.
  376.      *  <p>
  377.      *  If this method is not called at all,
  378.      *  the integrated orbit will follow a Keplerian evolution only.
  379.      *  </p>
  380.      *  @param force perturbing {@link DSSTForceModel force} to add
  381.      *  @see #removeForceModels()
  382.      *  @see #setMu(RealFieldElement)
  383.      */
  384.     public void addForceModel(final DSSTForceModel force) {

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

  387.             try {
  388.                 // ensure we are notified of any mu change
  389.                 force.getParametersDrivers()[0].addObserver(new ParameterObserver() {
  390.                     /** {@inheritDoc} */
  391.                     @Override
  392.                     public void valueChanged(final double previousValue, final ParameterDriver driver) {
  393.                         superSetMu(field.getZero().add(driver.getValue()));
  394.                     }
  395.                 });
  396.             } catch (OrekitException oe) {
  397.                 // this should never happen
  398.                 throw new OrekitInternalError(oe);
  399.             }

  400.             if (hasNewtonianAttraction()) {
  401.                 // there is already a central attraction model, replace it
  402.                 forceModels.set(forceModels.size() - 1, force);
  403.             } else {
  404.                 // there are no central attraction model yet, add it at the end of the list
  405.                 forceModels.add(force);
  406.             }
  407.         } else {
  408.             // we want to add a perturbing force model
  409.             if (hasNewtonianAttraction()) {
  410.                 // insert the new force model before Newtonian attraction,
  411.                 // which should always be the last one in the list
  412.                 forceModels.add(forceModels.size() - 1, force);
  413.             } else {
  414.                 // we only have perturbing force models up to now, just append at the end of the list
  415.                 forceModels.add(force);
  416.             }
  417.         }

  418.         force.registerAttitudeProvider(getAttitudeProvider());

  419.     }

  420.     /** Remove all perturbing force models from the global perturbation model
  421.      *  (except central attraction).
  422.      *  <p>
  423.      *  Once all perturbing forces have been removed (and as long as no new force model is added),
  424.      *  the integrated orbit will follow a Keplerian evolution only.
  425.      *  </p>
  426.      *  @see #addForceModel(DSSTForceModel)
  427.      */
  428.     public void removeForceModels() {
  429.         final int last = forceModels.size() - 1;
  430.         if (hasNewtonianAttraction()) {
  431.             // preserve the Newtonian attraction model at the end
  432.             final DSSTForceModel newton = forceModels.get(last);
  433.             forceModels.clear();
  434.             forceModels.add(newton);
  435.         } else {
  436.             forceModels.clear();
  437.         }
  438.     }

  439.     /** Get all the force models, perturbing forces and Newtonian attraction included.
  440.      * @return list of perturbing force models, with Newtonian attraction being the
  441.      * last one
  442.      * @see #addForceModel(DSSTForceModel)
  443.      * @see #setMu(RealFieldElement)
  444.      */
  445.     public List<DSSTForceModel> getAllForceModels() {
  446.         return Collections.unmodifiableList(forceModels);
  447.     }

  448.     /** Get propagation parameter type.
  449.      * @return orbit type used for propagation
  450.      */
  451.     public OrbitType getOrbitType() {
  452.         return super.getOrbitType();
  453.     }

  454.     /** Get propagation parameter type.
  455.      * @return angle type to use for propagation
  456.      */
  457.     public PositionAngle getPositionAngleType() {
  458.         return super.getPositionAngleType();
  459.     }

  460.     /** Conversion from mean to osculating orbit.
  461.      * <p>
  462.      * Compute osculating state <b>in a DSST sense</b>, corresponding to the
  463.      * mean SpacecraftState in input, and according to the Force models taken
  464.      * into account.
  465.      * </p><p>
  466.      * Since the osculating state is obtained by adding short-periodic variation
  467.      * of each force model, the resulting output will depend on the
  468.      * force models parameterized in input.
  469.      * </p>
  470.      * @param mean Mean state to convert
  471.      * @param forces Forces to take into account
  472.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  473.      * like atmospheric drag, radiation pressure or specific user-defined models)
  474.      * @return osculating state in a DSST sense
  475.      */
  476.     @SuppressWarnings("unchecked")
  477.     public FieldSpacecraftState<T> computeOsculatingState(final FieldSpacecraftState<T> mean,
  478.                                                           final AttitudeProvider attitudeProvider,
  479.                                                           final Collection<DSSTForceModel> forces) {

  480.         //Create the auxiliary object
  481.         final FieldAuxiliaryElements<T> aux = new FieldAuxiliaryElements<>(mean.getOrbit(), I);

  482.         // Set the force models
  483.         final List<FieldShortPeriodTerms<T>> shortPeriodTerms = new ArrayList<FieldShortPeriodTerms<T>>();
  484.         for (final DSSTForceModel force : forces) {
  485.             force.registerAttitudeProvider(attitudeProvider);
  486.             shortPeriodTerms.addAll(force.initialize(aux, PropagationType.OSCULATING, force.getParameters(field)));
  487.             force.updateShortPeriodTerms(force.getParameters(field), mean);
  488.         }

  489.         final FieldEquinoctialOrbit<T> osculatingOrbit = computeOsculatingOrbit(mean, shortPeriodTerms);

  490.         return new FieldSpacecraftState<>(osculatingOrbit, mean.getAttitude(), mean.getMass(),
  491.                                           mean.getAdditionalStates());

  492.     }

  493.     /** Conversion from osculating to mean orbit.
  494.      * <p>
  495.      * Compute mean state <b>in a DSST sense</b>, corresponding to the
  496.      * osculating SpacecraftState in input, and according to the Force models
  497.      * taken into account.
  498.      * </p><p>
  499.      * Since the osculating state is obtained with the computation of
  500.      * short-periodic variation of each force model, the resulting output will
  501.      * depend on the force models parameterized in input.
  502.      * </p><p>
  503.      * The computation is done through a fixed-point iteration process.
  504.      * </p>
  505.      * @param osculating Osculating state to convert
  506.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  507.      * like atmospheric drag, radiation pressure or specific user-defined models)
  508.      * @param forceModel Forces to take into account
  509.      * @return mean state in a DSST sense
  510.      */
  511.     public FieldSpacecraftState<T> computeMeanState(final FieldSpacecraftState<T> osculating,
  512.                                                     final AttitudeProvider attitudeProvider,
  513.                                                     final Collection<DSSTForceModel> forceModel) {
  514.         return computeMeanState(osculating, attitudeProvider, forceModel, EPSILON_DEFAULT, MAX_ITERATIONS_DEFAULT);
  515.     }

  516.     /** Conversion from osculating to mean orbit.
  517.      * <p>
  518.      * Compute mean state <b>in a DSST sense</b>, corresponding to the
  519.      * osculating SpacecraftState in input, and according to the Force models
  520.      * taken into account.
  521.      * </p><p>
  522.      * Since the osculating state is obtained with the computation of
  523.      * short-periodic variation of each force model, the resulting output will
  524.      * depend on the force models parameterized in input.
  525.      * </p><p>
  526.      * The computation is done through a fixed-point iteration process.
  527.      * </p>
  528.      * @param osculating Osculating state to convert
  529.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  530.      * like atmospheric drag, radiation pressure or specific user-defined models)
  531.      * @param forceModel Forces to take into account
  532.      * @param epsilon convergence threshold for mean parameters conversion
  533.      * @param maxIterations maximum iterations for mean parameters conversion
  534.      * @return mean state in a DSST sense
  535.      * @since 10.1
  536.      */
  537.     public FieldSpacecraftState<T> computeMeanState(final FieldSpacecraftState<T> osculating,
  538.                                                     final AttitudeProvider attitudeProvider,
  539.                                                     final Collection<DSSTForceModel> forceModel,
  540.                                                     final double epsilon,
  541.                                                     final int maxIterations) {
  542.         final FieldOrbit<T> meanOrbit = computeMeanOrbit(osculating, attitudeProvider, forceModel, epsilon, maxIterations);
  543.         return new FieldSpacecraftState<>(meanOrbit, osculating.getAttitude(), osculating.getMass(), osculating.getAdditionalStates());
  544.     }

  545.     /** Override the default value of the parameter.
  546.     *  <p>
  547.     *  By default, if the initial orbit is defined as osculating,
  548.     *  it will be averaged over 2 satellite revolutions.
  549.     *  This can be changed by using this method.
  550.     *  </p>
  551.     *  @param satelliteRevolution number of satellite revolutions to use for converting osculating to mean
  552.     *                             elements
  553.     */
  554.     public void setSatelliteRevolution(final int satelliteRevolution) {
  555.         mapper.setSatelliteRevolution(satelliteRevolution);
  556.     }

  557.    /** Get the number of satellite revolutions to use for converting osculating to mean elements.
  558.     *  @return number of satellite revolutions to use for converting osculating to mean elements
  559.     */
  560.     public int getSatelliteRevolution() {
  561.         return mapper.getSatelliteRevolution();
  562.     }

  563.    /** {@inheritDoc} */
  564.     @Override
  565.     public void setAttitudeProvider(final AttitudeProvider attitudeProvider) {
  566.         super.setAttitudeProvider(attitudeProvider);

  567.         //Register the attitude provider for each force model
  568.         for (final DSSTForceModel force : forceModels) {
  569.             force.registerAttitudeProvider(attitudeProvider);
  570.         }
  571.     }

  572.     /** Method called just before integration.
  573.      * <p>
  574.      * The default implementation does nothing, it may be specialized in subclasses.
  575.      * </p>
  576.      * @param initialState initial state
  577.      * @param tEnd target date at which state should be propagated
  578.      */
  579.     @SuppressWarnings("unchecked")
  580.     @Override
  581.     protected void beforeIntegration(final FieldSpacecraftState<T> initialState,
  582.                                      final FieldAbsoluteDate<T> tEnd) {

  583.         // check if only mean elements must be used
  584.         final PropagationType type = isMeanOrbit();

  585.         // compute common auxiliary elements
  586.         final FieldAuxiliaryElements<T> aux = new FieldAuxiliaryElements<>(initialState.getOrbit(), I);

  587.         // initialize all perturbing forces
  588.         final List<FieldShortPeriodTerms<T>> shortPeriodTerms = new ArrayList<FieldShortPeriodTerms<T>>();
  589.         for (final DSSTForceModel force : forceModels) {
  590.             shortPeriodTerms.addAll(force.initialize(aux, type, force.getParameters(field)));
  591.         }
  592.         mapper.setShortPeriodTerms(shortPeriodTerms);

  593.         // if required, insert the special short periodics step handler
  594.         if (type == PropagationType.OSCULATING) {
  595.             final FieldShortPeriodicsHandler spHandler = new FieldShortPeriodicsHandler(forceModels);
  596.             // Compute short periodic coefficients for this point
  597.             for (DSSTForceModel forceModel : forceModels) {
  598.                 forceModel.updateShortPeriodTerms(forceModel.getParameters(field), initialState);

  599.             }
  600.             final Collection<FieldODEStepHandler<T>> stepHandlers = new ArrayList<FieldODEStepHandler<T>>();
  601.             stepHandlers.add(spHandler);
  602.             final FieldODEIntegrator<T> integrator = getIntegrator();
  603.             final Collection<FieldODEStepHandler<T>> existing = integrator.getStepHandlers();
  604.             stepHandlers.addAll(existing);

  605.             integrator.clearStepHandlers();

  606.             // add back the existing handlers after the short periodics one
  607.             for (final FieldODEStepHandler<T> sp : stepHandlers) {
  608.                 integrator.addStepHandler(sp);
  609.             }
  610.         }
  611.     }

  612.     /** {@inheritDoc} */
  613.     @Override
  614.     protected void afterIntegration() {
  615.         // remove the special short periodics step handler if added before
  616.         if (isMeanOrbit() ==  PropagationType.OSCULATING) {
  617.             final List<FieldODEStepHandler<T>> preserved = new ArrayList<FieldODEStepHandler<T>>();
  618.             final FieldODEIntegrator<T> integrator = getIntegrator();

  619.             // clear the list
  620.             integrator.clearStepHandlers();

  621.             // add back the step handlers that were important for the user
  622.             for (final FieldODEStepHandler<T> sp : preserved) {
  623.                 integrator.addStepHandler(sp);
  624.             }
  625.         }
  626.     }

  627.     /** Compute mean state from osculating state.
  628.      * <p>
  629.      * Compute in a DSST sense the mean state corresponding to the input osculating state.
  630.      * </p><p>
  631.      * The computing is done through a fixed-point iteration process.
  632.      * </p>
  633.      * @param osculating initial osculating state
  634.      * @param attitudeProvider attitude provider (may be null if there are no Gaussian force models
  635.      * like atmospheric drag, radiation pressure or specific user-defined models)
  636.      * @param forceModel force models
  637.      * @param epsilon convergence threshold for mean parameters conversion
  638.      * @param maxIterations maximum iterations for mean parameters conversion
  639.      * @return mean state
  640.      * @since 10.1
  641.      */
  642.     @SuppressWarnings("unchecked")
  643.     private FieldOrbit<T> computeMeanOrbit(final FieldSpacecraftState<T> osculating, final AttitudeProvider attitudeProvider, final Collection<DSSTForceModel> forceModel,
  644.                                            final double epsilon, final int maxIterations) {

  645.         // zero
  646.         final T zero = field.getZero();

  647.         // rough initialization of the mean parameters
  648.         FieldEquinoctialOrbit<T> meanOrbit = (FieldEquinoctialOrbit<T>) OrbitType.EQUINOCTIAL.convertType(osculating.getOrbit());

  649.         // threshold for each parameter
  650.         final T epsilonT   = zero.add(epsilon);
  651.         final T thresholdA = epsilonT.multiply(FastMath.abs(meanOrbit.getA()).add(1.));
  652.         final T thresholdE = epsilonT.multiply(meanOrbit.getE().add(1.));
  653.         final T thresholdI = epsilonT.multiply(meanOrbit.getI().add(1.));
  654.         final T thresholdL = epsilonT.multiply(FastMath.PI);

  655.         // ensure all Gaussian force models can rely on attitude
  656.         for (final DSSTForceModel force : forceModel) {
  657.             force.registerAttitudeProvider(attitudeProvider);
  658.         }

  659.         int i = 0;
  660.         while (i++ < maxIterations) {

  661.             final FieldSpacecraftState<T> meanState = new FieldSpacecraftState<>(meanOrbit, osculating.getAttitude(), osculating.getMass());

  662.             //Create the auxiliary object
  663.             final FieldAuxiliaryElements<T> aux = new FieldAuxiliaryElements<>(meanOrbit, I);

  664.             // Set the force models
  665.             final List<FieldShortPeriodTerms<T>> shortPeriodTerms = new ArrayList<FieldShortPeriodTerms<T>>();
  666.             for (final DSSTForceModel force : forceModel) {
  667.                 shortPeriodTerms.addAll(force.initialize(aux, PropagationType.OSCULATING, force.getParameters(field)));
  668.                 force.updateShortPeriodTerms(force.getParameters(field), meanState);
  669.             }

  670.             // recompute the osculating parameters from the current mean parameters
  671.             final FieldEquinoctialOrbit<T> rebuilt = computeOsculatingOrbit(meanState, shortPeriodTerms);

  672.             // adapted parameters residuals
  673.             final T deltaA  = osculating.getA().subtract(rebuilt.getA());
  674.             final T deltaEx = osculating.getEquinoctialEx().subtract(rebuilt.getEquinoctialEx());
  675.             final T deltaEy = osculating.getEquinoctialEy().subtract(rebuilt.getEquinoctialEy());
  676.             final T deltaHx = osculating.getHx().subtract(rebuilt.getHx());
  677.             final T deltaHy = osculating.getHy().subtract(rebuilt.getHy());
  678.             final T deltaLv = MathUtils.normalizeAngle(osculating.getLv().subtract(rebuilt.getLv()), zero);

  679.             // check convergence
  680.             if (FastMath.abs(deltaA).getReal()  < thresholdA.getReal() &&
  681.                 FastMath.abs(deltaEx).getReal() < thresholdE.getReal() &&
  682.                 FastMath.abs(deltaEy).getReal() < thresholdE.getReal() &&
  683.                 FastMath.abs(deltaHx).getReal() < thresholdI.getReal() &&
  684.                 FastMath.abs(deltaHy).getReal() < thresholdI.getReal() &&
  685.                 FastMath.abs(deltaLv).getReal() < thresholdL.getReal()) {
  686.                 return meanOrbit;
  687.             }

  688.             // update mean parameters
  689.             meanOrbit = new FieldEquinoctialOrbit<>(meanOrbit.getA().add(deltaA),
  690.                                                     meanOrbit.getEquinoctialEx().add(deltaEx),
  691.                                                     meanOrbit.getEquinoctialEy().add(deltaEy),
  692.                                                     meanOrbit.getHx().add(deltaHx),
  693.                                                     meanOrbit.getHy().add(deltaHy),
  694.                                                     meanOrbit.getLv().add(deltaLv),
  695.                                                     PositionAngle.TRUE, meanOrbit.getFrame(),
  696.                                                     meanOrbit.getDate(), meanOrbit.getMu());
  697.         }

  698.         throw new OrekitException(OrekitMessages.UNABLE_TO_COMPUTE_DSST_MEAN_PARAMETERS, i);
  699.     }

  700.     /** Compute osculating state from mean state.
  701.      * <p>
  702.      * Compute and add the short periodic variation to the mean {@link SpacecraftState}.
  703.      * </p>
  704.      * @param meanState initial mean state
  705.      * @param shortPeriodTerms short period terms
  706.      * @return osculating state
  707.      */
  708.     private FieldEquinoctialOrbit<T> computeOsculatingOrbit(final FieldSpacecraftState<T> meanState,
  709.                                                             final List<FieldShortPeriodTerms<T>> shortPeriodTerms) {

  710.         final T[] mean = MathArrays.buildArray(field, 6);
  711.         final T[] meanDot = MathArrays.buildArray(field, 6);
  712.         OrbitType.EQUINOCTIAL.mapOrbitToArray(meanState.getOrbit(), PositionAngle.MEAN, mean, meanDot);
  713.         final T[] y = mean.clone();
  714.         for (final FieldShortPeriodTerms<T> spt : shortPeriodTerms) {
  715.             final T[] shortPeriodic = spt.value(meanState.getOrbit());
  716.             for (int i = 0; i < shortPeriodic.length; i++) {
  717.                 y[i] = y[i].add(shortPeriodic[i]);
  718.             }
  719.         }
  720.         return (FieldEquinoctialOrbit<T>) OrbitType.EQUINOCTIAL.mapArrayToOrbit(y, meanDot,
  721.                                                                                 PositionAngle.MEAN, meanState.getDate(),
  722.                                                                                 meanState.getMu(), meanState.getFrame());
  723.     }

  724.     /** {@inheritDoc} */
  725.     @Override
  726.     protected FieldSpacecraftState<T> getInitialIntegrationState() {
  727.         if (initialIsOsculating) {
  728.             // the initial state is an osculating state,
  729.             // it must be converted to mean state
  730.             return computeMeanState(getInitialState(), getAttitudeProvider(), forceModels);
  731.         } else {
  732.             // the initial state is already a mean state
  733.             return getInitialState();
  734.         }
  735.     }

  736.     /** {@inheritDoc}
  737.      * <p>
  738.      * Note that for DSST, orbit type is hardcoded to {@link OrbitType#EQUINOCTIAL}
  739.      * and position angle type is hardcoded to {@link PositionAngle#MEAN}, so
  740.      * the corresponding parameters are ignored.
  741.      * </p>
  742.      */
  743.     @Override
  744.     protected FieldStateMapper<T> createMapper(final FieldAbsoluteDate<T> referenceDate, final T mu,
  745.                                                final OrbitType ignoredOrbitType, final PositionAngle ignoredPositionAngleType,
  746.                                                final AttitudeProvider attitudeProvider, final Frame frame) {

  747.         // create a mapper with the common settings provided as arguments
  748.         final FieldMeanPlusShortPeriodicMapper newMapper =
  749.                 new FieldMeanPlusShortPeriodicMapper(referenceDate, mu, attitudeProvider, frame);

  750.         // copy the specific settings from the existing mapper
  751.         if (mapper != null) {
  752.             newMapper.setSatelliteRevolution(mapper.getSatelliteRevolution());
  753.             newMapper.setSelectedCoefficients(mapper.getSelectedCoefficients());
  754.             newMapper.setShortPeriodTerms(mapper.getShortPeriodTerms());
  755.         }

  756.         mapper = newMapper;
  757.         return mapper;

  758.     }

  759.     /** Internal mapper using mean parameters plus short periodic terms. */
  760.     private class FieldMeanPlusShortPeriodicMapper extends FieldStateMapper<T> {

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

  763.         /** Number of satellite revolutions in the averaging interval. */
  764.         private int                        satelliteRevolution;

  765.         /** Short period terms. */
  766.         private List<FieldShortPeriodTerms<T>>     shortPeriodTerms;

  767.         /** Simple constructor.
  768.          * @param referenceDate reference date
  769.          * @param mu central attraction coefficient (m³/s²)
  770.          * @param attitudeProvider attitude provider
  771.          * @param frame inertial frame
  772.          */
  773.         FieldMeanPlusShortPeriodicMapper(final FieldAbsoluteDate<T> referenceDate, final T mu,
  774.                                          final AttitudeProvider attitudeProvider, final Frame frame) {

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

  776.             this.selectedCoefficients = null;

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

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

  780.         }

  781.         /** {@inheritDoc} */
  782.         @Override
  783.         public FieldSpacecraftState<T> mapArrayToState(final FieldAbsoluteDate<T> date,
  784.                                                        final T[] y, final T[] yDot,
  785.                                                        final PropagationType type) {

  786.             // add short periodic variations to mean elements to get osculating elements
  787.             // (the loop may not be performed if there are no force models and in the
  788.             //  case we want to remain in mean parameters only)
  789.             final T[] elements = y.clone();
  790.             final Map<String, T[]> coefficients;
  791.             switch (type) {
  792.                 case MEAN:
  793.                     coefficients = null;
  794.                     break;
  795.                 case OSCULATING:
  796.                     final FieldOrbit<T> meanOrbit = OrbitType.EQUINOCTIAL.mapArrayToOrbit(elements, yDot, PositionAngle.MEAN, date, getMu(), getFrame());
  797.                     coefficients = selectedCoefficients == null ? null : new HashMap<String, T[]>();
  798.                     for (final FieldShortPeriodTerms<T> spt : shortPeriodTerms) {
  799.                         final T[] shortPeriodic = spt.value(meanOrbit);
  800.                         for (int i = 0; i < shortPeriodic.length; i++) {
  801.                             elements[i] = elements[i].add(shortPeriodic[i]);
  802.                         }
  803.                         if (selectedCoefficients != null) {
  804.                             coefficients.putAll(spt.getCoefficients(date, selectedCoefficients));
  805.                         }
  806.                     }
  807.                     break;
  808.                 default:
  809.                     throw new OrekitInternalError(null);
  810.             }

  811.             final T mass = elements[6];
  812.             if (mass.getReal() <= 0.0) {
  813.                 throw new OrekitException(OrekitMessages.SPACECRAFT_MASS_BECOMES_NEGATIVE, mass);
  814.             }

  815.             final FieldOrbit<T> orbit       = OrbitType.EQUINOCTIAL.mapArrayToOrbit(elements, yDot, PositionAngle.MEAN, date, getMu(), getFrame());
  816.             final FieldAttitude<T> attitude = getAttitudeProvider().getAttitude(orbit, date, getFrame());

  817.             if (coefficients == null) {
  818.                 return new FieldSpacecraftState<>(orbit, attitude, mass);
  819.             } else {
  820.                 return new FieldSpacecraftState<>(orbit, attitude, mass, coefficients);
  821.             }

  822.         }

  823.         /** {@inheritDoc} */
  824.         @Override
  825.         public void mapStateToArray(final FieldSpacecraftState<T> state, final T[] y, final T[] yDot) {

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

  828.         }

  829.         /** Set the number of satellite revolutions to use for converting osculating to mean elements.
  830.          *  <p>
  831.          *  By default, if the initial orbit is defined as osculating,
  832.          *  it will be averaged over 2 satellite revolutions.
  833.          *  This can be changed by using this method.
  834.          *  </p>
  835.          *  @param satelliteRevolution number of satellite revolutions to use for converting osculating to mean
  836.          *                             elements
  837.          */
  838.         public void setSatelliteRevolution(final int satelliteRevolution) {
  839.             this.satelliteRevolution = satelliteRevolution;
  840.         }

  841.         /** Get the number of satellite revolutions to use for converting osculating to mean elements.
  842.          *  @return number of satellite revolutions to use for converting osculating to mean elements
  843.          */
  844.         public int getSatelliteRevolution() {
  845.             return satelliteRevolution;
  846.         }

  847.         /** Set the selected short periodic coefficients that must be stored as additional states.
  848.          * @param selectedCoefficients short periodic coefficients that must be stored as additional states
  849.          * (null means no coefficients are selected, empty set means all coefficients are selected)
  850.          */
  851.         public void setSelectedCoefficients(final Set<String> selectedCoefficients) {
  852.             this.selectedCoefficients = selectedCoefficients;
  853.         }

  854.         /** Get the selected short periodic coefficients that must be stored as additional states.
  855.          * @return short periodic coefficients that must be stored as additional states
  856.          * (null means no coefficients are selected, empty set means all coefficients are selected)
  857.          */
  858.         public Set<String> getSelectedCoefficients() {
  859.             return selectedCoefficients;
  860.         }

  861.         /** Set the short period terms.
  862.          * @param shortPeriodTerms short period terms
  863.          * @since 7.1
  864.          */
  865.         public void setShortPeriodTerms(final List<FieldShortPeriodTerms<T>> shortPeriodTerms) {
  866.             this.shortPeriodTerms = shortPeriodTerms;
  867.         }

  868.         /** Get the short period terms.
  869.          * @return shortPeriodTerms short period terms
  870.          * @since 7.1
  871.          */
  872.         public List<FieldShortPeriodTerms<T>> getShortPeriodTerms() {
  873.             return shortPeriodTerms;
  874.         }

  875.     }

  876.     /** {@inheritDoc} */
  877.     @Override
  878.     protected MainStateEquations<T> getMainStateEquations(final FieldODEIntegrator<T> integrator) {
  879.         return new Main(integrator);
  880.     }

  881.     /** Internal class for mean parameters integration. */
  882.     private class Main implements MainStateEquations<T> {

  883.         /** Derivatives array. */
  884.         private final T[] yDot;

  885.         /** Simple constructor.
  886.          * @param integrator numerical integrator to use for propagation.
  887.          */
  888.         Main(final FieldODEIntegrator<T> integrator) {
  889.             yDot = MathArrays.buildArray(field, 7);

  890.             for (final DSSTForceModel forceModel : forceModels) {
  891.                 final FieldEventDetector<T>[] modelDetectors = forceModel.getFieldEventsDetectors(field);
  892.                 if (modelDetectors != null) {
  893.                     for (final FieldEventDetector<T> detector : modelDetectors) {
  894.                         setUpEventDetector(integrator, detector);
  895.                     }
  896.                 }
  897.             }

  898.         }

  899.         /** {@inheritDoc} */
  900.         @Override
  901.         public void init(final FieldSpacecraftState<T> initialState, final FieldAbsoluteDate<T> target) {
  902.         }

  903.         /** {@inheritDoc} */
  904.         @Override
  905.         public T[] computeDerivatives(final FieldSpacecraftState<T> state) {

  906.             final T zero = state.getDate().getField().getZero();
  907.             Arrays.fill(yDot, zero);

  908.             // compute common auxiliary elements
  909.             final FieldAuxiliaryElements<T> auxiliaryElements = new FieldAuxiliaryElements<>(state.getOrbit(), I);

  910.             // compute the contributions of all perturbing forces
  911.             for (final DSSTForceModel forceModel : forceModels) {
  912.                 final T[] daidt = elementRates(forceModel, state, auxiliaryElements, forceModel.getParameters(field));
  913.                 for (int i = 0; i < daidt.length; i++) {
  914.                     yDot[i] = yDot[i].add(daidt[i]);
  915.                 }
  916.             }

  917.             return yDot.clone();
  918.         }

  919.         /** This method allows to compute the mean equinoctial elements rates da<sub>i</sub> / dt
  920.          *  for a specific force model.
  921.          *  @param forceModel force to take into account
  922.          *  @param state current state
  923.          *  @param auxiliaryElements auxiliary elements related to the current orbit
  924.          *  @param parameters force model parameters
  925.          *  @return the mean equinoctial elements rates da<sub>i</sub> / dt
  926.          */
  927.         private T[] elementRates(final DSSTForceModel forceModel,
  928.                                  final FieldSpacecraftState<T> state,
  929.                                  final FieldAuxiliaryElements<T> auxiliaryElements,
  930.                                  final T[] parameters) {
  931.             return forceModel.getMeanElementRate(state, auxiliaryElements, parameters);
  932.         }

  933.     }

  934.     /** Estimate tolerance vectors for an AdaptativeStepsizeIntegrator.
  935.      *  <p>
  936.      *  The errors are estimated from partial derivatives properties of orbits,
  937.      *  starting from a scalar position error specified by the user.
  938.      *  Considering the energy conservation equation V = sqrt(mu (2/r - 1/a)),
  939.      *  we get at constant energy (i.e. on a Keplerian trajectory):
  940.      *
  941.      *  <pre>
  942.      *  V² r |dV| = mu |dr|
  943.      *  </pre>
  944.      *
  945.      *  <p> So we deduce a scalar velocity error consistent with the position error. From here, we apply
  946.      *  orbits Jacobians matrices to get consistent errors on orbital parameters.
  947.      *
  948.      *  <p>
  949.      *  The tolerances are only <em>orders of magnitude</em>, and integrator tolerances are only
  950.      *  local estimates, not global ones. So some care must be taken when using these tolerances.
  951.      *  Setting 1mm as a position error does NOT mean the tolerances will guarantee a 1mm error
  952.      *  position after several orbits integration.
  953.      *  </p>
  954.      * @param <T> elements type
  955.      * @param dP user specified position error (m)
  956.      * @param orbit reference orbit
  957.      * @return a two rows array, row 0 being the absolute tolerance error
  958.      *                       and row 1 being the relative tolerance error
  959.      */
  960.     public static <T extends RealFieldElement<T>> double[][] tolerances(final T dP, final FieldOrbit<T> orbit) {
  961.         return FieldNumericalPropagator.tolerances(dP, orbit, OrbitType.EQUINOCTIAL);
  962.     }

  963.     /** Estimate tolerance vectors for an AdaptativeStepsizeIntegrator.
  964.      *  <p>
  965.      *  The errors are estimated from partial derivatives properties of orbits,
  966.      *  starting from scalar position and velocity errors specified by the user.
  967.      *  <p>
  968.      *  The tolerances are only <em>orders of magnitude</em>, and integrator tolerances are only
  969.      *  local estimates, not global ones. So some care must be taken when using these tolerances.
  970.      *  Setting 1mm as a position error does NOT mean the tolerances will guarantee a 1mm error
  971.      *  position after several orbits integration.
  972.      *  </p>
  973.      *
  974.      * @param <T> elements type
  975.      * @param dP user specified position error (m)
  976.      * @param dV user specified velocity error (m/s)
  977.      * @param orbit reference orbit
  978.      * @return a two rows array, row 0 being the absolute tolerance error
  979.      *                       and row 1 being the relative tolerance error
  980.      * @since 10.3
  981.      */
  982.     public static <T extends RealFieldElement<T>> double[][] tolerances(final T dP, final T dV,
  983.                                                                         final FieldOrbit<T> orbit) {
  984.         return FieldNumericalPropagator.tolerances(dP, dV, orbit, OrbitType.EQUINOCTIAL);
  985.     }

  986.     /** Step handler used to compute the parameters for the short periodic contributions.
  987.      * @author Lucian Barbulescu
  988.      */
  989.     private class FieldShortPeriodicsHandler implements FieldODEStepHandler<T> {

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

  992.         /** Constructor.
  993.          * @param forceModels force models
  994.          */
  995.         FieldShortPeriodicsHandler(final List<DSSTForceModel> forceModels) {
  996.             this.forceModels = forceModels;
  997.         }

  998.         /** {@inheritDoc} */
  999.         @SuppressWarnings("unchecked")
  1000.         @Override
  1001.         public void handleStep(final FieldODEStateInterpolator<T> interpolator, final boolean isLast) {

  1002.             // Get the grid points to compute
  1003.             final T[] interpolationPoints =
  1004.                             interpolationgrid.getGridPoints(interpolator.getPreviousState().getTime(),
  1005.                                                             interpolator.getCurrentState().getTime());

  1006.             final FieldSpacecraftState<T>[] meanStates = new FieldSpacecraftState[interpolationPoints.length];
  1007.             for (int i = 0; i < interpolationPoints.length; ++i) {

  1008.                 // Build the mean state interpolated at grid point
  1009.                 final T time = interpolationPoints[i];
  1010.                 final FieldODEStateAndDerivative<T> sd = interpolator.getInterpolatedState(time);
  1011.                 meanStates[i] = mapper.mapArrayToState(time,
  1012.                                                        sd.getPrimaryState(),
  1013.                                                        sd.getPrimaryDerivative(),
  1014.                                                        PropagationType.MEAN);

  1015.             }

  1016.             // Compute short periodic coefficients for this step
  1017.             for (DSSTForceModel forceModel : forceModels) {
  1018.                 forceModel.updateShortPeriodTerms(forceModel.getParameters(field), meanStates);
  1019.             }

  1020.         }
  1021.     }

  1022. }