1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 2002-2018 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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections.Generic;
|
---|
24 | using System.Globalization;
|
---|
25 | using System.Linq;
|
---|
26 | using HeuristicLab.Common;
|
---|
27 | using HeuristicLab.Core;
|
---|
28 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
29 | using HeuristicLab.Optimization.Operators;
|
---|
30 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
31 |
|
---|
32 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
|
---|
33 | [StorableClass]
|
---|
34 | [Item("SymbolicExpressionTreeBottomUpSimilarityCalculator", "A similarity calculator which uses the tree bottom-up distance as a similarity metric.")]
|
---|
35 | public class SymbolicExpressionTreeBottomUpSimilarityCalculator : SolutionSimilarityCalculator {
|
---|
36 | private readonly HashSet<string> commutativeSymbols = new HashSet<string> { "Addition", "Multiplication", "Average", "And", "Or", "Xor" };
|
---|
37 |
|
---|
38 | public SymbolicExpressionTreeBottomUpSimilarityCalculator() { }
|
---|
39 | protected override bool IsCommutative { get { return true; } }
|
---|
40 |
|
---|
41 | public bool MatchConstantValues { get; set; }
|
---|
42 | public bool MatchVariableWeights { get; set; }
|
---|
43 |
|
---|
44 | [StorableConstructor]
|
---|
45 | protected SymbolicExpressionTreeBottomUpSimilarityCalculator(bool deserializing)
|
---|
46 | : base(deserializing) {
|
---|
47 | }
|
---|
48 |
|
---|
49 | protected SymbolicExpressionTreeBottomUpSimilarityCalculator(SymbolicExpressionTreeBottomUpSimilarityCalculator original, Cloner cloner)
|
---|
50 | : base(original, cloner) {
|
---|
51 | }
|
---|
52 |
|
---|
53 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
54 | return new SymbolicExpressionTreeBottomUpSimilarityCalculator(this, cloner);
|
---|
55 | }
|
---|
56 |
|
---|
57 | public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
|
---|
58 | if (t1 == t2)
|
---|
59 | return 1;
|
---|
60 |
|
---|
61 | var actualRoot1 = t1.Root.GetSubtree(0).GetSubtree(0); // skip root and start symbols
|
---|
62 | var actualRoot2 = t2.Root.GetSubtree(0).GetSubtree(0); // skip root and start symbols
|
---|
63 | var map = ComputeBottomUpMapping(actualRoot1, actualRoot2);
|
---|
64 | return 2.0 * map.Count / (t1.Length + t2.Length - 4); // -4 for skipping root and start symbols in the two trees
|
---|
65 | }
|
---|
66 |
|
---|
67 | public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, out Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> map) {
|
---|
68 | if (t1 == t2) {
|
---|
69 | map = null;
|
---|
70 | return 1;
|
---|
71 | }
|
---|
72 |
|
---|
73 | var actualRoot1 = t1.Root.GetSubtree(0).GetSubtree(0); // skip root and start symbols
|
---|
74 | var actualRoot2 = t2.Root.GetSubtree(0).GetSubtree(0); // skip root and start symbols
|
---|
75 | map = ComputeBottomUpMapping(actualRoot1, actualRoot2);
|
---|
76 |
|
---|
77 | return 2.0 * map.Count / (t1.Length + t2.Length - 4); // -4 for skipping root and start symbols in the two trees
|
---|
78 | }
|
---|
79 |
|
---|
80 | public override double CalculateSolutionSimilarity(IScope leftSolution, IScope rightSolution) {
|
---|
81 | if (leftSolution == rightSolution)
|
---|
82 | return 1.0;
|
---|
83 |
|
---|
84 | var t1 = leftSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
|
---|
85 | var t2 = rightSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
|
---|
86 |
|
---|
87 | if (t1 == null || t2 == null)
|
---|
88 | throw new ArgumentException("Cannot calculate similarity when one of the arguments is null.");
|
---|
89 |
|
---|
90 | var similarity = CalculateSimilarity(t1, t2);
|
---|
91 | if (similarity > 1.0)
|
---|
92 | throw new Exception("Similarity value cannot be greater than 1");
|
---|
93 |
|
---|
94 | return similarity;
|
---|
95 | }
|
---|
96 |
|
---|
97 | public Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
|
---|
98 | var comparer = new SymbolicExpressionTreeNodeComparer(); // use a node comparer because it's faster than calling node.ToString() (strings are expensive) and comparing strings
|
---|
99 | var compactedGraph = Compact(n1, n2);
|
---|
100 |
|
---|
101 | var forwardMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t1 => nodes of t2
|
---|
102 | var reverseMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t2 => nodes of t1
|
---|
103 |
|
---|
104 | // visit nodes in order of decreasing height to ensure correct mapping
|
---|
105 | var nodes1 = (List<ISymbolicExpressionTreeNode>)n1.IterateNodesPrefix();
|
---|
106 | var nodes2 = (List<ISymbolicExpressionTreeNode>)n2.IterateNodesPrefix();
|
---|
107 |
|
---|
108 | foreach (var v in nodes1) {
|
---|
109 | if (forwardMap.ContainsKey(v)) {
|
---|
110 | continue;
|
---|
111 | }
|
---|
112 |
|
---|
113 | var kv = compactedGraph[v];
|
---|
114 |
|
---|
115 | var w = nodes2.Last();
|
---|
116 | int k = nodes2.Count - 1;
|
---|
117 |
|
---|
118 | for (int j = 0; j < nodes2.Count; ++j) {
|
---|
119 | var t = nodes2[j];
|
---|
120 |
|
---|
121 | if (reverseMap.ContainsKey(t) || kv != compactedGraph[t])
|
---|
122 | continue;
|
---|
123 |
|
---|
124 | if (j < k) {
|
---|
125 | w = t;
|
---|
126 | k = j;
|
---|
127 | }
|
---|
128 | }
|
---|
129 |
|
---|
130 | if (kv != compactedGraph[w]) {
|
---|
131 | continue;
|
---|
132 | }
|
---|
133 |
|
---|
134 | // at this point we know that v and w are isomorphic (same length and depth)
|
---|
135 | // however, the mapping cannot be done directly (as in the paper)
|
---|
136 | // because the trees are unordered (subtree order might differ).
|
---|
137 | // the solution is to sort once again (this will work because the subtrees are isomorphic!)
|
---|
138 | var vv = v.IterateNodesPrefix().OrderBy(x => compactedGraph[x].Hash);
|
---|
139 | var ww = w.IterateNodesPrefix().OrderBy(x => compactedGraph[x].Hash);
|
---|
140 |
|
---|
141 | foreach (var pair in vv.Zip(ww, Tuple.Create)) {
|
---|
142 | var s = pair.Item1;
|
---|
143 | var t = pair.Item2;
|
---|
144 |
|
---|
145 | if (reverseMap.ContainsKey(t))
|
---|
146 | continue;
|
---|
147 |
|
---|
148 | forwardMap[s] = t;
|
---|
149 | reverseMap[t] = s;
|
---|
150 | }
|
---|
151 | }
|
---|
152 |
|
---|
153 | return forwardMap;
|
---|
154 | }
|
---|
155 |
|
---|
156 | /// <summary>
|
---|
157 | /// Creates a compact representation of the two trees as a directed acyclic graph
|
---|
158 | /// </summary>
|
---|
159 | /// <param name="n1">The root of the first tree</param>
|
---|
160 | /// <param name="n2">The root of the second tree</param>
|
---|
161 | /// <returns>The compacted DAG representing the two trees</returns>
|
---|
162 | private Dictionary<ISymbolicExpressionTreeNode, GraphNode> Compact(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
|
---|
163 | var nodeMap = new Dictionary<ISymbolicExpressionTreeNode, GraphNode>(); // K
|
---|
164 | var labelMap = new Dictionary<string, GraphNode>(); // L
|
---|
165 |
|
---|
166 | var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
|
---|
167 | var graph = new List<GraphNode>();
|
---|
168 |
|
---|
169 | foreach (var node in nodes) {
|
---|
170 | var label = GetLabel(node);
|
---|
171 |
|
---|
172 | if (node.SubtreeCount == 0) {
|
---|
173 | if (!labelMap.ContainsKey(label)) {
|
---|
174 | var g = new GraphNode(node, label);
|
---|
175 | graph.Add(g);
|
---|
176 | labelMap[label] = g;
|
---|
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 | IEnumerable<GraphNode> vv, ww;
|
---|
185 |
|
---|
186 | for (int i = graph.Count - 1; i >= 0; --i) {
|
---|
187 | var w = graph[i];
|
---|
188 |
|
---|
189 | if (v.Depth != w.Depth || v.SubtreeCount != w.SubtreeCount || v.Length != w.Length || v.Label != w.Label) {
|
---|
190 | continue;
|
---|
191 | }
|
---|
192 |
|
---|
193 | vv = commutative ? v.SymbolicExpressionTreeNode.Subtrees.Select(x => nodeMap[x]).OrderBy(x => x.Hash) : v.SymbolicExpressionTreeNode.Subtrees.Select(x => nodeMap[x]);
|
---|
194 | ww = commutative ? w.SymbolicExpressionTreeNode.Subtrees.Select(x => nodeMap[x]).OrderBy(x => x.Hash) : w.SymbolicExpressionTreeNode.Subtrees.Select(x => nodeMap[x]);
|
---|
195 | found = vv.SequenceEqual(ww);
|
---|
196 |
|
---|
197 | if (found) {
|
---|
198 | nodeMap[node] = w;
|
---|
199 | break;
|
---|
200 | }
|
---|
201 | }
|
---|
202 | if (!found) {
|
---|
203 | nodeMap[node] = v;
|
---|
204 | graph.Add(v);
|
---|
205 | }
|
---|
206 | }
|
---|
207 | }
|
---|
208 | return nodeMap;
|
---|
209 | }
|
---|
210 |
|
---|
211 | private string GetLabel(ISymbolicExpressionTreeNode node) {
|
---|
212 | if (node.SubtreeCount > 0)
|
---|
213 | return node.Symbol.Name;
|
---|
214 |
|
---|
215 | if (node is ConstantTreeNode constant)
|
---|
216 | return MatchConstantValues ? constant.Value.ToString(CultureInfo.InvariantCulture) : constant.Symbol.Name;
|
---|
217 |
|
---|
218 | if (node is VariableTreeNode variable)
|
---|
219 | return MatchVariableWeights ? variable.Weight + variable.VariableName : variable.VariableName;
|
---|
220 |
|
---|
221 | return node.ToString();
|
---|
222 | }
|
---|
223 |
|
---|
224 | private class GraphNode {
|
---|
225 | private GraphNode() { }
|
---|
226 |
|
---|
227 | public GraphNode(ISymbolicExpressionTreeNode node, string label) {
|
---|
228 | SymbolicExpressionTreeNode = node;
|
---|
229 | Label = label;
|
---|
230 | Hash = GetHashCode();
|
---|
231 | Depth = node.GetDepth();
|
---|
232 | Length = node.GetLength();
|
---|
233 | }
|
---|
234 |
|
---|
235 | public int Hash { get; }
|
---|
236 |
|
---|
237 | public ISymbolicExpressionTreeNode SymbolicExpressionTreeNode { get; }
|
---|
238 |
|
---|
239 | public string Label { get; }
|
---|
240 |
|
---|
241 | public int Depth { get; }
|
---|
242 |
|
---|
243 | public int SubtreeCount { get { return SymbolicExpressionTreeNode.SubtreeCount; } }
|
---|
244 |
|
---|
245 | public int Length { get; }
|
---|
246 | }
|
---|
247 | }
|
---|
248 | }
|
---|