Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeBottomUpSimilarityCalculator.cs @ 12287

Last change on this file since 12287 was 12287, checked in by bburlacu, 9 years ago

#1772: Added storable attributes to the before/after evolution tracking operators in HeuristicLab.Problems.DataAnalysis.Symbolic. Very small changes to the trace calculator (updated license header, removed old sample count code).

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