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
018package org.apache.commons.math3.ode.sampling;
019
020import org.apache.commons.math3.exception.MaxCountExceededException;
021import org.apache.commons.math3.util.FastMath;
022import org.apache.commons.math3.util.Precision;
023
024/**
025 * This class wraps an object implementing {@link FixedStepHandler}
026 * into a {@link StepHandler}.
027
028 * <p>This wrapper allows to use fixed step handlers with general
029 * integrators which cannot guaranty their integration steps will
030 * remain constant and therefore only accept general step
031 * handlers.</p>
032 *
033 * <p>The stepsize used is selected at construction time. The {@link
034 * FixedStepHandler#handleStep handleStep} method of the underlying
035 * {@link FixedStepHandler} object is called at normalized times. The
036 * normalized times can be influenced by the {@link StepNormalizerMode} and
037 * {@link StepNormalizerBounds}.</p>
038 *
039 * <p>There is no constraint on the integrator, it can use any time step
040 * it needs (time steps longer or shorter than the fixed time step and
041 * non-integer ratios are all allowed).</p>
042 *
043 * <p>
044 * <table border="1" align="center">
045 * <tr BGCOLOR="#CCCCFF"><td colspan=6><font size="+2">Examples (step size = 0.5)</font></td></tr>
046 * <tr BGCOLOR="#EEEEFF"><font size="+1"><td>Start time</td><td>End time</td>
047 *  <td>Direction</td><td>{@link StepNormalizerMode Mode}</td>
048 *  <td>{@link StepNormalizerBounds Bounds}</td><td>Output</td></font></tr>
049 * <tr><td>0.3</td><td>3.1</td><td>forward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#NEITHER NEITHER}</td><td>0.8, 1.3, 1.8, 2.3, 2.8</td></tr>
050 * <tr><td>0.3</td><td>3.1</td><td>forward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#FIRST FIRST}</td><td>0.3, 0.8, 1.3, 1.8, 2.3, 2.8</td></tr>
051 * <tr><td>0.3</td><td>3.1</td><td>forward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#LAST LAST}</td><td>0.8, 1.3, 1.8, 2.3, 2.8, 3.1</td></tr>
052 * <tr><td>0.3</td><td>3.1</td><td>forward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#BOTH BOTH}</td><td>0.3, 0.8, 1.3, 1.8, 2.3, 2.8, 3.1</td></tr>
053 * <tr><td>0.3</td><td>3.1</td><td>forward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#NEITHER NEITHER}</td><td>0.5, 1.0, 1.5, 2.0, 2.5, 3.0</td></tr>
054 * <tr><td>0.3</td><td>3.1</td><td>forward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#FIRST FIRST}</td><td>0.3, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0</td></tr>
055 * <tr><td>0.3</td><td>3.1</td><td>forward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#LAST LAST}</td><td>0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.1</td></tr>
056 * <tr><td>0.3</td><td>3.1</td><td>forward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#BOTH BOTH}</td><td>0.3, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.1</td></tr>
057 * <tr><td>0.0</td><td>3.0</td><td>forward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#NEITHER NEITHER}</td><td>0.5, 1.0, 1.5, 2.0, 2.5, 3.0</td></tr>
058 * <tr><td>0.0</td><td>3.0</td><td>forward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#FIRST FIRST}</td><td>0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0</td></tr>
059 * <tr><td>0.0</td><td>3.0</td><td>forward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#LAST LAST}</td><td>0.5, 1.0, 1.5, 2.0, 2.5, 3.0</td></tr>
060 * <tr><td>0.0</td><td>3.0</td><td>forward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#BOTH BOTH}</td><td>0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0</td></tr>
061 * <tr><td>0.0</td><td>3.0</td><td>forward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#NEITHER NEITHER}</td><td>0.5, 1.0, 1.5, 2.0, 2.5, 3.0</td></tr>
062 * <tr><td>0.0</td><td>3.0</td><td>forward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#FIRST FIRST}</td><td>0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0</td></tr>
063 * <tr><td>0.0</td><td>3.0</td><td>forward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#LAST LAST}</td><td>0.5, 1.0, 1.5, 2.0, 2.5, 3.0</td></tr>
064 * <tr><td>0.0</td><td>3.0</td><td>forward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#BOTH BOTH}</td><td>0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0</td></tr>
065 * <tr><td>3.1</td><td>0.3</td><td>backward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#NEITHER NEITHER}</td><td>2.6, 2.1, 1.6, 1.1, 0.6</td></tr>
066 * <tr><td>3.1</td><td>0.3</td><td>backward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#FIRST FIRST}</td><td>3.1, 2.6, 2.1, 1.6, 1.1, 0.6</td></tr>
067 * <tr><td>3.1</td><td>0.3</td><td>backward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#LAST LAST}</td><td>2.6, 2.1, 1.6, 1.1, 0.6, 0.3</td></tr>
068 * <tr><td>3.1</td><td>0.3</td><td>backward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#BOTH BOTH}</td><td>3.1, 2.6, 2.1, 1.6, 1.1, 0.6, 0.3</td></tr>
069 * <tr><td>3.1</td><td>0.3</td><td>backward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#NEITHER NEITHER}</td><td>3.0, 2.5, 2.0, 1.5, 1.0, 0.5</td></tr>
070 * <tr><td>3.1</td><td>0.3</td><td>backward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#FIRST FIRST}</td><td>3.1, 3.0, 2.5, 2.0, 1.5, 1.0, 0.5</td></tr>
071 * <tr><td>3.1</td><td>0.3</td><td>backward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#LAST LAST}</td><td>3.0, 2.5, 2.0, 1.5, 1.0, 0.5, 0.3</td></tr>
072 * <tr><td>3.1</td><td>0.3</td><td>backward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#BOTH BOTH}</td><td>3.1, 3.0, 2.5, 2.0, 1.5, 1.0, 0.5, 0.3</td></tr>
073 * <tr><td>3.0</td><td>0.0</td><td>backward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#NEITHER NEITHER}</td><td>2.5, 2.0, 1.5, 1.0, 0.5, 0.0</td></tr>
074 * <tr><td>3.0</td><td>0.0</td><td>backward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#FIRST FIRST}</td><td>3.0, 2.5, 2.0, 1.5, 1.0, 0.5, 0.0</td></tr>
075 * <tr><td>3.0</td><td>0.0</td><td>backward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#LAST LAST}</td><td>2.5, 2.0, 1.5, 1.0, 0.5, 0.0</td></tr>
076 * <tr><td>3.0</td><td>0.0</td><td>backward</td><td>{@link StepNormalizerMode#INCREMENT INCREMENT}</td><td>{@link StepNormalizerBounds#BOTH BOTH}</td><td>3.0, 2.5, 2.0, 1.5, 1.0, 0.5, 0.0</td></tr>
077 * <tr><td>3.0</td><td>0.0</td><td>backward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#NEITHER NEITHER}</td><td>2.5, 2.0, 1.5, 1.0, 0.5, 0.0</td></tr>
078 * <tr><td>3.0</td><td>0.0</td><td>backward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#FIRST FIRST}</td><td>3.0, 2.5, 2.0, 1.5, 1.0, 0.5, 0.0</td></tr>
079 * <tr><td>3.0</td><td>0.0</td><td>backward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#LAST LAST}</td><td>2.5, 2.0, 1.5, 1.0, 0.5, 0.0</td></tr>
080 * <tr><td>3.0</td><td>0.0</td><td>backward</td><td>{@link StepNormalizerMode#MULTIPLES MULTIPLES}</td><td>{@link StepNormalizerBounds#BOTH BOTH}</td><td>3.0, 2.5, 2.0, 1.5, 1.0, 0.5, 0.0</td></tr>
081 * </table>
082 * </p>
083 *
084 * @see StepHandler
085 * @see FixedStepHandler
086 * @see StepNormalizerMode
087 * @see StepNormalizerBounds
088 * @since 1.2
089 */
090
091public class StepNormalizer implements StepHandler {
092    /** Fixed time step. */
093    private double h;
094
095    /** Underlying step handler. */
096    private final FixedStepHandler handler;
097
098    /** First step time. */
099    private double firstTime;
100
101    /** Last step time. */
102    private double lastTime;
103
104    /** Last state vector. */
105    private double[] lastState;
106
107    /** Last derivatives vector. */
108    private double[] lastDerivatives;
109
110    /** Integration direction indicator. */
111    private boolean forward;
112
113    /** The step normalizer bounds settings to use. */
114    private final StepNormalizerBounds bounds;
115
116    /** The step normalizer mode to use. */
117    private final StepNormalizerMode mode;
118
119    /** Simple constructor. Uses {@link StepNormalizerMode#INCREMENT INCREMENT}
120     * mode, and {@link StepNormalizerBounds#FIRST FIRST} bounds setting, for
121     * backwards compatibility.
122     * @param h fixed time step (sign is not used)
123     * @param handler fixed time step handler to wrap
124     */
125    public StepNormalizer(final double h, final FixedStepHandler handler) {
126        this(h, handler, StepNormalizerMode.INCREMENT,
127             StepNormalizerBounds.FIRST);
128    }
129
130    /** Simple constructor. Uses {@link StepNormalizerBounds#FIRST FIRST}
131     * bounds setting.
132     * @param h fixed time step (sign is not used)
133     * @param handler fixed time step handler to wrap
134     * @param mode step normalizer mode to use
135     * @since 3.0
136     */
137    public StepNormalizer(final double h, final FixedStepHandler handler,
138                          final StepNormalizerMode mode) {
139        this(h, handler, mode, StepNormalizerBounds.FIRST);
140    }
141
142    /** Simple constructor. Uses {@link StepNormalizerMode#INCREMENT INCREMENT}
143     * mode.
144     * @param h fixed time step (sign is not used)
145     * @param handler fixed time step handler to wrap
146     * @param bounds step normalizer bounds setting to use
147     * @since 3.0
148     */
149    public StepNormalizer(final double h, final FixedStepHandler handler,
150                          final StepNormalizerBounds bounds) {
151        this(h, handler, StepNormalizerMode.INCREMENT, bounds);
152    }
153
154    /** Simple constructor.
155     * @param h fixed time step (sign is not used)
156     * @param handler fixed time step handler to wrap
157     * @param mode step normalizer mode to use
158     * @param bounds step normalizer bounds setting to use
159     * @since 3.0
160     */
161    public StepNormalizer(final double h, final FixedStepHandler handler,
162                          final StepNormalizerMode mode,
163                          final StepNormalizerBounds bounds) {
164        this.h          = FastMath.abs(h);
165        this.handler    = handler;
166        this.mode       = mode;
167        this.bounds     = bounds;
168        firstTime       = Double.NaN;
169        lastTime        = Double.NaN;
170        lastState       = null;
171        lastDerivatives = null;
172        forward         = true;
173    }
174
175    /** {@inheritDoc} */
176    public void init(double t0, double[] y0, double t) {
177
178        firstTime       = Double.NaN;
179        lastTime        = Double.NaN;
180        lastState       = null;
181        lastDerivatives = null;
182        forward         = true;
183
184        // initialize the underlying handler
185        handler.init(t0, y0, t);
186
187    }
188
189    /**
190     * Handle the last accepted step
191     * @param interpolator interpolator for the last accepted step. For
192     * efficiency purposes, the various integrators reuse the same
193     * object on each call, so if the instance wants to keep it across
194     * all calls (for example to provide at the end of the integration a
195     * continuous model valid throughout the integration range), it
196     * should build a local copy using the clone method and store this
197     * copy.
198     * @param isLast true if the step is the last one
199     * @exception MaxCountExceededException if the interpolator throws one because
200     * the number of functions evaluations is exceeded
201     */
202    public void handleStep(final StepInterpolator interpolator, final boolean isLast)
203        throws MaxCountExceededException {
204        // The first time, update the last state with the start information.
205        if (lastState == null) {
206            firstTime = interpolator.getPreviousTime();
207            lastTime = interpolator.getPreviousTime();
208            interpolator.setInterpolatedTime(lastTime);
209            lastState = interpolator.getInterpolatedState().clone();
210            lastDerivatives = interpolator.getInterpolatedDerivatives().clone();
211
212            // Take the integration direction into account.
213            forward = interpolator.getCurrentTime() >= lastTime;
214            if (!forward) {
215                h = -h;
216            }
217        }
218
219        // Calculate next normalized step time.
220        double nextTime = (mode == StepNormalizerMode.INCREMENT) ?
221                          lastTime + h :
222                          (FastMath.floor(lastTime / h) + 1) * h;
223        if (mode == StepNormalizerMode.MULTIPLES &&
224            Precision.equals(nextTime, lastTime, 1)) {
225            nextTime += h;
226        }
227
228        // Process normalized steps as long as they are in the current step.
229        boolean nextInStep = isNextInStep(nextTime, interpolator);
230        while (nextInStep) {
231            // Output the stored previous step.
232            doNormalizedStep(false);
233
234            // Store the next step as last step.
235            storeStep(interpolator, nextTime);
236
237            // Move on to the next step.
238            nextTime += h;
239            nextInStep = isNextInStep(nextTime, interpolator);
240        }
241
242        if (isLast) {
243            // There will be no more steps. The stored one should be given to
244            // the handler. We may have to output one more step. Only the last
245            // one of those should be flagged as being the last.
246            boolean addLast = bounds.lastIncluded() &&
247                              lastTime != interpolator.getCurrentTime();
248            doNormalizedStep(!addLast);
249            if (addLast) {
250                storeStep(interpolator, interpolator.getCurrentTime());
251                doNormalizedStep(true);
252            }
253        }
254    }
255
256    /**
257     * Returns a value indicating whether the next normalized time is in the
258     * current step.
259     * @param nextTime the next normalized time
260     * @param interpolator interpolator for the last accepted step, to use to
261     * get the end time of the current step
262     * @return value indicating whether the next normalized time is in the
263     * current step
264     */
265    private boolean isNextInStep(double nextTime,
266                                 StepInterpolator interpolator) {
267        return forward ?
268               nextTime <= interpolator.getCurrentTime() :
269               nextTime >= interpolator.getCurrentTime();
270    }
271
272    /**
273     * Invokes the underlying step handler for the current normalized step.
274     * @param isLast true if the step is the last one
275     */
276    private void doNormalizedStep(boolean isLast) {
277        if (!bounds.firstIncluded() && firstTime == lastTime) {
278            return;
279        }
280        handler.handleStep(lastTime, lastState, lastDerivatives, isLast);
281    }
282
283    /** Stores the interpolated information for the given time in the current
284     * state.
285     * @param interpolator interpolator for the last accepted step, to use to
286     * get the interpolated information
287     * @param t the time for which to store the interpolated information
288     * @exception MaxCountExceededException if the interpolator throws one because
289     * the number of functions evaluations is exceeded
290     */
291    private void storeStep(StepInterpolator interpolator, double t)
292        throws MaxCountExceededException {
293        lastTime = t;
294        interpolator.setInterpolatedTime(lastTime);
295        System.arraycopy(interpolator.getInterpolatedState(), 0,
296                         lastState, 0, lastState.length);
297        System.arraycopy(interpolator.getInterpolatedDerivatives(), 0,
298                         lastDerivatives, 0, lastDerivatives.length);
299    }
300}