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.analytical;
18  
19  import java.util.ArrayList;
20  import java.util.Collection;
21  import java.util.Collections;
22  import java.util.Comparator;
23  import java.util.List;
24  import java.util.PriorityQueue;
25  import java.util.Queue;
26  
27  import org.hipparchus.exception.MathRuntimeException;
28  import org.hipparchus.ode.events.Action;
29  import org.orekit.attitudes.Attitude;
30  import org.orekit.attitudes.AttitudeProvider;
31  import org.orekit.errors.OrekitException;
32  import org.orekit.errors.OrekitIllegalArgumentException;
33  import org.orekit.errors.OrekitInternalError;
34  import org.orekit.errors.OrekitMessages;
35  import org.orekit.frames.Frame;
36  import org.orekit.orbits.Orbit;
37  import org.orekit.propagation.AbstractPropagator;
38  import org.orekit.propagation.AdditionalStateProvider;
39  import org.orekit.propagation.BoundedPropagator;
40  import org.orekit.propagation.EphemerisGenerator;
41  import org.orekit.propagation.MatricesHarvester;
42  import org.orekit.propagation.SpacecraftState;
43  import org.orekit.propagation.events.EventDetector;
44  import org.orekit.propagation.events.EventState;
45  import org.orekit.propagation.events.EventState.EventOccurrence;
46  import org.orekit.propagation.sampling.OrekitStepInterpolator;
47  import org.orekit.time.AbsoluteDate;
48  import org.orekit.utils.PVCoordinatesProvider;
49  import org.orekit.utils.TimeStampedPVCoordinates;
50  
51  /** Common handling of {@link org.orekit.propagation.Propagator} methods for analytical propagators.
52   * <p>
53   * This abstract class allows to provide easily the full set of {@link
54   * org.orekit.propagation.Propagator Propagator} methods, including all propagation
55   * modes support and discrete events support for any simple propagation method. Only
56   * two methods must be implemented by derived classes: {@link #propagateOrbit(AbsoluteDate)}
57   * and {@link #getMass(AbsoluteDate)}. The first method should perform straightforward
58   * propagation starting from some internally stored initial state up to the specified target date.
59   * </p>
60   * @author Luc Maisonobe
61   */
62  public abstract class AbstractAnalyticalPropagator extends AbstractPropagator {
63  
64      /** Provider for attitude computation. */
65      private PVCoordinatesProvider pvProvider;
66  
67      /** Start date of last propagation. */
68      private AbsoluteDate lastPropagationStart;
69  
70      /** End date of last propagation. */
71      private AbsoluteDate lastPropagationEnd;
72  
73      /** Initialization indicator of events states. */
74      private boolean statesInitialized;
75  
76      /** Indicator for last step. */
77      private boolean isLastStep;
78  
79      /** Event steps. */
80      private final Collection<EventState<?>> eventsStates;
81  
82      /** Build a new instance.
83       * @param attitudeProvider provider for attitude computation
84       */
85      protected AbstractAnalyticalPropagator(final AttitudeProvider attitudeProvider) {
86          setAttitudeProvider(attitudeProvider);
87          pvProvider           = new LocalPVProvider();
88          lastPropagationStart = AbsoluteDate.PAST_INFINITY;
89          lastPropagationEnd   = AbsoluteDate.FUTURE_INFINITY;
90          statesInitialized    = false;
91          eventsStates         = new ArrayList<>();
92      }
93  
94      /** {@inheritDoc} */
95      @Override
96      public EphemerisGenerator getEphemerisGenerator() {
97          return () -> new BoundedPropagatorView(lastPropagationStart, lastPropagationEnd);
98      }
99  
100     /** {@inheritDoc} */
101     public <T extends EventDetector> void addEventDetector(final T detector) {
102         eventsStates.add(new EventState<>(detector));
103     }
104 
105     /** {@inheritDoc} */
106     public Collection<EventDetector> getEventsDetectors() {
107         final List<EventDetector> list = new ArrayList<>();
108         for (final EventState<?> state : eventsStates) {
109             list.add(state.getEventDetector());
110         }
111         return Collections.unmodifiableCollection(list);
112     }
113 
114     /** {@inheritDoc} */
115     public void clearEventsDetectors() {
116         eventsStates.clear();
117     }
118 
119     /** {@inheritDoc} */
120     public SpacecraftState propagate(final AbsoluteDate start, final AbsoluteDate target) {
121         checkStartDateIsNotInfinity(start);
122         try {
123             initializePropagation();
124 
125             lastPropagationStart = start;
126 
127             // Initialize additional states
128             initializeAdditionalStates(target);
129 
130             final boolean isForward = target.compareTo(start) >= 0;
131             SpacecraftState state   = updateAdditionalStates(basicPropagate(start));
132 
133             // initialize event detectors
134             for (final EventState<?> es : eventsStates) {
135                 es.init(state, target);
136             }
137 
138             // initialize step handlers
139             getMultiplexer().init(state, target);
140 
141             // iterate over the propagation range, need loop due to reset events
142             statesInitialized = false;
143             isLastStep = false;
144             do {
145 
146                 // attempt to advance to the target date
147                 final SpacecraftState previous = state;
148                 final SpacecraftState current = updateAdditionalStates(basicPropagate(target));
149                 final OrekitStepInterpolator interpolator =
150                         new BasicStepInterpolator(isForward, previous, current);
151 
152                 // accept the step, trigger events and step handlers
153                 state = acceptStep(interpolator, target);
154 
155                 // Update the potential changes in the spacecraft state due to the events
156                 // especially the potential attitude transition
157                 state = updateAdditionalStates(basicPropagate(state.getDate()));
158 
159             } while (!isLastStep);
160 
161             // return the last computed state
162             lastPropagationEnd = state.getDate();
163             setStartDate(state.getDate());
164             return state;
165 
166         } catch (MathRuntimeException mrte) {
167             throw OrekitException.unwrap(mrte);
168         }
169     }
170 
171     /**
172      * Check the starting date is not {@code AbsoluteDate.PAST_INFINITY} or {@code AbsoluteDate.FUTURE_INFINITY}.
173      * @param start propagation starting date
174      */
175     private void checkStartDateIsNotInfinity(final AbsoluteDate start) {
176         if (start.isEqualTo(AbsoluteDate.PAST_INFINITY) || start.isEqualTo(AbsoluteDate.FUTURE_INFINITY)) {
177             throw new OrekitIllegalArgumentException(OrekitMessages.CANNOT_START_PROPAGATION_FROM_INFINITY);
178         }
179     }
180 
181     /** Accept a step, triggering events and step handlers.
182      * @param interpolator interpolator for the current step
183      * @param target final propagation time
184      * @return state at the end of the step
185      * @exception MathRuntimeException if an event cannot be located
186      */
187     protected SpacecraftState acceptStep(final OrekitStepInterpolator interpolator,
188                                          final AbsoluteDate target)
189         throws MathRuntimeException {
190 
191         SpacecraftState        previous   = interpolator.getPreviousState();
192         final SpacecraftState  current    = interpolator.getCurrentState();
193         OrekitStepInterpolator restricted = interpolator;
194 
195 
196         // initialize the events states if needed
197         if (!statesInitialized) {
198 
199             if (!eventsStates.isEmpty()) {
200                 // initialize the events states
201                 for (final EventState<?> state : eventsStates) {
202                     state.reinitializeBegin(interpolator);
203                 }
204             }
205 
206             statesInitialized = true;
207 
208         }
209 
210         // search for next events that may occur during the step
211         final int orderingSign = interpolator.isForward() ? +1 : -1;
212         final Queue<EventState<?>> occurringEvents = new PriorityQueue<>(new Comparator<EventState<?>>() {
213             /** {@inheritDoc} */
214             @Override
215             public int compare(final EventState<?> es0, final EventState<?> es1) {
216                 return orderingSign * es0.getEventDate().compareTo(es1.getEventDate());
217             }
218         });
219 
220         boolean doneWithStep = false;
221         resetEvents:
222         do {
223 
224             // Evaluate all event detectors for events
225             occurringEvents.clear();
226             for (final EventState<?> state : eventsStates) {
227                 if (state.evaluateStep(interpolator)) {
228                     // the event occurs during the current step
229                     occurringEvents.add(state);
230                 }
231             }
232 
233             do {
234 
235                 eventLoop:
236                 while (!occurringEvents.isEmpty()) {
237 
238                     // handle the chronologically first event
239                     final EventState<?> currentEvent = occurringEvents.poll();
240 
241                     // get state at event time
242                     SpacecraftState eventState = restricted.getInterpolatedState(currentEvent.getEventDate());
243 
244                     // restrict the interpolator to the first part of the step, up to the event
245                     restricted = restricted.restrictStep(previous, eventState);
246 
247                     // try to advance all event states to current time
248                     for (final EventState<?> state : eventsStates) {
249                         if (state != currentEvent && state.tryAdvance(eventState, interpolator)) {
250                             // we need to handle another event first
251                             // remove event we just updated to prevent heap corruption
252                             occurringEvents.remove(state);
253                             // add it back to update its position in the heap
254                             occurringEvents.add(state);
255                             // re-queue the event we were processing
256                             occurringEvents.add(currentEvent);
257                             continue eventLoop;
258                         }
259                     }
260                     // all event detectors agree we can advance to the current event time
261 
262                     // handle the first part of the step, up to the event
263                     getMultiplexer().handleStep(restricted);
264 
265                     // acknowledge event occurrence
266                     final EventOccurrence occurrence = currentEvent.doEvent(eventState);
267                     final Action action = occurrence.getAction();
268                     isLastStep = action == Action.STOP;
269 
270                     if (isLastStep) {
271 
272                         // ensure the event is after the root if it is returned STOP
273                         // this lets the user integrate to a STOP event and then restart
274                         // integration from the same time.
275                         final SpacecraftState savedState = eventState;
276                         eventState = interpolator.getInterpolatedState(occurrence.getStopDate());
277                         restricted = restricted.restrictStep(savedState, eventState);
278 
279                         // handle the almost zero size last part of the final step, at event time
280                         getMultiplexer().handleStep(restricted);
281                         getMultiplexer().finish(restricted.getCurrentState());
282 
283                     }
284 
285                     if (isLastStep) {
286                         // the event asked to stop integration
287                         return eventState;
288                     }
289 
290                     if (action == Action.RESET_DERIVATIVES || action == Action.RESET_STATE) {
291                         // some event handler has triggered changes that
292                         // invalidate the derivatives, we need to recompute them
293                         final SpacecraftState resetState = occurrence.getNewState();
294                         resetIntermediateState(resetState, interpolator.isForward());
295                         return resetState;
296                     }
297                     // at this point action == Action.CONTINUE or Action.RESET_EVENTS
298 
299                     // prepare handling of the remaining part of the step
300                     previous = eventState;
301                     restricted = new BasicStepInterpolator(restricted.isForward(), eventState, current);
302 
303                     if (action == Action.RESET_EVENTS) {
304                         continue resetEvents;
305                     }
306 
307                     // at this point action == Action.CONTINUE
308                     // check if the same event occurs again in the remaining part of the step
309                     if (currentEvent.evaluateStep(restricted)) {
310                         // the event occurs during the current step
311                         occurringEvents.add(currentEvent);
312                     }
313 
314                 }
315 
316                 // last part of the step, after the last event. Advance all detectors to
317                 // the end of the step. Should only detect a new event here if an event
318                 // modified the g function of another detector. Detecting such events here
319                 // is unreliable and RESET_EVENTS should be used instead. Might as well
320                 // re-check here because we have to loop through all the detectors anyway
321                 // and the alternative is to throw an exception.
322                 for (final EventState<?> state : eventsStates) {
323                     if (state.tryAdvance(current, interpolator)) {
324                         occurringEvents.add(state);
325                     }
326                 }
327 
328             } while (!occurringEvents.isEmpty());
329 
330             doneWithStep = true;
331         } while (!doneWithStep);
332 
333         isLastStep = target.equals(current.getDate());
334 
335         // handle the remaining part of the step, after all events if any
336         getMultiplexer().handleStep(restricted);
337         if (isLastStep) {
338             getMultiplexer().finish(restricted.getCurrentState());
339         }
340 
341         return current;
342 
343     }
344 
345     /** Get the mass.
346      * @param date target date for the orbit
347      * @return mass mass
348      */
349     protected abstract double getMass(AbsoluteDate date);
350 
351     /** Get PV coordinates provider.
352      * @return PV coordinates provider
353      */
354     public PVCoordinatesProvider getPvProvider() {
355         return pvProvider;
356     }
357 
358     /** Reset an intermediate state.
359      * @param state new intermediate state to consider
360      * @param forward if true, the intermediate state is valid for
361      * propagations after itself
362      */
363     protected abstract void resetIntermediateState(SpacecraftState state, boolean forward);
364 
365     /** Extrapolate an orbit up to a specific target date.
366      * @param date target date for the orbit
367      * @return extrapolated parameters
368      */
369     protected abstract Orbit propagateOrbit(AbsoluteDate date);
370 
371     /** Propagate an orbit without any fancy features.
372      * <p>This method is similar in spirit to the {@link #propagate} method,
373      * except that it does <strong>not</strong> call any handler during
374      * propagation, nor any discrete events, not additional states. It always
375      * stop exactly at the specified date.</p>
376      * @param date target date for propagation
377      * @return state at specified date
378      */
379     protected SpacecraftState basicPropagate(final AbsoluteDate date) {
380         try {
381 
382             // evaluate orbit
383             final Orbit orbit = propagateOrbit(date);
384 
385             // evaluate attitude
386             final Attitude attitude =
387                 getAttitudeProvider().getAttitude(pvProvider, date, orbit.getFrame());
388 
389             // build raw state
390             return new SpacecraftState(orbit, attitude, getMass(date));
391 
392         } catch (OrekitException oe) {
393             throw new OrekitException(oe);
394         }
395     }
396 
397     /**
398      * Get the names of the parameters in the matrix returned by {@link MatricesHarvester#getParametersJacobian}.
399      * @return names of the parameters (i.e. columns) of the Jacobian matrix
400      * @since 11.1
401      */
402     protected List<String> getJacobiansColumnsNames() {
403         return Collections.emptyList();
404     }
405 
406     /** Internal PVCoordinatesProvider for attitude computation. */
407     private class LocalPVProvider implements PVCoordinatesProvider {
408 
409         /** {@inheritDoc} */
410         public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
411             return propagateOrbit(date).getPVCoordinates(frame);
412         }
413 
414     }
415 
416     /** {@link BoundedPropagator} view of the instance. */
417     private class BoundedPropagatorView extends AbstractAnalyticalPropagator implements BoundedPropagator {
418 
419         /** Min date. */
420         private final AbsoluteDate minDate;
421 
422         /** Max date. */
423         private final AbsoluteDate maxDate;
424 
425         /** Simple constructor.
426          * @param startDate start date of the propagation
427          * @param endDate end date of the propagation
428          */
429         BoundedPropagatorView(final AbsoluteDate startDate, final AbsoluteDate endDate) {
430             super(AbstractAnalyticalPropagator.this.getAttitudeProvider());
431             super.resetInitialState(AbstractAnalyticalPropagator.this.getInitialState());
432             if (startDate.compareTo(endDate) <= 0) {
433                 minDate = startDate;
434                 maxDate = endDate;
435             } else {
436                 minDate = endDate;
437                 maxDate = startDate;
438             }
439 
440             try {
441                 // copy the same additional state providers as the original propagator
442                 for (AdditionalStateProvider provider : AbstractAnalyticalPropagator.this.getAdditionalStateProviders()) {
443                     addAdditionalStateProvider(provider);
444                 }
445             } catch (OrekitException oe) {
446                 // as the generators are already compatible with each other,
447                 // this should never happen
448                 throw new OrekitInternalError(null);
449             }
450 
451         }
452 
453         /** {@inheritDoc} */
454         public AbsoluteDate getMinDate() {
455             return minDate;
456         }
457 
458         /** {@inheritDoc} */
459         public AbsoluteDate getMaxDate() {
460             return maxDate;
461         }
462 
463         /** {@inheritDoc} */
464         protected Orbit propagateOrbit(final AbsoluteDate target) {
465             return AbstractAnalyticalPropagator.this.propagateOrbit(target);
466         }
467 
468         /** {@inheritDoc} */
469         public double getMass(final AbsoluteDate date) {
470             return AbstractAnalyticalPropagator.this.getMass(date);
471         }
472 
473         /** {@inheritDoc} */
474         public void resetInitialState(final SpacecraftState state) {
475             super.resetInitialState(state);
476             AbstractAnalyticalPropagator.this.resetInitialState(state);
477         }
478 
479         /** {@inheritDoc} */
480         protected void resetIntermediateState(final SpacecraftState state, final boolean forward) {
481             AbstractAnalyticalPropagator.this.resetIntermediateState(state, forward);
482         }
483 
484         /** {@inheritDoc} */
485         public SpacecraftState getInitialState() {
486             return AbstractAnalyticalPropagator.this.getInitialState();
487         }
488 
489         /** {@inheritDoc} */
490         public Frame getFrame() {
491             return AbstractAnalyticalPropagator.this.getFrame();
492         }
493 
494     }
495 
496     /** Internal class for local propagation. */
497     private class BasicStepInterpolator implements OrekitStepInterpolator {
498 
499         /** Previous state. */
500         private final SpacecraftState previousState;
501 
502         /** Current state. */
503         private final SpacecraftState currentState;
504 
505         /** Forward propagation indicator. */
506         private final boolean forward;
507 
508         /** Simple constructor.
509          * @param isForward integration direction indicator
510          * @param previousState start of the step
511          * @param currentState end of the step
512          */
513         BasicStepInterpolator(final boolean isForward,
514                               final SpacecraftState previousState,
515                               final SpacecraftState currentState) {
516             this.forward         = isForward;
517             this.previousState   = previousState;
518             this.currentState    = currentState;
519         }
520 
521         /** {@inheritDoc} */
522         @Override
523         public SpacecraftState getPreviousState() {
524             return previousState;
525         }
526 
527         /** {@inheritDoc} */
528         @Override
529         public boolean isPreviousStateInterpolated() {
530             // no difference in analytical propagators
531             return false;
532         }
533 
534         /** {@inheritDoc} */
535         @Override
536         public SpacecraftState getCurrentState() {
537             return currentState;
538         }
539 
540         /** {@inheritDoc} */
541         @Override
542         public boolean isCurrentStateInterpolated() {
543             // no difference in analytical propagators
544             return false;
545         }
546 
547         /** {@inheritDoc} */
548         @Override
549         public SpacecraftState getInterpolatedState(final AbsoluteDate date) {
550 
551             // compute the basic spacecraft state
552             final SpacecraftState basicState = basicPropagate(date);
553 
554             // add the additional states
555             return updateAdditionalStates(basicState);
556 
557         }
558 
559         /** {@inheritDoc} */
560         @Override
561         public boolean isForward() {
562             return forward;
563         }
564 
565         /** {@inheritDoc} */
566         @Override
567         public BasicStepInterpolator restrictStep(final SpacecraftState newPreviousState,
568                                                   final SpacecraftState newCurrentState) {
569             return new BasicStepInterpolator(forward, newPreviousState, newCurrentState);
570         }
571 
572     }
573 
574 }