Free cookie consent management tool by TermsFeed Policy Generator

source: branches/VOSGA/HeuristicLab.Algorithms.VOffspringSelectionGeneticAlgorithm/Comparators/UnwantedMutationsComparator.cs @ 13605

Last change on this file since 13605 was 12079, checked in by ascheibe, 10 years ago

#2267 adapted branch to changes from #2332

File size: 15.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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.Linq;
24using HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.PermutationEncoding;
29using HeuristicLab.Operators;
30using HeuristicLab.Optimization;
31using HeuristicLab.Optimization.Operators;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.PluginInfrastructure;
35
36namespace HeuristicLab.Algorithms.VOffspringSelectionGeneticAlgorithm {
37  [Item("UnwantedMutationsComparator", "Compares the similarity against that of its parents (assumes the parents are subscopes to the child scope). This operator works with any number of subscopes > 0.")]
38  [StorableClass]
39  public class UnwantedMutationsComparator : SingleSuccessorOperator, ISubScopesQualityComparatorOperator {
40    [Storable]
41    public ISolutionSimilarityCalculator SimilarityCalculator { get; set; }
42    public IValueLookupParameter<ISolutionSimilarityCalculator> SimilarityCalculatorParameter {
43      get { return (IValueLookupParameter<ISolutionSimilarityCalculator>)Parameters["SimilarityCalculator"]; }
44    }
45    public IValueLookupParameter<BoolValue> MaximizationParameter {
46      get { return (IValueLookupParameter<BoolValue>)Parameters["Maximization"]; }
47    }
48    public ILookupParameter<DoubleValue> LeftSideParameter {
49      get { return (ILookupParameter<DoubleValue>)Parameters["LeftSide"]; }
50    }
51    public ILookupParameter<ItemArray<DoubleValue>> RightSideParameter {
52      get { return (ILookupParameter<ItemArray<DoubleValue>>)Parameters["RightSide"]; }
53    }
54    public ILookupParameter<BoolValue> ResultParameter {
55      get { return (ILookupParameter<BoolValue>)Parameters["Result"]; }
56    }
57    public ValueLookupParameter<DoubleValue> ComparisonFactorParameter {
58      get { return (ValueLookupParameter<DoubleValue>)Parameters["ComparisonFactor"]; }
59    }
60    public ValueLookupParameter<DoubleValue> DiversityComparisonFactorParameter {
61      get { return (ValueLookupParameter<DoubleValue>)Parameters["DiversityComparisonFactor"]; }
62    }
63    private ValueLookupParameter<DoubleValue> ComparisonFactorLowerBoundParameter {
64      get { return (ValueLookupParameter<DoubleValue>)Parameters["DiversityComparisonFactorLowerBound"]; }
65    }
66    private ValueLookupParameter<DoubleValue> ComparisonFactorUpperBoundParameter {
67      get { return (ValueLookupParameter<DoubleValue>)Parameters["DiversityComparisonFactorUpperBound"]; }
68    }
69    public IConstrainedValueParameter<IDiscreteDoubleValueModifier> ComparisonFactorModifierParameter {
70      get { return (IConstrainedValueParameter<IDiscreteDoubleValueModifier>)Parameters["ComparisonFactorModifier"]; }
71    }
72    public ValueLookupParameter<ResultCollection> ResultsParameter {
73      get { return (ValueLookupParameter<ResultCollection>)Parameters["Results"]; }
74    }
75    public ILookupParameter<IntValue> GenerationsParameter {
76      get { return (LookupParameter<IntValue>)Parameters["Generations"]; }
77    }
78    public ValueParameter<BoolValue> EnableDivCriteriaParameter {
79      get { return (ValueParameter<BoolValue>)Parameters["EnableDivCriteria"]; }
80    }
81    public ValueParameter<BoolValue> EnableQualityCriteriaParameter {
82      get { return (ValueParameter<BoolValue>)Parameters["EnableQualityCriteria"]; }
83    }
84
85    private const string spDetailsParameterName = "SPDetails";
86    private const string divDataRowName = "DiversitySuccessCount";
87    private const string qualityDataRowName = "QualitySuccessCount";
88    private const string divFailDataRowName = "DiversityFailCount";
89    private const string qualityFailDataRowName = "QualityFailCount";
90    private const string overallCountDataRowName = "OverallCount";
91    private const string successCountDataRowName = "SuccessCount";
92    private const string unwantedMutationsDataRowName = "UnwantedMutations";
93
94    [Storable]
95    private int currentGeneration;
96    [Storable]
97    private int divCount;
98    [Storable]
99    private int qualityCount;
100    [Storable]
101    private int badQualityCount;
102    [Storable]
103    private int badDivCount;
104    [Storable]
105    private int overallCount;
106    [Storable]
107    private int successCount;
108    [Storable]
109    private double umRatio;
110
111    [StorableConstructor]
112    protected UnwantedMutationsComparator(bool deserializing) : base(deserializing) { }
113    protected UnwantedMutationsComparator(UnwantedMutationsComparator original, Cloner cloner)
114      : base(original, cloner) {
115      SimilarityCalculator = cloner.Clone(original.SimilarityCalculator);
116      currentGeneration = original.currentGeneration;
117      divCount = original.divCount;
118      qualityCount = original.qualityCount;
119      overallCount = original.overallCount;
120      successCount = original.successCount;
121      badDivCount = original.badDivCount;
122      badQualityCount = original.badQualityCount;
123      umRatio = original.umRatio;
124    }
125    public UnwantedMutationsComparator()
126      : base() {
127      Parameters.Add(new ValueLookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem, false otherwise"));
128      Parameters.Add(new LookupParameter<DoubleValue>("LeftSide", "The quality of the child."));
129      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("RightSide", "The qualities of the parents."));
130      Parameters.Add(new LookupParameter<BoolValue>("Result", "The result of the comparison: True means Quality is better, False means it is worse than parents."));
131      Parameters.Add(new ValueLookupParameter<DoubleValue>("ComparisonFactor", "Determines if the quality should be compared to the better parent (1.0), to the worse (0.0) or to any linearly interpolated value between them."));
132      Parameters.Add(new ValueLookupParameter<DoubleValue>("DiversityComparisonFactor", "Determines if the quality should be compared to the better parent (1.0), to the worse (0.0) or to any linearly interpolated value between them.", new DoubleValue(0.0)));
133      Parameters.Add(new ValueLookupParameter<DoubleValue>("DiversityComparisonFactorLowerBound", "The lower bound of the comparison factor (start).", new DoubleValue(0.7)));
134      Parameters.Add(new ValueLookupParameter<DoubleValue>("DiversityComparisonFactorUpperBound", "The upper bound of the comparison factor (end).", new DoubleValue(1.0)));
135      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("ComparisonFactorModifier", "The operator used to modify the comparison factor.", new ItemSet<IDiscreteDoubleValueModifier>(new IDiscreteDoubleValueModifier[] { new LinearDiscreteDoubleValueModifier() }), new LinearDiscreteDoubleValueModifier()));
136      Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the population diversity analysis results should be stored."));
137      Parameters.Add(new LookupParameter<IntValue>("Generations", "The current number of generations."));
138      Parameters.Add(new ValueParameter<BoolValue>("EnableDivCriteria", "Use diversity as additional offspring selection criteria.", new BoolValue(true)));
139      Parameters.Add(new ValueParameter<BoolValue>("EnableQualityCriteria", "Use quality as additional offspring selection criteria.", new BoolValue(false)));
140      Parameters.Add(new ValueLookupParameter<ISolutionSimilarityCalculator>("SimilarityCalculator", "The similarity calculator that should be used to calculate solution similarity."));
141
142      foreach (IDiscreteDoubleValueModifier modifier in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
143        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
144      IDiscreteDoubleValueModifier linearModifier = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("LinearDiscreteDoubleValueModifier"));
145      if (linearModifier != null) ComparisonFactorModifierParameter.Value = linearModifier;
146      ParameterizeComparisonFactorModifiers();
147    }
148
149    public override IDeepCloneable Clone(Cloner cloner) {
150      return new UnwantedMutationsComparator(this, cloner);
151    }
152
153    [StorableHook(HookType.AfterDeserialization)]
154    private void AfterDeserialization() {
155      // BackwardsCompatibility3.3
156      #region Backwards compatible code, remove with 3.4
157      if (!Parameters.ContainsKey("SimilarityCalculator"))
158        Parameters.Add(new ValueLookupParameter<ISolutionSimilarityCalculator>("SimilarityCalculator", "The similarity calculator that should be used to calculate solution similarity."));
159      #endregion
160    }
161
162    private void ParameterizeComparisonFactorModifiers() {
163      //TODO: does not work if Generations parameter names are changed
164      foreach (IDiscreteDoubleValueModifier modifier in ComparisonFactorModifierParameter.ValidValues) {
165        modifier.IndexParameter.ActualName = "Generations";
166        modifier.EndIndexParameter.ActualName = "MaximumGenerations";
167        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
168        modifier.StartIndexParameter.Value = new IntValue(0);
169        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
170        modifier.ValueParameter.ActualName = "DiversityComparisonFactor";
171      }
172    }
173
174    public override IOperation Apply() {
175      ItemArray<DoubleValue> rightQualities = RightSideParameter.ActualValue;
176      if (rightQualities.Length < 1) throw new InvalidOperationException(Name + ": No subscopes found.");
177      double compFact = ComparisonFactorParameter.ActualValue.Value;
178      double diversityComFact = DiversityComparisonFactorParameter.ActualValue.Value;
179      bool maximization = MaximizationParameter.ActualValue.Value;
180      double leftQuality = LeftSideParameter.ActualValue.Value;
181      double threshold = 0;
182
183      DataTable spDetailsTable;
184      if (ResultsParameter.ActualValue.ContainsKey(spDetailsParameterName)) {
185        spDetailsTable = (DataTable)ResultsParameter.ActualValue[spDetailsParameterName].Value;
186      } else {
187        spDetailsTable = new DataTable(spDetailsParameterName);
188        spDetailsTable.Rows.Add(new DataRow(divDataRowName));
189        spDetailsTable.Rows.Add(new DataRow(qualityDataRowName));
190        spDetailsTable.Rows.Add(new DataRow(overallCountDataRowName));
191        spDetailsTable.Rows.Add(new DataRow(successCountDataRowName));
192        spDetailsTable.Rows.Add(new DataRow(divFailDataRowName));
193        spDetailsTable.Rows.Add(new DataRow(qualityFailDataRowName));
194        spDetailsTable.Rows.Add(new DataRow(unwantedMutationsDataRowName));
195        ResultsParameter.ActualValue.Add(new Result(spDetailsParameterName, spDetailsTable));
196      }
197
198      if (GenerationsParameter.ActualValue.Value != currentGeneration) {
199        spDetailsTable.Rows[divDataRowName].Values.Add(divCount);
200        divCount = 0;
201        spDetailsTable.Rows[qualityDataRowName].Values.Add(qualityCount);
202        qualityCount = 0;
203        spDetailsTable.Rows[overallCountDataRowName].Values.Add(overallCount);
204        spDetailsTable.Rows[successCountDataRowName].Values.Add(successCount);
205        successCount = 0;
206        spDetailsTable.Rows[qualityFailDataRowName].Values.Add(badQualityCount);
207        badQualityCount = 0;
208        spDetailsTable.Rows[divFailDataRowName].Values.Add(badDivCount);
209        badDivCount = 0;
210        if (overallCount != 0) {
211          spDetailsTable.Rows[unwantedMutationsDataRowName].Values.Add(umRatio / (double)overallCount);
212        }
213        umRatio = 0.0;
214        overallCount = 0;
215        currentGeneration = GenerationsParameter.ActualValue.Value;
216      }
217
218      string solutionVariableName = ((ISingleObjectiveSolutionSimilarityCalculator)SimilarityCalculatorParameter.ActualValue).SolutionVariableName;
219      double resultVal = AnalyzeUnwantedMutations(ExecutionContext.Scope.SubScopes[0],
220        ExecutionContext.Scope.SubScopes[1], ExecutionContext.Scope, solutionVariableName);
221
222      bool resultDiversity = resultVal < diversityComFact;
223      umRatio += resultVal;
224
225      double minQuality = Math.Min(rightQualities[0].Value, rightQualities[1].Value);
226      double maxQuality = Math.Max(rightQualities[0].Value, rightQualities[1].Value);
227      if (maximization)
228        threshold = minQuality + (maxQuality - minQuality) * compFact;
229      else
230        threshold = maxQuality - (maxQuality - minQuality) * compFact;
231
232      bool result = maximization && leftQuality > threshold || !maximization && leftQuality < threshold;
233
234      //collect statistics
235      if (result) {
236        qualityCount++;
237      } else {
238        badQualityCount++;
239      }
240      if (resultDiversity) {
241        divCount++;
242      } else {
243        badDivCount++;
244      }
245      if (result && resultDiversity) {
246        successCount++;
247      }
248      overallCount++;
249
250      if (EnableDivCriteriaParameter.Value.Value && !EnableQualityCriteriaParameter.Value.Value) {
251        result = resultDiversity;
252      }
253      //use diveristiy criteria or not
254      if (EnableDivCriteriaParameter.Value.Value && EnableQualityCriteriaParameter.Value.Value) {
255        result = result && resultDiversity;
256      }
257
258      BoolValue resultValue = ResultParameter.ActualValue;
259      if (resultValue == null) {
260        ResultParameter.ActualValue = new BoolValue(result);
261      } else {
262        resultValue.Value = result;
263      }
264
265      //like the placeholder, though we create child operations
266      OperationCollection next = new OperationCollection(base.Apply());
267      IOperator op = ComparisonFactorModifierParameter.Value;
268      if (op != null)
269        next.Insert(0, ExecutionContext.CreateChildOperation(op));
270      return next;
271    }
272
273    public double AnalyzeUnwantedMutations(IScope parent1, IScope parent2, IScope child, string solutionVariableName) {
274      Permutation p1 = parent1.Variables[solutionVariableName].Value as Permutation;
275      Permutation p2 = parent2.Variables[solutionVariableName].Value as Permutation;
276      Permutation c = child.Variables[solutionVariableName].Value as Permutation;
277
278      return AnalyzeUnwantedMutations(p1, p2, c);
279    }
280
281    private double AnalyzeUnwantedMutations(Permutation parent1, Permutation parent2, Permutation child) {
282      int cnt = 0;
283      int[] edgesP1 = CalculateEdgesVector(parent1);
284      int[] edgesP2 = CalculateEdgesVector(parent2);
285      int[] edgesC = CalculateEdgesVector(child);
286
287      for (int i = 0; i < edgesP1.Length; i++) {
288        if (edgesC[i] != edgesP1[i] &&
289            edgesC[i] != edgesP2[i] &&
290            edgesP1[edgesC[i]] != i &&
291            edgesP2[edgesC[i]] != i) {
292          cnt += 1;
293        }
294      }
295
296      //reverse so that it matches the other diversity charts
297      return 1.0 - (((double)cnt) / parent1.Length);
298    }
299
300    //copied from PermutationEqualityComparer
301    private int[] CalculateEdgesVector(Permutation permutation) {
302      // transform path representation into adjacency representation
303      int[] edgesVector = new int[permutation.Length];
304      for (int i = 0; i < permutation.Length - 1; i++)
305        edgesVector[permutation[i]] = permutation[i + 1];
306      edgesVector[permutation[permutation.Length - 1]] = permutation[0];
307      return edgesVector;
308    }
309  }
310}
Note: See TracBrowser for help on using the repository browser.