Free cookie consent management tool by TermsFeed Policy Generator

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

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

FixedSGAMain, added support for engine abortion. (ticket #580)

File size: 9.8 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;
34
35namespace HeuristicLab.FixedOperators {
36  class FixedAllSGAMain : CombinedOperator {
37    public override string Description {
38      get { return @"Implements the functionality of SGAMain with fixed control structures. Operators like selection, crossover, mutation and evaluation are delegated."; }
39    }
40
41    ChildrenInitializer ci;
42    OperatorBase crossover;
43    OperatorBase mutator;
44    OperatorBase evaluator;
45    IRandom random;
46    DoubleData probability;
47
48    long[] timesExecuteCreateChildren;
49
50    public FixedAllSGAMain()
51      : base() {
52      AddVariableInfo(new VariableInfo("Selector", "Selection strategy for SGA", typeof(OperatorBase), VariableKind.In));
53      AddVariableInfo(new VariableInfo("MaximumGenerations", "Maximum number of generations to create", typeof(IntData), VariableKind.In));
54      AddVariableInfo(new VariableInfo("Generations", "Number of processed generations", typeof(IntData), VariableKind.In | VariableKind.Out));
55      Name = "FixedAllSGAMain";
56      InitCreateChildrenHW();
57
58    }
59
60    private void InitCreateChildrenHW() {
61      // variables infos
62      AddVariableInfo(new VariableInfo("Random", "Pseudo random number generator", typeof(IRandom), VariableKind.In));
63      AddVariableInfo(new VariableInfo("MutationRate", "Probability to choose first branch", typeof(DoubleData), VariableKind.In));
64      AddVariableInfo(new VariableInfo("Crossover", "Crossover strategy for SGA", typeof(OperatorBase), VariableKind.In));
65      AddVariableInfo(new VariableInfo("Mutator", "Mutation strategy for SGA", typeof(OperatorBase), VariableKind.In));
66      AddVariableInfo(new VariableInfo("Evaluator", "Evaluation strategy for SGA", typeof(OperatorBase), VariableKind.In));
67      AddVariableInfo(new VariableInfo("EvaluatedSolutions", "Number of evaluated solutions", typeof(IntData), VariableKind.In | VariableKind.Out));
68      AddVariableInfo(new VariableInfo("Maximization", "Sort in descending order", typeof(BoolData), VariableKind.In));
69      AddVariableInfo(new VariableInfo("Quality", "Sorting value", typeof(DoubleData), VariableKind.In));
70    }
71
72    public override IOperation Apply(IScope scope) {
73      Stopwatch swApply = new Stopwatch();
74      swApply.Start();
75      //base.Apply(scope); // noch nachfragen ob das auch in ordnung wäre
76      for (int i = 0; i < SubOperators.Count; i++) {
77        if (scope.GetVariable(SubOperators[i].Name) != null)
78          scope.RemoveVariable(SubOperators[i].Name);
79        scope.AddVariable(new Variable(SubOperators[i].Name, SubOperators[i]));
80      }
81
82      OperatorBase selector = (OperatorBase)GetVariableValue("Selector", scope, true);
83      OperatorBase createReplacement = new CreateReplacement();
84      QualityLogger ql = new QualityLogger();
85
86      BestAverageWorstQualityCalculator bawqc = new BestAverageWorstQualityCalculator();
87      DataCollector dc = new DataCollector();
88      ItemList<StringData> names = dc.GetVariable("VariableNames").GetValue<ItemList<StringData>>();
89      names.Add(new StringData("BestQuality"));
90      names.Add(new StringData("AverageQuality"));
91      names.Add(new StringData("WorstQuality"));
92
93      LinechartInjector lci = new LinechartInjector();
94      lci.GetVariableInfo("Linechart").ActualName = "Quality Linechart";
95      lci.GetVariable("NumberOfLines").GetValue<IntData>().Data = 3;
96
97      Counter c = new Counter();
98      c.GetVariableInfo("Value").ActualName = "Generations";
99
100      LessThanComparator ltc = new LessThanComparator();
101      ltc.GetVariableInfo("LeftSide").ActualName = "Generations";
102      ltc.GetVariableInfo("RightSide").ActualName = "MaximumGenerations";
103      ltc.GetVariableInfo("Result").ActualName = "GenerationsCondition";
104
105      IntData maxGenerations = GetVariableValue<IntData>("MaximumGenerations", scope, true);
106      IntData nrOfGenerations = GetVariableValue<IntData>("Generations", scope, true);
107
108      InitializeExecuteCreateChildren(scope);
109      IntData evaluatedSolutions = GetVariableValue<IntData>("EvaluatedSolutions", scope, true);
110      Stopwatch watch = new Stopwatch();
111      long[] times = new long[10];
112      timesExecuteCreateChildren = new long[10];
113      for (int i = 0; i < maxGenerations.Data; i++) {
114        watch.Start();
115        selector.Execute(scope);
116        watch.Stop();
117        times[0] += watch.ElapsedTicks;
118        watch.Reset();
119        watch.Start();
120        ExecuteCreateChildren(scope.SubScopes[1], evaluatedSolutions);
121        watch.Stop();
122        times[1] += watch.ElapsedTicks;
123        watch.Reset();
124        watch.Start();
125        createReplacement.Execute(scope);
126        watch.Stop();
127        times[2] += watch.ElapsedTicks;
128        watch.Reset();
129        watch.Start();
130        ql.Execute(scope);
131        watch.Stop();
132        times[3] += watch.ElapsedTicks;
133        watch.Reset();
134        watch.Start();
135        bawqc.Execute(scope);
136        watch.Stop();
137        times[4] += watch.ElapsedTicks;
138        watch.Reset();
139        watch.Start();
140        dc.Execute(scope);
141        watch.Stop();
142        times[5] += watch.ElapsedTicks;
143        watch.Reset();
144        watch.Start();
145        lci.Execute(scope);
146        watch.Stop();
147        times[6] += watch.ElapsedTicks;
148        watch.Reset();
149        watch.Start();
150        nrOfGenerations.Data++;
151      }
152
153      swApply.Stop();
154      Console.WriteLine("SGAMain.Apply(): {0}", swApply.Elapsed);
155      return null;
156    } // Apply
157
158    /// <summary>
159    /// Initializes some variables needed before the execution of create children
160    /// </summary>
161    /// <param name="scope"></param>
162    private void InitializeExecuteCreateChildren(IScope scope) {
163      crossover = (OperatorBase)GetVariableValue("Crossover", scope, true);
164      mutator = (OperatorBase)GetVariableValue("Mutator", scope, true);
165      evaluator = GetVariableValue<OperatorBase>("Evaluator", scope, true);
166
167      random = GetVariableValue<IRandom>("Random", scope, true);
168      probability = GetVariableValue<DoubleData>("MutationRate", scope, true);
169
170      ci = new ChildrenInitializer();
171    }
172
173    private void ExecuteCreateChildren(IScope scope, IntData evaluatedSolutions) {
174      //Stopwatch watch = new Stopwatch();
175      //long[] times = new long[10];
176      // ChildrenInitializer
177      //watch.Start();
178      ci.Apply(scope);
179      //watch.Stop();
180      //timesExecuteCreateChildren[0] += watch.ElapsedTicks;
181      //watch.Reset();
182      // UniformSequentialSubScopesProcessor
183      foreach (IScope s in scope.SubScopes) {
184        //watch.Start();
185        if (crossover.Execute(s) != null)
186          throw new InvalidOperationException("ERROR: no support for combined operators!");
187        //watch.Stop();
188        //timesExecuteCreateChildren[1] += watch.ElapsedTicks;
189        //watch.Reset();
190
191
192        // Stochastic Branch
193        if (random.NextDouble() < probability.Data) {
194          //watch.Start();
195          if (mutator.Execute(s) != null)
196            throw new InvalidOperationException("ERROR: no support for combined operators!");
197          //watch.Stop();
198          //timesExecuteCreateChildren[2] += watch.ElapsedTicks;
199          //watch.Reset();
200
201        }
202
203        //watch.Start();
204        if (evaluator.Execute(s) != null)
205          throw new InvalidOperationException("ERROR: no support for combined operators!");
206        //watch.Stop();
207        //timesExecuteCreateChildren[3] += watch.ElapsedTicks;
208        //watch.Reset();
209
210        // subscopes remover
211        //watch.Start();
212        while (s.SubScopes.Count > 0)
213          s.RemoveSubScope(s.SubScopes[0]);
214        //watch.Stop();
215        //timesExecuteCreateChildren[4] += watch.ElapsedTicks;
216        //watch.Reset();
217
218        evaluatedSolutions.Data++;
219      } // foreach
220
221      // sort scopes
222      bool descending = GetVariableValue<BoolData>("Maximization", scope, true).Data;
223
224      double[] keys = new double[scope.SubScopes.Count];
225      int[] sequence = new int[keys.Length];
226
227      for (int i = 0; i < keys.Length; i++) {
228        keys[i] = scope.SubScopes[i].GetVariableValue<DoubleData>("Quality", false).Data;
229        sequence[i] = i;
230      }
231
232      Array.Sort<double, int>(keys, sequence);
233
234      if (descending) {
235        int temp;
236        for (int i = 0; i < sequence.Length / 2; i++) {
237          temp = sequence[i];
238          sequence[i] = sequence[sequence.Length - 1 - i];
239          sequence[sequence.Length - 1 - i] = temp;
240        }
241      }
242      scope.ReorderSubScopes(sequence);
243      //watch.Stop();
244      //timesExecuteCreateChildren[5] += watch.ElapsedTicks;
245      //watch.Reset();
246
247      return;
248    } // ExecuteCreateChildrenHW
249
250  } // class AllFixedSGAMain
251} // namespace HeuristicLab.FixedOperators
Note: See TracBrowser for help on using the repository browser.