FieldAbstractAnalyticalPropagator.java

  1. /* Copyright 2002-2024 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.propagation.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 org.hipparchus.CalculusFieldElement;
  26. import org.hipparchus.Field;
  27. import org.hipparchus.exception.MathRuntimeException;
  28. import org.hipparchus.ode.events.Action;
  29. import org.orekit.attitudes.AttitudeProvider;
  30. import org.orekit.attitudes.FieldAttitude;
  31. import org.orekit.errors.OrekitException;
  32. import org.orekit.errors.OrekitInternalError;
  33. import org.orekit.frames.Frame;
  34. import org.orekit.orbits.FieldOrbit;
  35. import org.orekit.propagation.BoundedPropagator;
  36. import org.orekit.propagation.FieldAbstractPropagator;
  37. import org.orekit.propagation.FieldAdditionalStateProvider;
  38. import org.orekit.propagation.FieldBoundedPropagator;
  39. import org.orekit.propagation.FieldEphemerisGenerator;
  40. import org.orekit.propagation.FieldSpacecraftState;
  41. import org.orekit.propagation.events.FieldEventDetector;
  42. import org.orekit.propagation.events.FieldEventState;
  43. import org.orekit.propagation.events.FieldEventState.EventOccurrence;
  44. import org.orekit.propagation.sampling.FieldOrekitStepInterpolator;
  45. import org.orekit.time.FieldAbsoluteDate;
  46. import org.orekit.utils.FieldPVCoordinatesProvider;
  47. import org.orekit.utils.ParameterDriver;
  48. import org.orekit.utils.ParameterDriversProvider;
  49. import org.orekit.utils.TimeStampedFieldPVCoordinates;

  50. /** Common handling of {@link org.orekit.propagation.FieldPropagator} methods for analytical propagators.
  51.  * <p>
  52.  * This abstract class allows to provide easily the full set of {@link
  53.  * org.orekit.propagation.FieldPropagator FieldPropagator} methods, including all propagation
  54.  * modes support and discrete events support for any simple propagation method. Only
  55.  * two methods must be implemented by derived classes: {@link #propagateOrbit(FieldAbsoluteDate, CalculusFieldElement[])}
  56.  * and {@link #getMass(FieldAbsoluteDate)}. The first method should perform straightforward
  57.  * propagation starting from some internally stored initial state up to the specified target date.
  58.  * </p>
  59.  * @author Luc Maisonobe
  60.  * @param <T> type of the field elements
  61.  */

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

  64.     /** Provider for attitude computation. */
  65.     private FieldPVCoordinatesProvider<T> pvProvider;

  66.     /** Start date of last propagation. */
  67.     private FieldAbsoluteDate<T> lastPropagationStart;

  68.     /** End date of last propagation. */
  69.     private FieldAbsoluteDate<T> lastPropagationEnd;

  70.     /** Initialization indicator of events states. */
  71.     private boolean statesInitialized;

  72.     /** Indicator for last step. */
  73.     private boolean isLastStep;

  74.     /** Event steps. */
  75.     private final Collection<FieldEventState<?, T>> eventsStates;

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

  89.     /** {@inheritDoc} */
  90.     @Override
  91.     public FieldEphemerisGenerator<T> getEphemerisGenerator() {
  92.         return () -> new FieldBoundedPropagatorView(lastPropagationStart, lastPropagationEnd);
  93.     }

  94.     /** {@inheritDoc} */
  95.     public <D extends FieldEventDetector<T>> void addEventDetector(final D detector) {
  96.         eventsStates.add(new FieldEventState<>(detector));
  97.     }

  98.     /** {@inheritDoc} */
  99.     @Override
  100.     public Collection<FieldEventDetector<T>> getEventsDetectors() {
  101.         final List<FieldEventDetector<T>> list = new ArrayList<>();
  102.         for (final FieldEventState<?, T> state : eventsStates) {
  103.             list.add(state.getEventDetector());
  104.         }
  105.         return Collections.unmodifiableCollection(list);
  106.     }

  107.     /** {@inheritDoc} */
  108.     @Override
  109.     public void clearEventsDetectors() {
  110.         eventsStates.clear();
  111.     }
  112.     /** {@inheritDoc} */
  113.     @Override
  114.     public FieldSpacecraftState<T> propagate(final FieldAbsoluteDate<T> start, final FieldAbsoluteDate<T> target) {
  115.         try {

  116.             initializePropagation();

  117.             lastPropagationStart = start;

  118.             // Initialize additional states
  119.             initializeAdditionalStates(target);

  120.             final boolean           isForward = target.compareTo(start) >= 0;
  121.             FieldSpacecraftState<T> state   = updateAdditionalStates(basicPropagate(start));

  122.             // initialize event detectors
  123.             for (final FieldEventState<?, T> es : eventsStates) {
  124.                 es.init(state, target);
  125.             }

  126.             // initialize step handlers
  127.             getMultiplexer().init(state, target);

  128.             // iterate over the propagation range, need loop due to reset events
  129.             statesInitialized = false;
  130.             isLastStep = false;
  131.             do {

  132.                 // attempt to advance to the target date
  133.                 final FieldSpacecraftState<T> previous = state;
  134.                 final FieldSpacecraftState<T> current = updateAdditionalStates(basicPropagate(target));
  135.                 final FieldBasicStepInterpolator interpolator =
  136.                         new FieldBasicStepInterpolator(isForward, previous, current);

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

  139.                 // Update the potential changes in the spacecraft state due to the events
  140.                 // especially the potential attitude transition
  141.                 state = updateAdditionalStates(basicPropagate(state.getDate()));

  142.             } while (!isLastStep);

  143.             // return the last computed state
  144.             lastPropagationEnd = state.getDate();
  145.             setStartDate(state.getDate());
  146.             return state;

  147.         } catch (MathRuntimeException mrte) {
  148.             throw OrekitException.unwrap(mrte);
  149.         }
  150.     }

  151.     /** Accept a step, triggering events and step handlers.
  152.      * @param interpolator interpolator for the current step
  153.      * @param target final propagation time
  154.      * @return state at the end of the step
  155.      * @exception MathRuntimeException if an event cannot be located
  156.      */
  157.     protected FieldSpacecraftState<T> acceptStep(final FieldBasicStepInterpolator interpolator,
  158.                                                  final FieldAbsoluteDate<T> target)
  159.         throws MathRuntimeException {

  160.         FieldSpacecraftState<T>       previous   = interpolator.getPreviousState();
  161.         final FieldSpacecraftState<T> current    = interpolator.getCurrentState();
  162.         FieldBasicStepInterpolator    restricted = interpolator;

  163.         // initialize the events states if needed
  164.         if (!statesInitialized) {

  165.             if (!eventsStates.isEmpty()) {
  166.                 // initialize the events states
  167.                 for (final FieldEventState<?, T> state : eventsStates) {
  168.                     state.reinitializeBegin(interpolator);
  169.                 }
  170.             }

  171.             statesInitialized = true;

  172.         }

  173.         // search for next events that may occur during the step
  174.         final int orderingSign = interpolator.isForward() ? +1 : -1;
  175.         final Queue<FieldEventState<?, T>> occurringEvents = new PriorityQueue<>(new Comparator<FieldEventState<?, T>>() {
  176.             /** {@inheritDoc} */
  177.             @Override
  178.             public int compare(final FieldEventState<?, T> es0, final FieldEventState<?, T> es1) {
  179.                 return orderingSign * es0.getEventDate().compareTo(es1.getEventDate());
  180.             }
  181.         });

  182.         boolean doneWithStep = false;
  183.         resetEvents:
  184.         do {

  185.             // Evaluate all event detectors for events
  186.             occurringEvents.clear();
  187.             for (final FieldEventState<?, T> state : eventsStates) {
  188.                 if (state.evaluateStep(interpolator)) {
  189.                     // the event occurs during the current step
  190.                     occurringEvents.add(state);
  191.                 }
  192.             }


  193.             do {

  194.                 eventLoop:
  195.                 while (!occurringEvents.isEmpty()) {

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

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

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

  202.                     // try to advance all event states to current time
  203.                     for (final FieldEventState<?, T> state : eventsStates) {
  204.                         if (state != currentEvent && state.tryAdvance(eventState, interpolator)) {
  205.                             // we need to handle another event first
  206.                             // remove event we just updated to prevent heap corruption
  207.                             occurringEvents.remove(state);
  208.                             // add it back to update its position in the heap
  209.                             occurringEvents.add(state);
  210.                             // re-queue the event we were processing
  211.                             occurringEvents.add(currentEvent);
  212.                             continue eventLoop;
  213.                         }
  214.                     }
  215.                     // all event detectors agree we can advance to the current event time

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

  218.                     // acknowledge event occurrence
  219.                     final EventOccurrence<T> occurrence = currentEvent.doEvent(eventState);
  220.                     final Action action = occurrence.getAction();
  221.                     isLastStep = action == Action.STOP;
  222.                     if (isLastStep) {

  223.                         // ensure the event is after the root if it is returned STOP
  224.                         // this lets the user integrate to a STOP event and then restart
  225.                         // integration from the same time.
  226.                         final FieldSpacecraftState<T> savedState = eventState;
  227.                         eventState = interpolator.getInterpolatedState(occurrence.getStopDate());
  228.                         restricted = restricted.restrictStep(savedState, eventState);

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

  232.                     }

  233.                     if (isLastStep) {
  234.                         // the event asked to stop integration
  235.                         return eventState;
  236.                     }

  237.                     if (action == Action.RESET_DERIVATIVES || action == Action.RESET_STATE) {
  238.                         // some event handler has triggered changes that
  239.                         // invalidate the derivatives, we need to recompute them
  240.                         final FieldSpacecraftState<T> resetState = occurrence.getNewState();
  241.                         resetIntermediateState(resetState, interpolator.isForward());
  242.                         return resetState;
  243.                     }
  244.                     // at this point action == Action.CONTINUE or Action.RESET_EVENTS

  245.                     // prepare handling of the remaining part of the step
  246.                     previous = eventState;
  247.                     restricted = new FieldBasicStepInterpolator(restricted.isForward(), eventState, current);

  248.                     if (action == Action.RESET_EVENTS) {
  249.                         continue resetEvents;
  250.                     }

  251.                     // at this pint action == Action.CONTINUE
  252.                     // check if the same event occurs again in the remaining part of the step
  253.                     if (currentEvent.evaluateStep(restricted)) {
  254.                         // the event occurs during the current step
  255.                         occurringEvents.add(currentEvent);
  256.                     }

  257.                 }

  258.                 // last part of the step, after the last event. Advance all detectors to
  259.                 // the end of the step. Should only detect a new event here if an event
  260.                 // modified the g function of another detector. Detecting such events here
  261.                 // is unreliable and RESET_EVENTS should be used instead. Might as well
  262.                 // re-check here because we have to loop through all the detectors anyway
  263.                 // and the alternative is to throw an exception.
  264.                 for (final FieldEventState<?, T> state : eventsStates) {
  265.                     if (state.tryAdvance(current, interpolator)) {
  266.                         occurringEvents.add(state);
  267.                     }
  268.                 }

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

  270.             doneWithStep = true;
  271.         } while (!doneWithStep);

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

  273.         // handle the remaining part of the step, after all events if any
  274.         getMultiplexer().handleStep(restricted);
  275.         if (isLastStep) {
  276.             getMultiplexer().finish(restricted.getCurrentState());
  277.         }

  278.         return current;

  279.     }

  280.     /** Get the mass.
  281.      * @param date target date for the orbit
  282.      * @return mass mass
  283.      */
  284.     protected abstract T getMass(FieldAbsoluteDate<T> date);

  285.     /** Get PV coordinates provider.
  286.      * @return PV coordinates provider
  287.      */
  288.     public FieldPVCoordinatesProvider<T> getPvProvider() {
  289.         return pvProvider;
  290.     }

  291.     /** Reset an intermediate state.
  292.      * @param state new intermediate state to consider
  293.      * @param forward if true, the intermediate state is valid for
  294.      * propagations after itself
  295.      */
  296.     protected abstract void resetIntermediateState(FieldSpacecraftState<T> state, boolean forward);

  297.     /** Extrapolate an orbit up to a specific target date.
  298.      * @param date target date for the orbit
  299.      * @param parameters model parameters
  300.      * @return extrapolated parameters
  301.      */
  302.     protected abstract FieldOrbit<T> propagateOrbit(FieldAbsoluteDate<T> date, T[] parameters);

  303.     /** Propagate an orbit without any fancy features.
  304.      * <p>This method is similar in spirit to the {@link #propagate} method,
  305.      * except that it does <strong>not</strong> call any handler during
  306.      * propagation, nor any discrete events, not additional states. It always
  307.      * stop exactly at the specified date.</p>
  308.      * @param date target date for propagation
  309.      * @return state at specified date
  310.      */
  311.     protected FieldSpacecraftState<T> basicPropagate(final FieldAbsoluteDate<T> date) {
  312.         try {

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

  315.             // evaluate attitude
  316.             final FieldAttitude<T> attitude =
  317.                 getAttitudeProvider().getAttitude(pvProvider, date, orbit.getFrame());

  318.             // build raw state
  319.             return new FieldSpacecraftState<>(orbit, attitude, getMass(date));

  320.         } catch (OrekitException oe) {
  321.             throw new OrekitException(oe);
  322.         }
  323.     }

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

  326.         /** {@inheritDoc} */
  327.         @Override
  328.         public TimeStampedFieldPVCoordinates<T> getPVCoordinates(final FieldAbsoluteDate<T> date, final Frame frame) {
  329.             return propagateOrbit(date, getParameters(date.getField(), date)).getPVCoordinates(frame);
  330.         }

  331.     }

  332.     /** {@link BoundedPropagator} view of the instance. */
  333.     private class FieldBoundedPropagatorView extends FieldAbstractAnalyticalPropagator<T>
  334.         implements FieldBoundedPropagator<T> {

  335.         /** Min date. */
  336.         private final FieldAbsoluteDate<T> minDate;

  337.         /** Max date. */
  338.         private final FieldAbsoluteDate<T> maxDate;

  339.         /** Simple constructor.
  340.          * @param startDate start date of the propagation
  341.          * @param endDate end date of the propagation
  342.          */
  343.         FieldBoundedPropagatorView(final FieldAbsoluteDate<T> startDate, final FieldAbsoluteDate<T> endDate) {
  344.             super(startDate.durationFrom(endDate).getField(), FieldAbstractAnalyticalPropagator.this.getAttitudeProvider());
  345.             super.resetInitialState(FieldAbstractAnalyticalPropagator.this.getInitialState());
  346.             if (startDate.compareTo(endDate) <= 0) {
  347.                 minDate = startDate;
  348.                 maxDate = endDate;
  349.             } else {
  350.                 minDate = endDate;
  351.                 maxDate = startDate;
  352.             }

  353.             try {
  354.                 // copy the same additional state providers as the original propagator
  355.                 for (FieldAdditionalStateProvider<T> provider : FieldAbstractAnalyticalPropagator.this.getAdditionalStateProviders()) {
  356.                     addAdditionalStateProvider(provider);
  357.                 }
  358.             } catch (OrekitException oe) {
  359.                 // as the providers are already compatible with each other,
  360.                 // this should never happen
  361.                 throw new OrekitInternalError(null);
  362.             }

  363.         }

  364.         /** {@inheritDoc} */
  365.         @Override
  366.         public FieldAbsoluteDate<T> getMinDate() {
  367.             return minDate;
  368.         }

  369.         /** {@inheritDoc} */
  370.         @Override
  371.         public FieldAbsoluteDate<T> getMaxDate() {
  372.             return maxDate;
  373.         }

  374.         /** {@inheritDoc} */
  375.         @Override
  376.         protected FieldOrbit<T> propagateOrbit(final FieldAbsoluteDate<T> target, final T[] parameters) {
  377.             return FieldAbstractAnalyticalPropagator.this.propagateOrbit(target, parameters);
  378.         }

  379.         /** {@inheritDoc} */
  380.         @Override
  381.         public T getMass(final FieldAbsoluteDate<T> date) {
  382.             return FieldAbstractAnalyticalPropagator.this.getMass(date);
  383.         }

  384.         /** {@inheritDoc} */
  385.         @Override
  386.         public void resetInitialState(final FieldSpacecraftState<T> state) {
  387.             super.resetInitialState(state);
  388.             FieldAbstractAnalyticalPropagator.this.resetInitialState(state);
  389.         }

  390.         /** {@inheritDoc} */
  391.         @Override
  392.         protected void resetIntermediateState(final FieldSpacecraftState<T> state, final boolean forward) {
  393.             FieldAbstractAnalyticalPropagator.this.resetIntermediateState(state, forward);
  394.         }

  395.         /** {@inheritDoc} */
  396.         @Override
  397.         public FieldSpacecraftState<T> getInitialState() {
  398.             return FieldAbstractAnalyticalPropagator.this.getInitialState();
  399.         }

  400.         /** {@inheritDoc} */
  401.         @Override
  402.         public Frame getFrame() {
  403.             return FieldAbstractAnalyticalPropagator.this.getFrame();
  404.         }

  405.         /** {@inheritDoc} */
  406.         @Override
  407.         public List<ParameterDriver> getParametersDrivers() {
  408.             return FieldAbstractAnalyticalPropagator.this.getParametersDrivers();
  409.         }
  410.     }

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

  413.         /** Previous state. */
  414.         private final FieldSpacecraftState<T> previousState;

  415.         /** Current state. */
  416.         private final FieldSpacecraftState<T> currentState;

  417.         /** Forward propagation indicator. */
  418.         private final boolean forward;

  419.         /** Simple constructor.
  420.          * @param isForward integration direction indicator
  421.          * @param previousState start of the step
  422.          * @param currentState end of the step
  423.          */
  424.         FieldBasicStepInterpolator(final boolean isForward,
  425.                                    final FieldSpacecraftState<T> previousState,
  426.                                    final FieldSpacecraftState<T> currentState) {
  427.             this.forward             = isForward;
  428.             this.previousState   = previousState;
  429.             this.currentState    = currentState;
  430.         }

  431.         /** {@inheritDoc} */
  432.         @Override
  433.         public FieldSpacecraftState<T> getPreviousState() {
  434.             return previousState;
  435.         }

  436.         /** {@inheritDoc} */
  437.         @Override
  438.         public FieldSpacecraftState<T> getCurrentState() {
  439.             return currentState;
  440.         }

  441.         /** {@inheritDoc} */
  442.         @Override
  443.         public FieldSpacecraftState<T> getInterpolatedState(final FieldAbsoluteDate<T> date) {

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

  446.             // add the additional states
  447.             return updateAdditionalStates(basicState);

  448.         }

  449.         /** {@inheritDoc} */
  450.         @Override
  451.         public boolean isForward() {
  452.             return forward;
  453.         }

  454.         /** {@inheritDoc} */
  455.         @Override
  456.         public FieldBasicStepInterpolator restrictStep(final FieldSpacecraftState<T> newPreviousState,
  457.                                                        final FieldSpacecraftState<T> newCurrentState) {
  458.             return new FieldBasicStepInterpolator(forward, newPreviousState, newCurrentState);
  459.         }

  460.     }

  461. }