FieldAbstractAnalyticalPropagator.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.CalculusFieldElement;
  26. import org.hipparchus.Field;
  27. import org.hipparchus.exception.MathRuntimeException;
  28. import org.hipparchus.ode.events.Action;
  29. import org.hipparchus.util.MathArrays;
  30. import org.orekit.attitudes.AttitudeProvider;
  31. import org.orekit.attitudes.FieldAttitude;
  32. import org.orekit.errors.OrekitException;
  33. import org.orekit.errors.OrekitInternalError;
  34. import org.orekit.frames.Frame;
  35. import org.orekit.orbits.FieldOrbit;
  36. import org.orekit.propagation.BoundedPropagator;
  37. import org.orekit.propagation.FieldAbstractPropagator;
  38. import org.orekit.propagation.FieldAdditionalStateProvider;
  39. import org.orekit.propagation.FieldBoundedPropagator;
  40. import org.orekit.propagation.FieldEphemerisGenerator;
  41. import org.orekit.propagation.FieldSpacecraftState;
  42. import org.orekit.propagation.events.FieldEventDetector;
  43. import org.orekit.propagation.events.FieldEventState;
  44. import org.orekit.propagation.events.FieldEventState.EventOccurrence;
  45. import org.orekit.propagation.sampling.FieldOrekitStepInterpolator;
  46. import org.orekit.time.FieldAbsoluteDate;
  47. import org.orekit.utils.FieldPVCoordinatesProvider;
  48. import org.orekit.utils.ParameterDriver;
  49. import org.orekit.utils.TimeStampedFieldPVCoordinates;

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

  61. public abstract class FieldAbstractAnalyticalPropagator<T extends CalculusFieldElement<T>> extends FieldAbstractPropagator<T> {

  62.     /** Provider for attitude computation. */
  63.     private FieldPVCoordinatesProvider<T> pvProvider;

  64.     /** Start date of last propagation. */
  65.     private FieldAbsoluteDate<T> lastPropagationStart;

  66.     /** End date of last propagation. */
  67.     private FieldAbsoluteDate<T> lastPropagationEnd;

  68.     /** Initialization indicator of events states. */
  69.     private boolean statesInitialized;

  70.     /** Indicator for last step. */
  71.     private boolean isLastStep;

  72.     /** Event steps. */
  73.     private final Collection<FieldEventState<?, T>> eventsStates;

  74.     /** Build a new instance.
  75.      * @param attitudeProvider provider for attitude computation
  76.      * @param field field used as default
  77.      */
  78.     protected FieldAbstractAnalyticalPropagator(final Field<T> field, final AttitudeProvider attitudeProvider) {
  79.         super(field);
  80.         setAttitudeProvider(attitudeProvider);
  81.         pvProvider           = new FieldLocalPVProvider();
  82.         lastPropagationStart = FieldAbsoluteDate.getPastInfinity(field);
  83.         lastPropagationEnd   = FieldAbsoluteDate.getFutureInfinity(field);
  84.         statesInitialized    = false;
  85.         eventsStates         = new ArrayList<>();
  86.     }

  87.     /** {@inheritDoc} */
  88.     @Override
  89.     public FieldEphemerisGenerator<T> getEphemerisGenerator() {
  90.         return () -> new FieldBoundedPropagatorView(lastPropagationStart, lastPropagationEnd);
  91.     }

  92.     /** {@inheritDoc} */
  93.     public <D extends FieldEventDetector<T>> void addEventDetector(final D detector) {
  94.         eventsStates.add(new FieldEventState<>(detector));
  95.     }

  96.     /** {@inheritDoc} */
  97.     @Override
  98.     public Collection<FieldEventDetector<T>> getEventsDetectors() {
  99.         final List<FieldEventDetector<T>> list = new ArrayList<>();
  100.         for (final FieldEventState<?, T> state : eventsStates) {
  101.             list.add(state.getEventDetector());
  102.         }
  103.         return Collections.unmodifiableCollection(list);
  104.     }

  105.     /** {@inheritDoc} */
  106.     @Override
  107.     public void clearEventsDetectors() {
  108.         eventsStates.clear();
  109.     }
  110.     /** {@inheritDoc} */
  111.     @Override
  112.     public FieldSpacecraftState<T> propagate(final FieldAbsoluteDate<T> start, final FieldAbsoluteDate<T> target) {
  113.         try {

  114.             initializePropagation();

  115.             lastPropagationStart = start;

  116.             final boolean           isForward = target.compareTo(start) >= 0;
  117.             FieldSpacecraftState<T> state   = updateAdditionalStates(basicPropagate(start));

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

  122.             // initialize step handlers
  123.             getMultiplexer().init(state, target);

  124.             // iterate over the propagation range, need loop due to reset events
  125.             statesInitialized = false;
  126.             isLastStep = false;
  127.             do {

  128.                 // attempt to advance to the target date
  129.                 final FieldSpacecraftState<T> previous = state;
  130.                 final FieldSpacecraftState<T> current = updateAdditionalStates(basicPropagate(target));
  131.                 final FieldBasicStepInterpolator interpolator =
  132.                         new FieldBasicStepInterpolator(isForward, previous, current);

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

  135.                 // Update the potential changes in the spacecraft state due to the events
  136.                 // especially the potential attitude transition
  137.                 state = updateAdditionalStates(basicPropagate(state.getDate()));

  138.             } while (!isLastStep);

  139.             // return the last computed state
  140.             lastPropagationEnd = state.getDate();
  141.             setStartDate(state.getDate());
  142.             return state;

  143.         } catch (MathRuntimeException mrte) {
  144.             throw OrekitException.unwrap(mrte);
  145.         }
  146.     }

  147.     /** Accept a step, triggering events and step handlers.
  148.      * @param interpolator interpolator for the current step
  149.      * @param target final propagation time
  150.      * @return state at the end of the step
  151.      * @exception MathRuntimeException if an event cannot be located
  152.      */
  153.     protected FieldSpacecraftState<T> acceptStep(final FieldBasicStepInterpolator interpolator,
  154.                                                  final FieldAbsoluteDate<T> target)
  155.         throws MathRuntimeException {

  156.         FieldSpacecraftState<T>       previous   = interpolator.getPreviousState();
  157.         final FieldSpacecraftState<T> current    = interpolator.getCurrentState();
  158.         FieldBasicStepInterpolator    restricted = interpolator;

  159.         // initialize the events states if needed
  160.         if (!statesInitialized) {

  161.             if (!eventsStates.isEmpty()) {
  162.                 // initialize the events states
  163.                 for (final FieldEventState<?, T> state : eventsStates) {
  164.                     state.reinitializeBegin(interpolator);
  165.                 }
  166.             }

  167.             statesInitialized = true;

  168.         }

  169.         // search for next events that may occur during the step
  170.         final int orderingSign = interpolator.isForward() ? +1 : -1;
  171.         final Queue<FieldEventState<?, T>> occurringEvents = new PriorityQueue<>(new Comparator<FieldEventState<?, T>>() {
  172.             /** {@inheritDoc} */
  173.             @Override
  174.             public int compare(final FieldEventState<?, T> es0, final FieldEventState<?, T> es1) {
  175.                 return orderingSign * es0.getEventDate().compareTo(es1.getEventDate());
  176.             }
  177.         });

  178.         boolean doneWithStep = false;
  179.         resetEvents:
  180.         do {

  181.             // Evaluate all event detectors for events
  182.             occurringEvents.clear();
  183.             for (final FieldEventState<?, T> state : eventsStates) {
  184.                 if (state.evaluateStep(interpolator)) {
  185.                     // the event occurs during the current step
  186.                     occurringEvents.add(state);
  187.                 }
  188.             }


  189.             do {

  190.                 eventLoop:
  191.                 while (!occurringEvents.isEmpty()) {

  192.                     // handle the chronologically first event
  193.                     final FieldEventState<?, T> currentEvent = occurringEvents.poll();

  194.                     // get state at event time
  195.                     FieldSpacecraftState<T> eventState = restricted.getInterpolatedState(currentEvent.getEventDate());

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

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

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

  214.                     // acknowledge event occurrence
  215.                     final EventOccurrence<T> occurrence = currentEvent.doEvent(eventState);
  216.                     final Action action = occurrence.getAction();
  217.                     isLastStep = action == Action.STOP;
  218.                     if (isLastStep) {

  219.                         // ensure the event is after the root if it is returned STOP
  220.                         // this lets the user integrate to a STOP event and then restart
  221.                         // integration from the same time.
  222.                         final FieldSpacecraftState<T> savedState = eventState;
  223.                         eventState = interpolator.getInterpolatedState(occurrence.getStopDate());
  224.                         restricted = restricted.restrictStep(savedState, eventState);

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

  228.                     }

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

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

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

  244.                     if (action == Action.RESET_EVENTS) {
  245.                         continue resetEvents;
  246.                     }

  247.                     // at this pint action == Action.CONTINUE
  248.                     // check if the same event occurs again in the remaining part of the step
  249.                     if (currentEvent.evaluateStep(restricted)) {
  250.                         // the event occurs during the current step
  251.                         occurringEvents.add(currentEvent);
  252.                     }

  253.                 }

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

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

  266.             doneWithStep = true;
  267.         } while (!doneWithStep);

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

  269.         // handle the remaining part of the step, after all events if any
  270.         getMultiplexer().handleStep(restricted);
  271.         if (isLastStep) {
  272.             getMultiplexer().finish(restricted.getCurrentState());
  273.         }

  274.         return current;

  275.     }

  276.     /** Get the mass.
  277.      * @param date target date for the orbit
  278.      * @return mass mass
  279.      */
  280.     protected abstract T getMass(FieldAbsoluteDate<T> date);

  281.     /** Get PV coordinates provider.
  282.      * @return PV coordinates provider
  283.      */
  284.     public FieldPVCoordinatesProvider<T> getPvProvider() {
  285.         return pvProvider;
  286.     }

  287.     /** Reset an intermediate state.
  288.      * @param state new intermediate state to consider
  289.      * @param forward if true, the intermediate state is valid for
  290.      * propagations after itself
  291.      */
  292.     protected abstract void resetIntermediateState(FieldSpacecraftState<T> state, boolean forward);

  293.     /** Extrapolate an orbit up to a specific target date.
  294.      * @param date target date for the orbit
  295.      * @param parameters model parameters
  296.      * @return extrapolated parameters
  297.      */
  298.     protected abstract FieldOrbit<T> propagateOrbit(FieldAbsoluteDate<T> date, T[] parameters);

  299.     /** Get the parameters driver for propagation model.
  300.      * @return drivers for propagation model
  301.      */
  302.     protected abstract List<ParameterDriver> getParametersDrivers();

  303.     /** Get model parameters.
  304.      * @param field field to which the elements belong
  305.      * @return model parameters
  306.      */
  307.     public T[] getParameters(final Field<T> field) {
  308.         final List<ParameterDriver> drivers = getParametersDrivers();
  309.         final T[] parameters = MathArrays.buildArray(field, drivers.size());
  310.         for (int i = 0; i < drivers.size(); ++i) {
  311.             parameters[i] = field.getZero().add(drivers.get(i).getValue());
  312.         }
  313.         return parameters;
  314.     }

  315.     /** Propagate an orbit without any fancy features.
  316.      * <p>This method is similar in spirit to the {@link #propagate} method,
  317.      * except that it does <strong>not</strong> call any handler during
  318.      * propagation, nor any discrete events, not additional states. It always
  319.      * stop exactly at the specified date.</p>
  320.      * @param date target date for propagation
  321.      * @return state at specified date
  322.      */
  323.     protected FieldSpacecraftState<T> basicPropagate(final FieldAbsoluteDate<T> date) {
  324.         try {

  325.             // evaluate orbit
  326.             final FieldOrbit<T> orbit = propagateOrbit(date, getParameters(date.getField()));

  327.             // evaluate attitude
  328.             final FieldAttitude<T> attitude =
  329.                 getAttitudeProvider().getAttitude(pvProvider, date, orbit.getFrame());

  330.             // build raw state
  331.             return new FieldSpacecraftState<>(orbit, attitude, getMass(date));

  332.         } catch (OrekitException oe) {
  333.             throw new OrekitException(oe);
  334.         }
  335.     }

  336.     /** Internal FieldPVCoordinatesProvider<T> for attitude computation. */
  337.     private class FieldLocalPVProvider implements FieldPVCoordinatesProvider<T> {

  338.         /** {@inheritDoc} */
  339.         @Override
  340.         public TimeStampedFieldPVCoordinates<T> getPVCoordinates(final FieldAbsoluteDate<T> date, final Frame frame) {
  341.             return propagateOrbit(date, getParameters(date.getField())).getPVCoordinates(frame);
  342.         }

  343.     }

  344.     /** {@link BoundedPropagator} view of the instance. */
  345.     private class FieldBoundedPropagatorView extends FieldAbstractAnalyticalPropagator<T>
  346.         implements FieldBoundedPropagator<T> {

  347.         /** Min date. */
  348.         private final FieldAbsoluteDate<T> minDate;

  349.         /** Max date. */
  350.         private final FieldAbsoluteDate<T> maxDate;

  351.         /** Simple constructor.
  352.          * @param startDate start date of the propagation
  353.          * @param endDate end date of the propagation
  354.          */
  355.         FieldBoundedPropagatorView(final FieldAbsoluteDate<T> startDate, final FieldAbsoluteDate<T> endDate) {
  356.             super(startDate.durationFrom(endDate).getField(), FieldAbstractAnalyticalPropagator.this.getAttitudeProvider());
  357.             super.resetInitialState(FieldAbstractAnalyticalPropagator.this.getInitialState());
  358.             if (startDate.compareTo(endDate) <= 0) {
  359.                 minDate = startDate;
  360.                 maxDate = endDate;
  361.             } else {
  362.                 minDate = endDate;
  363.                 maxDate = startDate;
  364.             }

  365.             try {
  366.                 // copy the same additional state providers as the original propagator
  367.                 for (FieldAdditionalStateProvider<T> provider : FieldAbstractAnalyticalPropagator.this.getAdditionalStateProviders()) {
  368.                     addAdditionalStateProvider(provider);
  369.                 }
  370.             } catch (OrekitException oe) {
  371.                 // as the providers are already compatible with each other,
  372.                 // this should never happen
  373.                 throw new OrekitInternalError(null);
  374.             }

  375.         }

  376.         /** {@inheritDoc} */
  377.         @Override
  378.         public FieldAbsoluteDate<T> getMinDate() {
  379.             return minDate;
  380.         }

  381.         /** {@inheritDoc} */
  382.         @Override
  383.         public FieldAbsoluteDate<T> getMaxDate() {
  384.             return maxDate;
  385.         }

  386.         /** {@inheritDoc} */
  387.         @Override
  388.         protected FieldOrbit<T> propagateOrbit(final FieldAbsoluteDate<T> target, final T[] parameters) {
  389.             return FieldAbstractAnalyticalPropagator.this.propagateOrbit(target, parameters);
  390.         }

  391.         /** {@inheritDoc} */
  392.         @Override
  393.         public T getMass(final FieldAbsoluteDate<T> date) {
  394.             return FieldAbstractAnalyticalPropagator.this.getMass(date);
  395.         }

  396.         /** {@inheritDoc} */
  397.         @Override
  398.         public TimeStampedFieldPVCoordinates<T> getPVCoordinates(final FieldAbsoluteDate<T> date, final Frame frame) {
  399.             return propagate(date).getPVCoordinates(frame);
  400.         }

  401.         /** {@inheritDoc} */
  402.         @Override
  403.         public void resetInitialState(final FieldSpacecraftState<T> state) {
  404.             super.resetInitialState(state);
  405.             FieldAbstractAnalyticalPropagator.this.resetInitialState(state);
  406.         }

  407.         /** {@inheritDoc} */
  408.         @Override
  409.         protected void resetIntermediateState(final FieldSpacecraftState<T> state, final boolean forward) {
  410.             FieldAbstractAnalyticalPropagator.this.resetIntermediateState(state, forward);
  411.         }

  412.         /** {@inheritDoc} */
  413.         @Override
  414.         public FieldSpacecraftState<T> getInitialState() {
  415.             return FieldAbstractAnalyticalPropagator.this.getInitialState();
  416.         }

  417.         /** {@inheritDoc} */
  418.         @Override
  419.         public Frame getFrame() {
  420.             return FieldAbstractAnalyticalPropagator.this.getFrame();
  421.         }

  422.         @Override
  423.         protected List<ParameterDriver> getParametersDrivers() {
  424.             return FieldAbstractAnalyticalPropagator.this.getParametersDrivers();
  425.         }
  426.     }


  427.     /** Internal class for local propagation. */
  428.     private class FieldBasicStepInterpolator implements FieldOrekitStepInterpolator<T> {

  429.         /** Previous state. */
  430.         private final FieldSpacecraftState<T> previousState;

  431.         /** Current state. */
  432.         private final FieldSpacecraftState<T> currentState;

  433.         /** Forward propagation indicator. */
  434.         private final boolean forward;

  435.         /** Simple constructor.
  436.          * @param isForward integration direction indicator
  437.          * @param previousState start of the step
  438.          * @param currentState end of the step
  439.          */
  440.         FieldBasicStepInterpolator(final boolean isForward,
  441.                                    final FieldSpacecraftState<T> previousState,
  442.                                    final FieldSpacecraftState<T> currentState) {
  443.             this.forward             = isForward;
  444.             this.previousState   = previousState;
  445.             this.currentState    = currentState;
  446.         }

  447.         /** {@inheritDoc} */
  448.         @Override
  449.         public FieldSpacecraftState<T> getPreviousState() {
  450.             return previousState;
  451.         }

  452.         /** {@inheritDoc} */
  453.         @Override
  454.         public FieldSpacecraftState<T> getCurrentState() {
  455.             return currentState;
  456.         }

  457.         /** {@inheritDoc} */
  458.         @Override
  459.         public FieldSpacecraftState<T> getInterpolatedState(final FieldAbsoluteDate<T> date) {

  460.             // compute the basic spacecraft state
  461.             final FieldSpacecraftState<T> basicState = basicPropagate(date);

  462.             // add the additional states
  463.             return updateAdditionalStates(basicState);

  464.         }

  465.         /** {@inheritDoc} */
  466.         @Override
  467.         public boolean isForward() {
  468.             return forward;
  469.         }

  470.         /** {@inheritDoc} */
  471.         @Override
  472.         public FieldBasicStepInterpolator restrictStep(final FieldSpacecraftState<T> newPreviousState,
  473.                                                        final FieldSpacecraftState<T> newCurrentState) {
  474.             return new FieldBasicStepInterpolator(forward, newPreviousState, newCurrentState);
  475.         }

  476.     }

  477. }