EmbeddedRungeKuttaIntegrator.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.ode.ExpandableStatefulODE;
  23. import org.apache.commons.math4.core.jdkmath.JdkMath;

  24. /**
  25.  * This class implements the common part of all embedded Runge-Kutta
  26.  * integrators for Ordinary Differential Equations.
  27.  *
  28.  * <p>These methods are embedded explicit Runge-Kutta methods with two
  29.  * sets of coefficients allowing to estimate the error, their Butcher
  30.  * arrays are as follows :
  31.  * <pre>
  32.  *    0  |
  33.  *   c2  | a21
  34.  *   c3  | a31  a32
  35.  *   ... |        ...
  36.  *   cs  | as1  as2  ...  ass-1
  37.  *       |--------------------------
  38.  *       |  b1   b2  ...   bs-1  bs
  39.  *       |  b'1  b'2 ...   b's-1 b's
  40.  * </pre>
  41.  *
  42.  * <p>In fact, we rather use the array defined by ej = bj - b'j to
  43.  * compute directly the error rather than computing two estimates and
  44.  * then comparing them.</p>
  45.  *
  46.  * <p>Some methods are qualified as <i>fsal</i> (first same as last)
  47.  * methods. This means the last evaluation of the derivatives in one
  48.  * step is the same as the first in the next step. Then, this
  49.  * evaluation can be reused from one step to the next one and the cost
  50.  * of such a method is really s-1 evaluations despite the method still
  51.  * has s stages. This behaviour is true only for successful steps, if
  52.  * the step is rejected after the error estimation phase, no
  53.  * evaluation is saved. For an <i>fsal</i> method, we have cs = 1 and
  54.  * asi = bi for all i.</p>
  55.  *
  56.  * @since 1.2
  57.  */

  58. public abstract class EmbeddedRungeKuttaIntegrator
  59.   extends AdaptiveStepsizeIntegrator {

  60.     /** Indicator for <i>fsal</i> methods. */
  61.     private final boolean fsal;

  62.     /** Time steps from Butcher array (without the first zero). */
  63.     private final double[] c;

  64.     /** Internal weights from Butcher array (without the first empty row). */
  65.     private final double[][] a;

  66.     /** External weights for the high order method from Butcher array. */
  67.     private final double[] b;

  68.     /** Prototype of the step interpolator. */
  69.     private final RungeKuttaStepInterpolator prototype;

  70.     /** Stepsize control exponent. */
  71.     private final double exp;

  72.     /** Safety factor for stepsize control. */
  73.     private double safety;

  74.     /** Minimal reduction factor for stepsize control. */
  75.     private double minReduction;

  76.     /** Maximal growth factor for stepsize control. */
  77.     private double maxGrowth;

  78.   /** Build a Runge-Kutta integrator with the given Butcher array.
  79.    * @param name name of the method
  80.    * @param fsal indicate that the method is an <i>fsal</i>
  81.    * @param c time steps from Butcher array (without the first zero)
  82.    * @param a internal weights from Butcher array (without the first empty row)
  83.    * @param b propagation weights for the high order method from Butcher array
  84.    * @param prototype prototype of the step interpolator to use
  85.    * @param minStep minimal step (sign is irrelevant, regardless of
  86.    * integration direction, forward or backward), the last step can
  87.    * be smaller than this
  88.    * @param maxStep maximal step (sign is irrelevant, regardless of
  89.    * integration direction, forward or backward), the last step can
  90.    * be smaller than this
  91.    * @param scalAbsoluteTolerance allowed absolute error
  92.    * @param scalRelativeTolerance allowed relative error
  93.    */
  94.   protected EmbeddedRungeKuttaIntegrator(final String name, final boolean fsal,
  95.                                          final double[] c, final double[][] a, final double[] b,
  96.                                          final RungeKuttaStepInterpolator prototype,
  97.                                          final double minStep, final double maxStep,
  98.                                          final double scalAbsoluteTolerance,
  99.                                          final double scalRelativeTolerance) {

  100.     super(name, minStep, maxStep, scalAbsoluteTolerance, scalRelativeTolerance);

  101.     this.fsal      = fsal;
  102.     this.c         = c;
  103.     this.a         = a;
  104.     this.b         = b;
  105.     this.prototype = prototype;

  106.     exp = -1.0 / getOrder();

  107.     // set the default values of the algorithm control parameters
  108.     setSafety(0.9);
  109.     setMinReduction(0.2);
  110.     setMaxGrowth(10.0);
  111.   }

  112.   /** Build a Runge-Kutta integrator with the given Butcher array.
  113.    * @param name name of the method
  114.    * @param fsal indicate that the method is an <i>fsal</i>
  115.    * @param c time steps from Butcher array (without the first zero)
  116.    * @param a internal weights from Butcher array (without the first empty row)
  117.    * @param b propagation weights for the high order method from Butcher array
  118.    * @param prototype prototype of the step interpolator to use
  119.    * @param minStep minimal step (must be positive even for backward
  120.    * integration), the last step can be smaller than this
  121.    * @param maxStep maximal step (must be positive even for backward
  122.    * integration)
  123.    * @param vecAbsoluteTolerance allowed absolute error
  124.    * @param vecRelativeTolerance allowed relative error
  125.    */
  126.   protected EmbeddedRungeKuttaIntegrator(final String name, final boolean fsal,
  127.                                          final double[] c, final double[][] a, final double[] b,
  128.                                          final RungeKuttaStepInterpolator prototype,
  129.                                          final double   minStep, final double maxStep,
  130.                                          final double[] vecAbsoluteTolerance,
  131.                                          final double[] vecRelativeTolerance) {

  132.     super(name, minStep, maxStep, vecAbsoluteTolerance, vecRelativeTolerance);

  133.     this.fsal      = fsal;
  134.     this.c         = c;
  135.     this.a         = a;
  136.     this.b         = b;
  137.     this.prototype = prototype;

  138.     exp = -1.0 / getOrder();

  139.     // set the default values of the algorithm control parameters
  140.     setSafety(0.9);
  141.     setMinReduction(0.2);
  142.     setMaxGrowth(10.0);
  143.   }

  144.   /** Get the order of the method.
  145.    * @return order of the method
  146.    */
  147.   public abstract int getOrder();

  148.   /** Get the safety factor for stepsize control.
  149.    * @return safety factor
  150.    */
  151.   public double getSafety() {
  152.     return safety;
  153.   }

  154.   /** Set the safety factor for stepsize control.
  155.    * @param safety safety factor
  156.    */
  157.   public void setSafety(final double safety) {
  158.     this.safety = safety;
  159.   }

  160.   /** {@inheritDoc} */
  161.   @Override
  162.   public void integrate(final ExpandableStatefulODE equations, final double t)
  163.       throws NumberIsTooSmallException, DimensionMismatchException,
  164.              MaxCountExceededException, NoBracketingException {

  165.     sanityChecks(equations, t);
  166.     setEquations(equations);
  167.     final boolean forward = t > equations.getTime();

  168.     // create some internal working arrays
  169.     final double[] y0  = equations.getCompleteState();
  170.     final double[] y = y0.clone();
  171.     final int stages = c.length + 1;
  172.     final double[][] yDotK = new double[stages][y.length];
  173.     final double[] yTmp    = y0.clone();
  174.     final double[] yDotTmp = new double[y.length];

  175.     // set up an interpolator sharing the integrator arrays
  176.     final RungeKuttaStepInterpolator interpolator = (RungeKuttaStepInterpolator) prototype.copy();
  177.     interpolator.reinitialize(this, yTmp, yDotK, forward,
  178.                               equations.getPrimaryMapper(), equations.getSecondaryMappers());
  179.     interpolator.storeTime(equations.getTime());

  180.     // set up integration control objects
  181.     stepStart         = equations.getTime();
  182.     double  hNew      = 0;
  183.     boolean firstTime = true;
  184.     initIntegration(equations.getTime(), y0, t);

  185.     // main integration loop
  186.     isLastStep = false;
  187.     do {

  188.       interpolator.shift();

  189.       // iterate over step size, ensuring local normalized error is smaller than 1
  190.       double error = 10;
  191.       while (error >= 1.0) {

  192.         if (firstTime || !fsal) {
  193.           // first stage
  194.           computeDerivatives(stepStart, y, yDotK[0]);
  195.         }

  196.         if (firstTime) {
  197.           final double[] scale = new double[mainSetDimension];
  198.           if (vecAbsoluteTolerance == null) {
  199.               for (int i = 0; i < scale.length; ++i) {
  200.                 scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * JdkMath.abs(y[i]);
  201.               }
  202.           } else {
  203.               for (int i = 0; i < scale.length; ++i) {
  204.                 scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * JdkMath.abs(y[i]);
  205.               }
  206.           }
  207.           hNew = initializeStep(forward, getOrder(), scale,
  208.                                 stepStart, y, yDotK[0], yTmp, yDotK[1]);
  209.           firstTime = false;
  210.         }

  211.         stepSize = hNew;
  212.         if (forward) {
  213.             if (stepStart + stepSize >= t) {
  214.                 stepSize = t - stepStart;
  215.             }
  216.         } else {
  217.             if (stepStart + stepSize <= t) {
  218.                 stepSize = t - stepStart;
  219.             }
  220.         }

  221.         // next stages
  222.         for (int k = 1; k < stages; ++k) {

  223.           for (int j = 0; j < y0.length; ++j) {
  224.             double sum = a[k-1][0] * yDotK[0][j];
  225.             for (int l = 1; l < k; ++l) {
  226.               sum += a[k-1][l] * yDotK[l][j];
  227.             }
  228.             yTmp[j] = y[j] + stepSize * sum;
  229.           }

  230.           computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]);
  231.         }

  232.         // estimate the state at the end of the step
  233.         for (int j = 0; j < y0.length; ++j) {
  234.           double sum    = b[0] * yDotK[0][j];
  235.           for (int l = 1; l < stages; ++l) {
  236.             sum    += b[l] * yDotK[l][j];
  237.           }
  238.           yTmp[j] = y[j] + stepSize * sum;
  239.         }

  240.         // estimate the error at the end of the step
  241.         error = estimateError(yDotK, y, yTmp, stepSize);
  242.         if (error >= 1.0) {
  243.           // reject the step and attempt to reduce error by stepsize control
  244.           final double factor =
  245.               JdkMath.min(maxGrowth,
  246.                            JdkMath.max(minReduction, safety * JdkMath.pow(error, exp)));
  247.           hNew = filterStep(stepSize * factor, forward, false);
  248.         }
  249.       }

  250.       // local error is small enough: accept the step, trigger events and step handlers
  251.       interpolator.storeTime(stepStart + stepSize);
  252.       System.arraycopy(yTmp, 0, y, 0, y0.length);
  253.       System.arraycopy(yDotK[stages - 1], 0, yDotTmp, 0, y0.length);
  254.       stepStart = acceptStep(interpolator, y, yDotTmp, t);
  255.       System.arraycopy(y, 0, yTmp, 0, y.length);

  256.       if (!isLastStep) {

  257.           // prepare next step
  258.           interpolator.storeTime(stepStart);

  259.           if (fsal) {
  260.               // save the last evaluation for the next step
  261.               System.arraycopy(yDotTmp, 0, yDotK[0], 0, y0.length);
  262.           }

  263.           // stepsize control for next step
  264.           final double factor =
  265.               JdkMath.min(maxGrowth, JdkMath.max(minReduction, safety * JdkMath.pow(error, exp)));
  266.           final double  scaledH    = stepSize * factor;
  267.           final double  nextT      = stepStart + scaledH;
  268.           final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);
  269.           hNew = filterStep(scaledH, forward, nextIsLast);

  270.           final double  filteredNextT      = stepStart + hNew;
  271.           final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t);
  272.           if (filteredNextIsLast) {
  273.               hNew = t - stepStart;
  274.           }
  275.       }
  276.     } while (!isLastStep);

  277.     // dispatch results
  278.     equations.setTime(stepStart);
  279.     equations.setCompleteState(y);

  280.     resetInternalState();
  281.   }

  282.   /** Get the minimal reduction factor for stepsize control.
  283.    * @return minimal reduction factor
  284.    */
  285.   public double getMinReduction() {
  286.     return minReduction;
  287.   }

  288.   /** Set the minimal reduction factor for stepsize control.
  289.    * @param minReduction minimal reduction factor
  290.    */
  291.   public void setMinReduction(final double minReduction) {
  292.     this.minReduction = minReduction;
  293.   }

  294.   /** Get the maximal growth factor for stepsize control.
  295.    * @return maximal growth factor
  296.    */
  297.   public double getMaxGrowth() {
  298.     return maxGrowth;
  299.   }

  300.   /** Set the maximal growth factor for stepsize control.
  301.    * @param maxGrowth maximal growth factor
  302.    */
  303.   public void setMaxGrowth(final double maxGrowth) {
  304.     this.maxGrowth = maxGrowth;
  305.   }

  306.   /** Compute the error ratio.
  307.    * @param yDotK derivatives computed during the first stages
  308.    * @param y0 estimate of the step at the start of the step
  309.    * @param y1 estimate of the step at the end of the step
  310.    * @param h  current step
  311.    * @return error ratio, greater than 1 if step should be rejected
  312.    */
  313.   protected abstract double estimateError(double[][] yDotK,
  314.                                           double[] y0, double[] y1,
  315.                                           double h);
  316. }