source: branches/HeuristicLab.BottomUpTreeDistance/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs @ 11224

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

#2215: Added checks for debugging purposes in the BottomUpSimilarityCalculator and refactored the SymbolicDataAnalysisInternalDiversityAnalyzer.

File size: 12.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.Drawing;
25using System.Globalization;
26using System.Linq;
27using System.Text;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
31using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
32using HeuristicLab.Optimization.Operators;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34
35namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
36  [StorableClass]
37  [Item("BottomUpSimilarityCalculator", "A similarity calculator which uses the tree bottom-up distance as a similarity metric.")]
38  public class BottomUpSimilarityCalculator : SingleObjectiveSolutionSimilarityCalculator {
39    private readonly HashSet<string> commutativeSymbols = new HashSet<string> { "Addition", "Multiplication", "Average", "And", "Or", "Xor" };
40
41    public BottomUpSimilarityCalculator() { }
42
43    public override IDeepCloneable Clone(Cloner cloner) {
44      return new BottomUpSimilarityCalculator(this, cloner);
45    }
46
47    protected BottomUpSimilarityCalculator(BottomUpSimilarityCalculator original, Cloner cloner)
48      : base(original, cloner) {
49    }
50
51    public override double CalculateSolutionSimilarity(IScope leftSolution, IScope rightSolution) {
52      var t1 = leftSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
53      var t2 = rightSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
54
55      if (t1 == null || t2 == null)
56        throw new ArgumentException("Cannot calculate similarity when one of the arguments is null.");
57
58      var similarity = CalculateSolutionSimilarity(t1, t2);
59      if (similarity > 1.0)
60        throw new Exception("Similarity value cannot be greater than 1");
61
62      return similarity;
63    }
64
65    public double CalculateSolutionSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
66      if (t1 == t2)
67        return 1;
68
69      var map = ComputeBottomUpMapping(t1.Root, t2.Root);
70      return 2.0 * map.Count / (t1.Length + t2.Length);
71    }
72
73    public Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
74      var compactedGraph = Compact(n1, n2);
75
76      var forwardMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t1 => nodes of t2
77      var reverseMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t2 => nodes of t1
78
79      foreach (var v in IterateBreadthOrdered(n1)) {
80        if (forwardMap.ContainsKey(v)) continue;
81        var kv = compactedGraph[v];
82        ISymbolicExpressionTreeNode w = null;
83        foreach (var t in IterateBreadthOrdered(n2)) {
84          if (reverseMap.ContainsKey(t) || compactedGraph[t] != kv) continue;
85          w = t;
86          break;
87        }
88        if (w == null) continue;
89
90        // 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)
91        // 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
92        var eV = IterateBreadthOrdered(v).GetEnumerator();
93        var eW = IterateBreadthOrdered(w).GetEnumerator();
94
95        while (eV.MoveNext() && eW.MoveNext()) {
96          var s = eV.Current;
97          var t = eW.Current;
98          if (reverseMap.ContainsKey(t))
99            throw new Exception("Mapping already present");
100          forwardMap[s] = t;
101          reverseMap[t] = s;
102        }
103      }
104
105      return forwardMap;
106    }
107
108    /// <summary>
109    /// Creates a compact representation of the two trees as a directed acyclic graph
110    /// </summary>
111    /// <param name="t1">The first tree</param>
112    /// <param name="t2">The second tree</param>
113    /// <returns>The compacted DAG representing the two trees</returns>
114    private Dictionary<ISymbolicExpressionTreeNode, IVertex> Compact(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
115      var nodesToVertices = new Dictionary<ISymbolicExpressionTreeNode, IVertex>(); // K
116      var labelsToVertices = new Dictionary<string, IVertex>(); // L
117      var childrenCount = new Dictionary<ISymbolicExpressionTreeNode, int>(); // Children
118      var vertices = new List<IVertex>(); // G
119
120      var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
121      var queue = new Queue<ISymbolicExpressionTreeNode>();
122
123      foreach (var n in nodes) {
124        if (n.SubtreeCount == 0) {
125          var label = n.ToString();
126          var z = new Vertex { Content = n, Label = label };
127          labelsToVertices[z.Label] = z;
128          vertices.Add(z);
129          queue.Enqueue(n);
130        } else {
131          childrenCount[n] = n.SubtreeCount;
132        }
133      }
134
135      while (queue.Any()) {
136        var v = queue.Dequeue();
137        string label;
138        if (v.SubtreeCount == 0) {
139          label = v.ToString();
140          nodesToVertices[v] = labelsToVertices[label]; // 18
141        } else {
142          label = v.Symbol.Name;
143          bool found = false;
144          var height = v.GetDepth();
145
146          bool sort = commutativeSymbols.Contains(label);
147          var vSubtrees = v.Subtrees.Select(x => nodesToVertices[x]).ToList();
148          if (sort) vSubtrees.Sort((a, b) => String.Compare(a.Label, b.Label, StringComparison.Ordinal));
149
150          // for all nodes w in G in reverse order
151          for (int i = vertices.Count - 1; i >= 0; --i) {
152            var w = vertices[i];
153            var n = (ISymbolicExpressionTreeNode)w.Content;
154            if (n.SubtreeCount == 0) continue; // v is a function node so w will have to be a function node as well
155            if (height != (int)w.Weight || v.SubtreeCount != n.SubtreeCount || label != w.Label)
156              continue;
157
158            // sort V and W when the symbol is commutative because we are dealing with unordered trees
159            var wSubtrees = sort ? w.OutArcs.Select(x => x.Target).OrderBy(x => x.Label)
160                                 : w.OutArcs.Select(x => x.Target);
161
162            if (vSubtrees.SequenceEqual(wSubtrees)) {
163              nodesToVertices[v] = w;
164              found = true;
165              break;
166            }
167          } // 32: end for
168
169          if (!found) {
170            var w = new Vertex { Content = v, Label = label, Weight = height };
171            vertices.Add(w);
172            nodesToVertices[v] = w;
173
174            foreach (var u in v.Subtrees) {
175              AddArc(w, nodesToVertices[u]);
176            } // 40: end for
177          } // 41: end if
178        } // 42: end if
179
180        var p = v.Parent;
181        if (p == null)
182          continue;
183
184        childrenCount[p]--;
185
186        if (childrenCount[p] == 0)
187          queue.Enqueue(p);
188      }
189
190      return nodesToVertices;
191    }
192
193    private IEnumerable<ISymbolicExpressionTreeNode> IterateBreadthOrdered(ISymbolicExpressionTreeNode node) {
194      var list = new List<ISymbolicExpressionTreeNode> { node };
195      int i = 0;
196      while (i < list.Count) {
197        var n = list[i];
198        if (n.SubtreeCount > 0) {
199          var subtrees = commutativeSymbols.Contains(node.Symbol.Name) ? n.Subtrees.OrderBy(s => s.ToString()) : n.Subtrees;
200          list.AddRange(subtrees);
201        }
202        i++;
203      }
204      return list;
205    }
206
207    private static IArc AddArc(IVertex source, IVertex target) {
208      var arc = new Arc(source, target);
209      source.AddForwardArc(arc);
210      target.AddReverseArc(arc);
211      return arc;
212    }
213
214    // debugging
215    private static string FormatMapping(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> map) {
216      var symbolNameMap = new Dictionary<string, string>
217    {
218      {"ProgramRootSymbol", "Prog"},
219      {"StartSymbol","RPB"},
220      {"Multiplication", "$\\times$"},
221      {"Division", "$\\div$"},
222      {"Addition", "$+$"},
223      {"Subtraction", "$-$"},
224      {"Exponential", "$\\exp$"},
225      {"Logarithm", "$\\log$"}
226    };
227
228      var sb = new StringBuilder();
229      var nodeIds = new Dictionary<ISymbolicExpressionTreeNode, string>();
230      int offset = 0;
231      var layoutEngine = new ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode>(x => x.Subtrees);
232      var nodeCoordinates = layoutEngine.CalculateLayout(t1.Root).ToDictionary(n => n.Content, n => new PointF(n.X, n.Y));
233
234      double ws = 0.5;
235      double hs = 0.5;
236
237      var nl = Environment.NewLine;
238      sb.Append("\\documentclass[class=minimal,border=0pt]{standalone}" + nl +
239                 "\\usepackage{tikz}" + nl +
240                 "\\begin{document}" + nl +
241                 "\\begin{tikzpicture}" + nl +
242                 "\\def\\ws{1}" + nl +
243                 "\\def\\hs{0.7}" + nl +
244                 "\\def\\offs{" + offset + "}" + nl);
245
246      foreach (var node in t1.IterateNodesBreadth()) {
247        var id = Guid.NewGuid().ToString();
248        nodeIds[node] = id;
249        var coord = nodeCoordinates[node];
250        var nodeName = symbolNameMap.ContainsKey(node.Symbol.Name) ? symbolNameMap[node.Symbol.Name] : node.ToString();
251        sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\node ({0}) at (\\ws*{1} + \\offs,\\hs*{2}) {{{3}}};", nodeIds[node], ws * coord.X, -hs * coord.Y, EscapeLatexString(nodeName)));
252      }
253
254      foreach (ISymbolicExpressionTreeNode t in t1.IterateNodesBreadth()) {
255        var n = t;
256        foreach (var s in t.Subtrees) {
257          sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\draw ({0}) -- ({1});", nodeIds[n], nodeIds[s]));
258        }
259      }
260
261      nodeCoordinates = layoutEngine.CalculateLayout(t2.Root).ToDictionary(n => n.Content, n => new PointF(n.X, n.Y));
262
263      offset = 20;
264      sb.Append("\\def\\offs{" + offset + "}" + nl);
265      foreach (var node in t2.IterateNodesBreadth()) {
266        var id = Guid.NewGuid().ToString();
267        nodeIds[node] = id;
268        var coord = nodeCoordinates[node];
269        var nodeName = symbolNameMap.ContainsKey(node.Symbol.Name) ? symbolNameMap[node.Symbol.Name] : node.ToString();
270        sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\node ({0}) at (\\ws*{1} + \\offs,\\hs*{2}) {{{3}}};", nodeIds[node], ws * coord.X, -hs * coord.Y, EscapeLatexString(nodeName)));
271      }
272
273      foreach (ISymbolicExpressionTreeNode t in t2.IterateNodesBreadth()) {
274        var n = t;
275        foreach (var s in t.Subtrees) {
276          sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\draw ({0}) -- ({1});", nodeIds[n], nodeIds[s]));
277        }
278      }
279
280      foreach (var p in map) {
281        var id1 = nodeIds[p.Key];
282        var id2 = nodeIds[p.Value];
283
284        sb.Append(string.Format(CultureInfo.InvariantCulture, "\\path[draw,->,color=gray] ({0}) edge[bend left,dashed] ({1});" + Environment.NewLine, id1, id2));
285      }
286      sb.Append("\\end{tikzpicture}" + nl +
287                "\\end{document}" + nl);
288      return sb.ToString();
289    }
290
291    private static string EscapeLatexString(string s) {
292      return s.Replace("\\", "\\\\").Replace("{", "\\{").Replace("}", "\\}").Replace("_", "\\_");
293    }
294  }
295}
Note: See TracBrowser for help on using the repository browser.