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