Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs @ 11488

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

#1772: Merged changes from the BottomUpSimilarityCalculator branch.

  • Property svn:mergeinfo set to (toggle deleted branches)
    /branches/HeuristicLab.BottomUpTreeDistance/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.csmergedeligible
    /branches/Benchmarking/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs6917-7005
    /branches/CloningRefactoring/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs4656-4721
    /branches/DataAnalysis Refactoring/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs5471-5473
    /branches/DataAnalysis SolutionEnsembles/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs5815-6180
    /branches/DataAnalysis.IslandAlgorithms/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs10598
    /branches/DataAnalysis/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs4458-4459,​4462,​4464
    /branches/DataPreprocessing/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs10085-11101
    /branches/ExportSymbolicDataAnalysisSolutions/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs9511-9585
    /branches/GP.Grammar.Editor/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs6284-6795
    /branches/GP.Symbols (TimeLag, Diff, Integral)/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs5060
    /branches/HLScript/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs10331-10358
    /branches/HeuristicLab.BottomUpTreeDistance/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpTreeSimilarityCalculator.cs11237-11482
    /branches/HeuristicLab.DataAnalysis.Symbolic.LinearInterpreter/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs9271-9826
    /branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs7098-8789
    /branches/HeuristicLab.TreeSimplifier/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs8388-8942
    /branches/LogResidualEvaluator/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs10202-10483
    /branches/NET40/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs5138-5162
    /branches/ParallelEngine/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs5175-5192
    /branches/ProblemInstancesRegressionAndClassification/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs7568-7810
    /branches/QAPAlgorithms/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs6350-6627
    /branches/Restructure trunk solution/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs6828
    /branches/SpectralKernelForGaussianProcesses/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs10204-10479
    /branches/SuccessProgressAnalysis/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs5370-5682
    /branches/Trunk/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs6829-6865
    /branches/VNS/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs5594-5752
    /branches/histogram/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs5959-6341
    /stable/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs10032-10033,​11170,​11173
    /trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs10269-11210
