Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Operator Architecture Refactoring/HeuristicLab.FixedOperators/3.2/FixedSGAMain.cs @ 2498

Last change on this file since 2498 was 1923, checked in by dtraxing, 16 years ago

Added debugging code (ticket #580)

File size: 10.1 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    StringBuilder output = new StringBuilder();
66
67
68    //long[] timesExecuteCreateChildren;
69    public FixedSGAMain()
70      : base() {
71      AddVariableInfo(new VariableInfo("Selector", "Selection strategy for SGA", typeof(OperatorBase), VariableKind.In));
72      AddVariableInfo(new VariableInfo("MaximumGenerations", "Maximum number of generations to create", typeof(IntData), VariableKind.In));
73      AddVariableInfo(new VariableInfo("Generations", "Number of processed generations", typeof(IntData), VariableKind.In | VariableKind.Out));
74
75      Name = "FixedSGAMain";
76
77      sorter = new Sorter();
78      sorter.GetVariableInfo("Descending").ActualName = "Maximization";
79      sorter.GetVariableInfo("Value").ActualName = "Quality";
80
81      InitVariablesForCreateChildren();
82      InitVariablesForCreateReplacement();
83    }
84
85    private void InitVariablesForCreateReplacement() {
86      ls = new LeftSelector();
87      rr = new RightReducer();
88      rs = new RightSelector();
89      lr = new LeftReducer();
90      mr = new MergingReducer();
91
92      ls.GetVariableInfo("Selected").ActualName = "Elites";
93      rs.GetVariableInfo("Selected").ActualName = "Elites";
94
95    }
96
97    protected void InitVariablesForCreateChildren() {
98      // variables for create children
99      ci = new ChildrenInitializer();
100
101      // variables infos
102      AddVariableInfo(new VariableInfo("Random", "Pseudo random number generator", typeof(IRandom), VariableKind.In));
103      AddVariableInfo(new VariableInfo("MutationRate", "Probability to choose first branch", typeof(DoubleData), VariableKind.In));
104      AddVariableInfo(new VariableInfo("Crossover", "Crossover strategy for SGA", typeof(OperatorBase), VariableKind.In));
105      AddVariableInfo(new VariableInfo("Mutator", "Mutation strategy for SGA", typeof(OperatorBase), VariableKind.In));
106      AddVariableInfo(new VariableInfo("Evaluator", "Evaluation strategy for SGA", typeof(OperatorBase), VariableKind.In));
107
108      sr = new SubScopesRemover();
109      sr.GetVariableInfo("SubScopeIndex").Local = true;
110
111      counter = new Counter();
112      counter.GetVariableInfo("Value").ActualName = "EvaluatedSolutions";
113    }
114
115    public override IOperation Apply(IScope scope) {
116      base.Apply(scope);
117      Stopwatch swApply = new Stopwatch();
118      swApply.Start();
119      for (int i = 0; i < SubOperators.Count; i++) {
120        if (scope.GetVariable(SubOperators[i].Name) != null)
121          scope.RemoveVariable(SubOperators[i].Name);
122        scope.AddVariable(new Variable(SubOperators[i].Name, SubOperators[i]));
123      }
124
125      OperatorBase selector = (OperatorBase)GetVariableValue("Selector", scope, true);
126      QualityLogger ql = new QualityLogger();
127
128      BestAverageWorstQualityCalculator bawqc = new BestAverageWorstQualityCalculator();
129      DataCollector dc = new DataCollector();
130      ItemList<StringData> names = dc.GetVariable("VariableNames").GetValue<ItemList<StringData>>();
131      names.Add(new StringData("BestQuality"));
132      names.Add(new StringData("AverageQuality"));
133      names.Add(new StringData("WorstQuality"));
134
135      LinechartInjector lci = new LinechartInjector();
136      lci.GetVariableInfo("Linechart").ActualName = "Quality Linechart";
137      lci.GetVariable("NumberOfLines").GetValue<IntData>().Data = 3;
138
139      LessThanComparator ltc = new LessThanComparator();
140      ltc.GetVariableInfo("LeftSide").ActualName = "Generations";
141      ltc.GetVariableInfo("RightSide").ActualName = "MaximumGenerations";
142      ltc.GetVariableInfo("Result").ActualName = "GenerationsCondition";
143
144      IntData maxGenerations = GetVariableValue<IntData>("MaximumGenerations", scope, true);
145      IntData nrOfGenerations = GetVariableValue<IntData>("Generations", scope, true);
146      //nrOfGenerations.Data = 0;
147
148      IntData subscopeNr;
149      try {
150        subscopeNr = scope.GetVariableValue<IntData>("SubScopeNr", false);
151      }
152      catch (Exception) {
153        subscopeNr = new IntData(0);
154        scope.AddVariable(new Variable("SubScopeNr", subscopeNr));
155      }
156
157      EmptyOperator empty = new EmptyOperator();
158
159      IScope s;
160      IScope s2;
161      int tempExePointer = 0;
162      int tempPersExePointer = 0;
163      double randomNumber;
164     
165      // fetch variables from scope for create children
166      InitializeExecuteCreateChildren(scope);
167      try {
168        for (int i = nrOfGenerations.Data; i < maxGenerations.Data; i++) {
169          if (executionPointer == persistedExecutionPointer.Data)
170            persistedExecutionPointer.Data = 0;
171          executionPointer = 0;
172
173          Execute(selector, scope);
174
175          ////// Create Children //////
176          // ChildrenInitializer
177          s = scope.SubScopes[1];
178          Execute(ci, s);
179
180          tempExePointer = executionPointer;
181          tempPersExePointer = persistedExecutionPointer.Data;
182          // UniformSequentialSubScopesProcessor
183          for (int j = subscopeNr.Data; j < s.SubScopes.Count; j++) {
184            if (executionPointer == persistedExecutionPointer.Data)
185              persistedExecutionPointer.Data = tempExePointer;
186            executionPointer = tempExePointer;
187
188            s2 = s.SubScopes[j];
189            Execute(crossover, s2);
190            // Stochastic Branch
191
192            randomNumber = random.NextDouble();
193            //output.AppendLine(randomNumber.ToString());
194            if (randomNumber < probability.Data)
195              Execute(mutator, s2);
196            else
197              Execute(empty, s2);
198            Execute(evaluator, s2);
199            Execute(sr, s2);
200            Execute(counter, s2);
201            subscopeNr.Data++;
202          } // foreach
203
204
205          Execute(sorter, s);
206          ////// END Create Children //////
207
208          ExecuteCreateReplacementWithFixedConstrolStructures(scope);
209          Execute(ql, scope);
210          Execute(bawqc, scope);
211          Execute(dc, scope);
212          Execute(lci, scope);
213          subscopeNr.Data = 0;
214          nrOfGenerations.Data++;
215        } // for i
216
217
218
219      } // try
220      catch (CancelException) {
221        Console.WriteLine("Micro engine aborted by cancel flag.");
222      }
223      catch (Exception) {
224         
225      }
226
227      swApply.Stop();
228      Console.WriteLine("SGAMain.Apply(): {0}", swApply.Elapsed);
229
230      if (Canceled) {
231        return new AtomicOperation(this, scope);
232      }
233
234      return null;
235    } // Apply
236
237    private void WorkerMethod(object o) {
238     
239    } // Apply
240
241
242
243    /// <summary>
244    /// Initializes some variables needed before the execution of create children
245    /// </summary>
246    /// <param name="scope"></param>
247    private void InitializeExecuteCreateChildren(IScope scope) {
248      crossover = (OperatorBase)GetVariableValue("Crossover", scope, true);
249      mutator = (OperatorBase)GetVariableValue("Mutator", scope, true);
250      evaluator = GetVariableValue<OperatorBase>("Evaluator", scope, true);
251
252      random = GetVariableValue<IRandom>("Random", scope, true);
253      probability = GetVariableValue<DoubleData>("MutationRate", scope, true);
254
255      ci = new ChildrenInitializer();
256    }
257
258    /// <summary>
259    ///
260    /// </summary>
261    /// <param name="scope"></param>
262    protected void ExecuteCreateChildrenWithFixedControlStructures(IScope scope) {
263      // ChildrenInitializer
264      Execute(ci, scope);
265      // UniformSequentialSubScopesProcessor
266      foreach (IScope s in scope.SubScopes) {
267        Execute(crossover, s);
268        // Stochastic Branch
269        if (random.NextDouble() < probability.Data)
270          Execute(mutator, s);
271        Execute(evaluator, s);
272        Execute(sr, s);
273        Execute(counter, s);
274      } // foreach
275
276      Execute(sorter, scope);
277    } // ExecuteCreateChildrenHWCS
278
279    private void ExecuteCreateReplacementWithFixedConstrolStructures(IScope scope) {
280      //// SequentialSubScopesProcessor
281      Execute(ls, scope.SubScopes[0]);
282      Execute(rr, scope.SubScopes[0]);
283
284      Execute(rs, scope.SubScopes[1]);
285      Execute(lr, scope.SubScopes[1]);
286
287      Execute(mr, scope);
288      Execute(sorter, scope);
289    } // ExecuteCreateReplacementWithFixedConstrolStructures
290
291
292  } // class FixedSGAMain
293} // namespace HeuristicLab.FixedOperators
Note: See TracBrowser for help on using the repository browser.