Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisGeneticOperatorImprovementAnalyzer.cs @ 14312

Last change on this file since 14312 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: 8.9 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.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Analysis;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.EvolutionTracking;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33
34namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Analyzers {
35  [StorableClass]
36  [Item("SymbolicDataAnalysisGeneticOperatorImprovementAnalyzer", "An analyzer which records the best and average genetic operator improvement")]
37  public class SymbolicDataAnalysisGeneticOperatorImprovementAnalyzer : EvolutionTrackingAnalyzer<ISymbolicExpressionTree> {
38    public const string QualityParameterName = "Quality";
39    public const string PopulationParameterName = "SymbolicExpressionTree";
40    public const string CountIntermediateChildrenParameterName = "CountIntermediateChildren";
41
42    public IScopeTreeLookupParameter<DoubleValue> QualityParameter {
43      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters[QualityParameterName]; }
44    }
45
46    public IScopeTreeLookupParameter<ISymbolicExpressionTree> PopulationParameter {
47      get { return (IScopeTreeLookupParameter<ISymbolicExpressionTree>)Parameters[PopulationParameterName]; }
48    }
49
50    public IFixedValueParameter<BoolValue> CountIntermediateChildrenParameter {
51      get { return (IFixedValueParameter<BoolValue>)Parameters[CountIntermediateChildrenParameterName]; }
52    }
53
54    public bool CountIntermediateChildren {
55      get { return CountIntermediateChildrenParameter.Value.Value; }
56      set { CountIntermediateChildrenParameter.Value.Value = value; }
57    }
58
59    public SymbolicDataAnalysisGeneticOperatorImprovementAnalyzer() {
60      Parameters.Add(new ScopeTreeLookupParameter<ISymbolicExpressionTree>(PopulationParameterName, "The population of individuals."));
61      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>(QualityParameterName, "The individual qualities."));
62      Parameters.Add(new FixedValueParameter<BoolValue>(CountIntermediateChildrenParameterName, "Specifies whether to consider intermediate children (when crossover was followed by mutation). This should be set to false for offspring selection.", new BoolValue(true)));
63
64      CountIntermediateChildrenParameter.Hidden = true;
65    }
66
67
68    [StorableConstructor]
69    protected SymbolicDataAnalysisGeneticOperatorImprovementAnalyzer(bool deserializing) : base(deserializing) { }
70
71    public SymbolicDataAnalysisGeneticOperatorImprovementAnalyzer(
72    SymbolicDataAnalysisGeneticOperatorImprovementAnalyzer original, Cloner cloner) : base(original, cloner) {
73      CountIntermediateChildren = original.CountIntermediateChildren;
74    }
75
76    public override IDeepCloneable Clone(Cloner cloner) {
77      return new SymbolicDataAnalysisGeneticOperatorImprovementAnalyzer(this, cloner);
78    }
79
80    [StorableHook(HookType.AfterDeserialization)]
81    private void AfterDeserialization() {
82      if (!Parameters.ContainsKey(CountIntermediateChildrenParameterName))
83        Parameters.Add(new FixedValueParameter<BoolValue>(CountIntermediateChildrenParameterName, "Specifies whether to consider intermediate children (when crossover was followed by mutation", new BoolValue(true)));
84      CountIntermediateChildrenParameter.Hidden = true;
85    }
86
87    public override IOperation Apply() {
88      IntValue updateCounter = UpdateCounterParameter.ActualValue;
89      if (updateCounter == null) {
90        updateCounter = new IntValue(0);
91        UpdateCounterParameter.ActualValue = updateCounter;
92      }
93      updateCounter.Value++;
94      if (updateCounter.Value != UpdateInterval.Value) return base.Apply();
95      updateCounter.Value = 0;
96
97      var graph = PopulationGraph;
98      if (graph == null || Generation.Value == 0)
99        return base.Apply();
100
101      var generation = Generation.Value;
102      var averageQuality = QualityParameter.ActualValue.Average(x => x.Value);
103      var population = PopulationParameter.ActualValue;
104      var populationSize = population.Length;
105
106      //      var vertices = population.Select(graph.GetByContent).ToList();
107      var crossoverChildren = new List<IGenealogyGraphNode<ISymbolicExpressionTree>>();
108      var mutationChildren = new List<IGenealogyGraphNode<ISymbolicExpressionTree>>();
109      var vertices = graph.Vertices.Where(x => x.Rank > generation - 1);
110      foreach (var v in vertices) {
111        if (v.InDegree == 2) {
112          crossoverChildren.Add(v);
113        } else {
114          var parent = v.Parents.First();
115          // mutation is always preceded by mutation
116          // so the parent vertex should have an intermediate rank
117          // otherwise, it is the previos generation elite
118          if (parent.Rank.IsAlmost(generation - 1) && parent.IsElite)
119            continue;
120          mutationChildren.Add(v);
121        }
122      }
123      DataTable table;
124      #region crossover improvement
125      if (!Results.ContainsKey("Crossover improvement")) {
126        table = new DataTable("Crossover improvement");
127        Results.Add(new Result("Crossover improvement", table));
128        table.Rows.AddRange(new[] {
129          new DataRow("Average crossover child quality") { VisualProperties = { StartIndexZero = true } },
130          new DataRow("Average crossover parent quality") { VisualProperties = { StartIndexZero = true } },
131          new DataRow("Best crossover child quality") { VisualProperties = { StartIndexZero = true } },
132          new DataRow("Best crossover parent quality") { VisualProperties = { StartIndexZero = true } },
133        });
134      } else {
135        table = (DataTable)Results["Crossover improvement"].Value;
136      }
137
138      var avgCrossoverParentQuality = crossoverChildren.SelectMany(x => x.Parents).Average(x => x.Quality);
139      var avgCrossoverChildQuality = crossoverChildren.Average(x => x.Quality);
140
141      var bestCrossoverChildQuality = crossoverChildren.OrderBy(x => x.Quality).Last().Quality;
142      var bestCrossoverParentQuality = crossoverChildren.OrderBy(x => x.Quality).Last().Parents.First().Quality;
143
144      table.Rows["Average crossover child quality"].Values.Add(avgCrossoverChildQuality);
145      table.Rows["Average crossover parent quality"].Values.Add(avgCrossoverParentQuality);
146      table.Rows["Best crossover child quality"].Values.Add(bestCrossoverChildQuality);
147      table.Rows["Best crossover parent quality"].Values.Add(bestCrossoverParentQuality);
148      #endregion
149
150      #region mutation improvement
151      if (!Results.ContainsKey("Mutation improvement")) {
152        table = new DataTable("Mutation improvement");
153        Results.Add(new Result("Mutation improvement", table));
154        table.Rows.AddRange(new[] {
155          new DataRow("Average mutation child quality") { VisualProperties = { StartIndexZero = true } },
156          new DataRow("Average mutation parent quality") { VisualProperties = { StartIndexZero = true } },
157          new DataRow("Best mutation child quality") { VisualProperties = { StartIndexZero = true } },
158          new DataRow("Best mutation parent quality") { VisualProperties = { StartIndexZero = true } },
159        });
160      } else {
161        table = (DataTable)Results["Mutation improvement"].Value;
162      }
163
164      var avgMutationParentQuality = mutationChildren.SelectMany(x => x.Parents).Average(x => x.Quality);
165      var avgMutationChildQuality = mutationChildren.Average(x => x.Quality);
166
167      var bestMutationChildQuality = mutationChildren.OrderBy(x => x.Quality).Last().Quality;
168      var bestMutationParentQuality = mutationChildren.OrderBy(x => x.Quality).Last().Parents.First().Quality;
169
170      table.Rows["Average mutation child quality"].Values.Add(avgMutationChildQuality);
171      table.Rows["Average mutation parent quality"].Values.Add(avgMutationParentQuality);
172      table.Rows["Best mutation child quality"].Values.Add(bestMutationChildQuality);
173      table.Rows["Best mutation parent quality"].Values.Add(bestMutationParentQuality);
174
175      #endregion
176      return base.Apply();
177    }
178  }
179}
Note: See TracBrowser for help on using the repository browser.