Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2267 added analysis functionality to diversity comparer

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