Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/QueryMatch.cs @ 13482

Last change on this file since 13482 was 13482, checked in by bburlacu, 8 years ago

#1772: Merged trunk changes

File size: 8.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
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.Collections.Generic;
23using System.Linq;
24using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
25
26namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
27  // this class implements the decision version of the tree pattern query matching algorithm
28  // by M. Götz, C. Koch and W. Martens in http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.182.5440
29  public class QueryMatch {
30    public ISymbolicExpressionTreeNodeEqualityComparer Comparer { get; }
31
32    private QueryMatch() { }
33
34    // whether matching nodes should also have matching parents
35    // in theory, this restricts the matching so that parent-child
36    // pairs in the query tree are matched by parent-child pairs in
37    // the data tree (and not ancestor-descendant pairs)
38    public bool MatchParents { get; set; }
39
40    public QueryMatch(ISymbolicExpressionTreeNodeEqualityComparer comparer) {
41      this.Comparer = comparer;
42    }
43
44    internal bool Match(List<NodeInfo> data, List<NodeInfo> query) {
45      var dRoot = data.Last();
46      var qRoot = query.Last();
47
48      var result = Tmatch(dRoot, query.First(), qRoot);
49      return result == qRoot;
50    }
51
52    public bool Match(ISymbolicExpressionTree data, ISymbolicExpressionTree query) {
53      return Match(data.Root.GetSubtree(0).GetSubtree(0), query.Root.GetSubtree(0).GetSubtree(0));
54    }
55
56    public bool Match(ISymbolicExpressionTreeNode data, ISymbolicExpressionTreeNode query) {
57      if (!Comparer.Equals(data, query))
58        return false;
59
60      var dNodes = InitializePostOrder(data);
61      var qNodes = InitializePostOrder(query);
62
63      var dRoot = dNodes.Last();
64      var qRoot = qNodes.Last();
65      var result = Tmatch(dRoot, qNodes.First(), qRoot);
66      return result == qRoot;
67    }
68
69    public IEnumerable<ISymbolicExpressionTree> GetMatchingTrees(IEnumerable<ISymbolicExpressionTree> data, ISymbolicExpressionTree query) {
70      var qRoot = query.Root.GetSubtree(0).GetSubtree(0);
71      var filtered = data.Where(x => x.Length >= query.Length && Comparer.Equals(x.Root.GetSubtree(0).GetSubtree(0), qRoot));
72      var qNodes = InitializePostOrder(query.Root.GetSubtree(0).GetSubtree(0));
73      return from d in filtered let dNodes = InitializePostOrder(d.Root.GetSubtree(0).GetSubtree(0)) where Match(dNodes, qNodes) select d;
74    }
75
76    private bool AreMatching(NodeInfo a, NodeInfo b) {
77      // force the nodes to be on the same level
78      if (a.Level != b.Level)
79        return false;
80
81      bool equals = Comparer.Equals(a.Node, b.Node);
82      if (equals && MatchParents) {
83        var pa = a.Parent;
84        var pb = b.Parent;
85        if (pa == null && pb == null)
86          return true;
87        if (pa == null || pb == null)
88          return false;
89        return pa.Level == pb.Level && Comparer.Equals(pa.Node, pb.Node);
90      }
91      return equals;
92    }
93
94    private NodeInfo Tmatch(NodeInfo d, NodeInfo qFrom, NodeInfo qUntil) {
95      NodeInfo qBest = d.IsLeaf ? qFrom.Previous : Hmatch(d.LastChild, qFrom, qUntil);
96      var next = qBest.Next;
97      if (next.Index <= qUntil.Index && AreMatching(d, next)) {
98        qBest = next;
99        next = qBest.Next;
100        var lastSibling = qBest.LastSibling;
101        return next.Index <= lastSibling.Index ? Tmatch(d, next, lastSibling) : qBest;
102      }
103      return qBest;
104    }
105
106    private NodeInfo Hmatch(NodeInfo d, NodeInfo qFrom, NodeInfo qUntil) {
107      if (d.IsFirstSibling)
108        return Tmatch(d, qFrom, qUntil);
109
110      var qHedge = Hmatch(d.PreviousSibling, qFrom, qUntil);
111      var qTree = Tmatch(d, qFrom, qUntil);
112
113      for (;;) {
114        if (qHedge == qTree)
115          return qHedge;
116        if (qTree.Index < qHedge.Index) {
117          var rtop = Rtop(qTree.Next, qHedge);
118          while (rtop.Index < int.MaxValue && qHedge.Index < rtop.LastSibling.Index) {
119            qTree = Tmatch(d, rtop.Next, rtop.LastSibling);
120            rtop = Rtop(qTree.Next, qHedge);
121          }
122          if (qTree.Index <= qHedge.Index)
123            return qHedge;
124        } else {
125          var rtop = Rtop(qHedge.Next, qTree);
126          while (rtop.Index < int.MaxValue && qTree.Index < rtop.LastSibling.Index) {
127            qHedge = Hmatch(d.PreviousSibling, rtop.Next, rtop.LastSibling);
128            rtop = Rtop(qHedge.Next, qTree);
129          }
130          if (qHedge.Index <= qTree.Index)
131            return qTree;
132        }
133      }
134    }
135
136    // returns the rightmost node from the topmost nodes in the interval [hFrom, hUntil]
137    private NodeInfo Rtop(NodeInfo hFrom, NodeInfo hUntil) {
138      if (hFrom == hUntil)
139        return hUntil;
140      if (hFrom.Index > hUntil.Index)
141        return new NodeInfo { Node = null, Index = int.MaxValue };
142      // let u be the highest ancestor of hUntil that has a previous sibling s such that s >= hFrom
143      // if no such u exists, then Rtop(hFrom, hUntil) = hUntil. Otherwise, rtop(hFrom, hUntil) = s
144      NodeInfo rtop = null;
145      List<NodeInfo> ancestors = hUntil.Ancestors.ToList();
146      // ancestors list is ordered in decreasing depth therefore we start from the end
147      for (int i = ancestors.Count - 1; i >= 0; --i) {
148        if (ancestors[i].Parent == null || ancestors[i].IsFirstSibling)
149          continue;
150        var s = ancestors[i].PreviousSibling;
151        if (s != null && s.Index >= hFrom.Index) {
152          rtop = s;
153          break;
154        }
155      }
156      return rtop ?? hUntil;
157    }
158
159    internal static List<NodeInfo> InitializePostOrder(ISymbolicExpressionTreeNode node) {
160      var nodes = node.IterateNodesPostfix().Select((x, i) => new NodeInfo { Node = x, Index = i, Level = 0 }).ToList();
161      var map = nodes.ToDictionary(x => x.Node, x => x);
162
163      var inf = new NodeInfo { Node = null, Index = int.MaxValue, Previous = nodes.Last() };
164      var nil = new NodeInfo { Node = null, Index = -1, Next = nodes.First() };
165
166      for (int i = nodes.Count - 1; i >= 0; --i) {
167        var n = nodes[i];
168        n.Parent = n.Node.Parent != null && map.ContainsKey(n.Node.Parent) ? map[n.Node.Parent] : null;
169        n.Level = n.Parent?.Level + 1 ?? -1;
170        n.Next = n == nodes.Last() ? inf : nodes[n.Index + 1];
171        n.Previous = n == nodes.First() ? nil : nodes[n.Index - 1];
172        if (n.Parent == null) {
173          n.PreviousSibling = n.NextSibling = null;
174          n.LastSibling = nil;
175        } else {
176          var parent = n.Parent.Node;
177          int si = parent.IndexOfSubtree(n.Node);
178          n.PreviousSibling = n.IsFirstSibling ? null : map[parent.GetSubtree(si - 1)];
179          n.NextSibling = n.IsLastSibling ? null : map[parent.GetSubtree(si + 1)];
180          n.LastSibling = map[parent.Subtrees.Last()];
181        }
182        n.LastChild = n.IsLeaf ? null : n.Previous;
183      }
184      return nodes;
185    }
186  }
187
188  internal class NodeInfo {
189    public ISymbolicExpressionTreeNode Node { get; set; }
190    public int Index { get; set; }
191    public int Level { get; set; }
192    public NodeInfo Parent { get; set; }
193    public NodeInfo Previous { get; set; }
194    public NodeInfo PreviousSibling { get; set; }
195    public NodeInfo Next { get; set; }
196    public NodeInfo NextSibling { get; set; }
197    public NodeInfo LastSibling { get; set; }
198    public NodeInfo LastChild { get; set; }
199
200    public bool IsLeaf {
201      get { return Node.SubtreeCount == 0; }
202    }
203
204    public bool IsFirstSibling {
205      get { return Node.Parent != null && Node == Node.Parent.Subtrees.First(); }
206    }
207
208    public bool IsLastSibling {
209      get { return Node.Parent != null && Node == Node.Parent.Subtrees.Last(); }
210    }
211
212    public IEnumerable<NodeInfo> Ancestors {
213      get {
214        var p = Parent;
215        while (p != null) {
216          yield return p;
217          p = p.Parent;
218        }
219      }
220    }
221  }
222}
223
Note: See TracBrowser for help on using the repository browser.