Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Hashing/HashExtensions.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: 7.4 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 ulong HashValue;           // the initial (fixed) hash value for this individual node/data
35      public ulong 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 IsLeaf => 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        return Data.GetHashCode();
71      }
72
73      public static bool operator ==(HashNode<T> a, HashNode<T> b) {
74        return a.Equals(b);
75      }
76
77      public static bool operator !=(HashNode<T> a, HashNode<T> b) {
78        return !a.Equals(b);
79      }
80    }
81
82    public static ulong ComputeHash<T>(this HashNode<T>[] nodes, int i) where T : class {
83      var node = nodes[i];
84      var hashes = new ulong[node.Arity + 1];
85      for (int j = i - 1, k = 0; k < node.Arity; j -= 1 + nodes[j].Size, k++) {
86        hashes[k] = nodes[j].CalculatedHashValue;
87      }
88      hashes[node.Arity] = node.HashValue;
89      return HashUtil.JSHash(hashes);
90    }
91
92    public static HashNode<T>[] Simplify<T>(this HashNode<T>[] nodes) where T : class {
93      var reduced = nodes.UpdateNodeSizes().Reduce().Sort();
94
95      for (int i = 0; i < reduced.Length; ++i) {
96        var node = reduced[i];
97        if (node.IsLeaf) {
98          continue;
99        }
100        node.Simplify?.Invoke(reduced, i);
101      }
102      // detect if anything was simplified
103      var count = 0;
104      foreach (var node in reduced) {
105        if (!node.Enabled) { ++count; }
106      }
107      if (count == 0) {
108        return reduced;
109      }
110
111      var simplified = new HashNode<T>[reduced.Length - count];
112      int j = 0;
113      foreach (var node in reduced) {
114        if (node.Enabled) {
115          simplified[j++] = node;
116        }
117      }
118      return simplified.UpdateNodeSizes().Reduce().Sort();
119    }
120
121    public static HashNode<T>[] Sort<T>(this HashNode<T>[] nodes) where T : class {
122      int sort(int a, int b) => nodes[a].CompareTo(nodes[b]);
123
124      for (int i = 0; i < nodes.Length; ++i) {
125        var node = nodes[i];
126
127        if (node.IsLeaf) {
128          continue;
129        }
130
131        if (node.IsCommutative) { // only sort when the argument order does not matter
132          var arity = node.Arity;
133          var size = node.Size;
134
135          if (arity == size) { // all child nodes are terminals
136            Array.Sort(nodes, i - size, size);
137          } else { // i have some non-terminal children
138            var sorted = new HashNode<T>[size];
139            var indices = new int[node.Arity];
140            for (int j = i - 1, k = 0; k < node.Arity; j -= 1 + nodes[j].Size, ++k) {
141              indices[k] = j;
142            }
143            Array.Sort(indices, sort);
144
145            int idx = 0;
146            foreach (var j in indices) {
147              var child = nodes[j];
148              if (!child.IsLeaf) { // must copy complete subtree
149                Array.Copy(nodes, j - child.Size, sorted, idx, child.Size);
150                idx += child.Size;
151              }
152              sorted[idx++] = nodes[j];
153            }
154            Array.Copy(sorted, 0, nodes, i - size, size);
155          }
156        }
157        node.CalculatedHashValue = nodes.ComputeHash(i);
158      }
159      return nodes;
160    }
161
162    /// <summary>
163    /// Get a function node's child indicest
164    /// </summary>
165    /// <typeparam name="T">The data type encapsulated by a hash node</typeparam>
166    /// <param name="nodes">An array of hash nodes with up-to-date node sizes</param>
167    /// <param name="i">The index in the array of hash nodes of the node whose children we want to iterate</param>
168    /// <returns>An array containing child indices</returns>
169    public static int[] IterateChildren<T>(this HashNode<T>[] nodes, int i) where T : class {
170      var node = nodes[i];
171      var arity = node.Arity;
172      var children = new int[arity];
173      var idx = i - 1;
174      for (int j = 0; j < arity; ++j) {
175        children[j] = idx;
176        idx -= 1 + nodes[idx].Size;
177      }
178      return children;
179    }
180
181    public static HashNode<T>[] UpdateNodeSizes<T>(this HashNode<T>[] nodes) where T : class {
182      for (int i = 0; i < nodes.Length; ++i) {
183        var node = nodes[i];
184        if (node.IsLeaf) {
185          node.Size = 0;
186          continue;
187        }
188        node.Size = node.Arity;
189
190        for (int j = i - 1, k = 0; k < node.Arity; j -= 1 + nodes[j].Size, ++k) {
191          node.Size += nodes[j].Size;
192        }
193      }
194      return nodes;
195    }
196
197    private static HashNode<T>[] Reduce<T>(this HashNode<T>[] nodes) where T : class {
198      int count = 0;
199      for (int i = 0; i < nodes.Length; ++i) {
200        var node = nodes[i];
201        if (node.IsLeaf || !node.IsCommutative) {
202          continue;
203        }
204
205        var arity = node.Arity;
206        for (int j = i - 1, k = 0; k < arity; j -= 1 + nodes[j].Size, ++k) {
207          if (node.HashValue == nodes[j].HashValue) {
208            nodes[j].Enabled = false;
209            node.Arity += nodes[j].Arity - 1;
210            ++count;
211          }
212        }
213      }
214      if (count == 0)
215        return nodes;
216
217      var reduced = new HashNode<T>[nodes.Length - count];
218      var idx = 0;
219      foreach (var node in nodes) {
220        if (node.Enabled) { reduced[idx++] = node; }
221      }
222      return reduced.UpdateNodeSizes();
223    }
224  }
225}
Note: See TracBrowser for help on using the repository browser.