001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.math4.legacy.analysis.interpolation;
018
019import java.util.ArrayList;
020import java.util.List;
021
022import org.apache.commons.math4.legacy.core.FieldElement;
023import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
024import org.apache.commons.math4.legacy.exception.MathArithmeticException;
025import org.apache.commons.math4.legacy.exception.NoDataException;
026import org.apache.commons.math4.legacy.exception.NullArgumentException;
027import org.apache.commons.math4.legacy.exception.ZeroException;
028import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
029import org.apache.commons.math4.legacy.core.MathArrays;
030
031/** Polynomial interpolator using both sample values and sample derivatives.
032 * <p>
033 * The interpolation polynomials match all sample points, including both values
034 * and provided derivatives. There is one polynomial for each component of
035 * the values vector. All polynomials have the same degree. The degree of the
036 * polynomials depends on the number of points and number of derivatives at each
037 * point. For example the interpolation polynomials for n sample points without
038 * any derivatives all have degree n-1. The interpolation polynomials for n
039 * sample points with the two extreme points having value and first derivative
040 * and the remaining points having value only all have degree n+1. The
041 * interpolation polynomial for n sample points with value, first and second
042 * derivative for all points all have degree 3n-1.
043 * </p>
044 *
045 * @param <T> Type of the field elements.
046 *
047 * @since 3.2
048 */
049public class FieldHermiteInterpolator<T extends FieldElement<T>> {
050
051    /** Sample abscissae. */
052    private final List<T> abscissae;
053
054    /** Top diagonal of the divided differences array. */
055    private final List<T[]> topDiagonal;
056
057    /** Bottom diagonal of the divided differences array. */
058    private final List<T[]> bottomDiagonal;
059
060    /** Create an empty interpolator.
061     */
062    public FieldHermiteInterpolator() {
063        this.abscissae      = new ArrayList<>();
064        this.topDiagonal    = new ArrayList<>();
065        this.bottomDiagonal = new ArrayList<>();
066    }
067
068    /** Add a sample point.
069     * <p>
070     * This method must be called once for each sample point. It is allowed to
071     * mix some calls with values only with calls with values and first
072     * derivatives.
073     * </p>
074     * <p>
075     * The point abscissae for all calls <em>must</em> be different.
076     * </p>
077     * @param x abscissa of the sample point
078     * @param value value and derivatives of the sample point
079     * (if only one row is passed, it is the value, if two rows are
080     * passed the first one is the value and the second the derivative
081     * and so on)
082     * @exception ZeroException if the abscissa difference between added point
083     * and a previous point is zero (i.e. the two points are at same abscissa)
084     * @exception MathArithmeticException if the number of derivatives is larger
085     * than 20, which prevents computation of a factorial
086     * @throws DimensionMismatchException if derivative structures are inconsistent
087     * @throws NullArgumentException if x is null
088     */
089    @SafeVarargs
090    public final void addSamplePoint(final T x, final T[] ... value)
091        throws ZeroException, MathArithmeticException,
092               DimensionMismatchException, NullArgumentException {
093
094        NullArgumentException.check(x);
095        T factorial = x.getField().getOne();
096        for (int i = 0; i < value.length; ++i) {
097
098            final T[] y = value[i].clone();
099            if (i > 1) {
100                factorial = factorial.multiply(i);
101                final T inv = factorial.reciprocal();
102                for (int j = 0; j < y.length; ++j) {
103                    y[j] = y[j].multiply(inv);
104                }
105            }
106
107            // update the bottom diagonal of the divided differences array
108            final int n = abscissae.size();
109            bottomDiagonal.add(n - i, y);
110            T[] bottom0 = y;
111            for (int j = i; j < n; ++j) {
112                final T[] bottom1 = bottomDiagonal.get(n - (j + 1));
113                if (x.equals(abscissae.get(n - (j + 1)))) {
114                    throw new ZeroException(LocalizedFormats.DUPLICATED_ABSCISSA_DIVISION_BY_ZERO, x);
115                }
116                final T inv = x.subtract(abscissae.get(n - (j + 1))).reciprocal();
117                for (int k = 0; k < y.length; ++k) {
118                    bottom1[k] = inv.multiply(bottom0[k].subtract(bottom1[k]));
119                }
120                bottom0 = bottom1;
121            }
122
123            // update the top diagonal of the divided differences array
124            topDiagonal.add(bottom0.clone());
125
126            // update the abscissae array
127            abscissae.add(x);
128        }
129    }
130
131    /** Interpolate value at a specified abscissa.
132     * @param x interpolation abscissa
133     * @return interpolated value
134     * @exception NoDataException if sample is empty
135     * @throws NullArgumentException if x is null
136     */
137    public T[] value(T x) throws NoDataException, NullArgumentException {
138
139        // safety check
140        NullArgumentException.check(x);
141        if (abscissae.isEmpty()) {
142            throw new NoDataException(LocalizedFormats.EMPTY_INTERPOLATION_SAMPLE);
143        }
144
145        final T[] value = MathArrays.buildArray(x.getField(), topDiagonal.get(0).length);
146        T valueCoeff = x.getField().getOne();
147        for (int i = 0; i < topDiagonal.size(); ++i) {
148            T[] dividedDifference = topDiagonal.get(i);
149            for (int k = 0; k < value.length; ++k) {
150                value[k] = value[k].add(dividedDifference[k].multiply(valueCoeff));
151            }
152            final T deltaX = x.subtract(abscissae.get(i));
153            valueCoeff = valueCoeff.multiply(deltaX);
154        }
155
156        return value;
157    }
158
159    /** Interpolate value and first derivatives at a specified abscissa.
160     * @param x interpolation abscissa
161     * @param order maximum derivation order
162     * @return interpolated value and derivatives (value in row 0,
163     * 1<sup>st</sup> derivative in row 1, ... n<sup>th</sup> derivative in row n)
164     * @exception NoDataException if sample is empty
165     * @throws NullArgumentException if x is null
166     */
167    public T[][] derivatives(T x, int order) throws NoDataException, NullArgumentException {
168
169        // safety check
170        NullArgumentException.check(x);
171        if (abscissae.isEmpty()) {
172            throw new NoDataException(LocalizedFormats.EMPTY_INTERPOLATION_SAMPLE);
173        }
174
175        final T zero = x.getField().getZero();
176        final T one  = x.getField().getOne();
177        final T[] tj = MathArrays.buildArray(x.getField(), order + 1);
178        tj[0] = zero;
179        for (int i = 0; i < order; ++i) {
180            tj[i + 1] = tj[i].add(one);
181        }
182
183        final T[][] derivatives =
184                MathArrays.buildArray(x.getField(), order + 1, topDiagonal.get(0).length);
185        final T[] valueCoeff = MathArrays.buildArray(x.getField(), order + 1);
186        valueCoeff[0] = x.getField().getOne();
187        for (int i = 0; i < topDiagonal.size(); ++i) {
188            T[] dividedDifference = topDiagonal.get(i);
189            final T deltaX = x.subtract(abscissae.get(i));
190            for (int j = order; j >= 0; --j) {
191                for (int k = 0; k < derivatives[j].length; ++k) {
192                    derivatives[j][k] =
193                            derivatives[j][k].add(dividedDifference[k].multiply(valueCoeff[j]));
194                }
195                valueCoeff[j] = valueCoeff[j].multiply(deltaX);
196                if (j > 0) {
197                    valueCoeff[j] = valueCoeff[j].add(tj[j].multiply(valueCoeff[j - 1]));
198                }
199            }
200        }
201
202        return derivatives;
203    }
204}