Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Operators/3.3/StochasticMultiBranch.cs @ 3418

Last change on this file since 3418 was 3418, checked in by abeham, 14 years ago

Moved TabuMaker from Optimization to Optimization.Operators (and updated references)
Added StochasticMultiBranch
Implemented MultiCrossover and PermutationMultiCrossover
#976, #840

File size: 6.4 KB
RevLine 
[46]1#region License Information
2/* HeuristicLab
[3418]3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[46]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;
[44]23using System.Collections.Generic;
[3418]24using System.Collections.ObjectModel;
25using System.Linq;
26using HeuristicLab.Collections;
27using HeuristicLab.Common;
[44]28using HeuristicLab.Core;
29using HeuristicLab.Data;
[3418]30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[44]32
33namespace HeuristicLab.Operators {
[801]34  /// <summary>
35  /// Branch of operators that have different probabilities to get executed.
36  /// </summary>
[3418]37  [Item("StochasticMultiBranch", "Branch of operators that have different probabilities to get executed.")]
38  [StorableClass]
39  public class StochasticMultiBranch : MultiOperator<IOperator> {
40    public ValueLookupParameter<DoubleArray> ProbabilitiesParameter {
41      get { return (ValueLookupParameter<DoubleArray>)Parameters["Probabilities"]; }
[46]42    }
[3418]43    public ILookupParameter<IRandom> RandomParameter {
44      get { return (ILookupParameter<IRandom>)Parameters["Random"]; }
45    }
[46]46
[3418]47    public DoubleArray Probabilities {
48      get { return ProbabilitiesParameter.Value; }
49      set { ProbabilitiesParameter.Value = value; }
50    }
51
52    [StorableConstructor]
53    public StochasticMultiBranch(bool deserializing) : base() { }
[801]54    /// <summary>
[3418]55    /// Initializes a new instance of <see cref="StochasticMultiBranch"/> with two parameters
[801]56    /// (<c>Probabilities</c> and <c>Random</c>).
57    /// </summary>
[46]58    public StochasticMultiBranch()
[44]59      : base() {
[3418]60      Parameters.Add(new ValueLookupParameter<DoubleArray>("Probabilities", "The array of relative probabilities for each operator.", new DoubleArray()));
61      Parameters.Add(new LookupParameter<IRandom>("Random", "The random number generator to use."));
62      Initialize();
[44]63    }
64
[3418]65    [StorableHook(HookType.AfterDeserialization)]
66    private void Initialize() {
67      Operators.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<IOperator>>(Operators_ItemsAdded);
68      Operators.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<IOperator>>(Operators_ItemsRemoved);
69      Operators.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<IOperator>>(Operators_ItemsMoved);
70    }
71
72    void Operators_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOperator>> e) {
73      if (Probabilities != null) {
74        DoubleArray oldProb = (DoubleArray)Probabilities.Clone();
75        foreach (IndexedItem<IOperator> old in e.OldItems) {
76          foreach (IndexedItem<IOperator> item in e.Items) {
77            if (old.Value == item.Value && item.Index < Probabilities.Length && old.Index < oldProb.Length)
78              Probabilities[item.Index] = oldProb[old.Index];
79          }
80        }
81      }
82    }
83
84    void Operators_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<IOperator>> e) {
85      if (Probabilities != null && Probabilities.Length > Operators.Count) {
86        List<double> probs = new List<double>(Probabilities.Cast<DoubleValue>().Select(x => x.Value));
87        var sorted = e.Items.OrderByDescending(x => x.Index);
88        foreach (IndexedItem<IOperator> item in sorted)
89          if (probs.Count > item.Index) probs.RemoveAt(item.Index);
90        Probabilities = new DoubleArray(probs.ToArray());
91      }
92    }
93
94    private void Operators_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IndexedItem<IOperator>> e) {
95      if (Probabilities != null && Probabilities.Length < Operators.Count) {
96        DoubleArray probs = new DoubleArray(Operators.Count);
97        double avg = 0;
98        if (Probabilities.Length > 0) {
99          for (int i = 0; i < Probabilities.Length; i++)
100            avg += Probabilities[i];
101          avg /= (double)Probabilities.Length;
102        } else avg = 1;
103
104        var added = e.Items.OrderBy(x => x.Index).ToList();
105        int insertCount = 0;
106        for (int i = 0; i < Operators.Count; i++) {
107          if (insertCount < added.Count && i == added[insertCount].Index) {
108            probs[i] = avg;
109            insertCount++;
110          } else if (i - insertCount < Probabilities.Length) {
111            probs[i] = Probabilities[i - insertCount];
112          } else probs[i] = avg;
113        }
114        Probabilities = probs;
115      }
116    }
117
[801]118    /// <summary>
[3418]119    /// Applies an operator of the branches to the current scope with a
[801]120    /// specific probability.
121    /// </summary>
122    /// <exception cref="InvalidOperationException">Thrown when the list of probabilites does not
[3418]123    /// match the number of operators.</exception>
124    /// <returns>A new operation with the operator that was selected followed by the current operator's successor.</returns>
125    public override IOperation Apply() {
126      IRandom random = RandomParameter.ActualValue;
127      DoubleArray probabilities = ProbabilitiesParameter.ActualValue;
128      if(probabilities.Length != Operators.Count) {
[46]129        throw new InvalidOperationException("StochasticMultiBranch: The list of probabilities has to match the number of operators");
[44]130      }
131      double sum = 0;
[3418]132      for (int i = 0; i < Operators.Count; i++) {
133        sum += probabilities[i];
[44]134      }
[3418]135      double r = random.NextDouble() * sum;
[44]136      sum = 0;
137      IOperator successor = null;
[3418]138      for(int i = 0; i < Operators.Count; i++) {
139        sum += probabilities[i];
[44]140        if(sum > r) {
[3418]141          successor = Operators[i];
[44]142          break;
143        }
144      }
[3418]145      OperationCollection next = new OperationCollection(base.Apply());
146      if (successor != null) {
147        next.Insert(0, ExecutionContext.CreateOperation(successor));
[44]148      }
[3418]149      return next;
[44]150    }
151  }
152}
Note: See TracBrowser for help on using the repository browser.