Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4068 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

File size: 6.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Linq;
25using HeuristicLab.Collections;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Operators {
32  /// <summary>
33  /// Selects one of its branches (if there are any) given a list of relative probabilities.
34  /// </summary>
35  [Item("StochasticMultiBranch", "Selects one of its branches (if there are any) given a list of relative probabilities.")]
36  [StorableClass]
37  public abstract class StochasticMultiBranch<T> : CheckedMultiOperator<T> where T : class, IOperator {
38    /// <summary>
39    /// Should return true if the StochasticMultiOperator should create a new child operation with the selected successor
40    /// or if it should create a new operation. If you need to shield the parameters of the successor you should return true here.
41    /// </summary>
42    protected abstract bool CreateChildOperation { get; }
43
44    public ValueLookupParameter<DoubleArray> ProbabilitiesParameter {
45      get { return (ValueLookupParameter<DoubleArray>)Parameters["Probabilities"]; }
46    }
47    public ILookupParameter<IRandom> RandomParameter {
48      get { return (ILookupParameter<IRandom>)Parameters["Random"]; }
49    }
50
51    public DoubleArray Probabilities {
52      get { return ProbabilitiesParameter.Value; }
53      set { ProbabilitiesParameter.Value = value; }
54    }
55
56    [StorableConstructor]
57    protected StochasticMultiBranch(bool deserializing) : base(deserializing) { }
58    /// <summary>
59    /// Initializes a new instance of <see cref="StochasticMultiOperator"/> with two parameters
60    /// (<c>Probabilities</c> and <c>Random</c>).
61    /// </summary>
62    public StochasticMultiBranch()
63      : base() {
64      Parameters.Add(new ValueLookupParameter<DoubleArray>("Probabilities", "The array of relative probabilities for each operator.", new DoubleArray()));
65      Parameters.Add(new LookupParameter<IRandom>("Random", "The random number generator to use."));
66    }
67
68    protected override void Operators_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
69      base.Operators_ItemsRemoved(sender, e);
70      if (Probabilities != null && Probabilities.Length > Operators.Count) {
71        List<double> probs = new List<double>(Probabilities.Cast<double>());
72        var sorted = e.Items.OrderByDescending(x => x.Index);
73        foreach (IndexedItem<T> item in sorted)
74          if (probs.Count > item.Index) probs.RemoveAt(item.Index);
75        Probabilities = new DoubleArray(probs.ToArray());
76      }
77    }
78
79    protected override void Operators_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
80      base.Operators_ItemsAdded(sender, e);
81      if (Probabilities != null && Probabilities.Length < Operators.Count) {
82        double avg = (Probabilities.Where(x => x > 0).Count() > 0) ? (Probabilities.Where(x => x > 0).Average()) : (1);
83        // add the average of all probabilities in the respective places (the new operators)
84        var added = e.Items.OrderBy(x => x.Index).ToList();
85        int insertCount = 0;
86        DoubleArray probs = new DoubleArray(Operators.Count);
87        for (int i = 0; i < Operators.Count; i++) {
88          if (insertCount < added.Count && i == added[insertCount].Index) {
89            probs[i] = avg;
90            insertCount++;
91          } else if (i - insertCount < Probabilities.Length) {
92            probs[i] = Probabilities[i - insertCount];
93          } else probs[i] = avg;
94        }
95        Probabilities = probs;
96      }
97    }
98
99    /// <summary>
100    /// Applies an operator of the branches to the current scope with a
101    /// specific probability.
102    /// </summary>
103    /// <exception cref="InvalidOperationException">Thrown when the list of probabilites does not
104    /// match the number of operators, the list of selected operators is empty,
105    /// or all selected operators have zero probabitlity.</exception>
106    /// <returns>A new operation with the operator that was selected followed by the current operator's successor.</returns>
107    public override IOperation Apply() {
108      IRandom random = RandomParameter.ActualValue;
109      DoubleArray probabilities = ProbabilitiesParameter.ActualValue;
110      if (probabilities.Length != Operators.Count) {
111        throw new InvalidOperationException(Name + ": The list of probabilities has to match the number of operators");
112      }
113      IOperator successor = null;
114      var checkedOperators = Operators.CheckedItems;
115      if (checkedOperators.Count() > 0) {
116        // select a random operator from the checked operators
117        double sum = (from indexedItem in checkedOperators select probabilities[indexedItem.Index]).Sum();
118        if (sum == 0) throw new InvalidOperationException(Name + ": All selected operators have zero probability.");
119        double r = random.NextDouble() * sum;
120        sum = 0;
121        foreach (var indexedItem in checkedOperators) {
122          sum += probabilities[indexedItem.Index];
123          if (sum > r) {
124            successor = indexedItem.Value;
125            break;
126          }
127        }
128      }
129      OperationCollection next = new OperationCollection(base.Apply());
130      if (successor != null) {
131        if (CreateChildOperation)
132          next.Insert(0, ExecutionContext.CreateChildOperation(successor));
133        else next.Insert(0, ExecutionContext.CreateOperation(successor));
134      }
135      return next;
136    }
137  }
138
139  /// <summary>
140  /// Selects one of its branches (if there are any) given a list of relative probabilities.
141  /// </summary>
142  [Item("StochasticMultiBranch", "Selects one of its branches (if there are any) given a list of relative probabilities.")]
143  [StorableClass]
144  public class StochasticMultiBranch : StochasticMultiBranch<IOperator> {
145    protected override bool CreateChildOperation {
146      get { return false; }
147    }
148  }
149}
Note: See TracBrowser for help on using the repository browser.