AdamsMoultonIntegrator.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 java.util.Arrays;

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


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

  154.     /** Integrator method name. */
  155.     private static final String METHOD_NAME = "Adams-Moulton";

  156.     /**
  157.      * Build an Adams-Moulton integrator with the given order and error control parameters.
  158.      * @param nSteps number of steps of the method excluding the one being computed
  159.      * @param minStep minimal step (sign is irrelevant, regardless of
  160.      * integration direction, forward or backward), the last step can
  161.      * be smaller than this
  162.      * @param maxStep maximal step (sign is irrelevant, regardless of
  163.      * integration direction, forward or backward), the last step can
  164.      * be smaller than this
  165.      * @param scalAbsoluteTolerance allowed absolute error
  166.      * @param scalRelativeTolerance allowed relative error
  167.      * @exception NumberIsTooSmallException if order is 1 or less
  168.      */
  169.     public AdamsMoultonIntegrator(final int nSteps,
  170.                                   final double minStep, final double maxStep,
  171.                                   final double scalAbsoluteTolerance,
  172.                                   final double scalRelativeTolerance)
  173.         throws NumberIsTooSmallException {
  174.         super(METHOD_NAME, nSteps, nSteps + 1, minStep, maxStep,
  175.               scalAbsoluteTolerance, scalRelativeTolerance);
  176.     }

  177.     /**
  178.      * Build an Adams-Moulton integrator with the given order and error control parameters.
  179.      * @param nSteps number of steps of the method excluding the one being computed
  180.      * @param minStep minimal step (sign is irrelevant, regardless of
  181.      * integration direction, forward or backward), the last step can
  182.      * be smaller than this
  183.      * @param maxStep maximal step (sign is irrelevant, regardless of
  184.      * integration direction, forward or backward), the last step can
  185.      * be smaller than this
  186.      * @param vecAbsoluteTolerance allowed absolute error
  187.      * @param vecRelativeTolerance allowed relative error
  188.      * @exception IllegalArgumentException if order is 1 or less
  189.      */
  190.     public AdamsMoultonIntegrator(final int nSteps,
  191.                                   final double minStep, final double maxStep,
  192.                                   final double[] vecAbsoluteTolerance,
  193.                                   final double[] vecRelativeTolerance)
  194.         throws IllegalArgumentException {
  195.         super(METHOD_NAME, nSteps, nSteps + 1, minStep, maxStep,
  196.               vecAbsoluteTolerance, vecRelativeTolerance);
  197.     }

  198.     /** {@inheritDoc} */
  199.     @Override
  200.     public void integrate(final ExpandableStatefulODE equations,final double t)
  201.         throws NumberIsTooSmallException, DimensionMismatchException,
  202.                MaxCountExceededException, NoBracketingException {

  203.         sanityChecks(equations, t);
  204.         setEquations(equations);
  205.         final boolean forward = t > equations.getTime();

  206.         // initialize working arrays
  207.         final double[] y0   = equations.getCompleteState();
  208.         final double[] y    = y0.clone();
  209.         final double[] yDot = new double[y.length];
  210.         final double[] yTmp = new double[y.length];
  211.         final double[] predictedScaled = new double[y.length];
  212.         Array2DRowRealMatrix nordsieckTmp = null;

  213.         // set up two interpolators sharing the integrator arrays
  214.         final NordsieckStepInterpolator interpolator = new NordsieckStepInterpolator();
  215.         interpolator.reinitialize(y, forward,
  216.                                   equations.getPrimaryMapper(), equations.getSecondaryMappers());

  217.         // set up integration control objects
  218.         initIntegration(equations.getTime(), y0, t);

  219.         // compute the initial Nordsieck vector using the configured starter integrator
  220.         start(equations.getTime(), y, t);
  221.         interpolator.reinitialize(stepStart, stepSize, scaled, nordsieck);
  222.         interpolator.storeTime(stepStart);

  223.         double hNew = stepSize;
  224.         interpolator.rescale(hNew);

  225.         isLastStep = false;
  226.         do {

  227.             double error = 10;
  228.             while (error >= 1.0) {

  229.                 stepSize = hNew;

  230.                 // predict a first estimate of the state at step end (P in the PECE sequence)
  231.                 final double stepEnd = stepStart + stepSize;
  232.                 interpolator.setInterpolatedTime(stepEnd);
  233.                 final ExpandableStatefulODE expandable = getExpandable();
  234.                 final EquationsMapper primary = expandable.getPrimaryMapper();
  235.                 primary.insertEquationData(interpolator.getInterpolatedState(), yTmp);
  236.                 int index = 0;
  237.                 for (final EquationsMapper secondary : expandable.getSecondaryMappers()) {
  238.                     secondary.insertEquationData(interpolator.getInterpolatedSecondaryState(index), yTmp);
  239.                     ++index;
  240.                 }

  241.                 // evaluate a first estimate of the derivative (first E in the PECE sequence)
  242.                 computeDerivatives(stepEnd, yTmp, yDot);

  243.                 // update Nordsieck vector
  244.                 for (int j = 0; j < y0.length; ++j) {
  245.                     predictedScaled[j] = stepSize * yDot[j];
  246.                 }
  247.                 nordsieckTmp = updateHighOrderDerivativesPhase1(nordsieck);
  248.                 updateHighOrderDerivativesPhase2(scaled, predictedScaled, nordsieckTmp);

  249.                 // apply correction (C in the PECE sequence)
  250.                 error = nordsieckTmp.walkInOptimizedOrder(new Corrector(y, predictedScaled, yTmp));

  251.                 if (error >= 1.0) {
  252.                     // reject the step and attempt to reduce error by stepsize control
  253.                     final double factor = computeStepGrowShrinkFactor(error);
  254.                     hNew = filterStep(stepSize * factor, forward, false);
  255.                     interpolator.rescale(hNew);
  256.                 }
  257.             }

  258.             // evaluate a final estimate of the derivative (second E in the PECE sequence)
  259.             final double stepEnd = stepStart + stepSize;
  260.             computeDerivatives(stepEnd, yTmp, yDot);

  261.             // update Nordsieck vector
  262.             final double[] correctedScaled = new double[y0.length];
  263.             for (int j = 0; j < y0.length; ++j) {
  264.                 correctedScaled[j] = stepSize * yDot[j];
  265.             }
  266.             updateHighOrderDerivativesPhase2(predictedScaled, correctedScaled, nordsieckTmp);

  267.             // discrete events handling
  268.             System.arraycopy(yTmp, 0, y, 0, y.length);
  269.             interpolator.reinitialize(stepEnd, stepSize, correctedScaled, nordsieckTmp);
  270.             interpolator.storeTime(stepStart);
  271.             interpolator.shift();
  272.             interpolator.storeTime(stepEnd);
  273.             stepStart = acceptStep(interpolator, y, yDot, t);
  274.             scaled    = correctedScaled;
  275.             nordsieck = nordsieckTmp;

  276.             if (!isLastStep) {

  277.                 // prepare next step
  278.                 interpolator.storeTime(stepStart);

  279.                 if (resetOccurred) {
  280.                     // some events handler has triggered changes that
  281.                     // invalidate the derivatives, we need to restart from scratch
  282.                     start(stepStart, y, t);
  283.                     interpolator.reinitialize(stepStart, stepSize, scaled, nordsieck);
  284.                 }

  285.                 // stepsize control for next step
  286.                 final double  factor     = computeStepGrowShrinkFactor(error);
  287.                 final double  scaledH    = stepSize * factor;
  288.                 final double  nextT      = stepStart + scaledH;
  289.                 final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);
  290.                 hNew = filterStep(scaledH, forward, nextIsLast);

  291.                 final double  filteredNextT      = stepStart + hNew;
  292.                 final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t);
  293.                 if (filteredNextIsLast) {
  294.                     hNew = t - stepStart;
  295.                 }

  296.                 interpolator.rescale(hNew);
  297.             }
  298.         } while (!isLastStep);

  299.         // dispatch results
  300.         equations.setTime(stepStart);
  301.         equations.setCompleteState(y);

  302.         resetInternalState();
  303.     }

  304.     /** Corrector for current state in Adams-Moulton method.
  305.      * <p>
  306.      * This visitor implements the Taylor series formula:
  307.      * <pre>
  308.      * Y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n+1) + [ -1 +1 -1 +1 ... &plusmn;1 ] r<sub>n+1</sub>
  309.      * </pre>
  310.      * </p>
  311.      */
  312.     private final class Corrector implements RealMatrixPreservingVisitor {

  313.         /** Previous state. */
  314.         private final double[] previous;

  315.         /** Current scaled first derivative. */
  316.         private final double[] scaled;

  317.         /** Current state before correction. */
  318.         private final double[] before;

  319.         /** Current state after correction. */
  320.         private final double[] after;

  321.         /** Simple constructor.
  322.          * @param previous previous state
  323.          * @param scaled current scaled first derivative
  324.          * @param state state to correct (will be overwritten after visit)
  325.          */
  326.         Corrector(final double[] previous, final double[] scaled, final double[] state) {
  327.             this.previous = previous;
  328.             this.scaled   = scaled;
  329.             this.after    = state;
  330.             this.before   = state.clone();
  331.         }

  332.         /** {@inheritDoc} */
  333.         @Override
  334.         public void start(int rows, int columns,
  335.                           int startRow, int endRow, int startColumn, int endColumn) {
  336.             Arrays.fill(after, 0.0);
  337.         }

  338.         /** {@inheritDoc} */
  339.         @Override
  340.         public void visit(int row, int column, double value) {
  341.             if ((row & 0x1) == 0) {
  342.                 after[column] -= value;
  343.             } else {
  344.                 after[column] += value;
  345.             }
  346.         }

  347.         /**
  348.          * End visiting the Nordsieck vector.
  349.          * <p>The correction is used to control stepsize. So its amplitude is
  350.          * considered to be an error, which must be normalized according to
  351.          * error control settings. If the normalized value is greater than 1,
  352.          * the correction was too large and the step must be rejected.</p>
  353.          * @return the normalized correction, if greater than 1, the step
  354.          * must be rejected
  355.          */
  356.         @Override
  357.         public double end() {

  358.             double error = 0;
  359.             for (int i = 0; i < after.length; ++i) {
  360.                 after[i] += previous[i] + scaled[i];
  361.                 if (i < mainSetDimension) {
  362.                     final double yScale = JdkMath.max(JdkMath.abs(previous[i]), JdkMath.abs(after[i]));
  363.                     final double tol    = (vecAbsoluteTolerance == null) ?
  364.                                           (scalAbsoluteTolerance + scalRelativeTolerance * yScale) :
  365.                                           (vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * yScale);
  366.                     final double ratio  = (after[i] - before[i]) / tol; // (corrected-predicted)/tol
  367.                     error += ratio * ratio;
  368.                 }
  369.             }

  370.             return JdkMath.sqrt(error / mainSetDimension);
  371.         }
  372.     }
  373. }