EmbeddedRungeKuttaFieldIntegrator.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.  *      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. /*
  18.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */

  21. package org.hipparchus.ode.nonstiff;

  22. import org.hipparchus.CalculusFieldElement;
  23. import org.hipparchus.Field;
  24. import org.hipparchus.exception.MathIllegalArgumentException;
  25. import org.hipparchus.exception.MathIllegalStateException;
  26. import org.hipparchus.ode.FieldEquationsMapper;
  27. import org.hipparchus.ode.FieldExpandableODE;
  28. import org.hipparchus.ode.FieldODEState;
  29. import org.hipparchus.ode.FieldODEStateAndDerivative;
  30. import org.hipparchus.ode.nonstiff.interpolators.RungeKuttaFieldStateInterpolator;
  31. import org.hipparchus.util.FastMath;
  32. import org.hipparchus.util.MathArrays;
  33. import org.hipparchus.util.MathUtils;

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

  68. public abstract class EmbeddedRungeKuttaFieldIntegrator<T extends CalculusFieldElement<T>>
  69.     extends AdaptiveStepsizeFieldIntegrator<T>
  70.     implements FieldExplicitRungeKuttaIntegrator<T> {

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

  73.     /** Time steps from Butcher array (without the first zero). */
  74.     private final T[] c;

  75.     /** Internal weights from Butcher array (without the first empty row). */
  76.     private final T[][] a;

  77.     /** External weights for the high order method from Butcher array. */
  78.     private final T[] b;

  79.     /** Time steps from Butcher array (without the first zero). */
  80.     private double[] realC = new double[0];

  81.     /** Internal weights from Butcher array (without the first empty row). Real version, optional. */
  82.     private double[][] realA = new double[0][];

  83.     /** External weights for the high order method from Butcher array. Real version, optional. */
  84.     private double[] realB = new double[0];

  85.     /** Stepsize control exponent. */
  86.     private final double exp;

  87.     /** Safety factor for stepsize control. */
  88.     private T safety;

  89.     /** Minimal reduction factor for stepsize control. */
  90.     private T minReduction;

  91.     /** Maximal growth factor for stepsize control. */
  92.     private T maxGrowth;

  93.     /** Flag setting whether coefficients in Butcher array are interpreted as Field or real numbers. */
  94.     private boolean usingFieldCoefficients;

  95.     /** Build a Runge-Kutta integrator with the given Butcher array.
  96.      * @param field field to which the time and state vector elements belong
  97.      * @param name name of the method
  98.      * @param fsal index of the pre-computed derivative for <i>fsal</i> methods
  99.      * or -1 if method is not <i>fsal</i>
  100.      * @param minStep minimal step (sign is irrelevant, regardless of
  101.      * integration direction, forward or backward), the last step can
  102.      * be smaller than this
  103.      * @param maxStep maximal step (sign is irrelevant, regardless of
  104.      * integration direction, forward or backward), the last step can
  105.      * be smaller than this
  106.      * @param scalAbsoluteTolerance allowed absolute error
  107.      * @param scalRelativeTolerance allowed relative error
  108.      */
  109.     protected EmbeddedRungeKuttaFieldIntegrator(final Field<T> field, final String name, final int fsal,
  110.                                                 final double minStep, final double maxStep,
  111.                                                 final double scalAbsoluteTolerance,
  112.                                                 final double scalRelativeTolerance) {

  113.         super(field, name, minStep, maxStep, scalAbsoluteTolerance, scalRelativeTolerance);

  114.         this.fsal = fsal;
  115.         this.c    = getC();
  116.         this.a    = getA();
  117.         this.b    = getB();

  118.         exp = -1.0 / getOrder();

  119.         // set the default values of the algorithm control parameters
  120.         setSafety(field.getZero().add(0.9));
  121.         setMinReduction(field.getZero().add(0.2));
  122.         setMaxGrowth(field.getZero().add(10.0));

  123.     }

  124.     /** Build a Runge-Kutta integrator with the given Butcher array.
  125.      * @param field field to which the time and state vector elements belong
  126.      * @param name name of the method
  127.      * @param fsal index of the pre-computed derivative for <i>fsal</i> methods
  128.      * or -1 if method is not <i>fsal</i>
  129.      * @param minStep minimal step (must be positive even for backward
  130.      * integration), the last step can be smaller than this
  131.      * @param maxStep maximal step (must be positive even for backward
  132.      * integration)
  133.      * @param vecAbsoluteTolerance allowed absolute error
  134.      * @param vecRelativeTolerance allowed relative error
  135.      */
  136.     protected EmbeddedRungeKuttaFieldIntegrator(final Field<T> field, final String name, final int fsal,
  137.                                                 final double   minStep, final double maxStep,
  138.                                                 final double[] vecAbsoluteTolerance,
  139.                                                 final double[] vecRelativeTolerance) {

  140.         super(field, name, minStep, maxStep, vecAbsoluteTolerance, vecRelativeTolerance);
  141.         this.usingFieldCoefficients = false;

  142.         this.fsal = fsal;
  143.         this.c    = getC();
  144.         this.a    = getA();
  145.         this.b    = getB();

  146.         exp = -1.0 / getOrder();

  147.         // set the default values of the algorithm control parameters
  148.         setSafety(field.getZero().add(0.9));
  149.         setMinReduction(field.getZero().add(0.2));
  150.         setMaxGrowth(field.getZero().add(10.0));

  151.     }

  152.     /** Create an interpolator.
  153.      * @param forward integration direction indicator
  154.      * @param yDotK slopes at the intermediate points
  155.      * @param globalPreviousState start of the global step
  156.      * @param globalCurrentState end of the global step
  157.      * @param mapper equations mapper for the all equations
  158.      * @return external weights for the high order method from Butcher array
  159.      */
  160.     protected abstract RungeKuttaFieldStateInterpolator<T> createInterpolator(boolean forward, T[][] yDotK,
  161.                                                                               FieldODEStateAndDerivative<T> globalPreviousState,
  162.                                                                               FieldODEStateAndDerivative<T> globalCurrentState,
  163.                                                                               FieldEquationsMapper<T> mapper);

  164.     /** Get the order of the method.
  165.      * @return order of the method
  166.      */
  167.     public abstract int getOrder();

  168.     /** Get the safety factor for stepsize control.
  169.      * @return safety factor
  170.      */
  171.     public T getSafety() {
  172.         return safety;
  173.     }

  174.     /** Set the safety factor for stepsize control.
  175.      * @param safety safety factor
  176.      */
  177.     public void setSafety(final T safety) {
  178.         this.safety = safety;
  179.     }

  180.     /**
  181.      * Setter for the flag between real or Field coefficients in the Butcher array.
  182.      *
  183.      * @param usingFieldCoefficients new value for flag
  184.      */
  185.     public void setUsingFieldCoefficients(boolean usingFieldCoefficients) {
  186.         this.usingFieldCoefficients = usingFieldCoefficients;
  187.     }

  188.     /** {@inheritDoc} */
  189.     @Override
  190.     public boolean isUsingFieldCoefficients() {
  191.         return usingFieldCoefficients;
  192.     }

  193.     /** {@inheritDoc} */
  194.     @Override
  195.     public int getNumberOfStages() {
  196.         return b.length;
  197.     }

  198.     /** {@inheritDoc} */
  199.     @Override
  200.     protected FieldODEStateAndDerivative<T> initIntegration(FieldExpandableODE<T> eqn, FieldODEState<T> s0, T t) {
  201.         if (!isUsingFieldCoefficients()) {
  202.             realA = getRealA();
  203.             realB = getRealB();
  204.             realC = getRealC();
  205.         }
  206.         return super.initIntegration(eqn, s0, t);
  207.     }

  208.     /** {@inheritDoc} */
  209.     @Override
  210.     public FieldODEStateAndDerivative<T> integrate(final FieldExpandableODE<T> equations,
  211.                                                    final FieldODEState<T> initialState, final T finalTime)
  212.         throws MathIllegalArgumentException, MathIllegalStateException {

  213.         sanityChecks(initialState, finalTime);
  214.         setStepStart(initIntegration(equations, initialState, finalTime));
  215.         final boolean forward = finalTime.subtract(initialState.getTime()).getReal() > 0;

  216.         // create some internal working arrays
  217.         final int   stages = getNumberOfStages();
  218.         final T[][] yDotK  = MathArrays.buildArray(getField(), stages, -1);
  219.         T[]   yTmp   = MathArrays.buildArray(getField(), equations.getMapper().getTotalDimension());

  220.         // set up integration control objects
  221.         T  hNew           = getField().getZero();
  222.         boolean firstTime = true;

  223.         // main integration loop
  224.         setIsLastStep(false);
  225.         do {

  226.             // iterate over step size, ensuring local normalized error is smaller than 1
  227.             double error = 10.0;
  228.             while (error >= 1.0) {

  229.                 // first stage
  230.                 final T[] y = getStepStart().getCompleteState();
  231.                 yDotK[0] = getStepStart().getCompleteDerivative();

  232.                 if (firstTime) {
  233.                     final StepsizeHelper helper = getStepSizeHelper();
  234.                     final T[] scale = MathArrays.buildArray(getField(), helper.getMainSetDimension());
  235.                     for (int i = 0; i < scale.length; ++i) {
  236.                         scale[i] = helper.getTolerance(i, y[i].abs());
  237.                     }
  238.                     hNew = getField().getZero().add(initializeStep(forward, getOrder(), scale, getStepStart()));
  239.                     firstTime = false;
  240.                 }

  241.                 setStepSize(hNew);
  242.                 if (forward) {
  243.                     if (getStepStart().getTime().add(getStepSize()).subtract(finalTime).getReal() >= 0) {
  244.                         setStepSize(finalTime.subtract(getStepStart().getTime()));
  245.                     }
  246.                 } else {
  247.                     if (getStepStart().getTime().add(getStepSize()).subtract(finalTime).getReal() <= 0) {
  248.                         setStepSize(finalTime.subtract(getStepStart().getTime()));
  249.                     }
  250.                 }

  251.                 // next stages
  252.                 if (isUsingFieldCoefficients()) {
  253.                     FieldExplicitRungeKuttaIntegrator.applyInternalButcherWeights(getEquations(),
  254.                             getStepStart().getTime(), y, getStepSize(), a, c, yDotK);
  255.                     yTmp = FieldExplicitRungeKuttaIntegrator.applyExternalButcherWeights(y, yDotK, getStepSize(), b);
  256.                 } else {
  257.                     FieldExplicitRungeKuttaIntegrator.applyInternalButcherWeights(getEquations(),
  258.                             getStepStart().getTime(), y, getStepSize(), realA, realC, yDotK);
  259.                     yTmp = FieldExplicitRungeKuttaIntegrator.applyExternalButcherWeights(y, yDotK, getStepSize(), realB);
  260.                 }

  261.                 incrementEvaluations(stages - 1);

  262.                 // estimate the error at the end of the step
  263.                 error = estimateError(yDotK, y, yTmp, getStepSize());
  264.                 if (error >= 1.0) {
  265.                     // reject the step and attempt to reduce error by stepsize control
  266.                     final T factor = MathUtils.min(maxGrowth,
  267.                                                    MathUtils.max(minReduction, safety.multiply(FastMath.pow(error, exp))));
  268.                     hNew = getStepSizeHelper().filterStep(getStepSize().multiply(factor), forward, false);
  269.                 }

  270.             }
  271.             final T   stepEnd = getStepStart().getTime().add(getStepSize());
  272.             final T[] yDotTmp = (fsal >= 0) ? yDotK[fsal] : computeDerivatives(stepEnd, yTmp);
  273.             final FieldODEStateAndDerivative<T> stateTmp = equations.getMapper().mapStateAndDerivative(stepEnd, yTmp, yDotTmp);

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

  277.             if (!isLastStep()) {

  278.                 // stepsize control for next step
  279.                 final T factor = MathUtils.min(maxGrowth,
  280.                                                MathUtils.max(minReduction, safety.multiply(FastMath.pow(error, exp))));
  281.                 final T  scaledH    = getStepSize().multiply(factor);
  282.                 final T  nextT      = getStepStart().getTime().add(scaledH);
  283.                 final boolean nextIsLast = forward ?
  284.                                            nextT.subtract(finalTime).getReal() >= 0 :
  285.                                            nextT.subtract(finalTime).getReal() <= 0;
  286.                 hNew = getStepSizeHelper().filterStep(scaledH, forward, nextIsLast);

  287.                 final T  filteredNextT      = getStepStart().getTime().add(hNew);
  288.                 final boolean filteredNextIsLast = forward ?
  289.                                                    filteredNextT.subtract(finalTime).getReal() >= 0 :
  290.                                                    filteredNextT.subtract(finalTime).getReal() <= 0;
  291.                 if (filteredNextIsLast) {
  292.                     hNew = finalTime.subtract(getStepStart().getTime());
  293.                 }

  294.             }

  295.         } while (!isLastStep());

  296.         final FieldODEStateAndDerivative<T> finalState = getStepStart();
  297.         resetInternalState();
  298.         return finalState;

  299.     }

  300.     /** Get the minimal reduction factor for stepsize control.
  301.      * @return minimal reduction factor
  302.      */
  303.     public T getMinReduction() {
  304.         return minReduction;
  305.     }

  306.     /** Set the minimal reduction factor for stepsize control.
  307.      * @param minReduction minimal reduction factor
  308.      */
  309.     public void setMinReduction(final T minReduction) {
  310.         this.minReduction = minReduction;
  311.     }

  312.     /** Get the maximal growth factor for stepsize control.
  313.      * @return maximal growth factor
  314.      */
  315.     public T getMaxGrowth() {
  316.         return maxGrowth;
  317.     }

  318.     /** Set the maximal growth factor for stepsize control.
  319.      * @param maxGrowth maximal growth factor
  320.      */
  321.     public void setMaxGrowth(final T maxGrowth) {
  322.         this.maxGrowth = maxGrowth;
  323.     }

  324.     /** Compute the error ratio.
  325.      * @param yDotK derivatives computed during the first stages
  326.      * @param y0 estimate of the step at the start of the step
  327.      * @param y1 estimate of the step at the end of the step
  328.      * @param h  current step
  329.      * @return error ratio, greater than 1 if step should be rejected
  330.      */
  331.     protected abstract double estimateError(T[][] yDotK, T[] y0, T[] y1, T h);

  332. }