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.nonstiff;
019
020import org.apache.commons.math3.exception.DimensionMismatchException;
021import org.apache.commons.math3.exception.MaxCountExceededException;
022import org.apache.commons.math3.exception.NoBracketingException;
023import org.apache.commons.math3.exception.NumberIsTooSmallException;
024import org.apache.commons.math3.linear.Array2DRowRealMatrix;
025import org.apache.commons.math3.ode.EquationsMapper;
026import org.apache.commons.math3.ode.ExpandableStatefulODE;
027import org.apache.commons.math3.ode.sampling.NordsieckStepInterpolator;
028import org.apache.commons.math3.util.FastMath;
029
030
031/**
032 * This class implements explicit Adams-Bashforth integrators for Ordinary
033 * Differential Equations.
034 *
035 * <p>Adams-Bashforth methods (in fact due to Adams alone) are explicit
036 * multistep ODE solvers. This implementation is a variation of the classical
037 * one: it uses adaptive stepsize to implement error control, whereas
038 * classical implementations are fixed step size. The value of state vector
039 * at step n+1 is a simple combination of the value at step n and of the
040 * derivatives at steps n, n-1, n-2 ... Depending on the number k of previous
041 * steps one wants to use for computing the next value, different formulas
042 * are available:</p>
043 * <ul>
044 *   <li>k = 1: y<sub>n+1</sub> = y<sub>n</sub> + h y'<sub>n</sub></li>
045 *   <li>k = 2: y<sub>n+1</sub> = y<sub>n</sub> + h (3y'<sub>n</sub>-y'<sub>n-1</sub>)/2</li>
046 *   <li>k = 3: y<sub>n+1</sub> = y<sub>n</sub> + h (23y'<sub>n</sub>-16y'<sub>n-1</sub>+5y'<sub>n-2</sub>)/12</li>
047 *   <li>k = 4: y<sub>n+1</sub> = y<sub>n</sub> + h (55y'<sub>n</sub>-59y'<sub>n-1</sub>+37y'<sub>n-2</sub>-9y'<sub>n-3</sub>)/24</li>
048 *   <li>...</li>
049 * </ul>
050 *
051 * <p>A k-steps Adams-Bashforth method is of order k.</p>
052 *
053 * <h3>Implementation details</h3>
054 *
055 * <p>We define scaled derivatives s<sub>i</sub>(n) at step n as:
056 * <pre>
057 * s<sub>1</sub>(n) = h y'<sub>n</sub> for first derivative
058 * s<sub>2</sub>(n) = h<sup>2</sup>/2 y''<sub>n</sub> for second derivative
059 * s<sub>3</sub>(n) = h<sup>3</sup>/6 y'''<sub>n</sub> for third derivative
060 * ...
061 * s<sub>k</sub>(n) = h<sup>k</sup>/k! y<sup>(k)</sup><sub>n</sub> for k<sup>th</sup> derivative
062 * </pre></p>
063 *
064 * <p>The definitions above use the classical representation with several previous first
065 * derivatives. Lets define
066 * <pre>
067 *   q<sub>n</sub> = [ s<sub>1</sub>(n-1) s<sub>1</sub>(n-2) ... s<sub>1</sub>(n-(k-1)) ]<sup>T</sup>
068 * </pre>
069 * (we omit the k index in the notation for clarity). With these definitions,
070 * Adams-Bashforth methods can be written:
071 * <ul>
072 *   <li>k = 1: y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n)</li>
073 *   <li>k = 2: y<sub>n+1</sub> = y<sub>n</sub> + 3/2 s<sub>1</sub>(n) + [ -1/2 ] q<sub>n</sub></li>
074 *   <li>k = 3: y<sub>n+1</sub> = y<sub>n</sub> + 23/12 s<sub>1</sub>(n) + [ -16/12 5/12 ] q<sub>n</sub></li>
075 *   <li>k = 4: y<sub>n+1</sub> = y<sub>n</sub> + 55/24 s<sub>1</sub>(n) + [ -59/24 37/24 -9/24 ] q<sub>n</sub></li>
076 *   <li>...</li>
077 * </ul></p>
078 *
079 * <p>Instead of using the classical representation with first derivatives only (y<sub>n</sub>,
080 * s<sub>1</sub>(n) and q<sub>n</sub>), our implementation uses the Nordsieck vector with
081 * higher degrees scaled derivatives all taken at the same step (y<sub>n</sub>, s<sub>1</sub>(n)
082 * and r<sub>n</sub>) where r<sub>n</sub> is defined as:
083 * <pre>
084 * r<sub>n</sub> = [ s<sub>2</sub>(n), s<sub>3</sub>(n) ... s<sub>k</sub>(n) ]<sup>T</sup>
085 * </pre>
086 * (here again we omit the k index in the notation for clarity)
087 * </p>
088 *
089 * <p>Taylor series formulas show that for any index offset i, s<sub>1</sub>(n-i) can be
090 * computed from s<sub>1</sub>(n), s<sub>2</sub>(n) ... s<sub>k</sub>(n), the formula being exact
091 * for degree k polynomials.
092 * <pre>
093 * s<sub>1</sub>(n-i) = s<sub>1</sub>(n) + &sum;<sub>j</sub> j (-i)<sup>j-1</sup> s<sub>j</sub>(n)
094 * </pre>
095 * The previous formula can be used with several values for i to compute the transform between
096 * classical representation and Nordsieck vector. The transform between r<sub>n</sub>
097 * and q<sub>n</sub> resulting from the Taylor series formulas above is:
098 * <pre>
099 * q<sub>n</sub> = s<sub>1</sub>(n) u + P r<sub>n</sub>
100 * </pre>
101 * where u is the [ 1 1 ... 1 ]<sup>T</sup> vector and P is the (k-1)&times;(k-1) matrix built
102 * with the j (-i)<sup>j-1</sup> terms:
103 * <pre>
104 *        [  -2   3   -4    5  ... ]
105 *        [  -4  12  -32   80  ... ]
106 *   P =  [  -6  27 -108  405  ... ]
107 *        [  -8  48 -256 1280  ... ]
108 *        [          ...           ]
109 * </pre></p>
110 *
111 * <p>Using the Nordsieck vector has several advantages:
112 * <ul>
113 *   <li>it greatly simplifies step interpolation as the interpolator mainly applies
114 *   Taylor series formulas,</li>
115 *   <li>it simplifies step changes that occur when discrete events that truncate
116 *   the step are triggered,</li>
117 *   <li>it allows to extend the methods in order to support adaptive stepsize.</li>
118 * </ul></p>
119 *
120 * <p>The Nordsieck vector at step n+1 is computed from the Nordsieck vector at step n as follows:
121 * <ul>
122 *   <li>y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n) + u<sup>T</sup> r<sub>n</sub></li>
123 *   <li>s<sub>1</sub>(n+1) = h f(t<sub>n+1</sub>, y<sub>n+1</sub>)</li>
124 *   <li>r<sub>n+1</sub> = (s<sub>1</sub>(n) - s<sub>1</sub>(n+1)) P<sup>-1</sup> u + P<sup>-1</sup> A P r<sub>n</sub></li>
125 * </ul>
126 * where A is a rows shifting matrix (the lower left part is an identity matrix):
127 * <pre>
128 *        [ 0 0   ...  0 0 | 0 ]
129 *        [ ---------------+---]
130 *        [ 1 0   ...  0 0 | 0 ]
131 *    A = [ 0 1   ...  0 0 | 0 ]
132 *        [       ...      | 0 ]
133 *        [ 0 0   ...  1 0 | 0 ]
134 *        [ 0 0   ...  0 1 | 0 ]
135 * </pre></p>
136 *
137 * <p>The P<sup>-1</sup>u vector and the P<sup>-1</sup> A P matrix do not depend on the state,
138 * they only depend on k and therefore are precomputed once for all.</p>
139 *
140 * @since 2.0
141 */
142public class AdamsBashforthIntegrator extends AdamsIntegrator {
143
144    /** Integrator method name. */
145    private static final String METHOD_NAME = "Adams-Bashforth";
146
147    /**
148     * Build an Adams-Bashforth integrator with the given order and step control parameters.
149     * @param nSteps number of steps of the method excluding the one being computed
150     * @param minStep minimal step (sign is irrelevant, regardless of
151     * integration direction, forward or backward), the last step can
152     * be smaller than this
153     * @param maxStep maximal step (sign is irrelevant, regardless of
154     * integration direction, forward or backward), the last step can
155     * be smaller than this
156     * @param scalAbsoluteTolerance allowed absolute error
157     * @param scalRelativeTolerance allowed relative error
158     * @exception NumberIsTooSmallException if order is 1 or less
159     */
160    public AdamsBashforthIntegrator(final int nSteps,
161                                    final double minStep, final double maxStep,
162                                    final double scalAbsoluteTolerance,
163                                    final double scalRelativeTolerance)
164        throws NumberIsTooSmallException {
165        super(METHOD_NAME, nSteps, nSteps, minStep, maxStep,
166              scalAbsoluteTolerance, scalRelativeTolerance);
167    }
168
169    /**
170     * Build an Adams-Bashforth integrator with the given order and step control parameters.
171     * @param nSteps number of steps of the method excluding the one being computed
172     * @param minStep minimal step (sign is irrelevant, regardless of
173     * integration direction, forward or backward), the last step can
174     * be smaller than this
175     * @param maxStep maximal step (sign is irrelevant, regardless of
176     * integration direction, forward or backward), the last step can
177     * be smaller than this
178     * @param vecAbsoluteTolerance allowed absolute error
179     * @param vecRelativeTolerance allowed relative error
180     * @exception IllegalArgumentException if order is 1 or less
181     */
182    public AdamsBashforthIntegrator(final int nSteps,
183                                    final double minStep, final double maxStep,
184                                    final double[] vecAbsoluteTolerance,
185                                    final double[] vecRelativeTolerance)
186        throws IllegalArgumentException {
187        super(METHOD_NAME, nSteps, nSteps, minStep, maxStep,
188              vecAbsoluteTolerance, vecRelativeTolerance);
189    }
190
191    /** {@inheritDoc} */
192    @Override
193    public void integrate(final ExpandableStatefulODE equations, final double t)
194        throws NumberIsTooSmallException, DimensionMismatchException,
195               MaxCountExceededException, NoBracketingException {
196
197        sanityChecks(equations, t);
198        setEquations(equations);
199        final boolean forward = t > equations.getTime();
200
201        // initialize working arrays
202        final double[] y0   = equations.getCompleteState();
203        final double[] y    = y0.clone();
204        final double[] yDot = new double[y.length];
205
206        // set up an interpolator sharing the integrator arrays
207        final NordsieckStepInterpolator interpolator = new NordsieckStepInterpolator();
208        interpolator.reinitialize(y, forward,
209                                  equations.getPrimaryMapper(), equations.getSecondaryMappers());
210
211        // set up integration control objects
212        initIntegration(equations.getTime(), y0, t);
213
214        // compute the initial Nordsieck vector using the configured starter integrator
215        start(equations.getTime(), y, t);
216        interpolator.reinitialize(stepStart, stepSize, scaled, nordsieck);
217        interpolator.storeTime(stepStart);
218        final int lastRow = nordsieck.getRowDimension() - 1;
219
220        // reuse the step that was chosen by the starter integrator
221        double hNew = stepSize;
222        interpolator.rescale(hNew);
223
224        // main integration loop
225        isLastStep = false;
226        do {
227
228            double error = 10;
229            while (error >= 1.0) {
230
231                stepSize = hNew;
232
233                // evaluate error using the last term of the Taylor expansion
234                error = 0;
235                for (int i = 0; i < mainSetDimension; ++i) {
236                    final double yScale = FastMath.abs(y[i]);
237                    final double tol = (vecAbsoluteTolerance == null) ?
238                                       (scalAbsoluteTolerance + scalRelativeTolerance * yScale) :
239                                       (vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * yScale);
240                    final double ratio  = nordsieck.getEntry(lastRow, i) / tol;
241                    error += ratio * ratio;
242                }
243                error = FastMath.sqrt(error / mainSetDimension);
244
245                if (error >= 1.0) {
246                    // reject the step and attempt to reduce error by stepsize control
247                    final double factor = computeStepGrowShrinkFactor(error);
248                    hNew = filterStep(stepSize * factor, forward, false);
249                    interpolator.rescale(hNew);
250
251                }
252            }
253
254            // predict a first estimate of the state at step end
255            final double stepEnd = stepStart + stepSize;
256            interpolator.shift();
257            interpolator.setInterpolatedTime(stepEnd);
258            final ExpandableStatefulODE expandable = getExpandable();
259            final EquationsMapper primary = expandable.getPrimaryMapper();
260            primary.insertEquationData(interpolator.getInterpolatedState(), y);
261            int index = 0;
262            for (final EquationsMapper secondary : expandable.getSecondaryMappers()) {
263                secondary.insertEquationData(interpolator.getInterpolatedSecondaryState(index), y);
264                ++index;
265            }
266
267            // evaluate the derivative
268            computeDerivatives(stepEnd, y, yDot);
269
270            // update Nordsieck vector
271            final double[] predictedScaled = new double[y0.length];
272            for (int j = 0; j < y0.length; ++j) {
273                predictedScaled[j] = stepSize * yDot[j];
274            }
275            final Array2DRowRealMatrix nordsieckTmp = updateHighOrderDerivativesPhase1(nordsieck);
276            updateHighOrderDerivativesPhase2(scaled, predictedScaled, nordsieckTmp);
277            interpolator.reinitialize(stepEnd, stepSize, predictedScaled, nordsieckTmp);
278
279            // discrete events handling
280            interpolator.storeTime(stepEnd);
281            stepStart = acceptStep(interpolator, y, yDot, t);
282            scaled    = predictedScaled;
283            nordsieck = nordsieckTmp;
284            interpolator.reinitialize(stepEnd, stepSize, scaled, nordsieck);
285
286            if (!isLastStep) {
287
288                // prepare next step
289                interpolator.storeTime(stepStart);
290
291                if (resetOccurred) {
292                    // some events handler has triggered changes that
293                    // invalidate the derivatives, we need to restart from scratch
294                    start(stepStart, y, t);
295                    interpolator.reinitialize(stepStart, stepSize, scaled, nordsieck);
296                }
297
298                // stepsize control for next step
299                final double  factor     = computeStepGrowShrinkFactor(error);
300                final double  scaledH    = stepSize * factor;
301                final double  nextT      = stepStart + scaledH;
302                final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);
303                hNew = filterStep(scaledH, forward, nextIsLast);
304
305                final double  filteredNextT      = stepStart + hNew;
306                final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t);
307                if (filteredNextIsLast) {
308                    hNew = t - stepStart;
309                }
310
311                interpolator.rescale(hNew);
312
313            }
314
315        } while (!isLastStep);
316
317        // dispatch results
318        equations.setTime(stepStart);
319        equations.setCompleteState(y);
320
321        resetInternalState();
322
323    }
324
325}