File size: 9.2 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.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("BottomUpSimilarityCalculator", "A similarity calculator which uses the tree bottom-up distance as a similarity metric.")]
36  public class BottomUpSimilarityCalculator : SingleObjectiveSolutionSimilarityCalculator, ISymbolicDataAnalysisExpressionSimilarityCalculator {
37    private readonly HashSet<string> commutativeSymbols = new HashSet<string> { "Addition", "Multiplication", "Average", "And", "Or", "Xor" };
38    public bool MatchVariableWeights { get; set; }
39    public bool MatchConstantValues { get; set; }
40
41    public BottomUpSimilarityCalculator() { }
42
43    protected BottomUpSimilarityCalculator(BottomUpSimilarityCalculator original, Cloner cloner)
44      : base(original, cloner) {
45    }
46
47    public override IDeepCloneable Clone(Cloner cloner) {
48      return new BottomUpSimilarityCalculator(this, cloner);
49    }
50
51    public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
52      if (t1 == t2)
53        return 1;
54
55      var map = ComputeBottomUpMapping(t1.Root, t2.Root);
56      return 2.0 * map.Count / (t1.Length + t2.Length);
57    }
58
59    public override double CalculateSolutionSimilarity(IScope leftSolution, IScope rightSolution) {
60      var t1 = leftSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
61      var t2 = rightSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
62
63      if (t1 == null || t2 == null)
64        throw new ArgumentException("Cannot calculate similarity when one of the arguments is null.");
65
66      var similarity = CalculateSimilarity(t1, t2);
67      if (similarity > 1.0)
68        throw new Exception("Similarity value cannot be greater than 1");
69
70      return similarity;
71    }
72
73    public Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
74      var comparer = new SymbolicExpressionTreeNodeComparer(); // use a node comparer because it's faster than calling node.ToString() (strings are expensive) and comparing strings
75      var compactedGraph = Compact(n1, n2);
76
77      var forwardMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t1 => nodes of t2
78      var reverseMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t2 => nodes of t1
79
80      // visit nodes in order of decreasing height to ensure correct mapping
81      var nodes1 = n1.IterateNodesPrefix().ToList();
82      var nodes2 = n2.IterateNodesPrefix().ToList();
83      foreach (var v in nodes1) {
84        if (forwardMap.ContainsKey(v))
85          continue;
86        var kv = compactedGraph[v];
87        ISymbolicExpressionTreeNode w = null;
88        foreach (var t in nodes2) {
89          if (reverseMap.ContainsKey(t) || compactedGraph[t] != kv)
90            continue;
91          w = t;
92          break;
93        }
94        if (w == null) continue;
95
96        // 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)
97        // 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
98        var eV = IterateBreadthOrdered(v, comparer).GetEnumerator();
99        var eW = IterateBreadthOrdered(w, comparer).GetEnumerator();
100
101        while (eV.MoveNext() && eW.MoveNext()) {
102          var s = eV.Current;
103          var t = eW.Current;
104
105          Debug.Assert(!reverseMap.ContainsKey(t));
106
107          forwardMap[s] = t;
108          reverseMap[t] = s;
109        }
110      }
111
112      return forwardMap;
113    }
114
115    /// <summary>
116    /// Creates a compact representation of the two trees as a directed acyclic graph
117    /// </summary>
118    /// <param name="n1">The root of the first tree</param>
119    /// <param name="n2">The root of the second tree</param>
120    /// <returns>The compacted DAG representing the two trees</returns>
121    private Dictionary<ISymbolicExpressionTreeNode, GraphNode> Compact(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
122      var nodeMap = new Dictionary<ISymbolicExpressionTreeNode, GraphNode>(); // K
123      var labelMap = new Dictionary<string, GraphNode>(); // L
124      var childrenCount = new Dictionary<ISymbolicExpressionTreeNode, int>(); // Children
125
126      var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
127      var list = new List<GraphNode>();
128      var queue = new Queue<ISymbolicExpressionTreeNode>();
129
130      foreach (var n in nodes) {
131        if (n.SubtreeCount == 0) {
132          var label = Label(n);
133          if (!labelMap.ContainsKey(label)) {
134            var z = new GraphNode { SymbolicExpressionTreeNode = n, Label = label };
135            labelMap[z.Label] = z;
136            list.Add(z);
137          }
138          nodeMap[n] = labelMap[label];
139          queue.Enqueue(n);
140        } else {
141          childrenCount[n] = n.SubtreeCount;
142        }
143      }
144      while (queue.Any()) {
145        var n = queue.Dequeue();
146
147        if (n.SubtreeCount > 0) {
148          var label = n.Symbol.Name;
149          bool found = false;
150          var depth = n.GetDepth();
151
152          bool sort = commutativeSymbols.Contains(label);
153          var nNodes = n.Subtrees.Select(x => nodeMap[x]).ToList();
154          if (sort) nNodes.Sort((a, b) => string.CompareOrdinal(a.Label, b.Label));
155
156          for (int i = list.Count - 1; i >= 0; --i) {
157            var w = list[i];
158
159            if (!(n.SubtreeCount == w.ChildrenCount && label == w.Label && depth == w.Depth))
160              continue;
161
162            // sort V and W when the symbol is commutative because we are dealing with unordered trees
163            var m = w.SymbolicExpressionTreeNode;
164            var mNodes = m.Subtrees.Select(x => nodeMap[x]).ToList();
165            if (sort) mNodes.Sort((a, b) => string.CompareOrdinal(a.Label, b.Label));
166
167            if (nNodes.SequenceEqual(mNodes)) {
168              nodeMap[n] = w;
169              found = true;
170              break;
171            }
172          }
173
174          if (!found) {
175            var w = new GraphNode { SymbolicExpressionTreeNode = n, Label = label, Depth = depth };
176            list.Add(w);
177            nodeMap[n] = w;
178          }
179        }
180
181        if (n == n1 || n == n2)
182          continue;
183
184        var p = n.Parent;
185        if (p == null)
186          continue;
187
188        childrenCount[p]--;
189
190        if (childrenCount[p] == 0)
191          queue.Enqueue(p);
192      }
193
194      return nodeMap;
195    }
196
197    private IEnumerable<ISymbolicExpressionTreeNode> IterateBreadthOrdered(ISymbolicExpressionTreeNode node, ISymbolicExpressionTreeNodeComparer comparer) {
198      var list = new List<ISymbolicExpressionTreeNode> { node };
199      int i = 0;
200      while (i < list.Count) {
201        var n = list[i];
202        if (n.SubtreeCount > 0) {
203          var subtrees = commutativeSymbols.Contains(node.Symbol.Name) ? n.Subtrees.OrderBy(x => x, comparer) : n.Subtrees;
204          list.AddRange(subtrees);
205        }
206        i++;
207      }
208      return list;
209    }
210
211    private string Label(ISymbolicExpressionTreeNode node) {
212      if (node.SubtreeCount > 0)
213        return node.Symbol.Name;
214
215      var constant = node as ConstantTreeNode;
216      if (constant != null)
217        return MatchConstantValues ? constant.Value.ToString(CultureInfo.InvariantCulture) : constant.Symbol.Name;
218      var variable = node as VariableTreeNode;
219      if (variable != null) {
220        return MatchVariableWeights ? variable.Weight + variable.VariableName : variable.VariableName;
221      }
222
223      return node.ToString();
224    }
225
226    private class GraphNode {
227      public ISymbolicExpressionTreeNode SymbolicExpressionTreeNode;
228      public string Label;
229      public int Depth;
230      public int ChildrenCount { get { return SymbolicExpressionTreeNode.SubtreeCount; } }
231    }
232  }
233}
Note: See TracBrowser for help on using the repository browser.