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 AdditionalEquations}.
  80.      * @since 11.1
  81.      */
  82.     private final Map<String, Integer> secondaryOffsets;

  83.     /** Additional derivatives providers.
  84.      * @since 11.1
  85.      */
  86.     private 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.     /** Flag for resetting the state at end of propagation. */
  93.     private boolean resetAtEnd;

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

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

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

  129.     /** Getter for the resetting flag regarding initial state.
  130.      * @return resetting flag
  131.      * @since 12.0
  132.      */
  133.     public boolean getResetAtEnd() {
  134.         return this.resetAtEnd;
  135.     }

  136.     /** Initialize the mapper. */
  137.     protected void initMapper() {
  138.         stateMapper = createMapper(null, Double.NaN, null, null, null, null);
  139.     }

  140.     /** Get the integrator's name.
  141.      * @return name of underlying integrator
  142.      * @since 12.0
  143.      */
  144.     public String getIntegratorName() {
  145.         return integrator.getName();
  146.     }

  147.     /**  {@inheritDoc} */
  148.     public void setAttitudeProvider(final AttitudeProvider attitudeProvider) {
  149.         super.setAttitudeProvider(attitudeProvider);
  150.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  151.                                    stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
  152.                                    attitudeProvider, stateMapper.getFrame());
  153.     }

  154.     /** Set propagation orbit type.
  155.      * @param orbitType orbit type to use for propagation, null for
  156.      * propagating using {@link org.orekit.utils.AbsolutePVCoordinates AbsolutePVCoordinates}
  157.      * rather than {@link org.orekit.orbits Orbit}
  158.      */
  159.     protected void setOrbitType(final OrbitType orbitType) {
  160.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  161.                                    orbitType, stateMapper.getPositionAngleType(),
  162.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  163.     }

  164.     /** Get propagation parameter type.
  165.      * @return orbit type used for propagation, null for
  166.      * propagating using {@link org.orekit.utils.AbsolutePVCoordinates AbsolutePVCoordinates}
  167.      * rather than {@link org.orekit.orbits Orbit}
  168.      */
  169.     protected OrbitType getOrbitType() {
  170.         return stateMapper.getOrbitType();
  171.     }

  172.     /** Get the propagation type.
  173.      * @return propagation type.
  174.      * @since 11.1
  175.      */
  176.     public PropagationType getPropagationType() {
  177.         return propagationType;
  178.     }

  179.     /** Set position angle type.
  180.      * <p>
  181.      * The position parameter type is meaningful only if {@link
  182.      * #getOrbitType() propagation orbit type}
  183.      * support it. As an example, it is not meaningful for propagation
  184.      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
  185.      * </p>
  186.      * @param positionAngleType angle type to use for propagation
  187.      */
  188.     protected void setPositionAngleType(final PositionAngleType positionAngleType) {
  189.         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
  190.                                    stateMapper.getOrbitType(), positionAngleType,
  191.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  192.     }

  193.     /** Get propagation parameter type.
  194.      * @return angle type to use for propagation
  195.      */
  196.     protected PositionAngleType getPositionAngleType() {
  197.         return stateMapper.getPositionAngleType();
  198.     }

  199.     /** Set the central attraction coefficient μ.
  200.      * @param mu central attraction coefficient (m³/s²)
  201.      */
  202.     public void setMu(final double mu) {
  203.         stateMapper = createMapper(stateMapper.getReferenceDate(), mu,
  204.                                    stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
  205.                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
  206.     }

  207.     /** Get the central attraction coefficient μ.
  208.      * @return mu central attraction coefficient (m³/s²)
  209.      * @see #setMu(double)
  210.      */
  211.     public double getMu() {
  212.         return stateMapper.getMu();
  213.     }

  214.     /** Get the number of calls to the differential equations computation method.
  215.      * <p>The number of calls is reset each time the {@link #propagate(AbsoluteDate)}
  216.      * method is called.</p>
  217.      * @return number of calls to the differential equations computation method
  218.      */
  219.     public int getCalls() {
  220.         return calls;
  221.     }

  222.     /** {@inheritDoc} */
  223.     @Override
  224.     public boolean isAdditionalStateManaged(final String name) {

  225.         // first look at already integrated states
  226.         if (super.isAdditionalStateManaged(name)) {
  227.             return true;
  228.         }

  229.         // then look at states we integrate ourselves
  230.         for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  231.             if (provider.getName().equals(name)) {
  232.                 return true;
  233.             }
  234.         }

  235.         return false;
  236.     }

  237.     /** {@inheritDoc} */
  238.     @Override
  239.     public String[] getManagedAdditionalStates() {
  240.         final String[] alreadyIntegrated = super.getManagedAdditionalStates();
  241.         final String[] managed = new String[alreadyIntegrated.length + additionalDerivativesProviders.size()];
  242.         System.arraycopy(alreadyIntegrated, 0, managed, 0, alreadyIntegrated.length);
  243.         for (int i = 0; i < additionalDerivativesProviders.size(); ++i) {
  244.             managed[i + alreadyIntegrated.length] = additionalDerivativesProviders.get(i).getName();
  245.         }
  246.         return managed;
  247.     }

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

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

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

  262.         secondaryOffsets.clear();

  263.     }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  347.             // Initialize additional states
  348.             initializeAdditionalStates(tEnd);

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

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

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

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

  368.             return finalState;

  369.         }

  370.     }

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

  377.     /** Propagation with or without event detection.
  378.      * @param tEnd target date to which orbit should be propagated
  379.      * @param forceResetAtEnd flag to force resetting state and date after integration
  380.      * @return state at end of propagation
  381.      */
  382.     private SpacecraftState integrateDynamics(final AbsoluteDate tEnd, final boolean forceResetAtEnd) {
  383.         try {

  384.             initializePropagation();

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

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


  393.             if (Double.isNaN(getMu())) {
  394.                 setMu(getInitialState().getMu());
  395.             }

  396.             if (getInitialState().getMass() <= 0.0) {
  397.                 throw new OrekitException(OrekitMessages.NOT_POSITIVE_SPACECRAFT_MASS,
  398.                                           getInitialState().getMass());
  399.             }

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

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

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

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

  430.             if (resetAtEnd || forceResetAtEnd) {
  431.                 resetInitialState(finalState);
  432.                 setStartDate(finalState.getDate());
  433.             }

  434.             return finalState;

  435.         } catch (MathRuntimeException mre) {
  436.             throw OrekitException.unwrap(mre);
  437.         }
  438.     }

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

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

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

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

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

  463.     }

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

  470.         if (secondaryOffsets.isEmpty()) {
  471.             return null;
  472.         }

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

  480.         return secondary;

  481.     }

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

  488.         if (secondaryOffsets.isEmpty()) {
  489.             return null;
  490.         }

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

  498.         return secondaryDerivative;

  499.     }

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

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

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

  511.         return ode;

  512.     }

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

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

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

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

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

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

  565.         return s;

  566.     }

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

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

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

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

  582.     }

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

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

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

  602.     }

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

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

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

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

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

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

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

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

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

  635.         }

  636.     }

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

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

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

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

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

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

  661.         }

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

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

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

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

  706.             return secondaryDot;

  707.         }

  708.         /** Convert mathematical view to space view.
  709.          * @param t current value of the independent <I>time</I> variable
  710.          * @param primary array containing the current value of the primary state vector
  711.          * @param primaryDot array containing the derivative of the primary state vector
  712.          * @param secondary array containing the current value of the secondary state vector
  713.          * @return space view of the state
  714.          */
  715.         private SpacecraftState convert(final double t, final double[] primary,
  716.                                         final double[] primaryDot, final double[] secondary) {

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

  718.             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  719.                 final String name      = provider.getName();
  720.                 final int    offset    = secondaryOffsets.get(name);
  721.                 final int    dimension = provider.getDimension();
  722.                 initialState = initialState.addAdditionalState(name, Arrays.copyOfRange(secondary, offset, offset + dimension));
  723.             }

  724.             return updateAdditionalStates(initialState);

  725.         }

  726.     }

  727.     /** Adapt an {@link org.orekit.propagation.events.EventDetector}
  728.      * to Hipparchus {@link org.hipparchus.ode.events.ODEEventDetector} interface.
  729.      * @author Fabien Maussion
  730.      */
  731.     private class AdaptedEventDetector implements ODEEventDetector {

  732.         /** Underlying event detector. */
  733.         private final EventDetector detector;

  734.         /** Underlying event handler.
  735.          * @since 12.0
  736.          */
  737.         private final EventHandler handler;

  738.         /** Time of the previous call to g. */
  739.         private double lastT;

  740.         /** Value from the previous call to g. */
  741.         private double lastG;

  742.         /** Build a wrapped event detector.
  743.          * @param detector event detector to wrap
  744.         */
  745.         AdaptedEventDetector(final EventDetector detector) {
  746.             this.detector = detector;
  747.             this.handler  = detector.getHandler();
  748.             this.lastT    = Double.NaN;
  749.             this.lastG    = Double.NaN;
  750.         }

  751.         /** {@inheritDoc} */
  752.         @Override
  753.         public AdaptableInterval getMaxCheckInterval() {
  754.             return s -> detector.getMaxCheckInterval().currentInterval(convert(s));
  755.         }

  756.         /** {@inheritDoc} */
  757.         @Override
  758.         public int getMaxIterationCount() {
  759.             return detector.getMaxIterationCount();
  760.         }

  761.         /** {@inheritDoc} */
  762.         @Override
  763.         public BracketedUnivariateSolver<UnivariateFunction> getSolver() {
  764.             return new BracketingNthOrderBrentSolver(0, detector.getThreshold(), 0, 5);
  765.         }

  766.         /** {@inheritDoc} */
  767.         public void init(final ODEStateAndDerivative s0, final double t) {
  768.             detector.init(convert(s0), stateMapper.mapDoubleToDate(t));
  769.             this.lastT = Double.NaN;
  770.             this.lastG = Double.NaN;
  771.         }

  772.         /** {@inheritDoc} */
  773.         public double g(final ODEStateAndDerivative s) {
  774.             if (!Precision.equals(lastT, s.getTime(), 0)) {
  775.                 lastT = s.getTime();
  776.                 lastG = detector.g(convert(s));
  777.             }
  778.             return lastG;
  779.         }

  780.         /** {@inheritDoc} */
  781.         public ODEEventHandler getHandler() {

  782.             return new ODEEventHandler() {

  783.                 /** {@inheritDoc} */
  784.                 public Action eventOccurred(final ODEStateAndDerivative s, final ODEEventDetector d, final boolean increasing) {
  785.                     return handler.eventOccurred(convert(s), detector, increasing);
  786.                 }

  787.                 /** {@inheritDoc} */
  788.                 public ODEState resetState(final ODEEventDetector d, final ODEStateAndDerivative s) {

  789.                     final SpacecraftState oldState = convert(s);
  790.                     final SpacecraftState newState = handler.resetState(detector, oldState);
  791.                     stateChanged(newState);

  792.                     // main part
  793.                     final double[] primary    = new double[s.getPrimaryStateDimension()];
  794.                     stateMapper.mapStateToArray(newState, primary, null);

  795.                     // secondary part
  796.                     final double[][] secondary = new double[1][secondaryOffsets.get(SECONDARY_DIMENSION)];
  797.                     for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
  798.                         final String name      = provider.getName();
  799.                         final int    offset    = secondaryOffsets.get(name);
  800.                         final int    dimension = provider.getDimension();
  801.                         System.arraycopy(newState.getAdditionalState(name), 0, secondary[0], offset, dimension);
  802.                     }

  803.                     return new ODEState(newState.getDate().durationFrom(getStartDate()),
  804.                                         primary, secondary);

  805.                 }

  806.             };
  807.         }

  808.     }

  809.     /** Adapt an {@link org.orekit.propagation.sampling.OrekitStepHandler}
  810.      * to Hipparchus {@link ODEStepHandler} interface.
  811.      * @author Luc Maisonobe
  812.      */
  813.     private class AdaptedStepHandler implements ODEStepHandler {

  814.         /** Underlying handler. */
  815.         private final OrekitStepHandler handler;

  816.         /** Build an instance.
  817.          * @param handler underlying handler to wrap
  818.          */
  819.         AdaptedStepHandler(final OrekitStepHandler handler) {
  820.             this.handler = handler;
  821.         }

  822.         /** {@inheritDoc} */
  823.         public void init(final ODEStateAndDerivative s0, final double t) {
  824.             handler.init(convert(s0), stateMapper.mapDoubleToDate(t));
  825.         }

  826.         /** {@inheritDoc} */
  827.         @Override
  828.         public void handleStep(final ODEStateInterpolator interpolator) {
  829.             handler.handleStep(new AdaptedStepInterpolator(interpolator));
  830.         }

  831.         /** {@inheritDoc} */
  832.         @Override
  833.         public void finish(final ODEStateAndDerivative finalState) {
  834.             handler.finish(convert(finalState));
  835.         }

  836.     }

  837.     /** Adapt an Hipparchus {@link ODEStateInterpolator}
  838.      * to an orekit {@link OrekitStepInterpolator} interface.
  839.      * @author Luc Maisonobe
  840.      */
  841.     private class AdaptedStepInterpolator implements OrekitStepInterpolator {

  842.         /** Underlying raw rawInterpolator. */
  843.         private final ODEStateInterpolator mathInterpolator;

  844.         /** Simple constructor.
  845.          * @param mathInterpolator underlying raw interpolator
  846.          */
  847.         AdaptedStepInterpolator(final ODEStateInterpolator mathInterpolator) {
  848.             this.mathInterpolator = mathInterpolator;
  849.         }

  850.         /** {@inheritDoc}} */
  851.         @Override
  852.         public SpacecraftState getPreviousState() {
  853.             return convert(mathInterpolator.getPreviousState());
  854.         }

  855.         /** {@inheritDoc}} */
  856.         @Override
  857.         public boolean isPreviousStateInterpolated() {
  858.             return mathInterpolator.isPreviousStateInterpolated();
  859.         }

  860.         /** {@inheritDoc}} */
  861.         @Override
  862.         public SpacecraftState getCurrentState() {
  863.             return convert(mathInterpolator.getCurrentState());
  864.         }

  865.         /** {@inheritDoc}} */
  866.         @Override
  867.         public boolean isCurrentStateInterpolated() {
  868.             return mathInterpolator.isCurrentStateInterpolated();
  869.         }

  870.         /** {@inheritDoc}} */
  871.         @Override
  872.         public SpacecraftState getInterpolatedState(final AbsoluteDate date) {
  873.             return convert(mathInterpolator.getInterpolatedState(date.durationFrom(stateMapper.getReferenceDate())));
  874.         }

  875.         /** {@inheritDoc}} */
  876.         @Override
  877.         public boolean isForward() {
  878.             return mathInterpolator.isForward();
  879.         }

  880.         /** {@inheritDoc}} */
  881.         @Override
  882.         public AdaptedStepInterpolator restrictStep(final SpacecraftState newPreviousState,
  883.                                                     final SpacecraftState newCurrentState) {
  884.             try {
  885.                 final AbstractODEStateInterpolator aosi = (AbstractODEStateInterpolator) mathInterpolator;
  886.                 return new AdaptedStepInterpolator(aosi.restrictStep(convert(newPreviousState),
  887.                                                                      convert(newCurrentState)));
  888.             } catch (ClassCastException cce) {
  889.                 // this should never happen
  890.                 throw new OrekitInternalError(cce);
  891.             }
  892.         }

  893.     }

  894.     /** Specialized step handler storing interpolators for ephemeris generation.
  895.      * @since 11.0
  896.      */
  897.     private class StoringStepHandler implements ODEStepHandler, EphemerisGenerator {

  898.         /** Underlying raw mathematical model. */
  899.         private DenseOutputModel model;

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

  902.         /** Generated ephemeris. */
  903.         private BoundedPropagator ephemeris;

  904.         /** Last interpolator handled by the object.*/
  905.         private  ODEStateInterpolator lastInterpolator;

  906.         /** Set the end date.
  907.          * @param endDate end date
  908.          */
  909.         public void setEndDate(final AbsoluteDate endDate) {
  910.             this.endDate = endDate;
  911.         }

  912.         /** {@inheritDoc} */
  913.         @Override
  914.         public void init(final ODEStateAndDerivative s0, final double t) {

  915.             this.model = new DenseOutputModel();
  916.             model.init(s0, t);

  917.             // ephemeris will be generated when last step is processed
  918.             this.ephemeris = null;

  919.             this.lastInterpolator = null;

  920.         }

  921.         /** {@inheritDoc} */
  922.         @Override
  923.         public BoundedPropagator getGeneratedEphemeris() {
  924.             // Each time we try to get the ephemeris, rebuild it using the last data.
  925.             buildEphemeris();
  926.             return ephemeris;
  927.         }

  928.         /** {@inheritDoc} */
  929.         @Override
  930.         public void handleStep(final ODEStateInterpolator interpolator) {
  931.             model.handleStep(interpolator);
  932.             lastInterpolator = interpolator;
  933.         }

  934.         /** {@inheritDoc} */
  935.         @Override
  936.         public void finish(final ODEStateAndDerivative finalState) {
  937.             buildEphemeris();
  938.         }

  939.         /** Method used to produce ephemeris at a given time.
  940.          * Can be used at multiple times, updating the ephemeris to
  941.          * its last state.
  942.          */
  943.         private void buildEphemeris() {
  944.             // buildEphemeris was built in order to allow access to what was previously the finish method.
  945.             // This now allows to call it through getGeneratedEphemeris, therefore through an external call,
  946.             // which was not previously the case.

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

  949.             // set up the boundary dates
  950.             final double tI = model.getInitialTime();
  951.             final double tF = model.getFinalTime();
  952.             // tI is almost? always zero
  953.             final AbsoluteDate startDate =
  954.                             stateMapper.mapDoubleToDate(tI);
  955.             final AbsoluteDate finalDate =
  956.                             stateMapper.mapDoubleToDate(tF, this.endDate);
  957.             final AbsoluteDate minDate;
  958.             final AbsoluteDate maxDate;
  959.             if (tF < tI) {
  960.                 minDate = finalDate;
  961.                 maxDate = startDate;
  962.             } else {
  963.                 minDate = startDate;
  964.                 maxDate = finalDate;
  965.             }

  966.             // get the initial additional states that are not managed
  967.             final DoubleArrayDictionary unmanaged = new DoubleArrayDictionary();
  968.             for (final DoubleArrayDictionary.Entry initial : getInitialState().getAdditionalStatesValues().getData()) {
  969.                 if (!isAdditionalStateManaged(initial.getKey())) {
  970.                     // this additional state was in the initial state, but is unknown to the propagator
  971.                     // we simply copy its initial value as is
  972.                     unmanaged.put(initial.getKey(), initial.getValue());
  973.                 }
  974.             }

  975.             // get the names of additional states managed by differential equations
  976.             final String[] names      = new String[additionalDerivativesProviders.size()];
  977.             final int[]    dimensions = new int[additionalDerivativesProviders.size()];
  978.             for (int i = 0; i < names.length; ++i) {
  979.                 names[i] = additionalDerivativesProviders.get(i).getName();
  980.                 dimensions[i] = additionalDerivativesProviders.get(i).getDimension();
  981.             }

  982.             // create the ephemeris
  983.             ephemeris = new IntegratedEphemeris(startDate, minDate, maxDate,
  984.                                                 stateMapper, propagationType, model,
  985.                                                 unmanaged, getAdditionalStateProviders(),
  986.                                                 names, dimensions);

  987.         }

  988.     }

  989.     /** Wrapper for resetting an integrator handlers.
  990.      * <p>
  991.      * This class is intended to be used in a try-with-resource statement.
  992.      * If propagator-specific event handlers and step handlers are added to
  993.      * the integrator in the try block, they will be removed automatically
  994.      * when leaving the block, so the integrator only keeps its own handlers
  995.      * between calls to {@link AbstractIntegratedPropagator#propagate(AbsoluteDate, AbsoluteDate).
  996.      * </p>
  997.      * @since 11.0
  998.      */
  999.     private static class IntegratorResetter implements AutoCloseable {

  1000.         /** Wrapped integrator. */
  1001.         private final ODEIntegrator integrator;

  1002.         /** Initial event detectors list. */
  1003.         private final List<ODEEventDetector> detectors;

  1004.         /** Initial step handlers list. */
  1005.         private final List<ODEStepHandler> stepHandlers;

  1006.         /** Simple constructor.
  1007.          * @param integrator wrapped integrator
  1008.          */
  1009.         IntegratorResetter(final ODEIntegrator integrator) {
  1010.             this.integrator   = integrator;
  1011.             this.detectors    = new ArrayList<>(integrator.getEventDetectors());
  1012.             this.stepHandlers = new ArrayList<>(integrator.getStepHandlers());
  1013.         }

  1014.         /** {@inheritDoc}
  1015.          * <p>
  1016.          * Reset event handlers and step handlers back to the initial list
  1017.          * </p>
  1018.          */
  1019.         @Override
  1020.         public void close() {

  1021.             // reset event handlers
  1022.             integrator.clearEventDetectors();
  1023.             detectors.forEach(integrator::addEventDetector);

  1024.             // reset step handlers
  1025.             integrator.clearStepHandlers();
  1026.             stepHandlers.forEach(integrator::addStepHandler);

  1027.         }

  1028.     }

  1029. }