Free cookie consent management tool by TermsFeed Policy Generator

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

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

added fixed operator for OSGA and deleted some unused old source files (ticket #580).
OSGA operator is under construction.

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