Free cookie consent management tool by TermsFeed Policy Generator

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

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

Improved algorithm abortion support. Added support for composite operations in FixedSGAMain. (ticket #580)

File size: 10.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;
35
36namespace HeuristicLab.FixedOperators {
37  class FixedSGAMain : FixedBase {
38    public override string Description {
39      get { return @"Implements the functionality of SGAMain with fixed control structures. Operators like selection, crossover, mutation and evaluation are delegated."; }
40    }
41
42    // Shared
43    Sorter sorter;
44
45    // CreateChildren
46    Counter counter;
47    IRandom random;
48    DoubleData probability;
49    ChildrenInitializer ci;
50    OperatorBase crossover;
51    OperatorBase mutator;
52    OperatorBase evaluator;
53    SubScopesRemover sr;
54
55    // CreateReplacement
56    LeftSelector ls;
57    RightReducer rr;
58    RightSelector rs;
59    LeftReducer lr;
60    MergingReducer mr;
61
62
63    //long[] timesExecuteCreateChildren;
64
65    public FixedSGAMain()
66      : base() {
67      AddVariableInfo(new VariableInfo("Selector", "Selection strategy for SGA", typeof(OperatorBase), VariableKind.In));
68      AddVariableInfo(new VariableInfo("MaximumGenerations", "Maximum number of generations to create", typeof(IntData), VariableKind.In));
69      AddVariableInfo(new VariableInfo("Generations", "Number of processed generations", typeof(IntData), VariableKind.In | VariableKind.Out));
70      AddVariableInfo(new VariableInfo("ExecutionPointer", "Execution pointer for algorithm abortion", typeof(IntData), VariableKind.New));
71
72      Name = "FixedSGAMain";
73
74      sorter = new Sorter();
75      sorter.GetVariableInfo("Descending").ActualName = "Maximization";
76      sorter.GetVariableInfo("Value").ActualName = "Quality";
77
78      InitVariablesForCreateChildren();
79      InitVariablesForCreateReplacement();
80    }
81
82    private void InitVariablesForCreateReplacement() {
83      ls = new LeftSelector();
84      rr = new RightReducer();
85      rs = new RightSelector();
86      lr = new LeftReducer();
87      mr = new MergingReducer();
88
89      ls.GetVariableInfo("Selected").ActualName = "Elites";
90      rs.GetVariableInfo("Selected").ActualName = "Elites";
91
92    }
93
94    protected void InitVariablesForCreateChildren() {
95      // variables for create children
96      ci = new ChildrenInitializer();
97
98      // variables infos
99      AddVariableInfo(new VariableInfo("Random", "Pseudo random number generator", typeof(IRandom), VariableKind.In));
100      AddVariableInfo(new VariableInfo("MutationRate", "Probability to choose first branch", typeof(DoubleData), VariableKind.In));
101      AddVariableInfo(new VariableInfo("Crossover", "Crossover strategy for SGA", typeof(OperatorBase), VariableKind.In));
102      AddVariableInfo(new VariableInfo("Mutator", "Mutation strategy for SGA", typeof(OperatorBase), VariableKind.In));
103      AddVariableInfo(new VariableInfo("Evaluator", "Evaluation strategy for SGA", typeof(OperatorBase), VariableKind.In));
104
105      sr = new SubScopesRemover();
106      sr.GetVariableInfo("SubScopeIndex").Local = true;
107
108      counter = new Counter();
109      counter.GetVariableInfo("Value").ActualName = "EvaluatedSolutions";
110    }
111
112    public override IOperation Apply(IScope scope) {
113      Stopwatch swApply = new Stopwatch();
114      swApply.Start();
115      //base.Apply(scope); // noch nachfragen ob das auch in ordnung wäre
116      for (int i = 0; i < SubOperators.Count; i++) {
117        if (scope.GetVariable(SubOperators[i].Name) != null)
118          scope.RemoveVariable(SubOperators[i].Name);
119        scope.AddVariable(new Variable(SubOperators[i].Name, SubOperators[i]));
120      }
121
122      OperatorBase selector = (OperatorBase)GetVariableValue("Selector", scope, true);
123      QualityLogger ql = new QualityLogger();
124
125      BestAverageWorstQualityCalculator bawqc = new BestAverageWorstQualityCalculator();
126      DataCollector dc = new DataCollector();
127      ItemList<StringData> names = dc.GetVariable("VariableNames").GetValue<ItemList<StringData>>();
128      names.Add(new StringData("BestQuality"));
129      names.Add(new StringData("AverageQuality"));
130      names.Add(new StringData("WorstQuality"));
131
132      LinechartInjector lci = new LinechartInjector();
133      lci.GetVariableInfo("Linechart").ActualName = "Quality Linechart";
134      lci.GetVariable("NumberOfLines").GetValue<IntData>().Data = 3;
135
136      LessThanComparator ltc = new LessThanComparator();
137      ltc.GetVariableInfo("LeftSide").ActualName = "Generations";
138      ltc.GetVariableInfo("RightSide").ActualName = "MaximumGenerations";
139      ltc.GetVariableInfo("Result").ActualName = "GenerationsCondition";
140
141      IntData maxGenerations = GetVariableValue<IntData>("MaximumGenerations", scope, true);
142      IntData nrOfGenerations = GetVariableValue<IntData>("Generations", scope, true);
143
144
145      // executionpointer saves the reentry point after engine abort occurs.
146      IntData executionPointer;
147      try
148      {
149        executionPointer = GetVariableValue<IntData>("ExecutionPointer", scope, true);
150      }
151      catch (Exception)
152      {
153        scope.AddVariable(new Variable("ExecutionPointer", new IntData(-1)));
154        executionPointer = GetVariableValue<IntData>("ExecutionPointer", scope, true);
155      }
156     
157      // fetch variables from scope for create children
158      InitializeExecuteCreateChildren(scope);
159      for (int i = nrOfGenerations.Data; i < maxGenerations.Data && !Canceled; i++) {
160        if (Canceled) {
161          executionPointer.Data = -1;
162          continue;
163        }
164        if (executionPointer.Data < 0)
165          Execute(selector, scope);
166
167        if (Canceled) {
168          executionPointer.Data = 0;
169          continue;
170        }
171        if (executionPointer.Data < 1)
172          ExecuteCreateChildrenWithFixedControlStructures(scope.SubScopes[1]);
173
174        if (Canceled) {
175          executionPointer.Data = 1;
176          continue;
177        }
178        if (executionPointer.Data < 2)
179          ExecuteCreateReplacementWithFixedConstrolStructures(scope);
180
181        if (Canceled) {
182          executionPointer.Data = 2;
183          continue;
184        }
185        if (executionPointer.Data < 3) {
186          ql.Execute(scope);
187          bawqc.Execute(scope);
188          dc.Execute(scope);
189          lci.Execute(scope);
190          nrOfGenerations.Data++;
191        }
192        executionPointer.Data = -1;
193      } // for i
194
195      //Stopwatch watch = new Stopwatch();
196      //long[] times = new long[10];
197      //timesExecuteCreateChildren = new long[10];
198      //for (int i = nrOfGenerations.Data; i < maxGenerations.Data && !Canceled; i++) {
199      //  watch.Start();
200      //  selector.Execute(scope);
201      //  watch.Stop();
202      //  times[0] += watch.ElapsedTicks;
203      //  watch.Reset();
204      //  watch.Start();
205      //  ExecuteCreateChildrenWithFixedControlStructures(scope.SubScopes[1]);
206      //  watch.Stop();
207      //  times[1] += watch.ElapsedTicks;
208      //  watch.Reset();
209      //  watch.Start();
210      //  ExecuteCreateReplacementWithFixedConstrolStructures(scope);
211      //  watch.Stop();
212      //  times[2] += watch.ElapsedTicks;
213      //  watch.Reset();
214      //  watch.Start();
215      //  ql.Execute(scope);
216      //  watch.Stop();
217      //  times[3] += watch.ElapsedTicks;
218      //  watch.Reset();
219      //  watch.Start();
220      //  bawqc.Execute(scope);
221      //  watch.Stop();
222      //  times[4] += watch.ElapsedTicks;
223      //  watch.Reset();
224      //  watch.Start();
225      //  dc.Execute(scope);
226      //  watch.Stop();
227      //  times[5] += watch.ElapsedTicks;
228      //  watch.Reset();
229      //  watch.Start();
230      //  lci.Execute(scope);
231      //  watch.Stop();
232      //  times[6] += watch.ElapsedTicks;
233      //  watch.Reset();
234      //  watch.Start();
235      //  nrOfGenerations.Data++;
236      //}
237
238      swApply.Stop();
239      Console.WriteLine("SGAMain.Apply(): {0}", swApply.Elapsed);
240
241      if (Canceled)
242        return new AtomicOperation(this, scope);
243
244      return null;
245    } // Apply
246
247 
248
249    /// <summary>
250    /// Initializes some variables needed before the execution of create children
251    /// </summary>
252    /// <param name="scope"></param>
253    private void InitializeExecuteCreateChildren(IScope scope) {
254      crossover = (OperatorBase)GetVariableValue("Crossover", scope, true);
255      mutator = (OperatorBase)GetVariableValue("Mutator", scope, true);
256      evaluator = GetVariableValue<OperatorBase>("Evaluator", scope, true);
257
258      random = GetVariableValue<IRandom>("Random", scope, true);
259      probability = GetVariableValue<DoubleData>("MutationRate", scope, true);
260
261      ci = new ChildrenInitializer();
262    }
263
264    protected void ExecuteCreateChildrenWithFixedControlStructures(IScope scope) {
265      // ChildrenInitializer
266      ci.Apply(scope);
267      // UniformSequentialSubScopesProcessor
268      foreach (IScope s in scope.SubScopes) {
269        Execute(crossover, s);
270        // Stochastic Branch
271        if (random.NextDouble() < probability.Data)
272          Execute(mutator, s);
273        Execute(evaluator, s);
274        sr.Execute(s);
275        counter.Execute(s);
276      } // foreach
277
278      sorter.Execute(scope);
279    } // ExecuteCreateChildrenHWCS
280
281    private void ExecuteCreateReplacementWithFixedConstrolStructures(IScope scope) {
282      // SequentialSubScopesProcessor
283      ls.Execute(scope.SubScopes[0]);
284      rr.Execute(scope.SubScopes[0]);
285
286      rs.Execute(scope.SubScopes[1]);
287      lr.Execute(scope.SubScopes[1]);
288
289      mr.Execute(scope);
290      sorter.Execute(scope);
291    } // ExecuteCreateReplacementWithFixedConstrolStructures
292  } // class FixedSGAMain
293} // namespace HeuristicLab.FixedOperators
Note: See TracBrowser for help on using the repository browser.