MultistepIntegrator.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;

  18. import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
  19. import org.apache.commons.math4.legacy.exception.MathIllegalStateException;
  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.exception.util.LocalizedFormats;
  24. import org.apache.commons.math4.legacy.linear.Array2DRowRealMatrix;
  25. import org.apache.commons.math4.legacy.ode.nonstiff.AdaptiveStepsizeIntegrator;
  26. import org.apache.commons.math4.legacy.ode.nonstiff.DormandPrince853Integrator;
  27. import org.apache.commons.math4.legacy.ode.sampling.StepHandler;
  28. import org.apache.commons.math4.legacy.ode.sampling.StepInterpolator;
  29. import org.apache.commons.math4.core.jdkmath.JdkMath;

  30. /**
  31.  * This class is the base class for multistep integrators for Ordinary
  32.  * Differential Equations.
  33.  * <p>We define scaled derivatives s<sub>i</sub>(n) at step n as:
  34.  * <div style="white-space: pre"><code>
  35.  * s<sub>1</sub>(n) = h y'<sub>n</sub> for first derivative
  36.  * s<sub>2</sub>(n) = h<sup>2</sup>/2 y''<sub>n</sub> for second derivative
  37.  * s<sub>3</sub>(n) = h<sup>3</sup>/6 y'''<sub>n</sub> for third derivative
  38.  * ...
  39.  * s<sub>k</sub>(n) = h<sup>k</sup>/k! y<sup>(k)</sup><sub>n</sub> for k<sup>th</sup> derivative
  40.  * </code></div>
  41.  * <p>Rather than storing several previous steps separately, this implementation uses
  42.  * the Nordsieck vector with higher degrees scaled derivatives all taken at the same
  43.  * step (y<sub>n</sub>, s<sub>1</sub>(n) and r<sub>n</sub>) where r<sub>n</sub> is defined as:
  44.  * <div style="white-space: pre"><code>
  45.  * r<sub>n</sub> = [ s<sub>2</sub>(n), s<sub>3</sub>(n) ... s<sub>k</sub>(n) ]<sup>T</sup>
  46.  * </code></div>
  47.  * (we omit the k index in the notation for clarity)
  48.  * <p>
  49.  * Multistep integrators with Nordsieck representation are highly sensitive to
  50.  * large step changes because when the step is multiplied by factor a, the
  51.  * k<sup>th</sup> component of the Nordsieck vector is multiplied by a<sup>k</sup>
  52.  * and the last components are the least accurate ones. The default max growth
  53.  * factor is therefore set to a quite low value: 2<sup>1/order</sup>.
  54.  * </p>
  55.  *
  56.  * @see org.apache.commons.math4.legacy.ode.nonstiff.AdamsBashforthIntegrator
  57.  * @see org.apache.commons.math4.legacy.ode.nonstiff.AdamsMoultonIntegrator
  58.  * @since 2.0
  59.  */
  60. public abstract class MultistepIntegrator extends AdaptiveStepsizeIntegrator {

  61.     /** First scaled derivative (h y'). */
  62.     protected double[] scaled;

  63.     /** Nordsieck matrix of the higher scaled derivatives.
  64.      * <p>(h<sup>2</sup>/2 y'', h<sup>3</sup>/6 y''' ..., h<sup>k</sup>/k! y<sup>(k)</sup>)</p>
  65.      */
  66.     protected Array2DRowRealMatrix nordsieck;

  67.     /** Starter integrator. */
  68.     private FirstOrderIntegrator starter;

  69.     /** Number of steps of the multistep method (excluding the one being computed). */
  70.     private final int nSteps;

  71.     /** Stepsize control exponent. */
  72.     private 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.     /**
  80.      * Build a multistep integrator with the given stepsize bounds.
  81.      * <p>The default starter integrator is set to the {@link
  82.      * DormandPrince853Integrator Dormand-Prince 8(5,3)} integrator with
  83.      * some defaults settings.</p>
  84.      * <p>
  85.      * The default max growth factor is set to a quite low value: 2<sup>1/order</sup>.
  86.      * </p>
  87.      * @param name name of the method
  88.      * @param nSteps number of steps of the multistep method
  89.      * (excluding the one being computed)
  90.      * @param order order of the method
  91.      * @param minStep minimal step (must be positive even for backward
  92.      * integration), the last step can be smaller than this
  93.      * @param maxStep maximal step (must be positive even for backward
  94.      * integration)
  95.      * @param scalAbsoluteTolerance allowed absolute error
  96.      * @param scalRelativeTolerance allowed relative error
  97.      * @exception NumberIsTooSmallException if number of steps is smaller than 2
  98.      */
  99.     protected MultistepIntegrator(final String name, final int nSteps,
  100.                                   final int order,
  101.                                   final double minStep, final double maxStep,
  102.                                   final double scalAbsoluteTolerance,
  103.                                   final double scalRelativeTolerance)
  104.         throws NumberIsTooSmallException {

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

  106.         if (nSteps < 2) {
  107.             throw new NumberIsTooSmallException(
  108.                   LocalizedFormats.INTEGRATION_METHOD_NEEDS_AT_LEAST_TWO_PREVIOUS_POINTS,
  109.                   nSteps, 2, true);
  110.         }

  111.         starter = new DormandPrince853Integrator(minStep, maxStep,
  112.                                                  scalAbsoluteTolerance,
  113.                                                  scalRelativeTolerance);
  114.         this.nSteps = nSteps;

  115.         exp = -1.0 / order;

  116.         // set the default values of the algorithm control parameters
  117.         setSafety(0.9);
  118.         setMinReduction(0.2);
  119.         setMaxGrowth(JdkMath.pow(2.0, -exp));
  120.     }

  121.     /**
  122.      * Build a multistep integrator with the given stepsize bounds.
  123.      * <p>The default starter integrator is set to the {@link
  124.      * DormandPrince853Integrator Dormand-Prince 8(5,3)} integrator with
  125.      * some defaults settings.</p>
  126.      * <p>
  127.      * The default max growth factor is set to a quite low value: 2<sup>1/order</sup>.
  128.      * </p>
  129.      * @param name name of the method
  130.      * @param nSteps number of steps of the multistep method
  131.      * (excluding the one being computed)
  132.      * @param order order of the method
  133.      * @param minStep minimal step (must be positive even for backward
  134.      * integration), the last step can be smaller than this
  135.      * @param maxStep maximal step (must be positive even for backward
  136.      * integration)
  137.      * @param vecAbsoluteTolerance allowed absolute error
  138.      * @param vecRelativeTolerance allowed relative error
  139.      */
  140.     protected MultistepIntegrator(final String name, final int nSteps,
  141.                                   final int order,
  142.                                   final double minStep, final double maxStep,
  143.                                   final double[] vecAbsoluteTolerance,
  144.                                   final double[] vecRelativeTolerance) {
  145.         super(name, minStep, maxStep, vecAbsoluteTolerance, vecRelativeTolerance);
  146.         starter = new DormandPrince853Integrator(minStep, maxStep,
  147.                                                  vecAbsoluteTolerance,
  148.                                                  vecRelativeTolerance);
  149.         this.nSteps = nSteps;

  150.         exp = -1.0 / order;

  151.         // set the default values of the algorithm control parameters
  152.         setSafety(0.9);
  153.         setMinReduction(0.2);
  154.         setMaxGrowth(JdkMath.pow(2.0, -exp));
  155.     }

  156.     /**
  157.      * Get the starter integrator.
  158.      * @return starter integrator
  159.      */
  160.     public ODEIntegrator getStarterIntegrator() {
  161.         return starter;
  162.     }

  163.     /**
  164.      * Set the starter integrator.
  165.      * <p>The various step and event handlers for this starter integrator
  166.      * will be managed automatically by the multi-step integrator. Any
  167.      * user configuration for these elements will be cleared before use.</p>
  168.      * @param starterIntegrator starter integrator
  169.      */
  170.     public void setStarterIntegrator(FirstOrderIntegrator starterIntegrator) {
  171.         this.starter = starterIntegrator;
  172.     }

  173.     /** Start the integration.
  174.      * <p>This method computes one step using the underlying starter integrator,
  175.      * and initializes the Nordsieck vector at step start. The starter integrator
  176.      * purpose is only to establish initial conditions, it does not really change
  177.      * time by itself. The top level multistep integrator remains in charge of
  178.      * handling time propagation and events handling as it will starts its own
  179.      * computation right from the beginning. In a sense, the starter integrator
  180.      * can be seen as a dummy one and so it will never trigger any user event nor
  181.      * call any user step handler.</p>
  182.      * @param t0 initial time
  183.      * @param y0 initial value of the state vector at t0
  184.      * @param t target time for the integration
  185.      * (can be set to a value smaller than <code>t0</code> for backward integration)
  186.      * @exception DimensionMismatchException if arrays dimension do not match equations settings
  187.      * @exception NumberIsTooSmallException if integration step is too small
  188.      * @exception MaxCountExceededException if the number of functions evaluations is exceeded
  189.      * @exception NoBracketingException if the location of an event cannot be bracketed
  190.      */
  191.     protected void start(final double t0, final double[] y0, final double t)
  192.         throws DimensionMismatchException, NumberIsTooSmallException,
  193.                MaxCountExceededException, NoBracketingException {

  194.         // make sure NO user event nor user step handler is triggered,
  195.         // this is the task of the top level integrator, not the task
  196.         // of the starter integrator
  197.         starter.clearEventHandlers();
  198.         starter.clearStepHandlers();

  199.         // set up one specific step handler to extract initial Nordsieck vector
  200.         starter.addStepHandler(new NordsieckInitializer((nSteps + 3) / 2, y0.length));

  201.         // start integration, expecting a InitializationCompletedMarkerException
  202.         try {

  203.             if (starter instanceof AbstractIntegrator) {
  204.                 ((AbstractIntegrator) starter).integrate(getExpandable(), t);
  205.             } else {
  206.                 starter.integrate(new FirstOrderDifferentialEquations() {

  207.                     /** {@inheritDoc} */
  208.                     @Override
  209.                     public int getDimension() {
  210.                         return getExpandable().getTotalDimension();
  211.                     }

  212.                     /** {@inheritDoc} */
  213.                     @Override
  214.                     public void computeDerivatives(double t, double[] y, double[] yDot) {
  215.                         getExpandable().computeDerivatives(t, y, yDot);
  216.                     }
  217.                 }, t0, y0, t, new double[y0.length]);
  218.             }

  219.             // we should not reach this step
  220.             throw new MathIllegalStateException(LocalizedFormats.MULTISTEP_STARTER_STOPPED_EARLY);
  221.         } catch (InitializationCompletedMarkerException icme) { // NOPMD
  222.             // this is the expected nominal interruption of the start integrator

  223.             // count the evaluations used by the starter
  224.             getCounter().increment(starter.getEvaluations());
  225.         }

  226.         // remove the specific step handler
  227.         starter.clearStepHandlers();
  228.     }

  229.     /** Initialize the high order scaled derivatives at step start.
  230.      * @param h step size to use for scaling
  231.      * @param t first steps times
  232.      * @param y first steps states
  233.      * @param yDot first steps derivatives
  234.      * @return Nordieck vector at first step (h<sup>2</sup>/2 y''<sub>n</sub>,
  235.      * h<sup>3</sup>/6 y'''<sub>n</sub> ... h<sup>k</sup>/k! y<sup>(k)</sup><sub>n</sub>)
  236.      */
  237.     protected abstract Array2DRowRealMatrix initializeHighOrderDerivatives(double h, double[] t,
  238.                                                                            double[][] y,
  239.                                                                            double[][] yDot);

  240.     /** Get the minimal reduction factor for stepsize control.
  241.      * @return minimal reduction factor
  242.      */
  243.     public double getMinReduction() {
  244.         return minReduction;
  245.     }

  246.     /** Set the minimal reduction factor for stepsize control.
  247.      * @param minReduction minimal reduction factor
  248.      */
  249.     public void setMinReduction(final double minReduction) {
  250.         this.minReduction = minReduction;
  251.     }

  252.     /** Get the maximal growth factor for stepsize control.
  253.      * @return maximal growth factor
  254.      */
  255.     public double getMaxGrowth() {
  256.         return maxGrowth;
  257.     }

  258.     /** Set the maximal growth factor for stepsize control.
  259.      * @param maxGrowth maximal growth factor
  260.      */
  261.     public void setMaxGrowth(final double maxGrowth) {
  262.         this.maxGrowth = maxGrowth;
  263.     }

  264.     /** Get the safety factor for stepsize control.
  265.      * @return safety factor
  266.      */
  267.     public double getSafety() {
  268.       return safety;
  269.     }

  270.     /** Set the safety factor for stepsize control.
  271.      * @param safety safety factor
  272.      */
  273.     public void setSafety(final double safety) {
  274.       this.safety = safety;
  275.     }

  276.     /** Get the number of steps of the multistep method (excluding the one being computed).
  277.      * @return number of steps of the multistep method (excluding the one being computed)
  278.      */
  279.     public int getNSteps() {
  280.       return nSteps;
  281.     }

  282.     /** Compute step grow/shrink factor according to normalized error.
  283.      * @param error normalized error of the current step
  284.      * @return grow/shrink factor for next step
  285.      */
  286.     protected double computeStepGrowShrinkFactor(final double error) {
  287.         return JdkMath.min(maxGrowth, JdkMath.max(minReduction, safety * JdkMath.pow(error, exp)));
  288.     }

  289.     /** Transformer used to convert the first step to Nordsieck representation.
  290.      * @deprecated as of 3.6 this unused interface is deprecated
  291.      */
  292.     @Deprecated
  293.     public interface NordsieckTransformer {
  294.         /** Initialize the high order scaled derivatives at step start.
  295.          * @param h step size to use for scaling
  296.          * @param t first steps times
  297.          * @param y first steps states
  298.          * @param yDot first steps derivatives
  299.          * @return Nordieck vector at first step (h<sup>2</sup>/2 y''<sub>n</sub>,
  300.          * h<sup>3</sup>/6 y'''<sub>n</sub> ... h<sup>k</sup>/k! y<sup>(k)</sup><sub>n</sub>)
  301.          */
  302.         Array2DRowRealMatrix initializeHighOrderDerivatives(double h, double[] t,
  303.                                                             double[][] y,
  304.                                                             double[][] yDot);
  305.     }

  306.     /** Specialized step handler storing the first step. */
  307.     private final class NordsieckInitializer implements StepHandler {

  308.         /** Steps counter. */
  309.         private int count;

  310.         /** First steps times. */
  311.         private final double[] t;

  312.         /** First steps states. */
  313.         private final double[][] y;

  314.         /** First steps derivatives. */
  315.         private final double[][] yDot;

  316.         /** Simple constructor.
  317.          * @param nbStartPoints number of start points (including the initial point)
  318.          * @param n problem dimension
  319.          */
  320.         NordsieckInitializer(final int nbStartPoints, final int n) {
  321.             this.count = 0;
  322.             this.t     = new double[nbStartPoints];
  323.             this.y     = new double[nbStartPoints][n];
  324.             this.yDot  = new double[nbStartPoints][n];
  325.         }

  326.         /** {@inheritDoc} */
  327.         @Override
  328.         public void handleStep(StepInterpolator interpolator, boolean isLast)
  329.             throws MaxCountExceededException {

  330.             final double prev = interpolator.getPreviousTime();
  331.             final double curr = interpolator.getCurrentTime();

  332.             if (count == 0) {
  333.                 // first step, we need to store also the point at the beginning of the step
  334.                 interpolator.setInterpolatedTime(prev);
  335.                 t[0] = prev;
  336.                 final ExpandableStatefulODE expandable = getExpandable();
  337.                 final EquationsMapper primary = expandable.getPrimaryMapper();
  338.                 primary.insertEquationData(interpolator.getInterpolatedState(), y[count]);
  339.                 primary.insertEquationData(interpolator.getInterpolatedDerivatives(), yDot[count]);
  340.                 int index = 0;
  341.                 for (final EquationsMapper secondary : expandable.getSecondaryMappers()) {
  342.                     secondary.insertEquationData(interpolator.getInterpolatedSecondaryState(index), y[count]);
  343.                     secondary.insertEquationData(interpolator.getInterpolatedSecondaryDerivatives(index), yDot[count]);
  344.                     ++index;
  345.                 }
  346.             }

  347.             // store the point at the end of the step
  348.             ++count;
  349.             interpolator.setInterpolatedTime(curr);
  350.             t[count] = curr;

  351.             final ExpandableStatefulODE expandable = getExpandable();
  352.             final EquationsMapper primary = expandable.getPrimaryMapper();
  353.             primary.insertEquationData(interpolator.getInterpolatedState(), y[count]);
  354.             primary.insertEquationData(interpolator.getInterpolatedDerivatives(), yDot[count]);
  355.             int index = 0;
  356.             for (final EquationsMapper secondary : expandable.getSecondaryMappers()) {
  357.                 secondary.insertEquationData(interpolator.getInterpolatedSecondaryState(index), y[count]);
  358.                 secondary.insertEquationData(interpolator.getInterpolatedSecondaryDerivatives(index), yDot[count]);
  359.                 ++index;
  360.             }

  361.             if (count == t.length - 1) {

  362.                 // this was the last point we needed, we can compute the derivatives
  363.                 stepStart = t[0];
  364.                 stepSize  = (t[t.length - 1] - t[0]) / (t.length - 1);

  365.                 // first scaled derivative
  366.                 scaled = yDot[0].clone();
  367.                 for (int j = 0; j < scaled.length; ++j) {
  368.                     scaled[j] *= stepSize;
  369.                 }

  370.                 // higher order derivatives
  371.                 nordsieck = initializeHighOrderDerivatives(stepSize, t, y, yDot);

  372.                 // stop the integrator now that all needed steps have been handled
  373.                 throw new InitializationCompletedMarkerException();
  374.             }
  375.         }

  376.         /** {@inheritDoc} */
  377.         @Override
  378.         public void init(double t0, double[] y0, double time) {
  379.             // nothing to do
  380.         }
  381.     }

  382.     /** Marker exception used ONLY to stop the starter integrator after first step. */
  383.     private static final class InitializationCompletedMarkerException
  384.         extends RuntimeException {

  385.         /** Serializable version identifier. */
  386.         private static final long serialVersionUID = -1914085471038046418L;

  387.         /** Simple constructor. */
  388.         InitializationCompletedMarkerException() {
  389.             super((Throwable) null);
  390.         }
  391.     }
  392. }