Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2950: Rename HashNode.IsChild property to IsLeaf

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