EmbeddedRungeKuttaIntegrator.java

  1. /*
  2.  * Licensed to the Hipparchus project 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 Hipparchus project 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.  *      https://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.hipparchus.ode.nonstiff;

  18. import org.hipparchus.exception.MathIllegalArgumentException;
  19. import org.hipparchus.exception.MathIllegalStateException;
  20. import org.hipparchus.ode.EquationsMapper;
  21. import org.hipparchus.ode.ExpandableODE;
  22. import org.hipparchus.ode.LocalizedODEFormats;
  23. import org.hipparchus.ode.ODEState;
  24. import org.hipparchus.ode.ODEStateAndDerivative;
  25. import org.hipparchus.ode.nonstiff.interpolators.RungeKuttaStateInterpolator;
  26. import org.hipparchus.util.FastMath;

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

  60. public abstract class EmbeddedRungeKuttaIntegrator
  61.     extends AdaptiveStepsizeIntegrator
  62.     implements ExplicitRungeKuttaIntegrator {

  63.     /** Index of the pre-computed derivative for <i>fsal</i> methods. */
  64.     private final int fsal;

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

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

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

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

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

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

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

  79.     /** Build a Runge-Kutta integrator with the given Butcher array.
  80.      * @param name name of the method
  81.      * @param fsal index of the pre-computed derivative for <i>fsal</i> methods
  82.      * or -1 if method is not <i>fsal</i>
  83.      * @param minStep minimal step (sign is irrelevant, regardless of
  84.      * integration direction, forward or backward), the last step can
  85.      * be smaller than this
  86.      * @param maxStep maximal step (sign is irrelevant, regardless of
  87.      * integration direction, forward or backward), the last step can
  88.      * be smaller than this
  89.      * @param scalAbsoluteTolerance allowed absolute error
  90.      * @param scalRelativeTolerance allowed relative error
  91.      */
  92.     protected EmbeddedRungeKuttaIntegrator(final String name, final int fsal,
  93.                                            final double minStep, final double maxStep,
  94.                                            final double scalAbsoluteTolerance,
  95.                                            final double scalRelativeTolerance) {

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

  97.         this.fsal = fsal;
  98.         this.c    = getC();
  99.         this.a    = getA();
  100.         this.b    = getB();

  101.         exp = -1.0 / getOrder();

  102.         // set the default values of the algorithm control parameters
  103.         setSafety(0.9);
  104.         setMinReduction(0.2);
  105.         setMaxGrowth(10.0);

  106.     }

  107.     /** Build a Runge-Kutta integrator with the given Butcher array.
  108.      * @param name name of the method
  109.      * @param fsal index of the pre-computed derivative for <i>fsal</i> methods
  110.      * or -1 if method is not <i>fsal</i>
  111.      * @param minStep minimal step (must be positive even for backward
  112.      * integration), the last step can be smaller than this
  113.      * @param maxStep maximal step (must be positive even for backward
  114.      * integration)
  115.      * @param vecAbsoluteTolerance allowed absolute error
  116.      * @param vecRelativeTolerance allowed relative error
  117.      */
  118.     protected EmbeddedRungeKuttaIntegrator(final String name, final int fsal,
  119.                                            final double   minStep, final double maxStep,
  120.                                            final double[] vecAbsoluteTolerance,
  121.                                            final double[] vecRelativeTolerance) {

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

  123.         this.fsal = fsal;
  124.         this.c    = getC();
  125.         this.a    = getA();
  126.         this.b    = getB();

  127.         exp = -1.0 / getOrder();

  128.         // set the default values of the algorithm control parameters
  129.         setSafety(0.9);
  130.         setMinReduction(0.2);
  131.         setMaxGrowth(10.0);

  132.     }

  133.     /** Create an interpolator.
  134.      * @param forward integration direction indicator
  135.      * @param yDotK slopes at the intermediate points
  136.      * @param globalPreviousState start of the global step
  137.      * @param globalCurrentState end of the global step
  138.      * @param mapper equations mapper for the all equations
  139.      * @return external weights for the high order method from Butcher array
  140.      */
  141.     protected abstract RungeKuttaStateInterpolator createInterpolator(boolean forward, double[][] yDotK,
  142.                                                                       ODEStateAndDerivative globalPreviousState,
  143.                                                                       ODEStateAndDerivative globalCurrentState,
  144.                                                                       EquationsMapper mapper);
  145.     /** Get the order of the method.
  146.      * @return order of the method
  147.      */
  148.     public abstract int getOrder();

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

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

  161.     /** {@inheritDoc} */
  162.     @Override
  163.     public ODEStateAndDerivative integrate(final ExpandableODE equations,
  164.                                            final ODEState initialState, final double finalTime)
  165.         throws MathIllegalArgumentException, MathIllegalStateException {

  166.         sanityChecks(initialState, finalTime);
  167.         setStepStart(initIntegration(equations, initialState, finalTime));
  168.         final boolean forward = finalTime > initialState.getTime();

  169.         // create some internal working arrays
  170.         final int        stages  = c.length + 1;
  171.         final double[][] yDotK   = new double[stages][];
  172.         double[]   yTmp    = new double[equations.getMapper().getTotalDimension()];

  173.         // set up integration control objects
  174.         double  hNew      = 0;
  175.         boolean firstTime = true;

  176.         // main integration loop
  177.         setIsLastStep(false);
  178.         do {

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

  182.                 // first stage
  183.                 final double[] y = getStepStart().getCompleteState();
  184.                 yDotK[0] = getStepStart().getCompleteDerivative();

  185.                 if (firstTime) {
  186.                     final StepsizeHelper helper = getStepSizeHelper();
  187.                     final double[] scale = new double[helper.getMainSetDimension()];
  188.                     for (int i = 0; i < scale.length; ++i) {
  189.                         scale[i] = helper.getTolerance(i, FastMath.abs(y[i]));
  190.                     }
  191.                     hNew = initializeStep(forward, getOrder(), scale, getStepStart());
  192.                     firstTime = false;
  193.                 }

  194.                 setStepSize(hNew);
  195.                 if (forward) {
  196.                     if (getStepStart().getTime() + getStepSize() >= finalTime) {
  197.                         setStepSize(finalTime - getStepStart().getTime());
  198.                     }
  199.                 } else {
  200.                     if (getStepStart().getTime() + getStepSize() <= finalTime) {
  201.                         setStepSize(finalTime - getStepStart().getTime());
  202.                     }
  203.                 }

  204.                 // next stages
  205.                 ExplicitRungeKuttaIntegrator.applyInternalButcherWeights(getEquations(), getStepStart().getTime(), y,
  206.                         getStepSize(), a, c, yDotK);
  207.                 yTmp = ExplicitRungeKuttaIntegrator.applyExternalButcherWeights(y, yDotK, getStepSize(), b);

  208.                 incrementEvaluations(stages - 1);

  209.                 // estimate the error at the end of the step
  210.                 error = estimateError(yDotK, y, yTmp, getStepSize());
  211.                 if (Double.isNaN(error)) {
  212.                     throw new MathIllegalStateException(LocalizedODEFormats.NAN_APPEARING_DURING_INTEGRATION,
  213.                                                         getStepStart().getTime() + getStepSize());
  214.                 }
  215.                 if (error >= 1.0) {
  216.                     // reject the step and attempt to reduce error by stepsize control
  217.                     final double factor =
  218.                                     FastMath.min(maxGrowth,
  219.                                                  FastMath.max(minReduction, safety * FastMath.pow(error, exp)));
  220.                     hNew = getStepSizeHelper().filterStep(getStepSize() * factor, forward, false);
  221.                 }

  222.             }
  223.             final double   stepEnd = getStepStart().getTime() + getStepSize();
  224.             final double[] yDotTmp = (fsal >= 0) ? yDotK[fsal] : computeDerivatives(stepEnd, yTmp);
  225.             final ODEStateAndDerivative stateTmp = equations.getMapper().mapStateAndDerivative(stepEnd, yTmp, yDotTmp);

  226.             // local error is small enough: accept the step, trigger events and step handlers
  227.             setStepStart(acceptStep(createInterpolator(forward, yDotK, getStepStart(), stateTmp, equations.getMapper()), finalTime));

  228.             if (!isLastStep()) {

  229.                 // stepsize control for next step
  230.                 final double factor =
  231.                                 FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.pow(error, exp)));
  232.                 final double  scaledH    = getStepSize() * factor;
  233.                 final double  nextT      = getStepStart().getTime() + scaledH;
  234.                 final boolean nextIsLast = forward ? (nextT >= finalTime) : (nextT <= finalTime);
  235.                 hNew = getStepSizeHelper().filterStep(scaledH, forward, nextIsLast);

  236.                 final double  filteredNextT      = getStepStart().getTime() + hNew;
  237.                 final boolean filteredNextIsLast = forward ? (filteredNextT >= finalTime) : (filteredNextT <= finalTime);
  238.                 if (filteredNextIsLast) {
  239.                     hNew = finalTime - getStepStart().getTime();
  240.                 }

  241.             }

  242.         } while (!isLastStep());

  243.         final ODEStateAndDerivative finalState = getStepStart();
  244.         resetInternalState();
  245.         return finalState;

  246.     }

  247.     /** Get the minimal reduction factor for stepsize control.
  248.      * @return minimal reduction factor
  249.      */
  250.     public double getMinReduction() {
  251.         return minReduction;
  252.     }

  253.     /** Set the minimal reduction factor for stepsize control.
  254.      * @param minReduction minimal reduction factor
  255.      */
  256.     public void setMinReduction(final double minReduction) {
  257.         this.minReduction = minReduction;
  258.     }

  259.     /** Get the maximal growth factor for stepsize control.
  260.      * @return maximal growth factor
  261.      */
  262.     public double getMaxGrowth() {
  263.         return maxGrowth;
  264.     }

  265.     /** Set the maximal growth factor for stepsize control.
  266.      * @param maxGrowth maximal growth factor
  267.      */
  268.     public void setMaxGrowth(final double maxGrowth) {
  269.         this.maxGrowth = maxGrowth;
  270.     }

  271.     /** Compute the error ratio.
  272.      * @param yDotK derivatives computed during the first stages
  273.      * @param y0 estimate of the step at the start of the step
  274.      * @param y1 estimate of the step at the end of the step
  275.      * @param h  current step
  276.      * @return error ratio, greater than 1 if step should be rejected
  277.      */
  278.     protected abstract double estimateError(double[][] yDotK,
  279.                                             double[] y0, double[] y1,
  280.                                             double h);

  281. }