Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisBuildingBlockAnalyzer.cs @ 16255

Last change on this file since 16255 was 16255, checked in by bburlacu, 6 years ago

#2950: Implement first version of hash-based building blocks analyzer. Minor performance improvement in HashExtensions.cs. Fix bug in SymbolicExpressionTreeHash.cs with simplification for Multiplication nodes inadvertently altering constant values.

File size: 6.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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 HeuristicLab.Analysis;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Optimization;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using static HeuristicLab.Problems.DataAnalysis.Symbolic.SymbolicExpressionHashExtensions;
34
35namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Analyzers {
36  [Item("SymbolicDataAnalysisBuildingBlockAnalyzer", "An analyzer that uses tree hashing to identify the most common subtrees (building blocks) in the population")]
37  [StorableClass]
38  public sealed class SymbolicDataAnalysisBuildingBlockAnalyzer : SymbolicDataAnalysisAnalyzer {
39    private const string BuildingBlocksResultName = "BuildingBlocks";
40    private const string MinimumSubtreeLengthParameterName = "MinimumSubtreeLength";
41    private const string SimplifyTreesParameterName = "SimplifyTrees";
42
43    private readonly InfixExpressionFormatter formatter = new InfixExpressionFormatter();
44    private Dictionary<int, DataRow> hashToRow = new Dictionary<int, DataRow>();
45
46    public IValueLookupParameter<IntValue> MinimumSubtreeLengthParameter {
47      get { return (IValueLookupParameter<IntValue>)Parameters[MinimumSubtreeLengthParameterName]; }
48    }
49
50    public IValueLookupParameter<BoolValue> SimplifyTreesParameter {
51      get { return (IValueLookupParameter<BoolValue>)Parameters[SimplifyTreesParameterName]; }
52    }
53
54    public IntValue MinimumSubtreeLength {
55      get { return MinimumSubtreeLengthParameter.ActualValue; }
56    }
57
58    public BoolValue SimplifyTrees {
59      get { return SimplifyTreesParameter.ActualValue; }
60    }
61
62    public override void InitializeState() {
63      base.InitializeState();
64
65      hashToRow = new Dictionary<int, DataRow>();
66    }
67
68
69    [StorableHook(HookType.AfterDeserialization)]
70    private void AfterDeserialization() {
71      if (!Parameters.ContainsKey(SimplifyTreesParameterName)) {
72        Parameters.Add(new ValueLookupParameter<BoolValue>(SimplifyTreesParameterName, new BoolValue(false)));
73      }
74    }
75
76    public SymbolicDataAnalysisBuildingBlockAnalyzer() {
77      Parameters.Add(new ValueLookupParameter<IntValue>(MinimumSubtreeLengthParameterName, new IntValue(3)));
78      Parameters.Add(new ValueLookupParameter<BoolValue>(SimplifyTreesParameterName, new BoolValue(false)));
79    }
80
81    private SymbolicDataAnalysisBuildingBlockAnalyzer(SymbolicDataAnalysisBuildingBlockAnalyzer original, Cloner cloner) : base(original, cloner) {
82    }
83
84    public override IDeepCloneable Clone(Cloner cloner) {
85      return new SymbolicDataAnalysisBuildingBlockAnalyzer(this, cloner);
86    }
87
88    public override IOperation Apply() {
89      DataTable dt;
90
91      if (!ResultCollection.ContainsKey(BuildingBlocksResultName)) {
92        dt = new DataTable(BuildingBlocksResultName);
93        ResultCollection.Add(new Result(BuildingBlocksResultName, dt));
94      } else {
95        dt = (DataTable)ResultCollection[BuildingBlocksResultName].Value;
96      }
97
98      var minLength = MinimumSubtreeLength.Value - 1; // -1 because the HashNode.Size property returns the size without current node (-1)
99      var simplify = SimplifyTrees.Value;
100
101      var expressions = new Dictionary<int, string>();
102      var expressionCounts = new Dictionary<int, int>();
103
104      int totalCount = 0; // total number of subtrees examined
105      foreach (var tree in SymbolicExpressionTree) {
106        var hashNodes = tree.Root.GetSubtree(0).GetSubtree(0).MakeNodes();
107        var simplified = simplify ? hashNodes.Simplify() : hashNodes.Sort();
108
109        for (int i = 0; i < simplified.Length; i++) {
110          HashNode<ISymbolicExpressionTreeNode> s = simplified[i];
111          if (s.IsChild || s.Size < minLength) {
112            continue;
113          }
114          ++totalCount;
115          var hash = s.CalculatedHashValue;
116          if (expressions.TryGetValue(hash, out string str)) {
117            expressionCounts[hash]++;
118          } else {
119            // set constant and weight values so the tree is formatted nicely by the formatter
120            var nodes = new HashNode<ISymbolicExpressionTreeNode>[1 + s.Size];
121            Array.Copy(simplified, i - s.Size, nodes, 0, nodes.Length);
122            var subtree = nodes.ToSubtree();
123
124            foreach (var node in subtree.IterateNodesPostfix()) {
125              if (node is ConstantTreeNode constantTreeNode) {
126                constantTreeNode.Value = 0;
127              } else if (node is VariableTreeNode variableTreeNode) {
128                variableTreeNode.Weight = 1;
129              }
130            }
131
132            expressions[hash] = formatter.Format(subtree);
133            expressionCounts[hash] = 1;
134          }
135        }
136      }
137
138      var mostCommon = expressionCounts.OrderByDescending(x => x.Value).Take(10).ToList();
139      var mostCommonLabels = mostCommon.Select(x => expressions[x.Key]).ToList();
140
141      foreach (var t in hashToRow) {
142        var hash = t.Key;
143        var row = t.Value;
144
145        if (expressionCounts.TryGetValue(hash, out int count)) {
146          row.Values.Add((double)count / totalCount);
147        } else {
148          row.Values.Add(0);
149        }
150      }
151
152      var nValues = dt.Rows.Any() ? dt.Rows.Max(x => x.Values.Count) : 0;
153
154      for (int i = 0; i < mostCommon.Count; ++i) {
155        var hash = mostCommon[i].Key;
156        var count = mostCommon[i].Value;
157
158        if (hashToRow.ContainsKey(hash)) {
159          continue;
160        }
161        var label = mostCommonLabels[i];
162        var row = new DataRow(label) { VisualProperties = { StartIndexZero = true } };
163        // pad with zeroes
164        for (int j = 0; j < nValues - 1; ++j) {
165          row.Values.Add(0);
166        }
167        row.Values.Add((double)count / totalCount);
168        dt.Rows.Add(row);
169        hashToRow[hash] = row;
170      }
171      return base.Apply();
172    }
173  }
174}
Note: See TracBrowser for help on using the repository browser.