Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Operators/MultiHeuristicBranch.cs @ 44

Last change on this file since 44 was 44, checked in by gkronber, 16 years ago

added operator MultiHeuristicBranch

File size: 1.7 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Text;
4using HeuristicLab.Core;
5using HeuristicLab.Data;
6
7namespace HeuristicLab.Operators {
8  public class MultiHeuristicBranch: OperatorBase {
9    public MultiHeuristicBranch()
10      : base() {
11
12      AddVariableInfo(new VariableInfo("Probabilities", "The probabilities, that define how likely each suboperator/graph is executed. This array must sum to 1", typeof(DoubleArrayData), VariableKind.In));
13      AddVariableInfo(new VariableInfo("Random", "The pseudo random-generator, used for any random-decision.", typeof(IRandom), VariableKind.In));
14    }
15
16    public override IOperation Apply(IScope scope) {
17      IRandom random = GetVariableValue<IRandom>("Random", scope, true);
18      DoubleArrayData probabilities = GetVariableValue<DoubleArrayData>("Probabilities", scope, true);
19      if(probabilities.Data.Length != SubOperators.Count) {
20        throw new InvalidOperationException("MultiHeuristicBranch: The list of probabilities has to match the number of operators");
21      }
22      double sum = 0;
23      foreach(double prob in probabilities.Data) {
24        sum+=prob;
25      }
26      double r = random.NextDouble()*sum;
27      sum = 0;
28      IOperator successor = null;
29      for(int i = 0; i < SubOperators.Count; i++) {
30        sum += probabilities.Data[i];
31        if(sum > r) {
32          successor = SubOperators[i];
33          break;
34        }
35      }
36      if(successor == null) {
37        throw new InvalidOperationException("MultiHeuristicBranch: There was a problem with the list of probabilities");
38      }
39      return new AtomicOperation(successor, scope);
40    }
41  }
42}
Note: See TracBrowser for help on using the repository browser.