Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 13527 was 13527, checked in by bburlacu, 8 years ago

#1772: Fixed the way operator improvement is calculated so it also works when a diversification strategy is applied (introducing multiple intermediate vertices between parent and child). Minor code refactoring in the diversification operators. Fixed very small typo in the BeforeManipulatorOperator.

File size: 17.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 readonly SymbolicExpressionTreePhenotypicSimilarityCalculator calculator = new SymbolicExpressionTreePhenotypicSimilarityCalculator();
135    private readonly QueryMatch qm;
136
137    public Func<double, double> ReplacementRule { get; set; }
138
139    private readonly ISymbolicExpressionTreeNodeEqualityComparer comp = new SymbolicExpressionTreeNodeEqualityComparer {
140      MatchConstantValues = false,
141      MatchVariableWeights = false,
142      MatchVariableNames = true
143    };
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
157    public SchemaEvaluator() {
158      qm = new QueryMatch(comp) { MatchParents = true };
159      this.updateQualityOperator = new UpdateQualityOperator();
160      #region add parameters
161      Parameters.Add(new LookupParameter<ISymbolicExpressionTree>(SchemaParameterName, "The current schema to be evaluated"));
162      Parameters.Add(new LookupParameter<PercentValue>(MinimumSchemaFrequencyParameterName));
163      Parameters.Add(new LookupParameter<PercentValue>(ReplacementRatioParameterName));
164      Parameters.Add(new LookupParameter<PercentValue>(MinimumPhenotypicSimilarityParameterName));
165      Parameters.Add(new LookupParameter<ISymbolicExpressionTree>(PopulationSizeParameterName));
166      Parameters.Add(new LookupParameter<IRandom>(RandomParameterName));
167      Parameters.Add(new LookupParameter<ISymbolicDataAnalysisSingleObjectiveEvaluator<IRegressionProblemData>>(EvaluatorParameterName));
168      Parameters.Add(new LookupParameter<IRegressionProblemData>(ProblemDataParameterName));
169      Parameters.Add(new LookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(InterpreterParameterName));
170      Parameters.Add(new LookupParameter<DoubleLimit>(EstimationLimitsParameterName));
171      Parameters.Add(new LookupParameter<BoolValue>(ApplyLinearScalingParameterName));
172      Parameters.Add(new LookupParameter<BoolValue>(StrictSchemaMatchingParameterName));
173      Parameters.Add(new LookupParameter<ISymbolicExpressionTreeManipulator>(MutatorParameterName));
174      Parameters.Add(new LookupParameter<ISymbolicExpressionTreeCrossover>(CrossoverParameterName));
175      Parameters.Add(new LookupParameter<BoolValue>(RandomReplacementParameterName));
176      Parameters.Add(new LookupParameter<IntValue>(NumberOfChangedTreesParameterName));
177      Parameters.Add(new LookupParameter<BoolValue>(ExecuteInParallelParameterName));
178      Parameters.Add(new LookupParameter<IntValue>(MaxDegreeOfParalellismParameterName));
179      Parameters.Add(new LookupParameter<BoolValue>(ExclusiveMatchingParameterName));
180      Parameters.Add(new LookupParameter<BoolValue>(UseAdaptiveReplacementRatioParameterName));
181      #endregion
182    }
183
184    [StorableConstructor]
185    protected SchemaEvaluator(bool deserializing) : base(deserializing) { }
186
187    protected SchemaEvaluator(SchemaEvaluator original, Cloner cloner) : base(original, cloner) {
188      this.comp = new SymbolicExpressionTreeNodeEqualityComparer();
189      this.qm = new QueryMatch(comp) { MatchParents = original.qm?.MatchParents ?? true };
190      this.updateQualityOperator = new UpdateQualityOperator();
191      Schema = original.Schema;
192    }
193
194    public override IDeepCloneable Clone(Cloner cloner) {
195      return new SchemaEvaluator(this, cloner);
196    }
197
198    public override IOperation Apply() {
199      var strictSchemaMatching = StrictSchemaMatchingParameter.ActualValue.Value;
200      if (strictSchemaMatching) {
201        comp.MatchVariableWeights = true;
202        comp.MatchConstantValues = true;
203      } else {
204        comp.MatchVariableWeights = false;
205        comp.MatchConstantValues = false;
206      }
207
208      var individuals = ExecutionContext.Scope.SubScopes; // the scopes represent the individuals
209      var trees = individuals.Select(x => (ISymbolicExpressionTree)x.Variables["SymbolicExpressionTree"].Value).ToList();
210
211      var random = RandomParameter.ActualValue;
212      var mutator = MutatorParameter.ActualValue;
213
214      var s = Schema;
215      var sRoot = s.Root.GetSubtree(0).GetSubtree(0);
216      int countThreshold = (int)Math.Max(2, Math.Round(MinimumSchemaFrequency.Value * individuals.Count));
217
218      // first apply the length and root equality checks in order to filter the individuals
219      var exclusiveMatching = ExclusiveMatchingParameter.ActualValue.Value;
220      var filtered = new List<int>();
221      for (int i = 0; i < individuals.Count; ++i) {
222        if (exclusiveMatching && individuals[i].Variables.ContainsKey("AlreadyMatched")) continue;
223        var t = trees[i];
224        var tRoot = t.Root.GetSubtree(0).GetSubtree(0);
225        if (t.Length < s.Length || !qm.Comparer.Equals(tRoot, sRoot)) continue;
226        filtered.Add(i);
227      }
228
229      // if we don't have enough filtered individuals, then we are done
230      // if the schema exceeds the minimum frequency, it gets processed further
231      if (filtered.Count < countThreshold) {
232        return base.Apply();
233      }
234
235      // check if the filtered individuals match the schema
236      var sNodes = QueryMatch.InitializePostOrder(sRoot);
237      var matchingIndividuals = new ScopeList();
238      bool executeInParallel = ExecuteInParallelParameter.ActualValue.Value;
239      int maxDegreeOfParallelism = MaxDegreeOfParallelismParameter.ActualValue.Value;
240
241      if (executeInParallel) {
242        var matching = new bool[filtered.Count];
243
244        Parallel.For(0, filtered.Count, new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism },
245          i => {
246            var index = filtered[i];
247            var t = trees[index];
248            var tNodes = QueryMatch.InitializePostOrder(t.Root.GetSubtree(0).GetSubtree(0));
249            if (qm.Match(tNodes, sNodes)) {
250              matching[i] = true;
251            }
252          });
253
254        matchingIndividuals.AddRange(filtered.Where((x, i) => matching[i]).Select(x => individuals[x]));
255      } else {
256        for (int i = 0; i < filtered.Count; ++i) {
257          // break early if it becomes impossible to reach the minimum threshold
258          if (matchingIndividuals.Count + filtered.Count - i < countThreshold)
259            break;
260
261          var index = filtered[i];
262          var tRoot = trees[index].Root.GetSubtree(0).GetSubtree(0);
263          var tNodes = QueryMatch.InitializePostOrder(tRoot);
264          if (qm.Match(tNodes, sNodes))
265            matchingIndividuals.Add(individuals[index]);
266        }
267      }
268
269      if (matchingIndividuals.Count < countThreshold) {
270        return base.Apply();
271      }
272
273      var similarity = CalculateSimilarity(matchingIndividuals, calculator, executeInParallel, maxDegreeOfParallelism);
274      if (similarity < MinimumPhenotypicSimilarity.Value) {
275        return base.Apply();
276      }
277
278      double replacementRatio;
279      var adaptiveReplacementRatio = UseAdaptiveReplacementRatioParameter.ActualValue.Value;
280
281      if (adaptiveReplacementRatio) {
282        var r = (double)matchingIndividuals.Count / individuals.Count;
283        replacementRatio = ReplacementRule(r);
284      } else {
285        replacementRatio = ReplacementRatio.Value;
286      }
287
288      int n = (int)Math.Floor(matchingIndividuals.Count * replacementRatio);
289      var individualsToReplace = RandomReplacement.Value ? matchingIndividuals.SampleRandomWithoutRepetition(random, n).ToList()
290                                                         : matchingIndividuals.OrderBy(x => (DoubleValue)x.Variables["Quality"].Value).Take(n).ToList();
291      var mutationOc = new OperationCollection { Parallel = false }; // cannot be parallel due to the before/after operators which insert vertices in the genealogy graph
292      var updateEstimatedValues = new OperationCollection { Parallel = true }; // evaluation should be done in parallel when possible
293      foreach (var ind in individualsToReplace) {
294        var mutatorOp = ExecutionContext.CreateChildOperation(mutator, ind);
295        var updateOp = ExecutionContext.CreateChildOperation(updateQualityOperator, ind);
296        mutationOc.Add(mutatorOp);
297        updateEstimatedValues.Add(updateOp);
298        if (exclusiveMatching)
299          ind.Variables.Add(new Core.Variable("AlreadyMatched"));
300      }
301
302      NumberOfChangedTrees.Value += individualsToReplace.Count; // a lock is not necessary here because the SchemaEvaluators cannot be executed in parallel
303
304      return new OperationCollection(mutationOc, updateEstimatedValues, base.Apply());
305    }
306
307    public static double CalculateSimilarity(ScopeList individuals, ISolutionSimilarityCalculator calculator, bool parallel = false, int nThreads = -1) {
308      double similarity = 0;
309      int count = individuals.Count;
310      if (count < 2) return double.NaN;
311      if (parallel) {
312        var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = nThreads };
313        var simArray = new double[count - 1];
314        Parallel.For(0, count - 1, parallelOptions, i => {
315          double innerSim = 0;
316          for (int j = i + 1; j < count; ++j) {
317            innerSim += calculator.CalculateSolutionSimilarity(individuals[i], individuals[j]);
318          }
319          simArray[i] = innerSim;
320        });
321        similarity = simArray.Sum();
322      } else {
323        for (int i = 0; i < count - 1; ++i) {
324          for (int j = i + 1; j < count; ++j) {
325            similarity += calculator.CalculateSolutionSimilarity(individuals[i], individuals[j]);
326          }
327        }
328      }
329      return similarity / (count * (count - 1) / 2.0);
330    }
331  }
332}
Note: See TracBrowser for help on using the repository browser.