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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Drawing;
|
---|
25 | using System.Globalization;
|
---|
26 | using System.Linq;
|
---|
27 | using System.Text;
|
---|
28 | using HeuristicLab.Common;
|
---|
29 | using HeuristicLab.Core;
|
---|
30 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
31 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
|
---|
32 | using HeuristicLab.Optimization.Operators;
|
---|
33 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
34 |
|
---|
35 | namespace 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 | // visit nodes in order of decreasing height to ensure correct mapping
|
---|
80 | foreach (var v in n1.IterateNodesPrefix().OrderByDescending(x => compactedGraph[x].Weight)) {
|
---|
81 | if (forwardMap.ContainsKey(v))
|
---|
82 | continue;
|
---|
83 | var kv = compactedGraph[v];
|
---|
84 | ISymbolicExpressionTreeNode w = null;
|
---|
85 | foreach (var t in n2.IterateNodesPrefix()) {
|
---|
86 | if (reverseMap.ContainsKey(t) || compactedGraph[t] != kv)
|
---|
87 | continue;
|
---|
88 | w = t;
|
---|
89 | break;
|
---|
90 | }
|
---|
91 | if (w == null) continue;
|
---|
92 |
|
---|
93 | // 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)
|
---|
94 | // 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
|
---|
95 | var eV = IterateBreadthOrdered(v).GetEnumerator();
|
---|
96 | var eW = IterateBreadthOrdered(w).GetEnumerator();
|
---|
97 |
|
---|
98 | while (eV.MoveNext() && eW.MoveNext()) {
|
---|
99 | var s = eV.Current;
|
---|
100 | var t = eW.Current;
|
---|
101 |
|
---|
102 | if (reverseMap.ContainsKey(t)) {
|
---|
103 | throw new Exception("A mapping to this node already exists.");
|
---|
104 | }
|
---|
105 |
|
---|
106 | forwardMap[s] = t;
|
---|
107 | reverseMap[t] = s;
|
---|
108 | }
|
---|
109 | }
|
---|
110 |
|
---|
111 | return forwardMap;
|
---|
112 | }
|
---|
113 |
|
---|
114 | /// <summary>
|
---|
115 | /// Creates a compact representation of the two trees as a directed acyclic graph
|
---|
116 | /// </summary>
|
---|
117 | /// <param name="t1">The first tree</param>
|
---|
118 | /// <param name="t2">The second tree</param>
|
---|
119 | /// <returns>The compacted DAG representing the two trees</returns>
|
---|
120 | private Dictionary<ISymbolicExpressionTreeNode, IVertex> Compact(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
|
---|
121 | var nodesToVertices = new Dictionary<ISymbolicExpressionTreeNode, IVertex>(); // K
|
---|
122 | var labelsToVertices = new Dictionary<string, IVertex>(); // L
|
---|
123 | var childrenCount = new Dictionary<ISymbolicExpressionTreeNode, int>(); // Children
|
---|
124 | var vertices = new List<IVertex>(); // G
|
---|
125 |
|
---|
126 | var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
|
---|
127 | var queue = new Queue<ISymbolicExpressionTreeNode>();
|
---|
128 |
|
---|
129 | foreach (var n in nodes) {
|
---|
130 | if (n.SubtreeCount == 0) {
|
---|
131 | var label = n.ToString();
|
---|
132 | if (!labelsToVertices.ContainsKey(label)) {
|
---|
133 | var z = new Vertex { Content = n, Label = label };
|
---|
134 | labelsToVertices[z.Label] = z;
|
---|
135 | vertices.Add(z);
|
---|
136 | }
|
---|
137 | nodesToVertices[n] = labelsToVertices[label];
|
---|
138 | queue.Enqueue(n);
|
---|
139 | } else {
|
---|
140 | childrenCount[n] = n.SubtreeCount;
|
---|
141 | }
|
---|
142 | }
|
---|
143 |
|
---|
144 | while (queue.Any()) {
|
---|
145 | var v = queue.Dequeue();
|
---|
146 |
|
---|
147 | if (v.SubtreeCount > 0) {
|
---|
148 | var label = v.Symbol.Name;
|
---|
149 | bool found = false;
|
---|
150 | var height = v.GetDepth();
|
---|
151 |
|
---|
152 | bool sort = commutativeSymbols.Contains(label);
|
---|
153 | var vSubtrees = v.Subtrees.Select(x => nodesToVertices[x]).ToList();
|
---|
154 | if (sort) vSubtrees.Sort((a, b) => String.Compare(a.Label, b.Label, StringComparison.Ordinal));
|
---|
155 |
|
---|
156 | // for all nodes w in G in reverse order
|
---|
157 | for (int i = vertices.Count - 1; i >= 0; --i) {
|
---|
158 | var w = vertices[i];
|
---|
159 | var n = (ISymbolicExpressionTreeNode)w.Content;
|
---|
160 | if (v.SubtreeCount != n.SubtreeCount || label != w.Label || height != (int)w.Weight)
|
---|
161 | continue;
|
---|
162 |
|
---|
163 | // sort V and W when the symbol is commutative because we are dealing with unordered trees
|
---|
164 | var wSubtrees = n.Subtrees.Select(x => nodesToVertices[x]).ToList();
|
---|
165 | if (sort) wSubtrees.Sort((a, b) => String.Compare(a.Label, b.Label, StringComparison.Ordinal));
|
---|
166 |
|
---|
167 | if (vSubtrees.SequenceEqual(wSubtrees)) {
|
---|
168 | nodesToVertices[v] = w;
|
---|
169 | found = true;
|
---|
170 | break;
|
---|
171 | }
|
---|
172 | } // 32: end for
|
---|
173 |
|
---|
174 | if (!found) {
|
---|
175 | var w = new Vertex { Content = v, Label = label, Weight = height };
|
---|
176 | vertices.Add(w);
|
---|
177 | nodesToVertices[v] = w;
|
---|
178 |
|
---|
179 | foreach (var u in v.Subtrees) {
|
---|
180 | AddArc(w, nodesToVertices[u]);
|
---|
181 | } // 40: end for
|
---|
182 | } // 41: end if
|
---|
183 | } // 42: end if
|
---|
184 |
|
---|
185 | var p = v.Parent;
|
---|
186 | if (p == null)
|
---|
187 | continue;
|
---|
188 |
|
---|
189 | childrenCount[p]--;
|
---|
190 |
|
---|
191 | if (childrenCount[p] == 0)
|
---|
192 | queue.Enqueue(p);
|
---|
193 | }
|
---|
194 |
|
---|
195 | return nodesToVertices;
|
---|
196 | }
|
---|
197 |
|
---|
198 | private IEnumerable<ISymbolicExpressionTreeNode> IterateBreadthOrdered(ISymbolicExpressionTreeNode node) {
|
---|
199 | var list = new List<ISymbolicExpressionTreeNode> { node };
|
---|
200 | int i = 0;
|
---|
201 | while (i < list.Count) {
|
---|
202 | var n = list[i];
|
---|
203 | if (n.SubtreeCount > 0) {
|
---|
204 | var subtrees = commutativeSymbols.Contains(node.Symbol.Name) ? n.Subtrees.OrderBy(s => s.ToString()) : n.Subtrees;
|
---|
205 | list.AddRange(subtrees);
|
---|
206 | }
|
---|
207 | i++;
|
---|
208 | }
|
---|
209 | return list;
|
---|
210 | }
|
---|
211 |
|
---|
212 | private static IArc AddArc(IVertex source, IVertex target) {
|
---|
213 | var arc = new Arc(source, target);
|
---|
214 | source.AddForwardArc(arc);
|
---|
215 | target.AddReverseArc(arc);
|
---|
216 | return arc;
|
---|
217 | }
|
---|
218 |
|
---|
219 | // debugging
|
---|
220 | private static string FormatMapping(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> map) {
|
---|
221 | var symbolNameMap = new Dictionary<string, string>
|
---|
222 | {
|
---|
223 | {"ProgramRootSymbol", "Prog"},
|
---|
224 | {"StartSymbol","RPB"},
|
---|
225 | {"Multiplication", "$\\times$"},
|
---|
226 | {"Division", "$\\div$"},
|
---|
227 | {"Addition", "$+$"},
|
---|
228 | {"Subtraction", "$-$"},
|
---|
229 | {"Exponential", "$\\exp$"},
|
---|
230 | {"Logarithm", "$\\log$"}
|
---|
231 | };
|
---|
232 |
|
---|
233 | var sb = new StringBuilder();
|
---|
234 | var nodeIds = new Dictionary<ISymbolicExpressionTreeNode, string>();
|
---|
235 | int offset = 0;
|
---|
236 | var layoutEngine = new ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode>(x => x.Subtrees);
|
---|
237 | var nodeCoordinates = layoutEngine.CalculateLayout(t1.Root).ToDictionary(n => n.Content, n => new PointF(n.X, n.Y));
|
---|
238 |
|
---|
239 | double ws = 0.5;
|
---|
240 | double hs = 0.5;
|
---|
241 |
|
---|
242 | var nl = Environment.NewLine;
|
---|
243 | sb.Append("\\documentclass[class=minimal,border=0pt]{standalone}" + nl +
|
---|
244 | "\\usepackage{tikz}" + nl +
|
---|
245 | "\\begin{document}" + nl +
|
---|
246 | "\\begin{tikzpicture}" + nl +
|
---|
247 | "\\def\\ws{1}" + nl +
|
---|
248 | "\\def\\hs{0.7}" + nl +
|
---|
249 | "\\def\\offs{" + offset + "}" + nl);
|
---|
250 |
|
---|
251 | foreach (var node in t1.IterateNodesBreadth()) {
|
---|
252 | var id = Guid.NewGuid().ToString();
|
---|
253 | nodeIds[node] = id;
|
---|
254 | var coord = nodeCoordinates[node];
|
---|
255 | var nodeName = symbolNameMap.ContainsKey(node.Symbol.Name) ? symbolNameMap[node.Symbol.Name] : node.ToString();
|
---|
256 | 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)));
|
---|
257 | }
|
---|
258 |
|
---|
259 | foreach (ISymbolicExpressionTreeNode t in t1.IterateNodesBreadth()) {
|
---|
260 | var n = t;
|
---|
261 | foreach (var s in t.Subtrees) {
|
---|
262 | sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\draw ({0}) -- ({1});", nodeIds[n], nodeIds[s]));
|
---|
263 | }
|
---|
264 | }
|
---|
265 |
|
---|
266 | nodeCoordinates = layoutEngine.CalculateLayout(t2.Root).ToDictionary(n => n.Content, n => new PointF(n.X, n.Y));
|
---|
267 |
|
---|
268 | offset = 20;
|
---|
269 | sb.Append("\\def\\offs{" + offset + "}" + nl);
|
---|
270 | foreach (var node in t2.IterateNodesBreadth()) {
|
---|
271 | var id = Guid.NewGuid().ToString();
|
---|
272 | nodeIds[node] = id;
|
---|
273 | var coord = nodeCoordinates[node];
|
---|
274 | var nodeName = symbolNameMap.ContainsKey(node.Symbol.Name) ? symbolNameMap[node.Symbol.Name] : node.ToString();
|
---|
275 | 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)));
|
---|
276 | }
|
---|
277 |
|
---|
278 | foreach (ISymbolicExpressionTreeNode t in t2.IterateNodesBreadth()) {
|
---|
279 | var n = t;
|
---|
280 | foreach (var s in t.Subtrees) {
|
---|
281 | sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\draw ({0}) -- ({1});", nodeIds[n], nodeIds[s]));
|
---|
282 | }
|
---|
283 | }
|
---|
284 |
|
---|
285 | foreach (var p in map) {
|
---|
286 | var id1 = nodeIds[p.Key];
|
---|
287 | var id2 = nodeIds[p.Value];
|
---|
288 |
|
---|
289 | sb.Append(string.Format(CultureInfo.InvariantCulture, "\\path[draw,->,color=gray] ({0}) edge[bend left,dashed] ({1});" + Environment.NewLine, id1, id2));
|
---|
290 | }
|
---|
291 | sb.Append("\\end{tikzpicture}" + nl +
|
---|
292 | "\\end{document}" + nl);
|
---|
293 | return sb.ToString();
|
---|
294 | }
|
---|
295 |
|
---|
296 | private static string EscapeLatexString(string s) {
|
---|
297 | return s.Replace("\\", "\\\\").Replace("{", "\\{").Replace("}", "\\}").Replace("_", "\\_");
|
---|
298 | }
|
---|
299 | }
|
---|
300 | }
|
---|