AbstractAnalyticalPropagator.java

  1. /* Copyright 2002-2019 CS Systèmes d'Information
  2.  * Licensed to CS Systèmes d'Information (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.io.NotSerializableException;
  19. import java.io.Serializable;
  20. import java.util.ArrayList;
  21. import java.util.Collection;
  22. import java.util.Collections;
  23. import java.util.Comparator;
  24. import java.util.List;
  25. import java.util.PriorityQueue;
  26. import java.util.Queue;

  27. import org.hipparchus.exception.MathRuntimeException;
  28. import org.hipparchus.util.FastMath;
  29. import org.orekit.attitudes.Attitude;
  30. import org.orekit.attitudes.AttitudeProvider;
  31. import org.orekit.errors.OrekitException;
  32. import org.orekit.errors.OrekitInternalError;
  33. import org.orekit.frames.Frame;
  34. import org.orekit.orbits.Orbit;
  35. import org.orekit.propagation.AbstractPropagator;
  36. import org.orekit.propagation.AdditionalStateProvider;
  37. import org.orekit.propagation.BoundedPropagator;
  38. import org.orekit.propagation.SpacecraftState;
  39. import org.orekit.propagation.events.EventDetector;
  40. import org.orekit.propagation.events.EventState;
  41. import org.orekit.propagation.events.EventState.EventOccurrence;
  42. import org.orekit.propagation.events.handlers.EventHandler.Action;
  43. import org.orekit.propagation.sampling.OrekitStepInterpolator;
  44. import org.orekit.time.AbsoluteDate;
  45. import org.orekit.utils.PVCoordinatesProvider;
  46. import org.orekit.utils.TimeStampedPVCoordinates;

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

  59.     /** Provider for attitude computation. */
  60.     private PVCoordinatesProvider pvProvider;

  61.     /** Start date of last propagation. */
  62.     private AbsoluteDate lastPropagationStart;

  63.     /** End date of last propagation. */
  64.     private AbsoluteDate lastPropagationEnd;

  65.     /** Initialization indicator of events states. */
  66.     private boolean statesInitialized;

  67.     /** Indicator for last step. */
  68.     private boolean isLastStep;

  69.     /** Event steps. */
  70.     private final Collection<EventState<?>> eventsStates;

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

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

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

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

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

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

  105.             lastPropagationStart = start;

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

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

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

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

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

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


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

  145.             } while (!isLastStep);

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

  150.         } catch (MathRuntimeException mrte) {
  151.             throw OrekitException.unwrap(mrte);
  152.         }
  153.     }

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

  164.         SpacecraftState       previous = interpolator.getPreviousState();
  165.         final SpacecraftState current  = interpolator.getCurrentState();

  166.         // initialize the events states if needed
  167.         if (!statesInitialized) {

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

  174.             statesInitialized = true;

  175.         }

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

  185.         for (final EventState<?> state : eventsStates) {
  186.             if (state.evaluateStep(interpolator)) {
  187.                 // the event occurs during the current step
  188.                 occurringEvents.add(state);
  189.             }
  190.         }

  191.         OrekitStepInterpolator restricted = interpolator;

  192.         do {

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

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

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

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

  213.                 final EventOccurrence occurrence = currentEvent.doEvent(eventState);
  214.                 final Action action = occurrence.getAction();
  215.                 isLastStep = action == Action.STOP;

  216.                 if (isLastStep) {
  217.                     // ensure the event is after the root if it is returned STOP
  218.                     // this lets the user integrate to a STOP event and then restart
  219.                     // integration from the same time.
  220.                     eventState = interpolator.getInterpolatedState(occurrence.getStopDate());
  221.                     restricted = restricted.restrictStep(previous, eventState);
  222.                 }

  223.                 // handle the first part of the step, up to the event
  224.                 if (getStepHandler() != null) {
  225.                     getStepHandler().handleStep(restricted, isLastStep);
  226.                 }

  227.                 if (isLastStep) {
  228.                     // the event asked to stop integration
  229.                     return eventState;
  230.                 }

  231.                 if (action == Action.RESET_DERIVATIVES || action == Action.RESET_STATE) {
  232.                     // some event handler has triggered changes that
  233.                     // invalidate the derivatives, we need to recompute them
  234.                     final SpacecraftState resetState = occurrence.getNewState();
  235.                     if (resetState != null) {
  236.                         resetIntermediateState(resetState, interpolator.isForward());
  237.                         return resetState;
  238.                     }
  239.                 }
  240.                 // at this point we know action == Action.CONTINUE

  241.                 // prepare handling of the remaining part of the step
  242.                 previous = eventState;
  243.                 restricted         = new BasicStepInterpolator(restricted.isForward(), eventState, current);

  244.                 // check if the same event occurs again in the remaining part of the step
  245.                 if (currentEvent.evaluateStep(restricted)) {
  246.                     // the event occurs during the current step
  247.                     occurringEvents.add(currentEvent);
  248.                 }

  249.             }

  250.             // last part of the step, after the last event
  251.             // may be a new event here if the last event modified the g function of
  252.             // another event detector.
  253.             for (final EventState<?> state : eventsStates) {
  254.                 if (state.tryAdvance(current, interpolator)) {
  255.                     occurringEvents.add(state);
  256.                 }
  257.             }

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

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

  260.         // handle the remaining part of the step, after all events if any
  261.         if (getStepHandler() != null) {
  262.             getStepHandler().handleStep(interpolator, isLastStep);
  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
  318.         extends AbstractAnalyticalPropagator
  319.         implements BoundedPropagator, Serializable {

  320.         /** Serializable UID. */
  321.         private static final long serialVersionUID = 20151117L;

  322.         /** Min date. */
  323.         private final AbsoluteDate minDate;

  324.         /** Max date. */
  325.         private final AbsoluteDate maxDate;

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

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

  349.         }

  350.         /** {@inheritDoc} */
  351.         public AbsoluteDate getMinDate() {
  352.             return minDate;
  353.         }

  354.         /** {@inheritDoc} */
  355.         public AbsoluteDate getMaxDate() {
  356.             return maxDate;
  357.         }

  358.         /** {@inheritDoc} */
  359.         protected Orbit propagateOrbit(final AbsoluteDate target) {
  360.             return AbstractAnalyticalPropagator.this.propagateOrbit(target);
  361.         }

  362.         /** {@inheritDoc} */
  363.         public double getMass(final AbsoluteDate date) {
  364.             return AbstractAnalyticalPropagator.this.getMass(date);
  365.         }

  366.         /** {@inheritDoc} */
  367.         public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
  368.             return propagate(date).getPVCoordinates(frame);
  369.         }

  370.         /** {@inheritDoc} */
  371.         public void resetInitialState(final SpacecraftState state) {
  372.             AbstractAnalyticalPropagator.this.resetInitialState(state);
  373.         }

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

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

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

  386.         /** Replace the instance with a data transfer object for serialization.
  387.          * @return data transfer object that will be serialized
  388.          * @exception NotSerializableException if attitude provider or additional
  389.          * state provider is not serializable
  390.          */
  391.         private Object writeReplace() throws NotSerializableException {
  392.             return new DataTransferObject(minDate, maxDate, AbstractAnalyticalPropagator.this);
  393.         }

  394.     }

  395.     /** Internal class used only for serialization. */
  396.     private static class DataTransferObject implements Serializable {

  397.         /** Serializable UID. */
  398.         private static final long serialVersionUID = 20151117L;

  399.         /** Min date. */
  400.         private final AbsoluteDate minDate;

  401.         /** Max date. */
  402.         private final AbsoluteDate maxDate;

  403.         /** Underlying propagator. */
  404.         private final AbstractAnalyticalPropagator propagator;

  405.         /** Simple constructor.
  406.          * @param minDate min date
  407.          * @param maxDate max date
  408.          * @param propagator underlying propagator
  409.          */
  410.         DataTransferObject(final AbsoluteDate minDate, final AbsoluteDate maxDate,
  411.                            final AbstractAnalyticalPropagator propagator) {
  412.             this.minDate    = minDate;
  413.             this.maxDate    = maxDate;
  414.             this.propagator = propagator;
  415.         }

  416.         /** Replace the deserialized data transfer object with an {@link BoundedPropagatorView}.
  417.          * @return replacement {@link BoundedPropagatorView}
  418.          */
  419.         private Object readResolve() {
  420.             propagator.lastPropagationStart = minDate;
  421.             propagator.lastPropagationEnd   = maxDate;
  422.             return propagator.getGeneratedEphemeris();
  423.         }

  424.     }

  425.     /** Internal class for local propagation. */
  426.     private class BasicStepInterpolator implements OrekitStepInterpolator {

  427.         /** Previous state. */
  428.         private final SpacecraftState previousState;

  429.         /** Current state. */
  430.         private final SpacecraftState currentState;

  431.         /** Forward propagation indicator. */
  432.         private final boolean forward;

  433.         /** Simple constructor.
  434.          * @param isForward integration direction indicator
  435.          * @param previousState start of the step
  436.          * @param currentState end of the step
  437.          */
  438.         BasicStepInterpolator(final boolean isForward,
  439.                               final SpacecraftState previousState,
  440.                               final SpacecraftState currentState) {
  441.             this.forward         = isForward;
  442.             this.previousState   = previousState;
  443.             this.currentState    = currentState;
  444.         }

  445.         /** {@inheritDoc} */
  446.         @Override
  447.         public SpacecraftState getPreviousState() {
  448.             return previousState;
  449.         }

  450.         /** {@inheritDoc} */
  451.         @Override
  452.         public boolean isPreviousStateInterpolated() {
  453.             // no difference in analytical propagators
  454.             return false;
  455.         }

  456.         /** {@inheritDoc} */
  457.         @Override
  458.         public SpacecraftState getCurrentState() {
  459.             return currentState;
  460.         }

  461.         /** {@inheritDoc} */
  462.         @Override
  463.         public boolean isCurrentStateInterpolated() {
  464.             // no difference in analytical propagators
  465.             return false;
  466.         }

  467.         /** {@inheritDoc} */
  468.         @Override
  469.         public SpacecraftState getInterpolatedState(final AbsoluteDate date) {

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

  472.             // add the additional states
  473.             return updateAdditionalStates(basicState);

  474.         }

  475.         /** {@inheritDoc} */
  476.         @Override
  477.         public boolean isForward() {
  478.             return forward;
  479.         }

  480.         /** {@inheritDoc} */
  481.         @Override
  482.         public BasicStepInterpolator restrictStep(final SpacecraftState newPreviousState,
  483.                                                   final SpacecraftState newCurrentState) {
  484.             return new BasicStepInterpolator(forward, newPreviousState, newCurrentState);
  485.         }

  486.     }

  487. }