Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/Evolutionary/EvolutionStrategy.cs @ 17357

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

#1614: updated to new persistence and .NET 4.6.1

File size: 10.2 KB
RevLine 
[15553]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;
[15562]23using System.Collections.Generic;
[15553]24using System.Linq;
25using System.Threading;
[16728]26using HEAL.Attic;
[15553]27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Encodings.IntegerVectorEncoding;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.Random;
34
[15562]35namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms.Evolutionary {
[16728]36  [StorableType("d568d524-1f84-461c-adf5-573d8e472063")]
[15562]37  public enum ESSelection { Plus = 0, Comma = 1 }
[15553]38
[15562]39  [Item("Evolution Strategy (GQAP)", "The algorithm implements a simple evolution strategy (ES).")]
[15553]40  [Creatable(CreatableAttribute.Categories.PopulationBasedAlgorithms)]
[16728]41  [StorableType("A1590185-F2E3-4163-896E-28EEC93A5CDF")]
[15572]42  public sealed class EvolutionStrategy : StochasticAlgorithm<ESContext, IntegerVectorEncoding> {
[15553]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]
[15562]58    private FixedValueParameter<IntValue> lambdaParameter;
59    private IFixedValueParameter<IntValue> LambdaParameter {
60      get { return lambdaParameter; }
[15553]61    }
62    [Storable]
[15562]63    private FixedValueParameter<IntValue> muParameter;
64    public IFixedValueParameter<IntValue> MuParameter {
65      get { return muParameter; }
[15553]66    }
67    [Storable]
[15562]68    private FixedValueParameter<EnumValue<ESSelection>> selectionParameter;
69    public IFixedValueParameter<EnumValue<ESSelection>> SelectionParameter {
70      get { return selectionParameter; }
[15553]71    }
[15564]72    [Storable]
73    private FixedValueParameter<BoolValue> useRecombinationParameter;
74    public IFixedValueParameter<BoolValue> UseRecombinationParameter {
75      get { return useRecombinationParameter; }
76    }
[15562]77
78    public int Lambda {
79      get { return lambdaParameter.Value.Value; }
80      set { lambdaParameter.Value.Value = value; }
[15553]81    }
[15562]82    public int Mu {
83      get { return muParameter.Value.Value; }
84      set { muParameter.Value.Value = value; }
[15553]85    }
[15562]86    public ESSelection Selection {
87      get { return selectionParameter.Value.Value; }
88      set { selectionParameter.Value.Value = value; }
[15553]89    }
[15564]90    public bool UseRecombination {
91      get { return useRecombinationParameter.Value.Value; }
92      set { useRecombinationParameter.Value.Value = value; }
93    }
[15553]94
95    [StorableConstructor]
[16728]96    private EvolutionStrategy(StorableConstructorFlag _) : base(_) { }
[15562]97    private EvolutionStrategy(EvolutionStrategy original, Cloner cloner)
[15553]98      : base(original, cloner) {
[15562]99      lambdaParameter = cloner.Clone(original.lambdaParameter);
100      muParameter = cloner.Clone(original.muParameter);
101      selectionParameter = cloner.Clone(original.selectionParameter);
[15564]102      useRecombinationParameter = cloner.Clone(original.useRecombinationParameter);
[15553]103    }
[15562]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)));
[15564]108      Parameters.Add(useRecombinationParameter = new FixedValueParameter<BoolValue>("Use Recombination", "Whether to create an \"intermediate\" solution to perform the mutation from.", new BoolValue(false)));
109
[15553]110      Problem = new GQAP();
111    }
112
113    public override IDeepCloneable Clone(Cloner cloner) {
[15562]114      return new EvolutionStrategy(this, cloner);
[15553]115    }
116
117    protected override void Initialize(CancellationToken cancellationToken) {
118      base.Initialize(cancellationToken);
119
[15563]120      Context.NormalRand = new NormalDistributedRandom(Context.Random, 0, 1);
[15700]121      Context.Problem = Problem;
[15562]122      Context.BestSolution = null;
[15563]123     
[15562]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
[15564]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));
[15562]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        }
[15553]140      }
141
[15562]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));
[15553]146
[15574]147      Context.RunOperator(Analyzer, cancellationToken);
[15553]148    }
149
150    protected override void Run(CancellationToken cancellationToken) {
[15700]151      base.Run(cancellationToken);
[15563]152      var lastUpdate = ExecutionTime;
[15564]153      var eq = new IntegerVectorEqualityComparer();
[15563]154
[15562]155      while (!StoppingCriterion()) {
156        var nextGen = new List<ISingleObjectiveSolutionScope<ESGQAPSolution>>(Lambda);
[15553]157
[15562]158        for (var l = 0; l < Lambda; l++) {
[15564]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++;
[15553]174
[15564]175          var offspring = new ESGQAPSolution(child, eval, sParam);
[15562]176
177          var fit = Problem.ProblemInstance.ToSingleObjective(offspring.Evaluation);
[15564]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));
[15562]180
181          if (fit < Context.BestQuality) {
182            Context.BestQuality = fit;
183            Context.BestSolution = (ESGQAPSolution)offspring.Clone();
[15553]184          }
185        }
186
[15562]187        if (Selection == ESSelection.Comma) {
188          Context.ReplacePopulation(nextGen.OrderBy(x => x.Fitness).Take(Mu));
189        } else if (Selection == ESSelection.Plus) {
[15564]190          var best = Context.Population.Concat(nextGen).OrderBy(x => x.Fitness).Take(Mu).ToList();
[15562]191          Context.ReplacePopulation(best);
192        } else throw new InvalidOperationException("Unknown Selection strategy: " + Selection);
193
[15553]194        IResult result;
[15563]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        }
[15553]204        if (Results.TryGetValue("BestQuality", out result))
[15562]205          ((DoubleValue)result.Value).Value = Context.BestQuality;
206        else Results.Add(new Result("BestQuality", new DoubleValue(Context.BestQuality)));
[15553]207        if (Results.TryGetValue("BestSolution", out result))
[15562]208          result.Value = Context.BestSolution;
209        else Results.Add(new Result("BestSolution", Context.BestSolution));
[15553]210
[15564]211        try {
[15574]212          Context.RunOperator(Analyzer, cancellationToken);
[15564]213        } catch (OperationCanceledException) { }
[15558]214
[15562]215        Context.Iterations++;
216        if (cancellationToken.IsCancellationRequested) break;
[15553]217      }
[15563]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)));
[15553]225    }
226  }
227}
Note: See TracBrowser for help on using the repository browser.