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.             return finalState;

  383.         }

  384.     }

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

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

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

  411.             initializePropagation();

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

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

  421.             if (Double.isNaN(getMu())) {
  422.                 setMu(getInitialState().getMu());
  423.             }

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

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

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

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

  445.             finalState = updateAdditionalStatesAndDerivatives(finalState, mathFinalState);

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

  450.             return finalState;

  451.         } catch (MathRuntimeException mre) {
  452.             throw OrekitException.unwrap(mre);
  453.         }
  454.     }

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

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

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

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

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

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

  503.     }

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

  510.         if (secondaryOffsets.isEmpty()) {
  511.             return null;
  512.         }

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

  520.         return secondary;

  521.     }

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

  528.         if (secondaryOffsets.isEmpty()) {
  529.             return null;
  530.         }

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

  538.         return secondaryDerivative;

  539.     }

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

  545.         final ExpandableODE ode =
  546.                 new ExpandableODE(new ConvertedMainStateEquations(getMainStateEquations(integ)));

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

  551.         return ode;

  552.     }

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

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

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

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

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

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

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

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

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

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

  608.     }

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

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

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

  628.     }

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

  631.         /** Main state equations. */
  632.         private final MainStateEquations main;

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

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

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

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

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

  676.             // increment calls counter
  677.             ++calls;

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

  682.             currentState = updateAdditionalStates(currentState);
  683.             // compute main state differentials
  684.             return main.computeDerivatives(currentState);

  685.         }

  686.     }

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

  689.         /** Dimension of the combined additional states. */
  690.         private final int combinedDimension;

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

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

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

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

  711.         }

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

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

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

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

  756.             return secondaryDot;

  757.         }

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

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

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

  774.             return updateAdditionalStates(initialState);

  775.         }

  776.     }

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

  782.         /** Underlying event detector. */
  783.         private final EventDetector detector;

  784.         /** Underlying event handler.
  785.          * @since 12.0
  786.          */
  787.         private final EventHandler handler;

  788.         /** Time of the previous call to g. */
  789.         private double lastT;

  790.         /** Value from the previous call to g. */
  791.         private double lastG;

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

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

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

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

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

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

  831.         /** {@inheritDoc} */
  832.         public ODEEventHandler getHandler() {

  833.             return new ODEEventHandler() {

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

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

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

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

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

  855.                     return new ODEState(newState.getDate().durationFrom(getStartDate()),
  856.                                         primary, secondary);

  857.                 }

  858.             };
  859.         }

  860.     }

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

  866.         /** Underlying handler. */
  867.         private final OrekitStepHandler handler;

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

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

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

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

  889.     }

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

  895.         /** Underlying raw rawInterpolator. */
  896.         private final ODEStateInterpolator mathInterpolator;

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

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

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

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

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

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

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

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

  946.     }

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

  951.         /** Underlying raw mathematical model. */
  952.         private DenseOutputModel model;

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

  955.         /** Generated ephemeris. */
  956.         private BoundedPropagator ephemeris;

  957.         /** Last interpolator handled by the object.*/
  958.         private  ODEStateInterpolator lastInterpolator;

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

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

  968.             this.model = new DenseOutputModel();
  969.             model.init(s0, t);

  970.             // ephemeris will be generated when last step is processed
  971.             this.ephemeris = null;

  972.             this.lastInterpolator = null;

  973.         }

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

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

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

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

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

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

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

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

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

  1040.         }

  1041.     }

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

  1053.         /** Wrapped integrator. */
  1054.         private final ODEIntegrator integrator;

  1055.         /** Initial event detectors list. */
  1056.         private final List<ODEEventDetector> detectors;

  1057.         /** Initial step handlers list. */
  1058.         private final List<ODEStepHandler> stepHandlers;

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

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

  1074.             // reset event handlers
  1075.             integrator.clearEventDetectors();
  1076.             detectors.forEach(integrator::addEventDetector);

  1077.             // reset step handlers
  1078.             integrator.clearStepHandlers();
  1079.             stepHandlers.forEach(integrator::addStepHandler);

  1080.         }

  1081.     }

  1082. }