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.  *      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.core.Field;
  19. import org.apache.commons.math4.legacy.core.RealFieldElement;
  20. import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
  21. import org.apache.commons.math4.legacy.exception.MathIllegalStateException;
  22. import org.apache.commons.math4.legacy.exception.MaxCountExceededException;
  23. import org.apache.commons.math4.legacy.exception.NoBracketingException;
  24. import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException;
  25. import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
  26. import org.apache.commons.math4.legacy.linear.Array2DRowFieldMatrix;
  27. import org.apache.commons.math4.legacy.ode.nonstiff.AdaptiveStepsizeFieldIntegrator;
  28. import org.apache.commons.math4.legacy.ode.nonstiff.DormandPrince853FieldIntegrator;
  29. import org.apache.commons.math4.legacy.ode.sampling.FieldStepHandler;
  30. import org.apache.commons.math4.legacy.ode.sampling.FieldStepInterpolator;
  31. import org.apache.commons.math4.core.jdkmath.JdkMath;
  32. import org.apache.commons.math4.legacy.core.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.  * <div style="white-space: pre"><code>
  38.  * s<sub>1</sub>(n) = h y'<sub>n</sub> for first derivative
  39.  * s<sub>2</sub>(n) = h<sup>2</sup>/2 y''<sub>n</sub> for second derivative
  40.  * s<sub>3</sub>(n) = h<sup>3</sup>/6 y'''<sub>n</sub> for third derivative
  41.  * ...
  42.  * s<sub>k</sub>(n) = h<sup>k</sup>/k! y<sup>(k)</sup><sub>n</sub> for k<sup>th</sup> derivative
  43.  * </code></div>
  44.  * <p>Rather than storing several previous steps separately, this implementation uses
  45.  * the Nordsieck vector with higher degrees scaled derivatives all taken at the same
  46.  * step (y<sub>n</sub>, s<sub>1</sub>(n) and r<sub>n</sub>) where r<sub>n</sub> is defined as:
  47.  * <div style="white-space: pre"><code>
  48.  * r<sub>n</sub> = [ s<sub>2</sub>(n), s<sub>3</sub>(n) ... s<sub>k</sub>(n) ]<sup>T</sup>
  49.  * </code></div>
  50.  * (we omit the k index in the notation for clarity)
  51.  * <p>
  52.  * Multistep integrators with Nordsieck representation are highly sensitive to
  53.  * large step changes because when the step is multiplied by factor a, the
  54.  * k<sup>th</sup> component of the Nordsieck vector is multiplied by a<sup>k</sup>
  55.  * and the last components are the least accurate ones. The default max growth
  56.  * factor is therefore set to a quite low value: 2<sup>1/order</sup>.
  57.  * </p>
  58.  *
  59.  * @see org.apache.commons.math4.legacy.ode.nonstiff.AdamsBashforthFieldIntegrator
  60.  * @see org.apache.commons.math4.legacy.ode.nonstiff.AdamsMoultonFieldIntegrator
  61.  * @param <T> the type of the field elements
  62.  * @since 3.6
  63.  */
  64. public abstract class MultistepFieldIntegrator<T extends RealFieldElement<T>>
  65.     extends AdaptiveStepsizeFieldIntegrator<T> {

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

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

  72.     /** Starter integrator. */
  73.     private FirstOrderFieldIntegrator<T> starter;

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

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

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

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

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

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

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

  112.         if (nSteps < 2) {
  113.             throw new NumberIsTooSmallException(
  114.                   LocalizedFormats.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(JdkMath.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.         starter = new DormandPrince853FieldIntegrator<>(field, minStep, maxStep,
  154.                                                          vecAbsoluteTolerance,
  155.                                                          vecRelativeTolerance);
  156.         this.nSteps = nSteps;

  157.         exp = -1.0 / order;

  158.         // set the default values of the algorithm control parameters
  159.         setSafety(0.9);
  160.         setMinReduction(0.2);
  161.         setMaxGrowth(JdkMath.pow(2.0, -exp));
  162.     }

  163.     /**
  164.      * Get the starter integrator.
  165.      * @return starter integrator
  166.      */
  167.     public FirstOrderFieldIntegrator<T> getStarterIntegrator() {
  168.         return starter;
  169.     }

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

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

  201.         // make sure NO user event nor user step handler is triggered,
  202.         // this is the task of the top level integrator, not the task
  203.         // of the starter integrator
  204.         starter.clearEventHandlers();
  205.         starter.clearStepHandlers();

  206.         // set up one specific step handler to extract initial Nordsieck vector
  207.         starter.addStepHandler(new FieldNordsieckInitializer(equations.getMapper(), (nSteps + 3) / 2));

  208.         // start integration, expecting a InitializationCompletedMarkerException
  209.         try {

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

  211.             // we should not reach this step
  212.             throw new MathIllegalStateException(LocalizedFormats.MULTISTEP_STARTER_STOPPED_EARLY);
  213.         } catch (InitializationCompletedMarkerException icme) { // NOPMD
  214.             // this is the expected nominal interruption of the start integrator

  215.             // count the evaluations used by the starter
  216.             getEvaluationsCounter().increment(starter.getEvaluations());
  217.         }

  218.         // remove the specific step handler
  219.         starter.clearStepHandlers();
  220.     }

  221.     /** Initialize the high order scaled derivatives at step start.
  222.      * @param h step size to use for scaling
  223.      * @param t first steps times
  224.      * @param y first steps states
  225.      * @param yDot first steps derivatives
  226.      * @return Nordieck vector at first step (h<sup>2</sup>/2 y''<sub>n</sub>,
  227.      * h<sup>3</sup>/6 y'''<sub>n</sub> ... h<sup>k</sup>/k! y<sup>(k)</sup><sub>n</sub>)
  228.      */
  229.     protected abstract Array2DRowFieldMatrix<T> initializeHighOrderDerivatives(T h, T[] t,
  230.                                                                                T[][] y,
  231.                                                                                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 T computeStepGrowShrinkFactor(final T error) {
  300.         return RealFieldElement.min(error.getField().getZero().add(maxGrowth),
  301.                              RealFieldElement.max(error.getField().getZero().add(minReduction),
  302.                                            error.pow(exp).multiply(safety)));
  303.     }

  304.     /** Specialized step handler storing the first step.
  305.      */
  306.     private final class FieldNordsieckInitializer implements FieldStepHandler<T> {

  307.         /** Equation mapper. */
  308.         private final FieldEquationsMapper<T> mapper;

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

  311.         /** Saved start. */
  312.         private FieldODEStateAndDerivative<T> savedStart;

  313.         /** First steps times. */
  314.         private final T[] t;

  315.         /** First steps states. */
  316.         private final T[][] y;

  317.         /** First steps derivatives. */
  318.         private final T[][] yDot;

  319.         /** Simple constructor.
  320.          * @param mapper equation mapper
  321.          * @param nbStartPoints number of start points (including the initial point)
  322.          */
  323.         FieldNordsieckInitializer(final FieldEquationsMapper<T> mapper, final int nbStartPoints) {
  324.             this.mapper = mapper;
  325.             this.count  = 0;
  326.             this.t      = MathArrays.buildArray(getField(), nbStartPoints);
  327.             this.y      = MathArrays.buildArray(getField(), nbStartPoints, -1);
  328.             this.yDot   = MathArrays.buildArray(getField(), nbStartPoints, -1);
  329.         }

  330.         /** {@inheritDoc} */
  331.         @Override
  332.         public void handleStep(FieldStepInterpolator<T> interpolator, boolean isLast)
  333.             throws MaxCountExceededException {


  334.             if (count == 0) {
  335.                 // first step, we need to store also the point at the beginning of the step
  336.                 final FieldODEStateAndDerivative<T> prev = interpolator.getPreviousState();
  337.                 savedStart  = prev;
  338.                 t[count]    = prev.getTime();
  339.                 y[count]    = mapper.mapState(prev);
  340.                 yDot[count] = mapper.mapDerivative(prev);
  341.             }

  342.             // store the point at the end of the step
  343.             ++count;
  344.             final FieldODEStateAndDerivative<T> curr = interpolator.getCurrentState();
  345.             t[count]    = curr.getTime();
  346.             y[count]    = mapper.mapState(curr);
  347.             yDot[count] = mapper.mapDerivative(curr);

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

  349.                 // this was the last point we needed, we can compute the derivatives
  350.                 setStepSize(t[t.length - 1].subtract(t[0]).divide(t.length - 1));

  351.                 // first scaled derivative
  352.                 scaled = MathArrays.buildArray(getField(), yDot[0].length);
  353.                 for (int j = 0; j < scaled.length; ++j) {
  354.                     scaled[j] = yDot[0][j].multiply(getStepSize());
  355.                 }

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

  358.                 // stop the integrator now that all needed steps have been handled
  359.                 setStepStart(savedStart);
  360.                 throw new InitializationCompletedMarkerException();
  361.             }
  362.         }

  363.         /** {@inheritDoc} */
  364.         @Override
  365.         public void init(final FieldODEStateAndDerivative<T> initialState, T finalTime) {
  366.             // nothing to do
  367.         }
  368.     }

  369.     /** Marker exception used ONLY to stop the starter integrator after first step. */
  370.     private static final class InitializationCompletedMarkerException
  371.         extends RuntimeException {

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

  374.         /** Simple constructor. */
  375.         InitializationCompletedMarkerException() {
  376.             super((Throwable) null);
  377.         }
  378.     }
  379. }