Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Matching/SymbolicExpressionTreeMatching.cs @ 11384

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

#2164: Added license header. Added a Difference method for calculating the difference between two trees T1 and T2. From a set theory perspective, this method calculates the relative complement of T2 in T1.

File size: 5.3 KB
Line 
1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) 2002-2014 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, SymbolicExpressionTreeNodeSimilarityComparer comparer) {
33      return FindMatches(root, subtree, comparer).Any();
34    }
35    public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTree tree, ISymbolicExpressionTreeNode subtree, SymbolicExpressionTreeNodeSimilarityComparer comparer) {
36      return FindMatches(tree.Root, subtree, comparer);
37    }
38
39    public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode subtree, SymbolicExpressionTreeNodeSimilarityComparer 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, SymbolicExpressionTreeNodeSimilarityComparer 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 these = node.IterateNodesPrefix().ToList();
83      var others = other.IterateNodesPrefix().ToList();
84
85      var minCount = Math.Min(these.Count, others.Count);
86      var list = new List<ISymbolicExpressionTreeNode>();
87
88      for (int i = 0; i < minCount; ++i) {
89        if (these[i].ToString() != others[i].ToString())
90          list.Add(these[i]);
91      }
92
93      return list.Count > 0 ? LowestCommonAncestor(node, list) : null;
94    }
95
96    private static ISymbolicExpressionTreeNode LowestCommonAncestor(ISymbolicExpressionTreeNode root, List<ISymbolicExpressionTreeNode> nodes) {
97      if (nodes.Count == 0)
98        throw new ArgumentException("The nodes list should contain at least one element.");
99
100      if (nodes.Count == 1)
101        return nodes[0];
102
103      int lowestLevel = nodes.Min(x => root.GetBranchLevel(x));
104
105      // bring the nodes in the nodes to the same level (relative to the root)
106      for (int i = 0; i < nodes.Count; ++i) {
107        var node = nodes[i];
108        var level = root.GetBranchLevel(node);
109        for (int j = lowestLevel; j < level; ++j)
110          node = node.Parent;
111        nodes[i] = node;
112      }
113
114      // while not all the elements in the nodes are equal, go one level up
115      while (nodes.Any(x => x != nodes[0])) {
116        for (int i = 0; i < nodes.Count; ++i)
117          nodes[i] = nodes[i].Parent;
118      }
119
120      return nodes[0];
121    }
122  }
123}
Note: See TracBrowser for help on using the repository browser.