#region License Information /* HeuristicLab * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL) * * This file is part of HeuristicLab. * * HeuristicLab is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HeuristicLab is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HeuristicLab. If not, see . */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Data; using HeuristicLab.Encodings.BinaryVectorEncoding; using HeuristicLab.Optimization; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; using HeuristicLab.Random; namespace HeuristicLab.Algorithms.ParameterlessPopulationPyramid { [Item("Hill Climber", "Test algorithm.")] [StorableClass] [Creatable("Parameterless Population Pyramid")] public class HillClimber : AlgorithmBase { [Storable] private IRandom random; [StorableConstructor] protected HillClimber(bool deserializing) : base(deserializing) { } protected HillClimber(HillClimber original, Cloner cloner) : base(original, cloner) { } public override IDeepCloneable Clone(Cloner cloner) { return new HillClimber(this, cloner); } public HillClimber() : base() { random = new MersenneTwister(); } protected override void Run() { bool[] solution = new bool[Problem.Length]; for (int i = 0; i < solution.Length; i++) { solution[i] = random.Next(2) == 1; } var fitness = Problem.Evaluate(solution); fitness = ImproveToLocalOptimum(Problem, solution, fitness, random); Results.Add(new Result("Best quality", new DoubleValue(fitness))); Results.Add(new Result("Best solution", new BinaryVector(solution))); } public static double ImproveToLocalOptimum(BinaryVectorProblem problem, bool[] solution, double fitness, IRandom rand) { var tried = new HashSet(); double newFitness=fitness; do { var options = Enumerable.Range(0, solution.Length).Shuffle(rand); foreach (var option in options) { solution[option] = !solution[option]; newFitness = problem.Evaluate(solution); if ((problem.Maximization && fitness < newFitness) || (!problem.Maximization && fitness > newFitness)) { fitness = newFitness; tried.Clear(); } else { solution[option] = !solution[option]; } tried.Add(option); } } while (tried.Count != solution.Length); return fitness; } } }