Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SymbolicDataAnalysisExpressionTreeMatching.cs @ 10302

Last change on this file since 10302 was 10302, checked in by bburlacu, 10 years ago

#1772: - Added a ViewHost in the right side of the GenealogyGraphView which displays the encoding-specific content when a GenealogyGraphNode is clicked.

  • Migrated new SymbolicExpressionTreeChart (drawing the tree using the ReingoldTilfordLayoutEngine) to the new branch
  • Copied SymbolicDataAnalysisExpressionTreeMatching.cs and SymbolicDataAnalysisExpressionTreeSimilarityCalculator.cs to the new branch
File size: 10.6 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using HeuristicLab.Common;
5using HeuristicLab.Core;
6using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
7using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
8using HeuristicLab.Problems.DataAnalysis.Symbolic;
9
10namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
11  [Item("SymbolicExpressionTreeNodeSimilarityComparer", "A comparison operator that checks node equality based on different similarity measures.")]
12  [StorableClass]
13  public class SymbolicExpressionTreeNodeSimilarityComparer : Item, ISymbolicExpressionTreeNodeSimilarityComparer {
14    [StorableConstructor]
15    private SymbolicExpressionTreeNodeSimilarityComparer(bool deserializing) : base(deserializing) { }
16    private SymbolicExpressionTreeNodeSimilarityComparer(SymbolicExpressionTreeNodeSimilarityComparer original, Cloner cloner)
17      : base(original, cloner) {
18      matchConstantValues = original.matchConstantValues;
19      matchVariableNames = original.matchVariableNames;
20      matchVariableWeights = original.matchVariableWeights;
21    }
22    public override IDeepCloneable Clone(Cloner cloner) { return new SymbolicExpressionTreeNodeSimilarityComparer(this, cloner); }
23
24    // more flexible matching criteria
25    [Storable]
26    private bool matchConstantValues;
27    public bool MatchConstantValues {
28      get { return matchConstantValues; }
29      set { matchConstantValues = value; }
30    }
31
32    [Storable]
33    private bool matchVariableNames;
34    public bool MatchVariableNames {
35      get { return matchVariableNames; }
36      set { matchVariableNames = value; }
37    }
38
39    [Storable]
40    private bool matchVariableWeights;
41    public bool MatchVariableWeights {
42      get { return matchVariableWeights; }
43      set { matchVariableWeights = value; }
44    }
45
46    [StorableHook(HookType.AfterDeserialization)]
47    private void AfterDeserialization() {
48    }
49
50    public SymbolicExpressionTreeNodeSimilarityComparer() {
51      matchConstantValues = true;
52      matchVariableNames = true;
53      matchVariableWeights = true;
54    }
55
56    public int GetHashCode(ISymbolicExpressionTreeNode n) {
57      return n.ToString().ToLower().GetHashCode();
58    }
59
60    public bool Equals(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) {
61      if (!(a is SymbolicExpressionTreeTerminalNode))
62        // if a and b are non terminal nodes, check equality of symbol names
63        return !(b is SymbolicExpressionTreeTerminalNode) && a.Symbol.Name.Equals(b.Symbol.Name);
64      var va = a as VariableTreeNode;
65      if (va != null) {
66        var vb = b as VariableTreeNode;
67        if (vb == null) return false;
68
69        return (!MatchVariableNames || va.VariableName.Equals(vb.VariableName)) && (!MatchVariableWeights || va.Weight.Equals(vb.Weight));
70      }
71      var ca = a as ConstantTreeNode;
72      if (ca != null) {
73        var cb = b as ConstantTreeNode;
74        if (cb == null) return false;
75        return (!MatchConstantValues || ca.Value.Equals(cb.Value));
76      }
77      return false;
78    }
79  }
80
81  public class SymbolicExpressionTreeFragmentSimilarityComparer : IEqualityComparer<IFragment> {
82    public SymbolicExpressionTreeNodeSimilarityComparer SimilarityComparer { get; set; }
83
84    public bool Equals(IFragment x, IFragment y) {
85      if (SimilarityComparer == null)
86        throw new ArgumentNullException("SimilarityComparer needs to be initialized first.");
87      return x.Length == y.Length && SymbolicExpressionTreeMatching.Match(x.Root, y.Root, SimilarityComparer) == x.Length;
88    }
89
90    public int GetHashCode(IFragment fragment) {
91      return fragment.Root.Symbol.Name.ToLower().GetHashCode();
92    }
93  }
94
95  // this comparer considers that a < b if the type of a is "greater" than the type of b, for example:
96  // - A function node is "greater" than a terminal node
97  // - A variable terminal is "greater" than a constant terminal
98  // - used for bringing subtrees to a "canonical" form when the operation allows reordering of arguments
99  public class SymbolicExpressionTreeNodeComparer : ISymbolicExpressionTreeNodeComparer {
100    public int Compare(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) {
101      if (!(a is SymbolicExpressionTreeTerminalNode)) {
102        return b is SymbolicExpressionTreeTerminalNode
103          ? -1
104          : string.Compare(a.Symbol.Name, b.Symbol.Name, StringComparison.Ordinal);
105      }
106      if (!(b is SymbolicExpressionTreeTerminalNode)) return 1;
107      // at this point we know a and b are terminal nodes
108      var va = a as VariableTreeNode;
109      if (va != null) {
110        if (b is ConstantTreeNode) return -1;
111        var vb = (VariableTreeNode)b;
112        return (va.VariableName.Equals(vb.VariableName)
113                  ? va.Weight.CompareTo(vb.Weight)
114                  : string.Compare(va.VariableName, vb.VariableName, StringComparison.Ordinal));
115      }
116      // at this point we know for sure that a is a constant tree node
117      if (b is VariableTreeNode) return 1;
118      var ca = (ConstantTreeNode)a;
119      var cb = (ConstantTreeNode)b;
120      return ca.Value.CompareTo(cb.Value);
121    }
122  }
123
124  // tree equality
125  public class SymbolicExpressionTreeEqualityComparer : IEqualityComparer<ISymbolicExpressionTree> {
126    public SymbolicExpressionTreeNodeSimilarityComparer SimilarityComparer { get; set; }
127
128    public bool Equals(ISymbolicExpressionTree a, ISymbolicExpressionTree b) {
129      if (SimilarityComparer == null) throw new Exception("SimilarityComparer needs to be initialized first.");
130      return a.Length == b.Length &&
131             SymbolicExpressionTreeMatching.Match(a.Root, b.Root, SimilarityComparer) == Math.Min(a.Length, b.Length);
132    }
133
134    public int GetHashCode(ISymbolicExpressionTree tree) {
135      return (tree.Length << 8) % 12345;
136    }
137  }
138
139  public class SymbolicExpressionTreeCanonicalSorter {
140    private readonly HashSet<Type> nonSymmetricSymbols = new HashSet<Type> { typeof(Subtraction), typeof(Division) };
141
142    public void SortSubtrees(ISymbolicExpressionTree tree) {
143      SortSubtrees(tree.Root);
144    }
145
146    public void SortSubtrees(ISymbolicExpressionTreeNode node) {
147      if (node.SubtreeCount == 0) return;
148      var subtrees = node.Subtrees as List<ISymbolicExpressionTreeNode> ?? node.Subtrees.ToList();
149      if (IsSymmetric(node.Symbol)) {
150        var comparer = new SymbolicExpressionTreeNodeComparer();
151        subtrees.Sort(comparer);
152      }
153      foreach (var s in subtrees)
154        SortSubtrees(s);
155    }
156
157    private bool IsSymmetric(ISymbol s) {
158      return !nonSymmetricSymbols.Contains(s.GetType());
159    }
160  }
161}
162
163public static class SymbolicExpressionTreeMatching {
164  public static bool ContainsFragment(this ISymbolicExpressionTreeNode root, IFragment fragment, SymbolicExpressionTreeNodeSimilarityComparer comparer) {
165    return FindMatches(root, fragment.Root, comparer).Any();
166  }
167  public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTree tree, ISymbolicExpressionTreeNode fragment, SymbolicExpressionTreeNodeSimilarityComparer comparer) {
168    return FindMatches(tree.Root, fragment, comparer);
169  }
170
171  public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode fragment, SymbolicExpressionTreeNodeSimilarityComparer comp) {
172    var fragmentLength = fragment.GetLength();
173    // below, we use ">=" for Match(n, fragment, comp) >= fragmentLength because in case of relaxed conditions,
174    // we can have multiple matches of the same node
175
176    return root.IterateNodesBreadth().Where(n => n.GetLength() >= fragmentLength && Match(n, fragment, comp) == fragmentLength);
177  }
178
179  ///<summary>
180  /// Finds the longest common subsequence in quadratic time and linear space
181  /// Variant of:
182  /// D. S. Hirschberg. A linear space algorithm for or computing maximal common subsequences. 1975.
183  /// http://dl.acm.org/citation.cfm?id=360861
184  /// </summary>
185  /// <returns>Number of pairs that were matched</returns>
186  public static int Match(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b, SymbolicExpressionTreeNodeSimilarityComparer comp) {
187    if (!comp.Equals(a, b)) return 0;
188    int m = a.SubtreeCount;
189    int n = b.SubtreeCount;
190    if (m == 0 || n == 0) return 1;
191    var matrix = new int[m + 1, n + 1];
192    for (int i = 1; i <= m; ++i) {
193      var ai = a.GetSubtree(i - 1);
194      for (int j = 1; j <= n; ++j) {
195        var bj = b.GetSubtree(j - 1);
196        int match = Match(ai, bj, comp);
197        matrix[i, j] = Math.Max(Math.Max(matrix[i, j - 1], matrix[i - 1, j]), matrix[i - 1, j - 1] + match);
198      }
199    }
200    return matrix[m, n] + 1;
201  }
202}
203
204// this maximal common subsequence calculator follows the same approach as the Match method above and should yield identical results
205// the difference is that the maximal common subsequence calculator returns the actual common subsequence as a list
206public class MaximalCommonSubsequenceCalculator {
207  private ISymbolicExpressionTreeNode[] x;
208  private ISymbolicExpressionTreeNode[] y;
209  private List<ISymbolicExpressionTreeNode> maxCommonSubseq;
210  private double[,] matrix;
211
212  public SymbolicExpressionTreeNodeSimilarityComparer SimilarityComparer { get; set; }
213
214  public List<ISymbolicExpressionTreeNode> Calculate(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
215    if (SimilarityComparer == null) throw new Exception("Comparer cannot be null.");
216
217    x = n1.IterateNodesPrefix().ToArray();
218    y = n2.IterateNodesPrefix().ToArray();
219
220    if (maxCommonSubseq == null) maxCommonSubseq = new List<ISymbolicExpressionTreeNode>();
221    else maxCommonSubseq.Clear();
222
223    int n = x.Length;
224    int m = y.Length;
225
226    matrix = new double[n + 1, m + 1];
227
228    for (int i = 0; i <= n; ++i) {
229      for (int j = 0; j <= m; ++j) {
230        if (i == 0 || j == 0) {
231          matrix[i, j] = 0;
232        } else if (SimilarityComparer.Equals(x[i - 1], y[j - 1])) {
233          matrix[i, j] = matrix[i - 1, j - 1] + 1;
234        } else {
235          matrix[i, j] = Math.Max(matrix[i - 1, j], matrix[i, j - 1]);
236        }
237      }
238    }
239    recon(n, m);
240    return new List<ISymbolicExpressionTreeNode>(maxCommonSubseq);
241  }
242
243  private void recon(int i, int j) {
244    while (true) {
245      if (i == 0 || j == 0) return;
246      if (SimilarityComparer.Equals(x[i - 1], y[j - 1])) {
247        recon(i - 1, j - 1);
248        maxCommonSubseq.Add(x[i - 1]);
249      } else if (matrix[i - 1, j] > matrix[i, j - 1]) {
250        i = i - 1;
251        continue;
252      } else {
253        j = j - 1;
254        continue;
255      }
256      break;
257    }
258  }
259}
Note: See TracBrowser for help on using the repository browser.