Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Operators/3.3/StochasticMultiBranch.cs @ 16245

Last change on this file since 16245 was 15583, checked in by swagner, 7 years ago

#2640: Updated year of copyrights in license headers

File size: 9.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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    public ValueParameter<BoolValue> TraceSelectedOperatorParameter {
52      get { return (ValueParameter<BoolValue>)Parameters["TraceSelectedOperator"]; }
53    }
54    public LookupParameter<StringValue> SelectedOperatorParameter {
55      get { return (LookupParameter<StringValue>)Parameters["SelectedOperator"]; }
56    }
57
58    public DoubleArray Probabilities {
59      get { return ProbabilitiesParameter.Value; }
60      set { ProbabilitiesParameter.Value = value; }
61    }
62
63    [StorableConstructor]
64    protected StochasticMultiBranch(bool deserializing) : base(deserializing) { }
65    protected StochasticMultiBranch(StochasticMultiBranch<T> original, Cloner cloner)
66      : base(original, cloner) {
67    }
68    /// <summary>
69    /// Initializes a new instance of <see cref="StochasticMultiOperator"/> with two parameters
70    /// (<c>Probabilities</c> and <c>Random</c>).
71    /// </summary>
72    public StochasticMultiBranch()
73      : base() {
74      Parameters.Add(new ValueLookupParameter<DoubleArray>("Probabilities", "The array of relative probabilities for each operator.", new DoubleArray()));
75      Parameters.Add(new LookupParameter<IRandom>("Random", "The random number generator to use."));
76      Parameters.Add(new LookupParameter<StringValue>("SelectedOperator", "If the TraceSelectedOperator flag is set, the name of the operator is traced in this parameter."));
77      Parameters.Add(new ValueParameter<BoolValue>("TraceSelectedOperator", "Indicates, if the selected operator should be traced.", new BoolValue(false)));
78      SelectedOperatorParameter.Hidden = false;
79    }
80
81    [StorableHook(HookType.AfterDeserialization)]
82    private void AfterDeserialization() {
83      // BackwardsCompatibility3.3
84      #region Backwards compatible code, remove with 3.4
85      if (!Parameters.ContainsKey("SelectedOperator")) {
86        Parameters.Add(new LookupParameter<StringValue>("SelectedOperator", "If the TraceSelectedOperator flag is set, the name of the operator is traced in this parameter."));
87        SelectedOperatorParameter.Hidden = false;
88      }
89      if (!Parameters.ContainsKey("TraceSelectedOperator")) {
90        Parameters.Add(new ValueParameter<BoolValue>("TraceSelectedOperator", "Indicates, if the selected operator should be traced.", new BoolValue(false)));
91      }
92      #endregion
93    }
94
95    protected override void Operators_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
96      base.Operators_ItemsRemoved(sender, e);
97      if (Probabilities != null && Probabilities.Length > Operators.Count) {
98        List<double> probs = new List<double>(Probabilities.Cast<double>());
99        var sorted = e.Items.OrderByDescending(x => x.Index);
100        foreach (IndexedItem<T> item in sorted)
101          if (probs.Count > item.Index) probs.RemoveAt(item.Index);
102        Probabilities = new DoubleArray(probs.ToArray());
103      }
104    }
105
106    protected override void Operators_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IndexedItem<T>> e) {
107      base.Operators_ItemsAdded(sender, e);
108      if (Probabilities != null && Probabilities.Length < Operators.Count) {
109        double avg = (Probabilities.Where(x => x > 0).Count() > 0) ? (Probabilities.Where(x => x > 0).Average()) : (1);
110        // add the average of all probabilities in the respective places (the new operators)
111        var added = e.Items.OrderBy(x => x.Index).ToList();
112        int insertCount = 0;
113        DoubleArray probs = new DoubleArray(Operators.Count);
114        for (int i = 0; i < Operators.Count; i++) {
115          if (insertCount < added.Count && i == added[insertCount].Index) {
116            probs[i] = avg;
117            insertCount++;
118          } else if (i - insertCount < Probabilities.Length) {
119            probs[i] = Probabilities[i - insertCount];
120          } else probs[i] = avg;
121        }
122        Probabilities = probs;
123      }
124    }
125
126    /// <summary>
127    /// Applies an operator of the branches to the current scope with a
128    /// specific probability.
129    /// </summary>
130    /// <exception cref="InvalidOperationException">Thrown when the list of probabilites does not
131    /// match the number of operators, the list of selected operators is empty,
132    /// or all selected operators have zero probabitlity.</exception>
133    /// <returns>A new operation with the operator that was selected followed by the current operator's successor.</returns>
134    public override IOperation InstrumentedApply() {
135      IRandom random = RandomParameter.ActualValue;
136      DoubleArray probabilities = ProbabilitiesParameter.ActualValue;
137      if (probabilities.Length != Operators.Count) {
138        throw new InvalidOperationException(Name + ": The list of probabilities has to match the number of operators");
139      }
140      IOperator successor = null;
141      int index = -1;
142      var checkedOperators = Operators.CheckedItems;
143      if (checkedOperators.Count() > 0) {
144        // select a random operator from the checked operators
145        double sum = (from indexedItem in checkedOperators select probabilities[indexedItem.Index]).Sum();
146        if (sum == 0) throw new InvalidOperationException(Name + ": All selected operators have zero probability.");
147        double r = random.NextDouble() * sum;
148        sum = 0;
149        foreach (var indexedItem in checkedOperators) {
150          sum += probabilities[indexedItem.Index];
151          if (sum > r) {
152            successor = indexedItem.Value;
153            index = indexedItem.Index;
154            break;
155          }
156        }
157      }
158      OperationCollection next = new OperationCollection(base.InstrumentedApply());
159      if (successor != null) {
160        if (TraceSelectedOperatorParameter.Value.Value)
161          SelectedOperatorParameter.ActualValue = new StringValue(index + ": " + successor.Name);
162
163        if (CreateChildOperation)
164          next.Insert(0, ExecutionContext.CreateChildOperation(successor));
165        else next.Insert(0, ExecutionContext.CreateOperation(successor));
166      } else {
167        if (TraceSelectedOperatorParameter.Value.Value)
168          SelectedOperatorParameter.ActualValue = new StringValue("");
169      }
170      return next;
171    }
172  }
173
174  /// <summary>
175  /// Selects one of its branches (if there are any) given a list of relative probabilities.
176  /// </summary>
177  [Item("StochasticMultiBranch", "Selects one of its branches (if there are any) given a list of relative probabilities.")]
178  [StorableClass]
179  public class StochasticMultiBranch : StochasticMultiBranch<IOperator> {
180    [StorableConstructor]
181    protected StochasticMultiBranch(bool deserializing) : base(deserializing) { }
182    protected StochasticMultiBranch(StochasticMultiBranch original, Cloner cloner)
183      : base(original, cloner) {
184    }
185    public StochasticMultiBranch() { }
186
187    public override IDeepCloneable Clone(Cloner cloner) {
188      return new StochasticMultiBranch(this, cloner);
189    }
190
191    protected override bool CreateChildOperation {
192      get { return false; }
193    }
194  }
195}
Note: See TracBrowser for help on using the repository browser.