AbstractAnalyticalPropagator.java

  1. /* Copyright 2002-2022 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.MatricesHarvester;
  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.sampling.OrekitStepInterpolator;
  43. import org.orekit.time.AbsoluteDate;
  44. import org.orekit.utils.PVCoordinatesProvider;
  45. import org.orekit.utils.TimeStampedPVCoordinates;

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

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

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

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

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

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

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

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

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

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

  90.     /** {@inheritDoc} */
  91.     public Collection<EventDetector> getEventsDetectors() {
  92.         final List<EventDetector> list = new ArrayList<>();
  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.             initializePropagation();

  106.             lastPropagationStart = start;

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

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

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

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

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

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

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

  129.             } while (!isLastStep);

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

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

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

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


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

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

  158.             statesInitialized = true;

  159.         }

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

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

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

  180.             do {

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

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

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

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

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

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

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

  209.                     if (isLastStep) {

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

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

  219.                     }

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

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

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

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

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

  244.                 }

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

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

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

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

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

  265.         return current;

  266.     }

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

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

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

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

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

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

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

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

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

  310.     /**
  311.      * Get the names of the parameters in the matrix returned by {@link MatricesHarvester#getParametersJacobian}.
  312.      * @return names of the parameters (i.e. columns) of the Jacobian matrix
  313.      * @since 11.1
  314.      */
  315.     protected List<String> getJacobiansColumnsNames() {
  316.         return Collections.emptyList();
  317.     }

  318.     /** Internal PVCoordinatesProvider for attitude computation. */
  319.     private class LocalPVProvider implements PVCoordinatesProvider {

  320.         /** {@inheritDoc} */
  321.         public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
  322.             return propagateOrbit(date).getPVCoordinates(frame);
  323.         }

  324.     }

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

  327.         /** Min date. */
  328.         private final AbsoluteDate minDate;

  329.         /** Max date. */
  330.         private final AbsoluteDate maxDate;

  331.         /** Simple constructor.
  332.          * @param startDate start date of the propagation
  333.          * @param endDate end date of the propagation
  334.          */
  335.         BoundedPropagatorView(final AbsoluteDate startDate, final AbsoluteDate endDate) {
  336.             super(AbstractAnalyticalPropagator.this.getAttitudeProvider());
  337.             super.resetInitialState(AbstractAnalyticalPropagator.this.getInitialState());
  338.             if (startDate.compareTo(endDate) <= 0) {
  339.                 minDate = startDate;
  340.                 maxDate = endDate;
  341.             } else {
  342.                 minDate = endDate;
  343.                 maxDate = startDate;
  344.             }

  345.             try {
  346.                 // copy the same additional state providers as the original propagator
  347.                 for (AdditionalStateProvider provider : AbstractAnalyticalPropagator.this.getAdditionalStateProviders()) {
  348.                     addAdditionalStateProvider(provider);
  349.                 }
  350.             } catch (OrekitException oe) {
  351.                 // as the generators are already compatible with each other,
  352.                 // this should never happen
  353.                 throw new OrekitInternalError(null);
  354.             }

  355.         }

  356.         /** {@inheritDoc} */
  357.         public AbsoluteDate getMinDate() {
  358.             return minDate;
  359.         }

  360.         /** {@inheritDoc} */
  361.         public AbsoluteDate getMaxDate() {
  362.             return maxDate;
  363.         }

  364.         /** {@inheritDoc} */
  365.         protected Orbit propagateOrbit(final AbsoluteDate target) {
  366.             return AbstractAnalyticalPropagator.this.propagateOrbit(target);
  367.         }

  368.         /** {@inheritDoc} */
  369.         public double getMass(final AbsoluteDate date) {
  370.             return AbstractAnalyticalPropagator.this.getMass(date);
  371.         }

  372.         /** {@inheritDoc} */
  373.         public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
  374.             return propagate(date).getPVCoordinates(frame);
  375.         }

  376.         /** {@inheritDoc} */
  377.         public void resetInitialState(final SpacecraftState state) {
  378.             super.resetInitialState(state);
  379.             AbstractAnalyticalPropagator.this.resetInitialState(state);
  380.         }

  381.         /** {@inheritDoc} */
  382.         protected void resetIntermediateState(final SpacecraftState state, final boolean forward) {
  383.             AbstractAnalyticalPropagator.this.resetIntermediateState(state, forward);
  384.         }

  385.         /** {@inheritDoc} */
  386.         public SpacecraftState getInitialState() {
  387.             return AbstractAnalyticalPropagator.this.getInitialState();
  388.         }

  389.         /** {@inheritDoc} */
  390.         public Frame getFrame() {
  391.             return AbstractAnalyticalPropagator.this.getFrame();
  392.         }

  393.     }

  394.     /** Internal class for local propagation. */
  395.     private class BasicStepInterpolator implements OrekitStepInterpolator {

  396.         /** Previous state. */
  397.         private final SpacecraftState previousState;

  398.         /** Current state. */
  399.         private final SpacecraftState currentState;

  400.         /** Forward propagation indicator. */
  401.         private final boolean forward;

  402.         /** Simple constructor.
  403.          * @param isForward integration direction indicator
  404.          * @param previousState start of the step
  405.          * @param currentState end of the step
  406.          */
  407.         BasicStepInterpolator(final boolean isForward,
  408.                               final SpacecraftState previousState,
  409.                               final SpacecraftState currentState) {
  410.             this.forward         = isForward;
  411.             this.previousState   = previousState;
  412.             this.currentState    = currentState;
  413.         }

  414.         /** {@inheritDoc} */
  415.         @Override
  416.         public SpacecraftState getPreviousState() {
  417.             return previousState;
  418.         }

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

  425.         /** {@inheritDoc} */
  426.         @Override
  427.         public SpacecraftState getCurrentState() {
  428.             return currentState;
  429.         }

  430.         /** {@inheritDoc} */
  431.         @Override
  432.         public boolean isCurrentStateInterpolated() {
  433.             // no difference in analytical propagators
  434.             return false;
  435.         }

  436.         /** {@inheritDoc} */
  437.         @Override
  438.         public SpacecraftState getInterpolatedState(final AbsoluteDate date) {

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

  441.             // add the additional states
  442.             return updateAdditionalStates(basicState);

  443.         }

  444.         /** {@inheritDoc} */
  445.         @Override
  446.         public boolean isForward() {
  447.             return forward;
  448.         }

  449.         /** {@inheritDoc} */
  450.         @Override
  451.         public BasicStepInterpolator restrictStep(final SpacecraftState newPreviousState,
  452.                                                   final SpacecraftState newCurrentState) {
  453.             return new BasicStepInterpolator(forward, newPreviousState, newCurrentState);
  454.         }

  455.     }

  456. }