View Javadoc
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  
19  import java.util.ArrayList;
20  import java.util.Arrays;
21  import java.util.List;
22  
23  import org.apache.commons.math4.legacy.analysis.differentiation.DerivativeStructure;
24  import org.apache.commons.math4.legacy.analysis.differentiation.UnivariateDifferentiableVectorFunction;
25  import org.apache.commons.math4.legacy.analysis.polynomials.PolynomialFunction;
26  import org.apache.commons.math4.legacy.exception.MathArithmeticException;
27  import org.apache.commons.math4.legacy.exception.NoDataException;
28  import org.apache.commons.math4.legacy.exception.ZeroException;
29  import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
30  import org.apache.commons.numbers.combinatorics.Factorial;
31  
32  /** Polynomial interpolator using both sample values and sample derivatives.
33   * <p>
34   * The interpolation polynomials match all sample points, including both values
35   * and provided derivatives. There is one polynomial for each component of
36   * the values vector. All polynomials have the same degree. The degree of the
37   * polynomials depends on the number of points and number of derivatives at each
38   * point. For example the interpolation polynomials for n sample points without
39   * any derivatives all have degree n-1. The interpolation polynomials for n
40   * sample points with the two extreme points having value and first derivative
41   * and the remaining points having value only all have degree n+1. The
42   * interpolation polynomial for n sample points with value, first and second
43   * derivative for all points all have degree 3n-1.
44   * </p>
45   *
46   * @since 3.1
47   */
48  public class HermiteInterpolator implements UnivariateDifferentiableVectorFunction {
49  
50      /** Sample abscissae. */
51      private final List<Double> abscissae;
52  
53      /** Top diagonal of the divided differences array. */
54      private final List<double[]> topDiagonal;
55  
56      /** Bottom diagonal of the divided differences array. */
57      private final List<double[]> bottomDiagonal;
58  
59      /** Create an empty interpolator.
60       */
61      public HermiteInterpolator() {
62          this.abscissae      = new ArrayList<>();
63          this.topDiagonal    = new ArrayList<>();
64          this.bottomDiagonal = new ArrayList<>();
65      }
66  
67      /** Add a sample point.
68       * <p>
69       * This method must be called once for each sample point. It is allowed to
70       * mix some calls with values only with calls with values and first
71       * derivatives.
72       * </p>
73       * <p>
74       * The point abscissae for all calls <em>must</em> be different.
75       * </p>
76       * @param x abscissa of the sample point
77       * @param value value and derivatives of the sample point
78       * (if only one row is passed, it is the value, if two rows are
79       * passed the first one is the value and the second the derivative
80       * and so on)
81       * @exception ZeroException if the abscissa difference between added point
82       * and a previous point is zero (i.e. the two points are at same abscissa)
83       * @exception MathArithmeticException if the number of derivatives is larger
84       * than 20, which prevents computation of a factorial
85       */
86      public void addSamplePoint(final double x, final double[] ... value)
87          throws ZeroException, MathArithmeticException {
88  
89          if (value.length > 20) {
90              throw new MathArithmeticException(LocalizedFormats.NUMBER_TOO_LARGE, value.length, 20);
91          }
92          for (int i = 0; i < value.length; ++i) {
93              final double[] y = value[i].clone();
94              if (i > 1) {
95                  double inv = 1.0 / Factorial.value(i);
96                  for (int j = 0; j < y.length; ++j) {
97                      y[j] *= inv;
98                  }
99              }
100 
101             // update the bottom diagonal of the divided differences array
102             final int n = abscissae.size();
103             bottomDiagonal.add(n - i, y);
104             double[] bottom0 = y;
105             for (int j = i; j < n; ++j) {
106                 final double[] bottom1 = bottomDiagonal.get(n - (j + 1));
107                 final double inv = 1.0 / (x - abscissae.get(n - (j + 1)));
108                 if (Double.isInfinite(inv)) {
109                     throw new ZeroException(LocalizedFormats.DUPLICATED_ABSCISSA_DIVISION_BY_ZERO, x);
110                 }
111                 for (int k = 0; k < y.length; ++k) {
112                     bottom1[k] = inv * (bottom0[k] - bottom1[k]);
113                 }
114                 bottom0 = bottom1;
115             }
116 
117             // update the top diagonal of the divided differences array
118             topDiagonal.add(bottom0.clone());
119 
120             // update the abscissae array
121             abscissae.add(x);
122         }
123     }
124 
125     /** Compute the interpolation polynomials.
126      * @return interpolation polynomials array
127      * @exception NoDataException if sample is empty
128      */
129     public PolynomialFunction[] getPolynomials()
130         throws NoDataException {
131 
132         // safety check
133         checkInterpolation();
134 
135         // iteration initialization
136         final PolynomialFunction zero = polynomial(0);
137         PolynomialFunction[] polynomials = new PolynomialFunction[topDiagonal.get(0).length];
138         for (int i = 0; i < polynomials.length; ++i) {
139             polynomials[i] = zero;
140         }
141         PolynomialFunction coeff = polynomial(1);
142 
143         // build the polynomials by iterating on the top diagonal of the divided differences array
144         for (int i = 0; i < topDiagonal.size(); ++i) {
145             double[] tdi = topDiagonal.get(i);
146             for (int k = 0; k < polynomials.length; ++k) {
147                 polynomials[k] = polynomials[k].add(coeff.multiply(polynomial(tdi[k])));
148             }
149             coeff = coeff.multiply(polynomial(-abscissae.get(i), 1.0));
150         }
151 
152         return polynomials;
153     }
154 
155     /** Interpolate value at a specified abscissa.
156      * <p>
157      * Calling this method is equivalent to call the {@link PolynomialFunction#value(double)
158      * value} methods of all polynomials returned by {@link #getPolynomials() getPolynomials},
159      * except it does not build the intermediate polynomials, so this method is faster and
160      * numerically more stable.
161      * </p>
162      * @param x interpolation abscissa
163      * @return interpolated value
164      * @exception NoDataException if sample is empty
165      */
166     @Override
167     public double[] value(double x) throws NoDataException {
168 
169         // safety check
170         checkInterpolation();
171 
172         final double[] value = new double[topDiagonal.get(0).length];
173         double valueCoeff = 1;
174         for (int i = 0; i < topDiagonal.size(); ++i) {
175             double[] dividedDifference = topDiagonal.get(i);
176             for (int k = 0; k < value.length; ++k) {
177                 value[k] += dividedDifference[k] * valueCoeff;
178             }
179             final double deltaX = x - abscissae.get(i);
180             valueCoeff *= deltaX;
181         }
182 
183         return value;
184     }
185 
186     /** Interpolate value at a specified abscissa.
187      * <p>
188      * Calling this method is equivalent to call the {@link
189      * PolynomialFunction#value(DerivativeStructure) value} methods of all polynomials
190      * returned by {@link #getPolynomials() getPolynomials}, except it does not build the
191      * intermediate polynomials, so this method is faster and numerically more stable.
192      * </p>
193      * @param x interpolation abscissa
194      * @return interpolated value
195      * @exception NoDataException if sample is empty
196      */
197     @Override
198     public DerivativeStructure[] value(final DerivativeStructure x)
199         throws NoDataException {
200 
201         // safety check
202         checkInterpolation();
203 
204         final DerivativeStructure[] value = new DerivativeStructure[topDiagonal.get(0).length];
205         Arrays.fill(value, x.getField().getZero());
206         DerivativeStructure valueCoeff = x.getField().getOne();
207         for (int i = 0; i < topDiagonal.size(); ++i) {
208             double[] dividedDifference = topDiagonal.get(i);
209             for (int k = 0; k < value.length; ++k) {
210                 value[k] = value[k].add(valueCoeff.multiply(dividedDifference[k]));
211             }
212             final DerivativeStructure deltaX = x.subtract(abscissae.get(i));
213             valueCoeff = valueCoeff.multiply(deltaX);
214         }
215 
216         return value;
217     }
218 
219     /** Check interpolation can be performed.
220      * @exception NoDataException if interpolation cannot be performed
221      * because sample is empty
222      */
223     private void checkInterpolation() throws NoDataException {
224         if (abscissae.isEmpty()) {
225             throw new NoDataException(LocalizedFormats.EMPTY_INTERPOLATION_SAMPLE);
226         }
227     }
228 
229     /** Create a polynomial from its coefficients.
230      * @param c polynomials coefficients
231      * @return polynomial
232      */
233     private PolynomialFunction polynomial(double ... c) {
234         return new PolynomialFunction(c);
235     }
236 }