Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Hashing/HashExtensions.cs @ 17099

Last change on this file since 17099 was 17099, checked in by mkommend, 5 years ago

#2950: Merged 16979, 16980, 16983 into stable.

File size: 8.0 KB
RevLine 
[16218]1#region License Information
2/* HeuristicLab
[17097]3 * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[16218]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;
[17099]23using System.Linq;
[16218]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;
[17090]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)
[16218]36
[17090]37      public delegate void SimplifyAction(ref HashNode<T>[] nodes, int i);
38      public SimplifyAction Simplify;
39
[17099]40      //public IComparer<T> Comparer;
[16218]41
[17090]42      public bool IsLeaf => Arity == 0;
[16218]43
[17099]44      //public HashNode(IComparer<T> comparer) {
45      //  Comparer = comparer;
46      //}
[16218]47
[17099]48      //public HashNode() { }
[16218]49
50      public int CompareTo(HashNode<T> other) {
[17099]51        return CalculatedHashValue.CompareTo(other.CalculatedHashValue);
[16218]52      }
53
54      public override string ToString() {
55        return $"{Data} {Arity} {Size} {CalculatedHashValue} {Enabled}";
56      }
57
58      public bool Equals(HashNode<T> other) {
59        return CalculatedHashValue.Equals(other.CalculatedHashValue);
60      }
61
62      public override bool Equals(object obj) {
63        var other = obj as HashNode<T>;
64        if (other != null)
65          return Equals(other);
66        return base.Equals(obj);
67      }
68
69      public override int GetHashCode() {
[17090]70        return (int)CalculatedHashValue;
[16218]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
[17090]82    public static ulong ComputeHash<T>(this HashNode<T>[] nodes, int i, Func<byte[], ulong> hashFunction) where T : class {
[16218]83      var node = nodes[i];
[17090]84      const int size = sizeof(ulong);
85      var hashes = new ulong[node.Arity + 1];
86      var bytes = new byte[(node.Arity + 1) * size];
87
88      for (int j = i - 1, k = 0; k < node.Arity; ++k, j -= 1 + nodes[j].Size) {
89        hashes[k] = nodes[j].CalculatedHashValue;
[16218]90      }
[17090]91      hashes[node.Arity] = node.HashValue;
92      Buffer.BlockCopy(hashes, 0, bytes, 0, bytes.Length);
93      return hashFunction(bytes);
[16218]94    }
95
[17090]96    // set the enabled state for the whole subtree rooted at this node
97    public static void SetEnabled<T>(this HashNode<T>[] nodes, int i, bool enabled) where T : class {
98      nodes[i].Enabled = enabled;
99      for (int j = i - nodes[i].Size; j < i; ++j)
100        nodes[j].Enabled = enabled;
101    }
[16218]102
[17090]103    public static HashNode<T>[] Simplify<T>(this HashNode<T>[] nodes, Func<byte[], ulong> hashFunction) where T : class {
[17099]104      bool simplified = false;
105      nodes = nodes.UpdateNodeSizes().Reduce().Sort(hashFunction);
106      do {
107        if (simplified) {
108          simplified = false;
109          nodes = nodes.Where(x => x.Enabled).ToArray().UpdateNodeSizes().Reduce().Sort(hashFunction);
[16218]110        }
111
[17099]112        for (int i = 0; i < nodes.Length; ++i) {
113          var node = nodes[i];
114          if (node.IsLeaf) {
115            continue;
116          }
117          node.Simplify?.Invoke(ref nodes, i);
118          for (int j = i - node.Size; j < i; ++j) {
119            // detect if anything was simplified
120            if (!nodes[j].Enabled) {
121              simplified = true;
122              break;
123            }
124          }
[16218]125        }
[17099]126      } while (simplified);
127      return nodes.UpdateNodeSizes().Sort(hashFunction);
[16218]128    }
129
[17090]130    public static HashNode<T>[] Sort<T>(this HashNode<T>[] nodes, Func<byte[], ulong> hashFunction) where T : class {
131      int sort(int a, int b) => nodes[a].CompareTo(nodes[b]);
132
[16218]133      for (int i = 0; i < nodes.Length; ++i) {
134        var node = nodes[i];
135
[17090]136        if (node.IsLeaf) {
[16218]137          continue;
138        }
139
140        if (node.IsCommutative) { // only sort when the argument order does not matter
141          var arity = node.Arity;
142          var size = node.Size;
143
144          if (arity == size) { // all child nodes are terminals
145            Array.Sort(nodes, i - size, size);
146          } else { // i have some non-terminal children
147            var sorted = new HashNode<T>[size];
[17090]148            var indices = new int[node.Arity];
149            for (int j = i - 1, k = 0; k < node.Arity; j -= 1 + nodes[j].Size, ++k) {
150              indices[k] = j;
151            }
152            Array.Sort(indices, sort);
[16218]153
154            int idx = 0;
155            foreach (var j in indices) {
156              var child = nodes[j];
[17090]157              if (!child.IsLeaf) { // must copy complete subtree
[16218]158                Array.Copy(nodes, j - child.Size, sorted, idx, child.Size);
159                idx += child.Size;
160              }
161              sorted[idx++] = nodes[j];
162            }
163            Array.Copy(sorted, 0, nodes, i - size, size);
164          }
165        }
[17090]166        node.CalculatedHashValue = nodes.ComputeHash(i, hashFunction);
[16218]167      }
[17090]168      return nodes;
[16218]169    }
170
171    /// <summary>
[17090]172    /// Get a function node's child indicest
[16218]173    /// </summary>
[17090]174    /// <typeparam name="T">The data type encapsulated by a hash node</typeparam>
175    /// <param name="nodes">An array of hash nodes with up-to-date node sizes</param>
176    /// <param name="i">The index in the array of hash nodes of the node whose children we want to iterate</param>
[16218]177    /// <returns>An array containing child indices</returns>
178    public static int[] IterateChildren<T>(this HashNode<T>[] nodes, int i) where T : class {
179      var node = nodes[i];
180      var arity = node.Arity;
181      var children = new int[arity];
182      var idx = i - 1;
183      for (int j = 0; j < arity; ++j) {
184        children[j] = idx;
185        idx -= 1 + nodes[idx].Size;
186      }
187      return children;
188    }
189
[17090]190    public static HashNode<T>[] UpdateNodeSizes<T>(this HashNode<T>[] nodes) where T : class {
[16218]191      for (int i = 0; i < nodes.Length; ++i) {
192        var node = nodes[i];
[17090]193        if (node.IsLeaf) {
[16218]194          node.Size = 0;
195          continue;
196        }
197        node.Size = node.Arity;
[17090]198
199        for (int j = i - 1, k = 0; k < node.Arity; j -= 1 + nodes[j].Size, ++k) {
[16218]200          node.Size += nodes[j].Size;
201        }
202      }
[17090]203      return nodes;
[16218]204    }
205
[17099]206    public static HashNode<T>[] Reduce<T>(this HashNode<T>[] nodes) where T : class {
[17090]207      int count = 0;
208      for (int i = 0; i < nodes.Length; ++i) {
209        var node = nodes[i];
210        if (node.IsLeaf || !node.IsCommutative) {
211          continue;
212        }
[16218]213
[17090]214        var arity = node.Arity;
215        for (int j = i - 1, k = 0; k < arity; j -= 1 + nodes[j].Size, ++k) {
216          if (node.HashValue == nodes[j].HashValue) {
217            nodes[j].Enabled = false;
218            node.Arity += nodes[j].Arity - 1;
219            ++count;
220          }
221        }
[16218]222      }
223      if (count == 0)
224        return nodes;
225
226      var reduced = new HashNode<T>[nodes.Length - count];
[17090]227      var idx = 0;
[16218]228      foreach (var node in nodes) {
[17090]229        if (node.Enabled) { reduced[idx++] = node; }
[16218]230      }
[17090]231      return reduced.UpdateNodeSizes();
[16218]232    }
233  }
234}
Note: See TracBrowser for help on using the repository browser.