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

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

#2267 fixed cloning bug

File size: 9.0 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.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using HeuristicLab.Operators;
28using HeuristicLab.Optimization;
29using HeuristicLab.Optimization.Operators;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.PluginInfrastructure;
33
34namespace HeuristicLab.Algorithms.VOffspringSelectionGeneticAlgorithm {
35  [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.")]
36  [StorableClass]
37  public class WeightedParentsDiversityComparator : SingleSuccessorOperator, ISubScopesQualityComparatorOperator, ISimilarityBasedOperator {
38    [Storable]
39    public ISolutionSimilarityCalculator SimilarityCalculator { get; set; }
40    public IValueLookupParameter<BoolValue> MaximizationParameter {
41      get { return (IValueLookupParameter<BoolValue>)Parameters["Maximization"]; }
42    }
43    public ILookupParameter<DoubleValue> LeftSideParameter {
44      get { return (ILookupParameter<DoubleValue>)Parameters["LeftSide"]; }
45    }
46    public ILookupParameter<ItemArray<DoubleValue>> RightSideParameter {
47      get { return (ILookupParameter<ItemArray<DoubleValue>>)Parameters["RightSide"]; }
48    }
49    public ILookupParameter<BoolValue> ResultParameter {
50      get { return (ILookupParameter<BoolValue>)Parameters["Result"]; }
51    }
52    public ValueLookupParameter<DoubleValue> ComparisonFactorParameter {
53      get { return (ValueLookupParameter<DoubleValue>)Parameters["ComparisonFactor"]; }
54    }
55    public ValueLookupParameter<DoubleValue> DiversityComparisonFactorParameter {
56      get { return (ValueLookupParameter<DoubleValue>)Parameters["DiversityComparisonFactor"]; }
57    }
58    private ValueLookupParameter<DoubleValue> ComparisonFactorLowerBoundParameter {
59      get { return (ValueLookupParameter<DoubleValue>)Parameters["DiversityComparisonFactorLowerBound"]; }
60    }
61    private ValueLookupParameter<DoubleValue> ComparisonFactorUpperBoundParameter {
62      get { return (ValueLookupParameter<DoubleValue>)Parameters["DiversityComparisonFactorUpperBound"]; }
63    }
64    public IConstrainedValueParameter<IDiscreteDoubleValueModifier> ComparisonFactorModifierParameter {
65      get { return (IConstrainedValueParameter<IDiscreteDoubleValueModifier>)Parameters["ComparisonFactorModifier"]; }
66    }
67
68    [StorableConstructor]
69    protected WeightedParentsDiversityComparator(bool deserializing) : base(deserializing) { }
70    protected WeightedParentsDiversityComparator(WeightedParentsDiversityComparator original, Cloner cloner)
71      : base(original, cloner) {
72      SimilarityCalculator = cloner.Clone(original.SimilarityCalculator);
73    }
74    public WeightedParentsDiversityComparator()
75      : base() {
76      Parameters.Add(new ValueLookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem, false otherwise"));
77      Parameters.Add(new LookupParameter<DoubleValue>("LeftSide", "The quality of the child."));
78      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("RightSide", "The qualities of the parents."));
79      Parameters.Add(new LookupParameter<BoolValue>("Result", "The result of the comparison: True means Quality is better, False means it is worse than parents."));
80      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."));
81      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)));
82      Parameters.Add(new ValueLookupParameter<DoubleValue>("DiversityComparisonFactorLowerBound", "The lower bound of the comparison factor (start).", new DoubleValue(0.5)));
83      Parameters.Add(new ValueLookupParameter<DoubleValue>("DiversityComparisonFactorUpperBound", "The upper bound of the comparison factor (end).", new DoubleValue(1.0)));
84      Parameters.Add(new OptionalConstrainedValueParameter<IDiscreteDoubleValueModifier>("ComparisonFactorModifier", "The operator used to modify the comparison factor.", new ItemSet<IDiscreteDoubleValueModifier>(new IDiscreteDoubleValueModifier[] { new LinearDiscreteDoubleValueModifier() }), new LinearDiscreteDoubleValueModifier()));
85
86      foreach (IDiscreteDoubleValueModifier modifier in ApplicationManager.Manager.GetInstances<IDiscreteDoubleValueModifier>().OrderBy(x => x.Name))
87        ComparisonFactorModifierParameter.ValidValues.Add(modifier);
88      IDiscreteDoubleValueModifier linearModifier = ComparisonFactorModifierParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("LinearDiscreteDoubleValueModifier"));
89      if (linearModifier != null) ComparisonFactorModifierParameter.Value = linearModifier;
90      ParameterizeComparisonFactorModifiers();
91    }
92
93    public override IDeepCloneable Clone(Cloner cloner) {
94      return new WeightedParentsDiversityComparator(this, cloner);
95    }
96
97    private void ParameterizeComparisonFactorModifiers() {
98      //TODO: does not work if Generations parameter names are changed
99      foreach (IDiscreteDoubleValueModifier modifier in ComparisonFactorModifierParameter.ValidValues) {
100        modifier.IndexParameter.ActualName = "Generations";
101        modifier.EndIndexParameter.ActualName = "MaximumGenerations";
102        modifier.EndValueParameter.ActualName = ComparisonFactorUpperBoundParameter.Name;
103        modifier.StartIndexParameter.Value = new IntValue(0);
104        modifier.StartValueParameter.ActualName = ComparisonFactorLowerBoundParameter.Name;
105        modifier.ValueParameter.ActualName = "DiversityComparisonFactor";
106      }
107    }
108
109    public override IOperation Apply() {
110      ItemArray<DoubleValue> rightQualities = RightSideParameter.ActualValue;
111      if (rightQualities.Length < 1) throw new InvalidOperationException(Name + ": No subscopes found.");
112      double compFact = ComparisonFactorParameter.ActualValue.Value;
113      double diversityComFact = DiversityComparisonFactorParameter.ActualValue.Value;
114      bool maximization = MaximizationParameter.ActualValue.Value;
115      double leftQuality = LeftSideParameter.ActualValue.Value;
116      bool resultDiversity;
117
118      double threshold = 0;
119
120      #region Calculate threshold
121      if (rightQualities.Length == 2) {
122        var sim1 = SimilarityCalculator.CalculateSolutionSimilarity(ExecutionContext.Scope, ExecutionContext.Scope.SubScopes[0]);
123        var sim2 = SimilarityCalculator.CalculateSolutionSimilarity(ExecutionContext.Scope, ExecutionContext.Scope.SubScopes[1]);
124        var simAvg = (sim1 + sim2) / 2.0;
125
126        //TODO: try out different things
127        //resultDiversity = simAvg < diversityComFact;
128        resultDiversity = sim1 < diversityComFact || sim2 < diversityComFact;
129
130        double minQuality = Math.Min(rightQualities[0].Value, rightQualities[1].Value);
131        double maxQuality = Math.Max(rightQualities[0].Value, rightQualities[1].Value);
132        if (maximization)
133          threshold = minQuality + (maxQuality - minQuality) * compFact;
134        else
135          threshold = maxQuality - (maxQuality - minQuality) * compFact;
136      } else {
137        throw new NotImplementedException("Only 2 parents are supported.");
138      }
139      #endregion
140
141      bool result = maximization && leftQuality > threshold || !maximization && leftQuality < threshold;
142      result = result && resultDiversity;
143      BoolValue resultValue = ResultParameter.ActualValue;
144      if (resultValue == null) {
145        ResultParameter.ActualValue = new BoolValue(result);
146      } else {
147        resultValue.Value = result;
148      }
149
150      //like the placeholder, though we create child operations
151      OperationCollection next = new OperationCollection(base.Apply());
152      IOperator op = ComparisonFactorModifierParameter.Value;
153      if (op != null)
154        next.Insert(0, ExecutionContext.CreateChildOperation(op));
155      return next;
156    }
157  }
158}
Note: See TracBrowser for help on using the repository browser.