1   /* Copyright 2002-2025 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  
19  import org.hipparchus.analysis.UnivariateFunction;
20  import org.hipparchus.analysis.solvers.BracketedUnivariateSolver;
21  import org.hipparchus.analysis.solvers.BracketingNthOrderBrentSolver;
22  import org.hipparchus.exception.MathRuntimeException;
23  import org.hipparchus.ode.DenseOutputModel;
24  import org.hipparchus.ode.ExpandableODE;
25  import org.hipparchus.ode.ODEIntegrator;
26  import org.hipparchus.ode.ODEState;
27  import org.hipparchus.ode.ODEStateAndDerivative;
28  import org.hipparchus.ode.OrdinaryDifferentialEquation;
29  import org.hipparchus.ode.SecondaryODE;
30  import org.hipparchus.ode.events.Action;
31  import org.hipparchus.ode.events.AdaptableInterval;
32  import org.hipparchus.ode.events.ODEEventDetector;
33  import org.hipparchus.ode.events.ODEEventHandler;
34  import org.hipparchus.ode.sampling.AbstractODEStateInterpolator;
35  import org.hipparchus.ode.sampling.ODEStateInterpolator;
36  import org.hipparchus.ode.sampling.ODEStepHandler;
37  import org.hipparchus.util.Precision;
38  import org.orekit.attitudes.AttitudeProvider;
39  import org.orekit.attitudes.AttitudeProviderModifier;
40  import org.orekit.errors.OrekitException;
41  import org.orekit.errors.OrekitInternalError;
42  import org.orekit.errors.OrekitMessages;
43  import org.orekit.frames.Frame;
44  import org.orekit.orbits.OrbitType;
45  import org.orekit.orbits.PositionAngleType;
46  import org.orekit.propagation.AbstractPropagator;
47  import org.orekit.propagation.BoundedPropagator;
48  import org.orekit.propagation.EphemerisGenerator;
49  import org.orekit.propagation.PropagationType;
50  import org.orekit.propagation.SpacecraftState;
51  import org.orekit.propagation.events.EventDetector;
52  import org.orekit.propagation.events.handlers.EventHandler;
53  import org.orekit.propagation.sampling.OrekitStepHandler;
54  import org.orekit.propagation.sampling.OrekitStepInterpolator;
55  import org.orekit.time.AbsoluteDate;
56  import org.orekit.utils.DataDictionary;
57  import org.orekit.utils.DoubleArrayDictionary;
58  
59  import java.util.ArrayList;
60  import java.util.Arrays;
61  import java.util.Collection;
62  import java.util.Collections;
63  import java.util.HashMap;
64  import java.util.LinkedList;
65  import java.util.List;
66  import java.util.Map;
67  import java.util.Queue;
68  
69  
70  /** Common handling of {@link org.orekit.propagation.Propagator Propagator}
71   *  methods for both numerical and semi-analytical propagators.
72   *  @author Luc Maisonobe
73   */
74  public abstract class AbstractIntegratedPropagator extends AbstractPropagator {
75  
76      /** Internal name used for complete secondary state dimension.
77       * @since 11.1
78       */
79      private static final String SECONDARY_DIMENSION = "Orekit-secondary-dimension";
80  
81      /** Event detectors not related to force models. */
82      private final List<EventDetector> detectors;
83  
84      /** Step handlers dedicated to ephemeris generation. */
85      private final List<StoringStepHandler> ephemerisGenerators;
86  
87      /** Integrator selected by the user for the orbital extrapolation process. */
88      private final ODEIntegrator integrator;
89  
90      /** Offsets of secondary states managed by {@link AdditionalDerivativesProvider}.
91       * @since 11.1
92       */
93      private final Map<String, Integer> secondaryOffsets;
94  
95      /** Additional derivatives providers.
96       * @since 11.1
97       */
98      private final List<AdditionalDerivativesProvider> additionalDerivativesProviders;
99  
100     /** Map of secondary equation offset in main
101     /** Counter for differential equations calls. */
102     private int calls;
103 
104     /** Mapper between raw double components and space flight dynamics objects. */
105     private StateMapper stateMapper;
106 
107     /**
108      * Attitude provider when evaluating derivatives. Can be a frozen one for performance.
109      * @since 12.1
110      */
111     private AttitudeProvider attitudeProviderForDerivatives;
112 
113     /**
114      * Attitude provider with frozen rates, used when possible for performance.
115      * @since 13.1
116      */
117     private AttitudeProvider frozenAttitudeProvider;
118 
119     /** Flag for resetting the state at end of propagation. */
120     private boolean resetAtEnd;
121 
122     /** Type of orbit to output (mean or osculating) <br/>
123      * <p>
124      * This is used only in the case of semi-analytical propagators where there is a clear separation between
125      * mean and short periodic elements. It is ignored by the Numerical propagator.
126      * </p>
127      */
128     private final PropagationType propagationType;
129 
130     /** Build a new instance.
131      * @param integrator numerical integrator to use for propagation.
132      * @param propagationType type of orbit to output (mean or osculating).
133      */
134     protected AbstractIntegratedPropagator(final ODEIntegrator integrator, final PropagationType propagationType) {
135         detectors                      = new ArrayList<>();
136         ephemerisGenerators            = new ArrayList<>();
137         additionalDerivativesProviders = new ArrayList<>();
138         this.secondaryOffsets          = new HashMap<>();
139         this.integrator                = integrator;
140         this.propagationType           = propagationType;
141         this.resetAtEnd                = true;
142     }
143 
144     /** Allow/disallow resetting the initial state at end of propagation.
145      * <p>
146      * By default, at the end of the propagation, the propagator resets the initial state
147      * to the final state, thus allowing a new propagation to be started from there without
148      * recomputing the part already performed. Calling this method with {@code resetAtEnd} set
149      * to false changes prevents such reset.
150      * </p>
151      * @param resetAtEnd if true, at end of each propagation, the {@link
152      * #getInitialState() initial state} will be reset to the final state of
153      * the propagation, otherwise the initial state will be preserved
154      * @since 9.0
155      */
156     public void setResetAtEnd(final boolean resetAtEnd) {
157         this.resetAtEnd = resetAtEnd;
158     }
159 
160     /** Getter for the resetting flag regarding initial state.
161      * @return resetting flag
162      * @since 12.0
163      */
164     public boolean getResetAtEnd() {
165         return this.resetAtEnd;
166     }
167 
168     /**
169      * Getter for the frozen attitude provider, used for performance when possible.
170      * @return frozen attitude provider
171      * @since 13.1
172      */
173     protected AttitudeProvider getFrozenAttitudeProvider() {
174         return frozenAttitudeProvider;
175     }
176 
177     /**
178      * Method called when initializing the attitude provider used when evaluating derivatives.
179      * @return attitude provider for derivatives
180      */
181     protected AttitudeProvider initializeAttitudeProviderForDerivatives() {
182         return getAttitudeProvider();
183     }
184 
185     /** Initialize the mapper. */
186     protected void initMapper() {
187         stateMapper = createMapper(null, Double.NaN, null, null, null, null);
188     }
189 
190     /** Get the integrator's name.
191      * @return name of underlying integrator
192      * @since 12.0
193      */
194     public String getIntegratorName() {
195         return integrator.getName();
196     }
197 
198     /**  {@inheritDoc} */
199     @Override
200     public void setAttitudeProvider(final AttitudeProvider attitudeProvider) {
201         super.setAttitudeProvider(attitudeProvider);
202         frozenAttitudeProvider = AttitudeProviderModifier.getFrozenAttitudeProvider(attitudeProvider);
203         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
204                                    stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
205                                    attitudeProvider, stateMapper.getFrame());
206     }
207 
208     /** Set propagation orbit type.
209      * @param orbitType orbit type to use for propagation, null for
210      * propagating using {@link org.orekit.utils.AbsolutePVCoordinates AbsolutePVCoordinates}
211      * rather than {@link org.orekit.orbits Orbit}
212      */
213     protected void setOrbitType(final OrbitType orbitType) {
214         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
215                                    orbitType, stateMapper.getPositionAngleType(),
216                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
217     }
218 
219     /** Get propagation parameter type.
220      * @return orbit type used for propagation, null for
221      * propagating using {@link org.orekit.utils.AbsolutePVCoordinates AbsolutePVCoordinates}
222      * rather than {@link org.orekit.orbits Orbit}
223      */
224     protected OrbitType getOrbitType() {
225         return stateMapper.getOrbitType();
226     }
227 
228     /** Get the propagation type.
229      * @return propagation type.
230      * @since 11.1
231      */
232     public PropagationType getPropagationType() {
233         return propagationType;
234     }
235 
236     /** Set position angle type.
237      * <p>
238      * The position parameter type is meaningful only if {@link
239      * #getOrbitType() propagation orbit type}
240      * support it. As an example, it is not meaningful for propagation
241      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
242      * </p>
243      * @param positionAngleType angle type to use for propagation
244      */
245     protected void setPositionAngleType(final PositionAngleType positionAngleType) {
246         stateMapper = createMapper(stateMapper.getReferenceDate(), stateMapper.getMu(),
247                                    stateMapper.getOrbitType(), positionAngleType,
248                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
249     }
250 
251     /** Get propagation parameter type.
252      * @return angle type to use for propagation
253      */
254     protected PositionAngleType getPositionAngleType() {
255         return stateMapper.getPositionAngleType();
256     }
257 
258     /** Set the central attraction coefficient μ.
259      * @param mu central attraction coefficient (m³/s²)
260      */
261     public void setMu(final double mu) {
262         stateMapper = createMapper(stateMapper.getReferenceDate(), mu,
263                                    stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
264                                    stateMapper.getAttitudeProvider(), stateMapper.getFrame());
265     }
266 
267     /** Get the central attraction coefficient μ.
268      * @return mu central attraction coefficient (m³/s²)
269      * @see #setMu(double)
270      */
271     public double getMu() {
272         return stateMapper.getMu();
273     }
274 
275     /** Get the number of calls to the differential equations computation method.
276      * <p>The number of calls is reset each time the {@link #propagate(AbsoluteDate)}
277      * method is called.</p>
278      * @return number of calls to the differential equations computation method
279      */
280     public int getCalls() {
281         return calls;
282     }
283 
284     /** {@inheritDoc} */
285     @Override
286     public boolean isAdditionalDataManaged(final String name) {
287 
288         // first look at already integrated states
289         if (super.isAdditionalDataManaged(name)) {
290             return true;
291         }
292 
293         // then look at states we integrate ourselves
294         for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
295             if (provider.getName().equals(name)) {
296                 return true;
297             }
298         }
299 
300         return false;
301     }
302 
303     /** {@inheritDoc} */
304     @Override
305     public String[] getManagedAdditionalData() {
306         final String[] alreadyIntegrated = super.getManagedAdditionalData();
307         final String[] managed = new String[alreadyIntegrated.length + additionalDerivativesProviders.size()];
308         System.arraycopy(alreadyIntegrated, 0, managed, 0, alreadyIntegrated.length);
309         for (int i = 0; i < additionalDerivativesProviders.size(); ++i) {
310             managed[i + alreadyIntegrated.length] = additionalDerivativesProviders.get(i).getName();
311         }
312         return managed;
313     }
314 
315     /** Add a provider for user-specified state derivatives to be integrated along with the orbit propagation.
316      * @param provider provider for additional derivatives
317      * @see #addAdditionalDataProvider(org.orekit.propagation.AdditionalDataProvider)
318      * @since 11.1
319      */
320     public void addAdditionalDerivativesProvider(final AdditionalDerivativesProvider provider) {
321 
322         // check if the name is already used
323         if (this.isAdditionalDataManaged(provider.getName())) {
324             // these derivatives are already registered, complain
325             throw new OrekitException(OrekitMessages.ADDITIONAL_STATE_NAME_ALREADY_IN_USE,
326                                       provider.getName());
327         }
328 
329         // this is really a new set of derivatives, add it
330         additionalDerivativesProviders.add(provider);
331 
332         secondaryOffsets.clear();
333 
334     }
335 
336     /** Get an unmodifiable list of providers for additional derivatives.
337      * @return providers for the additional derivatives
338      * @since 11.1
339      */
340     public List<AdditionalDerivativesProvider> getAdditionalDerivativesProviders() {
341         return Collections.unmodifiableList(additionalDerivativesProviders);
342     }
343 
344     /**
345      * Remove additional derivatives provider.
346      * @param name provider's name.
347      * @since 13.1
348      */
349     protected void removeAdditionalDerivativesProvider(final String name) {
350         additionalDerivativesProviders.removeIf(provider -> provider.getName().equals(name));
351     }
352 
353     /** {@inheritDoc} */
354     public void addEventDetector(final EventDetector detector) {
355         detectors.add(detector);
356     }
357 
358     /** {@inheritDoc} */
359     public Collection<EventDetector> getEventDetectors() {
360         return Collections.unmodifiableCollection(detectors);
361     }
362 
363     /** {@inheritDoc} */
364     public void clearEventsDetectors() {
365         detectors.clear();
366     }
367 
368     /** Set up all user defined event detectors.
369      */
370     protected void setUpUserEventDetectors() {
371         for (final EventDetector detector : detectors) {
372             setUpEventDetector(integrator, detector);
373         }
374     }
375 
376     /** Wrap an Orekit event detector and register it to the integrator.
377      * @param integ integrator into which event detector should be registered
378      * @param detector event detector to wrap
379      */
380     protected void setUpEventDetector(final ODEIntegrator integ, final EventDetector detector) {
381         integ.addEventDetector(new AdaptedEventDetector(detector));
382     }
383 
384     /**
385      * Clear the ephemeris generators.
386      * @since 13.0
387      */
388     public void clearEphemerisGenerators() {
389         ephemerisGenerators.clear();
390     }
391 
392     /** {@inheritDoc} */
393     @Override
394     public EphemerisGenerator getEphemerisGenerator() {
395         final StoringStepHandler storingHandler = new StoringStepHandler();
396         ephemerisGenerators.add(storingHandler);
397         return storingHandler;
398     }
399 
400     /** Create a mapper between raw double components and spacecraft state.
401     /** Simple constructor.
402      * <p>
403      * The position parameter type is meaningful only if {@link
404      * #getOrbitType() propagation orbit type}
405      * support it. As an example, it is not meaningful for propagation
406      * in {@link OrbitType#CARTESIAN Cartesian} parameters.
407      * </p>
408      * @param referenceDate reference date
409      * @param mu central attraction coefficient (m³/s²)
410      * @param orbitType orbit type to use for mapping
411      * @param positionAngleType angle type to use for propagation
412      * @param attitudeProvider attitude provider
413      * @param frame inertial frame
414      * @return new mapper
415      */
416     protected abstract StateMapper createMapper(AbsoluteDate referenceDate, double mu,
417                                                 OrbitType orbitType, PositionAngleType positionAngleType,
418                                                 AttitudeProvider attitudeProvider, Frame frame);
419 
420     /** Get the differential equations to integrate (for main state only).
421      * @param integ numerical integrator to use for propagation.
422      * @return differential equations for main state
423      */
424     protected abstract MainStateEquations getMainStateEquations(ODEIntegrator integ);
425 
426     /** {@inheritDoc} */
427     @Override
428     public SpacecraftState propagate(final AbsoluteDate target) {
429         if (getStartDate() == null) {
430             if (getInitialState() == null) {
431                 throw new OrekitException(OrekitMessages.INITIAL_STATE_NOT_SPECIFIED_FOR_ORBIT_PROPAGATION);
432             }
433             setStartDate(getInitialState().getDate());
434         }
435         return propagate(getStartDate(), target);
436     }
437 
438     /** {@inheritDoc} */
439     public SpacecraftState propagate(final AbsoluteDate tStart, final AbsoluteDate tEnd) {
440 
441         if (getInitialState() == null) {
442             throw new OrekitException(OrekitMessages.INITIAL_STATE_NOT_SPECIFIED_FOR_ORBIT_PROPAGATION);
443         }
444 
445         // make sure the integrator will be reset properly even if we change its events handlers and step handlers
446         try (IntegratorResetter resetter = new IntegratorResetter(integrator)) {
447 
448             // prepare handling of STM and Jacobian matrices
449             setUpStmAndJacobianGenerators();
450 
451             // Initialize additional data
452             initializeAdditionalData(tEnd);
453 
454             if (!tStart.equals(getInitialState().getDate())) {
455                 // if propagation start date is not initial date,
456                 // propagate from initial to start date without event detection
457                 try (IntegratorResetter startResetter = new IntegratorResetter(integrator)) {
458                     integrateDynamics(tStart, true);
459                 }
460             }
461 
462             // set up events added by user
463             setUpUserEventDetectors();
464 
465             // set up step handlers
466             for (final OrekitStepHandler handler : getMultiplexer().getHandlers()) {
467                 integrator.addStepHandler(new AdaptedStepHandler(handler));
468             }
469             for (final StoringStepHandler generator : ephemerisGenerators) {
470                 generator.setEndDate(tEnd);
471                 integrator.addStepHandler(generator);
472             }
473 
474             // propagate from start date to end date with event detection
475             final SpacecraftState finalState = integrateDynamics(tEnd, false);
476 
477             // Finalize event detectors
478             getEventDetectors().forEach(detector -> detector.finish(finalState));
479 
480             return finalState;
481         }
482 
483     }
484 
485     /** Reset initial state with a given propagation type.
486      *
487      * <p> By default this method returns the same as {@link #resetInitialState(SpacecraftState)}
488      * <p> Its purpose is mostly to be derived in DSSTPropagator
489      *
490      * @param state new initial state to consider
491      * @param stateType type of the new state (mean or osculating)
492      * @since 12.1.3
493      */
494     public void resetInitialState(final SpacecraftState state, final PropagationType stateType) {
495         // Default behavior, do not take propagation type into account
496         resetInitialState(state);
497     }
498 
499     /** Set up State Transition Matrix and Jacobian matrix handling.
500      * @since 11.1
501      */
502     protected void setUpStmAndJacobianGenerators() {
503         // nothing to do by default
504     }
505 
506     @Override
507     public void clearMatricesComputation() {
508         secondaryOffsets.clear();
509         super.clearMatricesComputation();
510     }
511 
512     /** Propagation with or without event detection.
513      * @param tEnd target date to which orbit should be propagated
514      * @param forceResetAtEnd flag to force resetting state and date after integration
515      * @return state at end of propagation
516      */
517     private SpacecraftState integrateDynamics(final AbsoluteDate tEnd, final boolean forceResetAtEnd) {
518         try {
519 
520             initializePropagation();
521 
522             if (getInitialState().getDate().equals(tEnd)) {
523                 // don't extrapolate
524                 return getInitialState();
525             }
526 
527             // space dynamics view
528             stateMapper = createMapper(getInitialState().getDate(), stateMapper.getMu(),
529                                        stateMapper.getOrbitType(), stateMapper.getPositionAngleType(),
530                                        stateMapper.getAttitudeProvider(), getInitialState().getFrame());
531             attitudeProviderForDerivatives = initializeAttitudeProviderForDerivatives();
532 
533             if (Double.isNaN(getMu())) {
534                 setMu(getInitialState().isOrbitDefined() ? getInitialState().getOrbit().getMu() : Double.NaN);
535             }
536 
537             if (getInitialState().getMass() <= 0.0) {
538                 throw new OrekitException(OrekitMessages.NOT_POSITIVE_SPACECRAFT_MASS,
539                                           getInitialState().getMass());
540             }
541 
542             // convertFromOrekit space flight dynamics API to math API
543             final SpacecraftState initialIntegrationState = getInitialIntegrationState();
544             final ODEState mathInitialState = createInitialState(initialIntegrationState);
545             final ExpandableODE mathODE = createODE(integrator);
546 
547             // mathematical integration
548             final ODEStateAndDerivative mathFinalState;
549             beforeIntegration(initialIntegrationState, tEnd);
550             mathFinalState = integrator.integrate(mathODE, mathInitialState,
551                                                   tEnd.durationFrom(getInitialState().getDate()));
552             afterIntegration();
553 
554             // get final state
555             SpacecraftState finalState =
556                             stateMapper.mapArrayToState(stateMapper.mapDoubleToDate(mathFinalState.getTime(),
557                                                                                     tEnd),
558                                                         mathFinalState.getPrimaryState(),
559                                                         mathFinalState.getPrimaryDerivative(),
560                                                         propagationType);
561 
562             finalState = updateAdditionalStatesAndDerivatives(finalState, mathFinalState);
563 
564             if (resetAtEnd || forceResetAtEnd) {
565                 resetInitialState(finalState, propagationType);
566                 setStartDate(finalState.getDate());
567             }
568 
569             return finalState;
570 
571         } catch (MathRuntimeException mre) {
572             throw OrekitException.unwrap(mre);
573         }
574     }
575 
576     /**
577      * Returns an updated version of the inputted state with additional states, including
578      * from derivatives providers.
579      * @param originalState input state
580      * @param os ODE state and derivative
581      * @return new state
582      * @since 12.1
583      */
584     private SpacecraftState updateAdditionalStatesAndDerivatives(final SpacecraftState originalState,
585                                                                  final ODEStateAndDerivative os) {
586         SpacecraftState updatedState = originalState;
587         if (os.getNumberOfSecondaryStates() > 0) {
588             final double[] secondary           = os.getSecondaryState(1);
589             final double[] secondaryDerivative = os.getSecondaryDerivative(1);
590             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
591                 final String name      = provider.getName();
592                 final int    offset    = secondaryOffsets.get(name);
593                 final int    dimension = provider.getDimension();
594                 updatedState = updatedState.addAdditionalData(name, Arrays.copyOfRange(secondary, offset, offset + dimension));
595                 updatedState = updatedState.addAdditionalStateDerivative(name, Arrays.copyOfRange(secondaryDerivative, offset, offset + dimension));
596             }
597         }
598         return updateAdditionalData(updatedState);
599     }
600 
601     /** Get the initial state for integration.
602      * @return initial state for integration
603      */
604     protected SpacecraftState getInitialIntegrationState() {
605         return getInitialState();
606     }
607 
608     /** Create an initial state.
609      * @param initialState initial state in flight dynamics world
610      * @return initial state in mathematics world
611      */
612     private ODEState createInitialState(final SpacecraftState initialState) {
613 
614         // retrieve initial state
615         final double[] primary = new double[getBasicDimension()];
616         stateMapper.mapStateToArray(initialState, primary, null);
617 
618         if (secondaryOffsets.isEmpty()) {
619             // compute dimension of the secondary state
620             int offset = 0;
621             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
622                 secondaryOffsets.put(provider.getName(), offset);
623                 offset += provider.getDimension();
624             }
625             secondaryOffsets.put(SECONDARY_DIMENSION, offset);
626         }
627 
628         return new ODEState(0.0, primary, secondary(initialState));
629 
630     }
631 
632     /** Create secondary state.
633      * @param state spacecraft state
634      * @return secondary state
635      * @since 11.1
636      */
637     private double[][] secondary(final SpacecraftState state) {
638 
639         if (secondaryOffsets.isEmpty()) {
640             return null;
641         }
642 
643         final double[][] secondary = new double[1][secondaryOffsets.get(SECONDARY_DIMENSION)];
644         for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
645             final String   name       = provider.getName();
646             final int      offset     = secondaryOffsets.get(name);
647             final double[] additional = state.getAdditionalState(name);
648             System.arraycopy(additional, 0, secondary[0], offset, additional.length);
649         }
650 
651         return secondary;
652 
653     }
654 
655     /** Create an ODE with all equations.
656      * @param integ numerical integrator to use for propagation.
657      * @return a new ode
658      */
659     private ExpandableODE createODE(final ODEIntegrator integ) {
660 
661         final ExpandableODE ode =
662                 new ExpandableODE(new ConvertedMainStateEquations(getMainStateEquations(integ)));
663 
664         // secondary part of the ODE
665         if (!additionalDerivativesProviders.isEmpty()) {
666             ode.addSecondaryEquations(new ConvertedSecondaryStateEquations());
667         }
668 
669         return ode;
670 
671     }
672 
673     /** Method called just before integration.
674      * <p>
675      * The default implementation does nothing, it may be specialized in subclasses.
676      * </p>
677      * @param initialState initial state
678      * @param tEnd target date at which state should be propagated
679      */
680     protected void beforeIntegration(final SpacecraftState initialState,
681                                      final AbsoluteDate tEnd) {
682         // do nothing by default
683     }
684 
685     /** Method called just after integration.
686      * <p>
687      * The default implementation does nothing, it may be specialized in subclasses.
688      * </p>
689      */
690     protected void afterIntegration() {
691         // do nothing by default
692     }
693 
694     /** Get state vector dimension without additional parameters.
695      * @return state vector dimension without additional parameters.
696      */
697     public int getBasicDimension() {
698         return 7;
699     }
700 
701     /** Get the integrator used by the propagator.
702      * @return the integrator.
703      */
704     protected ODEIntegrator getIntegrator() {
705         return integrator;
706     }
707 
708     /** Convert a state from mathematical world to space flight dynamics world.
709      * @param os mathematical state
710      * @return space flight dynamics state
711      */
712     private SpacecraftState convertToOrekitWithAdditional(final ODEStateAndDerivative os) {
713         final SpacecraftState s = convertToOrekitWithoutAdditional(os);
714         return updateAdditionalStatesAndDerivatives(s, os);
715     }
716 
717     /** Convert a state from mathematical world to space flight dynamics world without additional data and derivatives.
718      * @param os mathematical state
719      * @return space flight dynamics state
720      * @since 13.1
721      */
722     private SpacecraftState convertToOrekitWithoutAdditional(final ODEStateAndDerivative os) {
723         return stateMapper.mapArrayToState(os.getTime(), os.getPrimaryState(),
724             os.getPrimaryDerivative(), propagationType);
725     }
726 
727     /** Differential equations for the main state (orbit, attitude and mass). */
728     public interface MainStateEquations {
729 
730         /**
731          * Initialize the equations at the start of propagation. This method will be
732          * called before any calls to {@link #computeDerivatives(SpacecraftState)}.
733          *
734          * <p> The default implementation of this method does nothing.
735          *
736          * @param initialState initial state information at the start of propagation.
737          * @param target       date of propagation. Not equal to {@code
738          *                     initialState.getDate()}.
739          */
740         default void init(final SpacecraftState initialState, final AbsoluteDate target) {
741         }
742 
743         /** Compute differential equations for main state.
744          * @param state current state
745          * @return derivatives of main state
746          */
747         double[] computeDerivatives(SpacecraftState state);
748 
749     }
750 
751     /** Differential equations for the main state (orbit, attitude and mass), with converted API. */
752     private class ConvertedMainStateEquations implements OrdinaryDifferentialEquation {
753 
754         /** Main state equations. */
755         private final MainStateEquations main;
756 
757         /** Simple constructor.
758          * @param main main state equations
759          */
760         ConvertedMainStateEquations(final MainStateEquations main) {
761             this.main = main;
762             calls = 0;
763         }
764 
765         /** {@inheritDoc} */
766         public int getDimension() {
767             return getBasicDimension();
768         }
769 
770         @Override
771         public void init(final double t0, final double[] y0, final double finalTime) {
772             // update space dynamics view
773             SpacecraftState initialState = stateMapper.mapArrayToState(t0, y0, null, PropagationType.MEAN);
774             initialState = updateAdditionalData(initialState);
775             initialState = updateStatesFromAdditionalDerivativesIfKnown(initialState);
776             final AbsoluteDate target = stateMapper.mapDoubleToDate(finalTime);
777             main.init(initialState, target);
778             attitudeProviderForDerivatives = initializeAttitudeProviderForDerivatives();
779         }
780 
781         /**
782          * Returns an updated version of the inputted state, with additional states from
783          * derivatives providers as given in the stored initial state.
784          * @param originalState input state
785          * @return new state
786          * @since 12.1
787          */
788         private SpacecraftState updateStatesFromAdditionalDerivativesIfKnown(final SpacecraftState originalState) {
789             SpacecraftState updatedState = originalState;
790             final SpacecraftState storedInitialState = getInitialState();
791             final double originalTime = stateMapper.mapDateToDouble(originalState.getDate());
792             if (storedInitialState != null && stateMapper.mapDateToDouble(storedInitialState.getDate()) == originalTime) {
793                 for (final AdditionalDerivativesProvider provider: additionalDerivativesProviders) {
794                     final String name = provider.getName();
795                     final double[] value = storedInitialState.getAdditionalState(name);
796                     updatedState = updatedState.addAdditionalData(name, value);
797                 }
798             }
799             return updatedState;
800         }
801 
802         /** {@inheritDoc} */
803         public double[] computeDerivatives(final double t, final double[] y) {
804 
805             // increment calls counter
806             ++calls;
807 
808             // update space dynamics view
809             stateMapper.setAttitudeProvider(attitudeProviderForDerivatives);
810             SpacecraftState currentState = stateMapper.mapArrayToState(t, y, null, PropagationType.MEAN);
811             stateMapper.setAttitudeProvider(getAttitudeProvider());
812 
813             currentState = updateAdditionalData(currentState);
814             // compute main state differentials
815             return main.computeDerivatives(currentState);
816 
817         }
818 
819     }
820 
821     /** Differential equations for the secondary state (Jacobians, user variables ...), with converted API. */
822     private class ConvertedSecondaryStateEquations implements SecondaryODE {
823 
824         /** Dimension of the combined additional states. */
825         private final int combinedDimension;
826 
827         /** Simple constructor.
828           */
829         ConvertedSecondaryStateEquations() {
830             this.combinedDimension = secondaryOffsets.get(SECONDARY_DIMENSION);
831         }
832 
833         /** {@inheritDoc} */
834         @Override
835         public int getDimension() {
836             return combinedDimension;
837         }
838 
839         /** {@inheritDoc} */
840         @Override
841         public void init(final double t0, final double[] primary0,
842                          final double[] secondary0, final double finalTime) {
843             // update space dynamics view
844             final SpacecraftState initialState = convert(t0, primary0, null, secondary0);
845 
846             final AbsoluteDate target = stateMapper.mapDoubleToDate(finalTime);
847             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
848                 provider.init(initialState, target);
849             }
850 
851         }
852 
853         /** {@inheritDoc} */
854         @Override
855         public double[] computeDerivatives(final double t, final double[] primary,
856                                            final double[] primaryDot, final double[] secondary) {
857 
858             // update space dynamics view
859             // the integrable generators generate method will be called here,
860             // according to the generators yield order
861             SpacecraftState updated = convert(t, primary, primaryDot, secondary);
862 
863             // set up queue for equations
864             final Queue<AdditionalDerivativesProvider> pending = new LinkedList<>(additionalDerivativesProviders);
865 
866             // gather the derivatives from all additional equations, taking care of dependencies
867             final double[] secondaryDot = new double[combinedDimension];
868             final DoubleArrayDictionary derivativesDictionary = new DoubleArrayDictionary();
869             int yieldCount = 0;
870             while (!pending.isEmpty()) {
871                 final AdditionalDerivativesProvider provider = pending.remove();
872                 if (provider.yields(updated)) {
873                     // this provider has to wait for another one,
874                     // we put it again in the pending queue
875                     pending.add(provider);
876                     if (++yieldCount >= pending.size()) {
877                         // all pending providers yielded!, they probably need data not yet initialized
878                         // we let the propagation proceed, if these data are really needed right now
879                         // an appropriate exception will be triggered when caller tries to access them
880                         break;
881                     }
882                 } else {
883                     // we can use these equations right now
884                     final String              name           = provider.getName();
885                     final int                 offset         = secondaryOffsets.get(name);
886                     final int                 dimension      = provider.getDimension();
887                     final CombinedDerivatives derivatives    = provider.combinedDerivatives(updated);
888                     final double[]            additionalPart = derivatives.getAdditionalDerivatives();
889                     final double[]            mainPart       = derivatives.getMainStateDerivativesIncrements();
890                     System.arraycopy(additionalPart, 0, secondaryDot, offset, dimension);
891                     derivativesDictionary.put(name, additionalPart);
892                     updated = updated.withAdditionalStatesDerivatives(derivativesDictionary);
893                     if (mainPart != null) {
894                         // this equation does change the main state derivatives
895                         for (int i = 0; i < mainPart.length; ++i) {
896                             primaryDot[i] += mainPart[i];
897                         }
898                     }
899                     yieldCount = 0;
900                 }
901             }
902 
903             return secondaryDot;
904 
905         }
906 
907         /** Convert mathematical view to space view.
908          * @param t current value of the independent <I>time</I> variable
909          * @param primary array containing the current value of the primary state vector
910          * @param primaryDot array containing the derivative of the primary state vector
911          * @param secondary array containing the current value of the secondary state vector
912          * @return space view of the state
913          */
914         private SpacecraftState convert(final double t, final double[] primary,
915                                         final double[] primaryDot, final double[] secondary) {
916 
917             final SpacecraftState initialState = stateMapper.mapArrayToState(t, primary, primaryDot, PropagationType.MEAN);
918 
919             final DataDictionary additionalStateDictionary = new DataDictionary();
920             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
921                 final String name      = provider.getName();
922                 final int    offset    = secondaryOffsets.get(name);
923                 final int    dimension = provider.getDimension();
924                 additionalStateDictionary.put(name, Arrays.copyOfRange(secondary, offset, offset + dimension));
925             }
926 
927             return updateAdditionalData(initialState.withAdditionalData(additionalStateDictionary));
928 
929         }
930 
931     }
932 
933     /** Adapt an {@link org.orekit.propagation.events.EventDetector}
934      * to Hipparchus {@link org.hipparchus.ode.events.ODEEventDetector} interface.
935      * @author Fabien Maussion
936      */
937     private class AdaptedEventDetector implements ODEEventDetector {
938 
939         /** Underlying event detector. */
940         private final EventDetector detector;
941 
942         /** Underlying event handler.
943          * @since 12.0
944          */
945         private final EventHandler handler;
946 
947         /** Time of the previous call to g. */
948         private double lastT;
949 
950         /** Value from the previous call to g. */
951         private double lastG;
952 
953         /** Build a wrapped event detector.
954          * @param detector event detector to wrap
955         */
956         AdaptedEventDetector(final EventDetector detector) {
957             this.detector = detector;
958             this.handler  = detector.getHandler();
959             this.lastT    = Double.NaN;
960             this.lastG    = Double.NaN;
961         }
962 
963         /** {@inheritDoc} */
964         @Override
965         public AdaptableInterval getMaxCheckInterval() {
966             return (state, isForward) -> detector.getMaxCheckInterval().currentInterval(convertToOrekitForEventFunction(state), isForward);
967         }
968 
969         /** {@inheritDoc} */
970         @Override
971         public int getMaxIterationCount() {
972             return detector.getMaxIterationCount();
973         }
974 
975         /** {@inheritDoc} */
976         @Override
977         public BracketedUnivariateSolver<UnivariateFunction> getSolver() {
978             return new BracketingNthOrderBrentSolver(0, detector.getThreshold(), 0, 5);
979         }
980 
981         /** {@inheritDoc} */
982         @Override
983         public void init(final ODEStateAndDerivative s0, final double t) {
984             detector.init(convertToOrekitWithAdditional(s0), stateMapper.mapDoubleToDate(t));
985             this.lastT = Double.NaN;
986             this.lastG = Double.NaN;
987         }
988 
989         /** {@inheritDoc} */
990         @Override
991         public void reset(final ODEStateAndDerivative intermediateState, final double finalTime) {
992             detector.reset(convertToOrekitForEventFunction(intermediateState), stateMapper.mapDoubleToDate(finalTime));
993             this.lastT = Double.NaN;
994             this.lastG = Double.NaN;
995         }
996 
997         /** {@inheritDoc} */
998         public double g(final ODEStateAndDerivative s) {
999             if (!Precision.equals(lastT, s.getTime(), 0)) {
1000                 lastT = s.getTime();
1001                 lastG = detector.g(convertToOrekitForEventFunction(s));
1002             }
1003             return lastG;
1004         }
1005 
1006         /**
1007          * Convert state from Hipparchus to Orekit format.
1008          * @param s state vector
1009          * @return Orekit state
1010          */
1011         private SpacecraftState convertToOrekitForEventFunction(final ODEStateAndDerivative s) {
1012             if (!this.detector.dependsOnMainVariablesOnly()) {
1013                 return convertToOrekitWithAdditional(s);
1014             } else {
1015                 // event function does not require secondary states or attitude rates
1016                 stateMapper.setAttitudeProvider(getFrozenAttitudeProvider());
1017                 final SpacecraftState converted = convertToOrekitWithoutAdditional(s);
1018                 stateMapper.setAttitudeProvider(getAttitudeProvider());
1019                 return converted;
1020             }
1021         }
1022 
1023         /** {@inheritDoc} */
1024         public ODEEventHandler getHandler() {
1025 
1026             return new ODEEventHandler() {
1027 
1028                 /** {@inheritDoc} */
1029                 public Action eventOccurred(final ODEStateAndDerivative s, final ODEEventDetector d, final boolean increasing) {
1030                     return handler.eventOccurred(convertToOrekitWithAdditional(s), detector, increasing);
1031                 }
1032 
1033                 /** {@inheritDoc} */
1034                 @Override
1035                 public ODEState resetState(final ODEEventDetector d, final ODEStateAndDerivative s) {
1036 
1037                     final SpacecraftState oldState = convertToOrekitWithAdditional(s);
1038                     final SpacecraftState newState = handler.resetState(detector, oldState);
1039                     stateChanged(newState);
1040 
1041                     // main part
1042                     final double[] primary    = new double[s.getPrimaryStateDimension()];
1043                     stateMapper.mapStateToArray(newState, primary, null);
1044 
1045                     // secondary part
1046                     final double[][] secondary = new double[1][secondaryOffsets.get(SECONDARY_DIMENSION)];
1047                     for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
1048                         final String name      = provider.getName();
1049                         final int    offset    = secondaryOffsets.get(name);
1050                         final int    dimension = provider.getDimension();
1051                         System.arraycopy(newState.getAdditionalState(name), 0, secondary[0], offset, dimension);
1052                     }
1053 
1054                     return new ODEState(newState.getDate().durationFrom(getStartDate()),
1055                                         primary, secondary);
1056 
1057                 }
1058 
1059             };
1060         }
1061 
1062     }
1063 
1064     /** Adapt an {@link org.orekit.propagation.sampling.OrekitStepHandler}
1065      * to Hipparchus {@link ODEStepHandler} interface.
1066      * @author Luc Maisonobe
1067      */
1068     private class AdaptedStepHandler implements ODEStepHandler {
1069 
1070         /** Underlying handler. */
1071         private final OrekitStepHandler handler;
1072 
1073         /** Build an instance.
1074          * @param handler underlying handler to wrap
1075          */
1076         AdaptedStepHandler(final OrekitStepHandler handler) {
1077             this.handler = handler;
1078         }
1079 
1080         /** {@inheritDoc} */
1081         @Override
1082         public void init(final ODEStateAndDerivative s0, final double t) {
1083             handler.init(convertToOrekitWithAdditional(s0), stateMapper.mapDoubleToDate(t));
1084         }
1085 
1086         /** {@inheritDoc} */
1087         @Override
1088         public void handleStep(final ODEStateInterpolator interpolator) {
1089             handler.handleStep(new AdaptedStepInterpolator(interpolator));
1090         }
1091 
1092         /** {@inheritDoc} */
1093         @Override
1094         public void finish(final ODEStateAndDerivative finalState) {
1095             handler.finish(convertToOrekitWithAdditional(finalState));
1096         }
1097 
1098     }
1099 
1100     /** Adapt an Hipparchus {@link ODEStateInterpolator}
1101      * to an orekit {@link OrekitStepInterpolator} interface.
1102      * @author Luc Maisonobe
1103      */
1104     private class AdaptedStepInterpolator implements OrekitStepInterpolator {
1105 
1106         /** Underlying raw rawInterpolator. */
1107         private final ODEStateInterpolator mathInterpolator;
1108 
1109         /** Simple constructor.
1110          * @param mathInterpolator underlying raw interpolator
1111          */
1112         AdaptedStepInterpolator(final ODEStateInterpolator mathInterpolator) {
1113             this.mathInterpolator = mathInterpolator;
1114         }
1115 
1116         /** {@inheritDoc}} */
1117         @Override
1118         public SpacecraftState getPreviousState() {
1119             return convertToOrekitWithAdditional(mathInterpolator.getPreviousState());
1120         }
1121 
1122         /** {@inheritDoc}} */
1123         @Override
1124         public boolean isPreviousStateInterpolated() {
1125             return mathInterpolator.isPreviousStateInterpolated();
1126         }
1127 
1128         /** {@inheritDoc}} */
1129         @Override
1130         public SpacecraftState getCurrentState() {
1131             return convertToOrekitWithAdditional(mathInterpolator.getCurrentState());
1132         }
1133 
1134         /** {@inheritDoc}} */
1135         @Override
1136         public boolean isCurrentStateInterpolated() {
1137             return mathInterpolator.isCurrentStateInterpolated();
1138         }
1139 
1140         /** {@inheritDoc}} */
1141         @Override
1142         public SpacecraftState getInterpolatedState(final AbsoluteDate date) {
1143             return convertToOrekitWithAdditional(mathInterpolator.getInterpolatedState(date.durationFrom(stateMapper.getReferenceDate())));
1144         }
1145 
1146         /** {@inheritDoc}} */
1147         @Override
1148         public boolean isForward() {
1149             return mathInterpolator.isForward();
1150         }
1151 
1152         /** {@inheritDoc}} */
1153         @Override
1154         public AdaptedStepInterpolator restrictStep(final SpacecraftState newPreviousState,
1155                                                     final SpacecraftState newCurrentState) {
1156             try {
1157                 final AbstractODEStateInterpolator aosi = (AbstractODEStateInterpolator) mathInterpolator;
1158                 return new AdaptedStepInterpolator(aosi.restrictStep(convertFromOrekit(newPreviousState),
1159                                                                      convertFromOrekit(newCurrentState)));
1160             } catch (ClassCastException cce) {
1161                 // this should never happen
1162                 throw new OrekitInternalError(cce);
1163             }
1164         }
1165 
1166 
1167         /** Convert a state from space flight dynamics world to mathematical world.
1168          * @param state space flight dynamics state
1169          * @return mathematical state
1170          */
1171         private ODEStateAndDerivative convertFromOrekit(final SpacecraftState state) {
1172 
1173             // retrieve initial state
1174             final double[] primary    = new double[getBasicDimension()];
1175             final double[] primaryDot = new double[getBasicDimension()];
1176             stateMapper.mapStateToArray(state, primary, primaryDot);
1177 
1178             // secondary part of the ODE
1179             final double[][] secondary           = secondary(state);
1180             final double[][] secondaryDerivative = secondaryDerivative(state);
1181 
1182             return new ODEStateAndDerivative(stateMapper.mapDateToDouble(state.getDate()),
1183                     primary, primaryDot,
1184                     secondary, secondaryDerivative);
1185 
1186         }
1187 
1188         /** Create secondary state derivative.
1189          * @param state spacecraft state
1190          * @return secondary state derivative
1191          * @since 11.1
1192          */
1193         private double[][] secondaryDerivative(final SpacecraftState state) {
1194 
1195             if (secondaryOffsets.isEmpty()) {
1196                 return null;
1197             }
1198 
1199             final double[][] secondaryDerivative = new double[1][secondaryOffsets.get(SECONDARY_DIMENSION)];
1200             for (final AdditionalDerivativesProvider provider : additionalDerivativesProviders) {
1201                 final String   name       = provider.getName();
1202                 final int      offset     = secondaryOffsets.get(name);
1203                 final double[] additionalDerivative = state.getAdditionalStateDerivative(name);
1204                 System.arraycopy(additionalDerivative, 0, secondaryDerivative[0], offset, additionalDerivative.length);
1205             }
1206 
1207             return secondaryDerivative;
1208 
1209         }
1210     }
1211 
1212     /** Specialized step handler storing interpolators for ephemeris generation.
1213      * @since 11.0
1214      */
1215     private class StoringStepHandler implements ODEStepHandler, EphemerisGenerator {
1216 
1217         /** Underlying raw mathematical model. */
1218         private DenseOutputModel model;
1219 
1220         /** the user supplied end date. Propagation may not end on this date. */
1221         private AbsoluteDate endDate;
1222 
1223         /** Generated ephemeris. */
1224         private BoundedPropagator ephemeris;
1225 
1226         /** Last interpolator handled by the object.*/
1227         private  ODEStateInterpolator lastInterpolator;
1228 
1229         /** Set the end date.
1230          * @param endDate end date
1231          */
1232         public void setEndDate(final AbsoluteDate endDate) {
1233             this.endDate = endDate;
1234         }
1235 
1236         /** {@inheritDoc} */
1237         @Override
1238         public void init(final ODEStateAndDerivative s0, final double t) {
1239 
1240             this.model = new DenseOutputModel();
1241             model.init(s0, t);
1242 
1243             // ephemeris will be generated when last step is processed
1244             this.ephemeris = null;
1245 
1246             this.lastInterpolator = null;
1247 
1248         }
1249 
1250         /** {@inheritDoc} */
1251         @Override
1252         public BoundedPropagator getGeneratedEphemeris() {
1253             // Each time we try to get the ephemeris, rebuild it using the last data.
1254             buildEphemeris();
1255             return ephemeris;
1256         }
1257 
1258         /** {@inheritDoc} */
1259         @Override
1260         public void handleStep(final ODEStateInterpolator interpolator) {
1261             model.handleStep(interpolator);
1262             lastInterpolator = interpolator;
1263         }
1264 
1265         /** {@inheritDoc} */
1266         @Override
1267         public void finish(final ODEStateAndDerivative finalState) {
1268             buildEphemeris();
1269         }
1270 
1271         /** Method used to produce ephemeris at a given time.
1272          * Can be used at multiple times, updating the ephemeris to
1273          * its last state.
1274          */
1275         private void buildEphemeris() {
1276             // buildEphemeris was built in order to allow access to what was previously the finish method.
1277             // This now allows to call it through getGeneratedEphemeris, therefore through an external call,
1278             // which was not previously the case.
1279 
1280             // Update the model's finalTime with the last interpolator.
1281             model.finish(lastInterpolator.getCurrentState());
1282 
1283             // set up the boundary dates
1284             final double tI = model.getInitialTime();
1285             final double tF = model.getFinalTime();
1286             // tI is almost? always zero
1287             final AbsoluteDate startDate =
1288                             stateMapper.mapDoubleToDate(tI);
1289             final AbsoluteDate finalDate =
1290                             stateMapper.mapDoubleToDate(tF, this.endDate);
1291             final AbsoluteDate minDate;
1292             final AbsoluteDate maxDate;
1293             if (tF < tI) {
1294                 minDate = finalDate;
1295                 maxDate = startDate;
1296             } else {
1297                 minDate = startDate;
1298                 maxDate = finalDate;
1299             }
1300 
1301             // get the initial additional states that are not managed
1302             final DataDictionary unmanaged = new DataDictionary();
1303             for (final DataDictionary.Entry initial : getInitialState().getAdditionalDataValues().getData()) {
1304                 if (!AbstractIntegratedPropagator.this.isAdditionalDataManaged(initial.getKey())) {
1305                     // this additional state was in the initial state, but is unknown to the propagator
1306                     // we simply copy its initial value as is
1307                     unmanaged.put(initial.getKey(), initial.getValue());
1308                 }
1309             }
1310 
1311             // get the names of additional states managed by differential equations
1312             final String[] names      = new String[additionalDerivativesProviders.size()];
1313             final int[]    dimensions = new int[additionalDerivativesProviders.size()];
1314             for (int i = 0; i < names.length; ++i) {
1315                 names[i] = additionalDerivativesProviders.get(i).getName();
1316                 dimensions[i] = additionalDerivativesProviders.get(i).getDimension();
1317             }
1318 
1319             // create the ephemeris
1320             ephemeris = new IntegratedEphemeris(startDate, minDate, maxDate,
1321                                                 stateMapper, getAttitudeProvider(), propagationType, model,
1322                                                 unmanaged, getAdditionalDataProviders(),
1323                                                 names, dimensions);
1324 
1325         }
1326 
1327     }
1328 
1329     /** Wrapper for resetting an integrator handlers.
1330      * <p>
1331      * This class is intended to be used in a try-with-resource statement.
1332      * If propagator-specific event handlers and step handlers are added to
1333      * the integrator in the try block, they will be removed automatically
1334      * when leaving the block, so the integrator only keeps its own handlers
1335      * between calls to {@link AbstractIntegratedPropagator#propagate(AbsoluteDate, AbsoluteDate).
1336      * </p>
1337      * @since 11.0
1338      */
1339     private static class IntegratorResetter implements AutoCloseable {
1340 
1341         /** Wrapped integrator. */
1342         private final ODEIntegrator integrator;
1343 
1344         /** Initial event detectors list. */
1345         private final List<ODEEventDetector> detectors;
1346 
1347         /** Initial step handlers list. */
1348         private final List<ODEStepHandler> stepHandlers;
1349 
1350         /** Simple constructor.
1351          * @param integrator wrapped integrator
1352          */
1353         IntegratorResetter(final ODEIntegrator integrator) {
1354             this.integrator   = integrator;
1355             this.detectors    = new ArrayList<>(integrator.getEventDetectors());
1356             this.stepHandlers = new ArrayList<>(integrator.getStepHandlers());
1357         }
1358 
1359         /** {@inheritDoc}
1360          * <p>
1361          * Reset event handlers and step handlers back to the initial list
1362          * </p>
1363          */
1364         @Override
1365         public void close() {
1366 
1367             // reset event handlers
1368             integrator.clearEventDetectors();
1369             detectors.forEach(integrator::addEventDetector);
1370 
1371             // reset step handlers
1372             integrator.clearStepHandlers();
1373             stepHandlers.forEach(integrator::addStepHandler);
1374 
1375         }
1376 
1377     }
1378 
1379 }