AbstractIntegratedPropagator.java

  1. /* Copyright 2002-2024 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.propagation.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.analysis.UnivariateFunction;
  28. import org.hipparchus.analysis.solvers.BracketedUnivariateSolver;
  29. import org.hipparchus.analysis.solvers.BracketingNthOrderBrentSolver;
  30. import org.hipparchus.exception.MathRuntimeException;
  31. import org.hipparchus.ode.DenseOutputModel;
  32. import org.hipparchus.ode.ExpandableODE;
  33. import org.hipparchus.ode.ODEIntegrator;
  34. import org.hipparchus.ode.ODEState;
  35. import org.hipparchus.ode.ODEStateAndDerivative;
  36. import org.hipparchus.ode.OrdinaryDifferentialEquation;
  37. import org.hipparchus.ode.SecondaryODE;
  38. import org.hipparchus.ode.events.Action;
  39. import org.hipparchus.ode.events.AdaptableInterval;
  40. import org.hipparchus.ode.events.ODEEventDetector;
  41. import org.hipparchus.ode.events.ODEEventHandler;
  42. import org.hipparchus.ode.sampling.AbstractODEStateInterpolator;
  43. import org.hipparchus.ode.sampling.ODEStateInterpolator;
  44. import org.hipparchus.ode.sampling.ODEStepHandler;
  45. import org.hipparchus.util.Precision;
  46. import org.orekit.attitudes.AttitudeProvider;
  47. import org.orekit.errors.OrekitException;
  48. import org.orekit.errors.OrekitInternalError;
  49. import org.orekit.errors.OrekitMessages;
  50. import org.orekit.frames.Frame;
  51. import org.orekit.orbits.OrbitType;
  52. import org.orekit.orbits.PositionAngleType;
  53. import org.orekit.propagation.AbstractPropagator;
  54. import org.orekit.propagation.BoundedPropagator;
  55. import org.orekit.propagation.EphemerisGenerator;
  56. import org.orekit.propagation.PropagationType;
  57. import org.orekit.propagation.SpacecraftState;
  58. import org.orekit.propagation.events.EventDetector;
  59. import org.orekit.propagation.events.handlers.EventHandler;
  60. import org.orekit.propagation.sampling.OrekitStepHandler;
  61. import org.orekit.propagation.sampling.OrekitStepInterpolator;
  62. import org.orekit.time.AbsoluteDate;
  63. import org.orekit.utils.DoubleArrayDictionary;


  64. /** Common handling of {@link org.orekit.propagation.Propagator Propagator}
  65.  *  methods for both numerical and semi-analytical propagators.
  66.  *  @author Luc Maisonobe
  67.  */
  68. public abstract class AbstractIntegratedPropagator extends AbstractPropagator {

  69.     /** Internal name used for complete secondary state dimension.
  70.      * @since 11.1
  71.      */
  72.     private static final String SECONDARY_DIMENSION = "Orekit-secondary-dimension";

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

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

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

  79.     /** Offsets of secondary states managed by {@link AdditionalDerivativesProvider}.
  80.      * @since 11.1
  81.      */
  82.     private final Map<String, Integer> secondaryOffsets;

  83.     /** Additional derivatives providers.
  84.      * @since 11.1
  85.      */
  86.     private final List<AdditionalDerivativesProvider> additionalDerivativesProviders;

  87.     /** Map of secondary equation offset in main
  88.     /** Counter for differential equations calls. */
  89.     private int calls;

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

  92.     /**
  93.      * Attitude provider when evaluating derivatives. Can be a frozen one for performance.
  94.      * @since 12.1
  95.      */
  96.     private AttitudeProvider attitudeProviderForDerivatives;

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

  99.     /** Type of orbit to output (mean or osculating) <br/>
  100.      * <p>
  101.      * This is used only in the case of semi-analytical propagators where there is a clear separation between
  102.      * mean and short periodic elements. It is ignored by the Numerical propagator.
  103.      * </p>
  104.      */
  105.     private final PropagationType propagationType;

  106.     /** Build a new instance.
  107.      * @param integrator numerical integrator to use for propagation.
  108.      * @param propagationType type of orbit to output (mean or osculating).
  109.      */
  110.     protected AbstractIntegratedPropagator(final ODEIntegrator integrator, final PropagationType propagationType) {
  111.         detectors                      = new ArrayList<>();
  112.         ephemerisGenerators            = new ArrayList<>();
  113.         additionalDerivativesProviders = new ArrayList<>();
  114.         this.secondaryOffsets          = new HashMap<>();
  115.         this.integrator                = integrator;
  116.         this.propagationType           = propagationType;
  117.         this.resetAtEnd                = true;
  118.     }

  119.     /** Allow/disallow resetting the initial state at end of propagation.
  120.      * <p>
  121.      * By default, at the end of the propagation, the propagator resets the initial state
  122.      * to the final state, thus allowing a new propagation to be started from there without
  123.      * recomputing the part already performed. Calling this method with {@code resetAtEnd} set
  124.      * to false changes prevents such reset.
  125.      * </p>
  126.      * @param resetAtEnd if true, at end of each propagation, the {@link
  127.      * #getInitialState() initial state} will be reset to the final state of
  128.      * the propagation, otherwise the initial state will be preserved
  129.      * @since 9.0
  130.      */
  131.     public void setResetAtEnd(final boolean resetAtEnd) {
  132.         this.resetAtEnd = resetAtEnd;
  133.     }

  134.     /** Getter for the resetting flag regarding initial state.
  135.      * @return resetting flag
  136.      * @since 12.0
  137.      */
  138.     public boolean getResetAtEnd() {
  139.         return this.resetAtEnd;
  140.     }

  141.     /**
  142.      * Method called when initializing the attitude provider used when evaluating derivatives.
  143.      * @return attitude provider for derivatives
  144.      */
  145.     protected AttitudeProvider initializeAttitudeProviderForDerivatives() {
  146.         return getAttitudeProvider();
  147.     }

  148.     /** Initialize the mapper. */
  149.     protected void initMapper() {
  150.         stateMapper = createMapper(null, Double.NaN, null, null, null, null);
  151.     }

  152.     /** Get the integrator's name.
  153.      * @return name of underlying integrator
  154.      * @since 12.0
  155.      */
  156.     public String getIntegratorName() {
  157.         return integrator.getName();
  158.     }

  159.     /**  {@inheritDoc} */
  160.     @Override
  161.     public void setAttitudeProvider(final AttitudeProvider attitudeProvider) {
  162.         super.setAttitudeProvider(attitudeProvider);
  163.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  164.                                    stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
  165.                                    attitudeProvider, stateMapper.getFrame());
  166.     }

  167.     /** Set propagation orbit type.
  168.      * @param orbitType orbit type to use for propagation, null for
  169.      * propagating using {@link org.orekit.utils.AbsolutePVCoordinates AbsolutePVCoordinates}
  170.      * rather than {@link org.orekit.orbits Orbit}
  171.      */
  172.     protected void setOrbitType(final OrbitType orbitType) {
  173.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  174.                                    orbitType, stateMapper.getPositionAngleType(),
  175.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  176.     }

  177.     /** Get propagation parameter type.
  178.      * @return orbit type used for propagation, null for
  179.      * propagating using {@link org.orekit.utils.AbsolutePVCoordinates AbsolutePVCoordinates}
  180.      * rather than {@link org.orekit.orbits Orbit}
  181.      */
  182.     protected OrbitType getOrbitType() {
  183.         return stateMapper.getOrbitType();
  184.     }

  185.     /** Get the propagation type.
  186.      * @return propagation type.
  187.      * @since 11.1
  188.      */
  189.     public PropagationType getPropagationType() {
  190.         return propagationType;
  191.     }

  192.     /** Set position angle type.
  193.      * <p>
  194.      * The position parameter type is meaningful only if {@link
  195.      * #getOrbitType() propagation orbit type}
  196.      * support it. As an example, it is not meaningful for propagation
  197.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  198.      * </p>
  199.      * @param positionAngleType angle type to use for propagation
  200.      */
  201.     protected void setPositionAngleType(final PositionAngleType positionAngleType) {
  202.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  203.                                    stateMapper.getOrbitType(), positionAngleType,
  204.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  205.     }

  206.     /** Get propagation parameter type.
  207.      * @return angle type to use for propagation
  208.      */
  209.     protected PositionAngleType getPositionAngleType() {
  210.         return stateMapper.getPositionAngleType();
  211.     }

  212.     /** Set the central attraction coefficient μ.
  213.      * @param mu central attraction coefficient (m³/s²)
  214.      */
  215.     public void setMu(final double mu) {
  216.         stateMapper = createMapper(stateMapper.getReferenceDate(), mu,
  217.                                    stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
  218.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  219.     }

  220.     /** Get the central attraction coefficient μ.
  221.      * @return mu central attraction coefficient (m³/s²)
  222.      * @see #setMu(double)
  223.      */
  224.     public double getMu() {
  225.         return stateMapper.getMu();
  226.     }

  227.     /** Get the number of calls to the differential equations computation method.
  228.      * <p>The number of calls is reset each time the {@link #propagate(AbsoluteDate)}
  229.      * method is called.</p>
  230.      * @return number of calls to the differential equations computation method
  231.      */
  232.     public int getCalls() {
  233.         return calls;
  234.     }

  235.     /** {@inheritDoc} */
  236.     @Override
  237.     public boolean isAdditionalStateManaged(final String name) {

  238.         // first look at already integrated states
  239.         if (super.isAdditionalStateManaged(name)) {
  240.             return true;
  241.         }

  242.         // then look at states we integrate ourselves
  243.         for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  244.             if (provider.getName().equals(name)) {
  245.                 return true;
  246.             }
  247.         }

  248.         return false;
  249.     }

  250.     /** {@inheritDoc} */
  251.     @Override
  252.     public String[] getManagedAdditionalStates() {
  253.         final String[] alreadyIntegrated = super.getManagedAdditionalStates();
  254.         final String[] managed = new String[alreadyIntegrated.length + additionalDerivativesProviders.size()];
  255.         System.arraycopy(alreadyIntegrated, 0, managed, 0, alreadyIntegrated.length);
  256.         for (int i = 0; i < additionalDerivativesProviders.size(); ++i) {
  257.             managed[i + alreadyIntegrated.length] = additionalDerivativesProviders.get(i).getName();
  258.         }
  259.         return managed;
  260.     }

  261.     /** Add a provider for user-specified state derivatives to be integrated along with the orbit propagation.
  262.      * @param provider provider for additional derivatives
  263.      * @see #addAdditionalStateProvider(org.orekit.propagation.AdditionalStateProvider)
  264.      * @since 11.1
  265.      */
  266.     public void addAdditionalDerivativesProvider(final AdditionalDerivativesProvider provider) {

  267.         // check if the name is already used
  268.         if (isAdditionalStateManaged(provider.getName())) {
  269.             // these derivatives are already registered, complain
  270.             throw new OrekitException(OrekitMessages.ADDITIONAL_STATE_NAME_ALREADY_IN_USE,
  271.                                       provider.getName());
  272.         }

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

  275.         secondaryOffsets.clear();

  276.     }

  277.     /** Get an unmodifiable list of providers for additional derivatives.
  278.      * @return providers for the additional derivatives
  279.      * @since 11.1
  280.      */
  281.     public List<AdditionalDerivativesProvider> getAdditionalDerivativesProviders() {
  282.         return Collections.unmodifiableList(additionalDerivativesProviders);
  283.     }

  284.     /** {@inheritDoc} */
  285.     public void addEventDetector(final EventDetector detector) {
  286.         detectors.add(detector);
  287.     }

  288.     /** {@inheritDoc} */
  289.     public Collection<EventDetector> getEventsDetectors() {
  290.         return Collections.unmodifiableCollection(detectors);
  291.     }

  292.     /** {@inheritDoc} */
  293.     public void clearEventsDetectors() {
  294.         detectors.clear();
  295.     }

  296.     /** Set up all user defined event detectors.
  297.      */
  298.     protected void setUpUserEventDetectors() {
  299.         for (final EventDetector detector : detectors) {
  300.             setUpEventDetector(integrator, detector);
  301.         }
  302.     }

  303.     /** Wrap an Orekit event detector and register it to the integrator.
  304.      * @param integ integrator into which event detector should be registered
  305.      * @param detector event detector to wrap
  306.      */
  307.     protected void setUpEventDetector(final ODEIntegrator integ, final EventDetector detector) {
  308.         integ.addEventDetector(new AdaptedEventDetector(detector));
  309.     }

  310.     /** {@inheritDoc} */
  311.     @Override
  312.     public EphemerisGenerator getEphemerisGenerator() {
  313.         final StoringStepHandler storingHandler = new StoringStepHandler();
  314.         ephemerisGenerators.add(storingHandler);
  315.         return storingHandler;
  316.     }

  317.     /** Create a mapper between raw double components and spacecraft state.
  318.     /** Simple constructor.
  319.      * <p>
  320.      * The position parameter type is meaningful only if {@link
  321.      * #getOrbitType() propagation orbit type}
  322.      * support it. As an example, it is not meaningful for propagation
  323.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  324.      * </p>
  325.      * @param referenceDate reference date
  326.      * @param mu central attraction coefficient (m³/s²)
  327.      * @param orbitType orbit type to use for mapping
  328.      * @param positionAngleType angle type to use for propagation
  329.      * @param attitudeProvider attitude provider
  330.      * @param frame inertial frame
  331.      * @return new mapper
  332.      */
  333.     protected abstract StateMapper createMapper(AbsoluteDate referenceDate, double mu,
  334.                                                 OrbitType orbitType, PositionAngleType positionAngleType,
  335.                                                 AttitudeProvider attitudeProvider, Frame frame);

  336.     /** Get the differential equations to integrate (for main state only).
  337.      * @param integ numerical integrator to use for propagation.
  338.      * @return differential equations for main state
  339.      */
  340.     protected abstract MainStateEquations getMainStateEquations(ODEIntegrator integ);

  341.     /** {@inheritDoc} */
  342.     @Override
  343.     public SpacecraftState propagate(final AbsoluteDate target) {
  344.         if (getStartDate() == null) {
  345.             if (getInitialState() == null) {
  346.                 throw new OrekitException(OrekitMessages.INITIAL_STATE_NOT_SPECIFIED_FOR_ORBIT_PROPAGATION);
  347.             }
  348.             setStartDate(getInitialState().getDate());
  349.         }
  350.         return propagate(getStartDate(), target);
  351.     }

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

  354.         if (getInitialState() == null) {
  355.             throw new OrekitException(OrekitMessages.INITIAL_STATE_NOT_SPECIFIED_FOR_ORBIT_PROPAGATION);
  356.         }

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

  359.             // prepare handling of STM and Jacobian matrices
  360.             setUpStmAndJacobianGenerators();

  361.             // Initialize additional states
  362.             initializeAdditionalStates(tEnd);

  363.             if (!tStart.equals(getInitialState().getDate())) {
  364.                 // if propagation start date is not initial date,
  365.                 // propagate from initial to start date without event detection
  366.                 try (IntegratorResetter startResetter = new IntegratorResetter(integrator)) {
  367.                     integrateDynamics(tStart, true);
  368.                 }
  369.             }

  370.             // set up events added by user
  371.             setUpUserEventDetectors();

  372.             // set up step handlers
  373.             for (final OrekitStepHandler handler : getMultiplexer().getHandlers()) {
  374.                 integrator.addStepHandler(new AdaptedStepHandler(handler));
  375.             }
  376.             for (final StoringStepHandler generator : ephemerisGenerators) {
  377.                 generator.setEndDate(tEnd);
  378.                 integrator.addStepHandler(generator);
  379.             }

  380.             // propagate from start date to end date with event detection
  381.             final SpacecraftState finalState = integrateDynamics(tEnd, false);

  382.             // Finalize event detectors
  383.             getEventsDetectors().forEach(detector -> detector.finish(finalState));

  384.             return finalState;
  385.         }

  386.     }

  387.     /** Reset initial state with a given propagation type.
  388.      *
  389.      * <p> By default this method returns the same as {@link #resetInitialState(SpacecraftState)}
  390.      * <p> Its purpose is mostly to be derived in DSSTPropagator
  391.      *
  392.      * @param state new initial state to consider
  393.      * @param stateType type of the new state (mean or osculating)
  394.      * @since 12.1.3
  395.      */
  396.     public void resetInitialState(final SpacecraftState state, final PropagationType stateType) {
  397.         // Default behavior, do not take propagation type into account
  398.         resetInitialState(state);
  399.     }

  400.     /** Set up State Transition Matrix and Jacobian matrix handling.
  401.      * @since 11.1
  402.      */
  403.     protected void setUpStmAndJacobianGenerators() {
  404.         // nothing to do by default
  405.     }

  406.     /** Propagation with or without event detection.
  407.      * @param tEnd target date to which orbit should be propagated
  408.      * @param forceResetAtEnd flag to force resetting state and date after integration
  409.      * @return state at end of propagation
  410.      */
  411.     private SpacecraftState integrateDynamics(final AbsoluteDate tEnd, final boolean forceResetAtEnd) {
  412.         try {

  413.             initializePropagation();

  414.             if (getInitialState().getDate().equals(tEnd)) {
  415.                 // don't extrapolate
  416.                 return getInitialState();
  417.             }

  418.             // space dynamics view
  419.             stateMapper = createMapper(getInitialState().getDate(), stateMapper.getMu(),
  420.                                        stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
  421.                                        stateMapper.getAttitudeProvider(), getInitialState().getFrame());
  422.             attitudeProviderForDerivatives = initializeAttitudeProviderForDerivatives();

  423.             if (Double.isNaN(getMu())) {
  424.                 setMu(getInitialState().getMu());
  425.             }

  426.             if (getInitialState().getMass() <= 0.0) {
  427.                 throw new OrekitException(OrekitMessages.NOT_POSITIVE_SPACECRAFT_MASS,
  428.                                           getInitialState().getMass());
  429.             }

  430.             // convert space flight dynamics API to math API
  431.             final SpacecraftState initialIntegrationState = getInitialIntegrationState();
  432.             final ODEState mathInitialState = createInitialState(initialIntegrationState);
  433.             final ExpandableODE mathODE = createODE(integrator);

  434.             // mathematical integration
  435.             final ODEStateAndDerivative mathFinalState;
  436.             beforeIntegration(initialIntegrationState, tEnd);
  437.             mathFinalState = integrator.integrate(mathODE, mathInitialState,
  438.                                                   tEnd.durationFrom(getInitialState().getDate()));
  439.             afterIntegration();

  440.             // get final state
  441.             SpacecraftState finalState =
  442.                             stateMapper.mapArrayToState(stateMapper.mapDoubleToDate(mathFinalState.getTime(),
  443.                                                                                     tEnd),
  444.                                                         mathFinalState.getPrimaryState(),
  445.                                                         mathFinalState.getPrimaryDerivative(),
  446.                                                         propagationType);

  447.             finalState = updateAdditionalStatesAndDerivatives(finalState, mathFinalState);

  448.             if (resetAtEnd || forceResetAtEnd) {
  449.                 resetInitialState(finalState, propagationType);
  450.                 setStartDate(finalState.getDate());
  451.             }

  452.             return finalState;

  453.         } catch (MathRuntimeException mre) {
  454.             throw OrekitException.unwrap(mre);
  455.         }
  456.     }

  457.     /**
  458.      * Returns an updated version of the inputted state with additional states, including
  459.      * from derivatives providers.
  460.      * @param originalState input state
  461.      * @param os ODE state and derivative
  462.      * @return new state
  463.      * @since 12.1
  464.      */
  465.     private SpacecraftState updateAdditionalStatesAndDerivatives(final SpacecraftState originalState,
  466.                                                                  final ODEStateAndDerivative os) {
  467.         SpacecraftState updatedState = originalState;
  468.         if (os.getNumberOfSecondaryStates() > 0) {
  469.             final double[] secondary           = os.getSecondaryState(1);
  470.             final double[] secondaryDerivative = os.getSecondaryDerivative(1);
  471.             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  472.                 final String name      = provider.getName();
  473.                 final int    offset    = secondaryOffsets.get(name);
  474.                 final int    dimension = provider.getDimension();
  475.                 updatedState = updatedState.addAdditionalState(name, Arrays.copyOfRange(secondary, offset, offset + dimension));
  476.                 updatedState = updatedState.addAdditionalStateDerivative(name, Arrays.copyOfRange(secondaryDerivative, offset, offset + dimension));
  477.             }
  478.         }
  479.         return updateAdditionalStates(updatedState);
  480.     }

  481.     /** Get the initial state for integration.
  482.      * @return initial state for integration
  483.      */
  484.     protected SpacecraftState getInitialIntegrationState() {
  485.         return getInitialState();
  486.     }

  487.     /** Create an initial state.
  488.      * @param initialState initial state in flight dynamics world
  489.      * @return initial state in mathematics world
  490.      */
  491.     private ODEState createInitialState(final SpacecraftState initialState) {

  492.         // retrieve initial state
  493.         final double[] primary = new double[getBasicDimension()];
  494.         stateMapper.mapStateToArray(initialState, primary, null);

  495.         if (secondaryOffsets.isEmpty()) {
  496.             // compute dimension of the secondary state
  497.             int offset = 0;
  498.             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  499.                 secondaryOffsets.put(provider.getName(), offset);
  500.                 offset += provider.getDimension();
  501.             }
  502.             secondaryOffsets.put(SECONDARY_DIMENSION, offset);
  503.         }

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

  505.     }

  506.     /** Create secondary state.
  507.      * @param state spacecraft state
  508.      * @return secondary state
  509.      * @since 11.1
  510.      */
  511.     private double[][] secondary(final SpacecraftState state) {

  512.         if (secondaryOffsets.isEmpty()) {
  513.             return null;
  514.         }

  515.         final double[][] secondary = new double[1][secondaryOffsets.get(SECONDARY_DIMENSION)];
  516.         for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  517.             final String   name       = provider.getName();
  518.             final int      offset     = secondaryOffsets.get(name);
  519.             final double[] additional = state.getAdditionalState(name);
  520.             System.arraycopy(additional, 0, secondary[0], offset, additional.length);
  521.         }

  522.         return secondary;

  523.     }

  524.     /** Create secondary state derivative.
  525.      * @param state spacecraft state
  526.      * @return secondary state derivative
  527.      * @since 11.1
  528.      */
  529.     private double[][] secondaryDerivative(final SpacecraftState state) {

  530.         if (secondaryOffsets.isEmpty()) {
  531.             return null;
  532.         }

  533.         final double[][] secondaryDerivative = new double[1][secondaryOffsets.get(SECONDARY_DIMENSION)];
  534.         for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  535.             final String   name       = provider.getName();
  536.             final int      offset     = secondaryOffsets.get(name);
  537.             final double[] additionalDerivative = state.getAdditionalStateDerivative(name);
  538.             System.arraycopy(additionalDerivative, 0, secondaryDerivative[0], offset, additionalDerivative.length);
  539.         }

  540.         return secondaryDerivative;

  541.     }

  542.     /** Create an ODE with all equations.
  543.      * @param integ numerical integrator to use for propagation.
  544.      * @return a new ode
  545.      */
  546.     private ExpandableODE createODE(final ODEIntegrator integ) {

  547.         final ExpandableODE ode =
  548.                 new ExpandableODE(new ConvertedMainStateEquations(getMainStateEquations(integ)));

  549.         // secondary part of the ODE
  550.         if (!additionalDerivativesProviders.isEmpty()) {
  551.             ode.addSecondaryEquations(new ConvertedSecondaryStateEquations());
  552.         }

  553.         return ode;

  554.     }

  555.     /** Method called just before integration.
  556.      * <p>
  557.      * The default implementation does nothing, it may be specialized in subclasses.
  558.      * </p>
  559.      * @param initialState initial state
  560.      * @param tEnd target date at which state should be propagated
  561.      */
  562.     protected void beforeIntegration(final SpacecraftState initialState,
  563.                                      final AbsoluteDate tEnd) {
  564.         // do nothing by default
  565.     }

  566.     /** Method called just after integration.
  567.      * <p>
  568.      * The default implementation does nothing, it may be specialized in subclasses.
  569.      * </p>
  570.      */
  571.     protected void afterIntegration() {
  572.         // do nothing by default
  573.     }

  574.     /** Get state vector dimension without additional parameters.
  575.      * @return state vector dimension without additional parameters.
  576.      */
  577.     public int getBasicDimension() {
  578.         return 7;
  579.     }

  580.     /** Get the integrator used by the propagator.
  581.      * @return the integrator.
  582.      */
  583.     protected ODEIntegrator getIntegrator() {
  584.         return integrator;
  585.     }

  586.     /** Convert a state from mathematical world to space flight dynamics world.
  587.      * @param os mathematical state
  588.      * @return space flight dynamics state
  589.      */
  590.     private SpacecraftState convert(final ODEStateAndDerivative os) {

  591.         final SpacecraftState s = stateMapper.mapArrayToState(os.getTime(), os.getPrimaryState(),
  592.             os.getPrimaryDerivative(), propagationType);
  593.         return updateAdditionalStatesAndDerivatives(s, os);
  594.     }

  595.     /** Convert a state from space flight dynamics world to mathematical world.
  596.      * @param state space flight dynamics state
  597.      * @return mathematical state
  598.      */
  599.     private ODEStateAndDerivative convert(final SpacecraftState state) {

  600.         // retrieve initial state
  601.         final double[] primary    = new double[getBasicDimension()];
  602.         final double[] primaryDot = new double[getBasicDimension()];
  603.         stateMapper.mapStateToArray(state, primary, primaryDot);

  604.         // secondary part of the ODE
  605.         final double[][] secondary           = secondary(state);
  606.         final double[][] secondaryDerivative = secondaryDerivative(state);

  607.         return new ODEStateAndDerivative(stateMapper.mapDateToDouble(state.getDate()),
  608.                                          primary, primaryDot,
  609.                                          secondary, secondaryDerivative);

  610.     }

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

  613.         /**
  614.          * Initialize the equations at the start of propagation. This method will be
  615.          * called before any calls to {@link #computeDerivatives(SpacecraftState)}.
  616.          *
  617.          * <p> The default implementation of this method does nothing.
  618.          *
  619.          * @param initialState initial state information at the start of propagation.
  620.          * @param target       date of propagation. Not equal to {@code
  621.          *                     initialState.getDate()}.
  622.          */
  623.         default void init(final SpacecraftState initialState, final AbsoluteDate target) {
  624.         }

  625.         /** Compute differential equations for main state.
  626.          * @param state current state
  627.          * @return derivatives of main state
  628.          */
  629.         double[] computeDerivatives(SpacecraftState state);

  630.     }

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

  633.         /** Main state equations. */
  634.         private final MainStateEquations main;

  635.         /** Simple constructor.
  636.          * @param main main state equations
  637.          */
  638.         ConvertedMainStateEquations(final MainStateEquations main) {
  639.             this.main = main;
  640.             calls = 0;
  641.         }

  642.         /** {@inheritDoc} */
  643.         public int getDimension() {
  644.             return getBasicDimension();
  645.         }

  646.         @Override
  647.         public void init(final double t0, final double[] y0, final double finalTime) {
  648.             // update space dynamics view
  649.             SpacecraftState initialState = stateMapper.mapArrayToState(t0, y0, null, PropagationType.MEAN);
  650.             initialState = updateAdditionalStates(initialState);
  651.             initialState = updateStatesFromAdditionalDerivativesIfKnown(initialState);
  652.             final AbsoluteDate target = stateMapper.mapDoubleToDate(finalTime);
  653.             main.init(initialState, target);
  654.             attitudeProviderForDerivatives = initializeAttitudeProviderForDerivatives();
  655.         }

  656.         /**
  657.          * Returns an updated version of the inputted state, with additional states from
  658.          * derivatives providers as given in the stored initial state.
  659.          * @param originalState input state
  660.          * @return new state
  661.          * @since 12.1
  662.          */
  663.         private SpacecraftState updateStatesFromAdditionalDerivativesIfKnown(final SpacecraftState originalState) {
  664.             SpacecraftState updatedState = originalState;
  665.             final SpacecraftState storedInitialState = getInitialState();
  666.             final double originalTime = stateMapper.mapDateToDouble(originalState.getDate());
  667.             if (storedInitialState != null && stateMapper.mapDateToDouble(storedInitialState.getDate()) == originalTime) {
  668.                 for (final AdditionalDerivativesProvider provider: additionalDerivativesProviders) {
  669.                     final String name = provider.getName();
  670.                     final double[] value = storedInitialState.getAdditionalState(name);
  671.                     updatedState = updatedState.addAdditionalState(name, value);
  672.                 }
  673.             }
  674.             return updatedState;
  675.         }

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

  678.             // increment calls counter
  679.             ++calls;

  680.             // update space dynamics view
  681.             stateMapper.setAttitudeProvider(attitudeProviderForDerivatives);
  682.             SpacecraftState currentState = stateMapper.mapArrayToState(t, y, null, PropagationType.MEAN);
  683.             stateMapper.setAttitudeProvider(getAttitudeProvider());

  684.             currentState = updateAdditionalStates(currentState);
  685.             // compute main state differentials
  686.             return main.computeDerivatives(currentState);

  687.         }

  688.     }

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

  691.         /** Dimension of the combined additional states. */
  692.         private final int combinedDimension;

  693.         /** Simple constructor.
  694.           */
  695.         ConvertedSecondaryStateEquations() {
  696.             this.combinedDimension = secondaryOffsets.get(SECONDARY_DIMENSION);
  697.         }

  698.         /** {@inheritDoc} */
  699.         @Override
  700.         public int getDimension() {
  701.             return combinedDimension;
  702.         }

  703.         /** {@inheritDoc} */
  704.         @Override
  705.         public void init(final double t0, final double[] primary0,
  706.                          final double[] secondary0, final double finalTime) {
  707.             // update space dynamics view
  708.             final SpacecraftState initialState = convert(t0, primary0, null, secondary0);

  709.             final AbsoluteDate target = stateMapper.mapDoubleToDate(finalTime);
  710.             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  711.                 provider.init(initialState, target);
  712.             }

  713.         }

  714.         /** {@inheritDoc} */
  715.         @Override
  716.         public double[] computeDerivatives(final double t, final double[] primary,
  717.                                            final double[] primaryDot, final double[] secondary) {

  718.             // update space dynamics view
  719.             // the integrable generators generate method will be called here,
  720.             // according to the generators yield order
  721.             SpacecraftState updated = convert(t, primary, primaryDot, secondary);

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

  724.             // gather the derivatives from all additional equations, taking care of dependencies
  725.             final double[] secondaryDot = new double[combinedDimension];
  726.             int yieldCount = 0;
  727.             while (!pending.isEmpty()) {
  728.                 final AdditionalDerivativesProvider provider = pending.remove();
  729.                 if (provider.yields(updated)) {
  730.                     // this provider has to wait for another one,
  731.                     // we put it again in the pending queue
  732.                     pending.add(provider);
  733.                     if (++yieldCount >= pending.size()) {
  734.                         // all pending providers yielded!, they probably need data not yet initialized
  735.                         // we let the propagation proceed, if these data are really needed right now
  736.                         // an appropriate exception will be triggered when caller tries to access them
  737.                         break;
  738.                     }
  739.                 } else {
  740.                     // we can use these equations right now
  741.                     final String              name           = provider.getName();
  742.                     final int                 offset         = secondaryOffsets.get(name);
  743.                     final int                 dimension      = provider.getDimension();
  744.                     final CombinedDerivatives derivatives    = provider.combinedDerivatives(updated);
  745.                     final double[]            additionalPart = derivatives.getAdditionalDerivatives();
  746.                     final double[]            mainPart       = derivatives.getMainStateDerivativesIncrements();
  747.                     System.arraycopy(additionalPart, 0, secondaryDot, offset, dimension);
  748.                     updated = updated.addAdditionalStateDerivative(name, additionalPart);
  749.                     if (mainPart != null) {
  750.                         // this equation does change the main state derivatives
  751.                         for (int i = 0; i < mainPart.length; ++i) {
  752.                             primaryDot[i] += mainPart[i];
  753.                         }
  754.                     }
  755.                     yieldCount = 0;
  756.                 }
  757.             }

  758.             return secondaryDot;

  759.         }

  760.         /** Convert mathematical view to space view.
  761.          * @param t current value of the independent <I>time</I> variable
  762.          * @param primary array containing the current value of the primary state vector
  763.          * @param primaryDot array containing the derivative of the primary state vector
  764.          * @param secondary array containing the current value of the secondary state vector
  765.          * @return space view of the state
  766.          */
  767.         private SpacecraftState convert(final double t, final double[] primary,
  768.                                         final double[] primaryDot, final double[] secondary) {

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

  770.             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  771.                 final String name      = provider.getName();
  772.                 final int    offset    = secondaryOffsets.get(name);
  773.                 final int    dimension = provider.getDimension();
  774.                 initialState = initialState.addAdditionalState(name, Arrays.copyOfRange(secondary, offset, offset + dimension));
  775.             }

  776.             return updateAdditionalStates(initialState);

  777.         }

  778.     }

  779.     /** Adapt an {@link org.orekit.propagation.events.EventDetector}
  780.      * to Hipparchus {@link org.hipparchus.ode.events.ODEEventDetector} interface.
  781.      * @author Fabien Maussion
  782.      */
  783.     private class AdaptedEventDetector implements ODEEventDetector {

  784.         /** Underlying event detector. */
  785.         private final EventDetector detector;

  786.         /** Underlying event handler.
  787.          * @since 12.0
  788.          */
  789.         private final EventHandler handler;

  790.         /** Time of the previous call to g. */
  791.         private double lastT;

  792.         /** Value from the previous call to g. */
  793.         private double lastG;

  794.         /** Build a wrapped event detector.
  795.          * @param detector event detector to wrap
  796.         */
  797.         AdaptedEventDetector(final EventDetector detector) {
  798.             this.detector = detector;
  799.             this.handler  = detector.getHandler();
  800.             this.lastT    = Double.NaN;
  801.             this.lastG    = Double.NaN;
  802.         }

  803.         /** {@inheritDoc} */
  804.         @Override
  805.         public AdaptableInterval getMaxCheckInterval() {
  806.             return s -> detector.getMaxCheckInterval().currentInterval(convert(s));
  807.         }

  808.         /** {@inheritDoc} */
  809.         @Override
  810.         public int getMaxIterationCount() {
  811.             return detector.getMaxIterationCount();
  812.         }

  813.         /** {@inheritDoc} */
  814.         @Override
  815.         public BracketedUnivariateSolver<UnivariateFunction> getSolver() {
  816.             return new BracketingNthOrderBrentSolver(0, detector.getThreshold(), 0, 5);
  817.         }

  818.         /** {@inheritDoc} */
  819.         @Override
  820.         public void init(final ODEStateAndDerivative s0, final double t) {
  821.             detector.init(convert(s0), stateMapper.mapDoubleToDate(t));
  822.             this.lastT = Double.NaN;
  823.             this.lastG = Double.NaN;
  824.         }

  825.         /** {@inheritDoc} */
  826.         public double g(final ODEStateAndDerivative s) {
  827.             if (!Precision.equals(lastT, s.getTime(), 0)) {
  828.                 lastT = s.getTime();
  829.                 lastG = detector.g(convert(s));
  830.             }
  831.             return lastG;
  832.         }

  833.         /** {@inheritDoc} */
  834.         public ODEEventHandler getHandler() {

  835.             return new ODEEventHandler() {

  836.                 /** {@inheritDoc} */
  837.                 public Action eventOccurred(final ODEStateAndDerivative s, final ODEEventDetector d, final boolean increasing) {
  838.                     return handler.eventOccurred(convert(s), detector, increasing);
  839.                 }

  840.                 /** {@inheritDoc} */
  841.                 @Override
  842.                 public ODEState resetState(final ODEEventDetector d, final ODEStateAndDerivative s) {

  843.                     final SpacecraftState oldState = convert(s);
  844.                     final SpacecraftState newState = handler.resetState(detector, oldState);
  845.                     stateChanged(newState);

  846.                     // main part
  847.                     final double[] primary    = new double[s.getPrimaryStateDimension()];
  848.                     stateMapper.mapStateToArray(newState, primary, null);

  849.                     // secondary part
  850.                     final double[][] secondary = new double[1][secondaryOffsets.get(SECONDARY_DIMENSION)];
  851.                     for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  852.                         final String name      = provider.getName();
  853.                         final int    offset    = secondaryOffsets.get(name);
  854.                         final int    dimension = provider.getDimension();
  855.                         System.arraycopy(newState.getAdditionalState(name), 0, secondary[0], offset, dimension);
  856.                     }

  857.                     return new ODEState(newState.getDate().durationFrom(getStartDate()),
  858.                                         primary, secondary);

  859.                 }

  860.             };
  861.         }

  862.     }

  863.     /** Adapt an {@link org.orekit.propagation.sampling.OrekitStepHandler}
  864.      * to Hipparchus {@link ODEStepHandler} interface.
  865.      * @author Luc Maisonobe
  866.      */
  867.     private class AdaptedStepHandler implements ODEStepHandler {

  868.         /** Underlying handler. */
  869.         private final OrekitStepHandler handler;

  870.         /** Build an instance.
  871.          * @param handler underlying handler to wrap
  872.          */
  873.         AdaptedStepHandler(final OrekitStepHandler handler) {
  874.             this.handler = handler;
  875.         }

  876.         /** {@inheritDoc} */
  877.         @Override
  878.         public void init(final ODEStateAndDerivative s0, final double t) {
  879.             handler.init(convert(s0), stateMapper.mapDoubleToDate(t));
  880.         }

  881.         /** {@inheritDoc} */
  882.         @Override
  883.         public void handleStep(final ODEStateInterpolator interpolator) {
  884.             handler.handleStep(new AdaptedStepInterpolator(interpolator));
  885.         }

  886.         /** {@inheritDoc} */
  887.         @Override
  888.         public void finish(final ODEStateAndDerivative finalState) {
  889.             handler.finish(convert(finalState));
  890.         }

  891.     }

  892.     /** Adapt an Hipparchus {@link ODEStateInterpolator}
  893.      * to an orekit {@link OrekitStepInterpolator} interface.
  894.      * @author Luc Maisonobe
  895.      */
  896.     private class AdaptedStepInterpolator implements OrekitStepInterpolator {

  897.         /** Underlying raw rawInterpolator. */
  898.         private final ODEStateInterpolator mathInterpolator;

  899.         /** Simple constructor.
  900.          * @param mathInterpolator underlying raw interpolator
  901.          */
  902.         AdaptedStepInterpolator(final ODEStateInterpolator mathInterpolator) {
  903.             this.mathInterpolator = mathInterpolator;
  904.         }

  905.         /** {@inheritDoc}} */
  906.         @Override
  907.         public SpacecraftState getPreviousState() {
  908.             return convert(mathInterpolator.getPreviousState());
  909.         }

  910.         /** {@inheritDoc}} */
  911.         @Override
  912.         public boolean isPreviousStateInterpolated() {
  913.             return mathInterpolator.isPreviousStateInterpolated();
  914.         }

  915.         /** {@inheritDoc}} */
  916.         @Override
  917.         public SpacecraftState getCurrentState() {
  918.             return convert(mathInterpolator.getCurrentState());
  919.         }

  920.         /** {@inheritDoc}} */
  921.         @Override
  922.         public boolean isCurrentStateInterpolated() {
  923.             return mathInterpolator.isCurrentStateInterpolated();
  924.         }

  925.         /** {@inheritDoc}} */
  926.         @Override
  927.         public SpacecraftState getInterpolatedState(final AbsoluteDate date) {
  928.             return convert(mathInterpolator.getInterpolatedState(date.durationFrom(stateMapper.getReferenceDate())));
  929.         }

  930.         /** {@inheritDoc}} */
  931.         @Override
  932.         public boolean isForward() {
  933.             return mathInterpolator.isForward();
  934.         }

  935.         /** {@inheritDoc}} */
  936.         @Override
  937.         public AdaptedStepInterpolator restrictStep(final SpacecraftState newPreviousState,
  938.                                                     final SpacecraftState newCurrentState) {
  939.             try {
  940.                 final AbstractODEStateInterpolator aosi = (AbstractODEStateInterpolator) mathInterpolator;
  941.                 return new AdaptedStepInterpolator(aosi.restrictStep(convert(newPreviousState),
  942.                                                                      convert(newCurrentState)));
  943.             } catch (ClassCastException cce) {
  944.                 // this should never happen
  945.                 throw new OrekitInternalError(cce);
  946.             }
  947.         }

  948.     }

  949.     /** Specialized step handler storing interpolators for ephemeris generation.
  950.      * @since 11.0
  951.      */
  952.     private class StoringStepHandler implements ODEStepHandler, EphemerisGenerator {

  953.         /** Underlying raw mathematical model. */
  954.         private DenseOutputModel model;

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

  957.         /** Generated ephemeris. */
  958.         private BoundedPropagator ephemeris;

  959.         /** Last interpolator handled by the object.*/
  960.         private  ODEStateInterpolator lastInterpolator;

  961.         /** Set the end date.
  962.          * @param endDate end date
  963.          */
  964.         public void setEndDate(final AbsoluteDate endDate) {
  965.             this.endDate = endDate;
  966.         }

  967.         /** {@inheritDoc} */
  968.         @Override
  969.         public void init(final ODEStateAndDerivative s0, final double t) {

  970.             this.model = new DenseOutputModel();
  971.             model.init(s0, t);

  972.             // ephemeris will be generated when last step is processed
  973.             this.ephemeris = null;

  974.             this.lastInterpolator = null;

  975.         }

  976.         /** {@inheritDoc} */
  977.         @Override
  978.         public BoundedPropagator getGeneratedEphemeris() {
  979.             // Each time we try to get the ephemeris, rebuild it using the last data.
  980.             buildEphemeris();
  981.             return ephemeris;
  982.         }

  983.         /** {@inheritDoc} */
  984.         @Override
  985.         public void handleStep(final ODEStateInterpolator interpolator) {
  986.             model.handleStep(interpolator);
  987.             lastInterpolator = interpolator;
  988.         }

  989.         /** {@inheritDoc} */
  990.         @Override
  991.         public void finish(final ODEStateAndDerivative finalState) {
  992.             buildEphemeris();
  993.         }

  994.         /** Method used to produce ephemeris at a given time.
  995.          * Can be used at multiple times, updating the ephemeris to
  996.          * its last state.
  997.          */
  998.         private void buildEphemeris() {
  999.             // buildEphemeris was built in order to allow access to what was previously the finish method.
  1000.             // This now allows to call it through getGeneratedEphemeris, therefore through an external call,
  1001.             // which was not previously the case.

  1002.             // Update the model's finalTime with the last interpolator.
  1003.             model.finish(lastInterpolator.getCurrentState());

  1004.             // set up the boundary dates
  1005.             final double tI = model.getInitialTime();
  1006.             final double tF = model.getFinalTime();
  1007.             // tI is almost? always zero
  1008.             final AbsoluteDate startDate =
  1009.                             stateMapper.mapDoubleToDate(tI);
  1010.             final AbsoluteDate finalDate =
  1011.                             stateMapper.mapDoubleToDate(tF, this.endDate);
  1012.             final AbsoluteDate minDate;
  1013.             final AbsoluteDate maxDate;
  1014.             if (tF < tI) {
  1015.                 minDate = finalDate;
  1016.                 maxDate = startDate;
  1017.             } else {
  1018.                 minDate = startDate;
  1019.                 maxDate = finalDate;
  1020.             }

  1021.             // get the initial additional states that are not managed
  1022.             final DoubleArrayDictionary unmanaged = new DoubleArrayDictionary();
  1023.             for (final DoubleArrayDictionary.Entry initial : getInitialState().getAdditionalStatesValues().getData()) {
  1024.                 if (!isAdditionalStateManaged(initial.getKey())) {
  1025.                     // this additional state was in the initial state, but is unknown to the propagator
  1026.                     // we simply copy its initial value as is
  1027.                     unmanaged.put(initial.getKey(), initial.getValue());
  1028.                 }
  1029.             }

  1030.             // get the names of additional states managed by differential equations
  1031.             final String[] names      = new String[additionalDerivativesProviders.size()];
  1032.             final int[]    dimensions = new int[additionalDerivativesProviders.size()];
  1033.             for (int i = 0; i < names.length; ++i) {
  1034.                 names[i] = additionalDerivativesProviders.get(i).getName();
  1035.                 dimensions[i] = additionalDerivativesProviders.get(i).getDimension();
  1036.             }

  1037.             // create the ephemeris
  1038.             ephemeris = new IntegratedEphemeris(startDate, minDate, maxDate,
  1039.                                                 stateMapper, propagationType, model,
  1040.                                                 unmanaged, getAdditionalStateProviders(),
  1041.                                                 names, dimensions);

  1042.         }

  1043.     }

  1044.     /** Wrapper for resetting an integrator handlers.
  1045.      * <p>
  1046.      * This class is intended to be used in a try-with-resource statement.
  1047.      * If propagator-specific event handlers and step handlers are added to
  1048.      * the integrator in the try block, they will be removed automatically
  1049.      * when leaving the block, so the integrator only keeps its own handlers
  1050.      * between calls to {@link AbstractIntegratedPropagator#propagate(AbsoluteDate, AbsoluteDate).
  1051.      * </p>
  1052.      * @since 11.0
  1053.      */
  1054.     private static class IntegratorResetter implements AutoCloseable {

  1055.         /** Wrapped integrator. */
  1056.         private final ODEIntegrator integrator;

  1057.         /** Initial event detectors list. */
  1058.         private final List<ODEEventDetector> detectors;

  1059.         /** Initial step handlers list. */
  1060.         private final List<ODEStepHandler> stepHandlers;

  1061.         /** Simple constructor.
  1062.          * @param integrator wrapped integrator
  1063.          */
  1064.         IntegratorResetter(final ODEIntegrator integrator) {
  1065.             this.integrator   = integrator;
  1066.             this.detectors    = new ArrayList<>(integrator.getEventDetectors());
  1067.             this.stepHandlers = new ArrayList<>(integrator.getStepHandlers());
  1068.         }

  1069.         /** {@inheritDoc}
  1070.          * <p>
  1071.          * Reset event handlers and step handlers back to the initial list
  1072.          * </p>
  1073.          */
  1074.         @Override
  1075.         public void close() {

  1076.             // reset event handlers
  1077.             integrator.clearEventDetectors();
  1078.             detectors.forEach(integrator::addEventDetector);

  1079.             // reset step handlers
  1080.             integrator.clearStepHandlers();
  1081.             stepHandlers.forEach(integrator::addStepHandler);

  1082.         }

  1083.     }

  1084. }