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

  22. import org.hipparchus.exception.MathIllegalArgumentException;
  23. import org.hipparchus.exception.MathIllegalStateException;
  24. import org.hipparchus.linear.Array2DRowRealMatrix;
  25. import org.hipparchus.ode.nonstiff.AdaptiveStepsizeIntegrator;
  26. import org.hipparchus.ode.nonstiff.DormandPrince853Integrator;
  27. import org.hipparchus.ode.sampling.ODEStateInterpolator;
  28. import org.hipparchus.ode.sampling.ODEStepHandler;
  29. import org.hipparchus.util.FastMath;

  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.  * \[
  35.  *   \left\{\begin{align}
  36.  *   s_1(n) &amp;= h y'_n \text{ for first derivative}\\
  37.  *   s_2(n) &amp;= \frac{h^2}{2} y_n'' \text{ for second derivative}\\
  38.  *   s_3(n) &amp;= \frac{h^3}{6} y_n''' \text{ for third derivative}\\
  39.  *   &amp;\cdots\\
  40.  *   s_k(n) &amp;= \frac{h^k}{k!} y_n^{(k)} \text{ for } k^\mathrm{th} \text{ derivative}
  41.  *   \end{align}\right.
  42.  * \]</p>
  43.  * <p>Rather than storing several previous steps separately, this implementation uses
  44.  * the Nordsieck vector with higher degrees scaled derivatives all taken at the same
  45.  * step (y<sub>n</sub>, s<sub>1</sub>(n) and r<sub>n</sub>) where r<sub>n</sub> is defined as:
  46.  * \[
  47.  * r_n = [ s_2(n), s_3(n) \ldots s_k(n) ]^T
  48.  * \]
  49.  * (we omit the k index in the notation for clarity)</p>
  50.  * <p>
  51.  * Multistep integrators with Nordsieck representation are highly sensitive to
  52.  * large step changes because when the step is multiplied by factor a, the
  53.  * k<sup>th</sup> component of the Nordsieck vector is multiplied by a<sup>k</sup>
  54.  * and the last components are the least accurate ones. The default max growth
  55.  * factor is therefore set to a quite low value: 2<sup>1/order</sup>.
  56.  * </p>
  57.  *
  58.  * @see org.hipparchus.ode.nonstiff.AdamsBashforthIntegrator
  59.  * @see org.hipparchus.ode.nonstiff.AdamsMoultonIntegrator
  60.  */
  61. public abstract class MultistepIntegrator extends AdaptiveStepsizeIntegrator {

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

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

  68.     /** Starter integrator. */
  69.     private ODEIntegrator starter;

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

  72.     /** Stepsize control exponent. */
  73.     private double exp;

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

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

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

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

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

  107.         if (nSteps < 2) {
  108.             throw new MathIllegalArgumentException(LocalizedODEFormats.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(FastMath.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.         if (nSteps < 2) {
  147.             throw new MathIllegalArgumentException(LocalizedODEFormats.INTEGRATION_METHOD_NEEDS_AT_LEAST_TWO_PREVIOUS_POINTS,
  148.                                                    nSteps, 2, true);
  149.         }

  150.         starter = new DormandPrince853Integrator(minStep, maxStep,
  151.                                                  vecAbsoluteTolerance,
  152.                                                  vecRelativeTolerance);
  153.         this.nSteps = nSteps;

  154.         exp = -1.0 / order;

  155.         // set the default values of the algorithm control parameters
  156.         setSafety(0.9);
  157.         setMinReduction(0.2);
  158.         setMaxGrowth(FastMath.pow(2.0, -exp));

  159.     }

  160.     /**
  161.      * Get the starter integrator.
  162.      * @return starter integrator
  163.      */
  164.     public ODEIntegrator getStarterIntegrator() {
  165.         return starter;
  166.     }

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

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

  197.         // make sure NO user events nor user step handlers are triggered,
  198.         // this is the task of the top level integrator, not the task of the starter integrator
  199.         starter.clearEventDetectors();
  200.         starter.clearStepHandlers();

  201.         // set up one specific step handler to extract initial Nordsieck vector
  202.         starter.addStepHandler(new NordsieckInitializer((nSteps + 3) / 2));

  203.         // start integration, expecting a InitializationCompletedMarkerException
  204.         try {

  205.             starter.integrate(getEquations(), initialState, finalTime);

  206.             // we should not reach this step
  207.             throw new MathIllegalStateException(LocalizedODEFormats.MULTISTEP_STARTER_STOPPED_EARLY);

  208.         } catch (InitializationCompletedMarkerException icme) { // NOPMD
  209.             // this is the expected nominal interruption of the start integrator

  210.             // count the evaluations used by the starter
  211.             getEvaluationsCounter().increment(starter.getEvaluations());

  212.         }

  213.         // remove the specific step handler
  214.         starter.clearStepHandlers();

  215.     }

  216.     /** Initialize the high order scaled derivatives at step start.
  217.      * @param h step size to use for scaling
  218.      * @param t first steps times
  219.      * @param y first steps states
  220.      * @param yDot first steps derivatives
  221.      * @return Nordieck vector at first step (h<sup>2</sup>/2 y''<sub>n</sub>,
  222.      * h<sup>3</sup>/6 y'''<sub>n</sub> ... h<sup>k</sup>/k! y<sup>(k)</sup><sub>n</sub>)
  223.      */
  224.     protected abstract Array2DRowRealMatrix initializeHighOrderDerivatives(double h, double[] t, double[][] y, double[][] yDot);

  225.     /** Get the minimal reduction factor for stepsize control.
  226.      * @return minimal reduction factor
  227.      */
  228.     public double getMinReduction() {
  229.         return minReduction;
  230.     }

  231.     /** Set the minimal reduction factor for stepsize control.
  232.      * @param minReduction minimal reduction factor
  233.      */
  234.     public void setMinReduction(final double minReduction) {
  235.         this.minReduction = minReduction;
  236.     }

  237.     /** Get the maximal growth factor for stepsize control.
  238.      * @return maximal growth factor
  239.      */
  240.     public double getMaxGrowth() {
  241.         return maxGrowth;
  242.     }

  243.     /** Set the maximal growth factor for stepsize control.
  244.      * @param maxGrowth maximal growth factor
  245.      */
  246.     public void setMaxGrowth(final double maxGrowth) {
  247.         this.maxGrowth = maxGrowth;
  248.     }

  249.     /** Get the safety factor for stepsize control.
  250.      * @return safety factor
  251.      */
  252.     public double getSafety() {
  253.       return safety;
  254.     }

  255.     /** Set the safety factor for stepsize control.
  256.      * @param safety safety factor
  257.      */
  258.     public void setSafety(final double safety) {
  259.       this.safety = safety;
  260.     }

  261.     /** Get the number of steps of the multistep method (excluding the one being computed).
  262.      * @return number of steps of the multistep method (excluding the one being computed)
  263.      */
  264.     public int getNSteps() {
  265.       return nSteps;
  266.     }

  267.     /** Rescale the instance.
  268.      * <p>Since the scaled and Nordsieck arrays are shared with the caller,
  269.      * this method has the side effect of rescaling this arrays in the caller too.</p>
  270.      * @param newStepSize new step size to use in the scaled and Nordsieck arrays
  271.      */
  272.     protected void rescale(final double newStepSize) {

  273.         final double ratio = newStepSize / getStepSize();
  274.         for (int i = 0; i < scaled.length; ++i) {
  275.             scaled[i] = scaled[i] * ratio;
  276.         }

  277.         final double[][] nData = nordsieck.getDataRef();
  278.         double power = ratio;
  279.         for (int i = 0; i < nData.length; ++i) {
  280.             power = power * ratio;
  281.             final double[] nDataI = nData[i];
  282.             for (int j = 0; j < nDataI.length; ++j) {
  283.                 nDataI[j] = nDataI[j] * power;
  284.             }
  285.         }

  286.         setStepSize(newStepSize);

  287.     }

  288.     /** Compute step grow/shrink factor according to normalized error.
  289.      * @param error normalized error of the current step
  290.      * @return grow/shrink factor for next step
  291.      */
  292.     protected double computeStepGrowShrinkFactor(final double error) {
  293.         return FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.pow(error, exp)));
  294.     }

  295.     /** Specialized step handler storing the first step. */
  296.     private class NordsieckInitializer implements ODEStepHandler {

  297.         /** Steps counter. */
  298.         private int count;

  299.         /** Start of the integration. */
  300.         private ODEStateAndDerivative savedStart;

  301.         /** First steps times. */
  302.         private final double[] t;

  303.         /** First steps states. */
  304.         private final double[][] y;

  305.         /** First steps derivatives. */
  306.         private final double[][] yDot;

  307.         /** Simple constructor.
  308.          * @param nbStartPoints number of start points (including the initial point)
  309.          */
  310.         NordsieckInitializer(final int nbStartPoints) {
  311.             this.count  = 0;
  312.             this.t      = new double[nbStartPoints];
  313.             this.y      = new double[nbStartPoints][];
  314.             this.yDot   = new double[nbStartPoints][];
  315.         }

  316.         /** {@inheritDoc} */
  317.         @Override
  318.         public void handleStep(ODEStateInterpolator interpolator) {

  319.             if (count == 0) {
  320.                 // first step, we need to store also the point at the beginning of the step
  321.                 savedStart   = interpolator.getPreviousState();
  322.                 t[0]    = savedStart.getTime();
  323.                 y[0]    = savedStart.getCompleteState();
  324.                 yDot[0] = savedStart.getCompleteDerivative();
  325.             }

  326.             // store the point at the end of the step
  327.             ++count;
  328.             final ODEStateAndDerivative curr = interpolator.getCurrentState();
  329.             t[count]    = curr.getTime();
  330.             y[count]    = curr.getCompleteState();
  331.             yDot[count] = curr.getCompleteDerivative();

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

  333.                 // this was the last point we needed, we can compute the derivatives
  334.                 setStepStart(savedStart);
  335.                 final double rawStep = (t[t.length - 1] - t[0]) / (t.length - 1);
  336.                 setStepSize(getStepSizeHelper().filterStep(rawStep, rawStep >= 0, true));

  337.                 // first scaled derivative
  338.                 scaled = yDot[0].clone();
  339.                 for (int j = 0; j < scaled.length; ++j) {
  340.                     scaled[j] *= getStepSize();
  341.                 }

  342.                 // higher order derivatives
  343.                 nordsieck = initializeHighOrderDerivatives(getStepSize(), t, y, yDot);

  344.                 // stop the integrator now that all needed steps have been handled
  345.                 throw new InitializationCompletedMarkerException();

  346.             }

  347.         }

  348.     }

  349.     /** Marker exception used ONLY to stop the starter integrator after first step. */
  350.     private static class InitializationCompletedMarkerException
  351.         extends RuntimeException {

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

  354.         /** Simple constructor. */
  355.         InitializationCompletedMarkerException() {
  356.             super((Throwable) null);
  357.         }

  358.     }

  359. }