1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using System.Threading;
|
---|
5 | using HeuristicLab.Common;
|
---|
6 | using HeuristicLab.Core;
|
---|
7 | using HeuristicLab.Data;
|
---|
8 | using HeuristicLab.Optimization;
|
---|
9 | using HeuristicLab.Parameters;
|
---|
10 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
11 |
|
---|
12 | namespace HeuristicLab.Selection {
|
---|
13 | /// <summary>
|
---|
14 | /// A selector which tries to select two parents which differ in quality.
|
---|
15 | /// </summary>
|
---|
16 | [Item("NoSameMatesSelector", "A selector which tries to select two parents which differ in quality.")]
|
---|
17 | [StorableClass]
|
---|
18 | public class NoSameMatesSelector : StochasticSingleObjectiveSelector, ISingleObjectiveSelector {
|
---|
19 | private const string SelectorParameterName = "Selector";
|
---|
20 | private const string QualityDifferencePercentageParameterName = "QualityDifferencePercentage";
|
---|
21 | private const string QualityDifferenceMaxAttemptsParameterName = "QualityDifferenceMaxAttempts";
|
---|
22 | private const string QualityDifferenceUseRangeParameterName = "QualityDifferenceUseRange";
|
---|
23 |
|
---|
24 | #region Parameters
|
---|
25 | public IValueParameter<ISingleObjectiveSelector> SelectorParameter {
|
---|
26 | get { return (IValueParameter<ISingleObjectiveSelector>)Parameters[SelectorParameterName]; }
|
---|
27 | }
|
---|
28 | public IFixedValueParameter<PercentValue> QualityDifferencePercentageParameter {
|
---|
29 | get { return (IFixedValueParameter<PercentValue>)Parameters[QualityDifferencePercentageParameterName]; }
|
---|
30 | }
|
---|
31 | public IFixedValueParameter<IntValue> QualityDifferenceMaxAttemptsParameter {
|
---|
32 | get { return (IFixedValueParameter<IntValue>)Parameters[QualityDifferenceMaxAttemptsParameterName]; }
|
---|
33 | }
|
---|
34 | public IFixedValueParameter<BoolValue> QualityDifferenceUseRangeParameter {
|
---|
35 | get { return (IFixedValueParameter<BoolValue>)Parameters[QualityDifferenceUseRangeParameterName]; }
|
---|
36 | }
|
---|
37 | #endregion
|
---|
38 |
|
---|
39 | #region Properties
|
---|
40 | public ISingleObjectiveSelector Selector {
|
---|
41 | get { return SelectorParameter.Value; }
|
---|
42 | set { SelectorParameter.Value = value; }
|
---|
43 | }
|
---|
44 | public PercentValue QualityDifferencePercentage {
|
---|
45 | get { return QualityDifferencePercentageParameter.Value; }
|
---|
46 | }
|
---|
47 | public IntValue QualityDifferenceMaxAttempts {
|
---|
48 | get { return QualityDifferenceMaxAttemptsParameter.Value; }
|
---|
49 | }
|
---|
50 | public BoolValue QualityDifferenceUseRange {
|
---|
51 | get { return QualityDifferenceUseRangeParameter.Value; }
|
---|
52 | }
|
---|
53 | #endregion
|
---|
54 |
|
---|
55 | [StorableConstructor]
|
---|
56 | protected NoSameMatesSelector(bool deserializing) : base(deserializing) { }
|
---|
57 | protected NoSameMatesSelector(NoSameMatesSelector original, Cloner cloner)
|
---|
58 | : base(original, cloner) {
|
---|
59 | RegisterParameterEventHandlers();
|
---|
60 | }
|
---|
61 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
62 | return new NoSameMatesSelector(this, cloner);
|
---|
63 | }
|
---|
64 |
|
---|
65 | public NoSameMatesSelector()
|
---|
66 | : base() {
|
---|
67 | #region Create parameters
|
---|
68 | Parameters.Add(new ValueParameter<ISingleObjectiveSelector>(SelectorParameterName, "The inner selection operator to select the parents.", new TournamentSelector()));
|
---|
69 | Parameters.Add(new FixedValueParameter<PercentValue>(QualityDifferencePercentageParameterName, "The minimum quality difference from parent1 to parent2 to accept the selection.", new PercentValue(0.05)));
|
---|
70 | Parameters.Add(new FixedValueParameter<IntValue>(QualityDifferenceMaxAttemptsParameterName, "The maximum number of attempts to find parents which differ in quality.", new IntValue(5)));
|
---|
71 | Parameters.Add(new FixedValueParameter<BoolValue>(QualityDifferenceUseRangeParameterName, "Use the range from minimum to maximum quality as basis for QualityDifferencePercentage.", new BoolValue(true)));
|
---|
72 | #endregion
|
---|
73 |
|
---|
74 | CopySelectedParameter.Hidden = true;
|
---|
75 | RegisterParameterEventHandlers();
|
---|
76 | }
|
---|
77 |
|
---|
78 | [StorableHook(HookType.AfterDeserialization)]
|
---|
79 | private void AfterDeserialization() {
|
---|
80 | #region conversion of old NSM parameters
|
---|
81 | if (Parameters.ContainsKey(SelectorParameterName)) { // change SelectorParameter type from ISelector to ISingleObjectiveSelector
|
---|
82 | ValueParameter<ISelector> param = Parameters[SelectorParameterName] as ValueParameter<ISelector>;
|
---|
83 | if (param != null) {
|
---|
84 | ISingleObjectiveSelector selector = param.Value as ISingleObjectiveSelector;
|
---|
85 | if (selector == null) selector = new TournamentSelector();
|
---|
86 | Parameters.Remove(SelectorParameterName);
|
---|
87 | Parameters.Add(new ValueParameter<ISingleObjectiveSelector>(SelectorParameterName, "The inner selection operator to select the parents.", selector));
|
---|
88 | }
|
---|
89 | }
|
---|
90 | // FixedValueParameter for quality difference percentage, max attempts, use range
|
---|
91 | if (Parameters.ContainsKey(QualityDifferencePercentageParameterName)) {
|
---|
92 | ValueParameter<PercentValue> param = Parameters[QualityDifferencePercentageParameterName] as ValueParameter<PercentValue>;
|
---|
93 | if (!(param is FixedValueParameter<PercentValue>)) {
|
---|
94 | PercentValue diff = param != null ? param.Value as PercentValue : null;
|
---|
95 | if (diff == null) diff = new PercentValue(0.05);
|
---|
96 | Parameters.Remove(QualityDifferencePercentageParameterName);
|
---|
97 | Parameters.Add(new FixedValueParameter<PercentValue>(QualityDifferencePercentageParameterName, "The minimum quality difference from parent1 to parent2 to accept the selection.", diff));
|
---|
98 | }
|
---|
99 | }
|
---|
100 | if (Parameters.ContainsKey(QualityDifferenceMaxAttemptsParameterName)) {
|
---|
101 | ValueParameter<IntValue> param = Parameters[QualityDifferenceMaxAttemptsParameterName] as ValueParameter<IntValue>;
|
---|
102 | if (!(param is FixedValueParameter<IntValue>)) {
|
---|
103 | IntValue attempts = param != null ? param.Value as IntValue : null;
|
---|
104 | if (attempts == null) attempts = new IntValue(5);
|
---|
105 | Parameters.Remove(QualityDifferenceMaxAttemptsParameterName);
|
---|
106 | Parameters.Add(new FixedValueParameter<IntValue>(QualityDifferenceMaxAttemptsParameterName, "The maximum number of attempts to find parents which differ in quality.", attempts));
|
---|
107 | }
|
---|
108 | }
|
---|
109 | if (Parameters.ContainsKey(QualityDifferenceUseRangeParameterName)) {
|
---|
110 | ValueParameter<BoolValue> param = Parameters[QualityDifferenceUseRangeParameterName] as ValueParameter<BoolValue>;
|
---|
111 | if (!(param is FixedValueParameter<BoolValue>)) {
|
---|
112 | BoolValue range = param != null ? param.Value as BoolValue : null;
|
---|
113 | if (range == null) range = new BoolValue(true);
|
---|
114 | Parameters.Remove(QualityDifferenceUseRangeParameterName);
|
---|
115 | Parameters.Add(new FixedValueParameter<BoolValue>(QualityDifferenceUseRangeParameterName, "Use the range from minimum to maximum quality as basis for QualityDifferencePercentage.", range));
|
---|
116 | }
|
---|
117 | }
|
---|
118 | if (!Parameters.ContainsKey(QualityDifferenceUseRangeParameterName)) // add use range parameter
|
---|
119 | Parameters.Add(new FixedValueParameter<BoolValue>(QualityDifferenceUseRangeParameterName, "Use the range from minimum to maximum quality as basis for QualityDifferencePercentage.", new BoolValue(true)));
|
---|
120 | #endregion
|
---|
121 |
|
---|
122 | RegisterParameterEventHandlers();
|
---|
123 | }
|
---|
124 |
|
---|
125 | protected override IScope[] Select(List<IScope> scopes) {
|
---|
126 | int parentsToSelect = NumberOfSelectedSubScopesParameter.ActualValue.Value;
|
---|
127 | if (parentsToSelect % 2 > 0) throw new InvalidOperationException(Name + ": There must be an equal number of sub-scopes to be selected.");
|
---|
128 | IScope[] selected = new IScope[parentsToSelect];
|
---|
129 | IScope[] parentsPool = new IScope[parentsToSelect];
|
---|
130 |
|
---|
131 | double qualityDifferencePercentage = QualityDifferencePercentage.Value;
|
---|
132 | int qualityDifferenceMaxAttempts = QualityDifferenceMaxAttempts.Value;
|
---|
133 | bool qualityDifferenceUseRange = QualityDifferenceUseRange.Value;
|
---|
134 | string qualityName = QualityParameter.ActualName;
|
---|
135 |
|
---|
136 | // calculate quality offsets
|
---|
137 | double absoluteQualityOffset = 0;
|
---|
138 | double minRelativeQualityOffset = 0;
|
---|
139 | double maxRelativeQualityOffset = 0;
|
---|
140 | if (qualityDifferenceUseRange) {
|
---|
141 | // maximization flag is not needed because only the range is relevant
|
---|
142 | double minQuality = QualityParameter.ActualValue.Min(x => x.Value);
|
---|
143 | double maxQuality = QualityParameter.ActualValue.Max(x => x.Value);
|
---|
144 | absoluteQualityOffset = (maxQuality - minQuality) * qualityDifferencePercentage;
|
---|
145 | } else {
|
---|
146 | maxRelativeQualityOffset = 1.0 + qualityDifferencePercentage;
|
---|
147 | minRelativeQualityOffset = 1.0 - qualityDifferencePercentage;
|
---|
148 | }
|
---|
149 |
|
---|
150 | int selectedParents = 0;
|
---|
151 | int poolCount = 0;
|
---|
152 | // repeat until enough parents are selected or max attempts are reached
|
---|
153 | for (int attempts = 1; attempts <= qualityDifferenceMaxAttempts && selectedParents < parentsToSelect - 1; attempts++) {
|
---|
154 | ApplyInnerSelector();
|
---|
155 | ScopeList parents = CurrentScope.SubScopes[1].SubScopes;
|
---|
156 |
|
---|
157 | for (int indexParent1 = 0, indexParent2 = 1;
|
---|
158 | indexParent1 < parents.Count - 1 && selectedParents < parentsToSelect - 1;
|
---|
159 | indexParent1 += 2, indexParent2 += 2) {
|
---|
160 | double qualityParent1 = ((DoubleValue)parents[indexParent1].Variables[qualityName].Value).Value;
|
---|
161 | double qualityParent2 = ((DoubleValue)parents[indexParent2].Variables[qualityName].Value).Value;
|
---|
162 |
|
---|
163 | bool parentsDifferent;
|
---|
164 | if (qualityDifferenceUseRange) {
|
---|
165 | parentsDifferent = (qualityParent2 > qualityParent1 - absoluteQualityOffset ||
|
---|
166 | qualityParent2 < qualityParent1 + absoluteQualityOffset);
|
---|
167 | } else {
|
---|
168 | parentsDifferent = (qualityParent2 > qualityParent1 * maxRelativeQualityOffset ||
|
---|
169 | qualityParent2 < qualityParent1 * minRelativeQualityOffset);
|
---|
170 | }
|
---|
171 |
|
---|
172 | if (parentsDifferent) {
|
---|
173 | // inner selector already copied scopes, no cloning necessary here
|
---|
174 | selected[selectedParents++] = parents[indexParent1];
|
---|
175 | selected[selectedParents++] = parents[indexParent2];
|
---|
176 | } else if (attempts == qualityDifferenceMaxAttempts &&
|
---|
177 | poolCount < parentsToSelect - selectedParents) {
|
---|
178 | // last attempt: save parents to fill remaining positions
|
---|
179 | parentsPool[poolCount++] = parents[indexParent1];
|
---|
180 | parentsPool[poolCount++] = parents[indexParent2];
|
---|
181 | }
|
---|
182 | }
|
---|
183 | // modify scopes
|
---|
184 | ScopeList remaining = CurrentScope.SubScopes[0].SubScopes;
|
---|
185 | CurrentScope.SubScopes.Clear();
|
---|
186 | CurrentScope.SubScopes.AddRange(remaining);
|
---|
187 | }
|
---|
188 | // fill remaining positions with parents which don't meet the difference criterion
|
---|
189 | if (selectedParents < parentsToSelect - 1) {
|
---|
190 | Array.Copy(parentsPool, 0, selected, selectedParents, parentsToSelect - selectedParents);
|
---|
191 | }
|
---|
192 | return selected;
|
---|
193 | }
|
---|
194 |
|
---|
195 | #region Events
|
---|
196 | private void RegisterParameterEventHandlers() {
|
---|
197 | SelectorParameter.ValueChanged += new EventHandler(SelectorParameter_ValueChanged);
|
---|
198 | CopySelected.ValueChanged += new EventHandler(CopySelected_ValueChanged);
|
---|
199 | }
|
---|
200 |
|
---|
201 | private void SelectorParameter_ValueChanged(object sender, EventArgs e) {
|
---|
202 | ParameterizeSelector(Selector);
|
---|
203 | }
|
---|
204 |
|
---|
205 | private void CopySelected_ValueChanged(object sender, EventArgs e) {
|
---|
206 | if (CopySelected.Value != true) {
|
---|
207 | CopySelected.Value = true;
|
---|
208 | }
|
---|
209 | }
|
---|
210 | #endregion
|
---|
211 |
|
---|
212 | #region Helpers
|
---|
213 | private void ParameterizeSelector(ISingleObjectiveSelector selector) {
|
---|
214 | selector.CopySelected = new BoolValue(true); // must always be true
|
---|
215 | selector.MaximizationParameter.ActualName = MaximizationParameter.Name;
|
---|
216 | selector.QualityParameter.ActualName = QualityParameter.Name;
|
---|
217 |
|
---|
218 | IStochasticOperator stoOp = (selector as IStochasticOperator);
|
---|
219 | if (stoOp != null) stoOp.RandomParameter.ActualName = RandomParameter.Name;
|
---|
220 | }
|
---|
221 |
|
---|
222 | private void ApplyInnerSelector() {
|
---|
223 | // necessary for inner GenderSpecificSelector to execute all operations in OperationCollection
|
---|
224 | Stack<IOperation> executionStack = new Stack<IOperation>();
|
---|
225 | executionStack.Push(ExecutionContext.CreateChildOperation(Selector));
|
---|
226 | while (executionStack.Count > 0) {
|
---|
227 | CancellationToken.ThrowIfCancellationRequested();
|
---|
228 | IOperation next = executionStack.Pop();
|
---|
229 | if (next is OperationCollection) {
|
---|
230 | OperationCollection coll = (OperationCollection)next;
|
---|
231 | for (int i = coll.Count - 1; i >= 0; i--)
|
---|
232 | if (coll[i] != null) executionStack.Push(coll[i]);
|
---|
233 | } else if (next is IAtomicOperation) {
|
---|
234 | IAtomicOperation operation = (IAtomicOperation)next;
|
---|
235 | next = operation.Operator.Execute((IExecutionContext)operation, CancellationToken);
|
---|
236 | if (next != null) executionStack.Push(next);
|
---|
237 | }
|
---|
238 | }
|
---|
239 | }
|
---|
240 | #endregion
|
---|
241 | }
|
---|
242 | }
|
---|