EventState.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF 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.events;

  18. import org.hipparchus.analysis.UnivariateFunction;
  19. import org.hipparchus.analysis.solvers.BracketedUnivariateSolver;
  20. import org.hipparchus.analysis.solvers.BracketedUnivariateSolver.Interval;
  21. import org.hipparchus.analysis.solvers.BracketingNthOrderBrentSolver;
  22. import org.hipparchus.exception.MathRuntimeException;
  23. import org.hipparchus.util.FastMath;
  24. import org.hipparchus.util.Precision;
  25. import org.orekit.errors.OrekitInternalError;
  26. import org.orekit.propagation.SpacecraftState;
  27. import org.orekit.propagation.events.handlers.EventHandler;
  28. import org.orekit.propagation.sampling.OrekitStepInterpolator;
  29. import org.orekit.time.AbsoluteDate;

  30. import java.io.Serializable;

  31. /** This class handles the state for one {@link EventDetector
  32.  * event detector} during integration steps.
  33.  *
  34.  * <p>This class is heavily based on the class with the same name from the
  35.  * Hipparchus library. The changes performed consist in replacing
  36.  * raw types (double and double arrays) with space dynamics types
  37.  * ({@link AbsoluteDate}, {@link SpacecraftState}).</p>
  38.  * <p>Each time the propagator proposes a step, the event detector
  39.  * should be checked. This class handles the state of one detector
  40.  * during one propagation step, with references to the state at the
  41.  * end of the preceding step. This information is used to determine if
  42.  * the detector should trigger an event or not during the proposed
  43.  * step (and hence the step should be reduced to ensure the event
  44.  * occurs at a bound rather than inside the step).</p>
  45.  * @author Luc Maisonobe
  46.  * @param <T> class type for the generic version
  47.  */
  48. public class EventState<T extends EventDetector> implements Serializable {

  49.     /** Serializable version identifier. */
  50.     private static final long serialVersionUID = 4489391420715269318L;

  51.     /** Event detector. */
  52.     private T detector;

  53.     /** Time of the previous call to g. */
  54.     private AbsoluteDate lastT;

  55.     /** Value from the previous call to g. */
  56.     private double lastG;

  57.     /** Time at the beginning of the step. */
  58.     private AbsoluteDate t0;

  59.     /** Value of the event detector at the beginning of the step. */
  60.     private double g0;

  61.     /** Simulated sign of g0 (we cheat when crossing events). */
  62.     private boolean g0Positive;

  63.     /** Indicator of event expected during the step. */
  64.     private boolean pendingEvent;

  65.     /** Occurrence time of the pending event. */
  66.     private AbsoluteDate pendingEventTime;

  67.     /**
  68.      * Time to stop propagation if the event is a stop event. Used to enable stopping at
  69.      * an event and then restarting after that event.
  70.      */
  71.     private AbsoluteDate stopTime;

  72.     /** Time after the current event. */
  73.     private AbsoluteDate afterEvent;

  74.     /** Value of the g function after the current event. */
  75.     private double afterG;

  76.     /** The earliest time considered for events. */
  77.     private AbsoluteDate earliestTimeConsidered;

  78.     /** Integration direction. */
  79.     private boolean forward;

  80.     /** Variation direction around pending event.
  81.      *  (this is considered with respect to the integration direction)
  82.      */
  83.     private boolean increasing;

  84.     /** Simple constructor.
  85.      * @param detector monitored event detector
  86.      */
  87.     public EventState(final T detector) {
  88.         this.detector     = detector;

  89.         // some dummy values ...
  90.         lastT                  = AbsoluteDate.PAST_INFINITY;
  91.         lastG                  = Double.NaN;
  92.         t0                     = null;
  93.         g0                     = Double.NaN;
  94.         g0Positive             = true;
  95.         pendingEvent           = false;
  96.         pendingEventTime       = null;
  97.         stopTime               = null;
  98.         increasing             = true;
  99.         earliestTimeConsidered = null;
  100.         afterEvent             = null;
  101.         afterG                 = Double.NaN;

  102.     }

  103.     /** Get the underlying event detector.
  104.      * @return underlying event detector
  105.      */
  106.     public T getEventDetector() {
  107.         return detector;
  108.     }

  109.     /** Initialize event handler at the start of a propagation.
  110.      * <p>
  111.      * This method is called once at the start of the propagation. It
  112.      * may be used by the event handler to initialize some internal data
  113.      * if needed.
  114.      * </p>
  115.      * @param s0 initial state
  116.      * @param t target time for the integration
  117.      *
  118.      */
  119.     public void init(final SpacecraftState s0,
  120.                      final AbsoluteDate t) {
  121.         detector.init(s0, t);
  122.         lastT = AbsoluteDate.PAST_INFINITY;
  123.         lastG = Double.NaN;
  124.     }

  125.     /** Compute the value of the switching function.
  126.      * This function must be continuous (at least in its roots neighborhood),
  127.      * as the integrator will need to find its roots to locate the events.
  128.      * @param s the current state information: date, kinematics, attitude
  129.      * @return value of the switching function
  130.      */
  131.     private double g(final SpacecraftState s) {
  132.         if (!s.getDate().equals(lastT)) {
  133.             lastT = s.getDate();
  134.             lastG = detector.g(s);
  135.         }
  136.         return lastG;
  137.     }

  138.     /** Reinitialize the beginning of the step.
  139.      * @param interpolator interpolator valid for the current step
  140.      */
  141.     public void reinitializeBegin(final OrekitStepInterpolator interpolator) {
  142.         forward = interpolator.isForward();
  143.         final SpacecraftState s0 = interpolator.getPreviousState();
  144.         this.t0 = s0.getDate();
  145.         g0 = g(s0);
  146.         while (g0 == 0) {
  147.             // extremely rare case: there is a zero EXACTLY at interval start
  148.             // we will use the sign slightly after step beginning to force ignoring this zero
  149.             // try moving forward by half a convergence interval
  150.             final double dt = (forward ? 0.5 : -0.5) * detector.getThreshold();
  151.             AbsoluteDate startDate = t0.shiftedBy(dt);
  152.             // if convergence is too small move an ulp
  153.             if (t0.equals(startDate)) {
  154.                 startDate = nextAfter(startDate);
  155.             }
  156.             t0 = startDate;
  157.             g0 = g(interpolator.getInterpolatedState(t0));
  158.         }
  159.         g0Positive = g0 > 0;
  160.         // "last" event was increasing
  161.         increasing = g0Positive;
  162.     }

  163.     /** Evaluate the impact of the proposed step on the event detector.
  164.      * @param interpolator step interpolator for the proposed step
  165.      * @return true if the event detector triggers an event before
  166.      * the end of the proposed step (this implies the step should be
  167.      * rejected)
  168.      * @exception MathRuntimeException if an event cannot be located
  169.      */
  170.     public boolean evaluateStep(final OrekitStepInterpolator interpolator)
  171.         throws MathRuntimeException {

  172.         forward = interpolator.isForward();
  173.         final SpacecraftState s1 = interpolator.getCurrentState();
  174.         final AbsoluteDate t1 = s1.getDate();
  175.         final double dt = t1.durationFrom(t0);
  176.         if (FastMath.abs(dt) < detector.getThreshold()) {
  177.             // we cannot do anything on such a small step, don't trigger any events
  178.             return false;
  179.         }
  180.         // number of points to check in the current step
  181.         final int n = FastMath.max(1, (int) FastMath.ceil(FastMath.abs(dt) / detector.getMaxCheckInterval()));
  182.         final double h = dt / n;


  183.         AbsoluteDate ta = t0;
  184.         double ga = g0;
  185.         for (int i = 0; i < n; ++i) {

  186.             // evaluate handler value at the end of the substep
  187.             final AbsoluteDate tb = (i == n - 1) ? t1 : t0.shiftedBy((i + 1) * h);
  188.             final double gb = g(interpolator.getInterpolatedState(tb));

  189.             // check events occurrence
  190.             if (gb == 0.0 || (g0Positive ^ (gb > 0))) {
  191.                 // there is a sign change: an event is expected during this step
  192.                 if (findRoot(interpolator, ta, ga, tb, gb)) {
  193.                     return true;
  194.                 }
  195.             } else {
  196.                 // no sign change: there is no event for now
  197.                 ta = tb;
  198.                 ga = gb;
  199.             }

  200.         }

  201.         // no event during the whole step
  202.         pendingEvent     = false;
  203.         pendingEventTime = null;
  204.         return false;

  205.     }

  206.     /**
  207.      * Find a root in a bracketing interval.
  208.      *
  209.      * <p> When calling this method one of the following must be true. Either ga == 0, gb
  210.      * == 0, (ga < 0  and gb > 0), or (ga > 0 and gb < 0).
  211.      *
  212.      * @param interpolator that covers the interval.
  213.      * @param ta           earliest possible time for root.
  214.      * @param ga           g(ta).
  215.      * @param tb           latest possible time for root.
  216.      * @param gb           g(tb).
  217.      * @return if a zero crossing was found.
  218.      */
  219.     private boolean findRoot(final OrekitStepInterpolator interpolator,
  220.                              final AbsoluteDate ta, final double ga,
  221.                              final AbsoluteDate tb, final double gb) {
  222.         // check there appears to be a root in [ta, tb]
  223.         check(ga == 0.0 || gb == 0.0 || (ga > 0.0 && gb < 0.0) || (ga < 0.0 && gb > 0.0));

  224.         final double convergence = detector.getThreshold();
  225.         final int maxIterationCount = detector.getMaxIterationCount();
  226.         final BracketedUnivariateSolver<UnivariateFunction> solver =
  227.                 new BracketingNthOrderBrentSolver(0, convergence, 0, 5);

  228.         // event time, just at or before the actual root.
  229.         AbsoluteDate beforeRootT = null;
  230.         double beforeRootG = Double.NaN;
  231.         // time on the other side of the root.
  232.         // Initialized the the loop below executes once.
  233.         AbsoluteDate afterRootT = ta;
  234.         double afterRootG = 0.0;

  235.         // check for some conditions that the root finders don't like
  236.         // these conditions cannot not happen in the loop below
  237.         // the ga == 0.0 case is handled by the loop below
  238.         if (ta.equals(tb)) {
  239.             // both non-zero but times are the same. Probably due to reset state
  240.             beforeRootT = ta;
  241.             beforeRootG = ga;
  242.             afterRootT = shiftedBy(beforeRootT, convergence);
  243.             afterRootG = g(interpolator.getInterpolatedState(afterRootT));
  244.         } else if (ga != 0.0 && gb == 0.0) {
  245.             // hard: ga != 0.0 and gb == 0.0
  246.             // look past gb by up to convergence to find next sign
  247.             // throw an exception if g(t) = 0.0 in [tb, tb + convergence]
  248.             beforeRootT = tb;
  249.             beforeRootG = gb;
  250.             afterRootT = shiftedBy(beforeRootT, convergence);
  251.             afterRootG = g(interpolator.getInterpolatedState(afterRootT));
  252.         } else if (ga != 0.0) {
  253.             final double newGa = g(interpolator.getInterpolatedState(ta));
  254.             if (ga > 0 != newGa > 0) {
  255.                 // both non-zero, step sign change at ta, possibly due to reset state
  256.                 beforeRootT = ta;
  257.                 beforeRootG = newGa;
  258.                 afterRootT = minTime(shiftedBy(beforeRootT, convergence), tb);
  259.                 afterRootG = g(interpolator.getInterpolatedState(afterRootT));
  260.             }
  261.         }

  262.         // loop to skip through "fake" roots, i.e. where g(t) = g'(t) = 0.0
  263.         // executed once if we didn't hit a special case above
  264.         AbsoluteDate loopT = ta;
  265.         double loopG = ga;
  266.         while ((afterRootG == 0.0 || afterRootG > 0.0 == g0Positive) &&
  267.                 strictlyAfter(afterRootT, tb)) {
  268.             if (loopG == 0.0) {
  269.                 // ga == 0.0 and gb may or may not be 0.0
  270.                 // handle the root at ta first
  271.                 beforeRootT = loopT;
  272.                 beforeRootG = loopG;
  273.                 afterRootT = minTime(shiftedBy(beforeRootT, convergence), tb);
  274.                 afterRootG = g(interpolator.getInterpolatedState(afterRootT));
  275.             } else {
  276.                 // both non-zero, the usual case, use a root finder.
  277.                 // time zero for evaluating the function f. Needs to be final
  278.                 final AbsoluteDate fT0 = loopT;
  279.                 final UnivariateFunction f = dt -> {
  280.                     return g(interpolator.getInterpolatedState(fT0.shiftedBy(dt)));
  281.                 };
  282.                 // tb as a double for use in f
  283.                 final double tbDouble = tb.durationFrom(fT0);
  284.                 if (forward) {
  285.                     final Interval interval =
  286.                             solver.solveInterval(maxIterationCount, f, 0, tbDouble);
  287.                     beforeRootT = fT0.shiftedBy(interval.getLeftAbscissa());
  288.                     beforeRootG = interval.getLeftValue();
  289.                     afterRootT = fT0.shiftedBy(interval.getRightAbscissa());
  290.                     afterRootG = interval.getRightValue();
  291.                 } else {
  292.                     final Interval interval =
  293.                             solver.solveInterval(maxIterationCount, f, tbDouble, 0);
  294.                     beforeRootT = fT0.shiftedBy(interval.getRightAbscissa());
  295.                     beforeRootG = interval.getRightValue();
  296.                     afterRootT = fT0.shiftedBy(interval.getLeftAbscissa());
  297.                     afterRootG = interval.getLeftValue();
  298.                 }
  299.             }
  300.             // tolerance is set to less than 1 ulp
  301.             // assume tolerance is 1 ulp
  302.             if (beforeRootT.equals(afterRootT)) {
  303.                 afterRootT = nextAfter(afterRootT);
  304.                 afterRootG = g(interpolator.getInterpolatedState(afterRootT));
  305.             }
  306.             // check loop is making some progress
  307.             check((forward && afterRootT.compareTo(beforeRootT) > 0) ||
  308.                   (!forward && afterRootT.compareTo(beforeRootT) < 0));
  309.             // setup next iteration
  310.             loopT = afterRootT;
  311.             loopG = afterRootG;
  312.         }

  313.         // figure out the result of root finding, and return accordingly
  314.         if (afterRootG == 0.0 || afterRootG > 0.0 == g0Positive) {
  315.             // loop gave up and didn't find any crossing within this step
  316.             return false;
  317.         } else {
  318.             // real crossing
  319.             check(beforeRootT != null && !Double.isNaN(beforeRootG));
  320.             // variation direction, with respect to the integration direction
  321.             increasing = !g0Positive;
  322.             pendingEventTime = beforeRootT;
  323.             stopTime = beforeRootG == 0.0 ? beforeRootT : afterRootT;
  324.             pendingEvent = true;
  325.             afterEvent = afterRootT;
  326.             afterG = afterRootG;

  327.             // check increasing set correctly
  328.             check(afterG > 0 == increasing);
  329.             check(increasing == gb >= ga);

  330.             return true;
  331.         }

  332.     }

  333.     /**
  334.      * Get the next number after the given number in the current propagation direction.
  335.      *
  336.      * @param t input time
  337.      * @return t +/- 1 ulp depending on the direction.
  338.      */
  339.     private AbsoluteDate nextAfter(final AbsoluteDate t) {
  340.         return t.shiftedBy(forward ? +Precision.EPSILON : -Precision.EPSILON);
  341.     }

  342.     /** Get the occurrence time of the event triggered in the current
  343.      * step.
  344.      * @return occurrence time of the event triggered in the current
  345.      * step.
  346.      */
  347.     public AbsoluteDate getEventDate() {
  348.         return pendingEventTime;
  349.     }

  350.     /**
  351.      * Try to accept the current history up to the given time.
  352.      *
  353.      * <p> It is not necessary to call this method before calling {@link
  354.      * #doEvent(SpacecraftState)} with the same state. It is necessary to call this
  355.      * method before you call {@link #doEvent(SpacecraftState)} on some other event
  356.      * detector.
  357.      *
  358.      * @param state        to try to accept.
  359.      * @param interpolator to use to find the new root, if any.
  360.      * @return if the event detector has an event it has not detected before that is on or
  361.      * before the same time as {@code state}. In other words {@code false} means continue
  362.      * on while {@code true} means stop and handle my event first.
  363.      */
  364.     public boolean tryAdvance(final SpacecraftState state,
  365.                               final OrekitStepInterpolator interpolator) {
  366.         // check this is only called before a pending event.
  367.         check(!(pendingEvent && strictlyAfter(pendingEventTime, state.getDate())));

  368.         final AbsoluteDate t = state.getDate();

  369.         // just found an event and we know the next time we want to search again
  370.         if (strictlyAfter(t, earliestTimeConsidered)) {
  371.             return false;
  372.         }

  373.         final double g = g(state);
  374.         final boolean positive = g > 0;

  375.         // check for new root, pendingEventTime may be null if there is not pending event
  376.         if ((g == 0.0 && t.equals(pendingEventTime)) || positive == g0Positive) {
  377.             // at a root we already found, or g function has expected sign
  378.             t0 = t;
  379.             g0 = g; // g0Positive is the same
  380.             return false;
  381.         } else {
  382.             // found a root we didn't expect -> find precise location
  383.             return findRoot(interpolator, t0, g0, t, g);
  384.         }
  385.     }

  386.     /**
  387.      * Notify the user's listener of the event. The event occurs wholly within this method
  388.      * call including a call to {@link EventDetector#resetState(SpacecraftState)}
  389.      * if necessary.
  390.      *
  391.      * @param state the state at the time of the event. This must be at the same time as
  392.      *              the current value of {@link #getEventDate()}.
  393.      * @return the user's requested action and the new state if the action is {@link
  394.      * org.orekit.propagation.events.handlers.EventHandler.Action#RESET_STATE Action.RESET_STATE}.
  395.      * Otherwise the new state is {@code state}. The stop time indicates what time propagation
  396.      * should stop if the action is {@link
  397.      * org.orekit.propagation.events.handlers.EventHandler.Action#STOP Action.STOP}.
  398.      * This guarantees the integration will stop on or after the root, so that integration
  399.      * may be restarted safely.
  400.      */
  401.     public EventOccurrence doEvent(final SpacecraftState state) {
  402.         // check event is pending and is at the same time
  403.         check(pendingEvent);
  404.         check(state.getDate().equals(this.pendingEventTime));

  405.         final EventHandler.Action action = detector.eventOccurred(state, increasing == forward);
  406.         final SpacecraftState newState;
  407.         if (action == EventHandler.Action.RESET_STATE) {
  408.             newState = detector.resetState(state);
  409.         } else {
  410.             newState = state;
  411.         }
  412.         // clear pending event
  413.         pendingEvent     = false;
  414.         pendingEventTime = null;
  415.         // setup for next search
  416.         earliestTimeConsidered = afterEvent;
  417.         t0 = afterEvent;
  418.         g0 = afterG;
  419.         g0Positive = increasing;
  420.         // check g0Positive set correctly
  421.         check(g0 == 0.0 || g0Positive == (g0 > 0));
  422.         return new EventOccurrence(action, newState, stopTime);
  423.     }

  424.     /**
  425.      * Shift a time value along the current integration direction: {@link #forward}.
  426.      *
  427.      * @param t     the time to shift.
  428.      * @param delta the amount to shift.
  429.      * @return t + delta if forward, else t - delta. If the result has to be rounded it
  430.      * will be rounded to be before the true value of t + delta.
  431.      */
  432.     private AbsoluteDate shiftedBy(final AbsoluteDate t, final double delta) {
  433.         if (forward) {
  434.             final AbsoluteDate ret = t.shiftedBy(delta);
  435.             if (ret.durationFrom(t) > delta) {
  436.                 return ret.shiftedBy(-Precision.EPSILON);
  437.             } else {
  438.                 return ret;
  439.             }
  440.         } else {
  441.             final AbsoluteDate ret = t.shiftedBy(-delta);
  442.             if (t.durationFrom(ret) > delta) {
  443.                 return ret.shiftedBy(+Precision.EPSILON);
  444.             } else {
  445.                 return ret;
  446.             }
  447.         }
  448.     }

  449.     /**
  450.      * Get the time that happens first along the current propagation direction: {@link
  451.      * #forward}.
  452.      *
  453.      * @param a first time
  454.      * @param b second time
  455.      * @return min(a, b) if forward, else max (a, b)
  456.      */
  457.     private AbsoluteDate minTime(final AbsoluteDate a, final AbsoluteDate b) {
  458.         return (forward ^ (a.compareTo(b) > 0)) ? a : b;
  459.     }

  460.     /**
  461.      * Check the ordering of two times.
  462.      *
  463.      * @param t1 the first time.
  464.      * @param t2 the second time.
  465.      * @return true if {@code t2} is strictly after {@code t1} in the propagation
  466.      * direction.
  467.      */
  468.     private boolean strictlyAfter(final AbsoluteDate t1, final AbsoluteDate t2) {
  469.         if (t1 == null || t2 == null) {
  470.             return false;
  471.         } else {
  472.             return forward ? t1.compareTo(t2) < 0 : t2.compareTo(t1) < 0;
  473.         }
  474.     }

  475.     /**
  476.      * Same as keyword assert, but throw a {@link MathRuntimeException}.
  477.      *
  478.      * @param condition to check
  479.      * @throws MathRuntimeException if {@code condition} is false.
  480.      */
  481.     private void check(final boolean condition) throws MathRuntimeException {
  482.         if (!condition) {
  483.             throw new OrekitInternalError(null);
  484.         }
  485.     }

  486.     /**
  487.      * Class to hold the data related to an event occurrence that is needed to decide how
  488.      * to modify integration.
  489.      */
  490.     public static class EventOccurrence {

  491.         /** User requested action. */
  492.         private final EventHandler.Action action;
  493.         /** New state for a reset action. */
  494.         private final SpacecraftState newState;
  495.         /** The time to stop propagation if the action is a stop event. */
  496.         private final AbsoluteDate stopDate;

  497.         /**
  498.          * Create a new occurrence of an event.
  499.          *
  500.          * @param action   the user requested action.
  501.          * @param newState for a reset event. Should be the current state unless the
  502.          *                 action is {@link Action#RESET_STATE}.
  503.          * @param stopDate to stop propagation if the action is {@link Action#STOP}. Used
  504.          *                 to move the stop time to just after the root.
  505.          */
  506.         EventOccurrence(final EventHandler.Action action,
  507.                         final SpacecraftState newState,
  508.                         final AbsoluteDate stopDate) {
  509.             this.action = action;
  510.             this.newState = newState;
  511.             this.stopDate = stopDate;
  512.         }

  513.         /**
  514.          * Get the user requested action.
  515.          *
  516.          * @return the action.
  517.          */
  518.         public EventHandler.Action getAction() {
  519.             return action;
  520.         }

  521.         /**
  522.          * Get the new state for a reset action.
  523.          *
  524.          * @return the new state.
  525.          */
  526.         public SpacecraftState getNewState() {
  527.             return newState;
  528.         }

  529.         /**
  530.          * Get the new time for a stop action.
  531.          *
  532.          * @return when to stop propagation.
  533.          */
  534.         public AbsoluteDate getStopDate() {
  535.             return stopDate;
  536.         }

  537.     }

  538. }