Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2215: Fixed incorrect namespace of the BottomUpSimilarityCalculator. Changed signature of ComputeBottomMapping method to take tree nodes as arguments rather than trees, because we should be able to compute the bottom-up distance for any two subtrees. Added internal diversity calculator based on the bottom-up distance, which computes the average diversity of all the nodes inside a tree individual.

File size: 8.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("BottomUpSimilarityCalculator", "A similarity calculator which uses the tree bottom-up distance as a similarity metric.")]
34  public class BottomUpSimilarityCalculator : SingleObjectiveSolutionSimilarityCalculator {
35    private readonly HashSet<string> commutativeSymbols = new HashSet<string> { "Addition", "Multiplication", "Average", "And", "Or", "Xor" };
36
37    public BottomUpSimilarityCalculator() { }
38
39    public override IDeepCloneable Clone(Cloner cloner) {
40      return new BottomUpSimilarityCalculator(this, cloner);
41    }
42
43    protected BottomUpSimilarityCalculator(BottomUpSimilarityCalculator original, Cloner cloner)
44      : base(original, cloner) {
45    }
46
47    public override double CalculateSolutionSimilarity(IScope leftSolution, IScope rightSolution) {
48      var t1 = leftSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
49      var t2 = rightSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
50
51      if (t1 == null || t2 == null)
52        throw new ArgumentException("Cannot calculate similarity when one of the arguments is null.");
53
54      return CalculateSolutionSimilarity(t1, t2);
55    }
56
57    public double CalculateSolutionSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
58      if (t1 == t2)
59        return 1;
60
61      var map = ComputeBottomUpMapping(t1.Root, t2.Root);
62      return 2.0 * map.Count / (t1.Length + t2.Length);
63    }
64
65    public Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
66      var compactedGraph = Compact(n1, n2);
67
68      var forwardMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t1 => nodes of t2
69      var reverseMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t2 => nodes of t1
70
71      foreach (var v in n1.IterateNodesBreadth()) {
72        if (forwardMap.ContainsKey(v)) continue;
73        var kv = compactedGraph[v];
74        ISymbolicExpressionTreeNode w = null;
75        foreach (var t in n2.IterateNodesBreadth()) {
76          if (reverseMap.ContainsKey(t) || compactedGraph[t] != kv) continue;
77          w = t;
78          break;
79        }
80        if (w == null) continue;
81
82        // 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)
83        // 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
84        var eV = IterateBreadthOrdered(v).GetEnumerator();
85        var eW = IterateBreadthOrdered(w).GetEnumerator();
86
87        while (eV.MoveNext() && eW.MoveNext()) {
88          var s = eV.Current;
89          var t = eW.Current;
90          forwardMap[s] = t;
91          reverseMap[t] = s;
92        }
93      }
94
95      return forwardMap;
96    }
97
98    /// <summary>
99    /// Creates a compact representation of the two trees as a directed acyclic graph
100    /// </summary>
101    /// <param name="t1">The first tree</param>
102    /// <param name="t2">The second tree</param>
103    /// <returns>The compacted DAG representing the two trees</returns>
104    private Dictionary<ISymbolicExpressionTreeNode, IVertex> Compact(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
105      var nodesToVertices = new Dictionary<ISymbolicExpressionTreeNode, IVertex>(); // K
106      var labelsToVertices = new Dictionary<string, IVertex>(); // L
107      var childrenCount = new Dictionary<ISymbolicExpressionTreeNode, int>(); // Children
108      var vertices = new List<IVertex>(); // G
109
110      var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
111      var queue = new Queue<ISymbolicExpressionTreeNode>();
112
113      foreach (var n in nodes) {
114        if (n.SubtreeCount == 0) {
115          var label = n.ToString();
116          var z = new Vertex { Content = n, Label = label };
117          labelsToVertices[z.Label] = z;
118          vertices.Add(z);
119          queue.Enqueue(n);
120        } else {
121          childrenCount[n] = n.SubtreeCount;
122        }
123      }
124
125      while (queue.Any()) {
126        var v = queue.Dequeue();
127        string label;
128        if (v.SubtreeCount == 0) {
129          label = v.ToString();
130          nodesToVertices[v] = labelsToVertices[label]; // 18
131        } else {
132          label = v.Symbol.Name;
133          bool found = false;
134          var height = v.GetDepth();
135
136          bool sort = commutativeSymbols.Contains(label);
137          var vSubtrees = v.Subtrees.Select(x => nodesToVertices[x]).ToList();
138          if (sort) vSubtrees.Sort((a, b) => String.Compare(a.Label, b.Label, StringComparison.Ordinal));
139
140          // for all nodes w in G in reverse order
141          for (int i = vertices.Count - 1; i >= 0; --i) {
142            var w = vertices[i];
143            var n = (ISymbolicExpressionTreeNode)w.Content;
144            if (n.SubtreeCount == 0) continue; // v is a function node so w will have to be a function node as well
145            if (height != (int)w.Weight || v.SubtreeCount != n.SubtreeCount || label != w.Label)
146              continue;
147
148            // sort V and W when the symbol is commutative because we are dealing with unordered trees
149            var wSubtrees = sort ? w.OutArcs.Select(x => x.Target).OrderBy(x => x.Label)
150                                 : w.OutArcs.Select(x => x.Target);
151
152            if (vSubtrees.SequenceEqual(wSubtrees)) {
153              nodesToVertices[v] = w;
154              found = true;
155              break;
156            }
157          } // 32: end for
158
159          if (!found) {
160            var w = new Vertex { Content = v, Label = label, Weight = height };
161            vertices.Add(w);
162            nodesToVertices[v] = w;
163
164            foreach (var u in v.Subtrees) {
165              AddArc(w, nodesToVertices[u]);
166            } // 40: end for
167          } // 41: end if
168        } // 42: end if
169
170        var p = v.Parent;
171        if (p == null)
172          continue;
173
174        childrenCount[p]--;
175
176        if (childrenCount[p] == 0)
177          queue.Enqueue(p);
178      }
179
180      return nodesToVertices;
181    }
182
183    private IEnumerable<ISymbolicExpressionTreeNode> IterateBreadthOrdered(ISymbolicExpressionTreeNode node) {
184      var list = new List<ISymbolicExpressionTreeNode> { node };
185      int i = 0;
186      while (i < list.Count) {
187        var n = list[i];
188        if (n.SubtreeCount > 0) {
189          var subtrees = commutativeSymbols.Contains(node.Symbol.Name) ? n.Subtrees.OrderBy(s => s.ToString()) : n.Subtrees;
190          list.AddRange(subtrees);
191        }
192        i++;
193      }
194      return list;
195    }
196
197    private static IArc AddArc(IVertex source, IVertex target) {
198      var arc = new Arc(source, target);
199      source.AddForwardArc(arc);
200      target.AddReverseArc(arc);
201      return arc;
202    }
203  }
204}
Note: See TracBrowser for help on using the repository browser.