AbstractAnalyticalPropagator.java

  1. /* Copyright 2002-2020 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.hipparchus.util.FastMath;
  28. import org.orekit.attitudes.Attitude;
  29. import org.orekit.attitudes.AttitudeProvider;
  30. import org.orekit.errors.OrekitException;
  31. import org.orekit.errors.OrekitInternalError;
  32. import org.orekit.frames.Frame;
  33. import org.orekit.orbits.Orbit;
  34. import org.orekit.propagation.AbstractPropagator;
  35. import org.orekit.propagation.AdditionalStateProvider;
  36. import org.orekit.propagation.BoundedPropagator;
  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<EventState<?>>();
  79.     }

  80.     /** {@inheritDoc} */
  81.     public BoundedPropagator getGeneratedEphemeris() {
  82.         return new BoundedPropagatorView(lastPropagationStart, lastPropagationEnd);
  83.     }

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

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

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

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

  103.             initializePropagation();

  104.             lastPropagationStart = start;

  105.             final double dt       = target.durationFrom(start);
  106.             final double epsilon  = FastMath.ulp(dt);
  107.             SpacecraftState state = updateAdditionalStates(basicPropagate(start));

  108.             // evaluate step size
  109.             final double stepSize;
  110.             if (getMode() == MASTER_MODE) {
  111.                 if (Double.isNaN(getFixedStepSize())) {
  112.                     stepSize = FastMath.copySign(state.getKeplerianPeriod() / 100, dt);
  113.                 } else {
  114.                     stepSize = FastMath.copySign(getFixedStepSize(), dt);
  115.                 }
  116.             } else {
  117.                 stepSize = dt;
  118.             }

  119.             // initialize event detectors
  120.             for (final EventState<?> es : eventsStates) {
  121.                 es.init(state, target);
  122.             }

  123.             // initialize step handler
  124.             if (getStepHandler() != null) {
  125.                 getStepHandler().init(state, target);
  126.             }

  127.             // iterate over the propagation range
  128.             statesInitialized = false;
  129.             isLastStep = false;
  130.             do {

  131.                 // go ahead one step size
  132.                 final SpacecraftState previous = state;
  133.                 AbsoluteDate t = previous.getDate().shiftedBy(stepSize);
  134.                 if ((dt == 0) || ((dt > 0) ^ (t.compareTo(target) <= 0)) ||
  135.                         (FastMath.abs(target.durationFrom(t)) <= epsilon)) {
  136.                     // current step exceeds target
  137.                     // or is target to within double precision
  138.                     t = target;
  139.                 }
  140.                 final SpacecraftState current = updateAdditionalStates(basicPropagate(t));
  141.                 final OrekitStepInterpolator interpolator = new BasicStepInterpolator(dt >= 0, previous, current);


  142.                 // accept the step, trigger events and step handlers
  143.                 state = acceptStep(interpolator, target, epsilon);

  144.                 // Update the potential changes in the spacecraft state due to the events
  145.                 // especially the potential attitude transition
  146.                 state = updateAdditionalStates(basicPropagate(state.getDate()));

  147.             } while (!isLastStep);

  148.             // return the last computed state
  149.             lastPropagationEnd = state.getDate();
  150.             setStartDate(state.getDate());
  151.             return state;

  152.         } catch (MathRuntimeException mrte) {
  153.             throw OrekitException.unwrap(mrte);
  154.         }
  155.     }

  156.     /** Accept a step, triggering events and step handlers.
  157.      * @param interpolator interpolator for the current step
  158.      * @param target final propagation time
  159.      * @param epsilon threshold for end date detection
  160.      * @return state at the end of the step
  161.           * @exception MathRuntimeException if an event cannot be located
  162.      */
  163.     protected SpacecraftState acceptStep(final OrekitStepInterpolator interpolator,
  164.                                          final AbsoluteDate target, final double epsilon)
  165.         throws MathRuntimeException {

  166.         SpacecraftState       previous = interpolator.getPreviousState();
  167.         final SpacecraftState current  = interpolator.getCurrentState();
  168.         OrekitStepInterpolator restricted = interpolator;


  169.         // initialize the events states if needed
  170.         if (!statesInitialized) {

  171.             if (!eventsStates.isEmpty()) {
  172.                 // initialize the events states
  173.                 for (final EventState<?> state : eventsStates) {
  174.                     state.reinitializeBegin(interpolator);
  175.                 }
  176.             }

  177.             statesInitialized = true;

  178.         }

  179.         // search for next events that may occur during the step
  180.         final int orderingSign = interpolator.isForward() ? +1 : -1;
  181.         final Queue<EventState<?>> occurringEvents = new PriorityQueue<>(new Comparator<EventState<?>>() {
  182.             /** {@inheritDoc} */
  183.             @Override
  184.             public int compare(final EventState<?> es0, final EventState<?> es1) {
  185.                 return orderingSign * es0.getEventDate().compareTo(es1.getEventDate());
  186.             }
  187.         });

  188.         boolean doneWithStep = false;
  189.         resetEvents:
  190.         do {

  191.             // Evaluate all event detectors for events
  192.             occurringEvents.clear();
  193.             for (final EventState<?> state : eventsStates) {
  194.                 if (state.evaluateStep(interpolator)) {
  195.                     // the event occurs during the current step
  196.                     occurringEvents.add(state);
  197.                 }
  198.             }

  199.             do {

  200.                 eventLoop:
  201.                 while (!occurringEvents.isEmpty()) {

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

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

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

  220.                     final EventOccurrence occurrence = currentEvent.doEvent(eventState);
  221.                     final Action action = occurrence.getAction();
  222.                     isLastStep = action == Action.STOP;

  223.                     if (isLastStep) {
  224.                         // ensure the event is after the root if it is returned STOP
  225.                         // this lets the user integrate to a STOP event and then restart
  226.                         // integration from the same time.
  227.                         eventState = interpolator.getInterpolatedState(occurrence.getStopDate());
  228.                         restricted = restricted.restrictStep(previous, eventState);
  229.                     }

  230.                     // handle the first part of the step, up to the event
  231.                     if (getStepHandler() != null) {
  232.                         getStepHandler().handleStep(restricted, isLastStep);
  233.                     }

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

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

  248.                     // prepare handling of the remaining part of the step
  249.                     previous = eventState;
  250.                     restricted = new BasicStepInterpolator(restricted.isForward(), eventState, current);

  251.                     if (action == Action.RESET_EVENTS) {
  252.                         continue resetEvents;
  253.                     }

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

  260.                 }

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

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

  273.             doneWithStep = true;
  274.         } while (!doneWithStep);

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

  276.         // handle the remaining part of the step, after all events if any
  277.         if (getStepHandler() != null) {
  278.             getStepHandler().handleStep(interpolator, isLastStep);
  279.         }

  280.         return current;

  281.     }

  282.     /** Get the mass.
  283.      * @param date target date for the orbit
  284.      * @return mass mass
  285.      */
  286.     protected abstract double getMass(AbsoluteDate date);

  287.     /** Get PV coordinates provider.
  288.      * @return PV coordinates provider
  289.      */
  290.     public PVCoordinatesProvider getPvProvider() {
  291.         return pvProvider;
  292.     }

  293.     /** Reset an intermediate state.
  294.      * @param state new intermediate state to consider
  295.      * @param forward if true, the intermediate state is valid for
  296.      * propagations after itself
  297.      */
  298.     protected abstract void resetIntermediateState(SpacecraftState state, boolean forward);

  299.     /** Extrapolate an orbit up to a specific target date.
  300.      * @param date target date for the orbit
  301.      * @return extrapolated parameters
  302.      */
  303.     protected abstract Orbit propagateOrbit(AbsoluteDate date);

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

  314.             // evaluate orbit
  315.             final Orbit orbit = propagateOrbit(date);

  316.             // evaluate attitude
  317.             final Attitude attitude =
  318.                 getAttitudeProvider().getAttitude(pvProvider, date, orbit.getFrame());

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

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

  325.     /** Internal PVCoordinatesProvider for attitude computation. */
  326.     private class LocalPVProvider implements PVCoordinatesProvider {

  327.         /** {@inheritDoc} */
  328.         public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
  329.             return propagateOrbit(date).getPVCoordinates(frame);
  330.         }

  331.     }

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

  334.         /** Min date. */
  335.         private final AbsoluteDate minDate;

  336.         /** Max date. */
  337.         private final AbsoluteDate maxDate;

  338.         /** Simple constructor.
  339.          * @param startDate start date of the propagation
  340.          * @param endDate end date of the propagation
  341.          */
  342.         BoundedPropagatorView(final AbsoluteDate startDate, final AbsoluteDate endDate) {
  343.             super(AbstractAnalyticalPropagator.this.getAttitudeProvider());
  344.             if (startDate.compareTo(endDate) <= 0) {
  345.                 minDate = startDate;
  346.                 maxDate = endDate;
  347.             } else {
  348.                 minDate = endDate;
  349.                 maxDate = startDate;
  350.             }

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

  361.         }

  362.         /** {@inheritDoc} */
  363.         public AbsoluteDate getMinDate() {
  364.             return minDate;
  365.         }

  366.         /** {@inheritDoc} */
  367.         public AbsoluteDate getMaxDate() {
  368.             return maxDate;
  369.         }

  370.         /** {@inheritDoc} */
  371.         protected Orbit propagateOrbit(final AbsoluteDate target) {
  372.             return AbstractAnalyticalPropagator.this.propagateOrbit(target);
  373.         }

  374.         /** {@inheritDoc} */
  375.         public double getMass(final AbsoluteDate date) {
  376.             return AbstractAnalyticalPropagator.this.getMass(date);
  377.         }

  378.         /** {@inheritDoc} */
  379.         public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
  380.             return propagate(date).getPVCoordinates(frame);
  381.         }

  382.         /** {@inheritDoc} */
  383.         public void resetInitialState(final SpacecraftState state) {
  384.             AbstractAnalyticalPropagator.this.resetInitialState(state);
  385.         }

  386.         /** {@inheritDoc} */
  387.         protected void resetIntermediateState(final SpacecraftState state, final boolean forward) {
  388.             AbstractAnalyticalPropagator.this.resetIntermediateState(state, forward);
  389.         }

  390.         /** {@inheritDoc} */
  391.         public SpacecraftState getInitialState() {
  392.             return AbstractAnalyticalPropagator.this.getInitialState();
  393.         }

  394.         /** {@inheritDoc} */
  395.         public Frame getFrame() {
  396.             return AbstractAnalyticalPropagator.this.getFrame();
  397.         }

  398.     }

  399.     /** Internal class for local propagation. */
  400.     private class BasicStepInterpolator implements OrekitStepInterpolator {

  401.         /** Previous state. */
  402.         private final SpacecraftState previousState;

  403.         /** Current state. */
  404.         private final SpacecraftState currentState;

  405.         /** Forward propagation indicator. */
  406.         private final boolean forward;

  407.         /** Simple constructor.
  408.          * @param isForward integration direction indicator
  409.          * @param previousState start of the step
  410.          * @param currentState end of the step
  411.          */
  412.         BasicStepInterpolator(final boolean isForward,
  413.                               final SpacecraftState previousState,
  414.                               final SpacecraftState currentState) {
  415.             this.forward         = isForward;
  416.             this.previousState   = previousState;
  417.             this.currentState    = currentState;
  418.         }

  419.         /** {@inheritDoc} */
  420.         @Override
  421.         public SpacecraftState getPreviousState() {
  422.             return previousState;
  423.         }

  424.         /** {@inheritDoc} */
  425.         @Override
  426.         public boolean isPreviousStateInterpolated() {
  427.             // no difference in analytical propagators
  428.             return false;
  429.         }

  430.         /** {@inheritDoc} */
  431.         @Override
  432.         public SpacecraftState getCurrentState() {
  433.             return currentState;
  434.         }

  435.         /** {@inheritDoc} */
  436.         @Override
  437.         public boolean isCurrentStateInterpolated() {
  438.             // no difference in analytical propagators
  439.             return false;
  440.         }

  441.         /** {@inheritDoc} */
  442.         @Override
  443.         public SpacecraftState getInterpolatedState(final AbsoluteDate date) {

  444.             // compute the basic spacecraft state
  445.             final SpacecraftState 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 BasicStepInterpolator restrictStep(final SpacecraftState newPreviousState,
  457.                                                   final SpacecraftState newCurrentState) {
  458.             return new BasicStepInterpolator(forward, newPreviousState, newCurrentState);
  459.         }

  460.     }

  461. }