View Javadoc
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  /*
19   * This is not the original file distributed by the Apache Software Foundation
20   * It has been modified by the Hipparchus project
21   */
22  
23  package org.hipparchus.ode.nonstiff;
24  
25  import java.util.Arrays;
26  
27  import org.hipparchus.Field;
28  import org.hipparchus.CalculusFieldElement;
29  import org.hipparchus.exception.MathIllegalArgumentException;
30  import org.hipparchus.exception.MathIllegalStateException;
31  import org.hipparchus.linear.Array2DRowFieldMatrix;
32  import org.hipparchus.linear.FieldMatrix;
33  import org.hipparchus.linear.FieldMatrixPreservingVisitor;
34  import org.hipparchus.ode.FieldEquationsMapper;
35  import org.hipparchus.ode.FieldODEStateAndDerivative;
36  import org.hipparchus.ode.LocalizedODEFormats;
37  import org.hipparchus.ode.nonstiff.interpolators.AdamsFieldStateInterpolator;
38  import org.hipparchus.util.MathArrays;
39  import org.hipparchus.util.MathUtils;
40  
41  
42  /**
43   * This class implements implicit Adams-Moulton integrators for Ordinary
44   * Differential Equations.
45   *
46   * <p>Adams-Moulton methods (in fact due to Adams alone) are implicit
47   * multistep ODE solvers. This implementation is a variation of the classical
48   * one: it uses adaptive stepsize to implement error control, whereas
49   * classical implementations are fixed step size. The value of state vector
50   * at step n+1 is a simple combination of the value at step n and of the
51   * derivatives at steps n+1, n, n-1 ... Since y'<sub>n+1</sub> is needed to
52   * compute y<sub>n+1</sub>, another method must be used to compute a first
53   * estimate of y<sub>n+1</sub>, then compute y'<sub>n+1</sub>, then compute
54   * a final estimate of y<sub>n+1</sub> using the following formulas. Depending
55   * on the number k of previous steps one wants to use for computing the next
56   * value, different formulas are available for the final estimate:</p>
57   * <ul>
58   *   <li>k = 1: y<sub>n+1</sub> = y<sub>n</sub> + h y'<sub>n+1</sub></li>
59   *   <li>k = 2: y<sub>n+1</sub> = y<sub>n</sub> + h (y'<sub>n+1</sub>+y'<sub>n</sub>)/2</li>
60   *   <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>
61   *   <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>
62   *   <li>...</li>
63   * </ul>
64   *
65   * <p>A k-steps Adams-Moulton method is of order k+1.</p>
66   *
67   * <p> There must be sufficient time for the {@link #setStarterIntegrator(org.hipparchus.ode.FieldODEIntegrator)
68   * starter integrator} to take several steps between the the last reset event, and the end
69   * of integration, otherwise an exception may be thrown during integration. The user can
70   * adjust the end date of integration, or the step size of the starter integrator to
71   * ensure a sufficient number of steps can be completed before the end of integration.
72   * </p>
73   *
74   * <p><strong>Implementation details</strong></p>
75   *
76   * <p>We define scaled derivatives s<sub>i</sub>(n) at step n as:
77   * \[
78   *   \left\{\begin{align}
79   *   s_1(n) &amp;= h y'_n \text{ for first derivative}\\
80   *   s_2(n) &amp;= \frac{h^2}{2} y_n'' \text{ for second derivative}\\
81   *   s_3(n) &amp;= \frac{h^3}{6} y_n''' \text{ for third derivative}\\
82   *   &amp;\cdots\\
83   *   s_k(n) &amp;= \frac{h^k}{k!} y_n^{(k)} \text{ for } k^\mathrm{th} \text{ derivative}
84   *   \end{align}\right.
85   * \]</p>
86   *
87   * <p>The definitions above use the classical representation with several previous first
88   * derivatives. Lets define
89   * \[
90   *   q_n = [ s_1(n-1) s_1(n-2) \ldots s_1(n-(k-1)) ]^T
91   * \]
92   * (we omit the k index in the notation for clarity). With these definitions,
93   * Adams-Moulton methods can be written:</p>
94   * <ul>
95   *   <li>k = 1: y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n+1)</li>
96   *   <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>
97   *   <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>
98   *   <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>
99   *   <li>...</li>
100  * </ul>
101  *
102  * <p>Instead of using the classical representation with first derivatives only (y<sub>n</sub>,
103  * s<sub>1</sub>(n+1) and q<sub>n+1</sub>), our implementation uses the Nordsieck vector with
104  * higher degrees scaled derivatives all taken at the same step (y<sub>n</sub>, s<sub>1</sub>(n)
105  * and r<sub>n</sub>) where r<sub>n</sub> is defined as:
106  * \[
107  * r_n = [ s_2(n), s_3(n) \ldots s_k(n) ]^T
108  * \]
109  * (here again we omit the k index in the notation for clarity)
110  * </p>
111  *
112  * <p>Taylor series formulas show that for any index offset i, s<sub>1</sub>(n-i) can be
113  * computed from s<sub>1</sub>(n), s<sub>2</sub>(n) ... s<sub>k</sub>(n), the formula being exact
114  * for degree k polynomials.
115  * \[
116  * s_1(n-i) = s_1(n) + \sum_{j\gt 0} (j+1) (-i)^j s_{j+1}(n)
117  * \]
118  * The previous formula can be used with several values for i to compute the transform between
119  * classical representation and Nordsieck vector. The transform between r<sub>n</sub>
120  * and q<sub>n</sub> resulting from the Taylor series formulas above is:
121  * \[
122  * q_n = s_1(n) u + P r_n
123  * \]
124  * where u is the [ 1 1 ... 1 ]<sup>T</sup> vector and P is the (k-1)&times;(k-1) matrix built
125  * with the \((j+1) (-i)^j\) terms with i being the row number starting from 1 and j being
126  * the column number starting from 1:
127  * \[
128  *   P=\begin{bmatrix}
129  *   -2  &amp;  3 &amp;   -4 &amp;    5 &amp; \ldots \\
130  *   -4  &amp; 12 &amp;  -32 &amp;   80 &amp; \ldots \\
131  *   -6  &amp; 27 &amp; -108 &amp;  405 &amp; \ldots \\
132  *   -8  &amp; 48 &amp; -256 &amp; 1280 &amp; \ldots \\
133  *       &amp;    &amp;  \ldots\\
134  *    \end{bmatrix}
135  * \]
136  *
137  * <p>Using the Nordsieck vector has several advantages:</p>
138  * <ul>
139  *   <li>it greatly simplifies step interpolation as the interpolator mainly applies
140  *   Taylor series formulas,</li>
141  *   <li>it simplifies step changes that occur when discrete events that truncate
142  *   the step are triggered,</li>
143  *   <li>it allows to extend the methods in order to support adaptive stepsize.</li>
144  * </ul>
145  *
146  * <p>The predicted Nordsieck vector at step n+1 is computed from the Nordsieck vector at step
147  * n as follows:
148  * <ul>
149  *   <li>Y<sub>n+1</sub> = y<sub>n</sub> + s<sub>1</sub>(n) + u<sup>T</sup> r<sub>n</sub></li>
150  *   <li>S<sub>1</sub>(n+1) = h f(t<sub>n+1</sub>, Y<sub>n+1</sub>)</li>
151  *   <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>
152  * </ul>
153  * where A is a rows shifting matrix (the lower left part is an identity matrix):
154  * <pre>
155  *        [ 0 0   ...  0 0 | 0 ]
156  *        [ ---------------+---]
157  *        [ 1 0   ...  0 0 | 0 ]
158  *    A = [ 0 1   ...  0 0 | 0 ]
159  *        [       ...      | 0 ]
160  *        [ 0 0   ...  1 0 | 0 ]
161  *        [ 0 0   ...  0 1 | 0 ]
162  * </pre>
163  * From this predicted vector, the corrected vector is computed as follows:
164  * <ul>
165  *   <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>
166  *   <li>s<sub>1</sub>(n+1) = h f(t<sub>n+1</sub>, y<sub>n+1</sub>)</li>
167  *   <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>
168  * </ul>
169  * <p>where the upper case Y<sub>n+1</sub>, S<sub>1</sub>(n+1) and R<sub>n+1</sub> represent the
170  * predicted states whereas the lower case y<sub>n+1</sub>, s<sub>n+1</sub> and r<sub>n+1</sub>
171  * represent the corrected states.</p>
172  *
173  * <p>The P<sup>-1</sup>u vector and the P<sup>-1</sup> A P matrix do not depend on the state,
174  * they only depend on k and therefore are precomputed once for all.</p>
175  *
176  * @param <T> the type of the field elements
177  */
178 public class AdamsMoultonFieldIntegrator<T extends CalculusFieldElement<T>> extends AdamsFieldIntegrator<T> {
179 
180     /** Name of integration scheme. */
181     public static final String METHOD_NAME = AdamsMoultonIntegrator.METHOD_NAME;
182 
183     /**
184      * Build an Adams-Moulton integrator with the given order and error control parameters.
185      * @param field field to which the time and state vector elements belong
186      * @param nSteps number of steps of the method excluding the one being computed
187      * @param minStep minimal step (sign is irrelevant, regardless of
188      * integration direction, forward or backward), the last step can
189      * be smaller than this
190      * @param maxStep maximal step (sign is irrelevant, regardless of
191      * integration direction, forward or backward), the last step can
192      * be smaller than this
193      * @param scalAbsoluteTolerance allowed absolute error
194      * @param scalRelativeTolerance allowed relative error
195      * @exception MathIllegalArgumentException if order is 1 or less
196      */
197     public AdamsMoultonFieldIntegrator(final Field<T> field, final int nSteps,
198                                        final double minStep, final double maxStep,
199                                        final double scalAbsoluteTolerance,
200                                        final double scalRelativeTolerance)
201         throws MathIllegalArgumentException {
202         super(field, METHOD_NAME, nSteps, nSteps + 1, minStep, maxStep,
203               scalAbsoluteTolerance, scalRelativeTolerance);
204     }
205 
206     /**
207      * Build an Adams-Moulton integrator with the given order and error control parameters.
208      * @param field field to which the time and state vector elements belong
209      * @param nSteps number of steps of the method excluding the one being computed
210      * @param minStep minimal step (sign is irrelevant, regardless of
211      * integration direction, forward or backward), the last step can
212      * be smaller than this
213      * @param maxStep maximal step (sign is irrelevant, regardless of
214      * integration direction, forward or backward), the last step can
215      * be smaller than this
216      * @param vecAbsoluteTolerance allowed absolute error
217      * @param vecRelativeTolerance allowed relative error
218      * @exception IllegalArgumentException if order is 1 or less
219      */
220     public AdamsMoultonFieldIntegrator(final Field<T> field, final int nSteps,
221                                        final double minStep, final double maxStep,
222                                        final double[] vecAbsoluteTolerance,
223                                        final double[] vecRelativeTolerance)
224         throws IllegalArgumentException {
225         super(field, METHOD_NAME, nSteps, nSteps + 1, minStep, maxStep,
226               vecAbsoluteTolerance, vecRelativeTolerance);
227     }
228 
229     /** {@inheritDoc} */
230     @Override
231     protected double errorEstimation(final T[] previousState, final T predictedTime,
232                                      final T[] predictedState, final T[] predictedScaled,
233                                      final FieldMatrix<T> predictedNordsieck) {
234         final double error = predictedNordsieck.walkInOptimizedOrder(new Corrector(previousState, predictedScaled, predictedState)).getReal();
235         if (Double.isNaN(error)) {
236             throw new MathIllegalStateException(LocalizedODEFormats.NAN_APPEARING_DURING_INTEGRATION,
237                                                 predictedTime.getReal());
238         }
239         return error;
240     }
241 
242     /** {@inheritDoc} */
243     @Override
244     protected AdamsFieldStateInterpolator<T> finalizeStep(final T stepSize, final T[] predictedY,
245                                                           final T[] predictedScaled, final Array2DRowFieldMatrix<T> predictedNordsieck,
246                                                           final boolean isForward,
247                                                           final FieldODEStateAndDerivative<T> globalPreviousState,
248                                                           final FieldODEStateAndDerivative<T> globalCurrentState,
249                                                           final FieldEquationsMapper<T> equationsMapper) {
250 
251         final T[] correctedYDot = computeDerivatives(globalCurrentState.getTime(), predictedY);
252 
253         // update Nordsieck vector
254         final T[] correctedScaled = MathArrays.buildArray(getField(), predictedY.length);
255         for (int j = 0; j < correctedScaled.length; ++j) {
256             correctedScaled[j] = getStepSize().multiply(correctedYDot[j]);
257         }
258         updateHighOrderDerivativesPhase2(predictedScaled, correctedScaled, predictedNordsieck);
259 
260         final FieldODEStateAndDerivative<T> updatedStepEnd =
261                         equationsMapper.mapStateAndDerivative(globalCurrentState.getTime(), predictedY, correctedYDot);
262         return new AdamsFieldStateInterpolator<>(getStepSize(), updatedStepEnd,
263                                                           correctedScaled, predictedNordsieck, isForward,
264                                                           getStepStart(), updatedStepEnd,
265                                                           equationsMapper);
266 
267     }
268 
269     /** Corrector for current state in Adams-Moulton method.
270      * <p>
271      * This visitor implements the Taylor series formula:
272      * <pre>
273      * 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>
274      * </pre>
275      * </p>
276      */
277     private class Corrector implements FieldMatrixPreservingVisitor<T> {
278 
279         /** Previous state. */
280         private final T[] previous;
281 
282         /** Current scaled first derivative. */
283         private final T[] scaled;
284 
285         /** Current state before correction. */
286         private final T[] before;
287 
288         /** Current state after correction. */
289         private final T[] after;
290 
291         /** Simple constructor.
292          * <p>
293          * All arrays will be stored by reference to caller arrays.
294          * </p>
295          * @param previous previous state
296          * @param scaled current scaled first derivative
297          * @param state state to correct (will be overwritten after visit)
298          */
299         Corrector(final T[] previous, final T[] scaled, final T[] state) {
300             this.previous = previous; // NOPMD - array reference storage is intentional and documented here
301             this.scaled   = scaled;   // NOPMD - array reference storage is intentional and documented here
302             this.after    = state;    // NOPMD - array reference storage is intentional and documented here
303             this.before   = state.clone();
304         }
305 
306         /** {@inheritDoc} */
307         @Override
308         public void start(int rows, int columns,
309                           int startRow, int endRow, int startColumn, int endColumn) {
310             Arrays.fill(after, getField().getZero());
311         }
312 
313         /** {@inheritDoc} */
314         @Override
315         public void visit(int row, int column, T value) {
316             if ((row & 0x1) == 0) {
317                 after[column] = after[column].subtract(value);
318             } else {
319                 after[column] = after[column].add(value);
320             }
321         }
322 
323         /**
324          * End visiting the Nordsieck vector.
325          * <p>The correction is used to control stepsize. So its amplitude is
326          * considered to be an error, which must be normalized according to
327          * error control settings. If the normalized value is greater than 1,
328          * the correction was too large and the step must be rejected.</p>
329          * @return the normalized correction, if greater than 1, the step
330          * must be rejected
331          */
332         @Override
333         public T end() {
334 
335             final StepsizeHelper helper = getStepSizeHelper();
336             T error = getField().getZero();
337             for (int i = 0; i < after.length; ++i) {
338                 after[i] = after[i].add(previous[i].add(scaled[i]));
339                 if (i < helper.getMainSetDimension()) {
340                     final T tol   = helper.getTolerance(i, MathUtils.max(previous[i].abs(), after[i].abs()));
341                     final T ratio = after[i].subtract(before[i]).divide(tol); // (corrected-predicted)/tol
342                     error = error.add(ratio.multiply(ratio));
343                 }
344             }
345 
346             return error.divide(helper.getMainSetDimension()).sqrt();
347 
348         }
349     }
350 
351 }