Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.FixedOperators/3.2/FixedSGAMain.cs @ 1900

Last change on this file since 1900 was 1900, checked in by dtraxing, 15 years ago

new implementation for fixed sga main (ticket #580)

File size: 9.9 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      Stopwatch swApply = new Stopwatch();
117      swApply.Start();
118      for (int i = 0; i < SubOperators.Count; i++) {
119        if (scope.GetVariable(SubOperators[i].Name) != null)
120          scope.RemoveVariable(SubOperators[i].Name);
121        scope.AddVariable(new Variable(SubOperators[i].Name, SubOperators[i]));
122      }
123
124      OperatorBase selector = (OperatorBase)GetVariableValue("Selector", scope, true);
125      QualityLogger ql = new QualityLogger();
126
127      BestAverageWorstQualityCalculator bawqc = new BestAverageWorstQualityCalculator();
128      DataCollector dc = new DataCollector();
129      ItemList<StringData> names = dc.GetVariable("VariableNames").GetValue<ItemList<StringData>>();
130      names.Add(new StringData("BestQuality"));
131      names.Add(new StringData("AverageQuality"));
132      names.Add(new StringData("WorstQuality"));
133
134      LinechartInjector lci = new LinechartInjector();
135      lci.GetVariableInfo("Linechart").ActualName = "Quality Linechart";
136      lci.GetVariable("NumberOfLines").GetValue<IntData>().Data = 3;
137
138      LessThanComparator ltc = new LessThanComparator();
139      ltc.GetVariableInfo("LeftSide").ActualName = "Generations";
140      ltc.GetVariableInfo("RightSide").ActualName = "MaximumGenerations";
141      ltc.GetVariableInfo("Result").ActualName = "GenerationsCondition";
142
143      IntData maxGenerations = GetVariableValue<IntData>("MaximumGenerations", scope, true);
144      IntData nrOfGenerations = GetVariableValue<IntData>("Generations", scope, true);
145      //nrOfGenerations.Data = 0;
146
147      IntData subscopeNr;
148      try {
149        subscopeNr = scope.GetVariableValue<IntData>("SubScopeNr", false);
150      }
151      catch (Exception) {
152        subscopeNr = new IntData(0);
153        scope.AddVariable(new Variable("SubScopeNr", subscopeNr));
154      }
155
156      EmptyOperator empty = new EmptyOperator();
157
158      IScope s;
159      IScope s2;
160      int tempExePointer = 0;
161      int tempPersExePointer = 0;
162      // fetch variables from scope for create children
163      InitializeExecuteCreateChildren(scope);
164      try {
165        for (int i = nrOfGenerations.Data; i < maxGenerations.Data; i++) {
166          if (executionPointer == persistedExecutionPointer.Data)
167            persistedExecutionPointer.Data = 0;
168          executionPointer = 0;
169         
170          Execute(selector, scope);
171
172          ////// Create Children //////
173          // ChildrenInitializer
174          s = scope.SubScopes[1];
175          Execute(ci, s);
176         
177          tempExePointer = executionPointer;
178          tempPersExePointer = persistedExecutionPointer.Data;
179          // UniformSequentialSubScopesProcessor
180          for (int j = subscopeNr.Data; j < s.SubScopes.Count; j++ ) {
181            if (executionPointer == persistedExecutionPointer.Data)
182              persistedExecutionPointer.Data = tempExePointer;
183            executionPointer = tempExePointer;
184           
185            s2 = s.SubScopes[j];
186            Execute(crossover, s2);
187            // Stochastic Branch
188            if (random.NextDouble() < probability.Data)
189              Execute(mutator, s2);
190            else
191              Execute(empty, s2);
192            Execute(evaluator, s2);
193            Execute(sr, s2);
194            Execute(counter, s2);
195            subscopeNr.Data++;
196          } // foreach
197         
198
199          Execute(sorter, s);
200          ////// END Create Children //////
201
202          ExecuteCreateReplacementWithFixedConstrolStructures(scope);
203          Execute(ql, scope);
204          Execute(bawqc, scope);
205          Execute(dc, scope);
206          Execute(lci, scope);
207          subscopeNr.Data = 0;
208          nrOfGenerations.Data++;
209        } // for i
210      } // try
211      catch (CancelException) {
212        Console.WriteLine("Micro engine aborted by cancel flag.");
213      }
214
215      swApply.Stop();
216      Console.WriteLine("SGAMain.Apply(): {0}", swApply.Elapsed);
217
218      if (Canceled) {
219        return new AtomicOperation(this, scope);
220      }
221
222      return null;
223    } // Apply
224
225    private void WorkerMethod(object o) {
226     
227    } // Apply
228
229
230
231    /// <summary>
232    /// Initializes some variables needed before the execution of create children
233    /// </summary>
234    /// <param name="scope"></param>
235    private void InitializeExecuteCreateChildren(IScope scope) {
236      crossover = (OperatorBase)GetVariableValue("Crossover", scope, true);
237      mutator = (OperatorBase)GetVariableValue("Mutator", scope, true);
238      evaluator = GetVariableValue<OperatorBase>("Evaluator", scope, true);
239
240      random = GetVariableValue<IRandom>("Random", scope, true);
241      probability = GetVariableValue<DoubleData>("MutationRate", scope, true);
242
243      ci = new ChildrenInitializer();
244    }
245
246    /// <summary>
247    ///
248    /// </summary>
249    /// <param name="scope"></param>
250    protected void ExecuteCreateChildrenWithFixedControlStructures(IScope scope) {
251      // ChildrenInitializer
252      Execute(ci, scope);
253      // UniformSequentialSubScopesProcessor
254      foreach (IScope s in scope.SubScopes) {
255        Execute(crossover, s);
256        // Stochastic Branch
257        if (random.NextDouble() < probability.Data)
258          Execute(mutator, s);
259        Execute(evaluator, s);
260        Execute(sr, s);
261        Execute(counter, s);
262      } // foreach
263
264      Execute(sorter, scope);
265    } // ExecuteCreateChildrenHWCS
266
267    private void ExecuteCreateReplacementWithFixedConstrolStructures(IScope scope) {
268      //// SequentialSubScopesProcessor
269      Execute(ls, scope.SubScopes[0]);
270      Execute(rr, scope.SubScopes[0]);
271
272      Execute(rs, scope.SubScopes[1]);
273      Execute(lr, scope.SubScopes[1]);
274
275      Execute(mr, scope);
276      Execute(sorter, scope);
277    } // ExecuteCreateReplacementWithFixedConstrolStructures
278
279
280  } // class FixedSGAMain
281} // namespace HeuristicLab.FixedOperators
Note: See TracBrowser for help on using the repository browser.