AbstractIntegrator.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.math3.ode;

  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.Comparator;
  22. import java.util.Iterator;
  23. import java.util.List;
  24. import java.util.SortedSet;
  25. import java.util.TreeSet;

  26. import org.apache.commons.math3.analysis.solvers.BracketingNthOrderBrentSolver;
  27. import org.apache.commons.math3.analysis.solvers.UnivariateSolver;
  28. import org.apache.commons.math3.exception.DimensionMismatchException;
  29. import org.apache.commons.math3.exception.MaxCountExceededException;
  30. import org.apache.commons.math3.exception.NoBracketingException;
  31. import org.apache.commons.math3.exception.NumberIsTooSmallException;
  32. import org.apache.commons.math3.exception.util.LocalizedFormats;
  33. import org.apache.commons.math3.ode.events.EventHandler;
  34. import org.apache.commons.math3.ode.events.EventState;
  35. import org.apache.commons.math3.ode.sampling.AbstractStepInterpolator;
  36. import org.apache.commons.math3.ode.sampling.StepHandler;
  37. import org.apache.commons.math3.util.FastMath;
  38. import org.apache.commons.math3.util.Incrementor;
  39. import org.apache.commons.math3.util.Precision;

  40. /**
  41.  * Base class managing common boilerplate for all integrators.
  42.  * @since 2.0
  43.  */
  44. public abstract class AbstractIntegrator implements FirstOrderIntegrator {

  45.     /** Step handler. */
  46.     protected Collection<StepHandler> stepHandlers;

  47.     /** Current step start time. */
  48.     protected double stepStart;

  49.     /** Current stepsize. */
  50.     protected double stepSize;

  51.     /** Indicator for last step. */
  52.     protected boolean isLastStep;

  53.     /** Indicator that a state or derivative reset was triggered by some event. */
  54.     protected boolean resetOccurred;

  55.     /** Events states. */
  56.     private Collection<EventState> eventsStates;

  57.     /** Initialization indicator of events states. */
  58.     private boolean statesInitialized;

  59.     /** Name of the method. */
  60.     private final String name;

  61.     /** Counter for number of evaluations. */
  62.     private Incrementor evaluations;

  63.     /** Differential equations to integrate. */
  64.     private transient ExpandableStatefulODE expandable;

  65.     /** Build an instance.
  66.      * @param name name of the method
  67.      */
  68.     public AbstractIntegrator(final String name) {
  69.         this.name = name;
  70.         stepHandlers = new ArrayList<StepHandler>();
  71.         stepStart = Double.NaN;
  72.         stepSize  = Double.NaN;
  73.         eventsStates = new ArrayList<EventState>();
  74.         statesInitialized = false;
  75.         evaluations = new Incrementor();
  76.         setMaxEvaluations(-1);
  77.         evaluations.resetCount();
  78.     }

  79.     /** Build an instance with a null name.
  80.      */
  81.     protected AbstractIntegrator() {
  82.         this(null);
  83.     }

  84.     /** {@inheritDoc} */
  85.     public String getName() {
  86.         return name;
  87.     }

  88.     /** {@inheritDoc} */
  89.     public void addStepHandler(final StepHandler handler) {
  90.         stepHandlers.add(handler);
  91.     }

  92.     /** {@inheritDoc} */
  93.     public Collection<StepHandler> getStepHandlers() {
  94.         return Collections.unmodifiableCollection(stepHandlers);
  95.     }

  96.     /** {@inheritDoc} */
  97.     public void clearStepHandlers() {
  98.         stepHandlers.clear();
  99.     }

  100.     /** {@inheritDoc} */
  101.     public void addEventHandler(final EventHandler handler,
  102.                                 final double maxCheckInterval,
  103.                                 final double convergence,
  104.                                 final int maxIterationCount) {
  105.         addEventHandler(handler, maxCheckInterval, convergence,
  106.                         maxIterationCount,
  107.                         new BracketingNthOrderBrentSolver(convergence, 5));
  108.     }

  109.     /** {@inheritDoc} */
  110.     public void addEventHandler(final EventHandler handler,
  111.                                 final double maxCheckInterval,
  112.                                 final double convergence,
  113.                                 final int maxIterationCount,
  114.                                 final UnivariateSolver solver) {
  115.         eventsStates.add(new EventState(handler, maxCheckInterval, convergence,
  116.                                         maxIterationCount, solver));
  117.     }

  118.     /** {@inheritDoc} */
  119.     public Collection<EventHandler> getEventHandlers() {
  120.         final List<EventHandler> list = new ArrayList<EventHandler>(eventsStates.size());
  121.         for (EventState state : eventsStates) {
  122.             list.add(state.getEventHandler());
  123.         }
  124.         return Collections.unmodifiableCollection(list);
  125.     }

  126.     /** {@inheritDoc} */
  127.     public void clearEventHandlers() {
  128.         eventsStates.clear();
  129.     }

  130.     /** {@inheritDoc} */
  131.     public double getCurrentStepStart() {
  132.         return stepStart;
  133.     }

  134.     /** {@inheritDoc} */
  135.     public double getCurrentSignedStepsize() {
  136.         return stepSize;
  137.     }

  138.     /** {@inheritDoc} */
  139.     public void setMaxEvaluations(int maxEvaluations) {
  140.         evaluations.setMaximalCount((maxEvaluations < 0) ? Integer.MAX_VALUE : maxEvaluations);
  141.     }

  142.     /** {@inheritDoc} */
  143.     public int getMaxEvaluations() {
  144.         return evaluations.getMaximalCount();
  145.     }

  146.     /** {@inheritDoc} */
  147.     public int getEvaluations() {
  148.         return evaluations.getCount();
  149.     }

  150.     /** Prepare the start of an integration.
  151.      * @param t0 start value of the independent <i>time</i> variable
  152.      * @param y0 array containing the start value of the state vector
  153.      * @param t target time for the integration
  154.      */
  155.     protected void initIntegration(final double t0, final double[] y0, final double t) {

  156.         evaluations.resetCount();

  157.         for (final EventState state : eventsStates) {
  158.             state.setExpandable(expandable);
  159.             state.getEventHandler().init(t0, y0, t);
  160.         }

  161.         for (StepHandler handler : stepHandlers) {
  162.             handler.init(t0, y0, t);
  163.         }

  164.         setStateInitialized(false);

  165.     }

  166.     /** Set the equations.
  167.      * @param equations equations to set
  168.      */
  169.     protected void setEquations(final ExpandableStatefulODE equations) {
  170.         this.expandable = equations;
  171.     }

  172.     /** Get the differential equations to integrate.
  173.      * @return differential equations to integrate
  174.      * @since 3.2
  175.      */
  176.     protected ExpandableStatefulODE getExpandable() {
  177.         return expandable;
  178.     }

  179.     /** Get the evaluations counter.
  180.      * @return evaluations counter
  181.      * @since 3.2
  182.      */
  183.     protected Incrementor getEvaluationsCounter() {
  184.         return evaluations;
  185.     }

  186.     /** {@inheritDoc} */
  187.     public double integrate(final FirstOrderDifferentialEquations equations,
  188.                             final double t0, final double[] y0, final double t, final double[] y)
  189.         throws DimensionMismatchException, NumberIsTooSmallException,
  190.                MaxCountExceededException, NoBracketingException {

  191.         if (y0.length != equations.getDimension()) {
  192.             throw new DimensionMismatchException(y0.length, equations.getDimension());
  193.         }
  194.         if (y.length != equations.getDimension()) {
  195.             throw new DimensionMismatchException(y.length, equations.getDimension());
  196.         }

  197.         // prepare expandable stateful equations
  198.         final ExpandableStatefulODE expandableODE = new ExpandableStatefulODE(equations);
  199.         expandableODE.setTime(t0);
  200.         expandableODE.setPrimaryState(y0);

  201.         // perform integration
  202.         integrate(expandableODE, t);

  203.         // extract results back from the stateful equations
  204.         System.arraycopy(expandableODE.getPrimaryState(), 0, y, 0, y.length);
  205.         return expandableODE.getTime();

  206.     }

  207.     /** Integrate a set of differential equations up to the given time.
  208.      * <p>This method solves an Initial Value Problem (IVP).</p>
  209.      * <p>The set of differential equations is composed of a main set, which
  210.      * can be extended by some sets of secondary equations. The set of
  211.      * equations must be already set up with initial time and partial states.
  212.      * At integration completion, the final time and partial states will be
  213.      * available in the same object.</p>
  214.      * <p>Since this method stores some internal state variables made
  215.      * available in its public interface during integration ({@link
  216.      * #getCurrentSignedStepsize()}), it is <em>not</em> thread-safe.</p>
  217.      * @param equations complete set of differential equations to integrate
  218.      * @param t target time for the integration
  219.      * (can be set to a value smaller than <code>t0</code> for backward integration)
  220.      * @exception NumberIsTooSmallException if integration step is too small
  221.      * @throws DimensionMismatchException if the dimension of the complete state does not
  222.      * match the complete equations sets dimension
  223.      * @exception MaxCountExceededException if the number of functions evaluations is exceeded
  224.      * @exception NoBracketingException if the location of an event cannot be bracketed
  225.      */
  226.     public abstract void integrate(ExpandableStatefulODE equations, double t)
  227.         throws NumberIsTooSmallException, DimensionMismatchException,
  228.                MaxCountExceededException, NoBracketingException;

  229.     /** Compute the derivatives and check the number of evaluations.
  230.      * @param t current value of the independent <I>time</I> variable
  231.      * @param y array containing the current value of the state vector
  232.      * @param yDot placeholder array where to put the time derivative of the state vector
  233.      * @exception MaxCountExceededException if the number of functions evaluations is exceeded
  234.      * @exception DimensionMismatchException if arrays dimensions do not match equations settings
  235.      */
  236.     public void computeDerivatives(final double t, final double[] y, final double[] yDot)
  237.         throws MaxCountExceededException, DimensionMismatchException {
  238.         evaluations.incrementCount();
  239.         expandable.computeDerivatives(t, y, yDot);
  240.     }

  241.     /** Set the stateInitialized flag.
  242.      * <p>This method must be called by integrators with the value
  243.      * {@code false} before they start integration, so a proper lazy
  244.      * initialization is done automatically on the first step.</p>
  245.      * @param stateInitialized new value for the flag
  246.      * @since 2.2
  247.      */
  248.     protected void setStateInitialized(final boolean stateInitialized) {
  249.         this.statesInitialized = stateInitialized;
  250.     }

  251.     /** Accept a step, triggering events and step handlers.
  252.      * @param interpolator step interpolator
  253.      * @param y state vector at step end time, must be reset if an event
  254.      * asks for resetting or if an events stops integration during the step
  255.      * @param yDot placeholder array where to put the time derivative of the state vector
  256.      * @param tEnd final integration time
  257.      * @return time at end of step
  258.      * @exception MaxCountExceededException if the interpolator throws one because
  259.      * the number of functions evaluations is exceeded
  260.      * @exception NoBracketingException if the location of an event cannot be bracketed
  261.      * @exception DimensionMismatchException if arrays dimensions do not match equations settings
  262.      * @since 2.2
  263.      */
  264.     protected double acceptStep(final AbstractStepInterpolator interpolator,
  265.                                 final double[] y, final double[] yDot, final double tEnd)
  266.         throws MaxCountExceededException, DimensionMismatchException, NoBracketingException {

  267.             double previousT = interpolator.getGlobalPreviousTime();
  268.             final double currentT = interpolator.getGlobalCurrentTime();

  269.             // initialize the events states if needed
  270.             if (! statesInitialized) {
  271.                 for (EventState state : eventsStates) {
  272.                     state.reinitializeBegin(interpolator);
  273.                 }
  274.                 statesInitialized = true;
  275.             }

  276.             // search for next events that may occur during the step
  277.             final int orderingSign = interpolator.isForward() ? +1 : -1;
  278.             SortedSet<EventState> occurringEvents = new TreeSet<EventState>(new Comparator<EventState>() {

  279.                 /** {@inheritDoc} */
  280.                 public int compare(EventState es0, EventState es1) {
  281.                     return orderingSign * Double.compare(es0.getEventTime(), es1.getEventTime());
  282.                 }

  283.             });

  284.             for (final EventState state : eventsStates) {
  285.                 if (state.evaluateStep(interpolator)) {
  286.                     // the event occurs during the current step
  287.                     occurringEvents.add(state);
  288.                 }
  289.             }

  290.             while (!occurringEvents.isEmpty()) {

  291.                 // handle the chronologically first event
  292.                 final Iterator<EventState> iterator = occurringEvents.iterator();
  293.                 final EventState currentEvent = iterator.next();
  294.                 iterator.remove();

  295.                 // restrict the interpolator to the first part of the step, up to the event
  296.                 final double eventT = currentEvent.getEventTime();
  297.                 interpolator.setSoftPreviousTime(previousT);
  298.                 interpolator.setSoftCurrentTime(eventT);

  299.                 // get state at event time
  300.                 interpolator.setInterpolatedTime(eventT);
  301.                 final double[] eventYComplete = new double[y.length];
  302.                 expandable.getPrimaryMapper().insertEquationData(interpolator.getInterpolatedState(),
  303.                                                                  eventYComplete);
  304.                 int index = 0;
  305.                 for (EquationsMapper secondary : expandable.getSecondaryMappers()) {
  306.                     secondary.insertEquationData(interpolator.getInterpolatedSecondaryState(index++),
  307.                                                  eventYComplete);
  308.                 }

  309.                 // advance all event states to current time
  310.                 for (final EventState state : eventsStates) {
  311.                     state.stepAccepted(eventT, eventYComplete);
  312.                     isLastStep = isLastStep || state.stop();
  313.                 }

  314.                 // handle the first part of the step, up to the event
  315.                 for (final StepHandler handler : stepHandlers) {
  316.                     handler.handleStep(interpolator, isLastStep);
  317.                 }

  318.                 if (isLastStep) {
  319.                     // the event asked to stop integration
  320.                     System.arraycopy(eventYComplete, 0, y, 0, y.length);
  321.                     return eventT;
  322.                 }

  323.                 boolean needReset = false;
  324.                 for (final EventState state : eventsStates) {
  325.                     needReset =  needReset || state.reset(eventT, eventYComplete);
  326.                 }
  327.                 if (needReset) {
  328.                     // some event handler has triggered changes that
  329.                     // invalidate the derivatives, we need to recompute them
  330.                     interpolator.setInterpolatedTime(eventT);
  331.                     System.arraycopy(eventYComplete, 0, y, 0, y.length);
  332.                     computeDerivatives(eventT, y, yDot);
  333.                     resetOccurred = true;
  334.                     return eventT;
  335.                 }

  336.                 // prepare handling of the remaining part of the step
  337.                 previousT = eventT;
  338.                 interpolator.setSoftPreviousTime(eventT);
  339.                 interpolator.setSoftCurrentTime(currentT);

  340.                 // check if the same event occurs again in the remaining part of the step
  341.                 if (currentEvent.evaluateStep(interpolator)) {
  342.                     // the event occurs during the current step
  343.                     occurringEvents.add(currentEvent);
  344.                 }

  345.             }

  346.             // last part of the step, after the last event
  347.             interpolator.setInterpolatedTime(currentT);
  348.             final double[] currentY = new double[y.length];
  349.             expandable.getPrimaryMapper().insertEquationData(interpolator.getInterpolatedState(),
  350.                                                              currentY);
  351.             int index = 0;
  352.             for (EquationsMapper secondary : expandable.getSecondaryMappers()) {
  353.                 secondary.insertEquationData(interpolator.getInterpolatedSecondaryState(index++),
  354.                                              currentY);
  355.             }
  356.             for (final EventState state : eventsStates) {
  357.                 state.stepAccepted(currentT, currentY);
  358.                 isLastStep = isLastStep || state.stop();
  359.             }
  360.             isLastStep = isLastStep || Precision.equals(currentT, tEnd, 1);

  361.             // handle the remaining part of the step, after all events if any
  362.             for (StepHandler handler : stepHandlers) {
  363.                 handler.handleStep(interpolator, isLastStep);
  364.             }

  365.             return currentT;

  366.     }

  367.     /** Check the integration span.
  368.      * @param equations set of differential equations
  369.      * @param t target time for the integration
  370.      * @exception NumberIsTooSmallException if integration span is too small
  371.      * @exception DimensionMismatchException if adaptive step size integrators
  372.      * tolerance arrays dimensions are not compatible with equations settings
  373.      */
  374.     protected void sanityChecks(final ExpandableStatefulODE equations, final double t)
  375.         throws NumberIsTooSmallException, DimensionMismatchException {

  376.         final double threshold = 1000 * FastMath.ulp(FastMath.max(FastMath.abs(equations.getTime()),
  377.                                                                   FastMath.abs(t)));
  378.         final double dt = FastMath.abs(equations.getTime() - t);
  379.         if (dt <= threshold) {
  380.             throw new NumberIsTooSmallException(LocalizedFormats.TOO_SMALL_INTEGRATION_INTERVAL,
  381.                                                 dt, threshold, false);
  382.         }

  383.     }

  384. }