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.polynomials;
018
019import org.apache.commons.numbers.arrays.SortInPlace;
020import org.apache.commons.math4.legacy.analysis.UnivariateFunction;
021import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
022import org.apache.commons.math4.legacy.exception.NonMonotonicSequenceException;
023import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException;
024import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
025import org.apache.commons.math4.core.jdkmath.JdkMath;
026import org.apache.commons.math4.legacy.core.MathArrays;
027
028/**
029 * Implements the representation of a real polynomial function in
030 * <a href="http://mathworld.wolfram.com/LagrangeInterpolatingPolynomial.html">
031 * Lagrange Form</a>. For reference, see <b>Introduction to Numerical
032 * Analysis</b>, ISBN 038795452X, chapter 2.
033 * <p>
034 * The approximated function should be smooth enough for Lagrange polynomial
035 * to work well. Otherwise, consider using splines instead.</p>
036 *
037 * @since 1.2
038 */
039public class PolynomialFunctionLagrangeForm implements UnivariateFunction {
040    /**
041     * The coefficients of the polynomial, ordered by degree -- i.e.
042     * coefficients[0] is the constant term and coefficients[n] is the
043     * coefficient of x^n where n is the degree of the polynomial.
044     */
045    private double[] coefficients;
046    /**
047     * Interpolating points (abscissas).
048     */
049    private final double[] x;
050    /**
051     * Function values at interpolating points.
052     */
053    private final double[] y;
054    /**
055     * Whether the polynomial coefficients are available.
056     */
057    private boolean coefficientsComputed;
058
059    /**
060     * Construct a Lagrange polynomial with the given abscissas and function
061     * values. The order of interpolating points are not important.
062     * <p>
063     * The constructor makes copy of the input arrays and assigns them.</p>
064     *
065     * @param x interpolating points
066     * @param y function values at interpolating points
067     * @throws DimensionMismatchException if the array lengths are different.
068     * @throws NumberIsTooSmallException if the number of points is less than 2.
069     * @throws NonMonotonicSequenceException
070     * if two abscissae have the same value.
071     */
072    public PolynomialFunctionLagrangeForm(double[] x, double[] y)
073        throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException {
074        this.x = new double[x.length];
075        this.y = new double[y.length];
076        System.arraycopy(x, 0, this.x, 0, x.length);
077        System.arraycopy(y, 0, this.y, 0, y.length);
078        coefficientsComputed = false;
079
080        if (!verifyInterpolationArray(x, y, false)) {
081            SortInPlace.ASCENDING.apply(this.x, this.y);
082            // Second check in case some abscissa is duplicated.
083            verifyInterpolationArray(this.x, this.y, true);
084        }
085    }
086
087    /**
088     * Calculate the function value at the given point.
089     *
090     * @param z Point at which the function value is to be computed.
091     * @return the function value.
092     * @throws DimensionMismatchException if {@code x} and {@code y} have
093     * different lengths.
094     * @throws org.apache.commons.math4.legacy.exception.NonMonotonicSequenceException
095     * if {@code x} is not sorted in strictly increasing order.
096     * @throws NumberIsTooSmallException if the size of {@code x} is less
097     * than 2.
098     */
099    @Override
100    public double value(double z) {
101        return evaluateInternal(x, y, z);
102    }
103
104    /**
105     * Returns the degree of the polynomial.
106     *
107     * @return the degree of the polynomial
108     */
109    public int degree() {
110        return x.length - 1;
111    }
112
113    /**
114     * Returns a copy of the interpolating points array.
115     * <p>
116     * Changes made to the returned copy will not affect the polynomial.</p>
117     *
118     * @return a fresh copy of the interpolating points array
119     */
120    public double[] getInterpolatingPoints() {
121        double[] out = new double[x.length];
122        System.arraycopy(x, 0, out, 0, x.length);
123        return out;
124    }
125
126    /**
127     * Returns a copy of the interpolating values array.
128     * <p>
129     * Changes made to the returned copy will not affect the polynomial.</p>
130     *
131     * @return a fresh copy of the interpolating values array
132     */
133    public double[] getInterpolatingValues() {
134        double[] out = new double[y.length];
135        System.arraycopy(y, 0, out, 0, y.length);
136        return out;
137    }
138
139    /**
140     * Returns a copy of the coefficients array.
141     * <p>
142     * Changes made to the returned copy will not affect the polynomial.</p>
143     * <p>
144     * Note that coefficients computation can be ill-conditioned. Use with caution
145     * and only when it is necessary.</p>
146     *
147     * @return a fresh copy of the coefficients array
148     */
149    public double[] getCoefficients() {
150        if (!coefficientsComputed) {
151            computeCoefficients();
152        }
153        double[] out = new double[coefficients.length];
154        System.arraycopy(coefficients, 0, out, 0, coefficients.length);
155        return out;
156    }
157
158    /**
159     * Evaluate the Lagrange polynomial using
160     * <a href="http://mathworld.wolfram.com/NevillesAlgorithm.html">
161     * Neville's Algorithm</a>. It takes O(n^2) time.
162     *
163     * @param x Interpolating points array.
164     * @param y Interpolating values array.
165     * @param z Point at which the function value is to be computed.
166     * @return the function value.
167     * @throws DimensionMismatchException if {@code x} and {@code y} have
168     * different lengths.
169     * @throws NonMonotonicSequenceException
170     * if {@code x} is not sorted in strictly increasing order.
171     * @throws NumberIsTooSmallException if the size of {@code x} is less
172     * than 2.
173     */
174    public static double evaluate(double[] x, double[] y, double z)
175        throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException {
176        if (verifyInterpolationArray(x, y, false)) {
177            return evaluateInternal(x, y, z);
178        }
179
180        // Array is not sorted.
181        final double[] xNew = new double[x.length];
182        final double[] yNew = new double[y.length];
183        System.arraycopy(x, 0, xNew, 0, x.length);
184        System.arraycopy(y, 0, yNew, 0, y.length);
185
186        SortInPlace.ASCENDING.apply(xNew, yNew);
187        // Second check in case some abscissa is duplicated.
188        verifyInterpolationArray(xNew, yNew, true);
189        return evaluateInternal(xNew, yNew, z);
190    }
191
192    /**
193     * Evaluate the Lagrange polynomial using
194     * <a href="http://mathworld.wolfram.com/NevillesAlgorithm.html">
195     * Neville's Algorithm</a>. It takes O(n^2) time.
196     *
197     * @param x Interpolating points array.
198     * @param y Interpolating values array.
199     * @param z Point at which the function value is to be computed.
200     * @return the function value.
201     * @throws DimensionMismatchException if {@code x} and {@code y} have
202     * different lengths.
203     * @throws org.apache.commons.math4.legacy.exception.NonMonotonicSequenceException
204     * if {@code x} is not sorted in strictly increasing order.
205     * @throws NumberIsTooSmallException if the size of {@code x} is less
206     * than 2.
207     */
208    private static double evaluateInternal(double[] x, double[] y, double z) {
209        int nearest = 0;
210        final int n = x.length;
211        final double[] c = new double[n];
212        final double[] d = new double[n];
213        double minDist = Double.POSITIVE_INFINITY;
214        for (int i = 0; i < n; i++) {
215            // initialize the difference arrays
216            c[i] = y[i];
217            d[i] = y[i];
218            // find out the abscissa closest to z
219            final double dist = JdkMath.abs(z - x[i]);
220            if (dist < minDist) {
221                nearest = i;
222                minDist = dist;
223            }
224        }
225
226        // initial approximation to the function value at z
227        double value = y[nearest];
228
229        for (int i = 1; i < n; i++) {
230            for (int j = 0; j < n-i; j++) {
231                final double tc = x[j] - z;
232                final double td = x[i+j] - z;
233                final double divider = x[j] - x[i+j];
234                // update the difference arrays
235                final double w = (c[j+1] - d[j]) / divider;
236                c[j] = tc * w;
237                d[j] = td * w;
238            }
239            // sum up the difference terms to get the final value
240            if (nearest < 0.5*(n-i+1)) {
241                value += c[nearest];    // fork down
242            } else {
243                nearest--;
244                value += d[nearest];    // fork up
245            }
246        }
247
248        return value;
249    }
250
251    /**
252     * Calculate the coefficients of Lagrange polynomial from the
253     * interpolation data. It takes O(n^2) time.
254     * Note that this computation can be ill-conditioned: Use with caution
255     * and only when it is necessary.
256     */
257    protected void computeCoefficients() {
258        final int n = degree() + 1;
259        coefficients = new double[n];
260        for (int i = 0; i < n; i++) {
261            coefficients[i] = 0.0;
262        }
263
264        // c[] are the coefficients of P(x) = (x-x[0])(x-x[1])...(x-x[n-1])
265        final double[] c = new double[n+1];
266        c[0] = 1.0;
267        for (int i = 0; i < n; i++) {
268            for (int j = i; j > 0; j--) {
269                c[j] = c[j-1] - c[j] * x[i];
270            }
271            c[0] *= -x[i];
272            c[i+1] = 1;
273        }
274
275        final double[] tc = new double[n];
276        for (int i = 0; i < n; i++) {
277            // d = (x[i]-x[0])...(x[i]-x[i-1])(x[i]-x[i+1])...(x[i]-x[n-1])
278            double d = 1;
279            for (int j = 0; j < n; j++) {
280                if (i != j) {
281                    d *= x[i] - x[j];
282                }
283            }
284            final double t = y[i] / d;
285            // Lagrange polynomial is the sum of n terms, each of which is a
286            // polynomial of degree n-1. tc[] are the coefficients of the i-th
287            // numerator Pi(x) = (x-x[0])...(x-x[i-1])(x-x[i+1])...(x-x[n-1]).
288            tc[n-1] = c[n];     // actually c[n] = 1
289            coefficients[n-1] += t * tc[n-1];
290            for (int j = n-2; j >= 0; j--) {
291                tc[j] = c[j+1] + tc[j+1] * x[i];
292                coefficients[j] += t * tc[j];
293            }
294        }
295
296        coefficientsComputed = true;
297    }
298
299    /**
300     * Check that the interpolation arrays are valid.
301     * The arrays features checked by this method are that both arrays have the
302     * same length and this length is at least 2.
303     *
304     * @param x Interpolating points array.
305     * @param y Interpolating values array.
306     * @param abort Whether to throw an exception if {@code x} is not sorted.
307     * @throws DimensionMismatchException if the array lengths are different.
308     * @throws NumberIsTooSmallException if the number of points is less than 2.
309     * @throws org.apache.commons.math4.legacy.exception.NonMonotonicSequenceException
310     * if {@code x} is not sorted in strictly increasing order and {@code abort}
311     * is {@code true}.
312     * @return {@code false} if the {@code x} is not sorted in increasing order,
313     * {@code true} otherwise.
314     * @see #evaluate(double[], double[], double)
315     * @see #computeCoefficients()
316     */
317    public static boolean verifyInterpolationArray(double[] x, double[] y, boolean abort)
318        throws DimensionMismatchException, NumberIsTooSmallException, NonMonotonicSequenceException {
319        if (x.length != y.length) {
320            throw new DimensionMismatchException(x.length, y.length);
321        }
322        if (x.length < 2) {
323            throw new NumberIsTooSmallException(LocalizedFormats.WRONG_NUMBER_OF_POINTS, 2, x.length, true);
324        }
325
326        return MathArrays.checkOrder(x, MathArrays.OrderDirection.INCREASING, true, abort);
327    }
328}