Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Tracking/SchemaDiversification/SchemaEvaluator.cs @ 13693

Last change on this file since 13693 was 13565, checked in by bburlacu, 9 years ago

#1772: Slight refactor of schema diversification operators to try to fix potential problems with serialization/cloning

File size: 18.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Collections.Generic;
24using System.Linq;
25using System.Threading.Tasks;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.EvolutionTracking;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.Random;
35
36namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
37  [Item("SchemaEvaluator", "An operator that builds schemas based on the heredity relationship in the genealogy graph.")]
38  [StorableClass]
39  public class SchemaEvaluator : EvolutionTrackingOperator<ISymbolicExpressionTree> {
40    #region parameter names
41    private const string MinimumSchemaFrequencyParameterName = "MinimumSchemaFrequency";
42    private const string MinimumPhenotypicSimilarityParameterName = "MinimumPhenotypicSimilarity";
43    private const string ReplacementRatioParameterName = "ReplacementRatio";
44    private const string SchemaParameterName = "Schema";
45    private const string PopulationSizeParameterName = "PopulationSize";
46    private const string RandomParameterName = "Random";
47    private const string EvaluatorParameterName = "Evaluator";
48    private const string ProblemDataParameterName = "ProblemData";
49    private const string InterpreterParameterName = "SymbolicExpressionTreeInterpreter";
50    private const string EstimationLimitsParameterName = "EstimationLimits";
51    private const string ApplyLinearScalingParameterName = "ApplyLinearScaling";
52    private const string MutatorParameterName = "Mutator";
53    private const string CrossoverParameterName = "Crossover";
54    private const string RandomReplacementParameterName = "RandomReplacement";
55    private const string NumberOfChangedTreesParameterName = "NumberOfChangedTrees";
56    private const string ExecuteInParallelParameterName = "ExecuteInParallel";
57    private const string MaxDegreeOfParalellismParameterName = "MaxDegreeOfParallelism";
58    private const string ExclusiveMatchingParameterName = "ExclusiveMatching";
59    private const string UseAdaptiveReplacementRatioParameterName = "UseAdaptiveReplacementRatio";
60    private const string StrictSchemaMatchingParameterName = "StrictSchemaMatching";
61    #endregion
62
63    #region parameters
64    public ILookupParameter<BoolValue> UseAdaptiveReplacementRatioParameter {
65      get { return (ILookupParameter<BoolValue>)Parameters[UseAdaptiveReplacementRatioParameterName]; }
66    }
67    public ILookupParameter<BoolValue> ExclusiveMatchingParameter {
68      get { return (ILookupParameter<BoolValue>)Parameters[ExclusiveMatchingParameterName]; }
69    }
70    public ILookupParameter<BoolValue> ExecuteInParallelParameter {
71      get { return (ILookupParameter<BoolValue>)Parameters[ExecuteInParallelParameterName]; }
72    }
73    public ILookupParameter<IntValue> MaxDegreeOfParallelismParameter {
74      get { return (ILookupParameter<IntValue>)Parameters[MaxDegreeOfParalellismParameterName]; }
75    }
76    public ILookupParameter<ISymbolicDataAnalysisSingleObjectiveEvaluator<IRegressionProblemData>> EvaluatorParameter {
77      get { return (ILookupParameter<ISymbolicDataAnalysisSingleObjectiveEvaluator<IRegressionProblemData>>)Parameters[EvaluatorParameterName]; }
78    }
79    public ILookupParameter<IRegressionProblemData> ProblemDataParameter {
80      get { return (ILookupParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName]; }
81    }
82    public ILookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter> InterpreterParameter {
83      get { return (ILookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>)Parameters[InterpreterParameterName]; }
84    }
85    public ILookupParameter<DoubleLimit> EstimationLimitsParameter {
86      get { return (ILookupParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName]; }
87    }
88    public ILookupParameter<BoolValue> ApplyLinearScalingParameter {
89      get { return (ILookupParameter<BoolValue>)Parameters[ApplyLinearScalingParameterName]; }
90    }
91    public ILookupParameter<BoolValue> RandomReplacementParameter {
92      get { return (ILookupParameter<BoolValue>)Parameters[RandomReplacementParameterName]; }
93    }
94    public ILookupParameter<ISymbolicExpressionTreeManipulator> MutatorParameter {
95      get { return (ILookupParameter<ISymbolicExpressionTreeManipulator>)Parameters[MutatorParameterName]; }
96    }
97    public ILookupParameter<ISymbolicExpressionTreeCrossover> CrossoverParameter {
98      get { return (ILookupParameter<ISymbolicExpressionTreeCrossover>)Parameters[CrossoverParameterName]; }
99    }
100    public ILookupParameter<IRandom> RandomParameter {
101      get { return (ILookupParameter<IRandom>)Parameters[RandomParameterName]; }
102    }
103    public ILookupParameter<IntValue> PopulationSizeParameter {
104      get { return (ILookupParameter<IntValue>)Parameters[PopulationSizeParameterName]; }
105    }
106    public ILookupParameter<ISymbolicExpressionTree> SchemaParameter {
107      get { return (ILookupParameter<ISymbolicExpressionTree>)Parameters[SchemaParameterName]; }
108    }
109    public ILookupParameter<PercentValue> MinimumSchemaFrequencyParameter {
110      get { return (ILookupParameter<PercentValue>)Parameters[MinimumSchemaFrequencyParameterName]; }
111    }
112    public ILookupParameter<PercentValue> ReplacementRatioParameter {
113      get { return (ILookupParameter<PercentValue>)Parameters[ReplacementRatioParameterName]; }
114    }
115    public ILookupParameter<PercentValue> MinimumPhenotypicSimilarityParameter {
116      get { return (ILookupParameter<PercentValue>)Parameters[MinimumPhenotypicSimilarityParameterName]; }
117    }
118    public LookupParameter<IntValue> NumberOfChangedTreesParameter {
119      get { return (LookupParameter<IntValue>)Parameters[NumberOfChangedTreesParameterName]; }
120    }
121    public LookupParameter<BoolValue> StrictSchemaMatchingParameter {
122      get { return (LookupParameter<BoolValue>)Parameters[StrictSchemaMatchingParameterName]; }
123    }
124    #endregion
125
126    #region parameter properties
127    public PercentValue MinimumSchemaFrequency { get { return MinimumSchemaFrequencyParameter.ActualValue; } }
128    public PercentValue ReplacementRatio { get { return ReplacementRatioParameter.ActualValue; } }
129    public PercentValue MinimumPhenotypicSimilarity { get { return MinimumPhenotypicSimilarityParameter.ActualValue; } }
130    public BoolValue RandomReplacement { get { return RandomReplacementParameter.ActualValue; } }
131    public IntValue NumberOfChangedTrees { get { return NumberOfChangedTreesParameter.ActualValue; } }
132    #endregion
133
134    private QueryMatch qm;
135
136    [Storable]
137    private SymbolicExpressionTreePhenotypicSimilarityCalculator calculator;
138
139    [Storable]
140    public string ReplacementRule { get; set; }
141
142    [Storable]
143    private ISymbolicExpressionTreeNodeEqualityComparer comparer;
144
145    [Storable]
146    public ISymbolicExpressionTree Schema { get; set; }
147
148    [Storable]
149    private readonly UpdateQualityOperator updateQualityOperator;
150
151    [StorableHook(HookType.AfterDeserialization)]
152    private void AfterDeserialization() {
153      if (!Parameters.ContainsKey(StrictSchemaMatchingParameterName))
154        Parameters.Add(new LookupParameter<BoolValue>(StrictSchemaMatchingParameterName));
155
156      if (calculator == null)
157        calculator = new SymbolicExpressionTreePhenotypicSimilarityCalculator();
158
159      if (comparer == null)
160        comparer = new SymbolicExpressionTreeNodeEqualityComparer { MatchVariableNames = true, MatchVariableWeights = true, MatchConstantValues = false };
161
162      qm = new QueryMatch(comparer) { MatchParents = true };
163    }
164
165    public SchemaEvaluator() {
166      calculator = new SymbolicExpressionTreePhenotypicSimilarityCalculator();
167      comparer = new SymbolicExpressionTreeNodeEqualityComparer { MatchVariableNames = true, MatchVariableWeights = true, MatchConstantValues = false };
168      qm = new QueryMatch(comparer) { MatchParents = true };
169      updateQualityOperator = new UpdateQualityOperator();
170      #region add parameters
171      Parameters.Add(new LookupParameter<ISymbolicExpressionTree>(SchemaParameterName, "The current schema to be evaluated"));
172      Parameters.Add(new LookupParameter<PercentValue>(MinimumSchemaFrequencyParameterName));
173      Parameters.Add(new LookupParameter<PercentValue>(ReplacementRatioParameterName));
174      Parameters.Add(new LookupParameter<PercentValue>(MinimumPhenotypicSimilarityParameterName));
175      Parameters.Add(new LookupParameter<ISymbolicExpressionTree>(PopulationSizeParameterName));
176      Parameters.Add(new LookupParameter<IRandom>(RandomParameterName));
177      Parameters.Add(new LookupParameter<ISymbolicDataAnalysisSingleObjectiveEvaluator<IRegressionProblemData>>(EvaluatorParameterName));
178      Parameters.Add(new LookupParameter<IRegressionProblemData>(ProblemDataParameterName));
179      Parameters.Add(new LookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(InterpreterParameterName));
180      Parameters.Add(new LookupParameter<DoubleLimit>(EstimationLimitsParameterName));
181      Parameters.Add(new LookupParameter<BoolValue>(ApplyLinearScalingParameterName));
182      Parameters.Add(new LookupParameter<BoolValue>(StrictSchemaMatchingParameterName));
183      Parameters.Add(new LookupParameter<ISymbolicExpressionTreeManipulator>(MutatorParameterName));
184      Parameters.Add(new LookupParameter<ISymbolicExpressionTreeCrossover>(CrossoverParameterName));
185      Parameters.Add(new LookupParameter<BoolValue>(RandomReplacementParameterName));
186      Parameters.Add(new LookupParameter<IntValue>(NumberOfChangedTreesParameterName));
187      Parameters.Add(new LookupParameter<BoolValue>(ExecuteInParallelParameterName));
188      Parameters.Add(new LookupParameter<IntValue>(MaxDegreeOfParalellismParameterName));
189      Parameters.Add(new LookupParameter<BoolValue>(ExclusiveMatchingParameterName));
190      Parameters.Add(new LookupParameter<BoolValue>(UseAdaptiveReplacementRatioParameterName));
191      #endregion
192    }
193
194    [StorableConstructor]
195    protected SchemaEvaluator(bool deserializing) : base(deserializing) { }
196
197    protected SchemaEvaluator(SchemaEvaluator original, Cloner cloner) : base(original, cloner) {
198      calculator = cloner.Clone(original.calculator);
199      comparer = cloner.Clone(original.comparer);
200      qm = new QueryMatch(comparer) { MatchParents = true };
201      updateQualityOperator = new UpdateQualityOperator();
202      Schema = original.Schema;
203    }
204
205    public override IDeepCloneable Clone(Cloner cloner) {
206      return new SchemaEvaluator(this, cloner);
207    }
208
209    public override IOperation Apply() {
210      var strictSchemaMatching = StrictSchemaMatchingParameter.ActualValue.Value;
211      if (strictSchemaMatching) {
212        comparer.MatchVariableWeights = true;
213        comparer.MatchConstantValues = true;
214      } else {
215        comparer.MatchVariableWeights = false;
216        comparer.MatchConstantValues = false;
217      }
218
219      var individuals = ExecutionContext.Scope.SubScopes; // the scopes represent the individuals
220      var trees = individuals.Select(x => (ISymbolicExpressionTree)x.Variables["SymbolicExpressionTree"].Value).ToList();
221
222      var random = RandomParameter.ActualValue;
223      var mutator = MutatorParameter.ActualValue;
224
225      var s = Schema;
226      var sRoot = s.Root.GetSubtree(0).GetSubtree(0);
227      int countThreshold = (int)Math.Max(2, Math.Round(MinimumSchemaFrequency.Value * individuals.Count));
228
229      // first apply the length and root equality checks in order to filter the individuals
230      var exclusiveMatching = ExclusiveMatchingParameter.ActualValue.Value;
231      var filtered = new List<int>();
232      for (int i = 0; i < individuals.Count; ++i) {
233        if (exclusiveMatching && individuals[i].Variables.ContainsKey("AlreadyMatched")) continue;
234        var t = trees[i];
235        var tRoot = t.Root.GetSubtree(0).GetSubtree(0);
236        if (t.Length < s.Length || !qm.Comparer.Equals(tRoot, sRoot)) continue;
237        filtered.Add(i);
238      }
239
240      // if we don't have enough filtered individuals, then we are done
241      // if the schema exceeds the minimum frequency, it gets processed further
242      if (filtered.Count < countThreshold) {
243        return base.Apply();
244      }
245
246      // check if the filtered individuals match the schema
247      var sNodes = QueryMatch.InitializePostOrder(sRoot);
248      var matchingIndividuals = new ScopeList();
249      bool executeInParallel = ExecuteInParallelParameter.ActualValue.Value;
250      int maxDegreeOfParallelism = MaxDegreeOfParallelismParameter.ActualValue.Value;
251
252      if (executeInParallel) {
253        var matching = new bool[filtered.Count];
254
255        Parallel.For(0, filtered.Count, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism },
256          i => {
257            var index = filtered[i];
258            var t = trees[index];
259            var tNodes = QueryMatch.InitializePostOrder(t.Root.GetSubtree(0).GetSubtree(0));
260            if (qm.Match(tNodes, sNodes)) {
261              matching[i] = true;
262            }
263          });
264
265        matchingIndividuals.AddRange(filtered.Where((x, i) => matching[i]).Select(x => individuals[x]));
266      } else {
267        for (int i = 0; i < filtered.Count; ++i) {
268          // break early if it becomes impossible to reach the minimum threshold
269          if (matchingIndividuals.Count + filtered.Count - i < countThreshold)
270            break;
271
272          var index = filtered[i];
273          var tRoot = trees[index].Root.GetSubtree(0).GetSubtree(0);
274          var tNodes = QueryMatch.InitializePostOrder(tRoot);
275          if (qm.Match(tNodes, sNodes))
276            matchingIndividuals.Add(individuals[index]);
277        }
278      }
279
280      if (matchingIndividuals.Count < countThreshold) {
281        return base.Apply();
282      }
283
284      var similarity = CalculateSimilarity(matchingIndividuals, calculator, executeInParallel, maxDegreeOfParallelism);
285      if (similarity < MinimumPhenotypicSimilarity.Value) {
286        return base.Apply();
287      }
288
289      double replacementRatio;
290      var adaptiveReplacementRatio = UseAdaptiveReplacementRatioParameter.ActualValue.Value;
291
292      if (adaptiveReplacementRatio) {
293        var r = (double)matchingIndividuals.Count / individuals.Count;
294        replacementRatio = CalculateReplacementRatio(r);
295      } else {
296        replacementRatio = ReplacementRatio.Value;
297      }
298
299      int n = (int)Math.Floor(matchingIndividuals.Count * replacementRatio);
300      var individualsToReplace = RandomReplacement.Value ? matchingIndividuals.SampleRandomWithoutRepetition(random, n).ToList()
301                                                         : matchingIndividuals.OrderBy(x => (DoubleValue)x.Variables["Quality"].Value).Take(n).ToList();
302      var mutationOc = new OperationCollection { Parallel = false }; // cannot be parallel due to the before/after operators which insert vertices in the genealogy graph
303      var updateEstimatedValues = new OperationCollection { Parallel = true }; // evaluation should be done in parallel when possible
304      foreach (var ind in individualsToReplace) {
305        var mutatorOp = ExecutionContext.CreateChildOperation(mutator, ind);
306        var updateOp = ExecutionContext.CreateChildOperation(updateQualityOperator, ind);
307        mutationOc.Add(mutatorOp);
308        updateEstimatedValues.Add(updateOp);
309        if (exclusiveMatching)
310          ind.Variables.Add(new Core.Variable("AlreadyMatched"));
311      }
312
313      NumberOfChangedTrees.Value += individualsToReplace.Count; // a lock is not necessary here because the SchemaEvaluators cannot be executed in parallel
314
315      return new OperationCollection(mutationOc, updateEstimatedValues, base.Apply());
316    }
317
318    private double CalculateReplacementRatio(double r) {
319      switch (ReplacementRule) {
320        case "f(x) = x": {
321            return r;
322          }
323        case "f(x) = tanh(x)": {
324            return Math.Tanh(r);
325          }
326        case "f(x) = tanh(2x)": {
327            return Math.Tanh(2 * r);
328          }
329        case "f(x) = tanh(3x)": {
330            return Math.Tanh(3 * r);
331          }
332        case "f(x) = tanh(4x)": {
333            return Math.Tanh(4 * r);
334          }
335        case "f(x) = 1-sqrt(1-x)": {
336            return 1 - Math.Sqrt(1 - r);
337          }
338        default:
339          throw new ArgumentException("Unknown replacement rule");
340      }
341    }
342
343    public static double CalculateSimilarity(ScopeList individuals, ISolutionSimilarityCalculator calculator, bool parallel = false, int nThreads = -1) {
344      double similarity = 0;
345      int count = individuals.Count;
346      if (count < 2) return double.NaN;
347      if (parallel) {
348        var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = nThreads };
349        var simArray = new double[count - 1];
350        Parallel.For(0, count - 1, parallelOptions, i => {
351          double innerSim = 0;
352          for (int j = i + 1; j < count; ++j) {
353            innerSim += calculator.CalculateSolutionSimilarity(individuals[i], individuals[j]);
354          }
355          simArray[i] = innerSim;
356        });
357        similarity = simArray.Sum();
358      } else {
359        for (int i = 0; i < count - 1; ++i) {
360          for (int j = i + 1; j < count; ++j) {
361            similarity += calculator.CalculateSolutionSimilarity(individuals[i], individuals[j]);
362          }
363        }
364      }
365      return similarity / (count * (count - 1) / 2.0);
366    }
367  }
368}
Note: See TracBrowser for help on using the repository browser.