HermiteInterpolator.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.math4.legacy.analysis.interpolation;

  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.List;

  21. import org.apache.commons.math4.legacy.analysis.differentiation.DerivativeStructure;
  22. import org.apache.commons.math4.legacy.analysis.differentiation.UnivariateDifferentiableVectorFunction;
  23. import org.apache.commons.math4.legacy.analysis.polynomials.PolynomialFunction;
  24. import org.apache.commons.math4.legacy.exception.MathArithmeticException;
  25. import org.apache.commons.math4.legacy.exception.NoDataException;
  26. import org.apache.commons.math4.legacy.exception.ZeroException;
  27. import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
  28. import org.apache.commons.numbers.combinatorics.Factorial;

  29. /** Polynomial interpolator using both sample values and sample derivatives.
  30.  * <p>
  31.  * The interpolation polynomials match all sample points, including both values
  32.  * and provided derivatives. There is one polynomial for each component of
  33.  * the values vector. All polynomials have the same degree. The degree of the
  34.  * polynomials depends on the number of points and number of derivatives at each
  35.  * point. For example the interpolation polynomials for n sample points without
  36.  * any derivatives all have degree n-1. The interpolation polynomials for n
  37.  * sample points with the two extreme points having value and first derivative
  38.  * and the remaining points having value only all have degree n+1. The
  39.  * interpolation polynomial for n sample points with value, first and second
  40.  * derivative for all points all have degree 3n-1.
  41.  * </p>
  42.  *
  43.  * @since 3.1
  44.  */
  45. public class HermiteInterpolator implements UnivariateDifferentiableVectorFunction {

  46.     /** Sample abscissae. */
  47.     private final List<Double> abscissae;

  48.     /** Top diagonal of the divided differences array. */
  49.     private final List<double[]> topDiagonal;

  50.     /** Bottom diagonal of the divided differences array. */
  51.     private final List<double[]> bottomDiagonal;

  52.     /** Create an empty interpolator.
  53.      */
  54.     public HermiteInterpolator() {
  55.         this.abscissae      = new ArrayList<>();
  56.         this.topDiagonal    = new ArrayList<>();
  57.         this.bottomDiagonal = new ArrayList<>();
  58.     }

  59.     /** Add a sample point.
  60.      * <p>
  61.      * This method must be called once for each sample point. It is allowed to
  62.      * mix some calls with values only with calls with values and first
  63.      * derivatives.
  64.      * </p>
  65.      * <p>
  66.      * The point abscissae for all calls <em>must</em> be different.
  67.      * </p>
  68.      * @param x abscissa of the sample point
  69.      * @param value value and derivatives of the sample point
  70.      * (if only one row is passed, it is the value, if two rows are
  71.      * passed the first one is the value and the second the derivative
  72.      * and so on)
  73.      * @exception ZeroException if the abscissa difference between added point
  74.      * and a previous point is zero (i.e. the two points are at same abscissa)
  75.      * @exception MathArithmeticException if the number of derivatives is larger
  76.      * than 20, which prevents computation of a factorial
  77.      */
  78.     public void addSamplePoint(final double x, final double[] ... value)
  79.         throws ZeroException, MathArithmeticException {

  80.         if (value.length > 20) {
  81.             throw new MathArithmeticException(LocalizedFormats.NUMBER_TOO_LARGE, value.length, 20);
  82.         }
  83.         for (int i = 0; i < value.length; ++i) {
  84.             final double[] y = value[i].clone();
  85.             if (i > 1) {
  86.                 double inv = 1.0 / Factorial.value(i);
  87.                 for (int j = 0; j < y.length; ++j) {
  88.                     y[j] *= inv;
  89.                 }
  90.             }

  91.             // update the bottom diagonal of the divided differences array
  92.             final int n = abscissae.size();
  93.             bottomDiagonal.add(n - i, y);
  94.             double[] bottom0 = y;
  95.             for (int j = i; j < n; ++j) {
  96.                 final double[] bottom1 = bottomDiagonal.get(n - (j + 1));
  97.                 final double inv = 1.0 / (x - abscissae.get(n - (j + 1)));
  98.                 if (Double.isInfinite(inv)) {
  99.                     throw new ZeroException(LocalizedFormats.DUPLICATED_ABSCISSA_DIVISION_BY_ZERO, x);
  100.                 }
  101.                 for (int k = 0; k < y.length; ++k) {
  102.                     bottom1[k] = inv * (bottom0[k] - bottom1[k]);
  103.                 }
  104.                 bottom0 = bottom1;
  105.             }

  106.             // update the top diagonal of the divided differences array
  107.             topDiagonal.add(bottom0.clone());

  108.             // update the abscissae array
  109.             abscissae.add(x);
  110.         }
  111.     }

  112.     /** Compute the interpolation polynomials.
  113.      * @return interpolation polynomials array
  114.      * @exception NoDataException if sample is empty
  115.      */
  116.     public PolynomialFunction[] getPolynomials()
  117.         throws NoDataException {

  118.         // safety check
  119.         checkInterpolation();

  120.         // iteration initialization
  121.         final PolynomialFunction zero = polynomial(0);
  122.         PolynomialFunction[] polynomials = new PolynomialFunction[topDiagonal.get(0).length];
  123.         for (int i = 0; i < polynomials.length; ++i) {
  124.             polynomials[i] = zero;
  125.         }
  126.         PolynomialFunction coeff = polynomial(1);

  127.         // build the polynomials by iterating on the top diagonal of the divided differences array
  128.         for (int i = 0; i < topDiagonal.size(); ++i) {
  129.             double[] tdi = topDiagonal.get(i);
  130.             for (int k = 0; k < polynomials.length; ++k) {
  131.                 polynomials[k] = polynomials[k].add(coeff.multiply(polynomial(tdi[k])));
  132.             }
  133.             coeff = coeff.multiply(polynomial(-abscissae.get(i), 1.0));
  134.         }

  135.         return polynomials;
  136.     }

  137.     /** Interpolate value at a specified abscissa.
  138.      * <p>
  139.      * Calling this method is equivalent to call the {@link PolynomialFunction#value(double)
  140.      * value} methods of all polynomials returned by {@link #getPolynomials() getPolynomials},
  141.      * except it does not build the intermediate polynomials, so this method is faster and
  142.      * numerically more stable.
  143.      * </p>
  144.      * @param x interpolation abscissa
  145.      * @return interpolated value
  146.      * @exception NoDataException if sample is empty
  147.      */
  148.     @Override
  149.     public double[] value(double x) throws NoDataException {

  150.         // safety check
  151.         checkInterpolation();

  152.         final double[] value = new double[topDiagonal.get(0).length];
  153.         double valueCoeff = 1;
  154.         for (int i = 0; i < topDiagonal.size(); ++i) {
  155.             double[] dividedDifference = topDiagonal.get(i);
  156.             for (int k = 0; k < value.length; ++k) {
  157.                 value[k] += dividedDifference[k] * valueCoeff;
  158.             }
  159.             final double deltaX = x - abscissae.get(i);
  160.             valueCoeff *= deltaX;
  161.         }

  162.         return value;
  163.     }

  164.     /** Interpolate value at a specified abscissa.
  165.      * <p>
  166.      * Calling this method is equivalent to call the {@link
  167.      * PolynomialFunction#value(DerivativeStructure) value} methods of all polynomials
  168.      * returned by {@link #getPolynomials() getPolynomials}, except it does not build the
  169.      * intermediate polynomials, so this method is faster and numerically more stable.
  170.      * </p>
  171.      * @param x interpolation abscissa
  172.      * @return interpolated value
  173.      * @exception NoDataException if sample is empty
  174.      */
  175.     @Override
  176.     public DerivativeStructure[] value(final DerivativeStructure x)
  177.         throws NoDataException {

  178.         // safety check
  179.         checkInterpolation();

  180.         final DerivativeStructure[] value = new DerivativeStructure[topDiagonal.get(0).length];
  181.         Arrays.fill(value, x.getField().getZero());
  182.         DerivativeStructure valueCoeff = x.getField().getOne();
  183.         for (int i = 0; i < topDiagonal.size(); ++i) {
  184.             double[] dividedDifference = topDiagonal.get(i);
  185.             for (int k = 0; k < value.length; ++k) {
  186.                 value[k] = value[k].add(valueCoeff.multiply(dividedDifference[k]));
  187.             }
  188.             final DerivativeStructure deltaX = x.subtract(abscissae.get(i));
  189.             valueCoeff = valueCoeff.multiply(deltaX);
  190.         }

  191.         return value;
  192.     }

  193.     /** Check interpolation can be performed.
  194.      * @exception NoDataException if interpolation cannot be performed
  195.      * because sample is empty
  196.      */
  197.     private void checkInterpolation() throws NoDataException {
  198.         if (abscissae.isEmpty()) {
  199.             throw new NoDataException(LocalizedFormats.EMPTY_INTERPOLATION_SAMPLE);
  200.         }
  201.     }

  202.     /** Create a polynomial from its coefficients.
  203.      * @param c polynomials coefficients
  204.      * @return polynomial
  205.      */
  206.     private PolynomialFunction polynomial(double ... c) {
  207.         return new PolynomialFunction(c);
  208.     }
  209. }