FieldAbstractIntegratedPropagator.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.CalculusFieldElement;
  28. import org.hipparchus.Field;
  29. import org.hipparchus.analysis.solvers.FieldBracketingNthOrderBrentSolver;
  30. import org.hipparchus.exception.MathIllegalArgumentException;
  31. import org.hipparchus.exception.MathIllegalStateException;
  32. import org.hipparchus.ode.FieldDenseOutputModel;
  33. import org.hipparchus.ode.FieldExpandableODE;
  34. import org.hipparchus.ode.FieldODEIntegrator;
  35. import org.hipparchus.ode.FieldODEState;
  36. import org.hipparchus.ode.FieldODEStateAndDerivative;
  37. import org.hipparchus.ode.FieldOrdinaryDifferentialEquation;
  38. import org.hipparchus.ode.FieldSecondaryODE;
  39. import org.hipparchus.ode.events.Action;
  40. import org.hipparchus.ode.events.FieldAdaptableInterval;
  41. import org.hipparchus.ode.events.FieldODEEventDetector;
  42. import org.hipparchus.ode.events.FieldODEEventHandler;
  43. import org.hipparchus.ode.sampling.AbstractFieldODEStateInterpolator;
  44. import org.hipparchus.ode.sampling.FieldODEStateInterpolator;
  45. import org.hipparchus.ode.sampling.FieldODEStepHandler;
  46. import org.hipparchus.util.MathArrays;
  47. import org.hipparchus.util.Precision;
  48. import org.orekit.attitudes.AttitudeProvider;
  49. import org.orekit.errors.OrekitException;
  50. import org.orekit.errors.OrekitInternalError;
  51. import org.orekit.errors.OrekitMessages;
  52. import org.orekit.frames.Frame;
  53. import org.orekit.orbits.OrbitType;
  54. import org.orekit.orbits.PositionAngleType;
  55. import org.orekit.propagation.FieldAbstractPropagator;
  56. import org.orekit.propagation.FieldBoundedPropagator;
  57. import org.orekit.propagation.FieldEphemerisGenerator;
  58. import org.orekit.propagation.FieldSpacecraftState;
  59. import org.orekit.propagation.PropagationType;
  60. import org.orekit.propagation.events.FieldEventDetector;
  61. import org.orekit.propagation.events.handlers.FieldEventHandler;
  62. import org.orekit.propagation.sampling.FieldOrekitStepHandler;
  63. import org.orekit.propagation.sampling.FieldOrekitStepInterpolator;
  64. import org.orekit.time.FieldAbsoluteDate;
  65. import org.orekit.utils.FieldArrayDictionary;


  66. /** Common handling of {@link org.orekit.propagation.FieldPropagator FieldPropagator}
  67.  *  methods for both numerical and semi-analytical propagators.
  68.  * @author Luc Maisonobe
  69.  * @param <T> type of the field element
  70.  */
  71. public abstract class FieldAbstractIntegratedPropagator<T extends CalculusFieldElement<T>> extends FieldAbstractPropagator<T> {

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

  76.     /** Event detectors not related to force models. */
  77.     private final List<FieldEventDetector<T>> detectors;

  78.     /** Step handlers dedicated to ephemeris generation. */
  79.     private final List<FieldStoringStepHandler> ephemerisGenerators;

  80.     /** Integrator selected by the user for the orbital extrapolation process. */
  81.     private final FieldODEIntegrator<T> integrator;

  82.     /** Offsets of secondary states managed by {@link FieldAdditionalDerivativesProvider}.
  83.      * @since 11.1
  84.      */
  85.     private final Map<String, Integer> secondaryOffsets;

  86.     /** Additional derivatives providers.
  87.      * @since 11.1
  88.      */
  89.     private final List<FieldAdditionalDerivativesProvider<T>> additionalDerivativesProviders;

  90.     /** Counter for differential equations calls. */
  91.     private int calls;

  92.     /** Mapper between raw double components and space flight dynamics objects. */
  93.     private FieldStateMapper<T> stateMapper;

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

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

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

  108.     /** Build a new instance.
  109.      * @param integrator numerical integrator to use for propagation.
  110.      * @param propagationType type of orbit to output (mean or osculating).
  111.      * @param field Field used by default
  112.      */
  113.     protected FieldAbstractIntegratedPropagator(final Field<T> field, final FieldODEIntegrator<T> integrator, final PropagationType propagationType) {
  114.         super(field);
  115.         detectors                      = new ArrayList<>();
  116.         ephemerisGenerators            = new ArrayList<>();
  117.         additionalDerivativesProviders = new ArrayList<>();
  118.         this.secondaryOffsets          = new HashMap<>();
  119.         this.integrator                = integrator;
  120.         this.propagationType           = propagationType;
  121.         this.resetAtEnd                = true;
  122.     }

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

  138.     /** Getter for the resetting flag regarding initial state.
  139.      * @return resetting flag
  140.      * @since 12.0
  141.      */
  142.     public boolean getResetAtEnd() {
  143.         return this.resetAtEnd;
  144.     }

  145.     /**
  146.      * Method called when initializing the attitude provider used when evaluating derivatives.
  147.      * @return attitude provider for derivatives
  148.      */
  149.     protected AttitudeProvider initializeAttitudeProviderForDerivatives() {
  150.         return getAttitudeProvider();
  151.     }

  152.     /** Initialize the mapper.
  153.      * @param field Field used by default
  154.      */
  155.     protected void initMapper(final Field<T> field) {
  156.         final T zero = field.getZero();
  157.         stateMapper = createMapper(null, zero.add(Double.NaN), null, null, null, null);
  158.     }

  159.     /** Get the integrator's name.
  160.      * @return name of underlying integrator
  161.      * @since 12.0
  162.      */
  163.     public String getIntegratorName() {
  164.         return integrator.getName();
  165.     }

  166.     /**  {@inheritDoc} */
  167.     @Override
  168.     public void setAttitudeProvider(final AttitudeProvider attitudeProvider) {
  169.         super.setAttitudeProvider(attitudeProvider);
  170.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  171.                                    stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
  172.                                    attitudeProvider, stateMapper.getFrame());
  173.     }

  174.     /** Set propagation orbit type.
  175.      * @param orbitType orbit type to use for propagation
  176.      */
  177.     protected void setOrbitType(final OrbitType orbitType) {
  178.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  179.                                    orbitType, stateMapper.getPositionAngleType(),
  180.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  181.     }

  182.     /** Get propagation parameter type.
  183.      * @return orbit type used for propagation
  184.      */
  185.     protected OrbitType getOrbitType() {
  186.         return stateMapper.getOrbitType();
  187.     }

  188.     /** Check if only the mean elements should be used in a semi-analytical propagation.
  189.      * @return {@link PropagationType MEAN} if only mean elements have to be used or
  190.      *         {@link PropagationType OSCULATING} if osculating elements have to be also used.
  191.      */
  192.     protected PropagationType isMeanOrbit() {
  193.         return propagationType;
  194.     }

  195.     /** Get the propagation type.
  196.      * @return propagation type.
  197.      * @since 11.3.2
  198.      */
  199.     public PropagationType getPropagationType() {
  200.         return propagationType;
  201.     }

  202.     /** Set position angle type.
  203.      * <p>
  204.      * The position parameter type is meaningful only if {@link
  205.      * #getOrbitType() propagation orbit type}
  206.      * support it. As an example, it is not meaningful for propagation
  207.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  208.      * </p>
  209.      * @param positionAngleType angle type to use for propagation
  210.      */
  211.     protected void setPositionAngleType(final PositionAngleType positionAngleType) {
  212.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  213.                                    stateMapper.getOrbitType(), positionAngleType,
  214.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  215.     }

  216.     /** Get propagation parameter type.
  217.      * @return angle type to use for propagation
  218.      */
  219.     protected PositionAngleType getPositionAngleType() {
  220.         return stateMapper.getPositionAngleType();
  221.     }

  222.     /** Set the central attraction coefficient μ.
  223.      * @param mu central attraction coefficient (m³/s²)
  224.      */
  225.     public void setMu(final T mu) {
  226.         stateMapper = createMapper(stateMapper.getReferenceDate(), mu,
  227.                                    stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
  228.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  229.     }

  230.     /** Get the central attraction coefficient μ.
  231.      * @return mu central attraction coefficient (m³/s²)
  232.      * @see #setMu(CalculusFieldElement)
  233.      */
  234.     public T getMu() {
  235.         return stateMapper.getMu();
  236.     }

  237.     /** Get the number of calls to the differential equations computation method.
  238.      * <p>The number of calls is reset each time the {@link #propagate(FieldAbsoluteDate)}
  239.      * method is called.</p>
  240.      * @return number of calls to the differential equations computation method
  241.      */
  242.     public int getCalls() {
  243.         return calls;
  244.     }

  245.     /** {@inheritDoc} */
  246.     @Override
  247.     public boolean isAdditionalStateManaged(final String name) {

  248.         // first look at already integrated states
  249.         if (super.isAdditionalStateManaged(name)) {
  250.             return true;
  251.         }

  252.         // then look at states we integrate ourselves
  253.         for (final FieldAdditionalDerivativesProvider<T> provider : additionalDerivativesProviders) {
  254.             if (provider.getName().equals(name)) {
  255.                 return true;
  256.             }
  257.         }

  258.         return false;
  259.     }

  260.     /** {@inheritDoc} */
  261.     @Override
  262.     public String[] getManagedAdditionalStates() {
  263.         final String[] alreadyIntegrated = super.getManagedAdditionalStates();
  264.         final String[] managed = new String[alreadyIntegrated.length + additionalDerivativesProviders.size()];
  265.         System.arraycopy(alreadyIntegrated, 0, managed, 0, alreadyIntegrated.length);
  266.         for (int i = 0; i < additionalDerivativesProviders.size(); ++i) {
  267.             managed[i + alreadyIntegrated.length] = additionalDerivativesProviders.get(i).getName();
  268.         }
  269.         return managed;
  270.     }

  271.     /** Add a provider for user-specified state derivatives to be integrated along with the orbit propagation.
  272.      * @param provider provider for additional derivatives
  273.      * @see #addAdditionalStateProvider(org.orekit.propagation.FieldAdditionalStateProvider)
  274.      * @since 11.1
  275.      */
  276.     public void addAdditionalDerivativesProvider(final FieldAdditionalDerivativesProvider<T> provider) {
  277.         // check if the name is already used
  278.         if (isAdditionalStateManaged(provider.getName())) {
  279.             // these derivatives are already registered, complain
  280.             throw new OrekitException(OrekitMessages.ADDITIONAL_STATE_NAME_ALREADY_IN_USE,
  281.                                       provider.getName());
  282.         }

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

  285.         secondaryOffsets.clear();

  286.     }

  287.     /** Get an unmodifiable list of providers for additional derivatives.
  288.      * @return providers for additional derivatives
  289.      * @since 11.1
  290.      */
  291.     public List<FieldAdditionalDerivativesProvider<T>> getAdditionalDerivativesProviders() {
  292.         return Collections.unmodifiableList(additionalDerivativesProviders);
  293.     }

  294.     /** {@inheritDoc} */
  295.     public <D extends FieldEventDetector<T>> void addEventDetector(final D detector) {
  296.         detectors.add(detector);
  297.     }

  298.     /** {@inheritDoc} */
  299.     public Collection<FieldEventDetector<T>> getEventsDetectors() {
  300.         return Collections.unmodifiableCollection(detectors);
  301.     }

  302.     /** {@inheritDoc} */
  303.     public void clearEventsDetectors() {
  304.         detectors.clear();
  305.     }

  306.     /** Set up all user defined event detectors.
  307.      */
  308.     protected void setUpUserEventDetectors() {
  309.         for (final FieldEventDetector<T> detector : detectors) {
  310.             setUpEventDetector(integrator, detector);
  311.         }
  312.     }

  313.     /** Wrap an Orekit event detector and register it to the integrator.
  314.      * @param integ integrator into which event detector should be registered
  315.      * @param detector event detector to wrap
  316.      */
  317.     protected void setUpEventDetector(final FieldODEIntegrator<T> integ, final FieldEventDetector<T> detector) {
  318.         integ.addEventDetector(new FieldAdaptedEventDetector(detector));
  319.     }

  320.     /** {@inheritDoc} */
  321.     @Override
  322.     public FieldEphemerisGenerator<T> getEphemerisGenerator() {
  323.         final FieldStoringStepHandler storingHandler = new FieldStoringStepHandler();
  324.         ephemerisGenerators.add(storingHandler);
  325.         return storingHandler;
  326.     }

  327.     /** Create a mapper between raw double components and spacecraft state.
  328.     /** Simple constructor.
  329.      * <p>
  330.      * The position parameter type is meaningful only if {@link
  331.      * #getOrbitType() propagation orbit type}
  332.      * support it. As an example, it is not meaningful for propagation
  333.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  334.      * </p>
  335.      * @param referenceDate reference date
  336.      * @param mu central attraction coefficient (m³/s²)
  337.      * @param orbitType orbit type to use for mapping
  338.      * @param positionAngleType angle type to use for propagation
  339.      * @param attitudeProvider attitude provider
  340.      * @param frame inertial frame
  341.      * @return new mapper
  342.      */
  343.     protected abstract FieldStateMapper<T> createMapper(FieldAbsoluteDate<T> referenceDate, T mu,
  344.                                                         OrbitType orbitType, PositionAngleType positionAngleType,
  345.                                                         AttitudeProvider attitudeProvider, Frame frame);

  346.     /** Get the differential equations to integrate (for main state only).
  347.      * @param integ numerical integrator to use for propagation.
  348.      * @return differential equations for main state
  349.      */
  350.     protected abstract MainStateEquations<T> getMainStateEquations(FieldODEIntegrator<T> integ);

  351.     /** {@inheritDoc} */
  352.     @Override
  353.     public FieldSpacecraftState<T> propagate(final FieldAbsoluteDate<T> target) {
  354.         if (getStartDate() == null) {
  355.             if (getInitialState() == null) {
  356.                 throw new OrekitException(OrekitMessages.INITIAL_STATE_NOT_SPECIFIED_FOR_ORBIT_PROPAGATION);
  357.             }
  358.             setStartDate(getInitialState().getDate());
  359.         }
  360.         return propagate(getStartDate(), target);
  361.     }

  362.     /** {@inheritDoc} */
  363.     public FieldSpacecraftState<T> propagate(final FieldAbsoluteDate<T> tStart, final FieldAbsoluteDate<T> tEnd) {

  364.         if (getInitialState() == null) {
  365.             throw new OrekitException(OrekitMessages.INITIAL_STATE_NOT_SPECIFIED_FOR_ORBIT_PROPAGATION);
  366.         }

  367.         // make sure the integrator will be reset properly even if we change its events handlers and step handlers
  368.         try (IntegratorResetter<T> resetter = new IntegratorResetter<>(integrator)) {

  369.             // Initialize additional states
  370.             initializeAdditionalStates(tEnd);

  371.             if (!tStart.equals(getInitialState().getDate())) {
  372.                 // if propagation start date is not initial date,
  373.                 // propagate from initial to start date without event detection
  374.                 try (IntegratorResetter<T> startResetter = new IntegratorResetter<>(integrator)) {
  375.                     integrateDynamics(tStart);
  376.                 }
  377.             }

  378.             // set up events added by user
  379.             setUpUserEventDetectors();

  380.             // set up step handlers
  381.             for (final FieldOrekitStepHandler<T> handler : getMultiplexer().getHandlers()) {
  382.                 integrator.addStepHandler(new FieldAdaptedStepHandler(handler));
  383.             }
  384.             for (final FieldStoringStepHandler generator : ephemerisGenerators) {
  385.                 generator.setEndDate(tEnd);
  386.                 integrator.addStepHandler(generator);
  387.             }

  388.             // propagate from start date to end date with event detection
  389.             return integrateDynamics(tEnd);

  390.         }

  391.     }

  392.     /** Propagation with or without event detection.
  393.      * @param tEnd target date to which orbit should be propagated
  394.      * @return state at end of propagation
  395.      */
  396.     private FieldSpacecraftState<T> integrateDynamics(final FieldAbsoluteDate<T> tEnd) {
  397.         try {

  398.             initializePropagation();

  399.             if (getInitialState().getDate().equals(tEnd)) {
  400.                 // don't extrapolate
  401.                 return getInitialState();
  402.             }
  403.             // space dynamics view
  404.             stateMapper = createMapper(getInitialState().getDate(), stateMapper.getMu(),
  405.                                        stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
  406.                                        stateMapper.getAttitudeProvider(), getInitialState().getFrame());

  407.             // set propagation orbit type
  408.             if (Double.isNaN(getMu().getReal())) {
  409.                 setMu(getInitialState().getMu());
  410.             }
  411.             if (getInitialState().getMass().getReal() <= 0.0) {
  412.                 throw new OrekitException(OrekitMessages.NOT_POSITIVE_SPACECRAFT_MASS,
  413.                                                getInitialState().getMass());
  414.             }

  415.             // convert space flight dynamics API to math API
  416.             final FieldSpacecraftState<T> initialIntegrationState = getInitialIntegrationState();
  417.             final FieldODEState<T> mathInitialState = createInitialState(initialIntegrationState);
  418.             final FieldExpandableODE<T> mathODE = createODE(integrator);

  419.             // mathematical integration
  420.             final FieldODEStateAndDerivative<T> mathFinalState;
  421.             beforeIntegration(initialIntegrationState, tEnd);
  422.             mathFinalState = integrator.integrate(mathODE, mathInitialState,
  423.                                                   tEnd.durationFrom(getInitialState().getDate()));

  424.             afterIntegration();

  425.             // get final state
  426.             FieldSpacecraftState<T> finalState =
  427.                             stateMapper.mapArrayToState(stateMapper.mapDoubleToDate(mathFinalState.getTime(), tEnd),
  428.                                                         mathFinalState.getPrimaryState(),
  429.                                                         mathFinalState.getPrimaryDerivative(),
  430.                                                         propagationType);

  431.             finalState = updateAdditionalStatesAndDerivatives(finalState, mathFinalState);

  432.             if (resetAtEnd) {
  433.                 resetInitialState(finalState);
  434.                 setStartDate(finalState.getDate());
  435.             }

  436.             return finalState;

  437.         } catch (OrekitException pe) {
  438.             throw pe;
  439.         } catch (MathIllegalArgumentException | MathIllegalStateException me) {
  440.             throw OrekitException.unwrap(me);
  441.         }
  442.     }

  443.     /**
  444.      * Returns an updated version of the inputted state with additional states, including
  445.      * from derivatives providers.
  446.      * @param originalState input state
  447.      * @param os ODE state and derivative
  448.      * @return new state
  449.      * @since 12.1
  450.      */
  451.     private FieldSpacecraftState<T> updateAdditionalStatesAndDerivatives(final FieldSpacecraftState<T> originalState,
  452.                                                                          final FieldODEStateAndDerivative<T> os) {
  453.         FieldSpacecraftState<T> updatedState = originalState;
  454.         if (os.getNumberOfSecondaryStates() > 0) {
  455.             final T[] secondary           = os.getSecondaryState(1);
  456.             final T[] secondaryDerivative = os.getSecondaryDerivative(1);
  457.             for (final FieldAdditionalDerivativesProvider<T> provider : additionalDerivativesProviders) {
  458.                 final String name      = provider.getName();
  459.                 final int    offset    = secondaryOffsets.get(name);
  460.                 final int    dimension = provider.getDimension();
  461.                 updatedState = updatedState.addAdditionalState(name, Arrays.copyOfRange(secondary, offset, offset + dimension));
  462.                 updatedState = updatedState.addAdditionalStateDerivative(name, Arrays.copyOfRange(secondaryDerivative, offset, offset + dimension));
  463.             }
  464.         }
  465.         return updateAdditionalStates(updatedState);
  466.     }

  467.     /** Get the initial state for integration.
  468.      * @return initial state for integration
  469.      */
  470.     protected FieldSpacecraftState<T> getInitialIntegrationState() {
  471.         return getInitialState();
  472.     }

  473.     /** Create an initial state.
  474.      * @param initialState initial state in flight dynamics world
  475.      * @return initial state in mathematics world
  476.      */
  477.     private FieldODEState<T> createInitialState(final FieldSpacecraftState<T> initialState) {

  478.         // retrieve initial state
  479.         final T[] primary  = MathArrays.buildArray(initialState.getA().getField(), getBasicDimension());
  480.         stateMapper.mapStateToArray(initialState, primary, null);

  481.         if (secondaryOffsets.isEmpty()) {
  482.             // compute dimension of the secondary state
  483.             int offset = 0;
  484.             for (final FieldAdditionalDerivativesProvider<T> provider : additionalDerivativesProviders) {
  485.                 secondaryOffsets.put(provider.getName(), offset);
  486.                 offset += provider.getDimension();
  487.             }
  488.             secondaryOffsets.put(SECONDARY_DIMENSION, offset);
  489.         }

  490.         return new FieldODEState<>(initialState.getA().getField().getZero(), primary, secondary(initialState));

  491.     }

  492.     /** Create secondary state.
  493.      * @param state spacecraft state
  494.      * @return secondary state
  495.      * @since 11.1
  496.      */
  497.     private T[][] secondary(final FieldSpacecraftState<T> state) {

  498.         if (secondaryOffsets.isEmpty()) {
  499.             return null;
  500.         }

  501.         final T[][] secondary = MathArrays.buildArray(state.getDate().getField(), 1, secondaryOffsets.get(SECONDARY_DIMENSION));
  502.         for (final FieldAdditionalDerivativesProvider<T> provider : additionalDerivativesProviders) {
  503.             final String name       = provider.getName();
  504.             final int    offset     = secondaryOffsets.get(name);
  505.             final T[]    additional = state.getAdditionalState(name);
  506.             System.arraycopy(additional, 0, secondary[0], offset, additional.length);
  507.         }

  508.         return secondary;

  509.     }

  510.     /** Create secondary state derivative.
  511.      * @param state spacecraft state
  512.      * @return secondary state derivative
  513.      * @since 11.1
  514.      */
  515.     private T[][] secondaryDerivative(final FieldSpacecraftState<T> state) {

  516.         if (secondaryOffsets.isEmpty()) {
  517.             return null;
  518.         }

  519.         final T[][] secondaryDerivative = MathArrays.buildArray(state.getDate().getField(), 1, secondaryOffsets.get(SECONDARY_DIMENSION));
  520.         for (final FieldAdditionalDerivativesProvider<T> providcer : additionalDerivativesProviders) {
  521.             final String name       = providcer.getName();
  522.             final int    offset     = secondaryOffsets.get(name);
  523.             final T[]    additionalDerivative = state.getAdditionalStateDerivative(name);
  524.             System.arraycopy(additionalDerivative, 0, secondaryDerivative[0], offset, additionalDerivative.length);
  525.         }

  526.         return secondaryDerivative;

  527.     }

  528.     /** Create an ODE with all equations.
  529.      * @param integ numerical integrator to use for propagation.
  530.      * @return a new ode
  531.      */
  532.     private FieldExpandableODE<T> createODE(final FieldODEIntegrator<T> integ) {

  533.         final FieldExpandableODE<T> ode =
  534.                 new FieldExpandableODE<>(new ConvertedMainStateEquations(getMainStateEquations(integ)));

  535.         // secondary part of the ODE
  536.         if (!additionalDerivativesProviders.isEmpty()) {
  537.             ode.addSecondaryEquations(new ConvertedSecondaryStateEquations());
  538.         }

  539.         return ode;

  540.     }

  541.     /** Method called just before integration.
  542.      * <p>
  543.      * The default implementation does nothing, it may be specialized in subclasses.
  544.      * </p>
  545.      * @param initialState initial state
  546.      * @param tEnd target date at which state should be propagated
  547.      */
  548.     protected void beforeIntegration(final FieldSpacecraftState<T> initialState,
  549.                                      final FieldAbsoluteDate<T> tEnd) {
  550.         // do nothing by default
  551.     }

  552.     /** Method called just after integration.
  553.      * <p>
  554.      * The default implementation does nothing, it may be specialized in subclasses.
  555.      * </p>
  556.      */
  557.     protected void afterIntegration() {
  558.         // do nothing by default
  559.     }

  560.     /** Get state vector dimension without additional parameters.
  561.      * @return state vector dimension without additional parameters.
  562.      */
  563.     public int getBasicDimension() {
  564.         return 7;

  565.     }

  566.     /** Get the integrator used by the propagator.
  567.      * @return the integrator.
  568.      */
  569.     protected FieldODEIntegrator<T> getIntegrator() {
  570.         return integrator;
  571.     }

  572.     /** Convert a state from mathematical world to space flight dynamics world.
  573.      * @param os mathematical state
  574.      * @return space flight dynamics state
  575.      */
  576.     private FieldSpacecraftState<T> convert(final FieldODEStateAndDerivative<T> os) {

  577.         FieldSpacecraftState<T> s =
  578.                         stateMapper.mapArrayToState(os.getTime(),
  579.                                                     os.getPrimaryState(),
  580.                                                     os.getPrimaryDerivative(),
  581.                                                     propagationType);
  582.         if (os.getNumberOfSecondaryStates() > 0) {
  583.             final T[] secondary           = os.getSecondaryState(1);
  584.             final T[] secondaryDerivative = os.getSecondaryDerivative(1);
  585.             for (final FieldAdditionalDerivativesProvider<T> equations : additionalDerivativesProviders) {
  586.                 final String name      = equations.getName();
  587.                 final int    offset    = secondaryOffsets.get(name);
  588.                 final int    dimension = equations.getDimension();
  589.                 s = s.addAdditionalState(name, Arrays.copyOfRange(secondary, offset, offset + dimension));
  590.                 s = s.addAdditionalStateDerivative(name, Arrays.copyOfRange(secondaryDerivative, offset, offset + dimension));
  591.             }
  592.         }
  593.         s = updateAdditionalStates(s);

  594.         return s;

  595.     }

  596.     /** Convert a state from space flight dynamics world to mathematical world.
  597.      * @param state space flight dynamics state
  598.      * @return mathematical state
  599.      */
  600.     private FieldODEStateAndDerivative<T> convert(final FieldSpacecraftState<T> state) {

  601.         // retrieve initial state
  602.         final T[] primary    = MathArrays.buildArray(getField(), getBasicDimension());
  603.         final T[] primaryDot = MathArrays.buildArray(getField(), getBasicDimension());
  604.         stateMapper.mapStateToArray(state, primary, primaryDot);

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

  608.         return new FieldODEStateAndDerivative<>(stateMapper.mapDateToDouble(state.getDate()),
  609.                                                 primary, primaryDot,
  610.                                                 secondary, secondaryDerivative);

  611.     }

  612.     /** Differential equations for the main state (orbit, attitude and mass).
  613.      * @param <T> type of the field element
  614.      */
  615.     public interface MainStateEquations<T extends CalculusFieldElement<T>> {

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

  627.         /** Compute differential equations for main state.
  628.          * @param state current state
  629.          * @return derivatives of main state
  630.          */
  631.         T[] computeDerivatives(FieldSpacecraftState<T> state);

  632.     }

  633.     /** Differential equations for the main state (orbit, attitude and mass), with converted API. */
  634.     private class ConvertedMainStateEquations implements FieldOrdinaryDifferentialEquation<T> {

  635.         /** Main state equations. */
  636.         private final MainStateEquations<T> main;

  637.         /** Simple constructor.
  638.          * @param main main state equations
  639.          */
  640.         ConvertedMainStateEquations(final MainStateEquations<T> main) {
  641.             this.main = main;
  642.             calls = 0;
  643.         }

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

  648.         @Override
  649.         public void init(final T t0, final T[] y0, final T finalTime) {
  650.             // update space dynamics view
  651.             FieldSpacecraftState<T> initialState = stateMapper.mapArrayToState(t0, y0, null, PropagationType.MEAN);
  652.             initialState = updateAdditionalStates(initialState);
  653.             initialState = updateStatesFromAdditionalDerivativesIfKnown(initialState);
  654.             final FieldAbsoluteDate<T> target = stateMapper.mapDoubleToDate(finalTime);
  655.             main.init(initialState, target);
  656.             attitudeProviderForDerivatives = initializeAttitudeProviderForDerivatives();
  657.         }

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

  678.         /** {@inheritDoc} */
  679.         public T[] computeDerivatives(final T t, final T[] y) {

  680.             // increment calls counter
  681.             ++calls;

  682.             // update space dynamics view
  683.             stateMapper.setAttitudeProvider(attitudeProviderForDerivatives);
  684.             FieldSpacecraftState<T> currentState = stateMapper.mapArrayToState(t, y, null, PropagationType.MEAN);
  685.             stateMapper.setAttitudeProvider(getAttitudeProvider());
  686.             currentState = updateAdditionalStates(currentState);

  687.             // compute main state differentials
  688.             return main.computeDerivatives(currentState);

  689.         }

  690.     }

  691.     /** Differential equations for the secondary state (Jacobians, user variables ...), with converted API. */
  692.     private class ConvertedSecondaryStateEquations implements FieldSecondaryODE<T> {

  693.         /** Dimension of the combined additional states. */
  694.         private final int combinedDimension;

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

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

  705.         /** {@inheritDoc} */
  706.         @Override
  707.         public void init(final T t0, final T[] primary0,
  708.                          final T[] secondary0, final T finalTime) {
  709.             // update space dynamics view
  710.             final FieldSpacecraftState<T> initialState = convert(t0, primary0, null, secondary0);

  711.             final FieldAbsoluteDate<T> target = stateMapper.mapDoubleToDate(finalTime);
  712.             for (final FieldAdditionalDerivativesProvider<T> provider : additionalDerivativesProviders) {
  713.                 provider.init(initialState, target);
  714.             }

  715.         }

  716.         /** {@inheritDoc} */
  717.         @Override
  718.         public T[] computeDerivatives(final T t, final T[] primary,
  719.                                       final T[] primaryDot, final T[] secondary) {

  720.             // update space dynamics view
  721.             // the integrable generators generate method will be called here,
  722.             // according to the generators yield order
  723.             FieldSpacecraftState<T> updated = convert(t, primary, primaryDot, secondary);

  724.             // set up queue for equations
  725.             final Queue<FieldAdditionalDerivativesProvider<T>> pending = new LinkedList<>(additionalDerivativesProviders);

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

  760.             return secondaryDot;

  761.         }

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

  771.             FieldSpacecraftState<T> initialState = stateMapper.mapArrayToState(t, primary, primaryDot, PropagationType.MEAN);

  772.             for (final FieldAdditionalDerivativesProvider<T> provider : additionalDerivativesProviders) {
  773.                 final String name      = provider.getName();
  774.                 final int    offset    = secondaryOffsets.get(name);
  775.                 final int    dimension = provider.getDimension();
  776.                 initialState = initialState.addAdditionalState(name, Arrays.copyOfRange(secondary, offset, offset + dimension));
  777.             }

  778.             return updateAdditionalStates(initialState);

  779.         }

  780.     }

  781.     /** Adapt an {@link org.orekit.propagation.events.FieldEventDetector<T>}
  782.      * to Hipparchus {@link org.hipparchus.ode.events.FieldODEEventDetector<T>} interface.
  783.      * @author Fabien Maussion
  784.      */
  785.     private class FieldAdaptedEventDetector implements FieldODEEventDetector<T> {

  786.         /** Underlying event detector. */
  787.         private final FieldEventDetector<T> detector;

  788.         /** Underlying event handler.
  789.          * @since 12.0
  790.          */
  791.         private final FieldEventHandler<T> handler;

  792.         /** Time of the previous call to g. */
  793.         private T lastT;

  794.         /** Value from the previous call to g. */
  795.         private T lastG;

  796.         /** Build a wrapped event detector.
  797.          * @param detector event detector to wrap
  798.         */
  799.         FieldAdaptedEventDetector(final FieldEventDetector<T> detector) {
  800.             this.detector = detector;
  801.             this.handler  = detector.getHandler();
  802.             this.lastT    = getField().getZero().add(Double.NaN);
  803.             this.lastG    = getField().getZero().add(Double.NaN);
  804.         }

  805.         /** {@inheritDoc} */
  806.         @Override
  807.         public FieldAdaptableInterval<T> getMaxCheckInterval() {
  808.             return s -> detector.getMaxCheckInterval().currentInterval(convert(s));
  809.         }

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

  815.         /** {@inheritDoc} */
  816.         @Override
  817.         public FieldBracketingNthOrderBrentSolver<T> getSolver() {
  818.             final T zero = detector.getThreshold().getField().getZero();
  819.             return new FieldBracketingNthOrderBrentSolver<>(zero, detector.getThreshold(), zero, 5);
  820.         }

  821.         /** {@inheritDoc} */
  822.         @Override
  823.         public void init(final FieldODEStateAndDerivative<T> s0, final T t) {
  824.             detector.init(convert(s0), stateMapper.mapDoubleToDate(t));
  825.             this.lastT = getField().getZero().add(Double.NaN);
  826.             this.lastG = getField().getZero().add(Double.NaN);
  827.         }

  828.         /** {@inheritDoc} */
  829.         public T g(final FieldODEStateAndDerivative<T> s) {
  830.             if (!Precision.equals(lastT.getReal(), s.getTime().getReal(), 0)) {
  831.                 lastT = s.getTime();
  832.                 lastG = detector.g(convert(s));
  833.             }
  834.             return lastG;
  835.         }

  836.         /** {@inheritDoc} */
  837.         public FieldODEEventHandler<T> getHandler() {

  838.             return new FieldODEEventHandler<T>() {

  839.                 /** {@inheritDoc} */
  840.                 public Action eventOccurred(final FieldODEStateAndDerivative<T> s,
  841.                                             final FieldODEEventDetector<T> d,
  842.                                             final boolean increasing) {
  843.                     return handler.eventOccurred(convert(s), detector, increasing);
  844.                 }

  845.                 /** {@inheritDoc} */
  846.                 @Override
  847.                 public FieldODEState<T> resetState(final FieldODEEventDetector<T> d,
  848.                                                    final FieldODEStateAndDerivative<T> s) {

  849.                     final FieldSpacecraftState<T> oldState = convert(s);
  850.                     final FieldSpacecraftState<T> newState = handler.resetState(detector, oldState);
  851.                     stateChanged(newState);

  852.                     // main part
  853.                     final T[] primary    = MathArrays.buildArray(getField(), s.getPrimaryStateDimension());
  854.                     stateMapper.mapStateToArray(newState, primary, null);

  855.                     // secondary part
  856.                     final T[][] secondary = MathArrays.buildArray(getField(), 1, additionalDerivativesProviders.size());
  857.                     for (final FieldAdditionalDerivativesProvider<T> provider : additionalDerivativesProviders) {
  858.                         final String name      = provider.getName();
  859.                         final int    offset    = secondaryOffsets.get(name);
  860.                         final int    dimension = provider.getDimension();
  861.                         System.arraycopy(newState.getAdditionalState(name), 0, secondary[0], offset, dimension);
  862.                     }

  863.                     return new FieldODEState<>(newState.getDate().durationFrom(getStartDate()),
  864.                                                primary, secondary);
  865.                 }
  866.             };

  867.         }

  868.     }

  869.     /** Adapt an {@link org.orekit.propagation.sampling.FieldOrekitStepHandler<T>}
  870.      * to Hipparchus {@link FieldODEStepHandler<T>} interface.
  871.      * @author Luc Maisonobe
  872.      */
  873.     private class FieldAdaptedStepHandler implements FieldODEStepHandler<T> {

  874.         /** Underlying handler. */
  875.         private final FieldOrekitStepHandler<T> handler;

  876.         /** Build an instance.
  877.          * @param handler underlying handler to wrap
  878.          */
  879.         FieldAdaptedStepHandler(final FieldOrekitStepHandler<T> handler) {
  880.             this.handler = handler;
  881.         }

  882.         /** {@inheritDoc} */
  883.         @Override
  884.         public void init(final FieldODEStateAndDerivative<T> s0, final T t) {
  885.             handler.init(convert(s0), stateMapper.mapDoubleToDate(t));
  886.         }

  887.         /** {@inheritDoc} */
  888.         public void handleStep(final FieldODEStateInterpolator<T> interpolator) {
  889.             handler.handleStep(new FieldAdaptedStepInterpolator(interpolator));
  890.         }

  891.         /** {@inheritDoc} */
  892.         @Override
  893.         public void finish(final FieldODEStateAndDerivative<T> finalState) {
  894.             handler.finish(convert(finalState));
  895.         }

  896.     }

  897.     /** Adapt an {@link org.orekit.propagation.sampling.FieldOrekitStepInterpolator<T>}
  898.      * to Hipparchus {@link FieldODEStepInterpolator<T>} interface.
  899.      * @author Luc Maisonobe
  900.      */
  901.     private class FieldAdaptedStepInterpolator implements FieldOrekitStepInterpolator<T> {

  902.         /** Underlying raw rawInterpolator. */
  903.         private final FieldODEStateInterpolator<T> mathInterpolator;

  904.         /** Build an instance.
  905.          * @param mathInterpolator underlying raw interpolator
  906.          */
  907.         FieldAdaptedStepInterpolator(final FieldODEStateInterpolator<T> mathInterpolator) {
  908.             this.mathInterpolator = mathInterpolator;
  909.         }

  910.         /** {@inheritDoc}} */
  911.         @Override
  912.         public FieldSpacecraftState<T> getPreviousState() {
  913.             return convert(mathInterpolator.getPreviousState());
  914.         }

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

  920.         /** {@inheritDoc}} */
  921.         @Override
  922.         public FieldSpacecraftState<T> getInterpolatedState(final FieldAbsoluteDate<T> date) {
  923.             return convert(mathInterpolator.getInterpolatedState(date.durationFrom(getStartDate())));
  924.         }

  925.         /** Check is integration direction is forward in date.
  926.          * @return true if integration is forward in date
  927.          */
  928.         public boolean isForward() {
  929.             return mathInterpolator.isForward();
  930.         }

  931.         /** {@inheritDoc}} */
  932.         @Override
  933.         public FieldAdaptedStepInterpolator restrictStep(final FieldSpacecraftState<T> newPreviousState,
  934.                                                          final FieldSpacecraftState<T> newCurrentState) {
  935.             try {
  936.                 final AbstractFieldODEStateInterpolator<T> aosi = (AbstractFieldODEStateInterpolator<T>) mathInterpolator;
  937.                 return new FieldAdaptedStepInterpolator(aosi.restrictStep(convert(newPreviousState),
  938.                                                                           convert(newCurrentState)));
  939.             } catch (ClassCastException cce) {
  940.                 // this should never happen
  941.                 throw new OrekitInternalError(cce);
  942.             }
  943.         }

  944.     }

  945.     /** Specialized step handler storing interpolators for ephemeris generation.
  946.      * @since 11.0
  947.      */
  948.     private class FieldStoringStepHandler implements FieldODEStepHandler<T>, FieldEphemerisGenerator<T> {

  949.         /** Underlying raw mathematical model. */
  950.         private FieldDenseOutputModel<T> model;

  951.         /** the user supplied end date. Propagation may not end on this date. */
  952.         private FieldAbsoluteDate<T> endDate;

  953.         /** Generated ephemeris. */
  954.         private FieldBoundedPropagator<T> ephemeris;

  955.         /** Last interpolator handled by the object.*/
  956.         private  FieldODEStateInterpolator<T> lastInterpolator;

  957.         /** Set the end date.
  958.          * @param endDate end date
  959.          */
  960.         public void setEndDate(final FieldAbsoluteDate<T> endDate) {
  961.             this.endDate = endDate;
  962.         }

  963.         /** {@inheritDoc} */
  964.         @Override
  965.         public void init(final FieldODEStateAndDerivative<T> s0, final T t) {
  966.             this.model = new FieldDenseOutputModel<>();
  967.             model.init(s0, t);

  968.             // ephemeris will be generated when last step is processed
  969.             this.ephemeris = null;

  970.             this.lastInterpolator = null;

  971.         }

  972.         /** {@inheritDoc} */
  973.         @Override
  974.         public FieldBoundedPropagator<T> getGeneratedEphemeris() {
  975.             // Each time we try to get the ephemeris, rebuild it using the last data.
  976.             buildEphemeris();
  977.             return ephemeris;
  978.         }

  979.         /** {@inheritDoc} */
  980.         @Override
  981.         public void handleStep(final FieldODEStateInterpolator<T> interpolator) {
  982.             model.handleStep(interpolator);
  983.             lastInterpolator = interpolator;
  984.         }

  985.         /** {@inheritDoc} */
  986.         @Override
  987.         public void finish(final FieldODEStateAndDerivative<T> finalState) {
  988.             buildEphemeris();
  989.         }

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

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

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

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

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

  1033.             // create the ephemeris
  1034.             ephemeris = new FieldIntegratedEphemeris<>(startDate, minDate, maxDate,
  1035.                                                        stateMapper, propagationType, model,
  1036.                                                        unmanaged, getAdditionalStateProviders(),
  1037.                                                        names, dimensions);

  1038.         }

  1039.     }

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

  1052.         /** Wrapped integrator. */
  1053.         private final FieldODEIntegrator<T> integrator;

  1054.         /** Initial event detectors list. */
  1055.         private final List<FieldODEEventDetector<T>> detectors;

  1056.         /** Initial step handlers list. */
  1057.         private final List<FieldODEStepHandler<T>> stepHandlers;

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

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

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

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

  1079.         }

  1080.     }

  1081. }