/// ------------------------------------------------------ /// SwarmOps - Numeric and heuristic optimization for C# /// Copyright (C) 2003-2011 Magnus Erik Hvass Pedersen. /// Please see the file license.txt for license details. /// SwarmOps on the internet: http://www.Hvass-Labs.org/ /// ------------------------------------------------------ namespace SwarmOps.Problems { /// /// Base-class for curvefitting by minimizing the Mean-Squared-Error (MSE), /// that is, minimizing Sum((y - f(x))^2), for all given data-pairs (x,y). /// public abstract class CurveFitting : Problem { #region Constructors. /// /// Create the object. /// /// X-axis values. /// Y-axis values, curve to be fitted. public CurveFitting(double[] x, double[] y) : base() { if (x.Length == 0 || y.Length == 0) { throw new System.ArgumentException("Zero-length array."); } if (x.Length != y.Length) { throw new System.ArgumentException("Different array lengths."); } X = x; Y = y; } #endregion #region Public fields. /// /// X-axis values. /// public double[] X { get; private set; } /// /// Y-axis values. /// public double[] Y { get; private set; } #endregion #region Public methods. /// /// Compute the fitted curve. /// /// Parameters to use for the curve-function. /// X-axis values to map to Y-axis values for the fitted curve. /// Fitted curve. public double[] ComputeY(double[] parameters, double[] x) { double[] y = new double[x.Length]; for (int i = 0; i < x.Length; i++) { y[i] = ComputeY(parameters, x[i]); } return y; } #endregion #region Override these. /// /// Compute the value y given x using the curve-fitting function. /// /// Parameters for curve-fitting function. /// X-axis value. /// Computed Y-axis value. public abstract double ComputeY(double[] parameters, double x); #endregion #region Base-class overrides. /// /// Minimum possible fitness. /// public override double MinFitness { get { return 0; } } /// /// Compute and return fitness for the given parameters. /// /// Candidate solution. public override double Fitness(double[] parameters) { double sse = 0; for (int i = 0; i < X.Length; i++) { double x = X[i]; double y = Y[i]; double computedY = ComputeY(parameters, x); sse += System.Math.Pow(computedY - y, 2); } double mse = sse / X.Length; return mse; } #endregion } }