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

  22. import java.util.ArrayList;
  23. import java.util.Arrays;
  24. import java.util.List;

  25. import org.hipparchus.analysis.differentiation.Derivative;
  26. import org.hipparchus.analysis.differentiation.UnivariateDifferentiableVectorFunction;
  27. import org.hipparchus.analysis.polynomials.PolynomialFunction;
  28. import org.hipparchus.exception.LocalizedCoreFormats;
  29. import org.hipparchus.exception.MathIllegalArgumentException;
  30. import org.hipparchus.exception.MathRuntimeException;
  31. import org.hipparchus.exception.NullArgumentException;
  32. import org.hipparchus.util.CombinatoricsUtils;
  33. import org.hipparchus.util.MathArrays;
  34. import org.hipparchus.util.MathUtils;

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

  51.     /** Sample abscissae. */
  52.     private final List<Double> abscissae;

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

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

  57.     /** Create an empty interpolator.
  58.      */
  59.     public HermiteInterpolator() {
  60.         this.abscissae      = new ArrayList<>();
  61.         this.topDiagonal    = new ArrayList<>();
  62.         this.bottomDiagonal = new ArrayList<>();
  63.     }

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

  85.         for (int i = 0; i < value.length; ++i) {

  86.             final double[] y = value[i].clone();
  87.             if (i > 1) {
  88.                 double inv = 1.0 / CombinatoricsUtils.factorial(i);
  89.                 for (int j = 0; j < y.length; ++j) {
  90.                     y[j] *= inv;
  91.                 }
  92.             }

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

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

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

  112.         }

  113.     }

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

  120.         // safety check
  121.         checkInterpolation();

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

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

  137.         return polynomials;

  138.     }

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

  152.         // safety check
  153.         checkInterpolation();

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

  164.         return value;

  165.     }

  166.     /** {@inheritDoc}. */
  167.     @Override
  168.     public <T extends Derivative<T>> T[] value(T x)
  169.         throws MathIllegalArgumentException {

  170.         // safety check
  171.         checkInterpolation();

  172.         final T[] value = MathArrays.buildArray(x.getField(), topDiagonal.get(0).length);
  173.         Arrays.fill(value, x.getField().getZero());
  174.         T valueCoeff = x.getField().getOne();
  175.         for (int i = 0; i < topDiagonal.size(); ++i) {
  176.             double[] dividedDifference = topDiagonal.get(i);
  177.             for (int k = 0; k < value.length; ++k) {
  178.                 value[k] = value[k].add(valueCoeff.multiply(dividedDifference[k]));
  179.             }
  180.             final T deltaX = x.subtract(abscissae.get(i));
  181.             valueCoeff = valueCoeff.multiply(deltaX);
  182.         }

  183.         return value;

  184.     }


  185.     /** Interpolate value and first derivatives at a specified abscissa.
  186.      * @param x interpolation abscissa
  187.      * @param order maximum derivation order
  188.      * @return interpolated value and derivatives (value in row 0,
  189.      * 1<sup>st</sup> derivative in row 1, ... n<sup>th</sup> derivative in row n)
  190.      * @exception MathIllegalArgumentException if sample is empty
  191.      * @throws NullArgumentException if x is null
  192.      */
  193.     public double[][] derivatives(double x, int order)
  194.         throws MathIllegalArgumentException, NullArgumentException {

  195.         // safety check
  196.         MathUtils.checkNotNull(x);
  197.         if (abscissae.isEmpty()) {
  198.             throw new MathIllegalArgumentException(LocalizedCoreFormats.EMPTY_INTERPOLATION_SAMPLE);
  199.         }

  200.         final double[] tj = new double[order + 1];
  201.         tj[0] = 0.0;
  202.         for (int i = 0; i < order; ++i) {
  203.             tj[i + 1] = tj[i] + 1;
  204.         }

  205.         final double[][] derivatives = new double[order + 1][topDiagonal.get(0).length];
  206.         final double[] valueCoeff = new double[order + 1];
  207.         valueCoeff[0] = 1.0;
  208.         for (int i = 0; i < topDiagonal.size(); ++i) {
  209.             double[] dividedDifference = topDiagonal.get(i);
  210.             final double deltaX = x - abscissae.get(i);
  211.             for (int j = order; j >= 0; --j) {
  212.                 for (int k = 0; k < derivatives[j].length; ++k) {
  213.                     derivatives[j][k] += dividedDifference[k] * valueCoeff[j];
  214.                 }
  215.                 valueCoeff[j] *= deltaX;
  216.                 if (j > 0) {
  217.                     valueCoeff[j] += tj[j] * valueCoeff[j - 1];
  218.                 }
  219.             }
  220.         }

  221.         return derivatives;

  222.     }

  223.     /** Check interpolation can be performed.
  224.      * @exception MathIllegalArgumentException if interpolation cannot be performed
  225.      * because sample is empty
  226.      */
  227.     private void checkInterpolation() throws MathIllegalArgumentException {
  228.         if (abscissae.isEmpty()) {
  229.             throw new MathIllegalArgumentException(LocalizedCoreFormats.EMPTY_INTERPOLATION_SAMPLE);
  230.         }
  231.     }

  232.     /** Create a polynomial from its coefficients.
  233.      * @param c polynomials coefficients
  234.      * @return polynomial
  235.      */
  236.     private PolynomialFunction polynomial(double ... c) {
  237.         return new PolynomialFunction(c);
  238.     }

  239. }