Free cookie consent management tool by TermsFeed Policy Generator

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

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

FixedOperatorBase: added better exception text
FixedSGAMain: removed explicit constructor call, because it also works implicit
FixedSAMain: initial commit; simulated annealing with fixed operators
(ticket #580)

File size: 14.4 KB
RevLine 
[2120]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
22//using System;
23//using System.Collections.Generic;
24//using System.Text;
25//using System.Linq;
26//using HeuristicLab.Core;
27//using HeuristicLab.Data;
28//using HeuristicLab.Permutation;
29//using HeuristicLab.Evolutionary;
30//using HeuristicLab.Operators;
31//using HeuristicLab.Routing.TSP;
32//using HeuristicLab.Logging;
33//using System.Diagnostics;
34//using HeuristicLab.Selection;
35//using System.Threading;
36//using System.IO;
37//using HeuristicLab.Random;
38
39//namespace 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
277
278
279#region License Information
[1560]280/* HeuristicLab
281 * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
282 *
283 * This file is part of HeuristicLab.
284 *
285 * HeuristicLab is free software: you can redistribute it and/or modify
286 * it under the terms of the GNU General Public License as published by
287 * the Free Software Foundation, either version 3 of the License, or
288 * (at your option) any later version.
289 *
290 * HeuristicLab is distributed in the hope that it will be useful,
291 * but WITHOUT ANY WARRANTY; without even the implied warranty of
292 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
293 * GNU General Public License for more details.
294 *
295 * You should have received a copy of the GNU General Public License
296 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
297 */
298#endregion
299
300using System;
301using System.Collections.Generic;
302using System.Text;
303using System.Linq;
304using HeuristicLab.Core;
305using HeuristicLab.Data;
306using HeuristicLab.Permutation;
307using HeuristicLab.Evolutionary;
308using HeuristicLab.Operators;
309using HeuristicLab.Routing.TSP;
310using HeuristicLab.Logging;
[1610]311using System.Diagnostics;
[1661]312using HeuristicLab.Selection;
[1789]313using System.Threading;
[1995]314using System.IO;
315using HeuristicLab.Random;
[1560]316
[1646]317namespace HeuristicLab.FixedOperators {
[2120]318  class FixedSGAMain : FixedGAMainBase {
[1560]319    public override string Description {
[1661]320      get { return @"Implements the functionality of SGAMain with fixed control structures. Operators like selection, crossover, mutation and evaluation are delegated."; }
[1560]321    }
[1693]322    //long[] timesExecuteCreateChildren;
[2151]323    public FixedSGAMain() {
[1646]324      Name = "FixedSGAMain";
[1560]325    }
326
327    public override IOperation Apply(IScope scope) {
[1789]328      base.Apply(scope);
[1875]329      Stopwatch swApply = new Stopwatch();
330      swApply.Start();
[2120]331     
[1875]332      IScope s;
333      IScope s2;
[2129]334      bool loopSkipped = true;
[2120]335
[2129]336      tempExePointer = new int[10];
337      tempPersExePointer = new int[10];
338     
[1875]339      try {
[1995]340        for (; nrOfGenerations.Data < maxGenerations.Data; nrOfGenerations.Data++) {
[1875]341          Execute(selector, scope);
[1731]342
[1875]343          ////// Create Children //////
344          // ChildrenInitializer
345          s = scope.SubScopes[1];
346          Execute(ci, s);
[1923]347
[2120]348          SaveExecutionPointer(0);
[1875]349          // UniformSequentialSubScopesProcessor
[1995]350          for (; subscopeNr.Data < s.SubScopes.Count; subscopeNr.Data++) {
[2120]351            SetExecutionPointerToLastSaved(0);
[1923]352
[1995]353            s2 = s.SubScopes[subscopeNr.Data];
[1875]354            Execute(crossover, s2);
355            // Stochastic Branch
[1995]356            Execute(sb, s2);
[1923]357
[1995]358            // ganz böse!!!!!!!
359            // wird nach dem stochastic branch angehalten und später fortgesetzt,
360            // wird eine Zufallszahl erzeugt, die aber nicht verwendet wird.
361            // Dadurch kommt der GA auf ein anderes Endergebnis
362            // Lösung: Stochastic Branch Operator verwenden
363            //randomNumber = random.NextDouble();
[1923]364            //output.AppendLine(randomNumber.ToString());
[1995]365            //if (randomNumber < probability.Data)
366            //  Execute(mutator, s2);
367            //else
368            //  Execute(empty, s2);
369
[1875]370            Execute(evaluator, s2);
371            Execute(sr, s2);
372            Execute(counter, s2);
[2129]373            loopSkipped = false;
[1875]374          } // foreach
[1576]375
[2129]376          // if for loop skipped, we had to add skiped operations
377          // to execution pointer.
378          if (loopSkipped)
379            executionPointer += 5;
380
[1875]381          Execute(sorter, s);
382          ////// END Create Children //////
[1693]383
[1995]384          DoReplacement(scope);
[1875]385          Execute(ql, scope);
386          Execute(bawqc, scope);
387          Execute(dc, scope);
388          Execute(lci, scope);
[1900]389          subscopeNr.Data = 0;
[1995]390          ResetExecutionPointer();
[1875]391        } // for i
[1923]392
[1995]393        //TextWriter tw = new StreamWriter(DateTime.Now.ToFileTime() + ".txt");
394        //tw.Write(output.ToString());
395        //tw.Close();
396        //output = new StringBuilder();
[1923]397
[1995]398        swApply.Stop();
399        Console.WriteLine("SGAMain.Apply(): {0}", swApply.Elapsed);
[1875]400      } // try
401      catch (CancelException) {
402        return new AtomicOperation(this, scope);
[1789]403      }
404
[1875]405      return null;
[1560]406    } // Apply
[1646]407  } // class FixedSGAMain
408} // namespace HeuristicLab.FixedOperators
[2120]409
Note: See TracBrowser for help on using the repository browser.