Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeMatching.cs @ 16130

Last change on this file since 16130 was 16130, checked in by bburlacu, 6 years ago

#1772: Merge trunk changes

File size: 5.6 KB
Line 
1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) 2002-2018 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, ISymbolicExpressionTreeNodeEqualityComparer comparer) {
33      return FindMatches(root, subtree, comparer).Any();
34    }
35    public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTree tree, ISymbolicExpressionTreeNode subtree, ISymbolicExpressionTreeNodeEqualityComparer comparer) {
36      return FindMatches(tree.Root, subtree, comparer);
37    }
38
39    public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode subtree, ISymbolicExpressionTreeNodeEqualityComparer 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, ISymbolicExpressionTreeNodeEqualityComparer comp) {
55      if (!comp.Equals(a, b)) return 0;
56      // AnySubtree wildcards mach everything
57      if (a is AnySubtree)
58        return 1;
59      if (b is AnySubtree)
60        return 1;
61
62      int m = a.SubtreeCount;
63      int n = b.SubtreeCount;
64      if (m == 0 || n == 0) return 1;
65      var matrix = new int[m + 1, n + 1];
66      for (int i = 1; i <= m; ++i) {
67        var ai = a.GetSubtree(i - 1);
68        for (int j = 1; j <= n; ++j) {
69          var bj = b.GetSubtree(j - 1);
70          int match = Match(ai, bj, comp);
71          matrix[i, j] = Math.Max(Math.Max(matrix[i, j - 1], matrix[i - 1, j]), matrix[i - 1, j - 1] + match);
72        }
73      }
74      return matrix[m, n] + 1;
75    }
76
77    /// <summary>
78    /// Calculates the difference between two symbolic expression trees.
79    /// </summary>
80    /// <param name="tree">The first symbolic expression tree</param>
81    /// <param name="other">The second symbolic expression tree</param>
82    /// <returns>Returns the root of the subtree (from T1) by which T1 differs from T2, or null if no difference is found.</returns>
83    public static ISymbolicExpressionTreeNode Difference(this ISymbolicExpressionTree tree, ISymbolicExpressionTree other) {
84      return Difference(tree.Root, other.Root);
85    }
86
87    public static ISymbolicExpressionTreeNode Difference(this ISymbolicExpressionTreeNode node, ISymbolicExpressionTreeNode other) {
88      var a = node.IterateNodesPrefix().ToList();
89      var b = other.IterateNodesPrefix().ToList();
90      var list = new List<ISymbolicExpressionTreeNode>();
91      for (int i = 0, j = 0; i < a.Count && j < b.Count; ++i, ++j) {
92        var s1 = a[i].ToString();
93        var s2 = b[j].ToString();
94        if (s1 == s2) continue;
95        list.Add(a[i]);
96        // skip subtrees since the parents are already different
97        i += a[i].SubtreeCount;
98        j += b[j].SubtreeCount;
99      }
100      ISymbolicExpressionTreeNode result = list.Count > 0 ? LowestCommonAncestor(node, list) : null;
101      return result;
102    }
103
104    private static ISymbolicExpressionTreeNode LowestCommonAncestor(ISymbolicExpressionTreeNode root, List<ISymbolicExpressionTreeNode> nodes) {
105      if (nodes.Count == 0)
106        throw new ArgumentException("The nodes list should contain at least one element.");
107
108      if (nodes.Count == 1)
109        return nodes[0];
110
111      int minLevel = nodes.Min(root.GetBranchLevel);
112
113      // bring the nodes in the nodes to the same level (relative to the root)
114      for (int i = 0; i < nodes.Count; ++i) {
115        var node = nodes[i];
116        var level = root.GetBranchLevel(node);
117        for (int j = minLevel; j < level; ++j)
118          node = node.Parent;
119        nodes[i] = node;
120      }
121
122      // while not all the elements in the nodes are equal, go one level up
123      while (nodes.Any(x => x != nodes[0])) {
124        for (int i = 0; i < nodes.Count; ++i)
125          nodes[i] = nodes[i].Parent;
126      }
127
128      return nodes[0];
129    }
130  }
131}
Note: See TracBrowser for help on using the repository browser.