Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ScopedAlgorithms/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeMatching.cs @ 15904

Last change on this file since 15904 was 12012, checked in by ascheibe, 10 years ago

#2212 merged r12008, r12009, r12010 back into trunk

File size: 5.4 KB
Line 
1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
5 *
6 * This file is part of HeuristicLab.
7 *
8 * HeuristicLab is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * HeuristicLab is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#endregion
23
24using System;
25using System.Collections.Generic;
26using System.Linq;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28//using HeuristicLab.EvolutionTracking;
29
30namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
31  public static class SymbolicExpressionTreeMatching {
32    public static bool ContainsSubtree(this ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode subtree, SymbolicExpressionTreeNodeEqualityComparer comparer) {
33      return FindMatches(root, subtree, comparer).Any();
34    }
35    public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTree tree, ISymbolicExpressionTreeNode subtree, SymbolicExpressionTreeNodeEqualityComparer comparer) {
36      return FindMatches(tree.Root, subtree, comparer);
37    }
38
39    public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode subtree, SymbolicExpressionTreeNodeEqualityComparer comp) {
40      var fragmentLength = subtree.GetLength();
41      // below, we use ">=" for Match(n, subtree, comp) >= fragmentLength because in case of relaxed conditions,
42      // we can have multiple matches of the same node
43
44      return root.IterateNodesBreadth().Where(n => n.GetLength() >= fragmentLength && Match(n, subtree, comp) == fragmentLength);
45    }
46
47    ///<summary>
48    /// Finds the longest common subsequence in quadratic time and linear space
49    /// Variant of:
50    /// D. S. Hirschberg. A linear space algorithm for or computing maximal common subsequences. 1975.
51    /// http://dl.acm.org/citation.cfm?id=360861
52    /// </summary>
53    /// <returns>Number of pairs that were matched</returns>
54    public static int Match(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b, ISymbolicExpressionTreeNodeSimilarityComparer comp) {
55      if (!comp.Equals(a, b)) return 0;
56      int m = a.SubtreeCount;
57      int n = b.SubtreeCount;
58      if (m == 0 || n == 0) return 1;
59      var matrix = new int[m + 1, n + 1];
60      for (int i = 1; i <= m; ++i) {
61        var ai = a.GetSubtree(i - 1);
62        for (int j = 1; j <= n; ++j) {
63          var bj = b.GetSubtree(j - 1);
64          int match = Match(ai, bj, comp);
65          matrix[i, j] = Math.Max(Math.Max(matrix[i, j - 1], matrix[i - 1, j]), matrix[i - 1, j - 1] + match);
66        }
67      }
68      return matrix[m, n] + 1;
69    }
70
71    /// <summary>
72    /// Calculates the difference between two symbolic expression trees.
73    /// </summary>
74    /// <param name="tree">The first symbolic expression tree</param>
75    /// <param name="other">The second symbolic expression tree</param>
76    /// <returns>Returns the root of the subtree (from T1) by which T1 differs from T2, or null if no difference is found.</returns>
77    public static ISymbolicExpressionTreeNode Difference(this ISymbolicExpressionTree tree, ISymbolicExpressionTree other) {
78      return Difference(tree.Root, other.Root);
79    }
80
81    public static ISymbolicExpressionTreeNode Difference(this ISymbolicExpressionTreeNode node, ISymbolicExpressionTreeNode other) {
82      var a = node.IterateNodesPrefix().ToList();
83      var b = other.IterateNodesPrefix().ToList();
84      var list = new List<ISymbolicExpressionTreeNode>();
85      for (int i = 0, j = 0; i < a.Count && j < b.Count; ++i, ++j) {
86        var s1 = a[i].ToString();
87        var s2 = b[j].ToString();
88        if (s1 == s2) continue;
89        list.Add(a[i]);
90        // skip subtrees since the parents are already different
91        i += a[i].SubtreeCount;
92        j += b[j].SubtreeCount;
93      }
94      ISymbolicExpressionTreeNode result = list.Count > 0 ? LowestCommonAncestor(node, list) : null;
95      return result;
96    }
97
98    private static ISymbolicExpressionTreeNode LowestCommonAncestor(ISymbolicExpressionTreeNode root, List<ISymbolicExpressionTreeNode> nodes) {
99      if (nodes.Count == 0)
100        throw new ArgumentException("The nodes list should contain at least one element.");
101
102      if (nodes.Count == 1)
103        return nodes[0];
104
105      int minLevel = nodes.Min(x => root.GetBranchLevel(x));
106
107      // bring the nodes in the nodes to the same level (relative to the root)
108      for (int i = 0; i < nodes.Count; ++i) {
109        var node = nodes[i];
110        var level = root.GetBranchLevel(node);
111        for (int j = minLevel; j < level; ++j)
112          node = node.Parent;
113        nodes[i] = node;
114      }
115
116      // while not all the elements in the nodes are equal, go one level up
117      while (nodes.Any(x => x != nodes[0])) {
118        for (int i = 0; i < nodes.Count; ++i)
119          nodes[i] = nodes[i].Parent;
120      }
121
122      return nodes[0];
123    }
124  }
125}
Note: See TracBrowser for help on using the repository browser.