Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive_Milestone2/sources/HeuristicLab.FixedOperators/3.2/FixedSGAMain.cs @ 2273

Last change on this file since 2273 was 1789, checked in by dtraxing, 16 years ago

improved support for algorithm abort. (ticket #580)

File size: 13.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Text;
25using System.Linq;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Permutation;
29using HeuristicLab.Evolutionary;
30using HeuristicLab.Operators;
31using HeuristicLab.Routing.TSP;
32using HeuristicLab.Logging;
33using System.Diagnostics;
34using HeuristicLab.Selection;
35using System.Threading;
36
37namespace HeuristicLab.FixedOperators {
38  class FixedSGAMain : FixedOperatorBase {
39    public override string Description {
40      get { return @"Implements the functionality of SGAMain with fixed control structures. Operators like selection, crossover, mutation and evaluation are delegated."; }
41    }
42
43    // Shared
44    Sorter sorter;
45
46    // CreateChildren
47    Counter counter;
48    IRandom random;
49    DoubleData probability;
50    ChildrenInitializer ci;
51    OperatorBase crossover;
52    OperatorBase mutator;
53    OperatorBase evaluator;
54    SubScopesRemover sr;
55
56    // CreateReplacement
57    LeftSelector ls;
58    RightReducer rr;
59    RightSelector rs;
60    LeftReducer lr;
61    MergingReducer mr;
62
63    Thread executionThread;
64    Thread cancelThread;
65
66
67    //long[] timesExecuteCreateChildren;
68    public FixedSGAMain()
69      : base() {
70      AddVariableInfo(new VariableInfo("Selector", "Selection strategy for SGA", typeof(OperatorBase), VariableKind.In));
71      AddVariableInfo(new VariableInfo("MaximumGenerations", "Maximum number of generations to create", typeof(IntData), VariableKind.In));
72      AddVariableInfo(new VariableInfo("Generations", "Number of processed generations", typeof(IntData), VariableKind.In | VariableKind.Out));
73
74      Name = "FixedSGAMain";
75
76      sorter = new Sorter();
77      sorter.GetVariableInfo("Descending").ActualName = "Maximization";
78      sorter.GetVariableInfo("Value").ActualName = "Quality";
79
80      InitVariablesForCreateChildren();
81      InitVariablesForCreateReplacement();
82    }
83
84    private void InitVariablesForCreateReplacement() {
85      ls = new LeftSelector();
86      rr = new RightReducer();
87      rs = new RightSelector();
88      lr = new LeftReducer();
89      mr = new MergingReducer();
90
91      ls.GetVariableInfo("Selected").ActualName = "Elites";
92      rs.GetVariableInfo("Selected").ActualName = "Elites";
93
94    }
95
96    protected void InitVariablesForCreateChildren() {
97      // variables for create children
98      ci = new ChildrenInitializer();
99
100      // variables infos
101      AddVariableInfo(new VariableInfo("Random", "Pseudo random number generator", typeof(IRandom), VariableKind.In));
102      AddVariableInfo(new VariableInfo("MutationRate", "Probability to choose first branch", typeof(DoubleData), VariableKind.In));
103      AddVariableInfo(new VariableInfo("Crossover", "Crossover strategy for SGA", typeof(OperatorBase), VariableKind.In));
104      AddVariableInfo(new VariableInfo("Mutator", "Mutation strategy for SGA", typeof(OperatorBase), VariableKind.In));
105      AddVariableInfo(new VariableInfo("Evaluator", "Evaluation strategy for SGA", typeof(OperatorBase), VariableKind.In));
106
107      sr = new SubScopesRemover();
108      sr.GetVariableInfo("SubScopeIndex").Local = true;
109
110      counter = new Counter();
111      counter.GetVariableInfo("Value").ActualName = "EvaluatedSolutions";
112    }
113
114    public override IOperation Apply(IScope scope) {
115      base.Apply(scope);
116      object o = (object)scope;
117      WorkerMethod(o);
118      //try {
119      //  executionThread = new Thread(new ParameterizedThreadStart(WorkerMethod));
120      //  executionThread.Name = "ExecutionThread";
121      //  executionThread.Start(o);
122
123      //  //cancelThread = new Thread(new ThreadStart(CheckCancelFlag));
124      //  //cancelThread.Name = "CancelFlagCheckerThread";
125      //  //cancelThread.Start();
126
127      //  executionThread.Join();
128      //}
129      //catch (ThreadAbortException) {
130      //  return new AtomicOperation(this, scope);
131      //}
132
133      if (Canceled) {
134        return new AtomicOperation(this, scope);
135      }
136
137      return null;
138    } // Apply
139
140    private void CheckCancelFlag() {
141      while (executionThread.IsAlive) {
142        if (Canceled) {
143          executionThread.Abort();
144          return;
145        }
146        Thread.Sleep(500);
147      } // while
148    } // CheckCancelFlag
149
150    private void WorkerMethod(object o) {
151      try {
152        IScope scope = o as IScope;
153        Stopwatch swApply = new Stopwatch();
154        swApply.Start();
155        for (int i = 0; i < SubOperators.Count; i++) {
156          if (scope.GetVariable(SubOperators[i].Name) != null)
157            scope.RemoveVariable(SubOperators[i].Name);
158          scope.AddVariable(new Variable(SubOperators[i].Name, SubOperators[i]));
159        }
160
161        OperatorBase selector = (OperatorBase)GetVariableValue("Selector", scope, true);
162        QualityLogger ql = new QualityLogger();
163
164        BestAverageWorstQualityCalculator bawqc = new BestAverageWorstQualityCalculator();
165        DataCollector dc = new DataCollector();
166        ItemList<StringData> names = dc.GetVariable("VariableNames").GetValue<ItemList<StringData>>();
167        names.Add(new StringData("BestQuality"));
168        names.Add(new StringData("AverageQuality"));
169        names.Add(new StringData("WorstQuality"));
170
171        LinechartInjector lci = new LinechartInjector();
172        lci.GetVariableInfo("Linechart").ActualName = "Quality Linechart";
173        lci.GetVariable("NumberOfLines").GetValue<IntData>().Data = 3;
174
175        LessThanComparator ltc = new LessThanComparator();
176        ltc.GetVariableInfo("LeftSide").ActualName = "Generations";
177        ltc.GetVariableInfo("RightSide").ActualName = "MaximumGenerations";
178        ltc.GetVariableInfo("Result").ActualName = "GenerationsCondition";
179
180        IntData maxGenerations = GetVariableValue<IntData>("MaximumGenerations", scope, true);
181        IntData nrOfGenerations = GetVariableValue<IntData>("Generations", scope, true);
182        nrOfGenerations.Data = 0;
183
184        threaded = false;
185        // fetch variables from scope for create children
186        InitializeExecuteCreateChildren(scope);
187        try {
188          //for (int i = nrOfGenerations.Data; i < maxGenerations.Data; i++) {
189          //  Execute(selector, scope, false);
190          //  ExecuteCreateChildrenWithFixedControlStructures(scope.SubScopes[1]);
191          //  ExecuteCreateReplacementWithFixedConstrolStructures(scope);
192          //  ql.Execute(scope);
193          //  bawqc.Execute(scope);
194          //  dc.Execute(scope);
195          //  lci.Execute(scope);
196          //  nrOfGenerations.Data++;
197          //} // for i
198          for (int i = 0; i < maxGenerations.Data; i++) {
199            Execute(selector, scope, false);
200            ExecuteCreateChildrenWithFixedControlStructures(scope.SubScopes[1]);
201            ExecuteCreateReplacementWithFixedConstrolStructures(scope);
202            Execute(ql, scope, false);
203            Execute(bawqc, scope, false);
204            Execute(dc, scope, false);
205            Execute(lci, scope, false);
206            nrOfGenerations.Data++;
207          } // for i
208        } // try
209        catch (CancelException) {
210          Console.WriteLine("Micro engine aborted by cancel flag.");
211        }
212
213        //for (int i = nrOfGenerations.Data; i < maxGenerations.Data && !Canceled; i++) {
214        //  if (Canceled) {
215        //    executionPointer.Data = -1;
216        //    continue;
217        //  }
218        //  if (executionPointer.Data < 0)
219        //    Execute(selector, scope);
220
221        //  if (Canceled) {
222        //    executionPointer.Data = 0;
223        //    continue;
224        //  }
225        //  if (executionPointer.Data < 1)
226        //    ExecuteCreateChildrenWithFixedControlStructures(scope.SubScopes[1]);
227
228        //  if (Canceled) {
229        //    executionPointer.Data = 1;
230        //    continue;
231        //  }
232        //  if (executionPointer.Data < 2)
233        //    ExecuteCreateReplacementWithFixedConstrolStructures(scope);
234
235        //  if (Canceled) {
236        //    executionPointer.Data = 2;
237        //    continue;
238        //  }
239        //  if (executionPointer.Data < 3) {
240        //    ql.Execute(scope);
241        //    bawqc.Execute(scope);
242        //    dc.Execute(scope);
243        //    lci.Execute(scope);
244        //    nrOfGenerations.Data++;
245        //  }
246        //  executionPointer.Data = -1;
247        //} // for i
248
249
250        //Stopwatch watch = new Stopwatch();
251        //long[] times = new long[10];
252        //timesExecuteCreateChildren = new long[10];
253        //for (int i = nrOfGenerations.Data; i < maxGenerations.Data && !Canceled; i++) {
254        //  watch.Start();
255        //  selector.Execute(scope);
256        //  watch.Stop();
257        //  times[0] += watch.ElapsedTicks;
258        //  watch.Reset();
259        //  watch.Start();
260        //  ExecuteCreateChildrenWithFixedControlStructures(scope.SubScopes[1]);
261        //  watch.Stop();
262        //  times[1] += watch.ElapsedTicks;
263        //  watch.Reset();
264        //  watch.Start();
265        //  ExecuteCreateReplacementWithFixedConstrolStructures(scope);
266        //  watch.Stop();
267        //  times[2] += watch.ElapsedTicks;
268        //  watch.Reset();
269        //  watch.Start();
270        //  ql.Execute(scope);
271        //  watch.Stop();
272        //  times[3] += watch.ElapsedTicks;
273        //  watch.Reset();
274        //  watch.Start();
275        //  bawqc.Execute(scope);
276        //  watch.Stop();
277        //  times[4] += watch.ElapsedTicks;
278        //  watch.Reset();
279        //  watch.Start();
280        //  dc.Execute(scope);
281        //  watch.Stop();
282        //  times[5] += watch.ElapsedTicks;
283        //  watch.Reset();
284        //  watch.Start();
285        //  lci.Execute(scope);
286        //  watch.Stop();
287        //  times[6] += watch.ElapsedTicks;
288        //  watch.Reset();
289        //  watch.Start();
290        //  nrOfGenerations.Data++;
291        //}
292
293        swApply.Stop();
294        Console.WriteLine("SGAMain.Apply(): {0}", swApply.Elapsed);
295
296        //if (Canceled) {
297        //  return new AtomicOperation(this, scope);
298        //}
299
300        //return null;
301
302      }
303      catch (ThreadAbortException) {
304
305        throw;
306      }
307    } // Apply
308
309
310
311    /// <summary>
312    /// Initializes some variables needed before the execution of create children
313    /// </summary>
314    /// <param name="scope"></param>
315    private void InitializeExecuteCreateChildren(IScope scope) {
316      crossover = (OperatorBase)GetVariableValue("Crossover", scope, true);
317      mutator = (OperatorBase)GetVariableValue("Mutator", scope, true);
318      evaluator = GetVariableValue<OperatorBase>("Evaluator", scope, true);
319
320      random = GetVariableValue<IRandom>("Random", scope, true);
321      probability = GetVariableValue<DoubleData>("MutationRate", scope, true);
322
323      ci = new ChildrenInitializer();
324    }
325
326    /// <summary>
327    ///
328    /// </summary>
329    /// <param name="scope"></param>
330    protected void ExecuteCreateChildrenWithFixedControlStructures(IScope scope) {
331      //// ChildrenInitializer
332      //ci.Apply(scope);
333      //// UniformSequentialSubScopesProcessor
334      //foreach (IScope s in scope.SubScopes) {
335      //  Execute(crossover, s, false);
336      //  // Stochastic Branch
337      //  if (random.NextDouble() < probability.Data)
338      //    Execute(mutator, s, false);
339      //  Execute(evaluator, s, false);
340      //  sr.Execute(s);
341      //  counter.Execute(s);
342      //} // foreach
343
344      //sorter.Execute(scope);
345
346      EmptyOperator empty = new EmptyOperator();
347
348      // ChildrenInitializer
349      Execute(ci, scope, false);
350      // UniformSequentialSubScopesProcessor
351      foreach (IScope s in scope.SubScopes) {
352        Execute(crossover, s, false);
353        // Stochastic Branch
354        if (random.NextDouble() < probability.Data)
355          Execute(mutator, s, false);
356        else
357          Execute(empty, s, false);
358        Execute(evaluator, s, false);
359        Execute(sr, s, false);
360        Execute(counter, s, false);
361      } // foreach
362
363      Execute(sorter, scope, false);
364    } // ExecuteCreateChildrenHWCS
365
366    private void ExecuteCreateReplacementWithFixedConstrolStructures(IScope scope) {
367      //// SequentialSubScopesProcessor
368      //ls.Execute(scope.SubScopes[0]);
369      //rr.Execute(scope.SubScopes[0]);
370
371      //rs.Execute(scope.SubScopes[1]);
372      //lr.Execute(scope.SubScopes[1]);
373
374      //mr.Execute(scope);
375      //sorter.Execute(scope);
376
377      Execute(ls, scope.SubScopes[0], false);
378      Execute(rr, scope.SubScopes[0], false);
379
380      Execute(rs, scope.SubScopes[1], false);
381      Execute(lr, scope.SubScopes[1], false);
382
383      Execute(mr, scope, false);
384      Execute(sorter, scope, false);
385
386    } // ExecuteCreateReplacementWithFixedConstrolStructures
387
388    //public override void Abort() {
389    //  base.Abort();
390    //  executionThread.Abort();
391    //} // Abort
392
393  } // class FixedSGAMain
394} // namespace HeuristicLab.FixedOperators
Note: See TracBrowser for help on using the repository browser.