Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Hashing/SymbolicExpressionTreeHash.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: 11.3 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.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
25using static HeuristicLab.Problems.DataAnalysis.Symbolic.SymbolicExpressionHashExtensions;
26
27namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
28  public static class SymbolicExpressionTreeHash {
29    private static readonly Addition add = new Addition();
30    private static readonly Subtraction sub = new Subtraction();
31    private static readonly Multiplication mul = new Multiplication();
32    private static readonly Division div = new Division();
33    private static readonly Logarithm log = new Logarithm();
34    private static readonly Exponential exp = new Exponential();
35    private static readonly Sine sin = new Sine();
36    private static readonly Cosine cos = new Cosine();
37    private static readonly Constant constant = new Constant();
38
39    private static readonly ISymbolicExpressionTreeNodeComparer comparer = new SymbolicExpressionTreeNodeComparer();
40
41    public static int ComputeHash(this ISymbolicExpressionTree tree) {
42      return ComputeHash(tree.Root.GetSubtree(0).GetSubtree(0));
43    }
44
45    // compute node hashes without sorting the arguments
46    public static Dictionary<ISymbolicExpressionTreeNode, int> ComputeNodeHashes(this ISymbolicExpressionTree tree) {
47      var root = tree.Root.GetSubtree(0).GetSubtree(0);
48      var nodes = root.MakeNodes();
49      nodes.UpdateNodeSizes();
50
51      for (int i = 0; i < nodes.Length; ++i) {
52        if (nodes[i].IsChild)
53          continue;
54        nodes[i].CalculatedHashValue = nodes.ComputeHash(i);
55      }
56      return nodes.ToDictionary(x => x.Data, x => x.CalculatedHashValue);
57    }
58
59    public static int ComputeHash(this ISymbolicExpressionTreeNode treeNode) {
60      var hashNodes = treeNode.MakeNodes();
61      var simplified = hashNodes.Simplify();
62      return ComputeHash(simplified);
63    }
64
65    public static int ComputeHash(this HashNode<ISymbolicExpressionTreeNode>[] nodes) {
66      int hash = 1315423911;
67      foreach (var node in nodes)
68        hash ^= (hash << 5) + node.CalculatedHashValue + (hash >> 2);
69      return hash;
70    }
71
72    public static HashNode<ISymbolicExpressionTreeNode> ToHashNode(this ISymbolicExpressionTreeNode node) {
73      var symbol = node.Symbol;
74      var name = symbol.Name;
75      if (symbol is Variable) {
76        var variableTreeNode = (VariableTreeNode)node;
77        name = variableTreeNode.VariableName;
78      }
79      var hash = name.GetHashCode();
80      var hashNode = new HashNode<ISymbolicExpressionTreeNode>(comparer) {
81        Data = node,
82        Arity = node.SubtreeCount,
83        Size = node.SubtreeCount,
84        IsCommutative = node.Symbol is Addition || node.Symbol is Multiplication,
85        Enabled = true,
86        HashValue = hash,
87        CalculatedHashValue = hash
88      };
89      if (symbol is Addition) {
90        hashNode.Simplify = SimplifyAddition;
91      } else if (symbol is Multiplication) {
92        hashNode.Simplify = SimplifyMultiplication;
93      } else if (symbol is Division) {
94        hashNode.Simplify = SimplifyDivision;
95      } else if (symbol is Logarithm || symbol is Exponential || symbol is Sine || symbol is Cosine) {
96        hashNode.Simplify = SimplifyUnaryNode;
97      } else if (symbol is Subtraction) {
98        hashNode.Simplify = SimplifyBinaryNode;
99      }
100      return hashNode;
101    }
102
103    public static HashNode<ISymbolicExpressionTreeNode>[] MakeNodes(this ISymbolicExpressionTreeNode node) {
104      return node.IterateNodesPostfix().Select(ToHashNode).ToArray().UpdateNodeSizes();
105    }
106
107    #region parse a nodes array back into a tree
108    public static ISymbolicExpressionTree ToTree(this HashNode<ISymbolicExpressionTreeNode>[] nodes) {
109      var root = new ProgramRootSymbol().CreateTreeNode();
110      var start = new StartSymbol().CreateTreeNode();
111      root.AddSubtree(start);
112      start.AddSubtree(nodes.ToSubtree());
113      return new SymbolicExpressionTree(root);
114    }
115
116    public static ISymbolicExpressionTreeNode ToSubtree(this HashNode<ISymbolicExpressionTreeNode>[] nodes) {
117      var treeNodes = nodes.Select(x => x.Data.Symbol.CreateTreeNode()).ToArray();
118
119      for (int i = nodes.Length - 1; i >= 0; --i) {
120        var node = nodes[i];
121
122        if (node.IsChild) {
123          if (node.Data is VariableTreeNode variable) {
124            var variableTreeNode = (VariableTreeNode)treeNodes[i];
125            variableTreeNode.VariableName = variable.VariableName;
126            variableTreeNode.Weight = variable.Weight;
127          } else if (node.Data is ConstantTreeNode @const) {
128            var constantTreeNode = (ConstantTreeNode)treeNodes[i];
129            constantTreeNode.Value = @const.Value;
130          }
131          continue;
132        }
133
134        var treeNode = treeNodes[i];
135
136        foreach (var j in nodes.IterateChildren(i)) {
137          treeNode.AddSubtree(treeNodes[j]);
138        }
139      }
140
141      return treeNodes.Last();
142    }
143
144    private static T CreateTreeNode<T>(this ISymbol symbol) where T : class, ISymbolicExpressionTreeNode {
145      return (T)symbol.CreateTreeNode();
146    }
147    #endregion
148
149    #region tree simplification
150    // these simplification methods rely on the assumption that child nodes of the current node have already been simplified
151    // (in other words simplification should be applied in a bottom-up fashion)
152    public static ISymbolicExpressionTree Simplify(ISymbolicExpressionTree tree) {
153      var root = tree.Root.GetSubtree(0).GetSubtree(0);
154      var nodes = root.MakeNodes();
155      var simplified = nodes.Simplify();
156      return simplified.ToTree();
157    }
158
159    public static void SimplifyAddition(HashNode<ISymbolicExpressionTreeNode>[] nodes, int i) {
160      // simplify additions of terms by eliminating terms with the same symbol and hash
161      var children = nodes.IterateChildren(i);
162
163      var curr = children[0];
164      var node = nodes[i];
165
166      foreach (var j in children.Skip(1)) {
167        if (nodes[j] == nodes[curr]) {
168          for (int k = j - nodes[j].Size; k <= j; ++k) {
169            nodes[k].Enabled = false;
170          }
171          node.Arity--;
172        } else {
173          curr = j;
174        }
175      }
176      if (node.Arity == 1) { // if the arity is 1 we don't need the addition node at all
177        node.Enabled = false;
178      }
179    }
180
181    // simplify multiplications by reducing constants and div terms 
182    public static void SimplifyMultiplication(HashNode<ISymbolicExpressionTreeNode>[] nodes, int i) {
183      var node = nodes[i];
184      var children = nodes.IterateChildren(i);
185
186      for (int j = 0; j < children.Length; ++j) {
187        var c = children[j];
188        var child = nodes[c];
189
190        if (!child.Enabled)
191          continue;
192
193        var symbol = child.Data.Symbol;
194        if (symbol is Constant) {
195          for (int k = j + 1; k < children.Length; ++k) {
196            var d = children[k];
197            if (nodes[d].Data.Symbol is Constant) {
198              nodes[d].Enabled = false;
199              node.Arity--;
200            } else {
201              break;
202            }
203          }
204        } else if (symbol is Division) {
205          var div = nodes[c];
206          var denominator =
207            div.Arity == 1 ?
208            nodes[c - 1] :                    // 1 / x is expressed as div(x) (with a single child)
209            nodes[c - nodes[c - 1].Size - 2]; // assume division always has arity 1 or 2
210
211          foreach (var d in children) {
212            if (nodes[d].Enabled && nodes[d] == denominator) {
213              nodes[c].Enabled = nodes[d].Enabled = denominator.Enabled = false;
214              node.Arity -= 2; // matching child + division node
215              break;
216            }
217          }
218        }
219
220        if (node.Arity == 0) { // if everything is simplified this node becomes constant
221          var constantTreeNode = constant.CreateTreeNode<ConstantTreeNode>();
222          constantTreeNode.Value = 1;
223          nodes[i] = constantTreeNode.ToHashNode();
224        } else if (node.Arity == 1) { // when i have only 1 arg left i can skip this node
225          node.Enabled = false;
226        }
227      }
228    }
229
230    public static void SimplifyDivision(HashNode<ISymbolicExpressionTreeNode>[] nodes, int i) {
231      var node = nodes[i];
232      var children = nodes.IterateChildren(i);
233
234      if (children.All(x => nodes[x].Data.Symbol is Constant)) {
235        var v = ((ConstantTreeNode)nodes[children.First()].Data).Value;
236        if (node.Arity == 1) {
237          v = 1 / v;
238        } else if (node.Arity > 1) {
239          foreach (var j in children.Skip(1)) {
240            v /= ((ConstantTreeNode)nodes[j].Data).Value;
241          }
242        }
243        var constantTreeNode = constant.CreateTreeNode<ConstantTreeNode>();
244        constantTreeNode.Value = v;
245        nodes[i] = constantTreeNode.ToHashNode();
246        return;
247      }
248
249      var nominator = nodes[children[0]];
250      foreach (var j in children.Skip(1)) {
251        var denominator = nodes[j];
252        if (nominator == denominator) {
253          // disable all the children of the division node (nominator and children + denominator and children)
254          nominator.Enabled = denominator.Enabled = false;
255          node.Arity -= 2; // nominator + denominator
256        }
257        if (node.Arity == 0) {
258          var constantTreeNode = constant.CreateTreeNode<ConstantTreeNode>();
259          constantTreeNode.Value = 1; // x / x = 1
260          nodes[i] = constantTreeNode.ToHashNode();
261        }
262      }
263    }
264
265    public static void SimplifyUnaryNode(HashNode<ISymbolicExpressionTreeNode>[] nodes, int i) {
266      // check if the child of the unary node is a constant, then the whole node can be simplified
267      var parent = nodes[i];
268      var child = nodes[i - 1];
269
270      var parentSymbol = parent.Data.Symbol;
271      var childSymbol = child.Data.Symbol;
272
273      if (childSymbol is Constant) {
274        nodes[i].Enabled = false;
275      } else if ((parentSymbol is Exponential && childSymbol is Logarithm) || (parentSymbol is Logarithm && childSymbol is Exponential)) {
276        child.Enabled = parent.Enabled = false;
277      }
278    }
279
280    public static void SimplifyBinaryNode(HashNode<ISymbolicExpressionTreeNode>[] nodes, int i) {
281      var children = nodes.IterateChildren(i);
282      if (children.All(x => nodes[x].Data.Symbol is Constant)) {
283        foreach (var j in children) {
284          nodes[j].Enabled = false;
285        }
286        nodes[i] = constant.CreateTreeNode().ToHashNode();
287      }
288    }
289    #endregion
290  }
291}
Note: See TracBrowser for help on using the repository browser.