AbstractAnalyticalPropagator.java

  1. /* Copyright 2002-2024 CS GROUP
  2.  * Licensed to CS GROUP (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.propagation.analytical;

  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.Comparator;
  22. import java.util.List;
  23. import java.util.PriorityQueue;
  24. import java.util.Queue;

  25. import org.hipparchus.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.OrekitIllegalArgumentException;
  31. import org.orekit.errors.OrekitInternalError;
  32. import org.orekit.errors.OrekitMessages;
  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.EphemerisGenerator;
  39. import org.orekit.propagation.MatricesHarvester;
  40. import org.orekit.propagation.SpacecraftState;
  41. import org.orekit.propagation.events.EventDetector;
  42. import org.orekit.propagation.events.EventState;
  43. import org.orekit.propagation.events.EventState.EventOccurrence;
  44. import org.orekit.propagation.sampling.OrekitStepInterpolator;
  45. import org.orekit.time.AbsoluteDate;
  46. import org.orekit.utils.PVCoordinatesProvider;
  47. import org.orekit.utils.TimeStampedPVCoordinates;

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

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

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

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

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

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

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

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

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

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

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

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

  104.     /** {@inheritDoc} */
  105.     public SpacecraftState propagate(final AbsoluteDate start, final AbsoluteDate target) {
  106.         checkStartDateIsNotInfinity(start);
  107.         try {
  108.             initializePropagation();

  109.             lastPropagationStart = start;

  110.             // Initialize additional states
  111.             initializeAdditionalStates(target);

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

  114.             // initialize event detectors
  115.             for (final EventState<?> es : eventsStates) {
  116.                 es.init(state, target);
  117.             }

  118.             // initialize step handlers
  119.             getMultiplexer().init(state, target);

  120.             // iterate over the propagation range, need loop due to reset events
  121.             statesInitialized = false;
  122.             isLastStep = false;
  123.             do {

  124.                 // attempt to advance to the target date
  125.                 final SpacecraftState previous = state;
  126.                 final SpacecraftState current = updateAdditionalStates(basicPropagate(target));
  127.                 final OrekitStepInterpolator interpolator =
  128.                         new BasicStepInterpolator(isForward, previous, current);

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

  131.                 // Update the potential changes in the spacecraft state due to the events
  132.                 // especially the potential attitude transition
  133.                 state = updateAdditionalStates(basicPropagate(state.getDate()));

  134.             } while (!isLastStep);

  135.             // return the last computed state
  136.             lastPropagationEnd = state.getDate();
  137.             setStartDate(state.getDate());
  138.             return state;

  139.         } catch (MathRuntimeException mrte) {
  140.             throw OrekitException.unwrap(mrte);
  141.         }
  142.     }

  143.     /**
  144.      * Check the starting date is not {@code AbsoluteDate.PAST_INFINITY} or {@code AbsoluteDate.FUTURE_INFINITY}.
  145.      * @param start propagation starting date
  146.      */
  147.     private void checkStartDateIsNotInfinity(final AbsoluteDate start) {
  148.         if (start.isEqualTo(AbsoluteDate.PAST_INFINITY) || start.isEqualTo(AbsoluteDate.FUTURE_INFINITY)) {
  149.             throw new OrekitIllegalArgumentException(OrekitMessages.CANNOT_START_PROPAGATION_FROM_INFINITY);
  150.         }
  151.     }

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

  161.         SpacecraftState        previous   = interpolator.getPreviousState();
  162.         final SpacecraftState  current    = interpolator.getCurrentState();
  163.         OrekitStepInterpolator restricted = interpolator;


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

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

  172.             statesInitialized = true;

  173.         }

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

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

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

  194.             do {

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

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

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

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

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

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

  219.                     // acknowledge event occurrence
  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.                         final SpacecraftState savedState = eventState;
  228.                         eventState = interpolator.getInterpolatedState(occurrence.getStopDate());
  229.                         restricted = restricted.restrictStep(savedState, eventState);

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

  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.                         resetIntermediateState(resetState, interpolator.isForward());
  243.                         return resetState;
  244.                     }
  245.                     // at this point action == Action.CONTINUE or Action.RESET_EVENTS

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

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

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

  258.                 }

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

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

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

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

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

  279.         return current;

  280.     }

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

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

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

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

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

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

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

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

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

  324.     /**
  325.      * Get the names of the parameters in the matrix returned by {@link MatricesHarvester#getParametersJacobian}.
  326.      * @return names of the parameters (i.e. columns) of the Jacobian matrix
  327.      * @since 11.1
  328.      */
  329.     protected List<String> getJacobiansColumnsNames() {
  330.         return Collections.emptyList();
  331.     }

  332.     /** Internal PVCoordinatesProvider for attitude computation. */
  333.     private class LocalPVProvider implements PVCoordinatesProvider {

  334.         /** {@inheritDoc} */
  335.         public TimeStampedPVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame) {
  336.             return propagateOrbit(date).getPVCoordinates(frame);
  337.         }

  338.     }

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

  341.         /** Min date. */
  342.         private final AbsoluteDate minDate;

  343.         /** Max date. */
  344.         private final AbsoluteDate maxDate;

  345.         /** Simple constructor.
  346.          * @param startDate start date of the propagation
  347.          * @param endDate end date of the propagation
  348.          */
  349.         BoundedPropagatorView(final AbsoluteDate startDate, final AbsoluteDate endDate) {
  350.             super(AbstractAnalyticalPropagator.this.getAttitudeProvider());
  351.             super.resetInitialState(AbstractAnalyticalPropagator.this.getInitialState());
  352.             if (startDate.compareTo(endDate) <= 0) {
  353.                 minDate = startDate;
  354.                 maxDate = endDate;
  355.             } else {
  356.                 minDate = endDate;
  357.                 maxDate = startDate;
  358.             }

  359.             try {
  360.                 // copy the same additional state providers as the original propagator
  361.                 for (AdditionalStateProvider provider : AbstractAnalyticalPropagator.this.getAdditionalStateProviders()) {
  362.                     addAdditionalStateProvider(provider);
  363.                 }
  364.             } catch (OrekitException oe) {
  365.                 // as the generators are already compatible with each other,
  366.                 // this should never happen
  367.                 throw new OrekitInternalError(null);
  368.             }

  369.         }

  370.         /** {@inheritDoc} */
  371.         public AbsoluteDate getMinDate() {
  372.             return minDate;
  373.         }

  374.         /** {@inheritDoc} */
  375.         public AbsoluteDate getMaxDate() {
  376.             return maxDate;
  377.         }

  378.         /** {@inheritDoc} */
  379.         protected Orbit propagateOrbit(final AbsoluteDate target) {
  380.             return AbstractAnalyticalPropagator.this.propagateOrbit(target);
  381.         }

  382.         /** {@inheritDoc} */
  383.         public double getMass(final AbsoluteDate date) {
  384.             return AbstractAnalyticalPropagator.this.getMass(date);
  385.         }

  386.         /** {@inheritDoc} */
  387.         public void resetInitialState(final SpacecraftState state) {
  388.             super.resetInitialState(state);
  389.             AbstractAnalyticalPropagator.this.resetInitialState(state);
  390.         }

  391.         /** {@inheritDoc} */
  392.         protected void resetIntermediateState(final SpacecraftState state, final boolean forward) {
  393.             AbstractAnalyticalPropagator.this.resetIntermediateState(state, forward);
  394.         }

  395.         /** {@inheritDoc} */
  396.         public SpacecraftState getInitialState() {
  397.             return AbstractAnalyticalPropagator.this.getInitialState();
  398.         }

  399.         /** {@inheritDoc} */
  400.         public Frame getFrame() {
  401.             return AbstractAnalyticalPropagator.this.getFrame();
  402.         }

  403.     }

  404.     /** Internal class for local propagation. */
  405.     private class BasicStepInterpolator implements OrekitStepInterpolator {

  406.         /** Previous state. */
  407.         private final SpacecraftState previousState;

  408.         /** Current state. */
  409.         private final SpacecraftState currentState;

  410.         /** Forward propagation indicator. */
  411.         private final boolean forward;

  412.         /** Simple constructor.
  413.          * @param isForward integration direction indicator
  414.          * @param previousState start of the step
  415.          * @param currentState end of the step
  416.          */
  417.         BasicStepInterpolator(final boolean isForward,
  418.                               final SpacecraftState previousState,
  419.                               final SpacecraftState currentState) {
  420.             this.forward         = isForward;
  421.             this.previousState   = previousState;
  422.             this.currentState    = currentState;
  423.         }

  424.         /** {@inheritDoc} */
  425.         @Override
  426.         public SpacecraftState getPreviousState() {
  427.             return previousState;
  428.         }

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

  435.         /** {@inheritDoc} */
  436.         @Override
  437.         public SpacecraftState getCurrentState() {
  438.             return currentState;
  439.         }

  440.         /** {@inheritDoc} */
  441.         @Override
  442.         public boolean isCurrentStateInterpolated() {
  443.             // no difference in analytical propagators
  444.             return false;
  445.         }

  446.         /** {@inheritDoc} */
  447.         @Override
  448.         public SpacecraftState getInterpolatedState(final AbsoluteDate date) {

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

  451.             // add the additional states
  452.             return updateAdditionalStates(basicState);

  453.         }

  454.         /** {@inheritDoc} */
  455.         @Override
  456.         public boolean isForward() {
  457.             return forward;
  458.         }

  459.         /** {@inheritDoc} */
  460.         @Override
  461.         public BasicStepInterpolator restrictStep(final SpacecraftState newPreviousState,
  462.                                                   final SpacecraftState newCurrentState) {
  463.             return new BasicStepInterpolator(forward, newPreviousState, newCurrentState);
  464.         }

  465.     }

  466. }