AbstractIntegratedPropagator.java

  1. /* Copyright 2002-2022 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.integration;

  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.LinkedList;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Queue;

  27. import org.hipparchus.exception.MathRuntimeException;
  28. import org.hipparchus.ode.DenseOutputModel;
  29. import org.hipparchus.ode.ExpandableODE;
  30. import org.hipparchus.ode.ODEIntegrator;
  31. import org.hipparchus.ode.ODEState;
  32. import org.hipparchus.ode.ODEStateAndDerivative;
  33. import org.hipparchus.ode.OrdinaryDifferentialEquation;
  34. import org.hipparchus.ode.SecondaryODE;
  35. import org.hipparchus.ode.events.Action;
  36. import org.hipparchus.ode.events.EventHandlerConfiguration;
  37. import org.hipparchus.ode.events.ODEEventHandler;
  38. import org.hipparchus.ode.sampling.AbstractODEStateInterpolator;
  39. import org.hipparchus.ode.sampling.ODEStateInterpolator;
  40. import org.hipparchus.ode.sampling.ODEStepHandler;
  41. import org.hipparchus.util.Precision;
  42. import org.orekit.attitudes.AttitudeProvider;
  43. import org.orekit.errors.OrekitException;
  44. import org.orekit.errors.OrekitInternalError;
  45. import org.orekit.errors.OrekitMessages;
  46. import org.orekit.frames.Frame;
  47. import org.orekit.orbits.OrbitType;
  48. import org.orekit.orbits.PositionAngle;
  49. import org.orekit.propagation.AbstractPropagator;
  50. import org.orekit.propagation.BoundedPropagator;
  51. import org.orekit.propagation.EphemerisGenerator;
  52. import org.orekit.propagation.PropagationType;
  53. import org.orekit.propagation.SpacecraftState;
  54. import org.orekit.propagation.events.EventDetector;
  55. import org.orekit.propagation.sampling.OrekitStepHandler;
  56. import org.orekit.propagation.sampling.OrekitStepInterpolator;
  57. import org.orekit.time.AbsoluteDate;
  58. import org.orekit.utils.DoubleArrayDictionary;


  59. /** Common handling of {@link org.orekit.propagation.Propagator Propagator}
  60.  *  methods for both numerical and semi-analytical propagators.
  61.  *  @author Luc Maisonobe
  62.  */
  63. public abstract class AbstractIntegratedPropagator extends AbstractPropagator {

  64.     /** Internal name used for complete secondary state dimension.
  65.      * @since 11.1
  66.      */
  67.     private static final String SECONDARY_DIMENSION = "Orekit-secondary-dimension";

  68.     /** Event detectors not related to force models. */
  69.     private final List<EventDetector> detectors;

  70.     /** Step handlers dedicated to ephemeris generation. */
  71.     private final List<StoringStepHandler> ephemerisGenerators;

  72.     /** Integrator selected by the user for the orbital extrapolation process. */
  73.     private final ODEIntegrator integrator;

  74.     /** Offsets of secondary states managed by {@link AdditionalEquations}.
  75.      * @since 11.1
  76.      */
  77.     private final Map<String, Integer> secondaryOffsets;

  78.     /** Additional derivatives providers.
  79.      * @since 11.1
  80.      */
  81.     private List<AdditionalDerivativesProvider> additionalDerivativesProviders;

  82.     /** Map of secondary equation offset in main
  83.     /** Counter for differential equations calls. */
  84.     private int calls;

  85.     /** Mapper between raw double components and space flight dynamics objects. */
  86.     private StateMapper stateMapper;

  87.     /** Flag for resetting the state at end of propagation. */
  88.     private boolean resetAtEnd;

  89.     /** Type of orbit to output (mean or osculating) <br/>
  90.      * <p>
  91.      * This is used only in the case of semianalitical propagators where there is a clear separation between
  92.      * mean and short periodic elements. It is ignored by the Numerical propagator.
  93.      * </p>
  94.      */
  95.     private PropagationType propagationType;

  96.     /** Build a new instance.
  97.      * @param integrator numerical integrator to use for propagation.
  98.      * @param propagationType type of orbit to output (mean or osculating).
  99.      */
  100.     protected AbstractIntegratedPropagator(final ODEIntegrator integrator, final PropagationType propagationType) {
  101.         detectors                      = new ArrayList<>();
  102.         ephemerisGenerators            = new ArrayList<>();
  103.         additionalDerivativesProviders = new ArrayList<>();
  104.         this.secondaryOffsets          = new HashMap<>();
  105.         this.integrator                = integrator;
  106.         this.propagationType           = propagationType;
  107.         this.resetAtEnd                = true;
  108.     }

  109.     /** Allow/disallow resetting the initial state at end of propagation.
  110.      * <p>
  111.      * By default, at the end of the propagation, the propagator resets the initial state
  112.      * to the final state, thus allowing a new propagation to be started from there without
  113.      * recomputing the part already performed. Calling this method with {@code resetAtEnd} set
  114.      * to false changes prevents such reset.
  115.      * </p>
  116.      * @param resetAtEnd if true, at end of each propagation, the {@link
  117.      * #getInitialState() initial state} will be reset to the final state of
  118.      * the propagation, otherwise the initial state will be preserved
  119.      * @since 9.0
  120.      */
  121.     public void setResetAtEnd(final boolean resetAtEnd) {
  122.         this.resetAtEnd = resetAtEnd;
  123.     }

  124.     /** Initialize the mapper. */
  125.     protected void initMapper() {
  126.         stateMapper = createMapper(null, Double.NaN, null, null, null, null);
  127.     }

  128.     /**  {@inheritDoc} */
  129.     public void setAttitudeProvider(final AttitudeProvider attitudeProvider) {
  130.         super.setAttitudeProvider(attitudeProvider);
  131.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  132.                                    stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
  133.                                    attitudeProvider, stateMapper.getFrame());
  134.     }

  135.     /** Set propagation orbit type.
  136.      * @param orbitType orbit type to use for propagation, null for
  137.      * propagating using {@link org.orekit.utils.AbsolutePVCoordinates AbsolutePVCoordinates}
  138.      * rather than {@link org.orekit.orbits Orbit}
  139.      */
  140.     protected void setOrbitType(final OrbitType orbitType) {
  141.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  142.                                    orbitType, stateMapper.getPositionAngleType(),
  143.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  144.     }

  145.     /** Get propagation parameter type.
  146.      * @return orbit type used for propagation, null for
  147.      * propagating using {@link org.orekit.utils.AbsolutePVCoordinates AbsolutePVCoordinates}
  148.      * rather than {@link org.orekit.orbits Orbit}
  149.      */
  150.     protected OrbitType getOrbitType() {
  151.         return stateMapper.getOrbitType();
  152.     }

  153.     /** Check if only the mean elements should be used in a semianalitical propagation.
  154.      * @return {@link PropagationType MEAN} if only mean elements have to be used or
  155.      *         {@link PropagationType OSCULATING} if osculating elements have to be also used.
  156.      * @deprecated as of 11.1, replaced by {@link #getPropagationType()}
  157.      */
  158.     @Deprecated
  159.     protected PropagationType isMeanOrbit() {
  160.         return getPropagationType();
  161.     }

  162.     /** Get the propagation type.
  163.      * @return propagation type.
  164.      * @since 11.1
  165.      */
  166.     public PropagationType getPropagationType() {
  167.         return propagationType;
  168.     }

  169.     /** Set position angle type.
  170.      * <p>
  171.      * The position parameter type is meaningful only if {@link
  172.      * #getOrbitType() propagation orbit type}
  173.      * support it. As an example, it is not meaningful for propagation
  174.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  175.      * </p>
  176.      * @param positionAngleType angle type to use for propagation
  177.      */
  178.     protected void setPositionAngleType(final PositionAngle positionAngleType) {
  179.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  180.                                    stateMapper.getOrbitType(), positionAngleType,
  181.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  182.     }

  183.     /** Get propagation parameter type.
  184.      * @return angle type to use for propagation
  185.      */
  186.     protected PositionAngle getPositionAngleType() {
  187.         return stateMapper.getPositionAngleType();
  188.     }

  189.     /** Set the central attraction coefficient μ.
  190.      * @param mu central attraction coefficient (m³/s²)
  191.      */
  192.     public void setMu(final double mu) {
  193.         stateMapper = createMapper(stateMapper.getReferenceDate(), mu,
  194.                                    stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
  195.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  196.     }

  197.     /** Get the central attraction coefficient μ.
  198.      * @return mu central attraction coefficient (m³/s²)
  199.      * @see #setMu(double)
  200.      */
  201.     public double getMu() {
  202.         return stateMapper.getMu();
  203.     }

  204.     /** Get the number of calls to the differential equations computation method.
  205.      * <p>The number of calls is reset each time the {@link #propagate(AbsoluteDate)}
  206.      * method is called.</p>
  207.      * @return number of calls to the differential equations computation method
  208.      */
  209.     public int getCalls() {
  210.         return calls;
  211.     }

  212.     /** {@inheritDoc} */
  213.     @Override
  214.     public boolean isAdditionalStateManaged(final String name) {

  215.         // first look at already integrated states
  216.         if (super.isAdditionalStateManaged(name)) {
  217.             return true;
  218.         }

  219.         // then look at states we integrate ourselves
  220.         for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  221.             if (provider.getName().equals(name)) {
  222.                 return true;
  223.             }
  224.         }

  225.         return false;
  226.     }

  227.     /** {@inheritDoc} */
  228.     @Override
  229.     public String[] getManagedAdditionalStates() {
  230.         final String[] alreadyIntegrated = super.getManagedAdditionalStates();
  231.         final String[] managed = new String[alreadyIntegrated.length + additionalDerivativesProviders.size()];
  232.         System.arraycopy(alreadyIntegrated, 0, managed, 0, alreadyIntegrated.length);
  233.         for (int i = 0; i < additionalDerivativesProviders.size(); ++i) {
  234.             managed[i + alreadyIntegrated.length] = additionalDerivativesProviders.get(i).getName();
  235.         }
  236.         return managed;
  237.     }

  238.     /** Add a set of user-specified equations to be integrated along with the orbit propagation.
  239.      * @param additional additional equations
  240.      * @deprecated as of 11.1, replaced by {@link #addAdditionalDerivativesProvider(AdditionalDerivativesProvider)}
  241.      */
  242.     @Deprecated
  243.     public void addAdditionalEquations(final AdditionalEquations additional) {
  244.         addAdditionalDerivativesProvider(new AdditionalEquationsAdapter(additional, this::getInitialState));
  245.     }

  246.     /** Add a provider for user-specified state derivatives to be integrated along with the orbit propagation.
  247.      * @param provider provider for additional derivatives
  248.      * @see #addAdditionalStateProvider(org.orekit.propagation.AdditionalStateProvider)
  249.      * @since 11.1
  250.      */
  251.     public void addAdditionalDerivativesProvider(final AdditionalDerivativesProvider provider) {

  252.         // check if the name is already used
  253.         if (isAdditionalStateManaged(provider.getName())) {
  254.             // these derivatives are already registered, complain
  255.             throw new OrekitException(OrekitMessages.ADDITIONAL_STATE_NAME_ALREADY_IN_USE,
  256.                                       provider.getName());
  257.         }

  258.         // this is really a new set of derivatives, add it
  259.         additionalDerivativesProviders.add(provider);

  260.         secondaryOffsets.clear();

  261.     }

  262.     /** Get an unmodifiable list of providers for additional derivatives.
  263.      * @return providers for the additional derivatives
  264.      * @since 11.1
  265.      */
  266.     public List<AdditionalDerivativesProvider> getAdditionalDerivativesProviders() {
  267.         return Collections.unmodifiableList(additionalDerivativesProviders);
  268.     }

  269.     /** {@inheritDoc} */
  270.     public void addEventDetector(final EventDetector detector) {
  271.         detectors.add(detector);
  272.     }

  273.     /** {@inheritDoc} */
  274.     public Collection<EventDetector> getEventsDetectors() {
  275.         return Collections.unmodifiableCollection(detectors);
  276.     }

  277.     /** {@inheritDoc} */
  278.     public void clearEventsDetectors() {
  279.         detectors.clear();
  280.     }

  281.     /** Set up all user defined event detectors.
  282.      */
  283.     protected void setUpUserEventDetectors() {
  284.         for (final EventDetector detector : detectors) {
  285.             setUpEventDetector(integrator, detector);
  286.         }
  287.     }

  288.     /** Wrap an Orekit event detector and register it to the integrator.
  289.      * @param integ integrator into which event detector should be registered
  290.      * @param detector event detector to wrap
  291.      */
  292.     protected void setUpEventDetector(final ODEIntegrator integ, final EventDetector detector) {
  293.         integ.addEventHandler(new AdaptedEventDetector(detector),
  294.                               detector.getMaxCheckInterval(),
  295.                               detector.getThreshold(),
  296.                               detector.getMaxIterationCount());
  297.     }

  298.     /** {@inheritDoc} */
  299.     @Override
  300.     public EphemerisGenerator getEphemerisGenerator() {
  301.         final StoringStepHandler storingHandler = new StoringStepHandler();
  302.         ephemerisGenerators.add(storingHandler);
  303.         return storingHandler;
  304.     }

  305.     /** Create a mapper between raw double components and spacecraft state.
  306.     /** Simple constructor.
  307.      * <p>
  308.      * The position parameter type is meaningful only if {@link
  309.      * #getOrbitType() propagation orbit type}
  310.      * support it. As an example, it is not meaningful for propagation
  311.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  312.      * </p>
  313.      * @param referenceDate reference date
  314.      * @param mu central attraction coefficient (m³/s²)
  315.      * @param orbitType orbit type to use for mapping
  316.      * @param positionAngleType angle type to use for propagation
  317.      * @param attitudeProvider attitude provider
  318.      * @param frame inertial frame
  319.      * @return new mapper
  320.      */
  321.     protected abstract StateMapper createMapper(AbsoluteDate referenceDate, double mu,
  322.                                                 OrbitType orbitType, PositionAngle positionAngleType,
  323.                                                 AttitudeProvider attitudeProvider, Frame frame);

  324.     /** Get the differential equations to integrate (for main state only).
  325.      * @param integ numerical integrator to use for propagation.
  326.      * @return differential equations for main state
  327.      */
  328.     protected abstract MainStateEquations getMainStateEquations(ODEIntegrator integ);

  329.     /** {@inheritDoc} */
  330.     public SpacecraftState propagate(final AbsoluteDate target) {
  331.         if (getStartDate() == null) {
  332.             if (getInitialState() == null) {
  333.                 throw new OrekitException(OrekitMessages.INITIAL_STATE_NOT_SPECIFIED_FOR_ORBIT_PROPAGATION);
  334.             }
  335.             setStartDate(getInitialState().getDate());
  336.         }
  337.         return propagate(getStartDate(), target);
  338.     }

  339.     /** {@inheritDoc} */
  340.     public SpacecraftState propagate(final AbsoluteDate tStart, final AbsoluteDate tEnd) {

  341.         if (getInitialState() == null) {
  342.             throw new OrekitException(OrekitMessages.INITIAL_STATE_NOT_SPECIFIED_FOR_ORBIT_PROPAGATION);
  343.         }

  344.         // make sure the integrator will be reset properly even if we change its events handlers and step handlers
  345.         try (IntegratorResetter resetter = new IntegratorResetter(integrator)) {

  346.             // prepare handling of STM and Jacobian matrices
  347.             setUpStmAndJacobianGenerators();

  348.             if (!tStart.equals(getInitialState().getDate())) {
  349.                 // if propagation start date is not initial date,
  350.                 // propagate from initial to start date without event detection
  351.                 try (IntegratorResetter startResetter = new IntegratorResetter(integrator)) {
  352.                     integrateDynamics(tStart);
  353.                 }
  354.             }

  355.             // set up events added by user
  356.             setUpUserEventDetectors();

  357.             // set up step handlers
  358.             for (final OrekitStepHandler handler : getMultiplexer().getHandlers()) {
  359.                 integrator.addStepHandler(new AdaptedStepHandler(handler));
  360.             }
  361.             for (final StoringStepHandler generator : ephemerisGenerators) {
  362.                 generator.setEndDate(tEnd);
  363.                 integrator.addStepHandler(generator);
  364.             }

  365.             // propagate from start date to end date with event detection
  366.             final SpacecraftState finalState = integrateDynamics(tEnd);

  367.             return finalState;

  368.         }

  369.     }

  370.     /** Set up State Transition Matrix and Jacobian matrix handling.
  371.      * @since 11.1
  372.      */
  373.     protected void setUpStmAndJacobianGenerators() {
  374.         // nothing to do by default
  375.     }

  376.     /** Propagation with or without event detection.
  377.      * @param tEnd target date to which orbit should be propagated
  378.      * @return state at end of propagation
  379.      */
  380.     private SpacecraftState integrateDynamics(final AbsoluteDate tEnd) {
  381.         try {

  382.             initializePropagation();

  383.             if (getInitialState().getDate().equals(tEnd)) {
  384.                 // don't extrapolate
  385.                 return getInitialState();
  386.             }

  387.             // space dynamics view
  388.             stateMapper = createMapper(getInitialState().getDate(), stateMapper.getMu(),
  389.                                        stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
  390.                                        stateMapper.getAttitudeProvider(), getInitialState().getFrame());


  391.             if (Double.isNaN(getMu())) {
  392.                 setMu(getInitialState().getMu());
  393.             }

  394.             if (getInitialState().getMass() <= 0.0) {
  395.                 throw new OrekitException(OrekitMessages.SPACECRAFT_MASS_BECOMES_NEGATIVE,
  396.                                           getInitialState().getMass());
  397.             }

  398.             // convert space flight dynamics API to math API
  399.             final SpacecraftState initialIntegrationState = getInitialIntegrationState();
  400.             final ODEState mathInitialState = createInitialState(initialIntegrationState);
  401.             final ExpandableODE mathODE = createODE(integrator, mathInitialState);

  402.             // mathematical integration
  403.             final ODEStateAndDerivative mathFinalState;
  404.             beforeIntegration(initialIntegrationState, tEnd);
  405.             mathFinalState = integrator.integrate(mathODE, mathInitialState,
  406.                                                   tEnd.durationFrom(getInitialState().getDate()));
  407.             afterIntegration();

  408.             // get final state
  409.             SpacecraftState finalState =
  410.                             stateMapper.mapArrayToState(stateMapper.mapDoubleToDate(mathFinalState.getTime(),
  411.                                                                                     tEnd),
  412.                                                         mathFinalState.getPrimaryState(),
  413.                                                         mathFinalState.getPrimaryDerivative(),
  414.                                                         propagationType);

  415.             if (!additionalDerivativesProviders.isEmpty()) {
  416.                 final double[] secondary            = mathFinalState.getSecondaryState(1);
  417.                 final double[] secondaryDerivatives = mathFinalState.getSecondaryDerivative(1);
  418.                 for (AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  419.                     final String   name        = provider.getName();
  420.                     final int      offset      = secondaryOffsets.get(name);
  421.                     final int      dimension   = provider.getDimension();
  422.                     finalState = finalState.
  423.                                  addAdditionalState(name, Arrays.copyOfRange(secondary, offset, offset + dimension)).
  424.                                  addAdditionalStateDerivative(name, Arrays.copyOfRange(secondaryDerivatives, offset, offset + dimension));
  425.                 }
  426.             }
  427.             finalState = updateAdditionalStates(finalState);

  428.             if (resetAtEnd) {
  429.                 resetInitialState(finalState);
  430.                 setStartDate(finalState.getDate());
  431.             }

  432.             return finalState;

  433.         } catch (MathRuntimeException mre) {
  434.             throw OrekitException.unwrap(mre);
  435.         }
  436.     }

  437.     /** Get the initial state for integration.
  438.      * @return initial state for integration
  439.      */
  440.     protected SpacecraftState getInitialIntegrationState() {
  441.         return getInitialState();
  442.     }

  443.     /** Create an initial state.
  444.      * @param initialState initial state in flight dynamics world
  445.      * @return initial state in mathematics world
  446.      */
  447.     private ODEState createInitialState(final SpacecraftState initialState) {

  448.         // retrieve initial state
  449.         final double[] primary = new double[getBasicDimension()];
  450.         stateMapper.mapStateToArray(initialState, primary, null);

  451.         if (secondaryOffsets.isEmpty()) {
  452.             // compute dimension of the secondary state
  453.             int offset = 0;
  454.             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  455.                 secondaryOffsets.put(provider.getName(), offset);
  456.                 offset += provider.getDimension();
  457.             }
  458.             secondaryOffsets.put(SECONDARY_DIMENSION, offset);
  459.         }

  460.         return new ODEState(0.0, primary, secondary(initialState));

  461.     }

  462.     /** Create secondary state.
  463.      * @param state spacecraft state
  464.      * @return secondary state
  465.      * @since 11.1
  466.      */
  467.     private double[][] secondary(final SpacecraftState state) {

  468.         if (secondaryOffsets.isEmpty()) {
  469.             return null;
  470.         }

  471.         final double[][] secondary = new double[1][secondaryOffsets.get(SECONDARY_DIMENSION)];
  472.         for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  473.             final String   name       = provider.getName();
  474.             final int      offset     = secondaryOffsets.get(name);
  475.             final double[] additional = state.getAdditionalState(name);
  476.             System.arraycopy(additional, 0, secondary[0], offset, additional.length);
  477.         }

  478.         return secondary;

  479.     }

  480.     /** Create secondary state derivative.
  481.      * @param state spacecraft state
  482.      * @return secondary state derivative
  483.      * @since 11.1
  484.      */
  485.     private double[][] secondaryDerivative(final SpacecraftState state) {

  486.         if (secondaryOffsets.isEmpty()) {
  487.             return null;
  488.         }

  489.         final double[][] secondaryDerivative = new double[1][secondaryOffsets.get(SECONDARY_DIMENSION)];
  490.         for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  491.             final String   name       = provider.getName();
  492.             final int      offset     = secondaryOffsets.get(name);
  493.             final double[] additionalDerivative = state.getAdditionalStateDerivative(name);
  494.             System.arraycopy(additionalDerivative, 0, secondaryDerivative[0], offset, additionalDerivative.length);
  495.         }

  496.         return secondaryDerivative;

  497.     }

  498.     /** Create an ODE with all equations.
  499.      * @param integ numerical integrator to use for propagation.
  500.      * @param mathInitialState initial state
  501.      * @return a new ode
  502.      */
  503.     private ExpandableODE createODE(final ODEIntegrator integ,
  504.                                     final ODEState mathInitialState) {

  505.         final ExpandableODE ode =
  506.                 new ExpandableODE(new ConvertedMainStateEquations(getMainStateEquations(integ)));

  507.         // secondary part of the ODE
  508.         if (!additionalDerivativesProviders.isEmpty()) {
  509.             ode.addSecondaryEquations(new ConvertedSecondaryStateEquations());
  510.         }

  511.         return ode;

  512.     }

  513.     /** Method called just before integration.
  514.      * <p>
  515.      * The default implementation does nothing, it may be specialized in subclasses.
  516.      * </p>
  517.      * @param initialState initial state
  518.      * @param tEnd target date at which state should be propagated
  519.      */
  520.     protected void beforeIntegration(final SpacecraftState initialState,
  521.                                      final AbsoluteDate tEnd) {
  522.         // do nothing by default
  523.     }

  524.     /** Method called just after integration.
  525.      * <p>
  526.      * The default implementation does nothing, it may be specialized in subclasses.
  527.      * </p>
  528.      */
  529.     protected void afterIntegration() {
  530.         // do nothing by default
  531.     }

  532.     /** Get state vector dimension without additional parameters.
  533.      * @return state vector dimension without additional parameters.
  534.      */
  535.     public int getBasicDimension() {
  536.         return 7;
  537.     }

  538.     /** Get the integrator used by the propagator.
  539.      * @return the integrator.
  540.      */
  541.     protected ODEIntegrator getIntegrator() {
  542.         return integrator;
  543.     }

  544.     /** Convert a state from mathematical world to space flight dynamics world.
  545.      * @param os mathematical state
  546.      * @return space flight dynamics state
  547.      */
  548.     private SpacecraftState convert(final ODEStateAndDerivative os) {

  549.         SpacecraftState s = stateMapper.mapArrayToState(os.getTime(),
  550.                                                         os.getPrimaryState(),
  551.                                                         os.getPrimaryDerivative(),
  552.                                                         propagationType);
  553.         if (os.getNumberOfSecondaryStates() > 0) {
  554.             final double[] secondary           = os.getSecondaryState(1);
  555.             final double[] secondaryDerivative = os.getSecondaryDerivative(1);
  556.             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  557.                 final String name      = provider.getName();
  558.                 final int    offset    = secondaryOffsets.get(name);
  559.                 final int    dimension = provider.getDimension();
  560.                 s = s.addAdditionalState(name, Arrays.copyOfRange(secondary, offset, offset + dimension));
  561.                 s = s.addAdditionalStateDerivative(name, Arrays.copyOfRange(secondaryDerivative, offset, offset + dimension));
  562.             }
  563.         }
  564.         s = updateAdditionalStates(s);

  565.         return s;

  566.     }

  567.     /** Convert a state from space flight dynamics world to mathematical world.
  568.      * @param state space flight dynamics state
  569.      * @return mathematical state
  570.      */
  571.     private ODEStateAndDerivative convert(final SpacecraftState state) {

  572.         // retrieve initial state
  573.         final double[] primary    = new double[getBasicDimension()];
  574.         final double[] primaryDot = new double[getBasicDimension()];
  575.         stateMapper.mapStateToArray(state, primary, primaryDot);

  576.         // secondary part of the ODE
  577.         final double[][] secondary           = secondary(state);
  578.         final double[][] secondaryDerivative = secondaryDerivative(state);

  579.         return new ODEStateAndDerivative(stateMapper.mapDateToDouble(state.getDate()),
  580.                                          primary, primaryDot,
  581.                                          secondary, secondaryDerivative);

  582.     }

  583.     /** Differential equations for the main state (orbit, attitude and mass). */
  584.     public interface MainStateEquations {

  585.         /**
  586.          * Initialize the equations at the start of propagation. This method will be
  587.          * called before any calls to {@link #computeDerivatives(SpacecraftState)}.
  588.          *
  589.          * <p> The default implementation of this method does nothing.
  590.          *
  591.          * @param initialState initial state information at the start of propagation.
  592.          * @param target       date of propagation. Not equal to {@code
  593.          *                     initialState.getDate()}.
  594.          */
  595.         default void init(final SpacecraftState initialState, final AbsoluteDate target) {
  596.         }

  597.         /** Compute differential equations for main state.
  598.          * @param state current state
  599.          * @return derivatives of main state
  600.          */
  601.         double[] computeDerivatives(SpacecraftState state);

  602.     }

  603.     /** Differential equations for the main state (orbit, attitude and mass), with converted API. */
  604.     private class ConvertedMainStateEquations implements OrdinaryDifferentialEquation {

  605.         /** Main state equations. */
  606.         private final MainStateEquations main;

  607.         /** Simple constructor.
  608.          * @param main main state equations
  609.          */
  610.         ConvertedMainStateEquations(final MainStateEquations main) {
  611.             this.main = main;
  612.             calls = 0;
  613.         }

  614.         /** {@inheritDoc} */
  615.         public int getDimension() {
  616.             return getBasicDimension();
  617.         }

  618.         @Override
  619.         public void init(final double t0, final double[] y0, final double finalTime) {
  620.             // update space dynamics view
  621.             SpacecraftState initialState = stateMapper.mapArrayToState(t0, y0, null, PropagationType.MEAN);
  622.             initialState = updateAdditionalStates(initialState);
  623.             final AbsoluteDate target = stateMapper.mapDoubleToDate(finalTime);
  624.             main.init(initialState, target);
  625.         }

  626.         /** {@inheritDoc} */
  627.         public double[] computeDerivatives(final double t, final double[] y) {

  628.             // increment calls counter
  629.             ++calls;

  630.             // update space dynamics view
  631.             SpacecraftState currentState = stateMapper.mapArrayToState(t, y, null, PropagationType.MEAN);
  632.             currentState = updateAdditionalStates(currentState);

  633.             // compute main state differentials
  634.             return main.computeDerivatives(currentState);

  635.         }

  636.     }

  637.     /** Differential equations for the secondary state (Jacobians, user variables ...), with converted API. */
  638.     private class ConvertedSecondaryStateEquations implements SecondaryODE {

  639.         /** Dimension of the combined additional states. */
  640.         private final int combinedDimension;

  641.         /** Simple constructor.
  642.           */
  643.         ConvertedSecondaryStateEquations() {
  644.             this.combinedDimension = secondaryOffsets.get(SECONDARY_DIMENSION);
  645.         }

  646.         /** {@inheritDoc} */
  647.         @Override
  648.         public int getDimension() {
  649.             return combinedDimension;
  650.         }

  651.         /** {@inheritDoc} */
  652.         @Override
  653.         public void init(final double t0, final double[] primary0,
  654.                          final double[] secondary0, final double finalTime) {
  655.             // update space dynamics view
  656.             final SpacecraftState initialState = convert(t0, primary0, null, secondary0);

  657.             final AbsoluteDate target = stateMapper.mapDoubleToDate(finalTime);
  658.             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  659.                 provider.init(initialState, target);
  660.             }

  661.         }

  662.         /** {@inheritDoc} */
  663.         @Override
  664.         public double[] computeDerivatives(final double t, final double[] primary,
  665.                                            final double[] primaryDot, final double[] secondary) {

  666.             // update space dynamics view
  667.             // the integrable generators generate method will be called here,
  668.             // according to the generators yield order
  669.             SpacecraftState updated = convert(t, primary, primaryDot, secondary);

  670.             // set up queue for equations
  671.             final Queue<AdditionalDerivativesProvider> pending = new LinkedList<>(additionalDerivativesProviders);

  672.             // gather the derivatives from all additional equations, taking care of dependencies
  673.             final double[] secondaryDot = new double[combinedDimension];
  674.             int yieldCount = 0;
  675.             while (!pending.isEmpty()) {
  676.                 final AdditionalDerivativesProvider provider = pending.remove();
  677.                 if (provider.yield(updated)) {
  678.                     // this provider has to wait for another one,
  679.                     // we put it again in the pending queue
  680.                     pending.add(provider);
  681.                     if (++yieldCount >= pending.size()) {
  682.                         // all pending providers yielded!, they probably need data not yet initialized
  683.                         // we let the propagation proceed, if these data are really needed right now
  684.                         // an appropriate exception will be triggered when caller tries to access them
  685.                         break;
  686.                     }
  687.                 } else {
  688.                     // we can use these equations right now
  689.                     final String   name        = provider.getName();
  690.                     final int      offset      = secondaryOffsets.get(name);
  691.                     final int      dimension   = provider.getDimension();
  692.                     final double[] derivatives = provider.derivatives(updated);
  693.                     System.arraycopy(derivatives, 0, secondaryDot, offset, dimension);
  694.                     updated = updated.addAdditionalStateDerivative(name, derivatives);
  695.                     yieldCount = 0;
  696.                 }
  697.             }

  698.             return secondaryDot;

  699.         }

  700.         /** Convert mathematical view to space view.
  701.          * @param t current value of the independent <I>time</I> variable
  702.          * @param primary array containing the current value of the primary state vector
  703.          * @param primaryDot array containing the derivative of the primary state vector
  704.          * @param secondary array containing the current value of the secondary state vector
  705.          * @return space view of the state
  706.          */
  707.         private SpacecraftState convert(final double t, final double[] primary,
  708.                                         final double[] primaryDot, final double[] secondary) {

  709.             SpacecraftState initialState = stateMapper.mapArrayToState(t, primary, primaryDot, PropagationType.MEAN);

  710.             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  711.                 final String name      = provider.getName();
  712.                 final int    offset    = secondaryOffsets.get(name);
  713.                 final int    dimension = provider.getDimension();
  714.                 initialState = initialState.addAdditionalState(name, Arrays.copyOfRange(secondary, offset, offset + dimension));
  715.             }

  716.             return updateAdditionalStates(initialState);

  717.         }

  718.     }

  719.     /** Adapt an {@link org.orekit.propagation.events.EventDetector}
  720.      * to Hipparchus {@link org.hipparchus.ode.events.ODEEventHandler} interface.
  721.      * @author Fabien Maussion
  722.      */
  723.     private class AdaptedEventDetector implements ODEEventHandler {

  724.         /** Underlying event detector. */
  725.         private final EventDetector detector;

  726.         /** Time of the previous call to g. */
  727.         private double lastT;

  728.         /** Value from the previous call to g. */
  729.         private double lastG;

  730.         /** Build a wrapped event detector.
  731.          * @param detector event detector to wrap
  732.         */
  733.         AdaptedEventDetector(final EventDetector detector) {
  734.             this.detector = detector;
  735.             this.lastT    = Double.NaN;
  736.             this.lastG    = Double.NaN;
  737.         }

  738.         /** {@inheritDoc} */
  739.         public void init(final ODEStateAndDerivative s0, final double t) {
  740.             detector.init(convert(s0), stateMapper.mapDoubleToDate(t));
  741.             this.lastT = Double.NaN;
  742.             this.lastG = Double.NaN;
  743.         }

  744.         /** {@inheritDoc} */
  745.         public double g(final ODEStateAndDerivative s) {
  746.             if (!Precision.equals(lastT, s.getTime(), 0)) {
  747.                 lastT = s.getTime();
  748.                 lastG = detector.g(convert(s));
  749.             }
  750.             return lastG;
  751.         }

  752.         /** {@inheritDoc} */
  753.         public Action eventOccurred(final ODEStateAndDerivative s, final boolean increasing) {
  754.             return detector.eventOccurred(convert(s), increasing);
  755.         }

  756.         /** {@inheritDoc} */
  757.         public ODEState resetState(final ODEStateAndDerivative s) {

  758.             final SpacecraftState oldState = convert(s);
  759.             final SpacecraftState newState = detector.resetState(oldState);
  760.             stateChanged(newState);

  761.             // main part
  762.             final double[] primary    = new double[s.getPrimaryStateDimension()];
  763.             stateMapper.mapStateToArray(newState, primary, null);

  764.             // secondary part
  765.             final double[][] secondary = new double[1][secondaryOffsets.get(SECONDARY_DIMENSION)];
  766.             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  767.                 final String name      = provider.getName();
  768.                 final int    offset    = secondaryOffsets.get(name);
  769.                 final int    dimension = provider.getDimension();
  770.                 System.arraycopy(newState.getAdditionalState(name), 0, secondary[0], offset, dimension);
  771.             }

  772.             return new ODEState(newState.getDate().durationFrom(getStartDate()),
  773.                                 primary, secondary);

  774.         }

  775.     }

  776.     /** Adapt an {@link org.orekit.propagation.sampling.OrekitStepHandler}
  777.      * to Hipparchus {@link ODEStepHandler} interface.
  778.      * @author Luc Maisonobe
  779.      */
  780.     private class AdaptedStepHandler implements ODEStepHandler {

  781.         /** Underlying handler. */
  782.         private final OrekitStepHandler handler;

  783.         /** Build an instance.
  784.          * @param handler underlying handler to wrap
  785.          */
  786.         AdaptedStepHandler(final OrekitStepHandler handler) {
  787.             this.handler = handler;
  788.         }

  789.         /** {@inheritDoc} */
  790.         public void init(final ODEStateAndDerivative s0, final double t) {
  791.             handler.init(convert(s0), stateMapper.mapDoubleToDate(t));
  792.         }

  793.         /** {@inheritDoc} */
  794.         @Override
  795.         public void handleStep(final ODEStateInterpolator interpolator) {
  796.             handler.handleStep(new AdaptedStepInterpolator(interpolator));
  797.         }

  798.         /** {@inheritDoc} */
  799.         @Override
  800.         public void finish(final ODEStateAndDerivative finalState) {
  801.             handler.finish(convert(finalState));
  802.         }

  803.     }

  804.     /** Adapt an Hipparchus {@link ODEStateInterpolator}
  805.      * to an orekit {@link OrekitStepInterpolator} interface.
  806.      * @author Luc Maisonobe
  807.      */
  808.     private class AdaptedStepInterpolator implements OrekitStepInterpolator {

  809.         /** Underlying raw rawInterpolator. */
  810.         private final ODEStateInterpolator mathInterpolator;

  811.         /** Simple constructor.
  812.          * @param mathInterpolator underlying raw interpolator
  813.          */
  814.         AdaptedStepInterpolator(final ODEStateInterpolator mathInterpolator) {
  815.             this.mathInterpolator = mathInterpolator;
  816.         }

  817.         /** {@inheritDoc}} */
  818.         @Override
  819.         public SpacecraftState getPreviousState() {
  820.             return convert(mathInterpolator.getPreviousState());
  821.         }

  822.         /** {@inheritDoc}} */
  823.         @Override
  824.         public boolean isPreviousStateInterpolated() {
  825.             return mathInterpolator.isPreviousStateInterpolated();
  826.         }

  827.         /** {@inheritDoc}} */
  828.         @Override
  829.         public SpacecraftState getCurrentState() {
  830.             return convert(mathInterpolator.getCurrentState());
  831.         }

  832.         /** {@inheritDoc}} */
  833.         @Override
  834.         public boolean isCurrentStateInterpolated() {
  835.             return mathInterpolator.isCurrentStateInterpolated();
  836.         }

  837.         /** {@inheritDoc}} */
  838.         @Override
  839.         public SpacecraftState getInterpolatedState(final AbsoluteDate date) {
  840.             return convert(mathInterpolator.getInterpolatedState(date.durationFrom(stateMapper.getReferenceDate())));
  841.         }

  842.         /** {@inheritDoc}} */
  843.         @Override
  844.         public boolean isForward() {
  845.             return mathInterpolator.isForward();
  846.         }

  847.         /** {@inheritDoc}} */
  848.         @Override
  849.         public AdaptedStepInterpolator restrictStep(final SpacecraftState newPreviousState,
  850.                                                     final SpacecraftState newCurrentState) {
  851.             try {
  852.                 final AbstractODEStateInterpolator aosi = (AbstractODEStateInterpolator) mathInterpolator;
  853.                 return new AdaptedStepInterpolator(aosi.restrictStep(convert(newPreviousState),
  854.                                                                      convert(newCurrentState)));
  855.             } catch (ClassCastException cce) {
  856.                 // this should never happen
  857.                 throw new OrekitInternalError(cce);
  858.             }
  859.         }

  860.     }

  861.     /** Specialized step handler storing interpolators for ephemeris generation.
  862.      * @since 11.0
  863.      */
  864.     private class StoringStepHandler implements ODEStepHandler, EphemerisGenerator {

  865.         /** Underlying raw mathematical model. */
  866.         private DenseOutputModel model;

  867.         /** the user supplied end date. Propagation may not end on this date. */
  868.         private AbsoluteDate endDate;

  869.         /** Generated ephemeris. */
  870.         private BoundedPropagator ephemeris;

  871.         /** Set the end date.
  872.          * @param endDate end date
  873.          */
  874.         public void setEndDate(final AbsoluteDate endDate) {
  875.             this.endDate = endDate;
  876.         }

  877.         /** {@inheritDoc} */
  878.         @Override
  879.         public void init(final ODEStateAndDerivative s0, final double t) {

  880.             this.model = new DenseOutputModel();
  881.             model.init(s0, t);

  882.             // ephemeris will be generated when last step is processed
  883.             this.ephemeris = null;

  884.         }

  885.         /** {@inheritDoc} */
  886.         @Override
  887.         public BoundedPropagator getGeneratedEphemeris() {
  888.             return ephemeris;
  889.         }

  890.         /** {@inheritDoc} */
  891.         @Override
  892.         public void handleStep(final ODEStateInterpolator interpolator) {
  893.             model.handleStep(interpolator);
  894.         }

  895.         /** {@inheritDoc} */
  896.         @Override
  897.         public void finish(final ODEStateAndDerivative finalState) {

  898.             // set up the boundary dates
  899.             final double tI = model.getInitialTime();
  900.             final double tF = model.getFinalTime();
  901.             // tI is almost? always zero
  902.             final AbsoluteDate startDate =
  903.                             stateMapper.mapDoubleToDate(tI);
  904.             final AbsoluteDate finalDate =
  905.                             stateMapper.mapDoubleToDate(tF, this.endDate);
  906.             final AbsoluteDate minDate;
  907.             final AbsoluteDate maxDate;
  908.             if (tF < tI) {
  909.                 minDate = finalDate;
  910.                 maxDate = startDate;
  911.             } else {
  912.                 minDate = startDate;
  913.                 maxDate = finalDate;
  914.             }

  915.             // get the initial additional states that are not managed
  916.             final DoubleArrayDictionary unmanaged = new DoubleArrayDictionary();
  917.             for (final DoubleArrayDictionary.Entry initial : getInitialState().getAdditionalStatesValues().getData()) {
  918.                 if (!isAdditionalStateManaged(initial.getKey())) {
  919.                     // this additional state was in the initial state, but is unknown to the propagator
  920.                     // we simply copy its initial value as is
  921.                     unmanaged.put(initial.getKey(), initial.getValue());
  922.                 }
  923.             }

  924.             // get the names of additional states managed by differential equations
  925.             final String[] names = new String[additionalDerivativesProviders.size()];
  926.             for (int i = 0; i < names.length; ++i) {
  927.                 names[i] = additionalDerivativesProviders.get(i).getName();
  928.             }

  929.             // create the ephemeris
  930.             ephemeris = new IntegratedEphemeris(startDate, minDate, maxDate,
  931.                                                 stateMapper, propagationType, model,
  932.                                                 unmanaged, getAdditionalStateProviders(), names);

  933.         }

  934.     }

  935.     /** Wrapper for resetting an integrator handlers.
  936.      * <p>
  937.      * This class is intended to be used in a try-with-resource statement.
  938.      * If propagator-specific event handlers and step handlers are added to
  939.      * the integrator in the try block, they will be removed automatically
  940.      * when leaving the block, so the integrator only keeps its own handlers
  941.      * between calls to {@link AbstractIntegratedPropagator#propagate(AbsoluteDate, AbsoluteDate).
  942.      * </p>
  943.      * @since 11.0
  944.      */
  945.     private static class IntegratorResetter implements AutoCloseable {

  946.         /** Wrapped integrator. */
  947.         private final ODEIntegrator integrator;

  948.         /** Initial event handlers list. */
  949.         private final List<EventHandlerConfiguration> eventHandlersConfigurations;

  950.         /** Initial step handlers list. */
  951.         private final List<ODEStepHandler> stepHandlers;

  952.         /** Simple constructor.
  953.          * @param integrator wrapped integrator
  954.          */
  955.         IntegratorResetter(final ODEIntegrator integrator) {
  956.             this.integrator                  = integrator;
  957.             this.eventHandlersConfigurations = new ArrayList<>(integrator.getEventHandlersConfigurations());
  958.             this.stepHandlers                = new ArrayList<>(integrator.getStepHandlers());
  959.         }

  960.         /** {@inheritDoc}
  961.          * <p>
  962.          * Reset event handlers and step handlers back to the initial list
  963.          * </p>
  964.          */
  965.         @Override
  966.         public void close() {

  967.             // reset event handlers
  968.             integrator.clearEventHandlers();
  969.             eventHandlersConfigurations.forEach(c -> integrator.addEventHandler(c.getEventHandler(),
  970.                                                                                 c.getMaxCheckInterval(),
  971.                                                                                 c.getConvergence(),
  972.                                                                                 c.getMaxIterationCount(),
  973.                                                                                 c.getSolver()));

  974.             // reset step handlers
  975.             integrator.clearStepHandlers();
  976.             stepHandlers.forEach(stepHandler -> integrator.addStepHandler(stepHandler));

  977.         }

  978.     }

  979. }