001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.math3.ode.nonstiff;
019
020import org.apache.commons.math3.Field;
021import org.apache.commons.math3.RealFieldElement;
022import org.apache.commons.math3.exception.DimensionMismatchException;
023import org.apache.commons.math3.exception.MaxCountExceededException;
024import org.apache.commons.math3.exception.NoBracketingException;
025import org.apache.commons.math3.exception.NumberIsTooSmallException;
026import org.apache.commons.math3.ode.FieldEquationsMapper;
027import org.apache.commons.math3.ode.FieldExpandableODE;
028import org.apache.commons.math3.ode.FieldODEState;
029import org.apache.commons.math3.ode.FieldODEStateAndDerivative;
030import org.apache.commons.math3.util.MathArrays;
031import org.apache.commons.math3.util.MathUtils;
032
033/**
034 * This class implements the common part of all embedded Runge-Kutta
035 * integrators for Ordinary Differential Equations.
036 *
037 * <p>These methods are embedded explicit Runge-Kutta methods with two
038 * sets of coefficients allowing to estimate the error, their Butcher
039 * arrays are as follows :
040 * <pre>
041 *    0  |
042 *   c2  | a21
043 *   c3  | a31  a32
044 *   ... |        ...
045 *   cs  | as1  as2  ...  ass-1
046 *       |--------------------------
047 *       |  b1   b2  ...   bs-1  bs
048 *       |  b'1  b'2 ...   b's-1 b's
049 * </pre>
050 * </p>
051 *
052 * <p>In fact, we rather use the array defined by ej = bj - b'j to
053 * compute directly the error rather than computing two estimates and
054 * then comparing them.</p>
055 *
056 * <p>Some methods are qualified as <i>fsal</i> (first same as last)
057 * methods. This means the last evaluation of the derivatives in one
058 * step is the same as the first in the next step. Then, this
059 * evaluation can be reused from one step to the next one and the cost
060 * of such a method is really s-1 evaluations despite the method still
061 * has s stages. This behaviour is true only for successful steps, if
062 * the step is rejected after the error estimation phase, no
063 * evaluation is saved. For an <i>fsal</i> method, we have cs = 1 and
064 * asi = bi for all i.</p>
065 *
066 * @param <T> the type of the field elements
067 * @since 3.6
068 */
069
070public abstract class EmbeddedRungeKuttaFieldIntegrator<T extends RealFieldElement<T>>
071    extends AdaptiveStepsizeFieldIntegrator<T>
072    implements FieldButcherArrayProvider<T> {
073
074    /** Index of the pre-computed derivative for <i>fsal</i> methods. */
075    private final int fsal;
076
077    /** Time steps from Butcher array (without the first zero). */
078    private final T[] c;
079
080    /** Internal weights from Butcher array (without the first empty row). */
081    private final T[][] a;
082
083    /** External weights for the high order method from Butcher array. */
084    private final T[] b;
085
086    /** Stepsize control exponent. */
087    private final T exp;
088
089    /** Safety factor for stepsize control. */
090    private T safety;
091
092    /** Minimal reduction factor for stepsize control. */
093    private T minReduction;
094
095    /** Maximal growth factor for stepsize control. */
096    private T maxGrowth;
097
098    /** Build a Runge-Kutta integrator with the given Butcher array.
099     * @param field field to which the time and state vector elements belong
100     * @param name name of the method
101     * @param fsal index of the pre-computed derivative for <i>fsal</i> methods
102     * or -1 if method is not <i>fsal</i>
103     * @param minStep minimal step (sign is irrelevant, regardless of
104     * integration direction, forward or backward), the last step can
105     * be smaller than this
106     * @param maxStep maximal step (sign is irrelevant, regardless of
107     * integration direction, forward or backward), the last step can
108     * be smaller than this
109     * @param scalAbsoluteTolerance allowed absolute error
110     * @param scalRelativeTolerance allowed relative error
111     */
112    protected EmbeddedRungeKuttaFieldIntegrator(final Field<T> field, final String name, final int fsal,
113                                                final double minStep, final double maxStep,
114                                                final double scalAbsoluteTolerance,
115                                                final double scalRelativeTolerance) {
116
117        super(field, name, minStep, maxStep, scalAbsoluteTolerance, scalRelativeTolerance);
118
119        this.fsal = fsal;
120        this.c    = getC();
121        this.a    = getA();
122        this.b    = getB();
123
124        exp = field.getOne().divide(-getOrder());
125
126        // set the default values of the algorithm control parameters
127        setSafety(field.getZero().add(0.9));
128        setMinReduction(field.getZero().add(0.2));
129        setMaxGrowth(field.getZero().add(10.0));
130
131    }
132
133    /** Build a Runge-Kutta integrator with the given Butcher array.
134     * @param field field to which the time and state vector elements belong
135     * @param name name of the method
136     * @param fsal index of the pre-computed derivative for <i>fsal</i> methods
137     * or -1 if method is not <i>fsal</i>
138     * @param minStep minimal step (must be positive even for backward
139     * integration), the last step can be smaller than this
140     * @param maxStep maximal step (must be positive even for backward
141     * integration)
142     * @param vecAbsoluteTolerance allowed absolute error
143     * @param vecRelativeTolerance allowed relative error
144     */
145    protected EmbeddedRungeKuttaFieldIntegrator(final Field<T> field, final String name, final int fsal,
146                                                final double   minStep, final double maxStep,
147                                                final double[] vecAbsoluteTolerance,
148                                                final double[] vecRelativeTolerance) {
149
150        super(field, name, minStep, maxStep, vecAbsoluteTolerance, vecRelativeTolerance);
151
152        this.fsal = fsal;
153        this.c    = getC();
154        this.a    = getA();
155        this.b    = getB();
156
157        exp = field.getOne().divide(-getOrder());
158
159        // set the default values of the algorithm control parameters
160        setSafety(field.getZero().add(0.9));
161        setMinReduction(field.getZero().add(0.2));
162        setMaxGrowth(field.getZero().add(10.0));
163
164    }
165
166    /** Create a fraction.
167     * @param p numerator
168     * @param q denominator
169     * @return p/q computed in the instance field
170     */
171    protected T fraction(final int p, final int q) {
172        return getField().getOne().multiply(p).divide(q);
173    }
174
175    /** Create a fraction.
176     * @param p numerator
177     * @param q denominator
178     * @return p/q computed in the instance field
179     */
180    protected T fraction(final double p, final double q) {
181        return getField().getOne().multiply(p).divide(q);
182    }
183
184    /** Create an interpolator.
185     * @param forward integration direction indicator
186     * @param yDotK slopes at the intermediate points
187     * @param globalPreviousState start of the global step
188     * @param globalCurrentState end of the global step
189     * @param mapper equations mapper for the all equations
190     * @return external weights for the high order method from Butcher array
191     */
192    protected abstract RungeKuttaFieldStepInterpolator<T> createInterpolator(boolean forward, T[][] yDotK,
193                                                                             final FieldODEStateAndDerivative<T> globalPreviousState,
194                                                                             final FieldODEStateAndDerivative<T> globalCurrentState,
195                                                                             FieldEquationsMapper<T> mapper);
196    /** Get the order of the method.
197     * @return order of the method
198     */
199    public abstract int getOrder();
200
201    /** Get the safety factor for stepsize control.
202     * @return safety factor
203     */
204    public T getSafety() {
205        return safety;
206    }
207
208    /** Set the safety factor for stepsize control.
209     * @param safety safety factor
210     */
211    public void setSafety(final T safety) {
212        this.safety = safety;
213    }
214
215    /** {@inheritDoc} */
216    public FieldODEStateAndDerivative<T> integrate(final FieldExpandableODE<T> equations,
217                                                   final FieldODEState<T> initialState, final T finalTime)
218        throws NumberIsTooSmallException, DimensionMismatchException,
219        MaxCountExceededException, NoBracketingException {
220
221        sanityChecks(initialState, finalTime);
222        final T   t0 = initialState.getTime();
223        final T[] y0 = equations.getMapper().mapState(initialState);
224        setStepStart(initIntegration(equations, t0, y0, finalTime));
225        final boolean forward = finalTime.subtract(initialState.getTime()).getReal() > 0;
226
227        // create some internal working arrays
228        final int   stages = c.length + 1;
229        T[]         y      = y0;
230        final T[][] yDotK  = MathArrays.buildArray(getField(), stages, -1);
231        final T[]   yTmp   = MathArrays.buildArray(getField(), y0.length);
232
233        // set up integration control objects
234        T  hNew           = getField().getZero();
235        boolean firstTime = true;
236
237        // main integration loop
238        setIsLastStep(false);
239        do {
240
241            // iterate over step size, ensuring local normalized error is smaller than 1
242            T error = getField().getZero().add(10);
243            while (error.subtract(1.0).getReal() >= 0) {
244
245                // first stage
246                y        = equations.getMapper().mapState(getStepStart());
247                yDotK[0] = equations.getMapper().mapDerivative(getStepStart());
248
249                if (firstTime) {
250                    final T[] scale = MathArrays.buildArray(getField(), mainSetDimension);
251                    if (vecAbsoluteTolerance == null) {
252                        for (int i = 0; i < scale.length; ++i) {
253                            scale[i] = y[i].abs().multiply(scalRelativeTolerance).add(scalAbsoluteTolerance);
254                        }
255                    } else {
256                        for (int i = 0; i < scale.length; ++i) {
257                            scale[i] = y[i].abs().multiply(vecRelativeTolerance[i]).add(vecAbsoluteTolerance[i]);
258                        }
259                    }
260                    hNew = initializeStep(forward, getOrder(), scale, getStepStart(), equations.getMapper());
261                    firstTime = false;
262                }
263
264                setStepSize(hNew);
265                if (forward) {
266                    if (getStepStart().getTime().add(getStepSize()).subtract(finalTime).getReal() >= 0) {
267                        setStepSize(finalTime.subtract(getStepStart().getTime()));
268                    }
269                } else {
270                    if (getStepStart().getTime().add(getStepSize()).subtract(finalTime).getReal() <= 0) {
271                        setStepSize(finalTime.subtract(getStepStart().getTime()));
272                    }
273                }
274
275                // next stages
276                for (int k = 1; k < stages; ++k) {
277
278                    for (int j = 0; j < y0.length; ++j) {
279                        T sum = yDotK[0][j].multiply(a[k-1][0]);
280                        for (int l = 1; l < k; ++l) {
281                            sum = sum.add(yDotK[l][j].multiply(a[k-1][l]));
282                        }
283                        yTmp[j] = y[j].add(getStepSize().multiply(sum));
284                    }
285
286                    yDotK[k] = computeDerivatives(getStepStart().getTime().add(getStepSize().multiply(c[k-1])), yTmp);
287
288                }
289
290                // estimate the state at the end of the step
291                for (int j = 0; j < y0.length; ++j) {
292                    T sum    = yDotK[0][j].multiply(b[0]);
293                    for (int l = 1; l < stages; ++l) {
294                        sum = sum.add(yDotK[l][j].multiply(b[l]));
295                    }
296                    yTmp[j] = y[j].add(getStepSize().multiply(sum));
297                }
298
299                // estimate the error at the end of the step
300                error = estimateError(yDotK, y, yTmp, getStepSize());
301                if (error.subtract(1.0).getReal() >= 0) {
302                    // reject the step and attempt to reduce error by stepsize control
303                    final T factor = MathUtils.min(maxGrowth,
304                                                   MathUtils.max(minReduction, safety.multiply(error.pow(exp))));
305                    hNew = filterStep(getStepSize().multiply(factor), forward, false);
306                }
307
308            }
309            final T   stepEnd = getStepStart().getTime().add(getStepSize());
310            final T[] yDotTmp = (fsal >= 0) ? yDotK[fsal] : computeDerivatives(stepEnd, yTmp);
311            final FieldODEStateAndDerivative<T> stateTmp = new FieldODEStateAndDerivative<T>(stepEnd, yTmp, yDotTmp);
312
313            // local error is small enough: accept the step, trigger events and step handlers
314            System.arraycopy(yTmp, 0, y, 0, y0.length);
315            setStepStart(acceptStep(createInterpolator(forward, yDotK, getStepStart(), stateTmp, equations.getMapper()),
316                                    finalTime));
317
318            if (!isLastStep()) {
319
320                // stepsize control for next step
321                final T factor = MathUtils.min(maxGrowth,
322                                               MathUtils.max(minReduction, safety.multiply(error.pow(exp))));
323                final T  scaledH    = getStepSize().multiply(factor);
324                final T  nextT      = getStepStart().getTime().add(scaledH);
325                final boolean nextIsLast = forward ?
326                                           nextT.subtract(finalTime).getReal() >= 0 :
327                                           nextT.subtract(finalTime).getReal() <= 0;
328                hNew = filterStep(scaledH, forward, nextIsLast);
329
330                final T  filteredNextT      = getStepStart().getTime().add(hNew);
331                final boolean filteredNextIsLast = forward ?
332                                                   filteredNextT.subtract(finalTime).getReal() >= 0 :
333                                                   filteredNextT.subtract(finalTime).getReal() <= 0;
334                if (filteredNextIsLast) {
335                    hNew = finalTime.subtract(getStepStart().getTime());
336                }
337
338            }
339
340        } while (!isLastStep());
341
342        final FieldODEStateAndDerivative<T> finalState = getStepStart();
343        resetInternalState();
344        return finalState;
345
346    }
347
348    /** Get the minimal reduction factor for stepsize control.
349     * @return minimal reduction factor
350     */
351    public T getMinReduction() {
352        return minReduction;
353    }
354
355    /** Set the minimal reduction factor for stepsize control.
356     * @param minReduction minimal reduction factor
357     */
358    public void setMinReduction(final T minReduction) {
359        this.minReduction = minReduction;
360    }
361
362    /** Get the maximal growth factor for stepsize control.
363     * @return maximal growth factor
364     */
365    public T getMaxGrowth() {
366        return maxGrowth;
367    }
368
369    /** Set the maximal growth factor for stepsize control.
370     * @param maxGrowth maximal growth factor
371     */
372    public void setMaxGrowth(final T maxGrowth) {
373        this.maxGrowth = maxGrowth;
374    }
375
376    /** Compute the error ratio.
377     * @param yDotK derivatives computed during the first stages
378     * @param y0 estimate of the step at the start of the step
379     * @param y1 estimate of the step at the end of the step
380     * @param h  current step
381     * @return error ratio, greater than 1 if step should be rejected
382     */
383    protected abstract T estimateError(T[][] yDotK, T[] y0, T[] y1, T h);
384
385}