Free cookie consent management tool by TermsFeed Policy Generator

source: branches/VOSGA/HeuristicLab.Algorithms.VOffspringSelectionGeneticAlgorithm/Comparators/WeightedParentsDiversityComparator.cs @ 12062

Last change on this file since 12062 was 11844, checked in by ascheibe, 10 years ago

#2267 moved comparators into a own folder

File size: 13.7 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.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34
35namespace HeuristicLab.Algorithms.VOffspringSelectionGeneticAlgorithm {
36  [Item("WeightedParentsDiversityComparator", "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.")]
37  [StorableClass]
38  public class WeightedParentsDiversityComparator : SingleSuccessorOperator, ISubScopesQualityComparatorOperator, ISimilarityBasedOperator {
39    [Storable]
40    public ISolutionSimilarityCalculator SimilarityCalculator { get; set; }
41    public IValueLookupParameter<BoolValue> MaximizationParameter {
42      get { return (IValueLookupParameter<BoolValue>)Parameters["Maximization"]; }
43    }
44    public ILookupParameter<DoubleValue> LeftSideParameter {
45      get { return (ILookupParameter<DoubleValue>)Parameters["LeftSide"]; }
46    }
47    public ILookupParameter<ItemArray<DoubleValue>> RightSideParameter {
48      get { return (ILookupParameter<ItemArray<DoubleValue>>)Parameters["RightSide"]; }
49    }
50    public ILookupParameter<BoolValue> ResultParameter {
51      get { return (ILookupParameter<BoolValue>)Parameters["Result"]; }
52    }
53    public ValueLookupParameter<DoubleValue> ComparisonFactorParameter {
54      get { return (ValueLookupParameter<DoubleValue>)Parameters["ComparisonFactor"]; }
55    }
56    public ValueLookupParameter<DoubleValue> DiversityComparisonFactorParameter {
57      get { return (ValueLookupParameter<DoubleValue>)Parameters["DiversityComparisonFactor"]; }
58    }
59    private ValueLookupParameter<DoubleValue> ComparisonFactorLowerBoundParameter {
60      get { return (ValueLookupParameter<DoubleValue>)Parameters["DiversityComparisonFactorLowerBound"]; }
61    }
62    private ValueLookupParameter<DoubleValue> ComparisonFactorUpperBoundParameter {
63      get { return (ValueLookupParameter<DoubleValue>)Parameters["DiversityComparisonFactorUpperBound"]; }
64    }
65    public IConstrainedValueParameter<IDiscreteDoubleValueModifier> ComparisonFactorModifierParameter {
66      get { return (IConstrainedValueParameter<IDiscreteDoubleValueModifier>)Parameters["ComparisonFactorModifier"]; }
67    }
68    public ValueLookupParameter<ResultCollection> ResultsParameter {
69      get { return (ValueLookupParameter<ResultCollection>)Parameters["Results"]; }
70    }
71    public ILookupParameter<IntValue> GenerationsParameter {
72      get { return (LookupParameter<IntValue>)Parameters["Generations"]; }
73    }
74    public ValueParameter<BoolValue> EnableDivCriteriaParameter {
75      get { return (ValueParameter<BoolValue>)Parameters["EnableDivCriteria"]; }
76    }
77
78    private const string spDetailsParameterName = "SPDetails";
79    private const string divDataRowName = "DiversitySuccessCount";
80    private const string qualityDataRowName = "QualitySuccessCount";
81    private const string divFailDataRowName = "DiversityFailCount";
82    private const string qualityFailDataRowName = "QualityFailCount";
83    private const string overallCountDataRowName = "OverallCount";
84    private const string successCountDataRowName = "SuccessCount";
85
86    [Storable]
87    private int currentGeneration;
88    [Storable]
89    private int divCount;
90    [Storable]
91    private int qualityCount;
92    [Storable]
93    private int badQualityCount;
94    [Storable]
95    private int badDivCount;
96    [Storable]
97    private int overallCount;
98    [Storable]
99    private int successCount;
100
101    [StorableConstructor]
102    protected WeightedParentsDiversityComparator(bool deserializing) : base(deserializing) { }
103    protected WeightedParentsDiversityComparator(WeightedParentsDiversityComparator original, Cloner cloner)
104      : base(original, cloner) {
105      SimilarityCalculator = cloner.Clone(original.SimilarityCalculator);
106      currentGeneration = original.currentGeneration;
107      divCount = original.divCount;
108      qualityCount = original.qualityCount;
109      overallCount = original.overallCount;
110      successCount = original.successCount;
111      badDivCount = original.badDivCount;
112      badQualityCount = original.badQualityCount;
113    }
114    public WeightedParentsDiversityComparator()
115      : base() {
116      Parameters.Add(new ValueLookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem, false otherwise"));
117      Parameters.Add(new LookupParameter<DoubleValue>("LeftSide", "The quality of the child."));
118      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("RightSide", "The qualities of the parents."));
119      Parameters.Add(new LookupParameter<BoolValue>("Result", "The result of the comparison: True means Quality is better, False means it is worse than parents."));
120      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."));
121      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)));
122      Parameters.Add(new ValueLookupParameter<DoubleValue>("DiversityComparisonFactorLowerBound", "The lower bound of the comparison factor (start).", new DoubleValue(0.5)));
123      Parameters.Add(new ValueLookupParameter<DoubleValue>("DiversityComparisonFactorUpperBound", "The upper bound of the comparison factor (end).", new DoubleValue(1.0)));
124      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("ComparisonFactorModifier", "The operator used to modify the comparison factor.", new ItemSet<IDiscreteDoubleValueModifier>(new IDiscreteDoubleValueModifier[] { new LinearDiscreteDoubleValueModifier() }), new LinearDiscreteDoubleValueModifier()));
125      Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the population diversity analysis results should be stored."));
126      Parameters.Add(new LookupParameter<IntValue>("Generations", "The current number of generations."));
127      Parameters.Add(new ValueParameter<BoolValue>("EnableDivCriteria", "Use diversity as additional offspring selection criteria.", new BoolValue(true)));
128
129      foreach (IDiscreteDoubleValueModifier modifier in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
130        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
131      IDiscreteDoubleValueModifier linearModifier = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("LinearDiscreteDoubleValueModifier"));
132      if (linearModifier != null) ComparisonFactorModifierParameter.Value = linearModifier;
133      ParameterizeComparisonFactorModifiers();
134    }
135
136    public override IDeepCloneable Clone(Cloner cloner) {
137      return new WeightedParentsDiversityComparator(this, cloner);
138    }
139
140    [StorableHook(HookType.AfterDeserialization)]
141    private void AfterDeserialization() {
142      if (!Parameters.ContainsKey("Generations"))
143        Parameters.Add(new LookupParameter<IntValue>("Generations", "The current number of generations."));
144      if (!Parameters.ContainsKey("Results"))
145        Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the population diversity analysis results should be stored."));
146      if (!Parameters.ContainsKey("EnableDivCriteria"))
147        Parameters.Add(new ValueParameter<BoolValue>("EnableDivCriteria", "Use diversity as additional offspring selection criteria.", new BoolValue(true)));
148    }
149
150    private void ParameterizeComparisonFactorModifiers() {
151      //TODO: does not work if Generations parameter names are changed
152      foreach (IDiscreteDoubleValueModifier modifier in ComparisonFactorModifierParameter.ValidValues) {
153        modifier.IndexParameter.ActualName = "Generations";
154        modifier.EndIndexParameter.ActualName = "MaximumGenerations";
155        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
156        modifier.StartIndexParameter.Value = new IntValue(0);
157        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
158        modifier.ValueParameter.ActualName = "DiversityComparisonFactor";
159      }
160    }
161
162    public override IOperation Apply() {
163      ItemArray<DoubleValue> rightQualities = RightSideParameter.ActualValue;
164      if (rightQualities.Length < 1) throw new InvalidOperationException(Name + ": No subscopes found.");
165      double compFact = ComparisonFactorParameter.ActualValue.Value;
166      double diversityComFact = DiversityComparisonFactorParameter.ActualValue.Value;
167      bool maximization = MaximizationParameter.ActualValue.Value;
168      double leftQuality = LeftSideParameter.ActualValue.Value;
169      bool resultDiversity;
170      double threshold = 0;
171
172      DataTable spDetailsTable;
173      if (ResultsParameter.ActualValue.ContainsKey(spDetailsParameterName)) {
174        spDetailsTable = (DataTable)ResultsParameter.ActualValue[spDetailsParameterName].Value;
175      } else {
176        spDetailsTable = new DataTable(spDetailsParameterName);
177        spDetailsTable.Rows.Add(new DataRow(divDataRowName));
178        spDetailsTable.Rows.Add(new DataRow(qualityDataRowName));
179        spDetailsTable.Rows.Add(new DataRow(overallCountDataRowName));
180        spDetailsTable.Rows.Add(new DataRow(successCountDataRowName));
181        spDetailsTable.Rows.Add(new DataRow(divFailDataRowName));
182        spDetailsTable.Rows.Add(new DataRow(qualityFailDataRowName));
183        ResultsParameter.ActualValue.Add(new Result(spDetailsParameterName, spDetailsTable));
184      }
185
186      if (GenerationsParameter.ActualValue.Value != currentGeneration) {
187        spDetailsTable.Rows[divDataRowName].Values.Add(divCount);
188        divCount = 0;
189        spDetailsTable.Rows[qualityDataRowName].Values.Add(qualityCount);
190        qualityCount = 0;
191        spDetailsTable.Rows[overallCountDataRowName].Values.Add(overallCount);
192        overallCount = 0;
193        spDetailsTable.Rows[successCountDataRowName].Values.Add(successCount);
194        successCount = 0;
195        spDetailsTable.Rows[qualityFailDataRowName].Values.Add(badQualityCount);
196        badQualityCount = 0;
197        spDetailsTable.Rows[divFailDataRowName].Values.Add(badDivCount);
198        badDivCount = 0;
199        currentGeneration = GenerationsParameter.ActualValue.Value;
200      }
201
202      #region Calculate threshold
203      if (rightQualities.Length == 2) {
204        var sim1 = SimilarityCalculator.CalculateSolutionSimilarity(ExecutionContext.Scope, ExecutionContext.Scope.SubScopes[0]);
205        var sim2 = SimilarityCalculator.CalculateSolutionSimilarity(ExecutionContext.Scope, ExecutionContext.Scope.SubScopes[1]);
206        var simAvg = (sim1 + sim2) / 2.0;
207
208        //TODO: try out different things
209        //resultDiversity = simAvg < diversityComFact;
210        resultDiversity = sim1 < diversityComFact || sim2 < diversityComFact;
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      } else {
219        throw new NotImplementedException("Only 2 parents are supported.");
220      }
221      #endregion
222
223      bool result = maximization && leftQuality > threshold || !maximization && leftQuality < threshold;
224
225      //collect statistics
226      if (result) {
227        qualityCount++;
228      } else {
229        badQualityCount++;
230      }
231      if (resultDiversity) {
232        divCount++;
233      } else {
234        badDivCount++;
235      }
236      if (result && resultDiversity) {
237        successCount++;
238      }
239      overallCount++;
240
241      //use diveristiy criteria or not
242      if (EnableDivCriteriaParameter.Value.Value) {
243        result = result && resultDiversity;
244      }
245
246      BoolValue resultValue = ResultParameter.ActualValue;
247      if (resultValue == null) {
248        ResultParameter.ActualValue = new BoolValue(result);
249      } else {
250        resultValue.Value = result;
251      }
252
253      //like the placeholder, though we create child operations
254      OperationCollection next = new OperationCollection(base.Apply());
255      IOperator op = ComparisonFactorModifierParameter.Value;
256      if (op != null)
257        next.Insert(0, ExecutionContext.CreateChildOperation(op));
258      return next;
259    }
260  }
261}
Note: See TracBrowser for help on using the repository browser.