Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RemoveBackwardsCompatibility/HeuristicLab.Selection/3.3/NoSameMatesSelector.cs @ 16654

Last change on this file since 16654 was 12012, checked in by ascheibe, 10 years ago

#2212 merged r12008, r12009, r12010 back into trunk

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