AkimaSplineInterpolator.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.analysis.interpolation;

  18. import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
  19. import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction;
  20. import org.apache.commons.math3.exception.DimensionMismatchException;
  21. import org.apache.commons.math3.exception.NonMonotonicSequenceException;
  22. import org.apache.commons.math3.exception.NullArgumentException;
  23. import org.apache.commons.math3.exception.NumberIsTooSmallException;
  24. import org.apache.commons.math3.exception.util.LocalizedFormats;
  25. import org.apache.commons.math3.util.FastMath;
  26. import org.apache.commons.math3.util.MathArrays;
  27. import org.apache.commons.math3.util.Precision;

  28. /**
  29.  * Computes a cubic spline interpolation for the data set using the Akima
  30.  * algorithm, as originally formulated by Hiroshi Akima in his 1970 paper
  31.  * "A New Method of Interpolation and Smooth Curve Fitting Based on Local Procedures."
  32.  * J. ACM 17, 4 (October 1970), 589-602. DOI=10.1145/321607.321609
  33.  * http://doi.acm.org/10.1145/321607.321609
  34.  * <p>
  35.  * This implementation is based on the Akima implementation in the CubicSpline
  36.  * class in the Math.NET Numerics library. The method referenced is
  37.  * CubicSpline.InterpolateAkimaSorted
  38.  * </p>
  39.  * <p>
  40.  * The {@link #interpolate(double[], double[]) interpolate} method returns a
  41.  * {@link PolynomialSplineFunction} consisting of n cubic polynomials, defined
  42.  * over the subintervals determined by the x values, {@code x[0] < x[i] ... < x[n]}.
  43.  * The Akima algorithm requires that {@code n >= 5}.
  44.  * </p>
  45.  */
  46. public class AkimaSplineInterpolator
  47.     implements UnivariateInterpolator {
  48.     /** The minimum number of points that are needed to compute the function. */
  49.     private static final int MINIMUM_NUMBER_POINTS = 5;

  50.     /**
  51.      * Computes an interpolating function for the data set.
  52.      *
  53.      * @param xvals the arguments for the interpolation points
  54.      * @param yvals the values for the interpolation points
  55.      * @return a function which interpolates the data set
  56.      * @throws DimensionMismatchException if {@code xvals} and {@code yvals} have
  57.      *         different sizes.
  58.      * @throws NonMonotonicSequenceException if {@code xvals} is not sorted in
  59.      *         strict increasing order.
  60.      * @throws NumberIsTooSmallException if the size of {@code xvals} is smaller
  61.      *         than 5.
  62.      */
  63.     public PolynomialSplineFunction interpolate(double[] xvals,
  64.                                                 double[] yvals)
  65.         throws DimensionMismatchException,
  66.                NumberIsTooSmallException,
  67.                NonMonotonicSequenceException {
  68.         if (xvals == null ||
  69.             yvals == null) {
  70.             throw new NullArgumentException();
  71.         }

  72.         if (xvals.length != yvals.length) {
  73.             throw new DimensionMismatchException(xvals.length, yvals.length);
  74.         }

  75.         if (xvals.length < MINIMUM_NUMBER_POINTS) {
  76.             throw new NumberIsTooSmallException(LocalizedFormats.NUMBER_OF_POINTS,
  77.                                                 xvals.length,
  78.                                                 MINIMUM_NUMBER_POINTS, true);
  79.         }

  80.         MathArrays.checkOrder(xvals);

  81.         final int numberOfDiffAndWeightElements = xvals.length - 1;

  82.         final double[] differences = new double[numberOfDiffAndWeightElements];
  83.         final double[] weights = new double[numberOfDiffAndWeightElements];

  84.         for (int i = 0; i < differences.length; i++) {
  85.             differences[i] = (yvals[i + 1] - yvals[i]) / (xvals[i + 1] - xvals[i]);
  86.         }

  87.         for (int i = 1; i < weights.length; i++) {
  88.             weights[i] = FastMath.abs(differences[i] - differences[i - 1]);
  89.         }

  90.         // Prepare Hermite interpolation scheme.
  91.         final double[] firstDerivatives = new double[xvals.length];

  92.         for (int i = 2; i < firstDerivatives.length - 2; i++) {
  93.             final double wP = weights[i + 1];
  94.             final double wM = weights[i - 1];
  95.             if (Precision.equals(wP, 0.0) &&
  96.                 Precision.equals(wM, 0.0)) {
  97.                 final double xv = xvals[i];
  98.                 final double xvP = xvals[i + 1];
  99.                 final double xvM = xvals[i - 1];
  100.                 firstDerivatives[i] = (((xvP - xv) * differences[i - 1]) + ((xv - xvM) * differences[i])) / (xvP - xvM);
  101.             } else {
  102.                 firstDerivatives[i] = ((wP * differences[i - 1]) + (wM * differences[i])) / (wP + wM);
  103.             }
  104.         }

  105.         firstDerivatives[0] = differentiateThreePoint(xvals, yvals, 0, 0, 1, 2);
  106.         firstDerivatives[1] = differentiateThreePoint(xvals, yvals, 1, 0, 1, 2);
  107.         firstDerivatives[xvals.length - 2] = differentiateThreePoint(xvals, yvals, xvals.length - 2,
  108.                                                                      xvals.length - 3, xvals.length - 2,
  109.                                                                      xvals.length - 1);
  110.         firstDerivatives[xvals.length - 1] = differentiateThreePoint(xvals, yvals, xvals.length - 1,
  111.                                                                      xvals.length - 3, xvals.length - 2,
  112.                                                                      xvals.length - 1);

  113.         return interpolateHermiteSorted(xvals, yvals, firstDerivatives);
  114.     }

  115.     /**
  116.      * Three point differentiation helper, modeled off of the same method in the
  117.      * Math.NET CubicSpline class. This is used by both the Apache Math and the
  118.      * Math.NET Akima Cubic Spline algorithms
  119.      *
  120.      * @param xvals x values to calculate the numerical derivative with
  121.      * @param yvals y values to calculate the numerical derivative with
  122.      * @param indexOfDifferentiation index of the elemnt we are calculating the derivative around
  123.      * @param indexOfFirstSample index of the first element to sample for the three point method
  124.      * @param indexOfSecondsample index of the second element to sample for the three point method
  125.      * @param indexOfThirdSample index of the third element to sample for the three point method
  126.      * @return the derivative
  127.      */
  128.     private double differentiateThreePoint(double[] xvals, double[] yvals,
  129.                                            int indexOfDifferentiation,
  130.                                            int indexOfFirstSample,
  131.                                            int indexOfSecondsample,
  132.                                            int indexOfThirdSample) {
  133.         final double x0 = yvals[indexOfFirstSample];
  134.         final double x1 = yvals[indexOfSecondsample];
  135.         final double x2 = yvals[indexOfThirdSample];

  136.         final double t = xvals[indexOfDifferentiation] - xvals[indexOfFirstSample];
  137.         final double t1 = xvals[indexOfSecondsample] - xvals[indexOfFirstSample];
  138.         final double t2 = xvals[indexOfThirdSample] - xvals[indexOfFirstSample];

  139.         final double a = (x2 - x0 - (t2 / t1 * (x1 - x0))) / (t2 * t2 - t1 * t2);
  140.         final double b = (x1 - x0 - a * t1 * t1) / t1;

  141.         return (2 * a * t) + b;
  142.     }

  143.     /**
  144.      * Creates a Hermite cubic spline interpolation from the set of (x,y) value
  145.      * pairs and their derivatives. This is modeled off of the
  146.      * InterpolateHermiteSorted method in the Math.NET CubicSpline class.
  147.      *
  148.      * @param xvals x values for interpolation
  149.      * @param yvals y values for interpolation
  150.      * @param firstDerivatives first derivative values of the function
  151.      * @return polynomial that fits the function
  152.      */
  153.     private PolynomialSplineFunction interpolateHermiteSorted(double[] xvals,
  154.                                                               double[] yvals,
  155.                                                               double[] firstDerivatives) {
  156.         if (xvals.length != yvals.length) {
  157.             throw new DimensionMismatchException(xvals.length, yvals.length);
  158.         }

  159.         if (xvals.length != firstDerivatives.length) {
  160.             throw new DimensionMismatchException(xvals.length,
  161.                                                  firstDerivatives.length);
  162.         }

  163.         final int minimumLength = 2;
  164.         if (xvals.length < minimumLength) {
  165.             throw new NumberIsTooSmallException(LocalizedFormats.NUMBER_OF_POINTS,
  166.                                                 xvals.length, minimumLength,
  167.                                                 true);
  168.         }

  169.         final int size = xvals.length - 1;
  170.         final PolynomialFunction[] polynomials = new PolynomialFunction[size];
  171.         final double[] coefficients = new double[4];

  172.         for (int i = 0; i < polynomials.length; i++) {
  173.             final double w = xvals[i + 1] - xvals[i];
  174.             final double w2 = w * w;

  175.             final double yv = yvals[i];
  176.             final double yvP = yvals[i + 1];

  177.             final double fd = firstDerivatives[i];
  178.             final double fdP = firstDerivatives[i + 1];

  179.             coefficients[0] = yv;
  180.             coefficients[1] = firstDerivatives[i];
  181.             coefficients[2] = (3 * (yvP - yv) / w - 2 * fd - fdP) / w;
  182.             coefficients[3] = (2 * (yv - yvP) / w + fd + fdP) / w2;
  183.             polynomials[i] = new PolynomialFunction(coefficients);
  184.         }

  185.         return new PolynomialSplineFunction(xvals, polynomials);

  186.     }
  187. }