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

Last change on this file since 13495 was 13495, checked in by bburlacu, 5 years ago

#1772: Improve the average operator improvement and average fragment length analyzers. Update genealogy analyzer to always evaluate the intermediate children.

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