Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Hashing/HashExtensions.cs @ 16261

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

#2950: Fix bug in HashUtil.ToByteArray(). Improve hashing performance (10-15% gain) by avoiding array allocations for child node indices.

File size: 7.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;
23using System.Collections.Generic;
24
25namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
26  public static class SymbolicExpressionHashExtensions {
27    public sealed class HashNode<T> : IComparable<HashNode<T>>, IEquatable<HashNode<T>> where T : class {
28      public T Data;
29      public int Arity;
30      public int Size;
31      public bool IsCommutative;
32
33      public bool Enabled;
34      public int HashValue;           // the initial (fixed) hash value for this individual node/data
35      public int CalculatedHashValue; // the calculated hash value (taking into account the children hash values)
36
37      public Action<HashNode<T>[], int> Simplify;
38      public IComparer<T> Comparer;
39
40      public bool IsChild => Arity == 0;
41
42      public HashNode(IComparer<T> comparer) {
43        Comparer = comparer;
44      }
45
46      private HashNode() { }
47
48      public int CompareTo(HashNode<T> other) {
49        var res = Comparer.Compare(Data, other.Data);
50        return res == 0 ? CalculatedHashValue.CompareTo(other.CalculatedHashValue) : res;
51      }
52
53      public override string ToString() {
54        return $"{Data} {Arity} {Size} {CalculatedHashValue} {Enabled}";
55      }
56
57      public bool Equals(HashNode<T> other) {
58        return CalculatedHashValue.Equals(other.CalculatedHashValue);
59      }
60
61      public override bool Equals(object obj) {
62        var other = obj as HashNode<T>;
63        if (other != null)
64          return Equals(other);
65        return base.Equals(obj);
66      }
67
68      public override int GetHashCode() {
69        return CalculatedHashValue;
70      }
71
72      public static bool operator ==(HashNode<T> a, HashNode<T> b) {
73        return a.Equals(b);
74      }
75
76      public static bool operator !=(HashNode<T> a, HashNode<T> b) {
77        return !a.Equals(b);
78      }
79    }
80
81    public static int ComputeHash<T>(this HashNode<T>[] nodes, int i) where T : class {
82      var node = nodes[i];
83      var hashes = new int[node.Arity + 1];
84      for (int j = i - 1, k = 0; k < node.Arity; j -= 1 + nodes[j].Size, k++) {
85        hashes[k] = nodes[j].CalculatedHashValue;
86      }
87      hashes[node.Arity] = node.HashValue;
88      return HashUtil.JSHash(hashes);
89    }
90
91    public static HashNode<T>[] Simplify<T>(this HashNode<T>[] nodes) where T : class {
92      var reduced = nodes.UpdateNodeSizes().Reduce().Sort();
93
94      for (int i = 0; i < reduced.Length; ++i) {
95        var node = reduced[i];
96        if (node.IsChild) {
97          continue;
98        }
99        node.Simplify?.Invoke(reduced, i);
100      }
101      // detect if anything was simplified
102      var count = 0;
103      foreach (var node in reduced) {
104        if (!node.Enabled) { ++count; }
105      }
106      if (count == 0) {
107        return reduced;
108      }
109
110      var simplified = new HashNode<T>[reduced.Length - count];
111      int j = 0;
112      foreach (var node in reduced) {
113        if (node.Enabled) {
114          simplified[j++] = node;
115        }
116      }
117      return simplified.UpdateNodeSizes().Reduce().Sort();
118    }
119
120    public static HashNode<T>[] Sort<T>(this HashNode<T>[] nodes) where T : class {
121      int sort(int a, int b) => nodes[a].CompareTo(nodes[b]);
122
123      for (int i = 0; i < nodes.Length; ++i) {
124        var node = nodes[i];
125
126        if (node.IsChild) {
127          continue;
128        }
129
130        if (node.IsCommutative) { // only sort when the argument order does not matter
131          var arity = node.Arity;
132          var size = node.Size;
133
134          if (arity == size) { // all child nodes are terminals
135            Array.Sort(nodes, i - size, size);
136          } else { // i have some non-terminal children
137            var sorted = new HashNode<T>[size];
138            var indices = new int[node.Arity];
139            for (int j = i - 1, k = 0; k < node.Arity; j -= 1 + nodes[j].Size, ++k) {
140              indices[k] = j;
141            }
142            Array.Sort(indices, sort);
143
144            int idx = 0;
145            foreach (var j in indices) {
146              var child = nodes[j];
147              if (!child.IsChild) { // must copy complete subtree
148                Array.Copy(nodes, j - child.Size, sorted, idx, child.Size);
149                idx += child.Size;
150              }
151              sorted[idx++] = nodes[j];
152            }
153            Array.Copy(sorted, 0, nodes, i - size, size);
154          }
155        }
156        node.CalculatedHashValue = nodes.ComputeHash(i);
157      }
158      return nodes;
159    }
160
161    /// <summary>
162    /// Get a function node's child indicest
163    /// </summary>
164    /// <typeparam name="T">The data type encapsulated by a hash node</typeparam>
165    /// <param name="nodes">An array of hash nodes with up-to-date node sizes</param>
166    /// <param name="i">The index in the array of hash nodes of the node whose children we want to iterate</param>
167    /// <returns>An array containing child indices</returns>
168    public static int[] IterateChildren<T>(this HashNode<T>[] nodes, int i) where T : class {
169      var node = nodes[i];
170      var arity = node.Arity;
171      var children = new int[arity];
172      var idx = i - 1;
173      for (int j = 0; j < arity; ++j) {
174        children[j] = idx;
175        idx -= 1 + nodes[idx].Size;
176      }
177      return children;
178    }
179
180    public static HashNode<T>[] UpdateNodeSizes<T>(this HashNode<T>[] nodes) where T : class {
181      for (int i = 0; i < nodes.Length; ++i) {
182        var node = nodes[i];
183        if (node.IsChild) {
184          node.Size = 0;
185          continue;
186        }
187        node.Size = node.Arity;
188
189        for (int j = i - 1, k = 0; k < node.Arity; j -= 1 + nodes[j].Size, ++k) {
190          node.Size += nodes[j].Size;
191        }
192      }
193      return nodes;
194    }
195
196    private static HashNode<T>[] Reduce<T>(this HashNode<T>[] nodes) where T : class {
197      int count = 0;
198      for (int i = 0; i < nodes.Length; ++i) {
199        var node = nodes[i];
200        if (node.IsChild || !node.IsCommutative) {
201          continue;
202        }
203
204        var arity = node.Arity;
205        for (int j = i - 1, k = 0; k < arity; j -= 1 + nodes[j].Size, ++k) {
206          if (node.HashValue == nodes[j].HashValue) {
207            nodes[j].Enabled = false;
208            node.Arity += nodes[j].Arity - 1;
209            ++count;
210          }
211        }
212      }
213      if (count == 0)
214        return nodes;
215
216      var reduced = new HashNode<T>[nodes.Length - count];
217      var idx = 0;
218      foreach (var node in nodes) {
219        if (node.Enabled) { reduced[idx++] = node; }
220      }
221      return reduced.UpdateNodeSizes();
222    }
223  }
224}
Note: See TracBrowser for help on using the repository browser.