001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    
018    package org.apache.commons.math3.ode.events;
019    
020    
021    /** This interface represents a handler for discrete events triggered
022     * during ODE integration.
023     *
024     * <p>Some events can be triggered at discrete times as an ODE problem
025     * is solved. This occurs for example when the integration process
026     * should be stopped as some state is reached (G-stop facility) when the
027     * precise date is unknown a priori, or when the derivatives have
028     * discontinuities, or simply when the user wants to monitor some
029     * states boundaries crossings.
030     * </p>
031     *
032     * <p>These events are defined as occurring when a <code>g</code>
033     * switching function sign changes.</p>
034     *
035     * <p>Since events are only problem-dependent and are triggered by the
036     * independent <i>time</i> variable and the state vector, they can
037     * occur at virtually any time, unknown in advance. The integrators will
038     * take care to avoid sign changes inside the steps, they will reduce
039     * the step size when such an event is detected in order to put this
040     * event exactly at the end of the current step. This guarantees that
041     * step interpolation (which always has a one step scope) is relevant
042     * even in presence of discontinuities. This is independent from the
043     * stepsize control provided by integrators that monitor the local
044     * error (this event handling feature is available for all integrators,
045     * including fixed step ones).</p>
046     *
047     * @version $Id: EventHandler.java 1451658 2013-03-01 17:36:46Z luc $
048     * @since 1.2
049     */
050    
051    public interface EventHandler  {
052    
053        /** Enumerate for actions to be performed when an event occurs. */
054        public enum Action {
055    
056            /** Stop indicator.
057             * <p>This value should be used as the return value of the {@link
058             * #eventOccurred eventOccurred} method when the integration should be
059             * stopped after the event ending the current step.</p>
060             */
061            STOP,
062    
063            /** Reset state indicator.
064             * <p>This value should be used as the return value of the {@link
065             * #eventOccurred eventOccurred} method when the integration should
066             * go on after the event ending the current step, with a new state
067             * vector (which will be retrieved thanks to the {@link #resetState
068             * resetState} method).</p>
069             */
070            RESET_STATE,
071    
072            /** Reset derivatives indicator.
073             * <p>This value should be used as the return value of the {@link
074             * #eventOccurred eventOccurred} method when the integration should
075             * go on after the event ending the current step, with a new derivatives
076             * vector (which will be retrieved thanks to the {@link
077             * org.apache.commons.math3.ode.FirstOrderDifferentialEquations#computeDerivatives}
078             * method).</p>
079             */
080            RESET_DERIVATIVES,
081    
082            /** Continue indicator.
083             * <p>This value should be used as the return value of the {@link
084             * #eventOccurred eventOccurred} method when the integration should go
085             * on after the event ending the current step.</p>
086             */
087            CONTINUE;
088    
089        }
090    
091        /** Initialize event handler at the start of an ODE integration.
092         * <p>
093         * This method is called once at the start of the integration. It
094         * may be used by the event handler to initialize some internal data
095         * if needed.
096         * </p>
097         * @param t0 start value of the independent <i>time</i> variable
098         * @param y0 array containing the start value of the state vector
099         * @param t target time for the integration
100         */
101        void init(double t0, double[] y0, double t);
102    
103      /** Compute the value of the switching function.
104    
105       * <p>The discrete events are generated when the sign of this
106       * switching function changes. The integrator will take care to change
107       * the stepsize in such a way these events occur exactly at step boundaries.
108       * The switching function must be continuous in its roots neighborhood
109       * (but not necessarily smooth), as the integrator will need to find its
110       * roots to locate precisely the events.</p>
111       * <p>Also note that the integrator expect that once an event has occurred,
112       * the sign of the switching function at the start of the next step (i.e.
113       * just after the event) is the opposite of the sign just before the event.
114       * This consistency between the steps <string>must</strong> be preserved,
115       * otherwise {@link org.apache.commons.math3.exception.NoBracketingException
116       * exceptions} related to root not being bracketed will occur.</p>
117       * <p>This need for consistency is sometimes tricky to achieve. A typical
118       * example is using an event to model a ball bouncing on the floor. The first
119       * idea to represent this would be to have {@code g(t) = h(t)} where h is the
120       * height above the floor at time {@code t}. When {@code g(t)} reaches 0, the
121       * ball is on the floor, so it should bounce and the typical way to do this is
122       * to reverse its vertical velocity. However, this would mean that before the
123       * event {@code g(t)} was decreasing from positive values to 0, and after the
124       * event {@code g(t)} would be increasing from 0 to positive values again.
125       * Consistency is broken here! The solution here is to have {@code g(t) = sign
126       * * h(t)}, where sign is a variable with initial value set to {@code +1}. Each
127       * time {@link #eventOccurred(double, double[], boolean) eventOccurred} is called,
128       * {@code sign} is reset to {@code -sign}. This allows the {@code g(t)}
129       * function to remain continuous (and even smooth) even across events, despite
130       * {@code h(t)} is not. Basically, the event is used to <em>fold</em> {@code h(t)}
131       * at bounce points, and {@code sign} is used to <em>unfold</em> it back, so the
132       * solvers sees a {@code g(t)} function which behaves smoothly even across events.</p>
133    
134       * @param t current value of the independent <i>time</i> variable
135       * @param y array containing the current value of the state vector
136       * @return value of the g switching function
137       */
138      double g(double t, double[] y);
139    
140      /** Handle an event and choose what to do next.
141    
142       * <p>This method is called when the integrator has accepted a step
143       * ending exactly on a sign change of the function, just <em>before</em>
144       * the step handler itself is called (see below for scheduling). It
145       * allows the user to update his internal data to acknowledge the fact
146       * the event has been handled (for example setting a flag in the {@link
147       * org.apache.commons.math3.ode.FirstOrderDifferentialEquations
148       * differential equations} to switch the derivatives computation in
149       * case of discontinuity), or to direct the integrator to either stop
150       * or continue integration, possibly with a reset state or derivatives.</p>
151    
152       * <ul>
153       *   <li>if {@link Action#STOP} is returned, the step handler will be called
154       *   with the <code>isLast</code> flag of the {@link
155       *   org.apache.commons.math3.ode.sampling.StepHandler#handleStep handleStep}
156       *   method set to true and the integration will be stopped,</li>
157       *   <li>if {@link Action#RESET_STATE} is returned, the {@link #resetState
158       *   resetState} method will be called once the step handler has
159       *   finished its task, and the integrator will also recompute the
160       *   derivatives,</li>
161       *   <li>if {@link Action#RESET_DERIVATIVES} is returned, the integrator
162       *   will recompute the derivatives,
163       *   <li>if {@link Action#CONTINUE} is returned, no specific action will
164       *   be taken (apart from having called this method) and integration
165       *   will continue.</li>
166       * </ul>
167    
168       * <p>The scheduling between this method and the {@link
169       * org.apache.commons.math3.ode.sampling.StepHandler StepHandler} method {@link
170       * org.apache.commons.math3.ode.sampling.StepHandler#handleStep(
171       * org.apache.commons.math3.ode.sampling.StepInterpolator, boolean)
172       * handleStep(interpolator, isLast)} is to call this method first and
173       * <code>handleStep</code> afterwards. This scheduling allows the integrator to
174       * pass <code>true</code> as the <code>isLast</code> parameter to the step
175       * handler to make it aware the step will be the last one if this method
176       * returns {@link Action#STOP}. As the interpolator may be used to navigate back
177       * throughout the last step (as {@link
178       * org.apache.commons.math3.ode.sampling.StepNormalizer StepNormalizer}
179       * does for example), user code called by this method and user
180       * code called by step handlers may experience apparently out of order values
181       * of the independent time variable. As an example, if the same user object
182       * implements both this {@link EventHandler EventHandler} interface and the
183       * {@link org.apache.commons.math3.ode.sampling.FixedStepHandler FixedStepHandler}
184       * interface, a <em>forward</em> integration may call its
185       * <code>eventOccurred</code> method with t = 10 first and call its
186       * <code>handleStep</code> method with t = 9 afterwards. Such out of order
187       * calls are limited to the size of the integration step for {@link
188       * org.apache.commons.math3.ode.sampling.StepHandler variable step handlers} and
189       * to the size of the fixed step for {@link
190       * org.apache.commons.math3.ode.sampling.FixedStepHandler fixed step handlers}.</p>
191    
192       * @param t current value of the independent <i>time</i> variable
193       * @param y array containing the current value of the state vector
194       * @param increasing if true, the value of the switching function increases
195       * when times increases around event (note that increase is measured with respect
196       * to physical time, not with respect to integration which may go backward in time)
197       * @return indication of what the integrator should do next, this
198       * value must be one of {@link Action#STOP}, {@link Action#RESET_STATE},
199       * {@link Action#RESET_DERIVATIVES} or {@link Action#CONTINUE}
200       */
201      Action eventOccurred(double t, double[] y, boolean increasing);
202    
203      /** Reset the state prior to continue the integration.
204    
205       * <p>This method is called after the step handler has returned and
206       * before the next step is started, but only when {@link
207       * #eventOccurred} has itself returned the {@link Action#RESET_STATE}
208       * indicator. It allows the user to reset the state vector for the
209       * next step, without perturbing the step handler of the finishing
210       * step. If the {@link #eventOccurred} never returns the {@link
211       * Action#RESET_STATE} indicator, this function will never be called, and it is
212       * safe to leave its body empty.</p>
213    
214       * @param t current value of the independent <i>time</i> variable
215       * @param y array containing the current value of the state vector
216       * the new state should be put in the same array
217       */
218      void resetState(double t, double[] y);
219    
220    }