AdamsMoultonFieldIntegrator.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 java.util.Arrays;

  23. import org.hipparchus.Field;
  24. import org.hipparchus.CalculusFieldElement;
  25. import org.hipparchus.exception.MathIllegalArgumentException;
  26. import org.hipparchus.exception.MathIllegalStateException;
  27. import org.hipparchus.linear.Array2DRowFieldMatrix;
  28. import org.hipparchus.linear.FieldMatrix;
  29. import org.hipparchus.linear.FieldMatrixPreservingVisitor;
  30. import org.hipparchus.ode.FieldEquationsMapper;
  31. import org.hipparchus.ode.FieldODEStateAndDerivative;
  32. import org.hipparchus.ode.LocalizedODEFormats;
  33. import org.hipparchus.ode.nonstiff.interpolators.AdamsFieldStateInterpolator;
  34. import org.hipparchus.util.MathArrays;
  35. import org.hipparchus.util.MathUtils;


  36. /**
  37.  * This class implements implicit Adams-Moulton integrators for Ordinary
  38.  * Differential Equations.
  39.  *
  40.  * <p>Adams-Moulton methods (in fact due to Adams alone) are implicit
  41.  * multistep ODE solvers. This implementation is a variation of the classical
  42.  * one: it uses adaptive stepsize to implement error control, whereas
  43.  * classical implementations are fixed step size. The value of state vector
  44.  * at step n+1 is a simple combination of the value at step n and of the
  45.  * derivatives at steps n+1, n, n-1 ... Since y'<sub>n+1</sub> is needed to
  46.  * compute y<sub>n+1</sub>, another method must be used to compute a first
  47.  * estimate of y<sub>n+1</sub>, then compute y'<sub>n+1</sub>, then compute
  48.  * a final estimate of y<sub>n+1</sub> using the following formulas. Depending
  49.  * on the number k of previous steps one wants to use for computing the next
  50.  * value, different formulas are available for the final estimate:</p>
  51.  * <ul>
  52.  *   <li>k = 1: y<sub>n+1</sub> = y<sub>n</sub> + h y'<sub>n+1</sub></li>
  53.  *   <li>k = 2: y<sub>n+1</sub> = y<sub>n</sub> + h (y'<sub>n+1</sub>+y'<sub>n</sub>)/2</li>
  54.  *   <li>k = 3: y<sub>n+1</sub> = y<sub>n</sub> + h (5y'<sub>n+1</sub>+8y'<sub>n</sub>-y'<sub>n-1</sub>)/12</li>
  55.  *   <li>k = 4: y<sub>n+1</sub> = y<sub>n</sub> + h (9y'<sub>n+1</sub>+19y'<sub>n</sub>-5y'<sub>n-1</sub>+y'<sub>n-2</sub>)/24</li>
  56.  *   <li>...</li>
  57.  * </ul>
  58.  *
  59.  * <p>A k-steps Adams-Moulton method is of order k+1.</p>
  60.  *
  61.  * <p> There must be sufficient time for the {@link #setStarterIntegrator(org.hipparchus.ode.FieldODEIntegrator)
  62.  * starter integrator} to take several steps between the the last reset event, and the end
  63.  * of integration, otherwise an exception may be thrown during integration. The user can
  64.  * adjust the end date of integration, or the step size of the starter integrator to
  65.  * ensure a sufficient number of steps can be completed before the end of integration.
  66.  * </p>
  67.  *
  68.  * <p><strong>Implementation details</strong></p>
  69.  *
  70.  * <p>We define scaled derivatives s<sub>i</sub>(n) at step n as:
  71.  * \[
  72.  *   \left\{\begin{align}
  73.  *   s_1(n) &amp;= h y'_n \text{ for first derivative}\\
  74.  *   s_2(n) &amp;= \frac{h^2}{2} y_n'' \text{ for second derivative}\\
  75.  *   s_3(n) &amp;= \frac{h^3}{6} y_n''' \text{ for third derivative}\\
  76.  *   &amp;\cdots\\
  77.  *   s_k(n) &amp;= \frac{h^k}{k!} y_n^{(k)} \text{ for } k^\mathrm{th} \text{ derivative}
  78.  *   \end{align}\right.
  79.  * \]</p>
  80.  *
  81.  * <p>The definitions above use the classical representation with several previous first
  82.  * derivatives. Lets define
  83.  * \[
  84.  *   q_n = [ s_1(n-1) s_1(n-2) \ldots s_1(n-(k-1)) ]^T
  85.  * \]
  86.  * (we omit the k index in the notation for clarity). With these definitions,
  87.  * Adams-Moulton methods can be written:</p>
  88.  * <ul>
  89.  *   <li>k = 1: y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n+1)</li>
  90.  *   <li>k = 2: y<sub>n+1</sub> = y<sub>n</sub> + 1/2 s<sub>1</sub>(n+1) + [ 1/2 ] q<sub>n+1</sub></li>
  91.  *   <li>k = 3: y<sub>n+1</sub> = y<sub>n</sub> + 5/12 s<sub>1</sub>(n+1) + [ 8/12 -1/12 ] q<sub>n+1</sub></li>
  92.  *   <li>k = 4: y<sub>n+1</sub> = y<sub>n</sub> + 9/24 s<sub>1</sub>(n+1) + [ 19/24 -5/24 1/24 ] q<sub>n+1</sub></li>
  93.  *   <li>...</li>
  94.  * </ul>
  95.  *
  96.  * <p>Instead of using the classical representation with first derivatives only (y<sub>n</sub>,
  97.  * s<sub>1</sub>(n+1) and q<sub>n+1</sub>), our implementation uses the Nordsieck vector with
  98.  * higher degrees scaled derivatives all taken at the same step (y<sub>n</sub>, s<sub>1</sub>(n)
  99.  * and r<sub>n</sub>) where r<sub>n</sub> is defined as:
  100.  * \[
  101.  * r_n = [ s_2(n), s_3(n) \ldots s_k(n) ]^T
  102.  * \]
  103.  * (here again we omit the k index in the notation for clarity)
  104.  * </p>
  105.  *
  106.  * <p>Taylor series formulas show that for any index offset i, s<sub>1</sub>(n-i) can be
  107.  * computed from s<sub>1</sub>(n), s<sub>2</sub>(n) ... s<sub>k</sub>(n), the formula being exact
  108.  * for degree k polynomials.
  109.  * \[
  110.  * s_1(n-i) = s_1(n) + \sum_{j\gt 0} (j+1) (-i)^j s_{j+1}(n)
  111.  * \]
  112.  * The previous formula can be used with several values for i to compute the transform between
  113.  * classical representation and Nordsieck vector. The transform between r<sub>n</sub>
  114.  * and q<sub>n</sub> resulting from the Taylor series formulas above is:
  115.  * \[
  116.  * q_n = s_1(n) u + P r_n
  117.  * \]
  118.  * where u is the [ 1 1 ... 1 ]<sup>T</sup> vector and P is the (k-1)&times;(k-1) matrix built
  119.  * with the \((j+1) (-i)^j\) terms with i being the row number starting from 1 and j being
  120.  * the column number starting from 1:
  121.  * \[
  122.  *   P=\begin{bmatrix}
  123.  *   -2  &amp;  3 &amp;   -4 &amp;    5 &amp; \ldots \\
  124.  *   -4  &amp; 12 &amp;  -32 &amp;   80 &amp; \ldots \\
  125.  *   -6  &amp; 27 &amp; -108 &amp;  405 &amp; \ldots \\
  126.  *   -8  &amp; 48 &amp; -256 &amp; 1280 &amp; \ldots \\
  127.  *       &amp;    &amp;  \ldots\\
  128.  *    \end{bmatrix}
  129.  * \]
  130.  *
  131.  * <p>Using the Nordsieck vector has several advantages:</p>
  132.  * <ul>
  133.  *   <li>it greatly simplifies step interpolation as the interpolator mainly applies
  134.  *   Taylor series formulas,</li>
  135.  *   <li>it simplifies step changes that occur when discrete events that truncate
  136.  *   the step are triggered,</li>
  137.  *   <li>it allows to extend the methods in order to support adaptive stepsize.</li>
  138.  * </ul>
  139.  *
  140.  * <p>The predicted Nordsieck vector at step n+1 is computed from the Nordsieck vector at step
  141.  * n as follows:
  142.  * <ul>
  143.  *   <li>Y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n) + u<sup>T</sup> r<sub>n</sub></li>
  144.  *   <li>S<sub>1</sub>(n+1) = h f(t<sub>n+1</sub>, Y<sub>n+1</sub>)</li>
  145.  *   <li>R<sub>n+1</sub> = (s<sub>1</sub>(n) - S<sub>1</sub>(n+1)) P<sup>-1</sup> u + P<sup>-1</sup> A P r<sub>n</sub></li>
  146.  * </ul>
  147.  * where A is a rows shifting matrix (the lower left part is an identity matrix):
  148.  * <pre>
  149.  *        [ 0 0   ...  0 0 | 0 ]
  150.  *        [ ---------------+---]
  151.  *        [ 1 0   ...  0 0 | 0 ]
  152.  *    A = [ 0 1   ...  0 0 | 0 ]
  153.  *        [       ...      | 0 ]
  154.  *        [ 0 0   ...  1 0 | 0 ]
  155.  *        [ 0 0   ...  0 1 | 0 ]
  156.  * </pre>
  157.  * From this predicted vector, the corrected vector is computed as follows:
  158.  * <ul>
  159.  *   <li>y<sub>n+1</sub> = y<sub>n</sub> + S<sub>1</sub>(n+1) + [ -1 +1 -1 +1 ... &plusmn;1 ] r<sub>n+1</sub></li>
  160.  *   <li>s<sub>1</sub>(n+1) = h f(t<sub>n+1</sub>, y<sub>n+1</sub>)</li>
  161.  *   <li>r<sub>n+1</sub> = R<sub>n+1</sub> + (s<sub>1</sub>(n+1) - S<sub>1</sub>(n+1)) P<sup>-1</sup> u</li>
  162.  * </ul>
  163.  * <p>where the upper case Y<sub>n+1</sub>, S<sub>1</sub>(n+1) and R<sub>n+1</sub> represent the
  164.  * predicted states whereas the lower case y<sub>n+1</sub>, s<sub>n+1</sub> and r<sub>n+1</sub>
  165.  * represent the corrected states.</p>
  166.  *
  167.  * <p>The P<sup>-1</sup>u vector and the P<sup>-1</sup> A P matrix do not depend on the state,
  168.  * they only depend on k and therefore are precomputed once for all.</p>
  169.  *
  170.  * @param <T> the type of the field elements
  171.  */
  172. public class AdamsMoultonFieldIntegrator<T extends CalculusFieldElement<T>> extends AdamsFieldIntegrator<T> {

  173.     /** Name of integration scheme. */
  174.     public static final String METHOD_NAME = AdamsMoultonIntegrator.METHOD_NAME;

  175.     /**
  176.      * Build an Adams-Moulton integrator with the given order and error control parameters.
  177.      * @param field field to which the time and state vector elements belong
  178.      * @param nSteps number of steps of the method excluding the one being computed
  179.      * @param minStep minimal step (sign is irrelevant, regardless of
  180.      * integration direction, forward or backward), the last step can
  181.      * be smaller than this
  182.      * @param maxStep maximal step (sign is irrelevant, regardless of
  183.      * integration direction, forward or backward), the last step can
  184.      * be smaller than this
  185.      * @param scalAbsoluteTolerance allowed absolute error
  186.      * @param scalRelativeTolerance allowed relative error
  187.      * @exception MathIllegalArgumentException if order is 1 or less
  188.      */
  189.     public AdamsMoultonFieldIntegrator(final Field<T> field, final int nSteps,
  190.                                        final double minStep, final double maxStep,
  191.                                        final double scalAbsoluteTolerance,
  192.                                        final double scalRelativeTolerance)
  193.         throws MathIllegalArgumentException {
  194.         super(field, METHOD_NAME, nSteps, nSteps + 1, minStep, maxStep,
  195.               scalAbsoluteTolerance, scalRelativeTolerance);
  196.     }

  197.     /**
  198.      * Build an Adams-Moulton integrator with the given order and error control parameters.
  199.      * @param field field to which the time and state vector elements belong
  200.      * @param nSteps number of steps of the method excluding the one being computed
  201.      * @param minStep minimal step (sign is irrelevant, regardless of
  202.      * integration direction, forward or backward), the last step can
  203.      * be smaller than this
  204.      * @param maxStep maximal step (sign is irrelevant, regardless of
  205.      * integration direction, forward or backward), the last step can
  206.      * be smaller than this
  207.      * @param vecAbsoluteTolerance allowed absolute error
  208.      * @param vecRelativeTolerance allowed relative error
  209.      * @exception IllegalArgumentException if order is 1 or less
  210.      */
  211.     public AdamsMoultonFieldIntegrator(final Field<T> field, final int nSteps,
  212.                                        final double minStep, final double maxStep,
  213.                                        final double[] vecAbsoluteTolerance,
  214.                                        final double[] vecRelativeTolerance)
  215.         throws IllegalArgumentException {
  216.         super(field, METHOD_NAME, nSteps, nSteps + 1, minStep, maxStep,
  217.               vecAbsoluteTolerance, vecRelativeTolerance);
  218.     }

  219.     /** {@inheritDoc} */
  220.     @Override
  221.     protected double errorEstimation(final T[] previousState, final T predictedTime,
  222.                                      final T[] predictedState, final T[] predictedScaled,
  223.                                      final FieldMatrix<T> predictedNordsieck) {
  224.         final double error = predictedNordsieck.walkInOptimizedOrder(new Corrector(previousState, predictedScaled, predictedState)).getReal();
  225.         if (Double.isNaN(error)) {
  226.             throw new MathIllegalStateException(LocalizedODEFormats.NAN_APPEARING_DURING_INTEGRATION,
  227.                                                 predictedTime.getReal());
  228.         }
  229.         return error;
  230.     }

  231.     /** {@inheritDoc} */
  232.     @Override
  233.     protected AdamsFieldStateInterpolator<T> finalizeStep(final T stepSize, final T[] predictedY,
  234.                                                           final T[] predictedScaled, final Array2DRowFieldMatrix<T> predictedNordsieck,
  235.                                                           final boolean isForward,
  236.                                                           final FieldODEStateAndDerivative<T> globalPreviousState,
  237.                                                           final FieldODEStateAndDerivative<T> globalCurrentState,
  238.                                                           final FieldEquationsMapper<T> equationsMapper) {

  239.         final T[] correctedYDot = computeDerivatives(globalCurrentState.getTime(), predictedY);

  240.         // update Nordsieck vector
  241.         final T[] correctedScaled = MathArrays.buildArray(getField(), predictedY.length);
  242.         for (int j = 0; j < correctedScaled.length; ++j) {
  243.             correctedScaled[j] = getStepSize().multiply(correctedYDot[j]);
  244.         }
  245.         updateHighOrderDerivativesPhase2(predictedScaled, correctedScaled, predictedNordsieck);

  246.         final FieldODEStateAndDerivative<T> updatedStepEnd =
  247.                         equationsMapper.mapStateAndDerivative(globalCurrentState.getTime(), predictedY, correctedYDot);
  248.         return new AdamsFieldStateInterpolator<>(getStepSize(), updatedStepEnd,
  249.                                                           correctedScaled, predictedNordsieck, isForward,
  250.                                                           getStepStart(), updatedStepEnd,
  251.                                                           equationsMapper);

  252.     }

  253.     /** Corrector for current state in Adams-Moulton method.
  254.      * <p>
  255.      * This visitor implements the Taylor series formula:
  256.      * <pre>
  257.      * Y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n+1) + [ -1 +1 -1 +1 ... &plusmn;1 ] r<sub>n+1</sub>
  258.      * </pre>
  259.      * </p>
  260.      */
  261.     private class Corrector implements FieldMatrixPreservingVisitor<T> {

  262.         /** Previous state. */
  263.         private final T[] previous;

  264.         /** Current scaled first derivative. */
  265.         private final T[] scaled;

  266.         /** Current state before correction. */
  267.         private final T[] before;

  268.         /** Current state after correction. */
  269.         private final T[] after;

  270.         /** Simple constructor.
  271.          * <p>
  272.          * All arrays will be stored by reference to caller arrays.
  273.          * </p>
  274.          * @param previous previous state
  275.          * @param scaled current scaled first derivative
  276.          * @param state state to correct (will be overwritten after visit)
  277.          */
  278.         Corrector(final T[] previous, final T[] scaled, final T[] state) {
  279.             this.previous = previous; // NOPMD - array reference storage is intentional and documented here
  280.             this.scaled   = scaled;   // NOPMD - array reference storage is intentional and documented here
  281.             this.after    = state;    // NOPMD - array reference storage is intentional and documented here
  282.             this.before   = state.clone();
  283.         }

  284.         /** {@inheritDoc} */
  285.         @Override
  286.         public void start(int rows, int columns,
  287.                           int startRow, int endRow, int startColumn, int endColumn) {
  288.             Arrays.fill(after, getField().getZero());
  289.         }

  290.         /** {@inheritDoc} */
  291.         @Override
  292.         public void visit(int row, int column, T value) {
  293.             if ((row & 0x1) == 0) {
  294.                 after[column] = after[column].subtract(value);
  295.             } else {
  296.                 after[column] = after[column].add(value);
  297.             }
  298.         }

  299.         /**
  300.          * End visiting the Nordsieck vector.
  301.          * <p>The correction is used to control stepsize. So its amplitude is
  302.          * considered to be an error, which must be normalized according to
  303.          * error control settings. If the normalized value is greater than 1,
  304.          * the correction was too large and the step must be rejected.</p>
  305.          * @return the normalized correction, if greater than 1, the step
  306.          * must be rejected
  307.          */
  308.         @Override
  309.         public T end() {

  310.             final StepsizeHelper helper = getStepSizeHelper();
  311.             T error = getField().getZero();
  312.             for (int i = 0; i < after.length; ++i) {
  313.                 after[i] = after[i].add(previous[i].add(scaled[i]));
  314.                 if (i < helper.getMainSetDimension()) {
  315.                     final T tol   = helper.getTolerance(i, MathUtils.max(previous[i].abs(), after[i].abs()));
  316.                     final T ratio = after[i].subtract(before[i]).divide(tol); // (corrected-predicted)/tol
  317.                     error = error.add(ratio.multiply(ratio));
  318.                 }
  319.             }

  320.             return error.divide(helper.getMainSetDimension()).sqrt();

  321.         }
  322.     }

  323. }