AdamsBashforthIntegrator.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.math4.legacy.ode.nonstiff;

  18. import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
  19. import org.apache.commons.math4.legacy.exception.MaxCountExceededException;
  20. import org.apache.commons.math4.legacy.exception.NoBracketingException;
  21. import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException;
  22. import org.apache.commons.math4.legacy.linear.Array2DRowRealMatrix;
  23. import org.apache.commons.math4.legacy.linear.RealMatrix;
  24. import org.apache.commons.math4.legacy.ode.EquationsMapper;
  25. import org.apache.commons.math4.legacy.ode.ExpandableStatefulODE;
  26. import org.apache.commons.math4.legacy.ode.sampling.NordsieckStepInterpolator;
  27. import org.apache.commons.math4.core.jdkmath.JdkMath;


  28. /**
  29.  * This class implements explicit Adams-Bashforth integrators for Ordinary
  30.  * Differential Equations.
  31.  *
  32.  * <p>Adams-Bashforth methods (in fact due to Adams alone) are explicit
  33.  * multistep ODE solvers. This implementation is a variation of the classical
  34.  * one: it uses adaptive stepsize to implement error control, whereas
  35.  * classical implementations are fixed step size. The value of state vector
  36.  * at step n+1 is a simple combination of the value at step n and of the
  37.  * derivatives at steps n, n-1, n-2 ... Depending on the number k of previous
  38.  * steps one wants to use for computing the next value, different formulas
  39.  * are available:</p>
  40.  * <ul>
  41.  *   <li>k = 1: y<sub>n+1</sub> = y<sub>n</sub> + h y'<sub>n</sub></li>
  42.  *   <li>k = 2: y<sub>n+1</sub> = y<sub>n</sub> + h (3y'<sub>n</sub>-y'<sub>n-1</sub>)/2</li>
  43.  *   <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>
  44.  *   <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>
  45.  *   <li>...</li>
  46.  * </ul>
  47.  *
  48.  * <p>A k-steps Adams-Bashforth method is of order k.</p>
  49.  *
  50.  * <p><b>Implementation details</b></p>
  51.  *
  52.  * <p>We define scaled derivatives s<sub>i</sub>(n) at step n as:
  53.  * <div style="white-space: pre"><code>
  54.  * s<sub>1</sub>(n) = h y'<sub>n</sub> for first derivative
  55.  * s<sub>2</sub>(n) = h<sup>2</sup>/2 y''<sub>n</sub> for second derivative
  56.  * s<sub>3</sub>(n) = h<sup>3</sup>/6 y'''<sub>n</sub> for third derivative
  57.  * ...
  58.  * s<sub>k</sub>(n) = h<sup>k</sup>/k! y<sup>(k)</sup><sub>n</sub> for k<sup>th</sup> derivative
  59.  * </code></div>
  60.  *
  61.  * <p>The definitions above use the classical representation with several previous first
  62.  * derivatives. Lets define
  63.  * <div style="white-space: pre"><code>
  64.  *   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>
  65.  * </code></div>
  66.  * (we omit the k index in the notation for clarity). With these definitions,
  67.  * Adams-Bashforth methods can be written:
  68.  * <ul>
  69.  *   <li>k = 1: y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n)</li>
  70.  *   <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>
  71.  *   <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>
  72.  *   <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>
  73.  *   <li>...</li>
  74.  * </ul>
  75.  *
  76.  * <p>Instead of using the classical representation with first derivatives only (y<sub>n</sub>,
  77.  * s<sub>1</sub>(n) and q<sub>n</sub>), our implementation uses the Nordsieck vector with
  78.  * higher degrees scaled derivatives all taken at the same step (y<sub>n</sub>, s<sub>1</sub>(n)
  79.  * and r<sub>n</sub>) where r<sub>n</sub> is defined as:
  80.  * <div style="white-space: pre"><code>
  81.  * r<sub>n</sub> = [ s<sub>2</sub>(n), s<sub>3</sub>(n) ... s<sub>k</sub>(n) ]<sup>T</sup>
  82.  * </code></div>
  83.  * (here again we omit the k index in the notation for clarity)
  84.  *
  85.  * <p>Taylor series formulas show that for any index offset i, s<sub>1</sub>(n-i) can be
  86.  * computed from s<sub>1</sub>(n), s<sub>2</sub>(n) ... s<sub>k</sub>(n), the formula being exact
  87.  * for degree k polynomials.
  88.  * <div style="white-space: pre"><code>
  89.  * s<sub>1</sub>(n-i) = s<sub>1</sub>(n) + &sum;<sub>j&gt;0</sub> (j+1) (-i)<sup>j</sup> s<sub>j+1</sub>(n)
  90.  * </code></div>
  91.  * The previous formula can be used with several values for i to compute the transform between
  92.  * classical representation and Nordsieck vector. The transform between r<sub>n</sub>
  93.  * and q<sub>n</sub> resulting from the Taylor series formulas above is:
  94.  * <div style="white-space: pre"><code>
  95.  * q<sub>n</sub> = s<sub>1</sub>(n) u + P r<sub>n</sub>
  96.  * </code></div>
  97.  * where u is the [ 1 1 ... 1 ]<sup>T</sup> vector and P is the (k-1)&times;(k-1) matrix built
  98.  * with the (j+1) (-i)<sup>j</sup> terms with i being the row number starting from 1 and j being
  99.  * the column number starting from 1:
  100.  * <pre>
  101.  *        [  -2   3   -4    5  ... ]
  102.  *        [  -4  12  -32   80  ... ]
  103.  *   P =  [  -6  27 -108  405  ... ]
  104.  *        [  -8  48 -256 1280  ... ]
  105.  *        [          ...           ]
  106.  * </pre>
  107.  *
  108.  * <p>Using the Nordsieck vector has several advantages:
  109.  * <ul>
  110.  *   <li>it greatly simplifies step interpolation as the interpolator mainly applies
  111.  *   Taylor series formulas,</li>
  112.  *   <li>it simplifies step changes that occur when discrete events that truncate
  113.  *   the step are triggered,</li>
  114.  *   <li>it allows to extend the methods in order to support adaptive stepsize.</li>
  115.  * </ul>
  116.  *
  117.  * <p>The Nordsieck vector at step n+1 is computed from the Nordsieck vector at step n as follows:
  118.  * <ul>
  119.  *   <li>y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n) + u<sup>T</sup> r<sub>n</sub></li>
  120.  *   <li>s<sub>1</sub>(n+1) = h f(t<sub>n+1</sub>, y<sub>n+1</sub>)</li>
  121.  *   <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>
  122.  * </ul>
  123.  * where A is a rows shifting matrix (the lower left part is an identity matrix):
  124.  * <pre>
  125.  *        [ 0 0   ...  0 0 | 0 ]
  126.  *        [ ---------------+---]
  127.  *        [ 1 0   ...  0 0 | 0 ]
  128.  *    A = [ 0 1   ...  0 0 | 0 ]
  129.  *        [       ...      | 0 ]
  130.  *        [ 0 0   ...  1 0 | 0 ]
  131.  *        [ 0 0   ...  0 1 | 0 ]
  132.  * </pre>
  133.  *
  134.  * <p>The P<sup>-1</sup>u vector and the P<sup>-1</sup> A P matrix do not depend on the state,
  135.  * they only depend on k and therefore are precomputed once for all.</p>
  136.  *
  137.  * @since 2.0
  138.  */
  139. public class AdamsBashforthIntegrator extends AdamsIntegrator {

  140.     /** Integrator method name. */
  141.     private static final String METHOD_NAME = "Adams-Bashforth";

  142.     /**
  143.      * Build an Adams-Bashforth integrator with the given order and step control parameters.
  144.      * @param nSteps number of steps of the method excluding the one being computed
  145.      * @param minStep minimal step (sign is irrelevant, regardless of
  146.      * integration direction, forward or backward), the last step can
  147.      * be smaller than this
  148.      * @param maxStep maximal step (sign is irrelevant, regardless of
  149.      * integration direction, forward or backward), the last step can
  150.      * be smaller than this
  151.      * @param scalAbsoluteTolerance allowed absolute error
  152.      * @param scalRelativeTolerance allowed relative error
  153.      * @exception NumberIsTooSmallException if order is 1 or less
  154.      */
  155.     public AdamsBashforthIntegrator(final int nSteps,
  156.                                     final double minStep, final double maxStep,
  157.                                     final double scalAbsoluteTolerance,
  158.                                     final double scalRelativeTolerance)
  159.         throws NumberIsTooSmallException {
  160.         super(METHOD_NAME, nSteps, nSteps, minStep, maxStep,
  161.               scalAbsoluteTolerance, scalRelativeTolerance);
  162.     }

  163.     /**
  164.      * Build an Adams-Bashforth integrator with the given order and step control parameters.
  165.      * @param nSteps number of steps of the method excluding the one being computed
  166.      * @param minStep minimal step (sign is irrelevant, regardless of
  167.      * integration direction, forward or backward), the last step can
  168.      * be smaller than this
  169.      * @param maxStep maximal step (sign is irrelevant, regardless of
  170.      * integration direction, forward or backward), the last step can
  171.      * be smaller than this
  172.      * @param vecAbsoluteTolerance allowed absolute error
  173.      * @param vecRelativeTolerance allowed relative error
  174.      * @exception IllegalArgumentException if order is 1 or less
  175.      */
  176.     public AdamsBashforthIntegrator(final int nSteps,
  177.                                     final double minStep, final double maxStep,
  178.                                     final double[] vecAbsoluteTolerance,
  179.                                     final double[] vecRelativeTolerance)
  180.         throws IllegalArgumentException {
  181.         super(METHOD_NAME, nSteps, nSteps, minStep, maxStep,
  182.               vecAbsoluteTolerance, vecRelativeTolerance);
  183.     }

  184.     /** Estimate error.
  185.      * <p>
  186.      * Error is estimated by interpolating back to previous state using
  187.      * the state Taylor expansion and comparing to real previous state.
  188.      * </p>
  189.      * @param previousState state vector at step start
  190.      * @param predictedState predicted state vector at step end
  191.      * @param predictedScaled predicted value of the scaled derivatives at step end
  192.      * @param predictedNordsieck predicted value of the Nordsieck vector at step end
  193.      * @return estimated normalized local discretization error
  194.      */
  195.     private double errorEstimation(final double[] previousState,
  196.                                    final double[] predictedState,
  197.                                    final double[] predictedScaled,
  198.                                    final RealMatrix predictedNordsieck) {

  199.         double error = 0;
  200.         for (int i = 0; i < mainSetDimension; ++i) {
  201.             final double yScale = JdkMath.abs(predictedState[i]);
  202.             final double tol = (vecAbsoluteTolerance == null) ?
  203.                                (scalAbsoluteTolerance + scalRelativeTolerance * yScale) :
  204.                                (vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * yScale);

  205.             // apply Taylor formula from high order to low order,
  206.             // for the sake of numerical accuracy
  207.             double variation = 0;
  208.             int sign = (predictedNordsieck.getRowDimension() & 1) == 0 ? -1 : 1;
  209.             for (int k = predictedNordsieck.getRowDimension() - 1; k >= 0; --k) {
  210.                 variation += sign * predictedNordsieck.getEntry(k, i);
  211.                 sign       = -sign;
  212.             }
  213.             variation -= predictedScaled[i];

  214.             final double ratio  = (predictedState[i] - previousState[i] + variation) / tol;
  215.             error              += ratio * ratio;
  216.         }

  217.         return JdkMath.sqrt(error / mainSetDimension);
  218.     }

  219.     /** {@inheritDoc} */
  220.     @Override
  221.     public void integrate(final ExpandableStatefulODE equations, final double t)
  222.         throws NumberIsTooSmallException, DimensionMismatchException,
  223.                MaxCountExceededException, NoBracketingException {

  224.         sanityChecks(equations, t);
  225.         setEquations(equations);
  226.         final boolean forward = t > equations.getTime();

  227.         // initialize working arrays
  228.         final double[] y    = equations.getCompleteState();
  229.         final double[] yDot = new double[y.length];

  230.         // set up an interpolator sharing the integrator arrays
  231.         final NordsieckStepInterpolator interpolator = new NordsieckStepInterpolator();
  232.         interpolator.reinitialize(y, forward,
  233.                                   equations.getPrimaryMapper(), equations.getSecondaryMappers());

  234.         // set up integration control objects
  235.         initIntegration(equations.getTime(), y, t);

  236.         // compute the initial Nordsieck vector using the configured starter integrator
  237.         start(equations.getTime(), y, t);
  238.         interpolator.reinitialize(stepStart, stepSize, scaled, nordsieck);
  239.         interpolator.storeTime(stepStart);

  240.         // reuse the step that was chosen by the starter integrator
  241.         double hNew = stepSize;
  242.         interpolator.rescale(hNew);

  243.         // main integration loop
  244.         isLastStep = false;
  245.         do {

  246.             interpolator.shift();
  247.             final double[] predictedY      = new double[y.length];
  248.             final double[] predictedScaled = new double[y.length];
  249.             Array2DRowRealMatrix predictedNordsieck = null;
  250.             double error = 10;
  251.             while (error >= 1.0) {

  252.                 // predict a first estimate of the state at step end
  253.                 final double stepEnd = stepStart + hNew;
  254.                 interpolator.storeTime(stepEnd);
  255.                 final ExpandableStatefulODE expandable = getExpandable();
  256.                 final EquationsMapper primary = expandable.getPrimaryMapper();
  257.                 primary.insertEquationData(interpolator.getInterpolatedState(), predictedY);
  258.                 int index = 0;
  259.                 for (final EquationsMapper secondary : expandable.getSecondaryMappers()) {
  260.                     secondary.insertEquationData(interpolator.getInterpolatedSecondaryState(index), predictedY);
  261.                     ++index;
  262.                 }

  263.                 // evaluate the derivative
  264.                 computeDerivatives(stepEnd, predictedY, yDot);

  265.                 // predict Nordsieck vector at step end
  266.                 for (int j = 0; j < predictedScaled.length; ++j) {
  267.                     predictedScaled[j] = hNew * yDot[j];
  268.                 }
  269.                 predictedNordsieck = updateHighOrderDerivativesPhase1(nordsieck);
  270.                 updateHighOrderDerivativesPhase2(scaled, predictedScaled, predictedNordsieck);

  271.                 // evaluate error
  272.                 error = errorEstimation(y, predictedY, predictedScaled, predictedNordsieck);

  273.                 if (error >= 1.0) {
  274.                     // reject the step and attempt to reduce error by stepsize control
  275.                     final double factor = computeStepGrowShrinkFactor(error);
  276.                     hNew = filterStep(hNew * factor, forward, false);
  277.                     interpolator.rescale(hNew);
  278.                 }
  279.             }

  280.             stepSize = hNew;
  281.             final double stepEnd = stepStart + stepSize;
  282.             interpolator.reinitialize(stepEnd, stepSize, predictedScaled, predictedNordsieck);

  283.             // discrete events handling
  284.             interpolator.storeTime(stepEnd);
  285.             System.arraycopy(predictedY, 0, y, 0, y.length);
  286.             stepStart = acceptStep(interpolator, y, yDot, t);
  287.             scaled    = predictedScaled;
  288.             nordsieck = predictedNordsieck;
  289.             interpolator.reinitialize(stepEnd, stepSize, scaled, nordsieck);

  290.             if (!isLastStep) {

  291.                 // prepare next step
  292.                 interpolator.storeTime(stepStart);

  293.                 if (resetOccurred) {
  294.                     // some events handler has triggered changes that
  295.                     // invalidate the derivatives, we need to restart from scratch
  296.                     start(stepStart, y, t);
  297.                     interpolator.reinitialize(stepStart, stepSize, scaled, nordsieck);
  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.                 final double  filteredNextT      = stepStart + hNew;
  306.                 final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t);
  307.                 if (filteredNextIsLast) {
  308.                     hNew = t - stepStart;
  309.                 }

  310.                 interpolator.rescale(hNew);
  311.             }
  312.         } while (!isLastStep);

  313.         // dispatch results
  314.         equations.setTime(stepStart);
  315.         equations.setCompleteState(y);

  316.         resetInternalState();
  317.     }
  318. }