/// ------------------------------------------------------ /// 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.Collections.Generic; namespace SwarmOps { /// /// Log best solutions found during optimization, that is, log /// parameters and their associated fitness. Transparently wraps /// around a problem-object. /// public class LogSolutions : ProblemWrapper { #region Constructors. /// /// Create the object. /// /// Problem-object to be wrapped. /// Log capacity. /// Only log feasible solutions. public LogSolutions(Problem problem, int capacity, bool onlyFeasible) : base(problem) { Capacity = capacity; OnlyFeasible = onlyFeasible; Log = new List(capacity); } #endregion #region Public fields. /// /// Maximum capacity of log. /// public int Capacity { get; private set; } /// /// Only log feasible solutions. /// public bool OnlyFeasible { get; private set; } /// /// Log of candidate solutions. /// public List Log { get; private set; } #endregion #region Public methods. /// /// Clear the log. /// public void Clear() { Log.Clear(); } #endregion #region Problem base-class overrides. /// /// Return the name of the problem. /// public override string Name { get { return "LogSolutions (" + Problem.Name + ")"; } } /// /// Compute the fitness measure by passing the /// given parameters to the wrapped problem, and if /// candidate solution is an improvement then log /// the results. /// /// Candidate solution. /// Preemptive Fitness Limit /// Feasibility of old candidate solution. /// Feasibility of new candidate solution. /// Fitness value. public override double Fitness(double[] parameters, double fitnessLimit, bool oldFeasible, bool newFeasible) { double fitness = Problem.Fitness(parameters, fitnessLimit, oldFeasible, newFeasible); // Log solutions. If feasibiilty is required then only log feasible solutions. if (!OnlyFeasible || newFeasible) { // Log solutions with better fitness and feasibility. if (Tools.BetterFeasibleFitness(oldFeasible, newFeasible, fitnessLimit, fitness)) { // Ensure log does not exceed desired capacity. if (Log.Count >= Capacity) { // Assume log is sorted in ascending (worsening) order. // Remove worst from the log. Log.RemoveAt(Log.Count - 1); } Solution candidateSolution = new Solution(parameters, fitness, newFeasible); // Add new solution to the log. Log.Add(candidateSolution); // Sort log according to fitness. // This could be implemented more efficiently // but it is not crucial for runtime performance // so this simple implementation is sufficient. Log.Sort(new Solution.FitnessComparer()); } } return fitness; } #endregion } }