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

  48. /** Common handling of {@link org.orekit.propagation.FieldPropagator} methods for analytical propagators.
  49.  * <p>
  50.  * This abstract class allows to provide easily the full set of {@link
  51.  * org.orekit.propagation.FieldPropagator FieldPropagator} 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(FieldAbsoluteDate)}
  54.  * and {@link #getMass(FieldAbsoluteDate)}. 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 FieldAbstractAnalyticalPropagator<T extends RealFieldElement<T>> extends FieldAbstractPropagator<T> {

  60.     /** Provider for attitude computation. */
  61.     private FieldPVCoordinatesProvider<T> pvProvider;

  62.     /** Start date of last propagation. */
  63.     private FieldAbsoluteDate<T> lastPropagationStart;

  64.     /** End date of last propagation. */
  65.     private FieldAbsoluteDate<T> 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<FieldEventState<?, T>> eventsStates;

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

  85.     /** {@inheritDoc} */
  86.     public FieldBoundedPropagator<T> getGeneratedEphemeris() {
  87.         return new FieldBoundedPropagatorView(lastPropagationStart, lastPropagationEnd);
  88.     }

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

  97.     /** {@inheritDoc} */
  98.     public void clearEventsDetectors() {
  99.         eventsStates.clear();
  100.     }
  101.     /** {@inheritDoc} */
  102.     public FieldSpacecraftState<T> propagate(final FieldAbsoluteDate<T> start, final FieldAbsoluteDate<T> target) {
  103.         try {
  104.             lastPropagationStart = start;

  105.             final T dt       = target.durationFrom(start);

  106.             final double epsilon  = FastMath.ulp(dt.getReal());

  107.             FieldSpacecraftState<T> state = updateAdditionalStates(basicPropagate(start));

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

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

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

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

  131.                 // go ahead one step size
  132.                 final FieldSpacecraftState<T> previous = state;
  133.                 FieldAbsoluteDate<T> t = previous.getDate().shiftedBy(stepSize);
  134.                 if ((dt.getReal() == 0) || ((dt.getReal() > 0) ^ (t.compareTo(target) <= 0))) {
  135.                     // current step exceeds target
  136.                     t = target;
  137.                 }
  138.                 final FieldSpacecraftState<T> current = updateAdditionalStates(basicPropagate(t));
  139.                 final FieldBasicStepInterpolator interpolator = new FieldBasicStepInterpolator(dt.getReal() >= 0, previous, current);



  140.                 // accept the step, trigger events and step handlers
  141.                 state = acceptStep(interpolator, target, epsilon);
  142.             } while (!isLastStep);
  143.             // return the last computed state
  144.             lastPropagationEnd = state.getDate();
  145.             setStartDate(state.getDate());
  146.             return state;

  147.         } catch (OrekitException pe) {
  148.             throw pe;
  149.         } catch (MathRuntimeException mrte) {
  150.             throw OrekitException.unwrap(mrte);
  151.         }
  152.     }

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

  163.         FieldSpacecraftState<T>       previous = interpolator.getPreviousState();
  164.         final FieldSpacecraftState<T> current  = interpolator.getCurrentState();
  165.         // initialize the events states if needed
  166.         if (!statesInitialized) {

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

  173.             statesInitialized = true;

  174.         }
  175.         // search for next events that may occur during the step
  176.         final int orderingSign = interpolator.isForward() ? +1 : -1;
  177.         final Queue<FieldEventState<?, T>> occurringEvents = new PriorityQueue<>(new Comparator<FieldEventState<?, T>>() {
  178.             /** {@inheritDoc} */
  179.             @Override
  180.             public int compare(final FieldEventState<?, T> es0, final FieldEventState<?, T> es1) {
  181.                 return orderingSign * es0.getEventDate().compareTo(es1.getEventDate());
  182.             }
  183.         });
  184.         for (final FieldEventState<?, T> state : eventsStates) {
  185.             if (state.evaluateStep(interpolator)) {
  186.                 // the event occurs during the current step
  187.                 occurringEvents.add(state);
  188.             }
  189.         }



  190.         FieldBasicStepInterpolator restricted = interpolator;

  191.         do {
  192.             eventLoop:
  193.             while (!occurringEvents.isEmpty()) {
  194.                 // handle the chronologically first event
  195.                 final FieldEventState<?, T> currentEvent = occurringEvents.poll();

  196.                 // get state at event time
  197.                 FieldSpacecraftState<T> eventState = restricted.getInterpolatedState(currentEvent.getEventDate());
  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.                         occurringEvents.add(currentEvent);
  203.                         occurringEvents.remove(state); // remove if already has pending event
  204.                         occurringEvents.add(state);
  205.                         continue eventLoop;
  206.                     }
  207.                 }
  208.                 // all event detectors agree we can advance to the current event time
  209.                 final EventOccurrence<T> occurrence = currentEvent.doEvent(eventState);
  210.                 final Action action = occurrence.getAction();
  211.                 isLastStep = action == Action.STOP;
  212.                 if (isLastStep) {
  213.                     // ensure the event is after the root if it is returned STOP
  214.                     // this lets the user integrate to a STOP event and then restart
  215.                     // integration from the same time.
  216.                     eventState = interpolator.getInterpolatedState(occurrence.getStopDate());
  217.                     restricted = new FieldBasicStepInterpolator(restricted.isForward(), previous, eventState);
  218.                 }
  219.                 // handle the first part of the step, up to the event
  220.                 if (getStepHandler() != null) {
  221.                     getStepHandler().handleStep(restricted, isLastStep);
  222.                 }

  223.                 if (isLastStep) {
  224.                     // the event asked to stop integration
  225.                     return eventState;
  226.                 }

  227.                 if (action == Action.RESET_DERIVATIVES || action == Action.RESET_STATE) {
  228.                     // some event handler has triggered changes that
  229.                     // invalidate the derivatives, we need to recompute them
  230.                     final FieldSpacecraftState<T> resetState = occurrence.getNewState();
  231.                     if (resetState != null) {
  232.                         resetIntermediateState( resetState, interpolator.isForward());
  233.                         return resetState;
  234.                     }
  235.                 }
  236.                 // at this point we know action == Action.CONTINUE

  237.                 // prepare handling of the remaining part of the step
  238.                 previous = eventState;
  239.                 restricted         = new FieldBasicStepInterpolator(restricted.isForward(), eventState, current);

  240.                 // check if the same event occurs again in the remaining part of the step
  241.                 if (currentEvent.evaluateStep(restricted)) {
  242.                     // the event occurs during the current step
  243.                     occurringEvents.add(currentEvent);
  244.                 }

  245.             }

  246.             // last part of the step, after the last event
  247.             // may be a new event here if the last event modified the g function of
  248.             // another event detector.
  249.             for (final FieldEventState<?, T> state : eventsStates) {
  250.                 if (state.tryAdvance(current, interpolator)) {
  251.                     occurringEvents.add(state);
  252.                 }
  253.             }

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

  255.         final T remaining = target.durationFrom(current.getDate());
  256.         if (interpolator.isForward()) {
  257.             isLastStep = remaining.getReal() <  epsilon;
  258.         } else {
  259.             isLastStep = remaining.getReal() > -epsilon;
  260.         }

  261.         // handle the remaining part of the step, after all events if any
  262.         if (getStepHandler() != null) {
  263.             getStepHandler().handleStep(interpolator, isLastStep);
  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 T getMass(FieldAbsoluteDate<T> date);

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

  278.     /** {@inheritDoc} */
  279.     public <D extends FieldEventDetector<T>> void addEventDetector(final D detector) {
  280.         eventsStates.add(new FieldEventState<D, T>(detector));
  281.     }

  282.     /** Reset an intermediate state.
  283.      * @param state new intermediate state to consider
  284.      * @param forward if true, the intermediate state is valid for
  285.      * propagations after itself
  286.      */
  287.     protected abstract void resetIntermediateState(FieldSpacecraftState<T> state, boolean forward);

  288.     /** Extrapolate an orbit up to a specific target date.
  289.      * @param date target date for the orbit
  290.      * @return extrapolated parameters
  291.      */
  292.     protected abstract FieldOrbit<T> propagateOrbit(FieldAbsoluteDate<T> date);

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

  303.             // evaluate orbit
  304.             final FieldOrbit<T> orbit = propagateOrbit(date);

  305.             // evaluate attitude
  306.             final FieldAttitude<T> attitude =
  307.                 getAttitudeProvider().getAttitude(pvProvider, date, orbit.getFrame());

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

  310.         } catch (OrekitException oe) {
  311.             throw new OrekitException(oe);
  312.         }
  313.     }

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

  316.         /** {@inheritDoc} */
  317.         public TimeStampedFieldPVCoordinates<T> getPVCoordinates(final FieldAbsoluteDate<T> date, final Frame frame) {
  318.             return propagateOrbit(date).getPVCoordinates(frame);
  319.         }

  320.     }

  321.     /** {@link BoundedPropagator} view of the instance. */
  322.     private class FieldBoundedPropagatorView extends FieldAbstractAnalyticalPropagator<T>
  323.         implements FieldBoundedPropagator<T> {

  324.         /** Min date. */
  325.         private final FieldAbsoluteDate<T> minDate;

  326.         /** Max date. */
  327.         private final FieldAbsoluteDate<T> maxDate;

  328.         /** Simple constructor.
  329.          * @param startDate start date of the propagation
  330.          * @param endDate end date of the propagation
  331.          */
  332.         FieldBoundedPropagatorView(final FieldAbsoluteDate<T> startDate, final FieldAbsoluteDate<T> endDate) {
  333.             super(startDate.durationFrom(endDate).getField(), FieldAbstractAnalyticalPropagator.this.getAttitudeProvider());
  334.             if (startDate.compareTo(endDate) <= 0) {
  335.                 minDate = startDate;
  336.                 maxDate = endDate;
  337.             } else {
  338.                 minDate = endDate;
  339.                 maxDate = startDate;
  340.             }

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

  351.         }

  352.         /** {@inheritDoc} */
  353.         public FieldAbsoluteDate<T> getMinDate() {
  354.             return minDate;
  355.         }

  356.         /** {@inheritDoc} */
  357.         public FieldAbsoluteDate<T> getMaxDate() {
  358.             return maxDate;
  359.         }

  360.         /** {@inheritDoc} */
  361.         protected FieldOrbit<T> propagateOrbit(final FieldAbsoluteDate<T> target) {
  362.             return FieldAbstractAnalyticalPropagator.this.propagateOrbit(target);
  363.         }

  364.         /** {@inheritDoc} */
  365.         public T getMass(final FieldAbsoluteDate<T> date) {
  366.             return FieldAbstractAnalyticalPropagator.this.getMass(date);
  367.         }

  368.         /** {@inheritDoc} */
  369.         public TimeStampedFieldPVCoordinates<T> getPVCoordinates(final FieldAbsoluteDate<T> date, final Frame frame) {
  370.             return propagate(date).getPVCoordinates(frame);
  371.         }

  372.         /** {@inheritDoc} */
  373.         public void resetInitialState(final FieldSpacecraftState<T> state) {
  374.             FieldAbstractAnalyticalPropagator.this.resetInitialState(state);
  375.         }

  376.         /** {@inheritDoc} */
  377.         protected void resetIntermediateState(final FieldSpacecraftState<T> state, final boolean forward) {
  378.             FieldAbstractAnalyticalPropagator.this.resetIntermediateState(state, forward);
  379.         }

  380.         /** {@inheritDoc} */
  381.         public FieldSpacecraftState<T> getInitialState() {
  382.             return FieldAbstractAnalyticalPropagator.this.getInitialState();
  383.         }

  384.         /** {@inheritDoc} */
  385.         public Frame getFrame() {
  386.             return FieldAbstractAnalyticalPropagator.this.getFrame();
  387.         }
  388.     }


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

  391.         /** Previous state. */
  392.         private final FieldSpacecraftState<T> previousState;

  393.         /** Current state. */
  394.         private final FieldSpacecraftState<T> currentState;

  395.         /** Forward propagation indicator. */
  396.         private final boolean forward;

  397.         /** Simple constructor.
  398.          * @param isForward integration direction indicator
  399.          * @param previousState start of the step
  400.          * @param currentState end of the step
  401.          */
  402.         FieldBasicStepInterpolator(final boolean isForward,
  403.                               final FieldSpacecraftState<T> previousState,
  404.                               final FieldSpacecraftState<T> currentState) {
  405.             this.forward             = isForward;
  406.             this.previousState   = previousState;
  407.             this.currentState    = currentState;
  408.         }

  409.         /** {@inheritDoc} */
  410.         public FieldSpacecraftState<T> getPreviousState() {
  411.             return previousState;
  412.         }

  413.         /** {@inheritDoc} */
  414.         public FieldSpacecraftState<T> getCurrentState() {
  415.             return currentState;
  416.         }

  417.         /** {@inheritDoc} */
  418.         public FieldSpacecraftState<T> getInterpolatedState(final FieldAbsoluteDate<T> date) {

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

  421.             // add the additional states
  422.             return updateAdditionalStates(basicState);

  423.         }

  424.         /** {@inheritDoc} */
  425.         public boolean isForward() {
  426.             return forward;
  427.         }

  428.     }

  429. }