Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParameterBinding/HeuristicLab.Operators/3.3/StochasticMultiBranch.cs @ 6593

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

Merged cloning refactoring branch back into trunk (#922)

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