Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2267 adapted branch to changes from #2332

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