Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Algorithms.ParameterlessPopulationPyramid/3.3/HillClimber.cs @ 17382

Last change on this file since 17382 was 17382, checked in by mkommend, 4 years ago

#2521: Refactored single-objective problems to use EvaluationResult instead of double as return type from Evaluate.

File size: 5.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 * and the BEACON Center for the Study of Evolution in Action.
5 *
6 * This file is part of HeuristicLab.
7 *
8 * HeuristicLab is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * HeuristicLab is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
20 */
21#endregion
22
23using System;
24using System.Collections.Generic;
25using System.Linq;
26using System.Threading;
27using HEAL.Attic;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Encodings.BinaryVectorEncoding;
32using HeuristicLab.Optimization;
33using HeuristicLab.Parameters;
34using HeuristicLab.Random;
35
36
37namespace HeuristicLab.Algorithms.ParameterlessPopulationPyramid {
38  // This code is based off the publication
39  // B. W. Goldman and W. F. Punch, "Parameter-less Population Pyramid," GECCO, pp. 785–792, 2014
40  // and the original source code in C++11 available from: https://github.com/brianwgoldman/Parameter-less_Population_Pyramid
41  [Item("Hill Climber (HC)", "Binary Hill Climber.")]
42  [StorableType("BA349010-6295-406E-8989-B271FB96ED86")]
43  [Creatable(CreatableAttribute.Categories.SingleSolutionAlgorithms, Priority = 150)]
44  public class HillClimber : BasicAlgorithm {
45    [Storable]
46    private IRandom random;
47
48    private const string IterationsParameterName = "Iterations";
49    private const string BestQualityResultName = "Best quality";
50    private const string IterationsResultName = "Iterations";
51
52    public override Type ProblemType {
53      get { return typeof(ISingleObjectiveProblemDefinition<BinaryVectorEncoding, BinaryVector>); }
54    }
55    public new ISingleObjectiveProblemDefinition<BinaryVectorEncoding, BinaryVector> Problem {
56      get { return (ISingleObjectiveProblemDefinition<BinaryVectorEncoding, BinaryVector>)base.Problem; }
57      set { base.Problem = (IProblem)value; }
58    }
59
60    public override bool SupportsPause { get { return false; } }
61
62    public IFixedValueParameter<IntValue> IterationsParameter {
63      get { return (IFixedValueParameter<IntValue>)Parameters[IterationsParameterName]; }
64    }
65
66    public int Iterations {
67      get { return IterationsParameter.Value.Value; }
68      set { IterationsParameter.Value.Value = value; }
69    }
70
71    #region ResultsProperties
72    private double ResultsBestQuality {
73      get { return ((DoubleValue)Results[BestQualityResultName].Value).Value; }
74      set { ((DoubleValue)Results[BestQualityResultName].Value).Value = value; }
75    }
76    private int ResultsIterations {
77      get { return ((IntValue)Results[IterationsResultName].Value).Value; }
78      set { ((IntValue)Results[IterationsResultName].Value).Value = value; }
79    }
80    #endregion
81
82    [StorableConstructor]
83    protected HillClimber(StorableConstructorFlag _) : base(_) { }
84    protected HillClimber(HillClimber original, Cloner cloner)
85      : base(original, cloner) {
86    }
87    public override IDeepCloneable Clone(Cloner cloner) {
88      return new HillClimber(this, cloner);
89    }
90
91    public HillClimber()
92      : base() {
93      random = new MersenneTwister();
94      Parameters.Add(new FixedValueParameter<IntValue>(IterationsParameterName, "", new IntValue(100)));
95    }
96
97
98    protected override void Initialize(CancellationToken cancellationToken) {
99      Results.Add(new Result(BestQualityResultName, new DoubleValue(double.NaN)));
100      Results.Add(new Result(IterationsResultName, new IntValue(0)));
101      base.Initialize(cancellationToken);
102    }
103    protected override void Run(CancellationToken cancellationToken) {
104      while (ResultsIterations < Iterations) {
105        cancellationToken.ThrowIfCancellationRequested();
106
107        var solution = new BinaryVector(Problem.Encoding.Length);
108        for (int i = 0; i < solution.Length; i++) {
109          solution[i] = random.Next(2) == 1;
110        }
111
112        var evaluationResult = Problem.Evaluate(solution, random);
113        var fitness = evaluationResult.Quality;
114
115        fitness = ImproveToLocalOptimum(Problem, solution, fitness, random);
116        if (double.IsNaN(ResultsBestQuality) || Problem.IsBetter(fitness, ResultsBestQuality)) {
117          ResultsBestQuality = fitness;
118        }
119
120        ResultsIterations++;
121      }
122    }
123    // In the GECCO paper, Section 2.1
124    public static double ImproveToLocalOptimum(ISingleObjectiveProblemDefinition<BinaryVectorEncoding, BinaryVector> problem, BinaryVector solution, double fitness, IRandom rand) {
125      var tried = new HashSet<int>();
126      do {
127        var options = Enumerable.Range(0, solution.Length).Shuffle(rand);
128        foreach (var option in options) {
129          if (tried.Contains(option)) continue;
130          solution[option] = !solution[option];
131          var newEvaluationResult = problem.Evaluate(solution, rand);
132          double newFitness = newEvaluationResult.Quality;
133          if (problem.IsBetter(newFitness, fitness)) {
134            fitness = newFitness;
135            tried.Clear();
136          } else {
137            solution[option] = !solution[option];
138          }
139          tried.Add(option);
140        }
141      } while (tried.Count != solution.Length);
142      return fitness;
143    }
144  }
145}
Note: See TracBrowser for help on using the repository browser.