Free cookie consent management tool by TermsFeed Policy Generator

Changeset 1995


Ignore:
Timestamp:
06/03/09 15:00:51 (15 years ago)
Author:
dtraxing
Message:

Bug with non deterministic SGA execution fixed. (ticket #580)

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

Legend:

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

    r1900 r1995  
    2727using System.Threading;
    2828using System.Diagnostics;
     29using System.Text;
    2930
    3031namespace HeuristicLab.FixedOperators {
    3132  class FixedOperatorBase : CombinedOperator {
     33    protected ItemList<IOperation> persistedOperations;
     34    protected Stack<IOperation> executionStack;
     35
    3236    /// <summary>
    3337    /// Execution pointer shows which command actually is executed
     
    4044    protected IntData persistedExecutionPointer;
    4145
     46    protected int tempExePointer;
     47    protected int tempPersExePointer;
     48
    4249    /// <summary>
    4350    /// Current operator in execution.
     
    4552    protected IOperator currentOperator;
    4653
    47     public FixedOperatorBase() : base() {
    48       //AddVariableInfo(new VariableInfo("ExecutionPointer", "Execution pointer for algorithm abortion", typeof(IntData), VariableKind.New));   
     54    public FixedOperatorBase()
     55      : base() {
     56      executionStack = new Stack<IOperation>();
    4957    } // FixedOperatorBase
    5058
     
    5361    } // AlreadyExecuted
    5462
    55     protected void ExecuteExitable(IOperator op, IScope scope) { 
    56    
     63    protected void ExecuteExitable(IOperator op, IScope scope) {
     64
    5765    } // ExecuteExitable
    5866
    59     protected void SetRegion(string region) { 
    60    
     67    protected void SetRegion(string region) {
     68
    6169    } // SetRegion
    6270
     
    6573        ExecuteOperation(op, scope);
    6674        persistedExecutionPointer.Data++;
    67         //Console.WriteLine("Execute: {0}", executionPointer);
    6875      } // if not executed
    69       //else
    70         //Console.WriteLine("Skip Execute: {0}", executionPointer);
    7176      executionPointer++;
    7277
     
    7782    protected void ExecuteOperation(IOperator op, IScope scope) {
    7883      IOperation operation;
    79       currentOperator = op;
    80       operation = op.Execute(scope);
    81       if (operation != null) {
    82         //IOperator currentOperator;
    83         Stack<IOperation> executionStack = new Stack<IOperation>();
    84         executionStack.Push(op.Execute(scope));
     84       if (persistedOperations.Count == 0) {
     85        currentOperator = op;
     86        operation = op.Execute(scope);
     87        if (operation != null) {
     88          executionStack.Push(operation);
     89        }
     90      } else {
     91        executionStack = new Stack<IOperation>(persistedOperations); 
     92      }
    8593
    86         while (executionStack.Count > 0) {
    87           operation = executionStack.Pop();
    88           if (operation is AtomicOperation) {
    89             AtomicOperation atomicOperation = (AtomicOperation)operation;
    90             IOperation next = null;
    91             try {
    92               currentOperator = atomicOperation.Operator;
    93               next = currentOperator.Execute(atomicOperation.Scope);
    94             }
    95             catch (Exception) {
    96               throw new InvalidOperationException("Invalid Operation occured in FixedBase.Execute");
    97             }
    98             if (next != null)
    99               executionStack.Push(next);
    100           } else if (operation is CompositeOperation) {
    101             CompositeOperation compositeOperation = (CompositeOperation)operation;
    102             for (int i = compositeOperation.Operations.Count - 1; i >= 0; i--)
    103               executionStack.Push(compositeOperation.Operations[i]);
    104           } // else if
    105         } // while
    106       } // if (operation != null)
     94      while (executionStack.Count > 0) {
     95        operation = executionStack.Pop();
     96        if (operation is AtomicOperation) {
     97          AtomicOperation atomicOperation = (AtomicOperation)operation;
     98          IOperation next = null;
     99          try {
     100            currentOperator = atomicOperation.Operator;
     101            next = currentOperator.Execute(atomicOperation.Scope);
     102          }
     103          catch (Exception) {
     104            throw new InvalidOperationException("Invalid Operation occured in FixedBase.Execute");
     105          }
     106          if (next != null)
     107            executionStack.Push(next);
     108        } else if (operation is CompositeOperation) {
     109          CompositeOperation compositeOperation = (CompositeOperation)operation;
     110          for (int i = compositeOperation.Operations.Count - 1; i >= 0; i--)
     111            executionStack.Push(compositeOperation.Operations[i]);
     112        } // else if
     113
     114        if (Canceled && executionStack.Count > 0) {
     115          SaveExecutionStack(executionStack);
     116          throw new CancelException();
     117        }
     118      } // while
    107119    } // ExecuteOperation
    108120
     121    private void SaveExecutionStack(Stack<IOperation> stack) {
     122      persistedOperations = new ItemList<IOperation>();
     123      persistedOperations.AddRange(stack.ToArray());
     124    } // SaveExecutionStack
     125
    109126    public override IOperation Apply(IScope scope) {
     127      base.Apply(scope);
    110128      try {
    111129        persistedExecutionPointer = scope.GetVariableValue<IntData>("ExecutionPointer", false);
     
    115133        scope.AddVariable(new Variable("ExecutionPointer", persistedExecutionPointer));
    116134      }
    117      
     135
     136      try {
     137        persistedOperations = scope.GetVariableValue<ItemList<IOperation>>("ExecutionStack", false);
     138      }
     139      catch (Exception) {
     140        persistedOperations = new ItemList<IOperation>();
     141        scope.AddVariable(new Variable("ExecutionStack", persistedOperations));
     142      }
     143
    118144      executionPointer = 0;
     145
     146      for (int i = 0; i < SubOperators.Count; i++) {
     147        if (scope.GetVariable(SubOperators[i].Name) != null)
     148          scope.RemoveVariable(SubOperators[i].Name);
     149        scope.AddVariable(new Variable(SubOperators[i].Name, SubOperators[i]));
     150      }
     151
    119152      return null;
    120153    } // Apply
     
    123156      base.Abort();
    124157      currentOperator.Abort();
    125       //engineThread.Abort();
    126     }
     158    } // Abort
    127159
    128   } // class FixedBase
     160    /// <summary>
     161    /// Saves the value of the execution pointers into temp variables
     162    /// </summary>
     163    protected void SaveExecutionPointer() {
     164      tempExePointer = executionPointer;
     165      tempPersExePointer = persistedExecutionPointer.Data;
     166    } // SaveExecutionPointer
    129167
    130   class CancelException : Exception {
    131  
     168    protected void SetExecutionPointerToLastSaved() {
     169      if (executionPointer != persistedExecutionPointer.Data)
     170        persistedExecutionPointer.Data = tempPersExePointer;
     171      else
     172        persistedExecutionPointer.Data = tempExePointer;
     173      executionPointer = tempExePointer;
     174    } // SetExecutionPointerToLastSaved
     175
     176
     177    protected void ResetExecutionPointer() {
     178      executionPointer = 0;
     179      persistedExecutionPointer.Data = 0;
     180    } // ResetExecutionPointer
     181  } // class FixedOperatorBase
     182
     183  class CancelException : Exception {
     184
    132185  } // class CancelException
    133186} // namespace HeuristicLab.FixedOperators
  • trunk/sources/HeuristicLab.FixedOperators/3.2/FixedSGAMain.cs

    r1923 r1995  
    3434using HeuristicLab.Selection;
    3535using System.Threading;
     36using System.IO;
     37using HeuristicLab.Random;
    3638
    3739namespace HeuristicLab.FixedOperators {
     
    5355    OperatorBase evaluator;
    5456    SubScopesRemover sr;
     57    StochasticBranch sb;
     58
     59    OperatorBase selector;
    5560
    5661    // CreateReplacement
     
    6368    Thread executionThread;
    6469    Thread cancelThread;
    65     StringBuilder output = new StringBuilder();
    66 
     70   
     71    // for testing only
     72    QualityLogger ql;
     73    BestAverageWorstQualityCalculator bawqc;
     74    DataCollector dc;
     75    ItemList<StringData> names;
     76    LinechartInjector lci;
    6777
    6878    //long[] timesExecuteCreateChildren;
     
    7989      sorter.GetVariableInfo("Value").ActualName = "Quality";
    8090
    81       InitVariablesForCreateChildren();
    82       InitVariablesForCreateReplacement();
    83     }
    84 
    85     private void InitVariablesForCreateReplacement() {
     91      InitCreateChildren();
     92      InitReplacement();
     93
     94      sb = new StochasticBranch();
     95      sb.GetVariableInfo("Probability").ActualName = "MutationRate";
     96    }
     97
     98    private void InitReplacement() {
    8699      ls = new LeftSelector();
    87100      rr = new RightReducer();
     
    92105      ls.GetVariableInfo("Selected").ActualName = "Elites";
    93106      rs.GetVariableInfo("Selected").ActualName = "Elites";
    94 
    95     }
    96 
    97     protected void InitVariablesForCreateChildren() {
     107    }
     108
     109    protected void InitCreateChildren() {
    98110      // variables for create children
    99111      ci = new ChildrenInitializer();
     
    117129      Stopwatch swApply = new Stopwatch();
    118130      swApply.Start();
    119       for (int i = 0; i < SubOperators.Count; i++) {
    120         if (scope.GetVariable(SubOperators[i].Name) != null)
    121           scope.RemoveVariable(SubOperators[i].Name);
    122         scope.AddVariable(new Variable(SubOperators[i].Name, SubOperators[i]));
    123       }
    124 
    125       OperatorBase selector = (OperatorBase)GetVariableValue("Selector", scope, true);
     131
     132      #region Initialization
    126133      QualityLogger ql = new QualityLogger();
    127134
     
    137144      lci.GetVariable("NumberOfLines").GetValue<IntData>().Data = 3;
    138145
    139       LessThanComparator ltc = new LessThanComparator();
    140       ltc.GetVariableInfo("LeftSide").ActualName = "Generations";
    141       ltc.GetVariableInfo("RightSide").ActualName = "MaximumGenerations";
    142       ltc.GetVariableInfo("Result").ActualName = "GenerationsCondition";
    143 
    144146      IntData maxGenerations = GetVariableValue<IntData>("MaximumGenerations", scope, true);
    145147      IntData nrOfGenerations = GetVariableValue<IntData>("Generations", scope, true);
    146       //nrOfGenerations.Data = 0;
    147 
     148   
    148149      IntData subscopeNr;
    149150      try {
     
    155156      }
    156157
    157       EmptyOperator empty = new EmptyOperator();
     158      ci = new ChildrenInitializer();
     159     
     160
     161      GetOperatorsFromScope(scope);
     162
     163      try {
     164        sb.RemoveSubOperator(0);
     165      }
     166      catch (Exception) {
     167      }
     168      sb.AddSubOperator(mutator);
     169
    158170
    159171      IScope s;
    160172      IScope s2;
    161       int tempExePointer = 0;
    162       int tempPersExePointer = 0;
    163       double randomNumber;
    164      
    165       // fetch variables from scope for create children
    166       InitializeExecuteCreateChildren(scope);
     173      #endregion
    167174      try {
    168         for (int i = nrOfGenerations.Data; i < maxGenerations.Data; i++) {
    169           if (executionPointer == persistedExecutionPointer.Data)
    170             persistedExecutionPointer.Data = 0;
    171           executionPointer = 0;
    172 
     175        for (; nrOfGenerations.Data < maxGenerations.Data; nrOfGenerations.Data++) {
    173176          Execute(selector, scope);
    174177
     
    178181          Execute(ci, s);
    179182
    180           tempExePointer = executionPointer;
    181           tempPersExePointer = persistedExecutionPointer.Data;
     183          SaveExecutionPointer();
    182184          // UniformSequentialSubScopesProcessor
    183           for (int j = subscopeNr.Data; j < s.SubScopes.Count; j++) {
    184             if (executionPointer == persistedExecutionPointer.Data)
    185               persistedExecutionPointer.Data = tempExePointer;
    186             executionPointer = tempExePointer;
    187 
    188             s2 = s.SubScopes[j];
     185          for (; subscopeNr.Data < s.SubScopes.Count; subscopeNr.Data++) {
     186            SetExecutionPointerToLastSaved();
     187
     188            s2 = s.SubScopes[subscopeNr.Data];
    189189            Execute(crossover, s2);
    190190            // Stochastic Branch
    191 
    192             randomNumber = random.NextDouble();
     191            Execute(sb, s2);
     192
     193            // ganz böse!!!!!!!
     194            // wird nach dem stochastic branch angehalten und später fortgesetzt,
     195            // wird eine Zufallszahl erzeugt, die aber nicht verwendet wird.
     196            // Dadurch kommt der GA auf ein anderes Endergebnis
     197            // Lösung: Stochastic Branch Operator verwenden
     198            //randomNumber = random.NextDouble();
    193199            //output.AppendLine(randomNumber.ToString());
    194             if (randomNumber < probability.Data)
    195               Execute(mutator, s2);
    196             else
    197               Execute(empty, s2);
     200            //if (randomNumber < probability.Data)
     201            //  Execute(mutator, s2);
     202            //else
     203            //  Execute(empty, s2);
     204
    198205            Execute(evaluator, s2);
    199206            Execute(sr, s2);
    200207            Execute(counter, s2);
    201             subscopeNr.Data++;
    202208          } // foreach
    203 
    204209
    205210          Execute(sorter, s);
    206211          ////// END Create Children //////
    207212
    208           ExecuteCreateReplacementWithFixedConstrolStructures(scope);
     213          DoReplacement(scope);
    209214          Execute(ql, scope);
    210215          Execute(bawqc, scope);
     
    212217          Execute(lci, scope);
    213218          subscopeNr.Data = 0;
    214           nrOfGenerations.Data++;
     219          ResetExecutionPointer();
    215220        } // for i
    216221
    217 
    218 
     222        //TextWriter tw = new StreamWriter(DateTime.Now.ToFileTime() + ".txt");
     223        //tw.Write(output.ToString());
     224        //tw.Close();
     225        //output = new StringBuilder();
     226
     227        swApply.Stop();
     228        Console.WriteLine("SGAMain.Apply(): {0}", swApply.Elapsed);
    219229      } // try
    220230      catch (CancelException) {
    221231        Console.WriteLine("Micro engine aborted by cancel flag.");
    222       }
    223       catch (Exception) {
    224          
    225       }
    226 
    227       swApply.Stop();
    228       Console.WriteLine("SGAMain.Apply(): {0}", swApply.Elapsed);
    229 
    230       if (Canceled) {
    231232        return new AtomicOperation(this, scope);
    232233      }
     
    235236    } // Apply
    236237
    237     private void WorkerMethod(object o) {
    238      
    239     } // Apply
    240 
    241 
    242 
    243238    /// <summary>
    244     /// Initializes some variables needed before the execution of create children
     239    /// Fetch main operators like selector, crossover, mutator, ... from scope
     240    /// and store them in instance variables.
    245241    /// </summary>
    246242    /// <param name="scope"></param>
    247     private void InitializeExecuteCreateChildren(IScope scope) {
     243    private void GetOperatorsFromScope(IScope scope) {
     244      selector = (OperatorBase)GetVariableValue("Selector", scope, true);
    248245      crossover = (OperatorBase)GetVariableValue("Crossover", scope, true);
    249246      mutator = (OperatorBase)GetVariableValue("Mutator", scope, true);
     
    252249      random = GetVariableValue<IRandom>("Random", scope, true);
    253250      probability = GetVariableValue<DoubleData>("MutationRate", scope, true);
    254 
    255       ci = new ChildrenInitializer();
    256251    }
    257252
     
    260255    /// </summary>
    261256    /// <param name="scope"></param>
    262     protected void ExecuteCreateChildrenWithFixedControlStructures(IScope scope) {
     257    protected void CreateChildren(IScope scope) {
    263258      // ChildrenInitializer
    264259      Execute(ci, scope);
     
    275270
    276271      Execute(sorter, scope);
    277     } // ExecuteCreateChildrenHWCS
    278 
    279     private void ExecuteCreateReplacementWithFixedConstrolStructures(IScope scope) {
     272    } // CreateChildren
     273
     274    private void DoReplacement(IScope scope) {
    280275      //// SequentialSubScopesProcessor
    281276      Execute(ls, scope.SubScopes[0]);
     
    287282      Execute(mr, scope);
    288283      Execute(sorter, scope);
    289     } // ExecuteCreateReplacementWithFixedConstrolStructures
    290 
    291 
     284    } // DoReplacement
    292285  } // class FixedSGAMain
    293286} // namespace HeuristicLab.FixedOperators
Note: See TracChangeset for help on using the changeset viewer.