FieldAbstractAnalyticalPropagator.java

  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.analytical;

  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.Comparator;
  22. import java.util.List;
  23. import java.util.PriorityQueue;
  24. import java.util.Queue;
  25. import java.util.stream.Collectors;

  26. import org.hipparchus.CalculusFieldElement;
  27. import org.hipparchus.Field;
  28. import org.hipparchus.exception.MathRuntimeException;
  29. import org.hipparchus.ode.events.Action;
  30. import org.orekit.attitudes.AttitudeProvider;
  31. import org.orekit.attitudes.FieldAttitude;
  32. import org.orekit.errors.OrekitException;
  33. import org.orekit.errors.OrekitInternalError;
  34. import org.orekit.frames.Frame;
  35. import org.orekit.orbits.FieldOrbit;
  36. import org.orekit.propagation.BoundedPropagator;
  37. import org.orekit.propagation.FieldAbstractPropagator;
  38. import org.orekit.propagation.FieldAdditionalDataProvider;
  39. import org.orekit.propagation.FieldBoundedPropagator;
  40. import org.orekit.propagation.FieldEphemerisGenerator;
  41. import org.orekit.propagation.FieldSpacecraftState;
  42. import org.orekit.propagation.events.FieldEventDetector;
  43. import org.orekit.propagation.events.FieldEventState;
  44. import org.orekit.propagation.events.FieldEventState.EventOccurrence;
  45. import org.orekit.propagation.sampling.FieldOrekitStepInterpolator;
  46. import org.orekit.time.FieldAbsoluteDate;
  47. import org.orekit.utils.FieldPVCoordinatesProvider;
  48. import org.orekit.utils.ParameterDriver;
  49. import org.orekit.utils.ParameterDriversProvider;
  50. import org.orekit.utils.TimeStampedFieldPVCoordinates;

  51. /** Common handling of {@link org.orekit.propagation.FieldPropagator} methods for analytical propagators.
  52.  * <p>
  53.  * This abstract class allows to provide easily the full set of {@link
  54.  * org.orekit.propagation.FieldPropagator FieldPropagator} 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(FieldAbsoluteDate, CalculusFieldElement[])}
  57.  * and {@link #getMass(FieldAbsoluteDate)}. 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.  * @param <T> type of the field elements
  62.  */

  63. public abstract class FieldAbstractAnalyticalPropagator<T extends CalculusFieldElement<T>>
  64.     extends FieldAbstractPropagator<T>
  65.     implements ParameterDriversProvider {

  66.     /** Provider for attitude computation. */
  67.     private final FieldPVCoordinatesProvider<T> pvProvider;

  68.     /** Start date of last propagation. */
  69.     private FieldAbsoluteDate<T> lastPropagationStart;

  70.     /** End date of last propagation. */
  71.     private FieldAbsoluteDate<T> lastPropagationEnd;

  72.     /** Initialization indicator of events states. */
  73.     private boolean statesInitialized;

  74.     /** Indicator for last step. */
  75.     private boolean isLastStep;

  76.     /** User-defined event states. */
  77.     private final Collection<FieldEventState<?, T>> userEventsStates;

  78.     /** All event states, including internal ones. */
  79.     private Collection<FieldEventState<?, T>> eventsStates;

  80.     /** Build a new instance.
  81.      * @param attitudeProvider provider for attitude computation
  82.      * @param field field used as default
  83.      */
  84.     protected FieldAbstractAnalyticalPropagator(final Field<T> field, final AttitudeProvider attitudeProvider) {
  85.         super(field);
  86.         setAttitudeProvider(attitudeProvider);
  87.         pvProvider           = new FieldLocalPVProvider();
  88.         lastPropagationStart = FieldAbsoluteDate.getPastInfinity(field);
  89.         lastPropagationEnd   = FieldAbsoluteDate.getFutureInfinity(field);
  90.         statesInitialized    = false;
  91.         userEventsStates     = new ArrayList<>();
  92.     }

  93.     /** {@inheritDoc} */
  94.     @Override
  95.     public FieldEphemerisGenerator<T> getEphemerisGenerator() {
  96.         return () -> new FieldBoundedPropagatorView(lastPropagationStart, lastPropagationEnd);
  97.     }

  98.     /** {@inheritDoc} */
  99.     public <D extends FieldEventDetector<T>> void addEventDetector(final D detector) {
  100.         userEventsStates.add(new FieldEventState<>(detector));
  101.     }

  102.     /** {@inheritDoc} */
  103.     @Override
  104.     public Collection<FieldEventDetector<T>> getEventDetectors() {
  105.         final List<FieldEventDetector<T>> list = new ArrayList<>();
  106.         for (final FieldEventState<?, T> state : userEventsStates) {
  107.             list.add(state.getEventDetector());
  108.         }
  109.         return Collections.unmodifiableCollection(list);
  110.     }

  111.     /** {@inheritDoc} */
  112.     @Override
  113.     public void clearEventsDetectors() {
  114.         userEventsStates.clear();
  115.     }

  116.     /** {@inheritDoc} */
  117.     @Override
  118.     public FieldSpacecraftState<T> propagate(final FieldAbsoluteDate<T> start, final FieldAbsoluteDate<T> target) {
  119.         try {

  120.             initializePropagation();

  121.             lastPropagationStart = start;

  122.             // Initialize additional states
  123.             initializeAdditionalData(target);

  124.             final boolean           isForward = target.compareTo(start) >= 0;
  125.             FieldSpacecraftState<T> state   = updateAdditionalData(basicPropagate(start));

  126.             // initialize event detectors
  127.             eventsStates = getAttitudeProvider().
  128.                            getFieldEventDetectors(getField()).map(FieldEventState::new).
  129.                            collect(Collectors.toList());
  130.             eventsStates.addAll(userEventsStates);
  131.             for (final FieldEventState<?, T> es : eventsStates) {
  132.                 es.init(state, target);
  133.             }

  134.             // initialize step handlers
  135.             getMultiplexer().init(state, target);

  136.             // iterate over the propagation range, need loop due to reset events
  137.             statesInitialized = false;
  138.             isLastStep = false;
  139.             do {

  140.                 // attempt to advance to the target date
  141.                 final FieldSpacecraftState<T> previous = state;
  142.                 final FieldSpacecraftState<T> current = updateAdditionalData(basicPropagate(target));
  143.                 final FieldBasicStepInterpolator interpolator =
  144.                         new FieldBasicStepInterpolator(isForward, previous, current);

  145.                 // accept the step, trigger events and step handlers
  146.                 state = acceptStep(interpolator, target);

  147.                 // Update the potential changes in the spacecraft state due to the events
  148.                 // especially the potential attitude transition
  149.                 state = updateAdditionalData(basicPropagate(state.getDate()));

  150.             } while (!isLastStep);

  151.             // Finalize event detectors
  152.             for (final FieldEventState<?, T> es : eventsStates) {
  153.                 es.finish(state);
  154.             }

  155.             // return the last computed state
  156.             lastPropagationEnd = state.getDate();
  157.             setStartDate(state.getDate());
  158.             return state;

  159.         } catch (MathRuntimeException mrte) {
  160.             throw OrekitException.unwrap(mrte);
  161.         }
  162.     }

  163.     /** Accept a step, triggering events and step handlers.
  164.      * @param interpolator interpolator for the current step
  165.      * @param target final propagation time
  166.      * @return state at the end of the step
  167.      * @exception MathRuntimeException if an event cannot be located
  168.      */
  169.     protected FieldSpacecraftState<T> acceptStep(final FieldBasicStepInterpolator interpolator,
  170.                                                  final FieldAbsoluteDate<T> target)
  171.         throws MathRuntimeException {

  172.         FieldSpacecraftState<T>       previous   = interpolator.getPreviousState();
  173.         final FieldSpacecraftState<T> current    = interpolator.getCurrentState();
  174.         FieldBasicStepInterpolator    restricted = interpolator;

  175.         // initialize the events states if needed
  176.         if (!statesInitialized) {

  177.             if (!eventsStates.isEmpty()) {
  178.                 // initialize the events states
  179.                 for (final FieldEventState<?, T> state : eventsStates) {
  180.                     state.reinitializeBegin(interpolator);
  181.                 }
  182.             }

  183.             statesInitialized = true;

  184.         }

  185.         // search for next events that may occur during the step
  186.         final int orderingSign = interpolator.isForward() ? +1 : -1;
  187.         final Queue<FieldEventState<?, T>> occurringEvents = new PriorityQueue<>(new Comparator<FieldEventState<?, T>>() {
  188.             /** {@inheritDoc} */
  189.             @Override
  190.             public int compare(final FieldEventState<?, T> es0, final FieldEventState<?, T> es1) {
  191.                 return orderingSign * es0.getEventDate().compareTo(es1.getEventDate());
  192.             }
  193.         });

  194.         boolean doneWithStep = false;
  195.         resetEvents:
  196.         do {

  197.             // Evaluate all event detectors for events
  198.             occurringEvents.clear();
  199.             for (final FieldEventState<?, T> state : eventsStates) {
  200.                 if (state.evaluateStep(interpolator)) {
  201.                     // the event occurs during the current step
  202.                     occurringEvents.add(state);
  203.                 }
  204.             }


  205.             do {

  206.                 eventLoop:
  207.                 while (!occurringEvents.isEmpty()) {

  208.                     // handle the chronologically first event
  209.                     final FieldEventState<?, T> currentEvent = occurringEvents.poll();

  210.                     // get state at event time
  211.                     FieldSpacecraftState<T> eventState = restricted.getInterpolatedState(currentEvent.getEventDate());

  212.                     // restrict the interpolator to the first part of the step, up to the event
  213.                     restricted = restricted.restrictStep(previous, eventState);

  214.                     // try to advance all event states to current time
  215.                     for (final FieldEventState<?, T> state : eventsStates) {
  216.                         if (state != currentEvent && state.tryAdvance(eventState, interpolator)) {
  217.                             // we need to handle another event first
  218.                             // remove event we just updated to prevent heap corruption
  219.                             occurringEvents.remove(state);
  220.                             // add it back to update its position in the heap
  221.                             occurringEvents.add(state);
  222.                             // re-queue the event we were processing
  223.                             occurringEvents.add(currentEvent);
  224.                             continue eventLoop;
  225.                         }
  226.                     }
  227.                     // all event detectors agree we can advance to the current event time

  228.                     // handle the first part of the step, up to the event
  229.                     getMultiplexer().handleStep(restricted);

  230.                     // acknowledge event occurrence
  231.                     final EventOccurrence<T> occurrence = currentEvent.doEvent(eventState);
  232.                     final Action action = occurrence.getAction();
  233.                     isLastStep = action == Action.STOP;
  234.                     if (isLastStep) {

  235.                         // ensure the event is after the root if it is returned STOP
  236.                         // this lets the user integrate to a STOP event and then restart
  237.                         // integration from the same time.
  238.                         final FieldSpacecraftState<T> savedState = eventState;
  239.                         eventState = interpolator.getInterpolatedState(occurrence.getStopDate());
  240.                         restricted = restricted.restrictStep(savedState, eventState);

  241.                         // handle the almost zero size last part of the final step, at event time
  242.                         getMultiplexer().handleStep(restricted);
  243.                         getMultiplexer().finish(restricted.getCurrentState());

  244.                     }

  245.                     if (isLastStep) {
  246.                         // the event asked to stop integration
  247.                         return eventState;
  248.                     }

  249.                     if (action == Action.RESET_DERIVATIVES || action == Action.RESET_STATE) {
  250.                         // some event handler has triggered changes that
  251.                         // invalidate the derivatives, we need to recompute them
  252.                         final FieldSpacecraftState<T> resetState = occurrence.getNewState();
  253.                         resetIntermediateState(resetState, interpolator.isForward());
  254.                         for (final FieldEventState<?, T> fieldEventState: eventsStates) {
  255.                             fieldEventState.getEventDetector().reset(resetState, target);
  256.                         }
  257.                         return resetState;
  258.                     }
  259.                     // at this point action == Action.CONTINUE or Action.RESET_EVENTS

  260.                     // prepare handling of the remaining part of the step
  261.                     previous = eventState;
  262.                     restricted = new FieldBasicStepInterpolator(restricted.isForward(), eventState, current);

  263.                     if (action == Action.RESET_EVENTS) {
  264.                         continue resetEvents;
  265.                     }

  266.                     // at this pint action == Action.CONTINUE
  267.                     // check if the same event occurs again in the remaining part of the step
  268.                     if (currentEvent.evaluateStep(restricted)) {
  269.                         // the event occurs during the current step
  270.                         occurringEvents.add(currentEvent);
  271.                     }

  272.                 }

  273.                 // last part of the step, after the last event. Advance all detectors to
  274.                 // the end of the step. Should only detect a new event here if an event
  275.                 // modified the g function of another detector. Detecting such events here
  276.                 // is unreliable and RESET_EVENTS should be used instead. Might as well
  277.                 // re-check here because we have to loop through all the detectors anyway
  278.                 // and the alternative is to throw an exception.
  279.                 for (final FieldEventState<?, T> state : eventsStates) {
  280.                     if (state.tryAdvance(current, interpolator)) {
  281.                         occurringEvents.add(state);
  282.                     }
  283.                 }

  284.             } while (!occurringEvents.isEmpty());

  285.             doneWithStep = true;
  286.         } while (!doneWithStep);

  287.         isLastStep = target.equals(current.getDate());

  288.         // handle the remaining part of the step, after all events if any
  289.         getMultiplexer().handleStep(restricted);
  290.         if (isLastStep) {
  291.             getMultiplexer().finish(restricted.getCurrentState());
  292.         }

  293.         return current;

  294.     }

  295.     /** Get the mass.
  296.      * @param date target date for the orbit
  297.      * @return mass mass
  298.      */
  299.     protected abstract T getMass(FieldAbsoluteDate<T> date);

  300.     /** Reset an intermediate state.
  301.      * @param state new intermediate state to consider
  302.      * @param forward if true, the intermediate state is valid for
  303.      * propagations after itself
  304.      */
  305.     protected abstract void resetIntermediateState(FieldSpacecraftState<T> state, boolean forward);

  306.     /** Propagate an orbit up to a specific target date.
  307.      * @param date target date for the orbit
  308.      * @param parameters model parameters
  309.      * @return propagated orbit
  310.      */
  311.     public abstract FieldOrbit<T> propagateOrbit(FieldAbsoluteDate<T> date,
  312.                                                  T[] parameters);

  313.     /** Propagate an orbit without any fancy features.
  314.      * <p>This method is similar in spirit to the {@link #propagate} method,
  315.      * except that it does <strong>not</strong> call any handler during
  316.      * propagation, nor any discrete events, not additional states. It always
  317.      * stop exactly at the specified date.</p>
  318.      * @param date target date for propagation
  319.      * @return state at specified date
  320.      */
  321.     public FieldSpacecraftState<T> basicPropagate(final FieldAbsoluteDate<T> date) {
  322.         try {

  323.             // evaluate orbit
  324.             final FieldOrbit<T> orbit = propagateOrbit(date, getParameters(date.getField(), date.getDate()));

  325.             // evaluate attitude
  326.             final FieldAttitude<T> attitude =
  327.                 getAttitudeProvider().getAttitude(pvProvider, date, orbit.getFrame());

  328.             // build raw state
  329.             return new FieldSpacecraftState<>(orbit, attitude).withMass(getMass(date));

  330.         } catch (OrekitException oe) {
  331.             throw new OrekitException(oe);
  332.         }
  333.     }

  334.     /** Internal FieldPVCoordinatesProvider<T> for attitude computation. */
  335.     private class FieldLocalPVProvider implements FieldPVCoordinatesProvider<T> {

  336.         /** {@inheritDoc} */
  337.         @Override
  338.         public TimeStampedFieldPVCoordinates<T> getPVCoordinates(final FieldAbsoluteDate<T> date, final Frame frame) {
  339.             return propagateOrbit(date, getParameters(date.getField(), date)).getPVCoordinates(frame);
  340.         }

  341.     }

  342.     /** {@link BoundedPropagator} view of the instance. */
  343.     private class FieldBoundedPropagatorView extends FieldAbstractAnalyticalPropagator<T>
  344.         implements FieldBoundedPropagator<T> {

  345.         /** Min date. */
  346.         private final FieldAbsoluteDate<T> minDate;

  347.         /** Max date. */
  348.         private final FieldAbsoluteDate<T> maxDate;

  349.         /** Simple constructor.
  350.          * @param startDate start date of the propagation
  351.          * @param endDate end date of the propagation
  352.          */
  353.         FieldBoundedPropagatorView(final FieldAbsoluteDate<T> startDate, final FieldAbsoluteDate<T> endDate) {
  354.             super(startDate.durationFrom(endDate).getField(), FieldAbstractAnalyticalPropagator.this.getAttitudeProvider());
  355.             super.resetInitialState(FieldAbstractAnalyticalPropagator.this.getInitialState());
  356.             if (startDate.compareTo(endDate) <= 0) {
  357.                 minDate = startDate;
  358.                 maxDate = endDate;
  359.             } else {
  360.                 minDate = endDate;
  361.                 maxDate = startDate;
  362.             }

  363.             try {
  364.                 // copy the same additional data providers as the original propagator
  365.                 for (FieldAdditionalDataProvider<?, T> provider : FieldAbstractAnalyticalPropagator.this.getAdditionalDataProviders()) {
  366.                     addAdditionalDataProvider(provider);
  367.                 }
  368.             } catch (OrekitException oe) {
  369.                 // as the providers are already compatible with each other,
  370.                 // this should never happen
  371.                 throw new OrekitInternalError(null);
  372.             }

  373.         }

  374.         /** {@inheritDoc} */
  375.         @Override
  376.         public FieldAbsoluteDate<T> getMinDate() {
  377.             return minDate;
  378.         }

  379.         /** {@inheritDoc} */
  380.         @Override
  381.         public FieldAbsoluteDate<T> getMaxDate() {
  382.             return maxDate;
  383.         }

  384.         /** {@inheritDoc} */
  385.         @Override
  386.         public FieldOrbit<T> propagateOrbit(final FieldAbsoluteDate<T> target,
  387.                                             final T[] parameters) {
  388.             return FieldAbstractAnalyticalPropagator.this.propagateOrbit(target, parameters);
  389.         }

  390.         /** {@inheritDoc} */
  391.         @Override
  392.         public T getMass(final FieldAbsoluteDate<T> date) {
  393.             return FieldAbstractAnalyticalPropagator.this.getMass(date);
  394.         }

  395.         /** {@inheritDoc} */
  396.         @Override
  397.         public void resetInitialState(final FieldSpacecraftState<T> state) {
  398.             super.resetInitialState(state);
  399.             FieldAbstractAnalyticalPropagator.this.resetInitialState(state);
  400.         }

  401.         /** {@inheritDoc} */
  402.         @Override
  403.         protected void resetIntermediateState(final FieldSpacecraftState<T> state, final boolean forward) {
  404.             FieldAbstractAnalyticalPropagator.this.resetIntermediateState(state, forward);
  405.         }

  406.         /** {@inheritDoc} */
  407.         @Override
  408.         public FieldSpacecraftState<T> getInitialState() {
  409.             return FieldAbstractAnalyticalPropagator.this.getInitialState();
  410.         }

  411.         /** {@inheritDoc} */
  412.         @Override
  413.         public Frame getFrame() {
  414.             return FieldAbstractAnalyticalPropagator.this.getFrame();
  415.         }

  416.         /** {@inheritDoc} */
  417.         @Override
  418.         public List<ParameterDriver> getParametersDrivers() {
  419.             return FieldAbstractAnalyticalPropagator.this.getParametersDrivers();
  420.         }
  421.     }

  422.     /** Internal class for local propagation. */
  423.     private class FieldBasicStepInterpolator implements FieldOrekitStepInterpolator<T> {

  424.         /** Previous state. */
  425.         private final FieldSpacecraftState<T> previousState;

  426.         /** Current state. */
  427.         private final FieldSpacecraftState<T> currentState;

  428.         /** Forward propagation indicator. */
  429.         private final boolean forward;

  430.         /** Simple constructor.
  431.          * @param isForward integration direction indicator
  432.          * @param previousState start of the step
  433.          * @param currentState end of the step
  434.          */
  435.         FieldBasicStepInterpolator(final boolean isForward,
  436.                                    final FieldSpacecraftState<T> previousState,
  437.                                    final FieldSpacecraftState<T> currentState) {
  438.             this.forward             = isForward;
  439.             this.previousState   = previousState;
  440.             this.currentState    = currentState;
  441.         }

  442.         /** {@inheritDoc} */
  443.         @Override
  444.         public FieldSpacecraftState<T> getPreviousState() {
  445.             return previousState;
  446.         }

  447.         /** {@inheritDoc} */
  448.         @Override
  449.         public FieldSpacecraftState<T> getCurrentState() {
  450.             return currentState;
  451.         }

  452.         /** {@inheritDoc} */
  453.         @Override
  454.         public FieldSpacecraftState<T> getInterpolatedState(final FieldAbsoluteDate<T> date) {

  455.             // compute the basic spacecraft state
  456.             final FieldSpacecraftState<T> basicState = basicPropagate(date);

  457.             // add the additional states
  458.             return updateAdditionalData(basicState);

  459.         }

  460.         /** {@inheritDoc} */
  461.         @Override
  462.         public boolean isForward() {
  463.             return forward;
  464.         }

  465.         /** {@inheritDoc} */
  466.         @Override
  467.         public FieldBasicStepInterpolator restrictStep(final FieldSpacecraftState<T> newPreviousState,
  468.                                                        final FieldSpacecraftState<T> newCurrentState) {
  469.             return new FieldBasicStepInterpolator(forward, newPreviousState, newCurrentState);
  470.         }

  471.     }

  472. }