Free cookie consent management tool by TermsFeed Policy Generator

Changeset 2120 for trunk


Ignore:
Timestamp:
06/26/09 19:47:10 (15 years ago)
Author:
dtraxing
Message:

Extracted base class of SGAMain and OSGAMain (ticket #580)

Location:
trunk/sources/HeuristicLab.FixedOperators/3.2
Files:
2 added
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.FixedOperators/3.2/FixedOperatorBase.cs

    r1995 r2120  
    2828using System.Diagnostics;
    2929using System.Text;
     30using System.Collections;
    3031
    3132namespace HeuristicLab.FixedOperators {
     
    4445    protected IntData persistedExecutionPointer;
    4546
    46     protected int tempExePointer;
    47     protected int tempPersExePointer;
     47    protected int[] tempExePointer;
     48    protected int[] tempPersExePointer;
    4849
    4950    /// <summary>
     
    101102            next = currentOperator.Execute(atomicOperation.Scope);
    102103          }
    103           catch (Exception) {
     104          catch (Exception ex) {
    104105            throw new InvalidOperationException("Invalid Operation occured in FixedBase.Execute");
    105106          }
     
    161162    /// Saves the value of the execution pointers into temp variables
    162163    /// </summary>
    163     protected void SaveExecutionPointer() {
    164       tempExePointer = executionPointer;
    165       tempPersExePointer = persistedExecutionPointer.Data;
     164    protected void SaveExecutionPointer(int level) {
     165      tempExePointer[level] = executionPointer;
     166      tempPersExePointer[level] = persistedExecutionPointer.Data;
    166167    } // SaveExecutionPointer
    167168
    168     protected void SetExecutionPointerToLastSaved() {
     169    protected void SetExecutionPointerToLastSaved(int level) {
    169170      if (executionPointer != persistedExecutionPointer.Data)
    170         persistedExecutionPointer.Data = tempPersExePointer;
     171        persistedExecutionPointer.Data = tempPersExePointer[level];
    171172      else
    172         persistedExecutionPointer.Data = tempExePointer;
    173       executionPointer = tempExePointer;
     173        persistedExecutionPointer.Data = tempExePointer[level];
     174      executionPointer = tempExePointer[level];
    174175    } // SetExecutionPointerToLastSaved
    175176
  • trunk/sources/HeuristicLab.FixedOperators/3.2/FixedSGAMain.cs

    r2076 r2120  
    1 #region License Information
     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
    2280/* HeuristicLab
    3281 * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     
    38316
    39317namespace HeuristicLab.FixedOperators {
    40   class FixedSGAMain : FixedOperatorBase {
     318  class FixedSGAMain : FixedGAMainBase {
    41319    public override string Description {
    42320      get { return @"Implements the functionality of SGAMain with fixed control structures. Operators like selection, crossover, mutation and evaluation are delegated."; }
    43321    }
    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 
    68322    //long[] timesExecuteCreateChildren;
    69323    public FixedSGAMain()
    70324      : 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 
    75325      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";
    115326    }
    116327
     
    119330      Stopwatch swApply = new Stopwatch();
    120331      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 
     332     
    161333      IScope s;
    162334      IScope s2;
    163       #endregion
     335
    164336      try {
    165337        for (; nrOfGenerations.Data < maxGenerations.Data; nrOfGenerations.Data++) {
     
    171343          Execute(ci, s);
    172344
    173           SaveExecutionPointer();
     345          SaveExecutionPointer(0);
    174346          // UniformSequentialSubScopesProcessor
    175347          for (; subscopeNr.Data < s.SubScopes.Count; subscopeNr.Data++) {
    176             SetExecutionPointerToLastSaved();
     348            SetExecutionPointerToLastSaved(0);
    177349
    178350            s2 = s.SubScopes[subscopeNr.Data];
     
    219391      } // try
    220392      catch (CancelException) {
    221         Console.WriteLine("Micro engine aborted by cancel flag.");
     393        //Console.WriteLine("Micro engine aborted by cancel flag.");
    222394        return new AtomicOperation(this, scope);
    223395      }
     
    225397      return null;
    226398    } // 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
    275399  } // class FixedSGAMain
    276400} // namespace HeuristicLab.FixedOperators
     401
  • trunk/sources/HeuristicLab.FixedOperators/3.2/HeuristicLab.FixedOperators-3.2.csproj

    r2077 r2120  
    100100  </ItemGroup>
    101101  <ItemGroup>
     102    <Compile Include="FixedGAMainBase.cs" />
    102103    <Compile Include="FixedOperatorBase.cs" />
    103     <Compile Include="FixedOSGA.cs" />
     104    <Compile Include="FixedOSGAMain.cs" />
    104105    <Compile Include="FixedSGAMain.cs" />
    105106    <Compile Include="HeuristicLabFixedOperatorsPlugin.cs" />
Note: See TracChangeset for help on using the changeset viewer.