Free cookie consent management tool by TermsFeed Policy Generator

source: branches/1614_GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/LAHC/pLAHC.cs @ 15775

Last change on this file since 15775 was 15700, checked in by abeham, 7 years ago

#1614:

  • Changed performance measure to stopwatch instead of datetime for precision reasons
File size: 9.7 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.Threading;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Encodings.IntegerVectorEncoding;
28using HeuristicLab.Optimization;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms.LAHC {
33  [Item("pLAHC-s (GQAP)", "Parameterless Late-acceptance hill climber for the GQAP.")]
34  [Creatable(CreatableAttribute.Categories.SingleSolutionAlgorithms)]
35  [StorableClass]
36  public sealed class PLAHCS : StochasticAlgorithm<PLAHCContext, IntegerVectorEncoding> {
37
38    public override bool SupportsPause {
39      get { return true; }
40    }
41
42    public override Type ProblemType {
43      get { return typeof(GQAP); }
44    }
45
46    public new GQAP Problem {
47      get { return (GQAP)base.Problem; }
48      set { base.Problem = value; }
49    }
50
51    [Storable]
52    private FixedValueParameter<IntValue> maximumExponentParameter;
53    public IFixedValueParameter<IntValue> MaximumExponentParameter {
54      get { return maximumExponentParameter; }
55    }
56
57    [Storable]
58    private FixedValueParameter<IntValue> minimumSprintIterationsParameter;
59    public IFixedValueParameter<IntValue> MinimumSprintIterationsParameter {
60      get { return minimumSprintIterationsParameter; }
61    }
62
63    public int MaximumExponent {
64      get { return maximumExponentParameter.Value.Value; }
65      set { maximumExponentParameter.Value.Value = value; }
66    }
67
68    public int MinimumSprintIterations {
69      get { return minimumSprintIterationsParameter.Value.Value; }
70      set { minimumSprintIterationsParameter.Value.Value = value; }
71    }
72
73    [StorableConstructor]
74    private PLAHCS(bool deserializing) : base(deserializing) { }
75    private PLAHCS(PLAHCS original, Cloner cloner)
76      : base(original, cloner) {
77      maximumExponentParameter = cloner.Clone(original.maximumExponentParameter);
78      minimumSprintIterationsParameter = cloner.Clone(original.minimumSprintIterationsParameter);
79    }
80    public PLAHCS() {
81      Parameters.Add(maximumExponentParameter = new FixedValueParameter<IntValue>("MaximumExponent", "The maximum power to which memory sizes should be tried (2^x). Do not set higher than 31", new IntValue(24)));
82      Parameters.Add(minimumSprintIterationsParameter = new FixedValueParameter<IntValue>("MinimumSprintIterations", "The minimum amount of iterations per sprint.", new IntValue(100000)));
83
84      Problem = new GQAP();
85    }
86   
87    public override IDeepCloneable Clone(Cloner cloner) {
88      return new PLAHCS(this, cloner);
89    }
90
91    protected override void Initialize(CancellationToken token) {
92      base.Initialize(token);
93
94      Context.Problem = Problem;
95      Context.LastSuccess = 0;
96
97      var assign = new IntegerVector(Problem.ProblemInstance.Demands.Length, Context.Random, 0, Problem.ProblemInstance.Capacities.Length);
98      var eval = Problem.ProblemInstance.Evaluate(assign);
99      var fit = Problem.ProblemInstance.ToSingleObjective(eval);
100      Context.EvaluatedSolutions++;
101
102      var candidate = new GQAPSolution(assign, eval);
103
104      Context.ReplaceIncumbent(Context.ToScope(candidate, fit));
105      Context.BestQuality = fit;
106      Context.BestSolution = (GQAPSolution)candidate.Clone();
107
108      Context.BestList = new ItemList<DoubleValue>(new[] { new DoubleValue(Context.BestQuality) });
109
110      Results.Add(new Result("Sprint Iterations", new IntValue(Context.SprintIterations)));
111      Results.Add(new Result("Iterations", new IntValue(Context.Iterations)));
112      Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions)));
113      Results.Add(new Result("CurrentMemorySize", new IntValue(0)));
114
115      try {
116        Context.RunOperator(Analyzer, token);
117      } catch (OperationCanceledException) { }
118    }
119
120    protected override void Run(CancellationToken cancellationToken) {
121      base.Run(cancellationToken);
122      var lastUpdate = ExecutionTime;
123      for (var i = 0; i <= MaximumExponent; i++) {
124        var l = (int)Math.Pow(2, i);
125        var memory = new double[l];
126        for (var vv = 0; vv < l; vv++)
127          memory[vv] = Context.BestList[Context.BestList.Count - 1 - (vv % Context.BestList.Count)].Value;
128        Array.Sort(memory);
129        Context.Memory = new DoubleArray(memory);
130        if (i > 0) Context.ReplaceIncumbent(Context.ToScope((GQAPSolution)Context.BestSolution.Clone(), Context.BestQuality));
131        IResult memorySizeResult;
132        if (Results.TryGetValue("CurrentMemorySize", out memorySizeResult))
133          ((IntValue)memorySizeResult.Value).Value = Context.Memory.Length;
134        else Results.Add(new Result("CurrentMemorySize", new IntValue(Context.Memory.Length)));
135
136        Context.SprintIterations = 0;
137        while (!StoppingCriterion()
138          && (Context.SprintIterations < MinimumSprintIterations
139          || (Context.SprintIterations - Context.LastSuccess) < Context.SprintIterations * 0.02)) {
140
141          var move = StochasticNMoveSingleMoveGenerator.GenerateOneMove(Context.Random,
142            Context.Incumbent.Solution.Assignment, Problem.ProblemInstance.Capacities);
143          var moveEval = GQAPNMoveEvaluator.Evaluate(move,
144            Context.Incumbent.Solution.Assignment,
145            Context.Incumbent.Solution.Evaluation, Problem.ProblemInstance);
146          if (Context.SprintIterations % Problem.ProblemInstance.Demands.Length == 0)
147            Context.EvaluatedSolutions++;
148          var nextFit = Problem.ProblemInstance.ToSingleObjective(moveEval);
149          var nextVec = new IntegerVector(Context.Incumbent.Solution.Assignment);
150          NMoveMaker.Apply(nextVec, move);
151
152          var v = Context.Iterations % Context.Memory.Length;
153          Context.Iterations++;
154          Context.SprintIterations++;
155          var prevFit = Context.Memory[v];
156
157          var accept = nextFit <= Context.Incumbent.Fitness
158                    || nextFit <= prevFit;
159
160          if (accept && nextFit < Context.Incumbent.Fitness)
161            Context.LastSuccess = Context.SprintIterations;
162
163          if (accept) {
164            Context.ReplaceIncumbent(Context.ToScope(new GQAPSolution(nextVec, moveEval), nextFit));
165            if (nextFit < Context.BestQuality) {
166              Context.BestSolution = (GQAPSolution)Context.Incumbent.Solution.Clone();
167              Context.BestQuality = nextFit;
168              Context.BestList.Add(new DoubleValue(Context.BestQuality));
169            }
170          }
171
172          if (Context.Incumbent.Fitness < prevFit)
173            Context.Memory[v] = Context.Incumbent.Fitness;
174
175          IResult result;
176          if (ExecutionTime - lastUpdate > TimeSpan.FromSeconds(1)) {
177            if (Results.TryGetValue("Iterations", out result))
178              ((IntValue)result.Value).Value = Context.Iterations;
179            else Results.Add(new Result("Iterations", new IntValue(Context.Iterations)));
180            if (Results.TryGetValue("Sprint Iterations", out result))
181              ((IntValue)result.Value).Value = Context.SprintIterations;
182            else Results.Add(new Result("Total Iterations", new IntValue(Context.SprintIterations)));
183            if (Results.TryGetValue("EvaluatedSolutions", out result))
184              ((IntValue)result.Value).Value = Context.EvaluatedSolutions;
185            else Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions)));
186            lastUpdate = ExecutionTime;
187          }
188          if (Results.TryGetValue("BestQuality", out result))
189            ((DoubleValue)result.Value).Value = Context.BestQuality;
190          else Results.Add(new Result("BestQuality", new DoubleValue(Context.BestQuality)));
191          if (Results.TryGetValue("BestSolution", out result))
192            result.Value = Context.BestSolution;
193          else Results.Add(new Result("BestSolution", Context.BestSolution));
194
195          try {
196            Context.RunOperator(Analyzer, cancellationToken);
197          } catch (OperationCanceledException) { }
198
199          if (cancellationToken.IsCancellationRequested) break;
200        }
201        if (StoppingCriterion() || cancellationToken.IsCancellationRequested) break;
202      }
203
204      IResult result2;
205      if (Results.TryGetValue("Iterations", out result2))
206        ((IntValue)result2.Value).Value = Context.Iterations;
207      else Results.Add(new Result("Iterations", new IntValue(Context.Iterations)));
208      if (Results.TryGetValue("Sprint Iterations", out result2))
209        ((IntValue)result2.Value).Value = Context.SprintIterations;
210      else Results.Add(new Result("Sprint Iterations", new IntValue(Context.SprintIterations)));
211      if (Results.TryGetValue("EvaluatedSolutions", out result2))
212        ((IntValue)result2.Value).Value = Context.EvaluatedSolutions;
213      else Results.Add(new Result("EvaluatedSolutions", new IntValue(Context.EvaluatedSolutions)));
214    }
215  }
216}
Note: See TracBrowser for help on using the repository browser.