Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeBottomUpSimilarityCalculator.cs @ 18214

Last change on this file since 18214 was 18141, checked in by chaider, 3 years ago

#3140 merged branch into trunk

File size: 9.6 KB
RevLine 
[11219]1#region License Information
2/* HeuristicLab
[17180]3 * Copyright (C) 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.Globalization;
[11219]25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Optimization.Operators;
[16565]30using HEAL.Attic;
[11219]31
[16283]32using NodeMap = System.Collections.Generic.Dictionary<HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ISymbolicExpressionTreeNode, HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ISymbolicExpressionTreeNode>;
33
[11221]34namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
[16565]35  [StorableType("63ACB7A4-137F-468F-BE42-A4CA6B62C63B")]
[11910]36  [Item("SymbolicExpressionTreeBottomUpSimilarityCalculator", "A similarity calculator which uses the tree bottom-up distance as a similarity metric.")]
[12103]37  public class SymbolicExpressionTreeBottomUpSimilarityCalculator : SolutionSimilarityCalculator {
[11486]38    private readonly HashSet<string> commutativeSymbols = new HashSet<string> { "Addition", "Multiplication", "Average", "And", "Or", "Xor" };
[12070]39
[12103]40    public SymbolicExpressionTreeBottomUpSimilarityCalculator() { }
[12070]41    protected override bool IsCommutative { get { return true; } }
42
[18141]43    public bool MatchNumericValues { get; set; }
[16278]44    public bool MatchVariableWeights { get; set; }
45
[11918]46    [StorableConstructor]
[16565]47    protected SymbolicExpressionTreeBottomUpSimilarityCalculator(StorableConstructorFlag _) : base(_) {
[11918]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
[16283]58    #region static methods
59    private static ISymbolicExpressionTreeNode ActualRoot(ISymbolicExpressionTree tree) {
60      return tree.Root.GetSubtree(0).GetSubtree(0);
61    }
[11486]62
[16283]63    public static double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, bool strict = false) {
64      return CalculateSimilarity(ActualRoot(t1), ActualRoot(t2), strict);
[11219]65    }
66
[16283]67    public static double CalculateSimilarity(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2, bool strict = false) {
68      return CalculateSimilarity(n1, n2, strict);
69    }
70
[18132]71    public static NodeMap ComputeBottomUpMapping(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, bool strict = false) {
[16283]72      return ComputeBottomUpMapping(ActualRoot(t1), ActualRoot(t2), strict);
73    }
74
[18132]75    public static NodeMap ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2, bool strict = false) {
[18141]76      var calculator = new SymbolicExpressionTreeBottomUpSimilarityCalculator { MatchNumericValues = strict, MatchVariableWeights = strict };
[16283]77      return calculator.ComputeBottomUpMapping(n1, n2);
78    }
79    #endregion
80
81    public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
[18132]82      return CalculateSimilarity(t1, t2, out _);
[16283]83    }
84
85    public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, out NodeMap map) {
[16278]86      if (t1 == t2) {
87        map = null;
88        return 1;
89      }
[16283]90      map = ComputeBottomUpMapping(t1, t2);
[16278]91      return 2.0 * map.Count / (t1.Length + t2.Length - 4); // -4 for skipping root and start symbols in the two trees
92    }
93
[11219]94    public override double CalculateSolutionSimilarity(IScope leftSolution, IScope rightSolution) {
[12103]95      if (leftSolution == rightSolution)
96        return 1.0;
97
[11219]98      var t1 = leftSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
99      var t2 = rightSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
100
101      if (t1 == null || t2 == null)
102        throw new ArgumentException("Cannot calculate similarity when one of the arguments is null.");
103
[11486]104      var similarity = CalculateSimilarity(t1, t2);
[11224]105      if (similarity > 1.0)
[14354]106        throw new Exception("Similarity value cannot be greater than 1");
[11224]107
108      return similarity;
[11219]109    }
110
[18132]111    public NodeMap ComputeBottomUpMapping(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
[17077]112      return ComputeBottomUpMapping(ActualRoot(t1), ActualRoot(t2));
[16283]113    }
114
[18132]115    public NodeMap ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
[11221]116      var compactedGraph = Compact(n1, n2);
[11219]117
[16283]118      IEnumerable<ISymbolicExpressionTreeNode> Subtrees(ISymbolicExpressionTreeNode node, bool commutative) {
119        var subtrees = node.IterateNodesPrefix();
120        return commutative ? subtrees.OrderBy(x => compactedGraph[x].Hash) : subtrees;
121      }
[11219]122
[16283]123      var nodes1 = n1.IterateNodesPostfix().OrderByDescending(x => x.GetLength()); // by descending length so that largest subtrees are mapped first
124      var nodes2 = (List<ISymbolicExpressionTreeNode>)n2.IterateNodesPostfix();
[16278]125
[16283]126      var forward = new NodeMap();
127      var reverse = new NodeMap();
128
129      foreach (ISymbolicExpressionTreeNode v in nodes1) {
130        if (forward.ContainsKey(v))
[11225]131          continue;
[16278]132
[11219]133        var kv = compactedGraph[v];
[16283]134        var commutative = v.SubtreeCount > 1 && commutativeSymbols.Contains(kv.Label);
[16278]135
[16283]136        foreach (ISymbolicExpressionTreeNode w in nodes2) {
137          if (w.GetLength() != kv.Length || w.GetDepth() != kv.Depth || reverse.ContainsKey(w) || compactedGraph[w] != kv)
[11225]138            continue;
[16278]139
[16283]140          // map one whole subtree to the other
141          foreach (var t in Subtrees(v, commutative).Zip(Subtrees(w, commutative), Tuple.Create)) {
142            forward[t.Item1] = t.Item2;
143            reverse[t.Item2] = t.Item1;
[16278]144          }
[11219]145
[16283]146          break;
[16278]147        }
[11219]148      }
149
[16283]150      return forward;
[11219]151    }
152
153    /// <summary>
154    /// Creates a compact representation of the two trees as a directed acyclic graph
155    /// </summary>
[11229]156    /// <param name="n1">The root of the first tree</param>
157    /// <param name="n2">The root of the second tree</param>
[11219]158    /// <returns>The compacted DAG representing the two trees</returns>
[11229]159    private Dictionary<ISymbolicExpressionTreeNode, GraphNode> Compact(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
160      var nodeMap = new Dictionary<ISymbolicExpressionTreeNode, GraphNode>(); // K
161      var labelMap = new Dictionary<string, GraphNode>(); // L
[11219]162
[11221]163      var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
[16278]164      var graph = new List<GraphNode>();
[11219]165
[16283]166      IEnumerable<GraphNode> Subtrees(GraphNode g, bool commutative) {
167        var subtrees = g.SymbolicExpressionTreeNode.Subtrees.Select(x => nodeMap[x]);
168        return commutative ? subtrees.OrderBy(x => x.Hash) : subtrees;
169      }
170
[16278]171      foreach (var node in nodes) {
172        var label = GetLabel(node);
173
174        if (node.SubtreeCount == 0) {
[11229]175          if (!labelMap.ContainsKey(label)) {
[16283]176            labelMap[label] = new GraphNode(node, label);
[11225]177          }
[16278]178          nodeMap[node] = labelMap[label];
[11219]179        } else {
[16278]180          var v = new GraphNode(node, label);
[11894]181          bool found = false;
[16278]182          var commutative = node.SubtreeCount > 1 && commutativeSymbols.Contains(label);
[11219]183
[16283]184          var vv = Subtrees(v, commutative);
[11219]185
[16283]186          foreach (var w in graph) {
[16278]187            if (v.Depth != w.Depth || v.SubtreeCount != w.SubtreeCount || v.Length != w.Length || v.Label != w.Label) {
[11219]188              continue;
[16278]189            }
[11219]190
[16283]191            var ww = Subtrees(w, commutative);
[16278]192            found = vv.SequenceEqual(ww);
[11219]193
[11894]194            if (found) {
[16278]195              nodeMap[node] = w;
[11219]196              break;
197            }
[11229]198          }
[11219]199          if (!found) {
[16278]200            nodeMap[node] = v;
201            graph.Add(v);
[11229]202          }
203        }
[11220]204      }
[11229]205      return nodeMap;
[11219]206    }
207
[16278]208    private string GetLabel(ISymbolicExpressionTreeNode node) {
[11486]209      if (node.SubtreeCount > 0)
210        return node.Symbol.Name;
211
[18132]212      if (node is INumericTreeNode numNode)
[18141]213        return MatchNumericValues ? numNode.Value.ToString(CultureInfo.InvariantCulture) : "Numeric";
[11950]214
[16278]215      if (node is VariableTreeNode variable)
216        return MatchVariableWeights ? variable.Weight + variable.VariableName : variable.VariableName;
[11486]217
218      return node.ToString();
219    }
220
[11229]221    private class GraphNode {
[16278]222      private GraphNode() { }
223
224      public GraphNode(ISymbolicExpressionTreeNode node, string label) {
225        SymbolicExpressionTreeNode = node;
226        Label = label;
227        Hash = GetHashCode();
228        Depth = node.GetDepth();
229        Length = node.GetLength();
230      }
231
232      public int Hash { get; }
233      public ISymbolicExpressionTreeNode SymbolicExpressionTreeNode { get; }
234      public string Label { get; }
235      public int Depth { get; }
[11894]236      public int SubtreeCount { get { return SymbolicExpressionTreeNode.SubtreeCount; } }
[16278]237      public int Length { get; }
[11219]238    }
239  }
240}
Note: See TracBrowser for help on using the repository browser.