Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2457_ExpertSystem/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/Evolutionary/EvolutionStrategy.cs @ 17751

Last change on this file since 17751 was 16728, checked in by abeham, 6 years ago

#1614: updated to new persistence and .NET 4.6.1

File size: 10.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2017 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Threading;
26using HEAL.Attic;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Encodings.IntegerVectorEncoding;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.Random;
34
35namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms.Evolutionary {
36  [StorableType("d568d524-1f84-461c-adf5-573d8e472063")]
37  public enum ESSelection { Plus = 0, Comma = 1 }
38
39  [Item("Evolution Strategy (GQAP)", "The algorithm implements a simple evolution strategy (ES).")]
40  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms)]
41  [StorableType("A1590185-F2E3-4163-896E-28EEC93A5CDF")]
42  public sealed class EvolutionStrategy : StochasticAlgorithm<ESContext, IntegerVectorEncoding> {
43
44    public override bool SupportsPause {
45      get { return true; }
46    }
47
48    public override Type ProblemType {
49      get { return typeof(GQAP); }
50    }
51
52    public new GQAP Problem {
53      get { return (GQAP)base.Problem; }
54      set { base.Problem = value; }
55    }
56
57    [Storable]
58    private FixedValueParameter<IntValue> lambdaParameter;
59    private IFixedValueParameter<IntValue> LambdaParameter {
60      get { return lambdaParameter; }
61    }
62    [Storable]
63    private FixedValueParameter<IntValue> muParameter;
64    public IFixedValueParameter<IntValue> MuParameter {
65      get { return muParameter; }
66    }
67    [Storable]
68    private FixedValueParameter<EnumValue<ESSelection>> selectionParameter;
69    public IFixedValueParameter<EnumValue<ESSelection>> SelectionParameter {
70      get { return selectionParameter; }
71    }
72    [Storable]
73    private FixedValueParameter<BoolValue> useRecombinationParameter;
74    public IFixedValueParameter<BoolValue> UseRecombinationParameter {
75      get { return useRecombinationParameter; }
76    }
77
78    public int Lambda {
79      get { return lambdaParameter.Value.Value; }
80      set { lambdaParameter.Value.Value = value; }
81    }
82    public int Mu {
83      get { return muParameter.Value.Value; }
84      set { muParameter.Value.Value = value; }
85    }
86    public ESSelection Selection {
87      get { return selectionParameter.Value.Value; }
88      set { selectionParameter.Value.Value = value; }
89    }
90    public bool UseRecombination {
91      get { return useRecombinationParameter.Value.Value; }
92      set { useRecombinationParameter.Value.Value = value; }
93    }
94
95    [StorableConstructor]
96    private EvolutionStrategy(StorableConstructorFlag _) : base(_) { }
97    private EvolutionStrategy(EvolutionStrategy original, Cloner cloner)
98      : base(original, cloner) {
99      lambdaParameter = cloner.Clone(original.lambdaParameter);
100      muParameter = cloner.Clone(original.muParameter);
101      selectionParameter = cloner.Clone(original.selectionParameter);
102      useRecombinationParameter = cloner.Clone(original.useRecombinationParameter);
103    }
104    public EvolutionStrategy() {
105      Parameters.Add(lambdaParameter = new FixedValueParameter<IntValue>("Lambda", "(λ) The amount of offspring that are created each generation.", new IntValue(10)));
106      Parameters.Add(muParameter = new FixedValueParameter<IntValue>("Mu", "(μ) The population size.", new IntValue(1)));
107      Parameters.Add(selectionParameter= new FixedValueParameter<EnumValue<ESSelection>>("Selection", "The selection strategy: elitist (plus) or generational (comma).", new EnumValue<ESSelection>(ESSelection.Plus)));
108      Parameters.Add(useRecombinationParameter = new FixedValueParameter<BoolValue>("Use Recombination", "Whether to create an \"intermediate\" solution to perform the mutation from.", new BoolValue(false)));
109
110      Problem = new GQAP();
111    }
112
113    public override IDeepCloneable Clone(Cloner cloner) {
114      return new EvolutionStrategy(this, cloner);
115    }
116
117    protected override void Initialize(CancellationToken cancellationToken) {
118      base.Initialize(cancellationToken);
119
120      Context.NormalRand = new NormalDistributedRandom(Context.Random, 0, 1);
121      Context.Problem = Problem;
122      Context.BestSolution = null;
123     
124      for (var m = 0; m < Mu; m++) {
125        var assign = new IntegerVector(Problem.ProblemInstance.Demands.Length, Context.Random, 0, Problem.ProblemInstance.Capacities.Length);
126        var eval = Problem.ProblemInstance.Evaluate(assign);
127        Context.EvaluatedSolutions++;
128
129        var min = (1.0 / assign.Length) * 2 - 1; // desired min prob
130        var max = (4.0 / assign.Length) * 2 - 1; // desired max prob
131        min = 0.5 * (Math.Log(1 + min) - Math.Log(1 - min)); // arctanh
132        max = 0.5 * (Math.Log(1 + max) - Math.Log(1 - max));
133        var ind = new ESGQAPSolution(assign, eval, min + Context.Random.NextDouble() * (max - min));
134        var fit = Problem.ProblemInstance.ToSingleObjective(eval);
135        Context.AddToPopulation(Context.ToScope(ind, fit));
136        if (double.IsNaN(Context.BestQuality) || fit < Context.BestQuality) {
137          Context.BestQuality = fit;
138          Context.BestSolution = (ESGQAPSolution)ind.Clone();
139        }
140      }
141
142      Results.Add(new Result("Iterations", new IntValue(Context.Iterations)));
143      Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions)));
144      Results.Add(new Result("BestQuality", new DoubleValue(Context.BestQuality)));
145      Results.Add(new Result("BestSolution", Context.BestSolution));
146
147      Context.RunOperator(Analyzer, cancellationToken);
148    }
149
150    protected override void Run(CancellationToken cancellationToken) {
151      base.Run(cancellationToken);
152      var lastUpdate = ExecutionTime;
153      var eq = new IntegerVectorEqualityComparer();
154
155      while (!StoppingCriterion()) {
156        var nextGen = new List<ISingleObjectiveSolutionScope<ESGQAPSolution>>(Lambda);
157
158        for (var l = 0; l < Lambda; l++) {
159          IntegerVector child = null;
160          var sParam = 0.0;
161          if (UseRecombination) {
162            child = DiscreteLocationCrossover.Apply(Context.Random, new ItemArray<IntegerVector>(Context.Population.Select(x => x.Solution.Assignment)), Problem.ProblemInstance.Demands, Problem.ProblemInstance.Capacities);
163            sParam = Context.Population.Select(x => x.Solution.SParam).Average();
164          } else {
165            var m = Context.AtRandomPopulation();
166            child = (IntegerVector)m.Solution.Assignment.Clone();
167            sParam = m.Solution.SParam;
168          }
169          sParam += 0.7071 * Context.NormalRand.NextDouble();
170          RelocateEquipmentManipluator.Apply(Context.Random, child,
171            Problem.ProblemInstance.Capacities.Length, (Math.Tanh(sParam) + 1) / 2.0);
172          var eval = Problem.ProblemInstance.Evaluate(child);
173          Context.EvaluatedSolutions++;
174
175          var offspring = new ESGQAPSolution(child, eval, sParam);
176
177          var fit = Problem.ProblemInstance.ToSingleObjective(offspring.Evaluation);
178          if (Selection == ESSelection.Comma || Context.Population.Select(x => x.Solution.Assignment).All(x => !eq.Equals(child, x)))
179            nextGen.Add(Context.ToScope(offspring, fit));
180
181          if (fit < Context.BestQuality) {
182            Context.BestQuality = fit;
183            Context.BestSolution = (ESGQAPSolution)offspring.Clone();
184          }
185        }
186
187        if (Selection == ESSelection.Comma) {
188          Context.ReplacePopulation(nextGen.OrderBy(x => x.Fitness).Take(Mu));
189        } else if (Selection == ESSelection.Plus) {
190          var best = Context.Population.Concat(nextGen).OrderBy(x => x.Fitness).Take(Mu).ToList();
191          Context.ReplacePopulation(best);
192        } else throw new InvalidOperationException("Unknown Selection strategy: " + Selection);
193
194        IResult result;
195        if (ExecutionTime - lastUpdate > TimeSpan.FromSeconds(1)) {
196          if (Results.TryGetValue("Iterations", out result))
197            ((IntValue)result.Value).Value = Context.Iterations;
198          else Results.Add(new Result("Iterations", new IntValue(Context.Iterations)));
199          if (Results.TryGetValue("EvaluatedSolutions", out result))
200            ((IntValue)result.Value).Value = Context.EvaluatedSolutions;
201          else Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions)));
202          lastUpdate = ExecutionTime;
203        }
204        if (Results.TryGetValue("BestQuality", out result))
205          ((DoubleValue)result.Value).Value = Context.BestQuality;
206        else Results.Add(new Result("BestQuality", new DoubleValue(Context.BestQuality)));
207        if (Results.TryGetValue("BestSolution", out result))
208          result.Value = Context.BestSolution;
209        else Results.Add(new Result("BestSolution", Context.BestSolution));
210
211        try {
212          Context.RunOperator(Analyzer, cancellationToken);
213        } catch (OperationCanceledException) { }
214
215        Context.Iterations++;
216        if (cancellationToken.IsCancellationRequested) break;
217      }
218      IResult result2;
219      if (Results.TryGetValue("Iterations", out result2))
220        ((IntValue)result2.Value).Value = Context.Iterations;
221      else Results.Add(new Result("Iterations", new IntValue(Context.Iterations)));
222      if (Results.TryGetValue("EvaluatedSolutions", out result2))
223        ((IntValue)result2.Value).Value = Context.EvaluatedSolutions;
224      else Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions)));
225    }
226  }
227}
Note: See TracBrowser for help on using the repository browser.