Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.EvolutionaryTracking/3.4/Analyzers/SymbolicExpressionTreeEvolvabilityAnalyzer.cs @ 9082

Last change on this file since 9082 was 9082, checked in by bburlacu, 11 years ago

#1772: Renamed and refactored genealogy graph components. Added SymbolGraph and FPGraph (frequent pattern graph). Added evolvability and genetic operator average improvement analyzer.

File size: 8.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33// type definitions for ease of use
34
35namespace HeuristicLab.EvolutionaryTracking {
36  /// <summary>
37  /// Population diversity analyzer
38  /// </summary>
39  [Item("SymbolicExpressionTreeEvolvabilityAnalyzer", "An operator that measures relative improvements obtained by genetic operators.")]
40  [StorableClass]
41  public sealed class SymbolicExpressionTreeEvolvabilityAnalyzer : SingleSuccessorOperator, IAnalyzer {
42    #region Parameter names
43    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
44    private const string UpdateIntervalParameterName = "UpdateInterval";
45    private const string UpdateCounterParameterName = "UpdateCounter";
46    private const string ResultsParameterName = "Results";
47    private const string PopulationGraphParameterName = "PopulationGraph";
48    private const string PopulationSizeParameterName = "PopulationSize";
49    private const string ElitesParameterName = "Elites";
50    #endregion
51
52    #region Parameter properties
53    public ValueParameter<IntValue> UpdateIntervalParameter {
54      get { return (ValueParameter<IntValue>)Parameters[UpdateIntervalParameterName]; }
55    }
56    public ValueParameter<IntValue> UpdateCounterParameter {
57      get { return (ValueParameter<IntValue>)Parameters[UpdateCounterParameterName]; }
58    }
59    public LookupParameter<ResultCollection> ResultsParameter {
60      get { return (LookupParameter<ResultCollection>)Parameters[ResultsParameterName]; }
61    }
62    public IScopeTreeLookupParameter<ISymbolicExpressionTree> SymbolicExpressionTreeParameter {
63      get { return (IScopeTreeLookupParameter<ISymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
64    }
65    public LookupParameter<IntValue> ElitesParameter {
66      get { return (LookupParameter<IntValue>)Parameters[ElitesParameterName]; }
67    }
68    public LookupParameter<IntValue> PopulationSizeParameter {
69      get { return (LookupParameter<IntValue>)Parameters[PopulationSizeParameterName]; }
70    }
71    #endregion
72
73    #region Parameters
74    public IntValue UpdateInterval { get { return UpdateIntervalParameter.Value; } }
75    public IntValue UpdateCounter { get { return UpdateCounterParameter.Value; } }
76    public ResultCollection Results { get { return ResultsParameter.ActualValue; } }
77    public IntValue PopulationSize { get { return PopulationSizeParameter.ActualValue; } }
78    public IntValue Elites { get { return ElitesParameter.ActualValue; } }
79    #endregion
80
81    [StorableConstructor]
82    private SymbolicExpressionTreeEvolvabilityAnalyzer(bool deserializing) : base(deserializing) { }
83    private SymbolicExpressionTreeEvolvabilityAnalyzer(SymbolicExpressionTreeEvolvabilityAnalyzer original, Cloner cloner) : base(original, cloner) { }
84    public override IDeepCloneable Clone(Cloner cloner) {
85      return new SymbolicExpressionTreeEvolvabilityAnalyzer(this, cloner);
86    }
87    public SymbolicExpressionTreeEvolvabilityAnalyzer() {
88      // add parameters
89      Parameters.Add(new ScopeTreeLookupParameter<ISymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic expression trees to analyze."));
90      Parameters.Add(new ValueParameter<IntValue>(UpdateIntervalParameterName, "The interval in which the tree length analysis should be applied.", new IntValue(1)));
91      Parameters.Add(new ValueParameter<IntValue>(UpdateCounterParameterName, "The value which counts how many times the operator was called since the last update", new IntValue(0)));
92      Parameters.Add(new ValueLookupParameter<ResultCollection>(ResultsParameterName, "The results collection where the analysis values should be stored."));
93      Parameters.Add(new LookupParameter<IntValue>(PopulationSizeParameterName, "The population size."));
94      Parameters.Add(new LookupParameter<IntValue>(ElitesParameterName, "Number of elites in the population."));
95
96      UpdateCounterParameter.Hidden = true;
97      UpdateIntervalParameter.Hidden = true;
98    }
99    [StorableHook(HookType.AfterDeserialization)]
100    private void AfterDeserialization() { }
101
102    #region IStatefulItem members
103    public override void InitializeState() {
104      base.InitializeState();
105      UpdateCounter.Value = 0;
106    }
107
108    public override void ClearState() {
109      base.ClearState();
110      UpdateCounter.Value = 0;
111    }
112    #endregion
113
114    public override IOperation Apply() {
115      UpdateCounter.Value++;
116
117      if (UpdateCounter.Value == UpdateInterval.Value) {
118        UpdateCounter.Value = 0;
119
120        if (!Results.ContainsKey(PopulationGraphParameterName)) return base.Apply();
121        var graph = Results[PopulationGraphParameterName].Value as SymbolicExpressionTreeGenealogyGraph;
122        if (graph == null) return base.Apply();
123
124        if (graph.Nodes.Count < PopulationSize.Value) return base.Apply();
125
126        var trees = SymbolicExpressionTreeParameter.ActualValue.ToList();
127
128        var graphNodes = trees.Select(x => graph.GetGraphNodes(x).Last());
129
130        int count = 0;
131
132        foreach (var node in graphNodes) {
133          double parentQuality = 0.0;
134          if (node.InEdges == null) continue;
135          switch (node.InEdges.Count) {
136            case 2: // crossover
137              parentQuality = node.InEdges.Max(x => (x.Source as SymbolicExpressionGenealogyGraphNode).Quality);
138              break;
139            case 1: // mutation
140              parentQuality = (node.InEdges[0].Source as SymbolicExpressionGenealogyGraphNode).Quality;
141              break;
142          }
143
144          if (node.Quality > parentQuality) ++count;
145        }
146        double reproductiveSuccess = (double)count / (PopulationSize.Value - Elites.Value);
147
148        if (!Results.ContainsKey("RelativeReproductiveSuccess"))
149          Results.Add(new Result("RelativeReproductiveSuccess", new DataTable("Reproductive success")));
150
151        var relativeReproductiveSuccessTable = Results["RelativeReproductiveSuccess"].Value as DataTable;
152        if (relativeReproductiveSuccessTable == null) return base.Apply();
153        if (!relativeReproductiveSuccessTable.Rows.ContainsKey("Reproductive Success"))
154          relativeReproductiveSuccessTable.Rows.Add(new DataRow("Reproductive Success") { VisualProperties = { StartIndexZero = true } });
155        relativeReproductiveSuccessTable.Rows["Reproductive Success"].Values.Add(reproductiveSuccess);
156
157        if (!Results.ContainsKey("RelativeProportionOfLeafNodes"))
158          Results.Add(new Result("RelativeProportionOfLeafNodes", new DataTable("Proportion of leaf nodes")));
159        var relativeProportionOfLeafNodesTable = Results["RelativeProportionOfLeafNodes"].Value as DataTable;
160        if (!relativeProportionOfLeafNodesTable.Rows.ContainsKey("Percent of leaf nodes"))
161          relativeProportionOfLeafNodesTable.Rows.Add(new DataRow("Percent of leaf nodes") { VisualProperties = { StartIndexZero = true } });
162        if (!relativeProportionOfLeafNodesTable.Rows.ContainsKey("Average number of leafs"))
163          relativeProportionOfLeafNodesTable.Rows.Add(new DataRow("Average number of leafs") { VisualProperties = { StartIndexZero = true } });
164
165        double totalNodes = trees.Sum(x => x.Length);
166        double totalLeafs = trees.Sum(t => t.IterateNodesPostfix().Count(n => n.SubtreeCount == 0));
167
168        relativeProportionOfLeafNodesTable.Rows["Percent of leaf nodes"].Values.Add(totalLeafs / totalNodes);
169        relativeProportionOfLeafNodesTable.Rows["Average number of leafs"].Values.Add(totalLeafs / trees.Count);
170      }
171      return base.Apply();
172    }
173
174    public bool EnabledByDefault { get { return true; } }
175  }
176}
Note: See TracBrowser for help on using the repository browser.