Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Hashing/SymbolicExpressionTreeHash.cs @ 16252

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

#2950: Minor refactor of HashExtensions.cs to allow method chaining. Minor refactor in SymbolicExpressionTreeHash.cs.

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