Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12064 was 11884, checked in by ascheibe, 10 years ago

#2267 added another comparator

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