AdaptiveStepsizeFieldIntegrator.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 org.hipparchus.CalculusFieldElement;
  23. import org.hipparchus.Field;
  24. import org.hipparchus.exception.MathIllegalArgumentException;
  25. import org.hipparchus.exception.MathIllegalStateException;
  26. import org.hipparchus.ode.AbstractFieldIntegrator;
  27. import org.hipparchus.ode.FieldODEState;
  28. import org.hipparchus.ode.FieldODEStateAndDerivative;
  29. import org.hipparchus.util.FastMath;
  30. import org.hipparchus.util.MathArrays;

  31. /**
  32.  * This abstract class holds the common part of all adaptive
  33.  * stepsize integrators for Ordinary Differential Equations.
  34.  *
  35.  * <p>These algorithms perform integration with stepsize control, which
  36.  * means the user does not specify the integration step but rather a
  37.  * tolerance on error. The error threshold is computed as
  38.  * </p>
  39.  * <pre>
  40.  * threshold_i = absTol_i + relTol_i * max (abs (ym), abs (ym+1))
  41.  * </pre>
  42.  * <p>
  43.  * where absTol_i is the absolute tolerance for component i of the
  44.  * state vector and relTol_i is the relative tolerance for the same
  45.  * component. The user can also use only two scalar values absTol and
  46.  * relTol which will be used for all components.
  47.  * </p>
  48.  * <p>
  49.  * Note that <em>only</em> the {@link FieldODEState#getPrimaryState() main part}
  50.  * of the state vector is used for stepsize control. The {@link
  51.  * FieldODEState#getSecondaryState(int) secondary parts} of the state
  52.  * vector are explicitly ignored for stepsize control.
  53.  * </p>
  54.  *
  55.  * <p>If the estimated error for ym+1 is such that</p>
  56.  * <pre>
  57.  * sqrt((sum (errEst_i / threshold_i)^2 ) / n) &lt; 1
  58.  * </pre>
  59.  *
  60.  * <p>(where n is the main set dimension) then the step is accepted,
  61.  * otherwise the step is rejected and a new attempt is made with a new
  62.  * stepsize.</p>
  63.  *
  64.  * @param <T> the type of the field elements
  65.  *
  66.  */

  67. public abstract class AdaptiveStepsizeFieldIntegrator<T extends CalculusFieldElement<T>>
  68.     extends AbstractFieldIntegrator<T> {

  69.     /** Helper for step size control. */
  70.     private StepsizeHelper stepsizeHelper;

  71.     /** Build an integrator with the given stepsize bounds.
  72.      * The default step handler does nothing.
  73.      * @param field field to which the time and state vector elements belong
  74.      * @param name name of the method
  75.      * @param minStep minimal step (sign is irrelevant, regardless of
  76.      * integration direction, forward or backward), the last step can
  77.      * be smaller than this
  78.      * @param maxStep maximal step (sign is irrelevant, regardless of
  79.      * integration direction, forward or backward), the last step can
  80.      * be smaller than this
  81.      * @param scalAbsoluteTolerance allowed absolute error
  82.      * @param scalRelativeTolerance allowed relative error
  83.      */
  84.     protected AdaptiveStepsizeFieldIntegrator(final Field<T> field, final String name,
  85.                                               final double minStep, final double maxStep,
  86.                                               final double scalAbsoluteTolerance,
  87.                                               final double scalRelativeTolerance) {
  88.         super(field, name);
  89.         stepsizeHelper = new StepsizeHelper(minStep, maxStep, scalAbsoluteTolerance, scalRelativeTolerance);
  90.         resetInternalState();
  91.     }

  92.     /** Build an integrator with the given stepsize bounds.
  93.      * The default step handler does nothing.
  94.      * @param field field to which the time and state vector elements belong
  95.      * @param name name of the method
  96.      * @param minStep minimal step (sign is irrelevant, regardless of
  97.      * integration direction, forward or backward), the last step can
  98.      * be smaller than this
  99.      * @param maxStep maximal step (sign is irrelevant, regardless of
  100.      * integration direction, forward or backward), the last step can
  101.      * be smaller than this
  102.      * @param vecAbsoluteTolerance allowed absolute error
  103.      * @param vecRelativeTolerance allowed relative error
  104.      */
  105.     protected AdaptiveStepsizeFieldIntegrator(final Field<T> field, final String name,
  106.                                               final double minStep, final double maxStep,
  107.                                               final double[] vecAbsoluteTolerance,
  108.                                               final double[] vecRelativeTolerance) {
  109.         super(field, name);
  110.         stepsizeHelper = new StepsizeHelper(minStep, maxStep, vecAbsoluteTolerance, vecRelativeTolerance);
  111.         resetInternalState();
  112.     }

  113.     /** Set the adaptive step size control parameters.
  114.      * <p>
  115.      * A side effect of this method is to also reset the initial
  116.      * step so it will be automatically computed by the integrator
  117.      * if {@link #setInitialStepSize(double) setInitialStepSize}
  118.      * is not called by the user.
  119.      * </p>
  120.      * @param minimalStep minimal step (must be positive even for backward
  121.      * integration), the last step can be smaller than this
  122.      * @param maximalStep maximal step (must be positive even for backward
  123.      * integration)
  124.      * @param absoluteTolerance allowed absolute error
  125.      * @param relativeTolerance allowed relative error
  126.      */
  127.     public void setStepSizeControl(final double minimalStep, final double maximalStep,
  128.                                    final double absoluteTolerance, final double relativeTolerance) {
  129.         stepsizeHelper = new StepsizeHelper(minimalStep, maximalStep, absoluteTolerance, relativeTolerance);
  130.     }

  131.     /** Set the adaptive step size control parameters.
  132.      * <p>
  133.      * A side effect of this method is to also reset the initial
  134.      * step so it will be automatically computed by the integrator
  135.      * if {@link #setInitialStepSize(double) setInitialStepSize}
  136.      * is not called by the user.
  137.      * </p>
  138.      * @param minimalStep minimal step (must be positive even for backward
  139.      * integration), the last step can be smaller than this
  140.      * @param maximalStep maximal step (must be positive even for backward
  141.      * integration)
  142.      * @param absoluteTolerance allowed absolute error
  143.      * @param relativeTolerance allowed relative error
  144.      */
  145.     public void setStepSizeControl(final double minimalStep, final double maximalStep,
  146.                                    final double[] absoluteTolerance,
  147.                                    final double[] relativeTolerance) {
  148.         stepsizeHelper = new StepsizeHelper(minimalStep, maximalStep, absoluteTolerance, relativeTolerance);
  149.     }

  150.     /** Get the stepsize helper.
  151.      * @return stepsize helper
  152.      * @since 2.0
  153.      */
  154.     protected StepsizeHelper getStepSizeHelper() {
  155.         return stepsizeHelper;
  156.     }

  157.     /** Set the initial step size.
  158.      * <p>This method allows the user to specify an initial positive
  159.      * step size instead of letting the integrator guess it by
  160.      * itself. If this method is not called before integration is
  161.      * started, the initial step size will be estimated by the
  162.      * integrator.</p>
  163.      * @param initialStepSize initial step size to use (must be positive even
  164.      * for backward integration ; providing a negative value or a value
  165.      * outside of the min/max step interval will lead the integrator to
  166.      * ignore the value and compute the initial step size by itself)
  167.      */
  168.     public void setInitialStepSize(final double initialStepSize) {
  169.         stepsizeHelper.setInitialStepSize(initialStepSize);
  170.     }

  171.     /** {@inheritDoc} */
  172.     @Override
  173.     protected void sanityChecks(final FieldODEState<T> initialState, final T t)
  174.         throws MathIllegalArgumentException {
  175.         super.sanityChecks(initialState, t);
  176.         stepsizeHelper.setMainSetDimension(initialState.getPrimaryStateDimension());
  177.     }

  178.     /** Initialize the integration step.
  179.      * @param forward forward integration indicator
  180.      * @param order order of the method
  181.      * @param scale scaling vector for the state vector (can be shorter than state vector)
  182.      * @param state0 state at integration start time
  183.      * @return first integration step
  184.      * @exception MathIllegalStateException if the number of functions evaluations is exceeded
  185.      * @exception MathIllegalArgumentException if arrays dimensions do not match equations settings
  186.      */
  187.     public double initializeStep(final boolean forward, final int order, final T[] scale,
  188.                                  final FieldODEStateAndDerivative<T> state0)
  189.         throws MathIllegalArgumentException, MathIllegalStateException {

  190.         if (stepsizeHelper.getInitialStep() > 0) {
  191.             // use the user provided value
  192.             return forward ? stepsizeHelper.getInitialStep() : -stepsizeHelper.getInitialStep();
  193.         }

  194.         // very rough first guess : h = 0.01 * ||y/scale|| / ||y'/scale||
  195.         // this guess will be used to perform an Euler step
  196.         final T[] y0    = state0.getCompleteState();
  197.         final T[] yDot0 = state0.getCompleteDerivative();
  198.         double yOnScale2     = 0;
  199.         double yDotOnScale2  = 0;
  200.         for (int j = 0; j < scale.length; ++j) {
  201.             final double ratio    = y0[j].getReal() / scale[j].getReal();
  202.             yOnScale2            += ratio * ratio;
  203.             final double ratioDot = yDot0[j].getReal() / scale[j].getReal();
  204.             yDotOnScale2         += ratioDot * ratioDot;
  205.         }

  206.         double h = ((yOnScale2 < 1.0e-10) || (yDotOnScale2 < 1.0e-10)) ?
  207.                    1.0e-6 : (0.01 * FastMath.sqrt(yOnScale2 / yDotOnScale2));
  208.         if (h > getMaxStep()) {
  209.             h = getMaxStep();
  210.         }
  211.         if (! forward) {
  212.             h = -h;
  213.         }

  214.         // perform an Euler step using the preceding rough guess
  215.         final T[] y1 = MathArrays.buildArray(getField(), y0.length);
  216.         for (int j = 0; j < y0.length; ++j) {
  217.             y1[j] = y0[j].add(yDot0[j].multiply(h));
  218.         }
  219.         final T[] yDot1 = computeDerivatives(state0.getTime().add(h), y1);

  220.         // estimate the second derivative of the solution
  221.         double yDDotOnScale = 0;
  222.         for (int j = 0; j < scale.length; ++j) {
  223.             final double ratioDotDot = (yDot1[j].getReal() - yDot0[j].getReal()) / scale[j].getReal();
  224.             yDDotOnScale += ratioDotDot * ratioDotDot;
  225.         }
  226.         yDDotOnScale = FastMath.sqrt(yDDotOnScale) / h;

  227.         // step size is computed such that
  228.         // h^order * max (||y'/tol||, ||y''/tol||) = 0.01
  229.         final double maxInv2 = FastMath.max(FastMath.sqrt(yDotOnScale2), yDDotOnScale);
  230.         final double h1 = (maxInv2 < 1.0e-15) ?
  231.                           FastMath.max(1.0e-6, 0.001 * FastMath.abs(h)) :
  232.                           FastMath.pow(0.01 / maxInv2, 1.0 / order);
  233.         h = FastMath.min(100.0 * FastMath.abs(h), h1);
  234.         h = FastMath.max(h, 1.0e-12 * FastMath.abs(state0.getTime().getReal()));  // avoids cancellation when computing t1 - t0
  235.         if (h < getMinStep()) {
  236.             h = getMinStep();
  237.         }
  238.         if (h > getMaxStep()) {
  239.             h = getMaxStep();
  240.         }

  241.         if (! forward) {
  242.             h = -h;
  243.         }

  244.         return h;

  245.     }

  246.     /** Reset internal state to dummy values. */
  247.     protected void resetInternalState() {
  248.         setStepStart(null);
  249.         setStepSize(getField().getZero().add(stepsizeHelper.getDummyStepsize()));
  250.     }

  251.     /** Get the minimal step.
  252.      * @return minimal step
  253.      */
  254.     public double getMinStep() {
  255.         return stepsizeHelper.getMinStep();
  256.     }

  257.     /** Get the maximal step.
  258.      * @return maximal step
  259.      */
  260.     public double getMaxStep() {
  261.         return stepsizeHelper.getMaxStep();
  262.     }

  263. }