Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3140_NumberSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeBottomUpSimilarityCalculator.cs @ 18114

Last change on this file since 18114 was 18114, checked in by gkronber, 2 years ago

#3140: made several more changes while reviewing the branch.

File size: 9.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Globalization;
25using System.Linq;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Optimization.Operators;
30using HEAL.Attic;
31
32using NodeMap = System.Collections.Generic.Dictionary<HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ISymbolicExpressionTreeNode, HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ISymbolicExpressionTreeNode>;
33
34namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
35  [StorableType("63ACB7A4-137F-468F-BE42-A4CA6B62C63B")]
36  [Item("SymbolicExpressionTreeBottomUpSimilarityCalculator", "A similarity calculator which uses the tree bottom-up distance as a similarity metric.")]
37  public class SymbolicExpressionTreeBottomUpSimilarityCalculator : SolutionSimilarityCalculator {
38    private readonly HashSet<string> commutativeSymbols = new HashSet<string> { "Addition", "Multiplication", "Average", "And", "Or", "Xor" };
39
40    public SymbolicExpressionTreeBottomUpSimilarityCalculator() { }
41    protected override bool IsCommutative { get { return true; } }
42
43    public bool MatchParameterValues { get; set; }
44    public bool MatchVariableWeights { get; set; }
45
46    [StorableConstructor]
47    protected SymbolicExpressionTreeBottomUpSimilarityCalculator(StorableConstructorFlag _) : base(_) {
48    }
49
50    protected SymbolicExpressionTreeBottomUpSimilarityCalculator(SymbolicExpressionTreeBottomUpSimilarityCalculator original, Cloner cloner)
51      : base(original, cloner) {
52    }
53
54    public override IDeepCloneable Clone(Cloner cloner) {
55      return new SymbolicExpressionTreeBottomUpSimilarityCalculator(this, cloner);
56    }
57
58    #region static methods
59    private static ISymbolicExpressionTreeNode ActualRoot(ISymbolicExpressionTree tree) {
60      return tree.Root.GetSubtree(0).GetSubtree(0);
61    }
62
63    public static double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, bool strict = false) {
64      return CalculateSimilarity(ActualRoot(t1), ActualRoot(t2), strict);
65    }
66
67    public static double CalculateSimilarity(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2, bool strict = false) {
68      return CalculateSimilarity(n1, n2, strict);
69    }
70
71    public static NodeMap ComputeBottomUpMapping(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, bool strict = false) {
72      return ComputeBottomUpMapping(ActualRoot(t1), ActualRoot(t2), strict);
73    }
74
75    public static NodeMap ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2, bool strict = false) {
76      var calculator = new SymbolicExpressionTreeBottomUpSimilarityCalculator { MatchParameterValues = strict, MatchVariableWeights = strict };
77      return calculator.ComputeBottomUpMapping(n1, n2);
78    }
79    #endregion
80
81    public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
82      return CalculateSimilarity(t1, t2, out _);
83    }
84
85    public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, out NodeMap map) {
86      if (t1 == t2) {
87        map = null;
88        return 1;
89      }
90      map = ComputeBottomUpMapping(t1, t2);
91      return 2.0 * map.Count / (t1.Length + t2.Length - 4); // -4 for skipping root and start symbols in the two trees
92    }
93
94    public override double CalculateSolutionSimilarity(IScope leftSolution, IScope rightSolution) {
95      if (leftSolution == rightSolution)
96        return 1.0;
97
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
104      var similarity = CalculateSimilarity(t1, t2);
105      if (similarity > 1.0)
106        throw new Exception("Similarity value cannot be greater than 1");
107
108      return similarity;
109    }
110
111    public NodeMap ComputeBottomUpMapping(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
112      return ComputeBottomUpMapping(ActualRoot(t1), ActualRoot(t2));
113    }
114
115    public NodeMap ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
116      var compactedGraph = Compact(n1, n2);
117
118      IEnumerable<ISymbolicExpressionTreeNode> Subtrees(ISymbolicExpressionTreeNode node, bool commutative) {
119        var subtrees = node.IterateNodesPrefix();
120        return commutative ? subtrees.OrderBy(x => compactedGraph[x].Hash) : subtrees;
121      }
122
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();
125
126      var forward = new NodeMap();
127      var reverse = new NodeMap();
128
129      foreach (ISymbolicExpressionTreeNode v in nodes1) {
130        if (forward.ContainsKey(v))
131          continue;
132
133        var kv = compactedGraph[v];
134        var commutative = v.SubtreeCount > 1 && commutativeSymbols.Contains(kv.Label);
135
136        foreach (ISymbolicExpressionTreeNode w in nodes2) {
137          if (w.GetLength() != kv.Length || w.GetDepth() != kv.Depth || reverse.ContainsKey(w) || compactedGraph[w] != kv)
138            continue;
139
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;
144          }
145
146          break;
147        }
148      }
149
150      return forward;
151    }
152
153    /// <summary>
154    /// Creates a compact representation of the two trees as a directed acyclic graph
155    /// </summary>
156    /// <param name="n1">The root of the first tree</param>
157    /// <param name="n2">The root of the second tree</param>
158    /// <returns>The compacted DAG representing the two trees</returns>
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
162
163      var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
164      var graph = new List<GraphNode>();
165
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
171      foreach (var node in nodes) {
172        var label = GetLabel(node);
173
174        if (node.SubtreeCount == 0) {
175          if (!labelMap.ContainsKey(label)) {
176            labelMap[label] = new GraphNode(node, label);
177          }
178          nodeMap[node] = labelMap[label];
179        } else {
180          var v = new GraphNode(node, label);
181          bool found = false;
182          var commutative = node.SubtreeCount > 1 && commutativeSymbols.Contains(label);
183
184          var vv = Subtrees(v, commutative);
185
186          foreach (var w in graph) {
187            if (v.Depth != w.Depth || v.SubtreeCount != w.SubtreeCount || v.Length != w.Length || v.Label != w.Label) {
188              continue;
189            }
190
191            var ww = Subtrees(w, commutative);
192            found = vv.SequenceEqual(ww);
193
194            if (found) {
195              nodeMap[node] = w;
196              break;
197            }
198          }
199          if (!found) {
200            nodeMap[node] = v;
201            graph.Add(v);
202          }
203        }
204      }
205      return nodeMap;
206    }
207
208    private string GetLabel(ISymbolicExpressionTreeNode node) {
209      if (node.SubtreeCount > 0)
210        return node.Symbol.Name;
211
212      if (node is INumericTreeNode numNode)
213        return MatchParameterValues ? numNode.Value.ToString(CultureInfo.InvariantCulture) : "Numeric";
214
215      if (node is VariableTreeNode variable)
216        return MatchVariableWeights ? variable.Weight + variable.VariableName : variable.VariableName;
217
218      return node.ToString();
219    }
220
221    private class GraphNode {
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; }
236      public int SubtreeCount { get { return SymbolicExpressionTreeNode.SubtreeCount; } }
237      public int Length { get; }
238    }
239  }
240}
Note: See TracBrowser for help on using the repository browser.