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.ode.events.Action;
  24. import org.hipparchus.util.FastMath;
  25. import org.hipparchus.util.Precision;
  26. import org.orekit.errors.OrekitInternalError;
  27. import org.orekit.propagation.SpacecraftState;
  28. import org.orekit.propagation.sampling.OrekitStepInterpolator;
  29. import org.orekit.time.AbsoluteDate;

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

  48.     /** Event detector. */
  49.     private T detector;

  50.     /** Time of the previous call to g. */
  51.     private AbsoluteDate lastT;

  52.     /** Value from the previous call to g. */
  53.     private double lastG;

  54.     /** Time at the beginning of the step. */
  55.     private AbsoluteDate t0;

  56.     /** Value of the event detector at the beginning of the step. */
  57.     private double g0;

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

  60.     /** Indicator of event expected during the step. */
  61.     private boolean pendingEvent;

  62.     /** Occurrence time of the pending event. */
  63.     private AbsoluteDate pendingEventTime;

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

  69.     /** Time after the current event. */
  70.     private AbsoluteDate afterEvent;

  71.     /** Value of the g function after the current event. */
  72.     private double afterG;

  73.     /** The earliest time considered for events. */
  74.     private AbsoluteDate earliestTimeConsidered;

  75.     /** Integration direction. */
  76.     private boolean forward;

  77.     /** Variation direction around pending event.
  78.      *  (this is considered with respect to the integration direction)
  79.      */
  80.     private boolean increasing;

  81.     /** Simple constructor.
  82.      * @param detector monitored event detector
  83.      */
  84.     public EventState(final T detector) {
  85.         this.detector     = detector;

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

  99.     }

  100.     /** Get the underlying event detector.
  101.      * @return underlying event detector
  102.      */
  103.     public T getEventDetector() {
  104.         return detector;
  105.     }

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

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

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

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

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


  180.         AbsoluteDate ta = t0;
  181.         double ga = g0;
  182.         for (int i = 0; i < n; ++i) {

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

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

  197.         }

  198.         // no event during the whole step
  199.         pendingEvent     = false;
  200.         pendingEventTime = null;
  201.         return false;

  202.     }

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

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

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

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

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

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

  324.             // check increasing set correctly
  325.             check(afterG > 0 == increasing);
  326.             check(increasing == gb >= ga);

  327.             return true;
  328.         }

  329.     }

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

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

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

  366.         final boolean meFirst;

  367.         if (strictlyAfter(t, earliestTimeConsidered)) {
  368.             // just found an event and we know the next time we want to search again
  369.             meFirst = false;
  370.         } else {
  371.             // check g function to see if there is a new event
  372.             final double g = g(state);
  373.             final boolean positive = g > 0;

  374.             if (positive == g0Positive) {
  375.                 // g function has expected sign
  376.                 g0 = g; // g0Positive is the same
  377.                 meFirst = false;
  378.             } else {
  379.                 // found a root we didn't expect -> find precise location
  380.                 final AbsoluteDate oldPendingEventTime = pendingEventTime;
  381.                 final boolean foundRoot = findRoot(interpolator, t0, g0, t, g);
  382.                 // make sure the new root is not the same as the old root, if one exists
  383.                 meFirst = foundRoot && !pendingEventTime.equals(oldPendingEventTime);
  384.             }
  385.         }

  386.         if (!meFirst) {
  387.             // advance t0 to the current time so we can't find events that occur before t
  388.             t0 = t;
  389.         }

  390.         return meFirst;
  391.     }

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

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

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

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

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

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

  491.     /**
  492.      * Class to hold the data related to an event occurrence that is needed to decide how
  493.      * to modify integration.
  494.      */
  495.     public static class EventOccurrence {

  496.         /** User requested action. */
  497.         private final Action action;
  498.         /** New state for a reset action. */
  499.         private final SpacecraftState newState;
  500.         /** The time to stop propagation if the action is a stop event. */
  501.         private final AbsoluteDate stopDate;

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

  518.         /**
  519.          * Get the user requested action.
  520.          *
  521.          * @return the action.
  522.          */
  523.         public Action getAction() {
  524.             return action;
  525.         }

  526.         /**
  527.          * Get the new state for a reset action.
  528.          *
  529.          * @return the new state.
  530.          */
  531.         public SpacecraftState getNewState() {
  532.             return newState;
  533.         }

  534.         /**
  535.          * Get the new time for a stop action.
  536.          *
  537.          * @return when to stop propagation.
  538.          */
  539.         public AbsoluteDate getStopDate() {
  540.             return stopDate;
  541.         }

  542.     }

  543. }