Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeBottomUpSimilarityCalculator.cs @ 14353

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

#2685: Add correction step for values miscalculated due to cyclical symbol dependencies in the grammar. Updated unit test.

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