Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2950: Fix typo in ComputeAverageSimilarity

File size: 13.9 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.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 ulong ComputeHash(this ISymbolicExpressionTree tree) {
42      return ComputeHash(tree.Root.GetSubtree(0).GetSubtree(0));
43    }
44
45    public static double ComputeSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, bool simplify = false) {
46      return ComputeSimilarity(t1.Root.GetSubtree(0).GetSubtree(0), t2.Root.GetSubtree(0).GetSubtree(0), simplify);
47    }
48
49    public static double ComputeSimilarity(ISymbolicExpressionTreeNode t1, ISymbolicExpressionTreeNode t2, bool simplify = false) {
50      HashNode<ISymbolicExpressionTreeNode>[] lhs;
51      HashNode<ISymbolicExpressionTreeNode>[] rhs;
52
53      ulong hashFunction(byte[] input) => HashUtil.DJBHash(input);
54
55      if (simplify) {
56        lhs = t1.MakeNodes().Simplify(hashFunction);
57        rhs = t2.MakeNodes().Simplify(hashFunction);
58      } else {
59        lhs = t1.MakeNodes().Sort(hashFunction); // sort calculates hash values
60        rhs = t2.MakeNodes().Sort(hashFunction);
61      }
62
63      var lh = lhs.Select(x => x.CalculatedHashValue).ToArray();
64      var rh = rhs.Select(x => x.CalculatedHashValue).ToArray();
65
66      Array.Sort(lh);
67      Array.Sort(rh);
68
69      return ComputeSimilarity(lh, rh);
70    }
71
72    // this will only work if lh and rh are sorted
73    private static double ComputeSimilarity(ulong[] lh, ulong[] rh) {
74      double count = 0;
75      for (int i = 0, j = 0; i < lh.Length && j < rh.Length;) {
76        var h1 = lh[i];
77        var h2 = rh[j];
78        if (h1 == h2) {
79          ++count;
80          ++i;
81          ++j;
82        } else if (h1 < h2) {
83          ++i;
84        } else if (h1 > h2) {
85          ++j;
86        }
87      }
88
89      return 2d * count / (lh.Length + rh.Length);
90    }
91
92    public static double ComputeAverageSimilarity(ISymbolicExpressionTree[] trees, bool simplify = false) {
93      var total = (double)trees.Length * (trees.Length - 1) / 2;
94      double avg = 0;
95      var hashes = new ulong[trees.Length][];
96      // build hash arrays
97      for (int i = 0; i < trees.Length; ++i) {
98        hashes[i] = (simplify ? trees[i].MakeNodes().Simplify(HashUtil.DJBHash) : trees[i].MakeNodes().Sort(HashUtil.DJBHash)).Select(x => x.CalculatedHashValue).ToArray();
99        Array.Sort(hashes[i]);
100      }
101      // compute similarity matrix
102      for (int i = 0; i < trees.Length - 1; ++i) {
103        for (int j = i + 1; j < trees.Length; ++j) {
104          avg += ComputeSimilarity(hashes[i], hashes[j]);
105        }
106      }
107      return avg / total;
108    }
109
110    public static double[,] ComputeSimilarityMatrix(ISymbolicExpressionTree[] trees, bool simplify = false) {
111      var sim = new double[trees.Length, trees.Length];
112      var hashes = new ulong[trees.Length][];
113      // build hash arrays
114      for (int i = 0; i < trees.Length; ++i) {
115        hashes[i] = (simplify ? trees[i].MakeNodes().Simplify(HashUtil.DJBHash) : trees[i].MakeNodes().Sort(HashUtil.DJBHash)).Select(x => x.CalculatedHashValue).ToArray();
116        Array.Sort(hashes[i]);
117      }
118      // compute similarity matrix
119      for (int i = 0; i < trees.Length - 1; ++i) {
120        for (int j = i + 1; j < trees.Length; ++j) {
121          sim[i, j] = sim[j, i] = ComputeSimilarity(hashes[i], hashes[j]);
122        }
123      }
124      return sim;
125    }
126
127    public static ulong ComputeHash(this ISymbolicExpressionTreeNode treeNode) {
128      ulong hashFunction(byte[] input) => HashUtil.JSHash(input);
129      var hashNodes = treeNode.MakeNodes();
130      var simplified = hashNodes.Simplify(hashFunction);
131      return simplified.Last().CalculatedHashValue;
132    }
133
134    public static HashNode<ISymbolicExpressionTreeNode> ToHashNode(this ISymbolicExpressionTreeNode node) {
135      var symbol = node.Symbol;
136      var name = symbol.Name;
137      if (symbol is Variable) {
138        var variableTreeNode = (VariableTreeNode)node;
139        name = variableTreeNode.VariableName;
140      }
141      var hash = (ulong)name.GetHashCode();
142      var hashNode = new HashNode<ISymbolicExpressionTreeNode>(comparer) {
143        Data = node,
144        Arity = node.SubtreeCount,
145        Size = node.SubtreeCount,
146        IsCommutative = node.Symbol is Addition || node.Symbol is Multiplication,
147        Enabled = true,
148        HashValue = hash,
149        CalculatedHashValue = hash
150      };
151      if (symbol is Addition) {
152        hashNode.Simplify = SimplifyAddition;
153      } else if (symbol is Multiplication) {
154        hashNode.Simplify = SimplifyMultiplication;
155      } else if (symbol is Division) {
156        hashNode.Simplify = SimplifyDivision;
157      } else if (symbol is Logarithm || symbol is Exponential || symbol is Sine || symbol is Cosine) {
158        hashNode.Simplify = SimplifyUnaryNode;
159      } else if (symbol is Subtraction) {
160        hashNode.Simplify = SimplifyBinaryNode;
161      }
162      return hashNode;
163    }
164
165    public static HashNode<ISymbolicExpressionTreeNode>[] MakeNodes(this ISymbolicExpressionTree tree) {
166      return MakeNodes(tree.Root.GetSubtree(0).GetSubtree(0));
167    }
168
169    public static HashNode<ISymbolicExpressionTreeNode>[] MakeNodes(this ISymbolicExpressionTreeNode node) {
170      return node.IterateNodesPostfix().Select(ToHashNode).ToArray().UpdateNodeSizes();
171    }
172
173    #region parse a nodes array back into a tree
174    public static ISymbolicExpressionTree ToTree(this HashNode<ISymbolicExpressionTreeNode>[] nodes) {
175      var root = new ProgramRootSymbol().CreateTreeNode();
176      var start = new StartSymbol().CreateTreeNode();
177      root.AddSubtree(start);
178      start.AddSubtree(nodes.ToSubtree());
179      return new SymbolicExpressionTree(root);
180    }
181
182    public static ISymbolicExpressionTreeNode ToSubtree(this HashNode<ISymbolicExpressionTreeNode>[] nodes) {
183      var treeNodes = nodes.Select(x => x.Data.Symbol.CreateTreeNode()).ToArray();
184
185      for (int i = nodes.Length - 1; i >= 0; --i) {
186        var node = nodes[i];
187
188        if (node.IsLeaf) {
189          if (node.Data is VariableTreeNode variable) {
190            var variableTreeNode = (VariableTreeNode)treeNodes[i];
191            variableTreeNode.VariableName = variable.VariableName;
192            variableTreeNode.Weight = variable.Weight;
193          } else if (node.Data is ConstantTreeNode @const) {
194            var constantTreeNode = (ConstantTreeNode)treeNodes[i];
195            constantTreeNode.Value = @const.Value;
196          }
197          continue;
198        }
199
200        var treeNode = treeNodes[i];
201
202        foreach (var j in nodes.IterateChildren(i)) {
203          treeNode.AddSubtree(treeNodes[j]);
204        }
205      }
206
207      return treeNodes.Last();
208    }
209
210    private static T CreateTreeNode<T>(this ISymbol symbol) where T : class, ISymbolicExpressionTreeNode {
211      return (T)symbol.CreateTreeNode();
212    }
213    #endregion
214
215    #region tree simplification
216    // these simplification methods rely on the assumption that child nodes of the current node have already been simplified
217    // (in other words simplification should be applied in a bottom-up fashion)
218    public static ISymbolicExpressionTree Simplify(ISymbolicExpressionTree tree) {
219      ulong hashFunction(byte[] bytes) => HashUtil.JSHash(bytes);
220      var root = tree.Root.GetSubtree(0).GetSubtree(0);
221      var nodes = root.MakeNodes();
222      var simplified = nodes.Simplify(hashFunction);
223      return simplified.ToTree();
224    }
225
226    public static void SimplifyAddition(HashNode<ISymbolicExpressionTreeNode>[] nodes, int i) {
227      // simplify additions of terms by eliminating terms with the same symbol and hash
228      var children = nodes.IterateChildren(i);
229
230      var curr = children[0];
231      var node = nodes[i];
232
233      foreach (var j in children.Skip(1)) {
234        if (nodes[j] == nodes[curr]) {
235          for (int k = j - nodes[j].Size; k <= j; ++k) {
236            nodes[k].Enabled = false;
237          }
238          node.Arity--;
239        } else {
240          curr = j;
241        }
242      }
243      if (node.Arity == 1) { // if the arity is 1 we don't need the addition node at all
244        node.Enabled = false;
245      }
246    }
247
248    // simplify multiplications by reducing constants and div terms 
249    public static void SimplifyMultiplication(HashNode<ISymbolicExpressionTreeNode>[] nodes, int i) {
250      var node = nodes[i];
251      var children = nodes.IterateChildren(i);
252
253      for (int j = 0; j < children.Length; ++j) {
254        var c = children[j];
255        var child = nodes[c];
256
257        if (!child.Enabled)
258          continue;
259
260        var symbol = child.Data.Symbol;
261        if (symbol is Constant) {
262          for (int k = j + 1; k < children.Length; ++k) {
263            var d = children[k];
264            if (nodes[d].Data.Symbol is Constant) {
265              nodes[d].Enabled = false;
266              node.Arity--;
267            } else {
268              break;
269            }
270          }
271        } else if (symbol is Division) {
272          var div = nodes[c];
273          var denominator =
274            div.Arity == 1 ?
275            nodes[c - 1] :                    // 1 / x is expressed as div(x) (with a single child)
276            nodes[c - nodes[c - 1].Size - 2]; // assume division always has arity 1 or 2
277
278          foreach (var d in children) {
279            if (nodes[d].Enabled && nodes[d] == denominator) {
280              nodes[c].Enabled = nodes[d].Enabled = denominator.Enabled = false;
281              node.Arity -= 2; // matching child + division node
282              break;
283            }
284          }
285        }
286
287        if (node.Arity == 0) { // if everything is simplified this node becomes constant
288          var constantTreeNode = constant.CreateTreeNode<ConstantTreeNode>();
289          constantTreeNode.Value = 1;
290          nodes[i] = constantTreeNode.ToHashNode();
291        } else if (node.Arity == 1) { // when i have only 1 arg left i can skip this node
292          node.Enabled = false;
293        }
294      }
295    }
296
297    public static void SimplifyDivision(HashNode<ISymbolicExpressionTreeNode>[] nodes, int i) {
298      var node = nodes[i];
299      var children = nodes.IterateChildren(i);
300
301      if (children.All(x => nodes[x].Data.Symbol is Constant)) {
302        var v = ((ConstantTreeNode)nodes[children.First()].Data).Value;
303        if (node.Arity == 1) {
304          v = 1 / v;
305        } else if (node.Arity > 1) {
306          foreach (var j in children.Skip(1)) {
307            v /= ((ConstantTreeNode)nodes[j].Data).Value;
308          }
309        }
310        var constantTreeNode = constant.CreateTreeNode<ConstantTreeNode>();
311        constantTreeNode.Value = v;
312        nodes[i] = constantTreeNode.ToHashNode();
313        return;
314      }
315
316      var nominator = nodes[children[0]];
317      foreach (var j in children.Skip(1)) {
318        var denominator = nodes[j];
319        if (nominator == denominator) {
320          // disable all the children of the division node (nominator and children + denominator and children)
321          nominator.Enabled = denominator.Enabled = false;
322          node.Arity -= 2; // nominator + denominator
323        }
324        if (node.Arity == 0) {
325          var constantTreeNode = constant.CreateTreeNode<ConstantTreeNode>();
326          constantTreeNode.Value = 1; // x / x = 1
327          nodes[i] = constantTreeNode.ToHashNode();
328        }
329      }
330    }
331
332    public static void SimplifyUnaryNode(HashNode<ISymbolicExpressionTreeNode>[] nodes, int i) {
333      // check if the child of the unary node is a constant, then the whole node can be simplified
334      var parent = nodes[i];
335      var child = nodes[i - 1];
336
337      var parentSymbol = parent.Data.Symbol;
338      var childSymbol = child.Data.Symbol;
339
340      if (childSymbol is Constant) {
341        nodes[i].Enabled = false;
342      } else if ((parentSymbol is Exponential && childSymbol is Logarithm) || (parentSymbol is Logarithm && childSymbol is Exponential)) {
343        child.Enabled = parent.Enabled = false;
344      }
345    }
346
347    public static void SimplifyBinaryNode(HashNode<ISymbolicExpressionTreeNode>[] nodes, int i) {
348      var children = nodes.IterateChildren(i);
349      if (children.All(x => nodes[x].Data.Symbol is Constant)) {
350        foreach (var j in children) {
351          nodes[j].Enabled = false;
352        }
353        nodes[i] = constant.CreateTreeNode().ToHashNode();
354      }
355    }
356    #endregion
357  }
358}
Note: See TracBrowser for help on using the repository browser.