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 */ 017 018 package org.apache.commons.math.optimization.fitting; 019 020 import java.util.ArrayList; 021 import java.util.List; 022 023 import org.apache.commons.math.FunctionEvaluationException; 024 import org.apache.commons.math.analysis.DifferentiableMultivariateVectorialFunction; 025 import org.apache.commons.math.analysis.MultivariateMatrixFunction; 026 import org.apache.commons.math.optimization.DifferentiableMultivariateVectorialOptimizer; 027 import org.apache.commons.math.optimization.OptimizationException; 028 import org.apache.commons.math.optimization.VectorialPointValuePair; 029 030 /** Fitter for parametric univariate real functions y = f(x). 031 * <p>When a univariate real function y = f(x) does depend on some 032 * unknown parameters p<sub>0</sub>, p<sub>1</sub> ... p<sub>n-1</sub>, 033 * this class can be used to find these parameters. It does this 034 * by <em>fitting</em> the curve so it remains very close to a set of 035 * observed points (x<sub>0</sub>, y<sub>0</sub>), (x<sub>1</sub>, 036 * y<sub>1</sub>) ... (x<sub>k-1</sub>, y<sub>k-1</sub>). This fitting 037 * is done by finding the parameters values that minimizes the objective 038 * function ∑(y<sub>i</sub>-f(x<sub>i</sub>))<sup>2</sup>. This is 039 * really a least squares problem.</p> 040 * @version $Revision: 790380 $ $Date: 2009-07-01 17:03:38 -0400 (Wed, 01 Jul 2009) $ 041 * @since 2.0 042 */ 043 public class CurveFitter { 044 045 /** Optimizer to use for the fitting. */ 046 private final DifferentiableMultivariateVectorialOptimizer optimizer; 047 048 /** Observed points. */ 049 private final List<WeightedObservedPoint> observations; 050 051 /** Simple constructor. 052 * @param optimizer optimizer to use for the fitting 053 */ 054 public CurveFitter(final DifferentiableMultivariateVectorialOptimizer optimizer) { 055 this.optimizer = optimizer; 056 observations = new ArrayList<WeightedObservedPoint>(); 057 } 058 059 /** Add an observed (x,y) point to the sample with unit weight. 060 * <p>Calling this method is equivalent to call 061 * <code>addObservedPoint(1.0, x, y)</code>.</p> 062 * @param x abscissa of the point 063 * @param y observed value of the point at x, after fitting we should 064 * have f(x) as close as possible to this value 065 * @see #addObservedPoint(double, double, double) 066 * @see #addObservedPoint(WeightedObservedPoint) 067 * @see #getObservations() 068 */ 069 public void addObservedPoint(double x, double y) { 070 addObservedPoint(1.0, x, y); 071 } 072 073 /** Add an observed weighted (x,y) point to the sample. 074 * @param weight weight of the observed point in the fit 075 * @param x abscissa of the point 076 * @param y observed value of the point at x, after fitting we should 077 * have f(x) as close as possible to this value 078 * @see #addObservedPoint(double, double) 079 * @see #addObservedPoint(WeightedObservedPoint) 080 * @see #getObservations() 081 */ 082 public void addObservedPoint(double weight, double x, double y) { 083 observations.add(new WeightedObservedPoint(weight, x, y)); 084 } 085 086 /** Add an observed weighted (x,y) point to the sample. 087 * @param observed observed point to add 088 * @see #addObservedPoint(double, double) 089 * @see #addObservedPoint(double, double, double) 090 * @see #getObservations() 091 */ 092 public void addObservedPoint(WeightedObservedPoint observed) { 093 observations.add(observed); 094 } 095 096 /** Get the observed points. 097 * @return observed points 098 * @see #addObservedPoint(double, double) 099 * @see #addObservedPoint(double, double, double) 100 * @see #addObservedPoint(WeightedObservedPoint) 101 */ 102 public WeightedObservedPoint[] getObservations() { 103 return observations.toArray(new WeightedObservedPoint[observations.size()]); 104 } 105 106 /** Fit a curve. 107 * <p>This method compute the coefficients of the curve that best 108 * fit the sample of observed points previously given through calls 109 * to the {@link #addObservedPoint(WeightedObservedPoint) 110 * addObservedPoint} method.</p> 111 * @param f parametric function to fit 112 * @param initialGuess first guess of the function parameters 113 * @return fitted parameters 114 * @exception FunctionEvaluationException if the objective function throws one during 115 * the search 116 * @exception OptimizationException if the algorithm failed to converge 117 * @exception IllegalArgumentException if the start point dimension is wrong 118 */ 119 public double[] fit(final ParametricRealFunction f, 120 final double[] initialGuess) 121 throws FunctionEvaluationException, OptimizationException, IllegalArgumentException { 122 123 // prepare least squares problem 124 double[] target = new double[observations.size()]; 125 double[] weights = new double[observations.size()]; 126 int i = 0; 127 for (WeightedObservedPoint point : observations) { 128 target[i] = point.getY(); 129 weights[i] = point.getWeight(); 130 ++i; 131 } 132 133 // perform the fit 134 VectorialPointValuePair optimum = 135 optimizer.optimize(new TheoreticalValuesFunction(f), target, weights, initialGuess); 136 137 // extract the coefficients 138 return optimum.getPointRef(); 139 140 } 141 142 /** Vectorial function computing function theoretical values. */ 143 private class TheoreticalValuesFunction 144 implements DifferentiableMultivariateVectorialFunction { 145 146 /** Function to fit. */ 147 private final ParametricRealFunction f; 148 149 /** Simple constructor. 150 * @param f function to fit. 151 */ 152 public TheoreticalValuesFunction(final ParametricRealFunction f) { 153 this.f = f; 154 } 155 156 /** {@inheritDoc} */ 157 public MultivariateMatrixFunction jacobian() { 158 return new MultivariateMatrixFunction() { 159 public double[][] value(double[] point) 160 throws FunctionEvaluationException, IllegalArgumentException { 161 162 final double[][] jacobian = new double[observations.size()][]; 163 164 int i = 0; 165 for (WeightedObservedPoint observed : observations) { 166 jacobian[i++] = f.gradient(observed.getX(), point); 167 } 168 169 return jacobian; 170 171 } 172 }; 173 } 174 175 /** {@inheritDoc} */ 176 public double[] value(double[] point) 177 throws FunctionEvaluationException, IllegalArgumentException { 178 179 // compute the residuals 180 final double[] values = new double[observations.size()]; 181 int i = 0; 182 for (WeightedObservedPoint observed : observations) { 183 values[i++] = f.value(observed.getX(), point); 184 } 185 186 return values; 187 188 } 189 190 } 191 192 }