Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeBottomUpSimilarityCalculator.cs @ 12094

Last change on this file since 12094 was 11986, checked in by jkarder, 10 years ago

#2313: merged r11978 into stable

File size: 9.4 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;
23using System.Collections.Generic;
24using System.Diagnostics;
25using System.Globalization;
26using System.Linq;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
34  [StorableClass]
35  [Item("SymbolicExpressionTreeBottomUpSimilarityCalculator", "A similarity calculator which uses the tree bottom-up distance as a similarity metric.")]
36  public class SymbolicExpressionTreeBottomUpSimilarityCalculator : SingleObjectiveSolutionSimilarityCalculator {
37    private readonly HashSet<string> commutativeSymbols = new HashSet<string> { "Addition", "Multiplication", "Average", "And", "Or", "Xor" };
38    public SymbolicExpressionTreeBottomUpSimilarityCalculator() { }
39
40    [StorableConstructor]
41    protected SymbolicExpressionTreeBottomUpSimilarityCalculator(bool deserializing)
42      : base(deserializing) {
43    }
44
45    protected SymbolicExpressionTreeBottomUpSimilarityCalculator(SymbolicExpressionTreeBottomUpSimilarityCalculator original, Cloner cloner)
46      : base(original, cloner) {
47    }
48
49    public override IDeepCloneable Clone(Cloner cloner) {
50      return new SymbolicExpressionTreeBottomUpSimilarityCalculator(this, cloner);
51    }
52
53    public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
54      if (t1 == t2)
55        return 1;
56
57      var map = ComputeBottomUpMapping(t1.Root, t2.Root);
58      return 2.0 * map.Count / (t1.Length + t2.Length);
59    }
60
61    public override double CalculateSolutionSimilarity(IScope leftSolution, IScope rightSolution) {
62      var t1 = leftSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
63      var t2 = rightSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
64
65      if (t1 == null || t2 == null)
66        throw new ArgumentException("Cannot calculate similarity when one of the arguments is null.");
67
68      var similarity = CalculateSimilarity(t1, t2);
69      if (similarity > 1.0)
70        throw new Exception("Similarity value cannot be greater than 1");
71
72      return similarity;
73    }
74
75    public Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
76      var comparer = new SymbolicExpressionTreeNodeComparer(); // use a node comparer because it's faster than calling node.ToString() (strings are expensive) and comparing strings
77      var compactedGraph = Compact(n1, n2);
78
79      var forwardMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t1 => nodes of t2
80      var reverseMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t2 => nodes of t1
81
82      // visit nodes in order of decreasing height to ensure correct mapping
83      var nodes1 = n1.IterateNodesPrefix().OrderByDescending(x => x.GetDepth()).ToList();
84      var nodes2 = n2.IterateNodesPrefix().ToList();
85      for (int i = 0; i < nodes1.Count; ++i) {
86        var v = nodes1[i];
87        if (forwardMap.ContainsKey(v))
88          continue;
89        var kv = compactedGraph[v];
90        ISymbolicExpressionTreeNode w = null;
91        for (int j = 0; j < nodes2.Count; ++j) {
92          var t = nodes2[j];
93          if (reverseMap.ContainsKey(t) || compactedGraph[t] != kv)
94            continue;
95          w = t;
96          break;
97        }
98        if (w == null) continue;
99
100        // at this point we know that v and w are isomorphic, however, the mapping cannot be done directly
101        // (as in the paper) because the trees are unordered (subtree order might differ). the solution is
102        // to sort subtrees from under commutative labels (this will work because the subtrees are isomorphic!)
103        // while iterating over the two subtrees
104        var vv = IterateBreadthOrdered(v, comparer).ToList();
105        var ww = IterateBreadthOrdered(w, comparer).ToList();
106        int len = Math.Min(vv.Count, ww.Count);
107        for (int j = 0; j < len; ++j) {
108          var s = vv[j];
109          var t = ww[j];
110          Debug.Assert(!reverseMap.ContainsKey(t));
111
112          forwardMap[s] = t;
113          reverseMap[t] = s;
114        }
115      }
116
117      return forwardMap;
118    }
119
120    /// <summary>
121    /// Creates a compact representation of the two trees as a directed acyclic graph
122    /// </summary>
123    /// <param name="n1">The root of the first tree</param>
124    /// <param name="n2">The root of the second tree</param>
125    /// <returns>The compacted DAG representing the two trees</returns>
126    private Dictionary<ISymbolicExpressionTreeNode, GraphNode> Compact(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
127      var nodeMap = new Dictionary<ISymbolicExpressionTreeNode, GraphNode>(); // K
128      var labelMap = new Dictionary<string, GraphNode>(); // L
129      var childrenCount = new Dictionary<ISymbolicExpressionTreeNode, int>(); // Children
130
131      var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
132      var list = new List<GraphNode>();
133      var queue = new Queue<ISymbolicExpressionTreeNode>();
134
135      foreach (var n in nodes) {
136        if (n.SubtreeCount == 0) {
137          var label = GetLabel(n);
138          if (!labelMap.ContainsKey(label)) {
139            var z = new GraphNode { SymbolicExpressionTreeNode = n, Label = label };
140            labelMap[z.Label] = z;
141          }
142          nodeMap[n] = labelMap[label];
143          queue.Enqueue(n);
144        } else {
145          childrenCount[n] = n.SubtreeCount;
146        }
147      }
148      while (queue.Any()) {
149        var n = queue.Dequeue();
150        if (n.SubtreeCount > 0) {
151          bool found = false;
152          var label = n.Symbol.Name;
153          var depth = n.GetDepth();
154
155          bool sort = n.SubtreeCount > 1 && commutativeSymbols.Contains(label);
156          var nSubtrees = n.Subtrees.Select(x => nodeMap[x]).ToList();
157          if (sort) nSubtrees.Sort((a, b) => string.CompareOrdinal(a.Label, b.Label));
158
159          for (int i = list.Count - 1; i >= 0; --i) {
160            var w = list[i];
161            if (!(n.SubtreeCount == w.SubtreeCount && label == w.Label && depth == w.Depth))
162              continue;
163
164            // sort V and W when the symbol is commutative because we are dealing with unordered trees
165            var m = w.SymbolicExpressionTreeNode;
166            var mSubtrees = m.Subtrees.Select(x => nodeMap[x]).ToList();
167            if (sort) mSubtrees.Sort((a, b) => string.CompareOrdinal(a.Label, b.Label));
168
169            found = nSubtrees.SequenceEqual(mSubtrees);
170            if (found) {
171              nodeMap[n] = w;
172              break;
173            }
174          }
175
176          if (!found) {
177            var w = new GraphNode { SymbolicExpressionTreeNode = n, Label = label, Depth = depth };
178            list.Add(w);
179            nodeMap[n] = w;
180          }
181        }
182
183        if (n == n1 || n == n2)
184          continue;
185
186        var p = n.Parent;
187        if (p == null)
188          continue;
189
190        childrenCount[p]--;
191
192        if (childrenCount[p] == 0)
193          queue.Enqueue(p);
194      }
195
196      return nodeMap;
197    }
198
199    private IEnumerable<ISymbolicExpressionTreeNode> IterateBreadthOrdered(ISymbolicExpressionTreeNode node, ISymbolicExpressionTreeNodeComparer comparer) {
200      var list = new List<ISymbolicExpressionTreeNode> { node };
201      int i = 0;
202      while (i < list.Count) {
203        var n = list[i];
204        if (n.SubtreeCount > 0) {
205          var subtrees = commutativeSymbols.Contains(node.Symbol.Name) ? n.Subtrees.OrderBy(x => x, comparer) : n.Subtrees;
206          list.AddRange(subtrees);
207        }
208        i++;
209      }
210      return list;
211    }
212
213    private static string GetLabel(ISymbolicExpressionTreeNode node) {
214      if (node.SubtreeCount > 0)
215        return node.Symbol.Name;
216
217      var constant = node as ConstantTreeNode;
218      if (constant != null)
219        return constant.Value.ToString(CultureInfo.InvariantCulture);
220
221      var variable = node as VariableTreeNode;
222      if (variable != null)
223        return variable.Weight + variable.VariableName;
224
225      return node.ToString();
226    }
227
228    private class GraphNode {
229      public ISymbolicExpressionTreeNode SymbolicExpressionTreeNode;
230      public string Label;
231      public int Depth;
232      public int SubtreeCount { get { return SymbolicExpressionTreeNode.SubtreeCount; } }
233    }
234  }
235}
Note: See TracBrowser for help on using the repository browser.