Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 2113 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
RevLine 
[1560]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;
[1610]33using System.Diagnostics;
[1661]34using HeuristicLab.Selection;
[1789]35using System.Threading;
[1995]36using System.IO;
37using HeuristicLab.Random;
[1560]38
[1646]39namespace HeuristicLab.FixedOperators {
[1789]40  class FixedSGAMain : FixedOperatorBase {
[1560]41    public override string Description {
[1661]42      get { return @"Implements the functionality of SGAMain with fixed control structures. Operators like selection, crossover, mutation and evaluation are delegated."; }
[1560]43    }
44
[1661]45    // Shared
[2076]46    protected Sorter sorter;
[1661]47
48    // CreateChildren
[2076]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;
[1610]58
[2076]59    protected OperatorBase selector;
[1995]60
[1661]61    // CreateReplacement
[2076]62    protected LeftSelector ls;
63    protected RightReducer rr;
64    protected RightSelector rs;
65    protected LeftReducer lr;
66    protected MergingReducer mr;
[1661]67
[1693]68    //long[] timesExecuteCreateChildren;
[1646]69    public FixedSGAMain()
[1560]70      : base() {
71      AddVariableInfo(new VariableInfo("Selector", "Selection strategy for SGA", typeof(OperatorBase), VariableKind.In));
[1576]72      AddVariableInfo(new VariableInfo("MaximumGenerations", "Maximum number of generations to create", typeof(IntData), VariableKind.In));
[1610]73      AddVariableInfo(new VariableInfo("Generations", "Number of processed generations", typeof(IntData), VariableKind.In | VariableKind.Out));
[1693]74
[1646]75      Name = "FixedSGAMain";
[1610]76
[1661]77      sorter = new Sorter();
78      sorter.GetVariableInfo("Descending").ActualName = "Maximization";
79      sorter.GetVariableInfo("Value").ActualName = "Quality";
80
[1995]81      InitCreateChildren();
82      InitReplacement();
83
84      sb = new StochasticBranch();
85      sb.GetVariableInfo("Probability").ActualName = "MutationRate";
[1560]86    }
87
[1995]88    private void InitReplacement() {
[1661]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";
[1610]97    }
98
[2076]99    private void InitCreateChildren() {
[1610]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
[1560]117    public override IOperation Apply(IScope scope) {
[1789]118      base.Apply(scope);
[1875]119      Stopwatch swApply = new Stopwatch();
120      swApply.Start();
[1576]121
[1995]122      #region Initialization
[1875]123      QualityLogger ql = new QualityLogger();
[1576]124
[1875]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"));
[1576]131
[1875]132      LinechartInjector lci = new LinechartInjector();
133      lci.GetVariableInfo("Linechart").ActualName = "Quality Linechart";
134      lci.GetVariable("NumberOfLines").GetValue<IntData>().Data = 3;
[1560]135
[1875]136      IntData maxGenerations = GetVariableValue<IntData>("MaximumGenerations", scope, true);
137      IntData nrOfGenerations = GetVariableValue<IntData>("Generations", scope, true);
[2076]138
[1900]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      }
[1693]147
[1995]148      ci = new ChildrenInitializer();
[1900]149
[2076]150
[1995]151      GetOperatorsFromScope(scope);
152
153      try {
154        sb.RemoveSubOperator(0);
155      }
156      catch (Exception) {
157      }
158      sb.AddSubOperator(mutator);
159
160
[1875]161      IScope s;
162      IScope s2;
[1995]163      #endregion
[1875]164      try {
[1995]165        for (; nrOfGenerations.Data < maxGenerations.Data; nrOfGenerations.Data++) {
[1875]166          Execute(selector, scope);
[1731]167
[1875]168          ////// Create Children //////
169          // ChildrenInitializer
170          s = scope.SubScopes[1];
171          Execute(ci, s);
[1923]172
[1995]173          SaveExecutionPointer();
[1875]174          // UniformSequentialSubScopesProcessor
[1995]175          for (; subscopeNr.Data < s.SubScopes.Count; subscopeNr.Data++) {
176            SetExecutionPointerToLastSaved();
[1923]177
[1995]178            s2 = s.SubScopes[subscopeNr.Data];
[1875]179            Execute(crossover, s2);
180            // Stochastic Branch
[1995]181            Execute(sb, s2);
[1923]182
[1995]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();
[1923]189            //output.AppendLine(randomNumber.ToString());
[1995]190            //if (randomNumber < probability.Data)
191            //  Execute(mutator, s2);
192            //else
193            //  Execute(empty, s2);
194
[1875]195            Execute(evaluator, s2);
196            Execute(sr, s2);
197            Execute(counter, s2);
198          } // foreach
[1576]199
[1875]200          Execute(sorter, s);
201          ////// END Create Children //////
[1693]202
[1995]203          DoReplacement(scope);
[1875]204          Execute(ql, scope);
205          Execute(bawqc, scope);
206          Execute(dc, scope);
207          Execute(lci, scope);
[1900]208          subscopeNr.Data = 0;
[1995]209          ResetExecutionPointer();
[1875]210        } // for i
[1923]211
[1995]212        //TextWriter tw = new StreamWriter(DateTime.Now.ToFileTime() + ".txt");
213        //tw.Write(output.ToString());
214        //tw.Close();
215        //output = new StringBuilder();
[1923]216
[1995]217        swApply.Stop();
218        Console.WriteLine("SGAMain.Apply(): {0}", swApply.Elapsed);
[1875]219      } // try
220      catch (CancelException) {
221        Console.WriteLine("Micro engine aborted by cancel flag.");
222        return new AtomicOperation(this, scope);
[1789]223      }
224
[1875]225      return null;
[1560]226    } // Apply
[1610]227
[1646]228    /// <summary>
[1995]229    /// Fetch main operators like selector, crossover, mutator, ... from scope
230    /// and store them in instance variables.
[1646]231    /// </summary>
232    /// <param name="scope"></param>
[2076]233    protected void GetOperatorsFromScope(IScope scope) {
[1995]234      selector = (OperatorBase)GetVariableValue("Selector", scope, true);
[1610]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
[1731]243    /// <summary>
244    ///
245    /// </summary>
246    /// <param name="scope"></param>
[1995]247    protected void CreateChildren(IScope scope) {
[1610]248      // ChildrenInitializer
[1875]249      Execute(ci, scope);
[1610]250      // UniformSequentialSubScopesProcessor
251      foreach (IScope s in scope.SubScopes) {
[1875]252        Execute(crossover, s);
[1610]253        // Stochastic Branch
254        if (random.NextDouble() < probability.Data)
[1875]255          Execute(mutator, s);
256        Execute(evaluator, s);
257        Execute(sr, s);
258        Execute(counter, s);
[1610]259      } // foreach
260
[1875]261      Execute(sorter, scope);
[1995]262    } // CreateChildren
[1610]263
[2076]264    protected void DoReplacement(IScope scope) {
[1789]265      //// SequentialSubScopesProcessor
[1875]266      Execute(ls, scope.SubScopes[0]);
267      Execute(rr, scope.SubScopes[0]);
[1610]268
[1875]269      Execute(rs, scope.SubScopes[1]);
270      Execute(lr, scope.SubScopes[1]);
[1646]271
[1875]272      Execute(mr, scope);
273      Execute(sorter, scope);
[1995]274    } // DoReplacement
[1646]275  } // class FixedSGAMain
276} // namespace HeuristicLab.FixedOperators
Note: See TracBrowser for help on using the repository browser.