Free cookie consent management tool by TermsFeed Policy Generator

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

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

Bug with non deterministic SGA execution fixed. (ticket #580)

File size: 9.7 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;
36using System.IO;
37using HeuristicLab.Random;
38
39namespace HeuristicLab.FixedOperators {
40  class FixedSGAMain : FixedOperatorBase {
41    public override string Description {
42      get { return @"Implements the functionality of SGAMain with fixed control structures. Operators like selection, crossover, mutation and evaluation are delegated."; }
43    }
44
45    // Shared
46    Sorter sorter;
47
48    // CreateChildren
49    Counter counter;
50    IRandom random;
51    DoubleData probability;
52    ChildrenInitializer ci;
53    OperatorBase crossover;
54    OperatorBase mutator;
55    OperatorBase evaluator;
56    SubScopesRemover sr;
57    StochasticBranch sb;
58
59    OperatorBase selector;
60
61    // CreateReplacement
62    LeftSelector ls;
63    RightReducer rr;
64    RightSelector rs;
65    LeftReducer lr;
66    MergingReducer mr;
67
68    Thread executionThread;
69    Thread cancelThread;
70   
71    // for testing only
72    QualityLogger ql;
73    BestAverageWorstQualityCalculator bawqc;
74    DataCollector dc;
75    ItemList<StringData> names;
76    LinechartInjector lci;
77
78    //long[] timesExecuteCreateChildren;
79    public FixedSGAMain()
80      : base() {
81      AddVariableInfo(new VariableInfo("Selector", "Selection strategy for SGA", typeof(OperatorBase), VariableKind.In));
82      AddVariableInfo(new VariableInfo("MaximumGenerations", "Maximum number of generations to create", typeof(IntData), VariableKind.In));
83      AddVariableInfo(new VariableInfo("Generations", "Number of processed generations", typeof(IntData), VariableKind.In | VariableKind.Out));
84
85      Name = "FixedSGAMain";
86
87      sorter = new Sorter();
88      sorter.GetVariableInfo("Descending").ActualName = "Maximization";
89      sorter.GetVariableInfo("Value").ActualName = "Quality";
90
91      InitCreateChildren();
92      InitReplacement();
93
94      sb = new StochasticBranch();
95      sb.GetVariableInfo("Probability").ActualName = "MutationRate";
96    }
97
98    private void InitReplacement() {
99      ls = new LeftSelector();
100      rr = new RightReducer();
101      rs = new RightSelector();
102      lr = new LeftReducer();
103      mr = new MergingReducer();
104
105      ls.GetVariableInfo("Selected").ActualName = "Elites";
106      rs.GetVariableInfo("Selected").ActualName = "Elites";
107    }
108
109    protected void InitCreateChildren() {
110      // variables for create children
111      ci = new ChildrenInitializer();
112
113      // variables infos
114      AddVariableInfo(new VariableInfo("Random", "Pseudo random number generator", typeof(IRandom), VariableKind.In));
115      AddVariableInfo(new VariableInfo("MutationRate", "Probability to choose first branch", typeof(DoubleData), VariableKind.In));
116      AddVariableInfo(new VariableInfo("Crossover", "Crossover strategy for SGA", typeof(OperatorBase), VariableKind.In));
117      AddVariableInfo(new VariableInfo("Mutator", "Mutation strategy for SGA", typeof(OperatorBase), VariableKind.In));
118      AddVariableInfo(new VariableInfo("Evaluator", "Evaluation strategy for SGA", typeof(OperatorBase), VariableKind.In));
119
120      sr = new SubScopesRemover();
121      sr.GetVariableInfo("SubScopeIndex").Local = true;
122
123      counter = new Counter();
124      counter.GetVariableInfo("Value").ActualName = "EvaluatedSolutions";
125    }
126
127    public override IOperation Apply(IScope scope) {
128      base.Apply(scope);
129      Stopwatch swApply = new Stopwatch();
130      swApply.Start();
131
132      #region Initialization
133      QualityLogger ql = new QualityLogger();
134
135      BestAverageWorstQualityCalculator bawqc = new BestAverageWorstQualityCalculator();
136      DataCollector dc = new DataCollector();
137      ItemList<StringData> names = dc.GetVariable("VariableNames").GetValue<ItemList<StringData>>();
138      names.Add(new StringData("BestQuality"));
139      names.Add(new StringData("AverageQuality"));
140      names.Add(new StringData("WorstQuality"));
141
142      LinechartInjector lci = new LinechartInjector();
143      lci.GetVariableInfo("Linechart").ActualName = "Quality Linechart";
144      lci.GetVariable("NumberOfLines").GetValue<IntData>().Data = 3;
145
146      IntData maxGenerations = GetVariableValue<IntData>("MaximumGenerations", scope, true);
147      IntData nrOfGenerations = GetVariableValue<IntData>("Generations", scope, true);
148   
149      IntData subscopeNr;
150      try {
151        subscopeNr = scope.GetVariableValue<IntData>("SubScopeNr", false);
152      }
153      catch (Exception) {
154        subscopeNr = new IntData(0);
155        scope.AddVariable(new Variable("SubScopeNr", subscopeNr));
156      }
157
158      ci = new ChildrenInitializer();
159     
160
161      GetOperatorsFromScope(scope);
162
163      try {
164        sb.RemoveSubOperator(0);
165      }
166      catch (Exception) {
167      }
168      sb.AddSubOperator(mutator);
169
170
171      IScope s;
172      IScope s2;
173      #endregion
174      try {
175        for (; nrOfGenerations.Data < maxGenerations.Data; nrOfGenerations.Data++) {
176          Execute(selector, scope);
177
178          ////// Create Children //////
179          // ChildrenInitializer
180          s = scope.SubScopes[1];
181          Execute(ci, s);
182
183          SaveExecutionPointer();
184          // UniformSequentialSubScopesProcessor
185          for (; subscopeNr.Data < s.SubScopes.Count; subscopeNr.Data++) {
186            SetExecutionPointerToLastSaved();
187
188            s2 = s.SubScopes[subscopeNr.Data];
189            Execute(crossover, s2);
190            // Stochastic Branch
191            Execute(sb, s2);
192
193            // ganz böse!!!!!!!
194            // wird nach dem stochastic branch angehalten und später fortgesetzt,
195            // wird eine Zufallszahl erzeugt, die aber nicht verwendet wird.
196            // Dadurch kommt der GA auf ein anderes Endergebnis
197            // Lösung: Stochastic Branch Operator verwenden
198            //randomNumber = random.NextDouble();
199            //output.AppendLine(randomNumber.ToString());
200            //if (randomNumber < probability.Data)
201            //  Execute(mutator, s2);
202            //else
203            //  Execute(empty, s2);
204
205            Execute(evaluator, s2);
206            Execute(sr, s2);
207            Execute(counter, s2);
208          } // foreach
209
210          Execute(sorter, s);
211          ////// END Create Children //////
212
213          DoReplacement(scope);
214          Execute(ql, scope);
215          Execute(bawqc, scope);
216          Execute(dc, scope);
217          Execute(lci, scope);
218          subscopeNr.Data = 0;
219          ResetExecutionPointer();
220        } // for i
221
222        //TextWriter tw = new StreamWriter(DateTime.Now.ToFileTime() + ".txt");
223        //tw.Write(output.ToString());
224        //tw.Close();
225        //output = new StringBuilder();
226
227        swApply.Stop();
228        Console.WriteLine("SGAMain.Apply(): {0}", swApply.Elapsed);
229      } // try
230      catch (CancelException) {
231        Console.WriteLine("Micro engine aborted by cancel flag.");
232        return new AtomicOperation(this, scope);
233      }
234
235      return null;
236    } // Apply
237
238    /// <summary>
239    /// Fetch main operators like selector, crossover, mutator, ... from scope
240    /// and store them in instance variables.
241    /// </summary>
242    /// <param name="scope"></param>
243    private void GetOperatorsFromScope(IScope scope) {
244      selector = (OperatorBase)GetVariableValue("Selector", scope, true);
245      crossover = (OperatorBase)GetVariableValue("Crossover", scope, true);
246      mutator = (OperatorBase)GetVariableValue("Mutator", scope, true);
247      evaluator = GetVariableValue<OperatorBase>("Evaluator", scope, true);
248
249      random = GetVariableValue<IRandom>("Random", scope, true);
250      probability = GetVariableValue<DoubleData>("MutationRate", scope, true);
251    }
252
253    /// <summary>
254    ///
255    /// </summary>
256    /// <param name="scope"></param>
257    protected void CreateChildren(IScope scope) {
258      // ChildrenInitializer
259      Execute(ci, scope);
260      // UniformSequentialSubScopesProcessor
261      foreach (IScope s in scope.SubScopes) {
262        Execute(crossover, s);
263        // Stochastic Branch
264        if (random.NextDouble() < probability.Data)
265          Execute(mutator, s);
266        Execute(evaluator, s);
267        Execute(sr, s);
268        Execute(counter, s);
269      } // foreach
270
271      Execute(sorter, scope);
272    } // CreateChildren
273
274    private void DoReplacement(IScope scope) {
275      //// SequentialSubScopesProcessor
276      Execute(ls, scope.SubScopes[0]);
277      Execute(rr, scope.SubScopes[0]);
278
279      Execute(rs, scope.SubScopes[1]);
280      Execute(lr, scope.SubScopes[1]);
281
282      Execute(mr, scope);
283      Execute(sorter, scope);
284    } // DoReplacement
285  } // class FixedSGAMain
286} // namespace HeuristicLab.FixedOperators
Note: See TracBrowser for help on using the repository browser.