Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11824 was 11824, checked in by ascheibe, 8 years ago

#2267 added switch to turn off diversity as selection criteria but still generate the analysis chart

File size: 12.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.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 overallCountDataRowName = "OverallCount";
82    private const string successCountDataRowName = "SuccessCount";
83
84    [Storable]
85    private int currentGeneration;
86    [Storable]
87    private int divCount;
88    [Storable]
89    private int qualityCount;
90    [Storable]
91    private int overallCount;
92    [Storable]
93    private int successCount;
94
95    [StorableConstructor]
96    protected WeightedParentsDiversityComparator(bool deserializing) : base(deserializing) { }
97    protected WeightedParentsDiversityComparator(WeightedParentsDiversityComparator original, Cloner cloner)
98      : base(original, cloner) {
99      SimilarityCalculator = cloner.Clone(original.SimilarityCalculator);
100      currentGeneration = original.currentGeneration;
101      divCount = original.divCount;
102      qualityCount = original.qualityCount;
103      overallCount = original.overallCount;
104      successCount = original.successCount;
105    }
106    public WeightedParentsDiversityComparator()
107      : base() {
108      Parameters.Add(new ValueLookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem, false otherwise"));
109      Parameters.Add(new LookupParameter<DoubleValue>("LeftSide", "The quality of the child."));
110      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("RightSide", "The qualities of the parents."));
111      Parameters.Add(new LookupParameter<BoolValue>("Result", "The result of the comparison: True means Quality is better, False means it is worse than parents."));
112      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."));
113      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)));
114      Parameters.Add(new ValueLookupParameter<DoubleValue>("DiversityComparisonFactorLowerBound", "The lower bound of the comparison factor (start).", new DoubleValue(0.5)));
115      Parameters.Add(new ValueLookupParameter<DoubleValue>("DiversityComparisonFactorUpperBound", "The upper bound of the comparison factor (end).", new DoubleValue(1.0)));
116      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("ComparisonFactorModifier", "The operator used to modify the comparison factor.", new ItemSet<IDiscreteDoubleValueModifier>(new IDiscreteDoubleValueModifier[] { new LinearDiscreteDoubleValueModifier() }), new LinearDiscreteDoubleValueModifier()));
117      Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the population diversity analysis results should be stored."));
118      Parameters.Add(new LookupParameter<IntValue>("Generations", "The current number of generations."));
119      Parameters.Add(new ValueParameter<BoolValue>("EnableDivCriteria", "Use diversity as additional offspring selection criteria.", new BoolValue(true)));
120
121      foreach (IDiscreteDoubleValueModifier modifier in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
122        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
123      IDiscreteDoubleValueModifier linearModifier = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("LinearDiscreteDoubleValueModifier"));
124      if (linearModifier != null) ComparisonFactorModifierParameter.Value = linearModifier;
125      ParameterizeComparisonFactorModifiers();
126    }
127
128    public override IDeepCloneable Clone(Cloner cloner) {
129      return new WeightedParentsDiversityComparator(this, cloner);
130    }
131
132    [StorableHook(HookType.AfterDeserialization)]
133    private void AfterDeserialization() {
134      if (!Parameters.ContainsKey("Generations"))
135        Parameters.Add(new LookupParameter<IntValue>("Generations", "The current number of generations."));
136      if (!Parameters.ContainsKey("Results"))
137        Parameters.Add(new ValueLookupParameter<ResultCollection>("Results", "The result collection where the population diversity analysis results should be stored."));
138      if (!Parameters.ContainsKey("EnableDivCriteria"))
139        Parameters.Add(new ValueParameter<BoolValue>("EnableDivCriteria", "Use diversity as additional offspring selection criteria.", new BoolValue(true)));
140    }
141
142    private void ParameterizeComparisonFactorModifiers() {
143      //TODO: does not work if Generations parameter names are changed
144      foreach (IDiscreteDoubleValueModifier modifier in ComparisonFactorModifierParameter.ValidValues) {
145        modifier.IndexParameter.ActualName = "Generations";
146        modifier.EndIndexParameter.ActualName = "MaximumGenerations";
147        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
148        modifier.StartIndexParameter.Value = new IntValue(0);
149        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
150        modifier.ValueParameter.ActualName = "DiversityComparisonFactor";
151      }
152    }
153
154    public override IOperation Apply() {
155      ItemArray<DoubleValue> rightQualities = RightSideParameter.ActualValue;
156      if (rightQualities.Length < 1) throw new InvalidOperationException(Name + ": No subscopes found.");
157      double compFact = ComparisonFactorParameter.ActualValue.Value;
158      double diversityComFact = DiversityComparisonFactorParameter.ActualValue.Value;
159      bool maximization = MaximizationParameter.ActualValue.Value;
160      double leftQuality = LeftSideParameter.ActualValue.Value;
161      bool resultDiversity;
162      double threshold = 0;
163
164      DataTable spDetailsTable;
165      if (ResultsParameter.ActualValue.ContainsKey(spDetailsParameterName)) {
166        spDetailsTable = (DataTable)ResultsParameter.ActualValue[spDetailsParameterName].Value;
167      } else {
168        spDetailsTable = new DataTable(spDetailsParameterName);
169        spDetailsTable.Rows.Add(new DataRow(divDataRowName));
170        spDetailsTable.Rows.Add(new DataRow(qualityDataRowName));
171        spDetailsTable.Rows.Add(new DataRow(overallCountDataRowName));
172        spDetailsTable.Rows.Add(new DataRow(successCountDataRowName));
173        ResultsParameter.ActualValue.Add(new Result(spDetailsParameterName, spDetailsTable));
174      }
175
176      if (GenerationsParameter.ActualValue.Value != currentGeneration) {
177        spDetailsTable.Rows[divDataRowName].Values.Add(divCount);
178        divCount = 0;
179        spDetailsTable.Rows[qualityDataRowName].Values.Add(qualityCount);
180        qualityCount = 0;
181        spDetailsTable.Rows[overallCountDataRowName].Values.Add(overallCount);
182        overallCount = 0;
183        spDetailsTable.Rows[successCountDataRowName].Values.Add(successCount);
184        successCount = 0;
185        currentGeneration = GenerationsParameter.ActualValue.Value;
186      }
187
188      #region Calculate threshold
189      if (rightQualities.Length == 2) {
190        var sim1 = SimilarityCalculator.CalculateSolutionSimilarity(ExecutionContext.Scope, ExecutionContext.Scope.SubScopes[0]);
191        var sim2 = SimilarityCalculator.CalculateSolutionSimilarity(ExecutionContext.Scope, ExecutionContext.Scope.SubScopes[1]);
192        var simAvg = (sim1 + sim2) / 2.0;
193
194        //TODO: try out different things
195        //resultDiversity = simAvg < diversityComFact;
196        resultDiversity = sim1 < diversityComFact || sim2 < diversityComFact;
197
198        double minQuality = Math.Min(rightQualities[0].Value, rightQualities[1].Value);
199        double maxQuality = Math.Max(rightQualities[0].Value, rightQualities[1].Value);
200        if (maximization)
201          threshold = minQuality + (maxQuality - minQuality) * compFact;
202        else
203          threshold = maxQuality - (maxQuality - minQuality) * compFact;
204      } else {
205        throw new NotImplementedException("Only 2 parents are supported.");
206      }
207      #endregion
208
209      bool result = maximization && leftQuality > threshold || !maximization && leftQuality < threshold;
210
211      //collect statistics
212      if (result) {
213        qualityCount++;
214      }
215      if (resultDiversity) {
216        divCount++;
217      }
218      if (result && resultDiversity) {
219        successCount++;
220      }
221      overallCount++;
222
223      //use diveristiy criteria or not
224      if (EnableDivCriteriaParameter.Value.Value) {
225        result = result && resultDiversity;
226      }
227
228      BoolValue resultValue = ResultParameter.ActualValue;
229      if (resultValue == null) {
230        ResultParameter.ActualValue = new BoolValue(result);
231      } else {
232        resultValue.Value = result;
233      }
234
235      //like the placeholder, though we create child operations
236      OperationCollection next = new OperationCollection(base.Apply());
237      IOperator op = ComparisonFactorModifierParameter.Value;
238      if (op != null)
239        next.Insert(0, ExecutionContext.CreateChildOperation(op));
240      return next;
241    }
242  }
243}
Note: See TracBrowser for help on using the repository browser.