AbstractAnalyticalPropagator.java

  1. /* Copyright 2002-2021 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.exception.MathRuntimeException;
  26. import org.hipparchus.ode.events.Action;
  27. import org.orekit.attitudes.Attitude;
  28. import org.orekit.attitudes.AttitudeProvider;
  29. import org.orekit.errors.OrekitException;
  30. import org.orekit.errors.OrekitInternalError;
  31. import org.orekit.frames.Frame;
  32. import org.orekit.orbits.Orbit;
  33. import org.orekit.propagation.AbstractPropagator;
  34. import org.orekit.propagation.AdditionalStateProvider;
  35. import org.orekit.propagation.BoundedPropagator;
  36. import org.orekit.propagation.EphemerisGenerator;
  37. import org.orekit.propagation.SpacecraftState;
  38. import org.orekit.propagation.events.EventDetector;
  39. import org.orekit.propagation.events.EventState;
  40. import org.orekit.propagation.events.EventState.EventOccurrence;
  41. import org.orekit.propagation.sampling.OrekitStepInterpolator;
  42. import org.orekit.time.AbsoluteDate;
  43. import org.orekit.utils.PVCoordinatesProvider;
  44. import org.orekit.utils.TimeStampedPVCoordinates;

  45. /** Common handling of {@link org.orekit.propagation.Propagator} methods for analytical propagators.
  46.  * <p>
  47.  * This abstract class allows to provide easily the full set of {@link
  48.  * org.orekit.propagation.Propagator Propagator} methods, including all propagation
  49.  * modes support and discrete events support for any simple propagation method. Only
  50.  * two methods must be implemented by derived classes: {@link #propagateOrbit(AbsoluteDate)}
  51.  * and {@link #getMass(AbsoluteDate)}. The first method should perform straightforward
  52.  * propagation starting from some internally stored initial state up to the specified target date.
  53.  * </p>
  54.  * @author Luc Maisonobe
  55.  */
  56. public abstract class AbstractAnalyticalPropagator extends AbstractPropagator {

  57.     /** Provider for attitude computation. */
  58.     private PVCoordinatesProvider pvProvider;

  59.     /** Start date of last propagation. */
  60.     private AbsoluteDate lastPropagationStart;

  61.     /** End date of last propagation. */
  62.     private AbsoluteDate lastPropagationEnd;

  63.     /** Initialization indicator of events states. */
  64.     private boolean statesInitialized;

  65.     /** Indicator for last step. */
  66.     private boolean isLastStep;

  67.     /** Event steps. */
  68.     private final Collection<EventState<?>> eventsStates;

  69.     /** Build a new instance.
  70.      * @param attitudeProvider provider for attitude computation
  71.      */
  72.     protected AbstractAnalyticalPropagator(final AttitudeProvider attitudeProvider) {
  73.         setAttitudeProvider(attitudeProvider);
  74.         pvProvider           = new LocalPVProvider();
  75.         lastPropagationStart = AbsoluteDate.PAST_INFINITY;
  76.         lastPropagationEnd   = AbsoluteDate.FUTURE_INFINITY;
  77.         statesInitialized    = false;
  78.         eventsStates         = new ArrayList<>();
  79.     }

  80.     /** {@inheritDoc} */
  81.     @Override
  82.     public EphemerisGenerator getEphemerisGenerator() {
  83.         return () -> new BoundedPropagatorView(lastPropagationStart, lastPropagationEnd);
  84.     }

  85.     /** {@inheritDoc} */
  86.     public <T extends EventDetector> void addEventDetector(final T detector) {
  87.         eventsStates.add(new EventState<>(detector));
  88.     }

  89.     /** {@inheritDoc} */
  90.     public Collection<EventDetector> getEventsDetectors() {
  91.         final List<EventDetector> list = new ArrayList<>();
  92.         for (final EventState<?> state : eventsStates) {
  93.             list.add(state.getEventDetector());
  94.         }
  95.         return Collections.unmodifiableCollection(list);
  96.     }

  97.     /** {@inheritDoc} */
  98.     public void clearEventsDetectors() {
  99.         eventsStates.clear();
  100.     }

  101.     /** {@inheritDoc} */
  102.     public SpacecraftState propagate(final AbsoluteDate start, final AbsoluteDate target) {
  103.         try {

  104.             initializePropagation();

  105.             lastPropagationStart = start;

  106.             final boolean isForward = target.compareTo(start) >= 0;
  107.             SpacecraftState state   = updateAdditionalStates(basicPropagate(start));

  108.             // initialize event detectors
  109.             for (final EventState<?> es : eventsStates) {
  110.                 es.init(state, target);
  111.             }

  112.             // initialize step handlers
  113.             getMultiplexer().init(state, target);

  114.             // iterate over the propagation range, need loop due to reset events
  115.             statesInitialized = false;
  116.             isLastStep = false;
  117.             do {

  118.                 // attempt to advance to the target date
  119.                 final SpacecraftState previous = state;
  120.                 final SpacecraftState current = updateAdditionalStates(basicPropagate(target));
  121.                 final OrekitStepInterpolator interpolator =
  122.                         new BasicStepInterpolator(isForward, previous, current);

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

  125.                 // Update the potential changes in the spacecraft state due to the events
  126.                 // especially the potential attitude transition
  127.                 state = updateAdditionalStates(basicPropagate(state.getDate()));

  128.             } while (!isLastStep);

  129.             // return the last computed state
  130.             lastPropagationEnd = state.getDate();
  131.             setStartDate(state.getDate());
  132.             return state;

  133.         } catch (MathRuntimeException mrte) {
  134.             throw OrekitException.unwrap(mrte);
  135.         }
  136.     }

  137.     /** Accept a step, triggering events and step handlers.
  138.      * @param interpolator interpolator for the current step
  139.      * @param target final propagation time
  140.      * @return state at the end of the step
  141.      * @exception MathRuntimeException if an event cannot be located
  142.      */
  143.     protected SpacecraftState acceptStep(final OrekitStepInterpolator interpolator,
  144.                                          final AbsoluteDate target)
  145.         throws MathRuntimeException {

  146.         SpacecraftState        previous   = interpolator.getPreviousState();
  147.         final SpacecraftState  current    = interpolator.getCurrentState();
  148.         OrekitStepInterpolator restricted = interpolator;


  149.         // initialize the events states if needed
  150.         if (!statesInitialized) {

  151.             if (!eventsStates.isEmpty()) {
  152.                 // initialize the events states
  153.                 for (final EventState<?> state : eventsStates) {
  154.                     state.reinitializeBegin(interpolator);
  155.                 }
  156.             }

  157.             statesInitialized = true;

  158.         }

  159.         // search for next events that may occur during the step
  160.         final int orderingSign = interpolator.isForward() ? +1 : -1;
  161.         final Queue<EventState<?>> occurringEvents = new PriorityQueue<>(new Comparator<EventState<?>>() {
  162.             /** {@inheritDoc} */
  163.             @Override
  164.             public int compare(final EventState<?> es0, final EventState<?> es1) {
  165.                 return orderingSign * es0.getEventDate().compareTo(es1.getEventDate());
  166.             }
  167.         });

  168.         boolean doneWithStep = false;
  169.         resetEvents:
  170.         do {

  171.             // Evaluate all event detectors for events
  172.             occurringEvents.clear();
  173.             for (final EventState<?> state : eventsStates) {
  174.                 if (state.evaluateStep(interpolator)) {
  175.                     // the event occurs during the current step
  176.                     occurringEvents.add(state);
  177.                 }
  178.             }

  179.             do {

  180.                 eventLoop:
  181.                 while (!occurringEvents.isEmpty()) {

  182.                     // handle the chronologically first event
  183.                     final EventState<?> currentEvent = occurringEvents.poll();

  184.                     // get state at event time
  185.                     SpacecraftState eventState = restricted.getInterpolatedState(currentEvent.getEventDate());

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

  188.                     // try to advance all event states to current time
  189.                     for (final EventState<?> state : eventsStates) {
  190.                         if (state != currentEvent && state.tryAdvance(eventState, interpolator)) {
  191.                             // we need to handle another event first
  192.                             // remove event we just updated to prevent heap corruption
  193.                             occurringEvents.remove(state);
  194.                             // add it back to update its position in the heap
  195.                             occurringEvents.add(state);
  196.                             // re-queue the event we were processing
  197.                             occurringEvents.add(currentEvent);
  198.                             continue eventLoop;
  199.                         }
  200.                     }
  201.                     // all event detectors agree we can advance to the current event time

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

  204.                     // acknowledge event occurrence
  205.                     final EventOccurrence occurrence = currentEvent.doEvent(eventState);
  206.                     final Action action = occurrence.getAction();
  207.                     isLastStep = action == Action.STOP;

  208.                     if (isLastStep) {

  209.                         // ensure the event is after the root if it is returned STOP
  210.                         // this lets the user integrate to a STOP event and then restart
  211.                         // integration from the same time.
  212.                         final SpacecraftState savedState = eventState;
  213.                         eventState = interpolator.getInterpolatedState(occurrence.getStopDate());
  214.                         restricted = restricted.restrictStep(savedState, eventState);

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

  218.                     }

  219.                     if (isLastStep) {
  220.                         // the event asked to stop integration
  221.                         return eventState;
  222.                     }

  223.                     if (action == Action.RESET_DERIVATIVES || action == Action.RESET_STATE) {
  224.                         // some event handler has triggered changes that
  225.                         // invalidate the derivatives, we need to recompute them
  226.                         final SpacecraftState resetState = occurrence.getNewState();
  227.                         resetIntermediateState(resetState, interpolator.isForward());
  228.                         return resetState;
  229.                     }
  230.                     // at this point action == Action.CONTINUE or Action.RESET_EVENTS

  231.                     // prepare handling of the remaining part of the step
  232.                     previous = eventState;
  233.                     restricted = new BasicStepInterpolator(restricted.isForward(), eventState, current);

  234.                     if (action == Action.RESET_EVENTS) {
  235.                         continue resetEvents;
  236.                     }

  237.                     // at this point action == Action.CONTINUE
  238.                     // check if the same event occurs again in the remaining part of the step
  239.                     if (currentEvent.evaluateStep(restricted)) {
  240.                         // the event occurs during the current step
  241.                         occurringEvents.add(currentEvent);
  242.                     }

  243.                 }

  244.                 // last part of the step, after the last event. Advance all detectors to
  245.                 // the end of the step. Should only detect a new event here if an event
  246.                 // modified the g function of another detector. Detecting such events here
  247.                 // is unreliable and RESET_EVENTS should be used instead. Might as well
  248.                 // re-check here because we have to loop through all the detectors anyway
  249.                 // and the alternative is to throw an exception.
  250.                 for (final EventState<?> state : eventsStates) {
  251.                     if (state.tryAdvance(current, interpolator)) {
  252.                         occurringEvents.add(state);
  253.                     }
  254.                 }

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

  256.             doneWithStep = true;
  257.         } while (!doneWithStep);

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

  259.         // handle the remaining part of the step, after all events if any
  260.         getMultiplexer().handleStep(restricted);
  261.         if (isLastStep) {
  262.             getMultiplexer().finish(restricted.getCurrentState());
  263.         }

  264.         return current;

  265.     }

  266.     /** Get the mass.
  267.      * @param date target date for the orbit
  268.      * @return mass mass
  269.      */
  270.     protected abstract double getMass(AbsoluteDate date);

  271.     /** Get PV coordinates provider.
  272.      * @return PV coordinates provider
  273.      */
  274.     public PVCoordinatesProvider getPvProvider() {
  275.         return pvProvider;
  276.     }

  277.     /** Reset an intermediate state.
  278.      * @param state new intermediate state to consider
  279.      * @param forward if true, the intermediate state is valid for
  280.      * propagations after itself
  281.      */
  282.     protected abstract void resetIntermediateState(SpacecraftState state, boolean forward);

  283.     /** Extrapolate an orbit up to a specific target date.
  284.      * @param date target date for the orbit
  285.      * @return extrapolated parameters
  286.      */
  287.     protected abstract Orbit propagateOrbit(AbsoluteDate date);

  288.     /** Propagate an orbit without any fancy features.
  289.      * <p>This method is similar in spirit to the {@link #propagate} method,
  290.      * except that it does <strong>not</strong> call any handler during
  291.      * propagation, nor any discrete events, not additional states. It always
  292.      * stop exactly at the specified date.</p>
  293.      * @param date target date for propagation
  294.      * @return state at specified date
  295.      */
  296.     protected SpacecraftState basicPropagate(final AbsoluteDate date) {
  297.         try {

  298.             // evaluate orbit
  299.             final Orbit orbit = propagateOrbit(date);

  300.             // evaluate attitude
  301.             final Attitude attitude =
  302.                 getAttitudeProvider().getAttitude(pvProvider, date, orbit.getFrame());

  303.             // build raw state
  304.             return new SpacecraftState(orbit, attitude, getMass(date));

  305.         } catch (OrekitException oe) {
  306.             throw new OrekitException(oe);
  307.         }
  308.     }

  309.     /** Internal PVCoordinatesProvider for attitude computation. */
  310.     private class LocalPVProvider implements PVCoordinatesProvider {

  311.         /** {@inheritDoc} */
  312.         public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
  313.             return propagateOrbit(date).getPVCoordinates(frame);
  314.         }

  315.     }

  316.     /** {@link BoundedPropagator} view of the instance. */
  317.     private class BoundedPropagatorView extends AbstractAnalyticalPropagator implements BoundedPropagator {

  318.         /** Min date. */
  319.         private final AbsoluteDate minDate;

  320.         /** Max date. */
  321.         private final AbsoluteDate maxDate;

  322.         /** Simple constructor.
  323.          * @param startDate start date of the propagation
  324.          * @param endDate end date of the propagation
  325.          */
  326.         BoundedPropagatorView(final AbsoluteDate startDate, final AbsoluteDate endDate) {
  327.             super(AbstractAnalyticalPropagator.this.getAttitudeProvider());
  328.             super.resetInitialState(AbstractAnalyticalPropagator.this.getInitialState());
  329.             if (startDate.compareTo(endDate) <= 0) {
  330.                 minDate = startDate;
  331.                 maxDate = endDate;
  332.             } else {
  333.                 minDate = endDate;
  334.                 maxDate = startDate;
  335.             }

  336.             try {
  337.                 // copy the same additional state providers as the original propagator
  338.                 for (AdditionalStateProvider provider : AbstractAnalyticalPropagator.this.getAdditionalStateProviders()) {
  339.                     addAdditionalStateProvider(provider);
  340.                 }
  341.             } catch (OrekitException oe) {
  342.                 // as the providers are already compatible with each other,
  343.                 // this should never happen
  344.                 throw new OrekitInternalError(null);
  345.             }

  346.         }

  347.         /** {@inheritDoc} */
  348.         public AbsoluteDate getMinDate() {
  349.             return minDate;
  350.         }

  351.         /** {@inheritDoc} */
  352.         public AbsoluteDate getMaxDate() {
  353.             return maxDate;
  354.         }

  355.         /** {@inheritDoc} */
  356.         protected Orbit propagateOrbit(final AbsoluteDate target) {
  357.             return AbstractAnalyticalPropagator.this.propagateOrbit(target);
  358.         }

  359.         /** {@inheritDoc} */
  360.         public double getMass(final AbsoluteDate date) {
  361.             return AbstractAnalyticalPropagator.this.getMass(date);
  362.         }

  363.         /** {@inheritDoc} */
  364.         public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
  365.             return propagate(date).getPVCoordinates(frame);
  366.         }

  367.         /** {@inheritDoc} */
  368.         public void resetInitialState(final SpacecraftState state) {
  369.             super.resetInitialState(state);
  370.             AbstractAnalyticalPropagator.this.resetInitialState(state);
  371.         }

  372.         /** {@inheritDoc} */
  373.         protected void resetIntermediateState(final SpacecraftState state, final boolean forward) {
  374.             AbstractAnalyticalPropagator.this.resetIntermediateState(state, forward);
  375.         }

  376.         /** {@inheritDoc} */
  377.         public SpacecraftState getInitialState() {
  378.             return AbstractAnalyticalPropagator.this.getInitialState();
  379.         }

  380.         /** {@inheritDoc} */
  381.         public Frame getFrame() {
  382.             return AbstractAnalyticalPropagator.this.getFrame();
  383.         }

  384.     }

  385.     /** Internal class for local propagation. */
  386.     private class BasicStepInterpolator implements OrekitStepInterpolator {

  387.         /** Previous state. */
  388.         private final SpacecraftState previousState;

  389.         /** Current state. */
  390.         private final SpacecraftState currentState;

  391.         /** Forward propagation indicator. */
  392.         private final boolean forward;

  393.         /** Simple constructor.
  394.          * @param isForward integration direction indicator
  395.          * @param previousState start of the step
  396.          * @param currentState end of the step
  397.          */
  398.         BasicStepInterpolator(final boolean isForward,
  399.                               final SpacecraftState previousState,
  400.                               final SpacecraftState currentState) {
  401.             this.forward         = isForward;
  402.             this.previousState   = previousState;
  403.             this.currentState    = currentState;
  404.         }

  405.         /** {@inheritDoc} */
  406.         @Override
  407.         public SpacecraftState getPreviousState() {
  408.             return previousState;
  409.         }

  410.         /** {@inheritDoc} */
  411.         @Override
  412.         public boolean isPreviousStateInterpolated() {
  413.             // no difference in analytical propagators
  414.             return false;
  415.         }

  416.         /** {@inheritDoc} */
  417.         @Override
  418.         public SpacecraftState getCurrentState() {
  419.             return currentState;
  420.         }

  421.         /** {@inheritDoc} */
  422.         @Override
  423.         public boolean isCurrentStateInterpolated() {
  424.             // no difference in analytical propagators
  425.             return false;
  426.         }

  427.         /** {@inheritDoc} */
  428.         @Override
  429.         public SpacecraftState getInterpolatedState(final AbsoluteDate date) {

  430.             // compute the basic spacecraft state
  431.             final SpacecraftState basicState = basicPropagate(date);

  432.             // add the additional states
  433.             return updateAdditionalStates(basicState);

  434.         }

  435.         /** {@inheritDoc} */
  436.         @Override
  437.         public boolean isForward() {
  438.             return forward;
  439.         }

  440.         /** {@inheritDoc} */
  441.         @Override
  442.         public BasicStepInterpolator restrictStep(final SpacecraftState newPreviousState,
  443.                                                   final SpacecraftState newCurrentState) {
  444.             return new BasicStepInterpolator(forward, newPreviousState, newCurrentState);
  445.         }

  446.     }

  447. }