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.EquationsMapper;
026    import org.apache.commons.math3.ode.ExpandableStatefulODE;
027    import org.apache.commons.math3.ode.sampling.NordsieckStepInterpolator;
028    import 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     * @version $Id: AdamsBashforthIntegrator.java 1463684 2013-04-02 19:04:13Z luc $
141     * @since 2.0
142     */
143    public class AdamsBashforthIntegrator extends AdamsIntegrator {
144    
145        /** Integrator method name. */
146        private static final String METHOD_NAME = "Adams-Bashforth";
147    
148        /**
149         * Build an Adams-Bashforth integrator with the given order and step control parameters.
150         * @param nSteps number of steps of the method excluding the one being computed
151         * @param minStep minimal step (sign is irrelevant, regardless of
152         * integration direction, forward or backward), the last step can
153         * be smaller than this
154         * @param maxStep maximal step (sign is irrelevant, regardless of
155         * integration direction, forward or backward), the last step can
156         * be smaller than this
157         * @param scalAbsoluteTolerance allowed absolute error
158         * @param scalRelativeTolerance allowed relative error
159         * @exception NumberIsTooSmallException if order is 1 or less
160         */
161        public AdamsBashforthIntegrator(final int nSteps,
162                                        final double minStep, final double maxStep,
163                                        final double scalAbsoluteTolerance,
164                                        final double scalRelativeTolerance)
165            throws NumberIsTooSmallException {
166            super(METHOD_NAME, nSteps, nSteps, minStep, maxStep,
167                  scalAbsoluteTolerance, scalRelativeTolerance);
168        }
169    
170        /**
171         * Build an Adams-Bashforth integrator with the given order and step control parameters.
172         * @param nSteps number of steps of the method excluding the one being computed
173         * @param minStep minimal step (sign is irrelevant, regardless of
174         * integration direction, forward or backward), the last step can
175         * be smaller than this
176         * @param maxStep maximal step (sign is irrelevant, regardless of
177         * integration direction, forward or backward), the last step can
178         * be smaller than this
179         * @param vecAbsoluteTolerance allowed absolute error
180         * @param vecRelativeTolerance allowed relative error
181         * @exception IllegalArgumentException if order is 1 or less
182         */
183        public AdamsBashforthIntegrator(final int nSteps,
184                                        final double minStep, final double maxStep,
185                                        final double[] vecAbsoluteTolerance,
186                                        final double[] vecRelativeTolerance)
187            throws IllegalArgumentException {
188            super(METHOD_NAME, nSteps, nSteps, minStep, maxStep,
189                  vecAbsoluteTolerance, vecRelativeTolerance);
190        }
191    
192        /** {@inheritDoc} */
193        @Override
194        public void integrate(final ExpandableStatefulODE equations, final double t)
195            throws NumberIsTooSmallException, DimensionMismatchException,
196                   MaxCountExceededException, NoBracketingException {
197    
198            sanityChecks(equations, t);
199            setEquations(equations);
200            final boolean forward = t > equations.getTime();
201    
202            // initialize working arrays
203            final double[] y0   = equations.getCompleteState();
204            final double[] y    = y0.clone();
205            final double[] yDot = new double[y.length];
206    
207            // set up an interpolator sharing the integrator arrays
208            final NordsieckStepInterpolator interpolator = new NordsieckStepInterpolator();
209            interpolator.reinitialize(y, forward,
210                                      equations.getPrimaryMapper(), equations.getSecondaryMappers());
211    
212            // set up integration control objects
213            initIntegration(equations.getTime(), y0, t);
214    
215            // compute the initial Nordsieck vector using the configured starter integrator
216            start(equations.getTime(), y, t);
217            interpolator.reinitialize(stepStart, stepSize, scaled, nordsieck);
218            interpolator.storeTime(stepStart);
219            final int lastRow = nordsieck.getRowDimension() - 1;
220    
221            // reuse the step that was chosen by the starter integrator
222            double hNew = stepSize;
223            interpolator.rescale(hNew);
224    
225            // main integration loop
226            isLastStep = false;
227            do {
228    
229                double error = 10;
230                while (error >= 1.0) {
231    
232                    stepSize = hNew;
233    
234                    // evaluate error using the last term of the Taylor expansion
235                    error = 0;
236                    for (int i = 0; i < mainSetDimension; ++i) {
237                        final double yScale = FastMath.abs(y[i]);
238                        final double tol = (vecAbsoluteTolerance == null) ?
239                                           (scalAbsoluteTolerance + scalRelativeTolerance * yScale) :
240                                           (vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * yScale);
241                        final double ratio  = nordsieck.getEntry(lastRow, i) / tol;
242                        error += ratio * ratio;
243                    }
244                    error = FastMath.sqrt(error / mainSetDimension);
245    
246                    if (error >= 1.0) {
247                        // reject the step and attempt to reduce error by stepsize control
248                        final double factor = computeStepGrowShrinkFactor(error);
249                        hNew = filterStep(stepSize * factor, forward, false);
250                        interpolator.rescale(hNew);
251    
252                    }
253                }
254    
255                // predict a first estimate of the state at step end
256                final double stepEnd = stepStart + stepSize;
257                interpolator.shift();
258                interpolator.setInterpolatedTime(stepEnd);
259                final ExpandableStatefulODE expandable = getExpandable();
260                final EquationsMapper primary = expandable.getPrimaryMapper();
261                primary.insertEquationData(interpolator.getInterpolatedState(), y);
262                int index = 0;
263                for (final EquationsMapper secondary : expandable.getSecondaryMappers()) {
264                    secondary.insertEquationData(interpolator.getInterpolatedSecondaryState(index), y);
265                    ++index;
266                }
267    
268                // evaluate the derivative
269                computeDerivatives(stepEnd, y, yDot);
270    
271                // update Nordsieck vector
272                final double[] predictedScaled = new double[y0.length];
273                for (int j = 0; j < y0.length; ++j) {
274                    predictedScaled[j] = stepSize * yDot[j];
275                }
276                final Array2DRowRealMatrix nordsieckTmp = updateHighOrderDerivativesPhase1(nordsieck);
277                updateHighOrderDerivativesPhase2(scaled, predictedScaled, nordsieckTmp);
278                interpolator.reinitialize(stepEnd, stepSize, predictedScaled, nordsieckTmp);
279    
280                // discrete events handling
281                interpolator.storeTime(stepEnd);
282                stepStart = acceptStep(interpolator, y, yDot, t);
283                scaled    = predictedScaled;
284                nordsieck = nordsieckTmp;
285                interpolator.reinitialize(stepEnd, stepSize, scaled, nordsieck);
286    
287                if (!isLastStep) {
288    
289                    // prepare next step
290                    interpolator.storeTime(stepStart);
291    
292                    if (resetOccurred) {
293                        // some events handler has triggered changes that
294                        // invalidate the derivatives, we need to restart from scratch
295                        start(stepStart, y, t);
296                        interpolator.reinitialize(stepStart, stepSize, scaled, nordsieck);
297                    }
298    
299                    // stepsize control for next step
300                    final double  factor     = computeStepGrowShrinkFactor(error);
301                    final double  scaledH    = stepSize * factor;
302                    final double  nextT      = stepStart + scaledH;
303                    final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);
304                    hNew = filterStep(scaledH, forward, nextIsLast);
305    
306                    final double  filteredNextT      = stepStart + hNew;
307                    final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t);
308                    if (filteredNextIsLast) {
309                        hNew = t - stepStart;
310                    }
311    
312                    interpolator.rescale(hNew);
313    
314                }
315    
316            } while (!isLastStep);
317    
318            // dispatch results
319            equations.setTime(stepStart);
320            equations.setCompleteState(y);
321    
322            resetInternalState();
323    
324        }
325    
326    }