MultistepFieldIntegrator.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.Field;
  23. import org.hipparchus.CalculusFieldElement;
  24. import org.hipparchus.exception.MathIllegalArgumentException;
  25. import org.hipparchus.exception.MathIllegalStateException;
  26. import org.hipparchus.linear.Array2DRowFieldMatrix;
  27. import org.hipparchus.ode.nonstiff.AdaptiveStepsizeFieldIntegrator;
  28. import org.hipparchus.ode.nonstiff.DormandPrince853FieldIntegrator;
  29. import org.hipparchus.ode.sampling.FieldODEStateInterpolator;
  30. import org.hipparchus.ode.sampling.FieldODEStepHandler;
  31. import org.hipparchus.util.FastMath;
  32. import org.hipparchus.util.MathArrays;

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

  67.     /** First scaled derivative (h y'). */
  68.     protected T[] scaled;

  69.     /** Nordsieck matrix of the higher scaled derivatives.
  70.      * <p>(h<sup>2</sup>/2 y'', h<sup>3</sup>/6 y''' ..., h<sup>k</sup>/k! y<sup>(k)</sup>)</p>
  71.      */
  72.     protected Array2DRowFieldMatrix<T> nordsieck;

  73.     /** Starter integrator. */
  74.     private FieldODEIntegrator<T> starter;

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

  77.     /** Stepsize control exponent. */
  78.     private double exp;

  79.     /** Safety factor for stepsize control. */
  80.     private double safety;

  81.     /** Minimal reduction factor for stepsize control. */
  82.     private double minReduction;

  83.     /** Maximal growth factor for stepsize control. */
  84.     private double maxGrowth;

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

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

  113.         if (nSteps < 2) {
  114.             throw new MathIllegalArgumentException(LocalizedODEFormats.INTEGRATION_METHOD_NEEDS_AT_LEAST_TWO_PREVIOUS_POINTS,
  115.                                                    nSteps, 2, true);
  116.         }

  117.         starter = new DormandPrince853FieldIntegrator<>(field, minStep, maxStep,
  118.                                                         scalAbsoluteTolerance,
  119.                                                         scalRelativeTolerance);
  120.         this.nSteps = nSteps;

  121.         exp = -1.0 / order;

  122.         // set the default values of the algorithm control parameters
  123.         setSafety(0.9);
  124.         setMinReduction(0.2);
  125.         setMaxGrowth(FastMath.pow(2.0, -exp));

  126.     }

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

  153.         if (nSteps < 2) {
  154.             throw new MathIllegalArgumentException(LocalizedODEFormats.INTEGRATION_METHOD_NEEDS_AT_LEAST_TWO_PREVIOUS_POINTS,
  155.                                                    nSteps, 2, true);
  156.         }

  157.         starter = new DormandPrince853FieldIntegrator<>(field, minStep, maxStep,
  158.                                                         vecAbsoluteTolerance,
  159.                                                         vecRelativeTolerance);
  160.         this.nSteps = nSteps;

  161.         exp = -1.0 / order;

  162.         // set the default values of the algorithm control parameters
  163.         setSafety(0.9);
  164.         setMinReduction(0.2);
  165.         setMaxGrowth(FastMath.pow(2.0, -exp));

  166.     }

  167.     /**
  168.      * Get the starter integrator.
  169.      * @return starter integrator
  170.      */
  171.     public FieldODEIntegrator<T> getStarterIntegrator() {
  172.         return starter;
  173.     }

  174.     /**
  175.      * Set the starter integrator.
  176.      * <p>The various step and event handlers for this starter integrator
  177.      * will be managed automatically by the multi-step integrator. Any
  178.      * user configuration for these elements will be cleared before use.</p>
  179.      * @param starterIntegrator starter integrator
  180.      */
  181.     public void setStarterIntegrator(FieldODEIntegrator<T> starterIntegrator) {
  182.         this.starter = starterIntegrator;
  183.     }

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

  204.         // make sure NO user events nor user step handlers are triggered,
  205.         // this is the task of the top level integrator, not the task of the starter integrator
  206.         starter.clearEventDetectors();
  207.         starter.clearStepHandlers();

  208.         // set up one specific step handler to extract initial Nordsieck vector
  209.         starter.addStepHandler(new FieldNordsieckInitializer((nSteps + 3) / 2));

  210.         // start integration, expecting a InitializationCompletedMarkerException
  211.         try {

  212.             starter.integrate(equations, initialState, t);

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

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

  217.             // count the evaluations used by the starter
  218.             getEvaluationsCounter().increment(starter.getEvaluations());

  219.         }

  220.         // remove the specific step handler
  221.         starter.clearStepHandlers();

  222.     }

  223.     /** Initialize the high order scaled derivatives at step start.
  224.      * @param h step size to use for scaling
  225.      * @param t first steps times
  226.      * @param y first steps states
  227.      * @param yDot first steps derivatives
  228.      * @return Nordieck vector at first step (h<sup>2</sup>/2 y''<sub>n</sub>,
  229.      * h<sup>3</sup>/6 y'''<sub>n</sub> ... h<sup>k</sup>/k! y<sup>(k)</sup><sub>n</sub>)
  230.      */
  231.     protected abstract Array2DRowFieldMatrix<T> initializeHighOrderDerivatives(T h, T[] t, T[][] y, T[][] yDot);

  232.     /** Get the minimal reduction factor for stepsize control.
  233.      * @return minimal reduction factor
  234.      */
  235.     public double getMinReduction() {
  236.         return minReduction;
  237.     }

  238.     /** Set the minimal reduction factor for stepsize control.
  239.      * @param minReduction minimal reduction factor
  240.      */
  241.     public void setMinReduction(final double minReduction) {
  242.         this.minReduction = minReduction;
  243.     }

  244.     /** Get the maximal growth factor for stepsize control.
  245.      * @return maximal growth factor
  246.      */
  247.     public double getMaxGrowth() {
  248.         return maxGrowth;
  249.     }

  250.     /** Set the maximal growth factor for stepsize control.
  251.      * @param maxGrowth maximal growth factor
  252.      */
  253.     public void setMaxGrowth(final double maxGrowth) {
  254.         this.maxGrowth = maxGrowth;
  255.     }

  256.     /** Get the safety factor for stepsize control.
  257.      * @return safety factor
  258.      */
  259.     public double getSafety() {
  260.       return safety;
  261.     }

  262.     /** Set the safety factor for stepsize control.
  263.      * @param safety safety factor
  264.      */
  265.     public void setSafety(final double safety) {
  266.       this.safety = safety;
  267.     }

  268.     /** Get the number of steps of the multistep method (excluding the one being computed).
  269.      * @return number of steps of the multistep method (excluding the one being computed)
  270.      */
  271.     public int getNSteps() {
  272.       return nSteps;
  273.     }

  274.     /** Rescale the instance.
  275.      * <p>Since the scaled and Nordsieck arrays are shared with the caller,
  276.      * this method has the side effect of rescaling this arrays in the caller too.</p>
  277.      * @param newStepSize new step size to use in the scaled and Nordsieck arrays
  278.      */
  279.     protected void rescale(final T newStepSize) {

  280.         final T ratio = newStepSize.divide(getStepSize());
  281.         for (int i = 0; i < scaled.length; ++i) {
  282.             scaled[i] = scaled[i].multiply(ratio);
  283.         }

  284.         final T[][] nData = nordsieck.getDataRef();
  285.         T power = ratio;
  286.         for (int i = 0; i < nData.length; ++i) {
  287.             power = power.multiply(ratio);
  288.             final T[] nDataI = nData[i];
  289.             for (int j = 0; j < nDataI.length; ++j) {
  290.                 nDataI[j] = nDataI[j].multiply(power);
  291.             }
  292.         }

  293.         setStepSize(newStepSize);

  294.     }

  295.     /** Compute step grow/shrink factor according to normalized error.
  296.      * @param error normalized error of the current step
  297.      * @return grow/shrink factor for next step
  298.      */
  299.     protected double computeStepGrowShrinkFactor(final double error) {
  300.         return FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.pow(error, exp)));
  301.     }

  302.     /** Specialized step handler storing the first step.
  303.      */
  304.     private class FieldNordsieckInitializer implements FieldODEStepHandler<T> {

  305.         /** Steps counter. */
  306.         private int count;

  307.         /** Saved start. */
  308.         private FieldODEStateAndDerivative<T> savedStart;

  309.         /** First steps times. */
  310.         private final T[] t;

  311.         /** First steps states. */
  312.         private final T[][] y;

  313.         /** First steps derivatives. */
  314.         private final T[][] yDot;

  315.         /** Simple constructor.
  316.          * @param nbStartPoints number of start points (including the initial point)
  317.          */
  318.         FieldNordsieckInitializer(final int nbStartPoints) {
  319.             this.count  = 0;
  320.             this.t      = MathArrays.buildArray(getField(), nbStartPoints);
  321.             this.y      = MathArrays.buildArray(getField(), nbStartPoints, -1);
  322.             this.yDot   = MathArrays.buildArray(getField(), nbStartPoints, -1);
  323.         }

  324.         /** {@inheritDoc} */
  325.         @Override
  326.         public void handleStep(FieldODEStateInterpolator<T> interpolator) {


  327.             if (count == 0) {
  328.                 // first step, we need to store also the point at the beginning of the step
  329.                 final FieldODEStateAndDerivative<T> prev = interpolator.getPreviousState();
  330.                 savedStart  = prev;
  331.                 t[count]    = prev.getTime();
  332.                 y[count]    = prev.getCompleteState();
  333.                 yDot[count] = prev.getCompleteDerivative();
  334.             }

  335.             // store the point at the end of the step
  336.             ++count;
  337.             final FieldODEStateAndDerivative<T> curr = interpolator.getCurrentState();
  338.             t[count]    = curr.getTime();
  339.             y[count]    = curr.getCompleteState();
  340.             yDot[count] = curr.getCompleteDerivative();

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

  342.                 // this was the last point we needed, we can compute the derivatives
  343.                 setStepStart(savedStart);
  344.                 final T rawStep = t[t.length - 1].subtract(t[0]).divide(t.length - 1);
  345.                 setStepSize(getStepSizeHelper().filterStep(rawStep, rawStep.getReal() >= 0, true));

  346.                 // first scaled derivative
  347.                 scaled = MathArrays.buildArray(getField(), yDot[0].length);
  348.                 for (int j = 0; j < scaled.length; ++j) {
  349.                     scaled[j] = yDot[0][j].multiply(getStepSize());
  350.                 }

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

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

  355.             }

  356.         }

  357.         /** {@inheritDoc} */
  358.         @Override
  359.         public void init(final FieldODEStateAndDerivative<T> initialState, T finalTime) {
  360.             // nothing to do
  361.         }

  362.     }

  363.     /** Marker exception used ONLY to stop the starter integrator after first step. */
  364.     private static class InitializationCompletedMarkerException
  365.         extends RuntimeException {

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

  368.         /** Simple constructor. */
  369.         InitializationCompletedMarkerException() {
  370.             super((Throwable) null);
  371.         }

  372.     }

  373. }