source: branches/HeuristicLab.BottomUpTreeDistance/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpTreeSimilarityCalculator.cs @ 11239

Last change on this file since 11239 was 11239, checked in by bburlacu, 7 years ago

#2215:

  • Renamed BottomUpSimilarityCalculator to BottomUpTreeSimilarityCalculator.
  • Refactored the BottomUpTreeSimilarityCalculator to accept a configurable list of commutative symbols (the children of commutative symbols need to be sorted according to their label).
  • Added MaxCommonSubtreeSimilarityCalculator performance test
  • Updated BottomUpTreeSimilarityCalculatorTest
File size: 9.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Optimization.Operators;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
32  [StorableClass]
33  [Item("BottomUpTreeSimilarityCalculator", "A similarity calculator which uses the tree bottom-up distance as a similarity metric.")]
34  public class BottomUpTreeSimilarityCalculator : SingleObjectiveSolutionSimilarityCalculator {
35    private readonly HashSet<string> commutativeSymbols;
36
37    public BottomUpTreeSimilarityCalculator() {
38      commutativeSymbols = new HashSet<string>();
39    }
40
41    public BottomUpTreeSimilarityCalculator(IEnumerable<string> commutativeSymbols) {
42      this.commutativeSymbols = new HashSet<string>(commutativeSymbols);
43    }
44
45    public override IDeepCloneable Clone(Cloner cloner) {
46      return new BottomUpTreeSimilarityCalculator(this, cloner);
47    }
48
49    protected BottomUpTreeSimilarityCalculator(BottomUpTreeSimilarityCalculator original, Cloner cloner)
50      : base(original, cloner) {
51    }
52
53    public override double CalculateSolutionSimilarity(IScope leftSolution, IScope rightSolution) {
54      var t1 = leftSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
55      var t2 = rightSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
56
57      if (t1 == null || t2 == null)
58        throw new ArgumentException("Cannot calculate similarity when one of the arguments is null.");
59
60      var similarity = CalculateSolutionSimilarity(t1, t2);
61      if (similarity > 1.0)
62        throw new Exception("Similarity value cannot be greater than 1");
63
64      return similarity;
65    }
66
67    public bool AddCommutativeSymbol(string symbolName) {
68      return commutativeSymbols.Add(symbolName);
69    }
70
71    public bool RemoveCommutativeSymbol(string symbolName) {
72      return commutativeSymbols.Remove(symbolName);
73    }
74
75    public double CalculateSolutionSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
76      if (t1 == t2)
77        return 1;
78
79      var map = ComputeBottomUpMapping(t1.Root, t2.Root);
80      return 2.0 * map.Count / (t1.Length + t2.Length);
81    }
82
83    public Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
84      var compactedGraph = Compact(n1, n2);
85
86      var forwardMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t1 => nodes of t2
87      var reverseMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t2 => nodes of t1
88
89      // visit nodes in order of decreasing height to ensure correct mapping
90      foreach (var v in n1.IterateNodesPrefix().OrderByDescending(x => compactedGraph[x].Depth)) {
91        if (forwardMap.ContainsKey(v))
92          continue;
93        var kv = compactedGraph[v];
94        ISymbolicExpressionTreeNode w = null;
95        foreach (var t in n2.IterateNodesPrefix()) {
96          if (reverseMap.ContainsKey(t) || compactedGraph[t] != kv)
97            continue;
98          w = t;
99          break;
100        }
101        if (w == null) continue;
102
103        // at this point we know that v and w are isomorphic, however, the mapping cannot be done directly (as in the paper) because the trees are unordered (subtree order might differ)
104        // the solution is to sort subtrees by label using IterateBreadthOrdered (this will work because the subtrees are isomorphic!) and simultaneously iterate over the two subtrees
105        var eV = IterateBreadthOrdered(v).GetEnumerator();
106        var eW = IterateBreadthOrdered(w).GetEnumerator();
107
108        while (eV.MoveNext() && eW.MoveNext()) {
109          var s = eV.Current;
110          var t = eW.Current;
111
112          if (reverseMap.ContainsKey(t)) {
113            throw new Exception("A mapping to this node already exists.");
114          }
115
116          forwardMap[s] = t;
117          reverseMap[t] = s;
118        }
119      }
120
121      return forwardMap;
122    }
123
124    /// <summary>
125    /// Creates a compact representation of the two trees as a directed acyclic graph
126    /// </summary>
127    /// <param name="n1">The root of the first tree</param>
128    /// <param name="n2">The root of the second tree</param>
129    /// <returns>The compacted DAG representing the two trees</returns>
130    private Dictionary<ISymbolicExpressionTreeNode, GraphNode> Compact(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
131      var nodeMap = new Dictionary<ISymbolicExpressionTreeNode, GraphNode>(); // K
132      var labelMap = new Dictionary<string, GraphNode>(); // L
133      var childrenCount = new Dictionary<ISymbolicExpressionTreeNode, int>(); // Children
134
135      var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
136      var list = new List<GraphNode>();
137      var queue = new Queue<ISymbolicExpressionTreeNode>();
138
139      foreach (var n in nodes) {
140        if (n.SubtreeCount == 0) {
141          var label = n.ToString();
142          if (!labelMap.ContainsKey(label)) {
143            var z = new GraphNode { SymbolicExpressionTreeNode = n, Label = label };
144            labelMap[z.Label] = z;
145            list.Add(z);
146          }
147          nodeMap[n] = labelMap[label];
148          queue.Enqueue(n);
149        } else {
150          childrenCount[n] = n.SubtreeCount;
151        }
152      }
153      while (queue.Any()) {
154        var n = queue.Dequeue();
155
156        if (n.SubtreeCount > 0) {
157          var label = n.Symbol.Name;
158          bool found = false;
159          var depth = n.GetDepth();
160
161          bool sort = commutativeSymbols.Contains(label);
162          var nNodes = n.Subtrees.Select(x => nodeMap[x]).ToList();
163          if (sort) nNodes.Sort((a, b) => String.Compare(a.Label, b.Label, StringComparison.Ordinal));
164
165          for (int i = list.Count - 1; i >= 0; --i) {
166            var w = list[i];
167
168            if (!(n.SubtreeCount == w.ChildrenCount && label == w.Label && depth == w.Depth))
169              continue;
170
171            // sort V and W when the symbol is commutative because we are dealing with unordered trees
172            var m = w.SymbolicExpressionTreeNode;
173            var mNodes = m.Subtrees.Select(x => nodeMap[x]).ToList();
174            if (sort) mNodes.Sort((a, b) => String.Compare(a.Label, b.Label, StringComparison.Ordinal));
175
176            if (nNodes.SequenceEqual(mNodes)) {
177              nodeMap[n] = w;
178              found = true;
179              break;
180            }
181          }
182
183          if (!found) {
184            var w = new GraphNode { SymbolicExpressionTreeNode = n, Label = label, Depth = depth, ChildrenCount = n.SubtreeCount };
185            list.Add(w);
186            nodeMap[n] = w;
187          }
188        }
189
190        var p = n.Parent;
191        if (p == null)
192          continue;
193
194        childrenCount[p]--;
195
196        if (childrenCount[p] == 0)
197          queue.Enqueue(p);
198      }
199
200      return nodeMap;
201    }
202
203    /// <summary>
204    /// This method iterates the nodes of a subtree in breadth order while also sorting the subtrees of commutative symbols based on their label.
205    /// This is necessary in order for the mapping to be realized correctly.
206    /// </summary>
207    /// <param name="node">The root of the subtree</param>
208    /// <returns>A list of nodes in breadth order (with children of commutative symbols sorted by label)</returns>
209    private IEnumerable<ISymbolicExpressionTreeNode> IterateBreadthOrdered(ISymbolicExpressionTreeNode node) {
210      var list = new List<ISymbolicExpressionTreeNode> { node };
211      int i = 0;
212      while (i < list.Count) {
213        var n = list[i];
214        if (n.SubtreeCount > 0) {
215          var subtrees = commutativeSymbols.Contains(node.Symbol.Name) ? n.Subtrees.OrderBy(x => x.ToString(), StringComparer.Ordinal) : n.Subtrees;
216          list.AddRange(subtrees);
217        }
218        i++;
219      }
220      return list;
221    }
222
223    private class GraphNode {
224      public ISymbolicExpressionTreeNode SymbolicExpressionTreeNode;
225      public string Label;
226      public int Depth;
227      public int ChildrenCount;
228    }
229  }
230}
Note: See TracBrowser for help on using the repository browser.