Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GeneralizedQAP/HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms/3.3/GRASPContext.cs @ 15553

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

#1614:

  • Implementing basic algorithm according to paper (rechecking all operators)
  • Checking implementation with paper
  • Improved speed of move generator
  • Improved speed of randomized solution creator
File size: 14.0 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.Runtime.CompilerServices;
26using System.Threading;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.Random;
34
35namespace HeuristicLab.Problems.GeneralizedQuadraticAssignment.Algorithms.GRASP {
36  [Item("GRASP+PR (GQAP) Context", "Context for GRASP+PR (GQAP).")]
37  [StorableClass]
38  public sealed class GRASPContext : ParameterizedNamedItem, IExecutionContext {
39   
40    private IExecutionContext parent;
41    public IExecutionContext Parent {
42      get { return parent; }
43      set { parent = value; }
44    }
45
46    [Storable]
47    private IScope scope;
48    public IScope Scope {
49      get { return scope; }
50      private set { scope = value; }
51    }
52
53    IKeyedItemCollection<string, IParameter> IExecutionContext.Parameters {
54      get { return Parameters; }
55    }
56
57    [Storable]
58    private IValueParameter<GQAP> problem;
59    public GQAP Problem {
60      get { return problem.Value; }
61      set { problem.Value = value; }
62    }
63    public bool Maximization {
64      get { return Problem.Maximization; }
65    }
66
67    [Storable]
68    private IValueParameter<BoolValue> initialized;
69    public bool Initialized {
70      get { return initialized.Value.Value; }
71      set { initialized.Value.Value = value; }
72    }
73
74    [Storable]
75    private IValueParameter<IntValue> iterations;
76    public int Iterations {
77      get { return iterations.Value.Value; }
78      set { iterations.Value.Value = value; }
79    }
80
81    [Storable]
82    private IValueParameter<IntValue> evaluatedSolutions;
83    public int EvaluatedSolutions {
84      get { return evaluatedSolutions.Value.Value; }
85      set { evaluatedSolutions.Value.Value = value; }
86    }
87
88    [Storable]
89    private IValueParameter<DoubleValue> bestQuality;
90    public double BestQuality {
91      get { return bestQuality.Value.Value; }
92      set { bestQuality.Value.Value = value; }
93    }
94
95    [Storable]
96    private IValueParameter<GQAPSolution> bestSolution;
97    public GQAPSolution BestSolution {
98      get { return bestSolution.Value; }
99      set { bestSolution.Value = value; }
100    }
101
102    [Storable]
103    private IValueParameter<IntValue> localSearchEvaluations;
104    public int LocalSearchEvaluations {
105      get { return localSearchEvaluations.Value.Value; }
106      set { localSearchEvaluations.Value.Value = value; }
107    }
108   
109    [Storable]
110    private IValueParameter<IRandom> random;
111    public IRandom Random {
112      get { return random.Value; }
113      set { random.Value = value; }
114    }
115
116    public IEnumerable<ISingleObjectiveSolutionScope<GQAPSolution>> Population {
117      get { return scope.SubScopes.OfType<ISingleObjectiveSolutionScope<GQAPSolution>>(); }
118    }
119    public void AddToPopulation(ISingleObjectiveSolutionScope<GQAPSolution> solScope) {
120      scope.SubScopes.Add(solScope);
121    }
122    public void ReplaceAtPopulation(int index, ISingleObjectiveSolutionScope<GQAPSolution> solScope) {
123      scope.SubScopes[index] = solScope;
124    }
125    public ISingleObjectiveSolutionScope<GQAPSolution> AtPopulation(int index) {
126      return scope.SubScopes[index] as ISingleObjectiveSolutionScope<GQAPSolution>;
127    }
128    public void SortPopulation() {
129      scope.SubScopes.Replace(scope.SubScopes.OfType<ISingleObjectiveSolutionScope<GQAPSolution>>().OrderBy(x => Maximization ? -x.Fitness : x.Fitness).ToList());
130    }
131    public int PopulationCount {
132      get { return scope.SubScopes.Count; }
133    }
134   
135    [StorableConstructor]
136    private GRASPContext(bool deserializing) : base(deserializing) { }
137    private GRASPContext(GRASPContext original, Cloner cloner)
138      : base(original, cloner) {
139      scope = cloner.Clone(original.scope);
140      problem = cloner.Clone(original.problem);
141      initialized = cloner.Clone(original.initialized);
142      iterations = cloner.Clone(original.iterations);
143      evaluatedSolutions = cloner.Clone(original.evaluatedSolutions);
144      bestQuality = cloner.Clone(original.bestQuality);
145      bestSolution = cloner.Clone(original.bestSolution);
146      localSearchEvaluations = cloner.Clone(original.localSearchEvaluations);
147      random = cloner.Clone(original.random);
148    }
149    public GRASPContext() : this("GRASP+PR (GQAP) Context") { }
150    public GRASPContext(string name) : base(name) {
151      scope = new Scope("Global");
152
153      Parameters.Add(problem = new ValueParameter<GQAP>("Problem"));
154      Parameters.Add(initialized = new ValueParameter<BoolValue>("Initialized", new BoolValue(false)));
155      Parameters.Add(iterations = new ValueParameter<IntValue>("Iterations", new IntValue(0)));
156      Parameters.Add(evaluatedSolutions = new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue(0)));
157      Parameters.Add(bestQuality = new ValueParameter<DoubleValue>("BestQuality", new DoubleValue(double.NaN)));
158      Parameters.Add(bestSolution = new ValueParameter<GQAPSolution>("BestFoundSolution"));
159      Parameters.Add(localSearchEvaluations = new ValueParameter<IntValue>("LocalSearchEvaluations", new IntValue(0)));
160      Parameters.Add(random = new ValueParameter<IRandom>("Random", new MersenneTwister()));
161    }
162
163    public override IDeepCloneable Clone(Cloner cloner) {
164      return new GRASPContext(this, cloner);
165    }
166
167    public ISingleObjectiveSolutionScope<GQAPSolution> ToScope(GQAPSolution code, double fitness = double.NaN) {
168      var name = Problem.Encoding.Name;
169      var scope = new SingleObjectiveSolutionScope<GQAPSolution>(code,
170        name + "Solution", fitness, Problem.Evaluator.QualityParameter.ActualName) {
171        Parent = Scope
172      };
173      scope.Variables.Add(new Variable(name, code.Assignment));
174      scope.Variables.Add(new Variable("Evaluation", code.Evaluation));
175      return scope;
176    }
177
178    public double Evaluate(GQAPSolution solution, CancellationToken token) {
179      var solScope = ToScope(solution);
180      Evaluate(solScope, token);
181      return solScope.Fitness;
182    }
183
184    public void Evaluate(ISingleObjectiveSolutionScope<GQAPSolution> solScope, CancellationToken token) {
185      var pdef = Problem as ISingleObjectiveProblemDefinition;
186      if (pdef != null) {
187        var ind = new SingleEncodingIndividual(pdef.Encoding, solScope);
188        solScope.Fitness = pdef.Evaluate(ind, Random);
189      } else {
190        RunOperator(Problem.Evaluator, solScope, token);
191      }
192    }
193
194    public GRASPSolutionContext CreateSingleSolutionContext(ISingleObjectiveSolutionScope<GQAPSolution> solution) {
195      return new GRASPSolutionContext(this, solution);
196    }
197
198    public void IncrementEvaluatedSolutions(int byEvaluations) {
199      if (byEvaluations < 0) throw new ArgumentException("Can only increment and not decrement evaluated solutions.");
200      EvaluatedSolutions += byEvaluations;
201    }
202   
203    private static void ExecuteAlgorithm(IAlgorithm algorithm) {
204      using (var evt = new AutoResetEvent(false)) {
205        EventHandler exeStateChanged = (o, args) => {
206          if (algorithm.ExecutionState != ExecutionState.Started)
207            evt.Set();
208        };
209        algorithm.ExecutionStateChanged += exeStateChanged;
210        if (algorithm.ExecutionState != ExecutionState.Prepared) {
211          algorithm.Prepare(true);
212          evt.WaitOne();
213        }
214        algorithm.Start();
215        evt.WaitOne();
216        algorithm.ExecutionStateChanged -= exeStateChanged;
217      }
218    }
219    [MethodImpl(MethodImplOptions.AggressiveInlining)]
220    public bool IsBetter(ISingleObjectiveSolutionScope<GQAPSolution> a, ISingleObjectiveSolutionScope<GQAPSolution> b) {
221      return IsBetter(a.Fitness, b.Fitness);
222    }
223    [MethodImpl(MethodImplOptions.AggressiveInlining)]
224    public bool IsBetter(double a, double b) {
225      return double.IsNaN(b) && !double.IsNaN(a)
226        || Maximization && a > b
227        || !Maximization && a < b;
228    }
229
230    #region IExecutionContext members
231    public IAtomicOperation CreateOperation(IOperator op) {
232      return new Core.ExecutionContext(this, op, Scope);
233    }
234
235    public IAtomicOperation CreateOperation(IOperator op, IScope s) {
236      return new Core.ExecutionContext(this, op, s);
237    }
238
239    public IAtomicOperation CreateChildOperation(IOperator op) {
240      return new Core.ExecutionContext(this, op, Scope);
241    }
242
243    public IAtomicOperation CreateChildOperation(IOperator op, IScope s) {
244      return new Core.ExecutionContext(this, op, s);
245    }
246    #endregion
247
248    #region Engine Helper
249    public void RunOperator(IOperator op, IScope scope, CancellationToken cancellationToken) {
250      var stack = new Stack<IOperation>();
251      stack.Push(CreateChildOperation(op, scope));
252
253      while (stack.Count > 0) {
254        cancellationToken.ThrowIfCancellationRequested();
255
256        var next = stack.Pop();
257        if (next is OperationCollection) {
258          var coll = (OperationCollection)next;
259          for (int i = coll.Count - 1; i >= 0; i--)
260            if (coll[i] != null) stack.Push(coll[i]);
261        } else if (next is IAtomicOperation) {
262          var operation = (IAtomicOperation)next;
263          try {
264            next = operation.Operator.Execute((IExecutionContext)operation, cancellationToken);
265          } catch (Exception ex) {
266            stack.Push(operation);
267            if (ex is OperationCanceledException) throw ex;
268            else throw new OperatorExecutionException(operation.Operator, ex);
269          }
270          if (next != null) stack.Push(next);
271        }
272      }
273    }
274    #endregion
275  }
276
277  [Item("GRASP+PR (GQAP) SolutionContext", "SolutionContext for GRASP+PR (GQAP).")]
278  [StorableClass]
279  public sealed class GRASPSolutionContext : ParameterizedNamedItem, IExecutionContext {
280
281    private GRASPContext parent;
282    public IExecutionContext Parent {
283      get { return parent; }
284      set { throw new InvalidOperationException("Cannot set the parent of a single-solution context."); }
285    }
286
287    [Storable]
288    private ISingleObjectiveSolutionScope<GQAPSolution> scope;
289    public IScope Scope {
290      get { return scope; }
291    }
292
293    IKeyedItemCollection<string, IParameter> IExecutionContext.Parameters {
294      get { return Parameters; }
295    }
296
297    public GQAP Problem {
298      get { return parent.Problem; }
299    }
300    public bool Maximization {
301      get { return parent.Maximization; }
302    }
303
304    public double BestQuality {
305      get { return parent.BestQuality; }
306      set { parent.BestQuality = value; }
307    }
308
309    public GQAPSolution BestSolution {
310      get { return parent.BestSolution; }
311      set { parent.BestSolution = value; }
312    }
313
314    public IRandom Random {
315      get { return parent.Random; }
316    }
317
318    [Storable]
319    private IValueParameter<IntValue> evaluatedSolutions;
320    public int EvaluatedSolutions {
321      get { return evaluatedSolutions.Value.Value; }
322      set { evaluatedSolutions.Value.Value = value; }
323    }
324
325    [Storable]
326    private IValueParameter<IntValue> iterations;
327    public int Iterations {
328      get { return iterations.Value.Value; }
329      set { iterations.Value.Value = value; }
330    }
331
332    [StorableConstructor]
333    private GRASPSolutionContext(bool deserializing) : base(deserializing) { }
334    private GRASPSolutionContext(GRASPSolutionContext original, Cloner cloner)
335      : base(original, cloner) {
336      scope = cloner.Clone(original.scope);
337      evaluatedSolutions = cloner.Clone(original.evaluatedSolutions);
338      iterations = cloner.Clone(original.iterations);
339    }
340    public GRASPSolutionContext(GRASPContext baseContext, ISingleObjectiveSolutionScope<GQAPSolution> solution) {
341      parent = baseContext;
342      scope = solution;
343
344      Parameters.Add(evaluatedSolutions = new ValueParameter<IntValue>("EvaluatedSolutions", new IntValue(0)));
345      Parameters.Add(iterations = new ValueParameter<IntValue>("Iterations", new IntValue(0)));
346    }
347
348    public override IDeepCloneable Clone(Cloner cloner) {
349      return new GRASPSolutionContext(this, cloner);
350    }
351
352    public void IncrementEvaluatedSolutions(int byEvaluations) {
353      if (byEvaluations < 0) throw new ArgumentException("Can only increment and not decrement evaluated solutions.");
354      EvaluatedSolutions += byEvaluations;
355    }
356    public double Evaluate(GQAPSolution solution, CancellationToken token) {
357      return parent.Evaluate(solution, token);
358    }
359
360    public void Evaluate(ISingleObjectiveSolutionScope<GQAPSolution> solScope, CancellationToken token) {
361      parent.Evaluate(solScope, token);
362    }
363
364    #region IExecutionContext members
365    public IAtomicOperation CreateOperation(IOperator op) {
366      return new Core.ExecutionContext(this, op, Scope);
367    }
368
369    public IAtomicOperation CreateOperation(IOperator op, IScope s) {
370      return new Core.ExecutionContext(this, op, s);
371    }
372
373    public IAtomicOperation CreateChildOperation(IOperator op) {
374      return new Core.ExecutionContext(this, op, Scope);
375    }
376
377    public IAtomicOperation CreateChildOperation(IOperator op, IScope s) {
378      return new Core.ExecutionContext(this, op, s);
379    }
380    #endregion
381  }
382}
Note: See TracBrowser for help on using the repository browser.