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