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.nonstiff;
019    
020    import org.apache.commons.math3.exception.DimensionMismatchException;
021    import org.apache.commons.math3.exception.MaxCountExceededException;
022    import org.apache.commons.math3.exception.NoBracketingException;
023    import org.apache.commons.math3.exception.NumberIsTooSmallException;
024    import org.apache.commons.math3.linear.Array2DRowRealMatrix;
025    import org.apache.commons.math3.ode.ExpandableStatefulODE;
026    import org.apache.commons.math3.ode.sampling.NordsieckStepInterpolator;
027    import org.apache.commons.math3.util.FastMath;
028    
029    
030    /**
031     * This class implements explicit Adams-Bashforth integrators for Ordinary
032     * Differential Equations.
033     *
034     * <p>Adams-Bashforth methods (in fact due to Adams alone) are explicit
035     * multistep ODE solvers. This implementation is a variation of the classical
036     * one: it uses adaptive stepsize to implement error control, whereas
037     * classical implementations are fixed step size. The value of state vector
038     * at step n+1 is a simple combination of the value at step n and of the
039     * derivatives at steps n, n-1, n-2 ... Depending on the number k of previous
040     * steps one wants to use for computing the next value, different formulas
041     * are available:</p>
042     * <ul>
043     *   <li>k = 1: y<sub>n+1</sub> = y<sub>n</sub> + h y'<sub>n</sub></li>
044     *   <li>k = 2: y<sub>n+1</sub> = y<sub>n</sub> + h (3y'<sub>n</sub>-y'<sub>n-1</sub>)/2</li>
045     *   <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>
046     *   <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>
047     *   <li>...</li>
048     * </ul>
049     *
050     * <p>A k-steps Adams-Bashforth method is of order k.</p>
051     *
052     * <h3>Implementation details</h3>
053     *
054     * <p>We define scaled derivatives s<sub>i</sub>(n) at step n as:
055     * <pre>
056     * s<sub>1</sub>(n) = h y'<sub>n</sub> for first derivative
057     * s<sub>2</sub>(n) = h<sup>2</sup>/2 y''<sub>n</sub> for second derivative
058     * s<sub>3</sub>(n) = h<sup>3</sup>/6 y'''<sub>n</sub> for third derivative
059     * ...
060     * s<sub>k</sub>(n) = h<sup>k</sup>/k! y<sup>(k)</sup><sub>n</sub> for k<sup>th</sup> derivative
061     * </pre></p>
062     *
063     * <p>The definitions above use the classical representation with several previous first
064     * derivatives. Lets define
065     * <pre>
066     *   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>
067     * </pre>
068     * (we omit the k index in the notation for clarity). With these definitions,
069     * Adams-Bashforth methods can be written:
070     * <ul>
071     *   <li>k = 1: y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n)</li>
072     *   <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>
073     *   <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>
074     *   <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>
075     *   <li>...</li>
076     * </ul></p>
077     *
078     * <p>Instead of using the classical representation with first derivatives only (y<sub>n</sub>,
079     * s<sub>1</sub>(n) and q<sub>n</sub>), our implementation uses the Nordsieck vector with
080     * higher degrees scaled derivatives all taken at the same step (y<sub>n</sub>, s<sub>1</sub>(n)
081     * and r<sub>n</sub>) where r<sub>n</sub> is defined as:
082     * <pre>
083     * r<sub>n</sub> = [ s<sub>2</sub>(n), s<sub>3</sub>(n) ... s<sub>k</sub>(n) ]<sup>T</sup>
084     * </pre>
085     * (here again we omit the k index in the notation for clarity)
086     * </p>
087     *
088     * <p>Taylor series formulas show that for any index offset i, s<sub>1</sub>(n-i) can be
089     * computed from s<sub>1</sub>(n), s<sub>2</sub>(n) ... s<sub>k</sub>(n), the formula being exact
090     * for degree k polynomials.
091     * <pre>
092     * 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)
093     * </pre>
094     * The previous formula can be used with several values for i to compute the transform between
095     * classical representation and Nordsieck vector. The transform between r<sub>n</sub>
096     * and q<sub>n</sub> resulting from the Taylor series formulas above is:
097     * <pre>
098     * q<sub>n</sub> = s<sub>1</sub>(n) u + P r<sub>n</sub>
099     * </pre>
100     * where u is the [ 1 1 ... 1 ]<sup>T</sup> vector and P is the (k-1)&times;(k-1) matrix built
101     * with the j (-i)<sup>j-1</sup> terms:
102     * <pre>
103     *        [  -2   3   -4    5  ... ]
104     *        [  -4  12  -32   80  ... ]
105     *   P =  [  -6  27 -108  405  ... ]
106     *        [  -8  48 -256 1280  ... ]
107     *        [          ...           ]
108     * </pre></p>
109     *
110     * <p>Using the Nordsieck vector has several advantages:
111     * <ul>
112     *   <li>it greatly simplifies step interpolation as the interpolator mainly applies
113     *   Taylor series formulas,</li>
114     *   <li>it simplifies step changes that occur when discrete events that truncate
115     *   the step are triggered,</li>
116     *   <li>it allows to extend the methods in order to support adaptive stepsize.</li>
117     * </ul></p>
118     *
119     * <p>The Nordsieck vector at step n+1 is computed from the Nordsieck vector at step n as follows:
120     * <ul>
121     *   <li>y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n) + u<sup>T</sup> r<sub>n</sub></li>
122     *   <li>s<sub>1</sub>(n+1) = h f(t<sub>n+1</sub>, y<sub>n+1</sub>)</li>
123     *   <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>
124     * </ul>
125     * where A is a rows shifting matrix (the lower left part is an identity matrix):
126     * <pre>
127     *        [ 0 0   ...  0 0 | 0 ]
128     *        [ ---------------+---]
129     *        [ 1 0   ...  0 0 | 0 ]
130     *    A = [ 0 1   ...  0 0 | 0 ]
131     *        [       ...      | 0 ]
132     *        [ 0 0   ...  1 0 | 0 ]
133     *        [ 0 0   ...  0 1 | 0 ]
134     * </pre></p>
135     *
136     * <p>The P<sup>-1</sup>u vector and the P<sup>-1</sup> A P matrix do not depend on the state,
137     * they only depend on k and therefore are precomputed once for all.</p>
138     *
139     * @version $Id: AdamsBashforthIntegrator.java 1416643 2012-12-03 19:37:14Z tn $
140     * @since 2.0
141     */
142    public 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                System.arraycopy(interpolator.getInterpolatedState(), 0, y, 0, y0.length);
259    
260                // evaluate the derivative
261                computeDerivatives(stepEnd, y, yDot);
262    
263                // update Nordsieck vector
264                final double[] predictedScaled = new double[y0.length];
265                for (int j = 0; j < y0.length; ++j) {
266                    predictedScaled[j] = stepSize * yDot[j];
267                }
268                final Array2DRowRealMatrix nordsieckTmp = updateHighOrderDerivativesPhase1(nordsieck);
269                updateHighOrderDerivativesPhase2(scaled, predictedScaled, nordsieckTmp);
270                interpolator.reinitialize(stepEnd, stepSize, predictedScaled, nordsieckTmp);
271    
272                // discrete events handling
273                interpolator.storeTime(stepEnd);
274                stepStart = acceptStep(interpolator, y, yDot, t);
275                scaled    = predictedScaled;
276                nordsieck = nordsieckTmp;
277                interpolator.reinitialize(stepEnd, stepSize, scaled, nordsieck);
278    
279                if (!isLastStep) {
280    
281                    // prepare next step
282                    interpolator.storeTime(stepStart);
283    
284                    if (resetOccurred) {
285                        // some events handler has triggered changes that
286                        // invalidate the derivatives, we need to restart from scratch
287                        start(stepStart, y, t);
288                        interpolator.reinitialize(stepStart, stepSize, scaled, nordsieck);
289                    }
290    
291                    // stepsize control for next step
292                    final double  factor     = computeStepGrowShrinkFactor(error);
293                    final double  scaledH    = stepSize * factor;
294                    final double  nextT      = stepStart + scaledH;
295                    final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);
296                    hNew = filterStep(scaledH, forward, nextIsLast);
297    
298                    final double  filteredNextT      = stepStart + hNew;
299                    final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t);
300                    if (filteredNextIsLast) {
301                        hNew = t - stepStart;
302                    }
303    
304                    interpolator.rescale(hNew);
305    
306                }
307    
308            } while (!isLastStep);
309    
310            // dispatch results
311            equations.setTime(stepStart);
312            equations.setCompleteState(y);
313    
314            resetInternalState();
315    
316        }
317    
318    }