/// ------------------------------------------------------ /// 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/ /// ------------------------------------------------------ using System.Diagnostics; namespace SwarmOps.Problems { /// /// Sphere benchmark problem. /// public class Sphere : Benchmark { #region Constructors. /// /// Construct the object. /// /// Dimensionality of the problem (e.g. 20) /// Max optimization iterations to perform. public Sphere(int dimensionality, int maxIterations) : base(dimensionality, -100, 100, 50, 100, maxIterations) { } #endregion #region Base-class overrides. /// /// Name of the optimization problem. /// public override string Name { get { return "Sphere"; } } /// /// 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[] x) { Debug.Assert(x != null && x.Length == Dimensionality); double value = 0; for (int i = 0; i < Dimensionality; i++) { double elm = x[i]; value += elm * elm; } return value; } /// /// Has the gradient has been implemented? /// public override bool HasGradient { get { return true; } } /// /// Compute the gradient of the fitness-function. /// /// Candidate solution. /// Array for holding the gradient. public override int Gradient(double[] x, ref double[] v) { Debug.Assert(x != null && x.Length == Dimensionality); Debug.Assert(v != null && v.Length == Dimensionality); for (int i = 0; i < Dimensionality; i++) { double elm = x[i]; v[i] = 2 * elm; } return 0; } #endregion } }