1 | #region License Information
|
---|
2 |
|
---|
3 | /* HeuristicLab
|
---|
4 | * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
|
---|
5 | *
|
---|
6 | * This file is part of HeuristicLab.
|
---|
7 | *
|
---|
8 | * HeuristicLab is free software: you can redistribute it and/or modify
|
---|
9 | * it under the terms of the GNU General Public License as published by
|
---|
10 | * the Free Software Foundation, either version 3 of the License, or
|
---|
11 | * (at your option) any later version.
|
---|
12 | *
|
---|
13 | * HeuristicLab is distributed in the hope that it will be useful,
|
---|
14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
16 | * GNU General Public License for more details.
|
---|
17 | *
|
---|
18 | * You should have received a copy of the GNU General Public License
|
---|
19 | * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
|
---|
20 | */
|
---|
21 |
|
---|
22 | #endregion License Information
|
---|
23 |
|
---|
24 | using System;
|
---|
25 | using System.Collections.Generic;
|
---|
26 | using System.Globalization;
|
---|
27 | using System.Linq;
|
---|
28 | using HeuristicLab.Common;
|
---|
29 | using HeuristicLab.Core;
|
---|
30 | using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
|
---|
31 | using HeuristicLab.Optimization.Operators;
|
---|
32 | using HEAL.Attic;
|
---|
33 |
|
---|
34 | using NodeMap = System.Collections.Generic.Dictionary<HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ISymbolicExpressionTreeNode, HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ISymbolicExpressionTreeNode>;
|
---|
35 |
|
---|
36 | namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
|
---|
37 | [StorableType("63ACB7A4-137F-468F-BE42-A4CA6B62C63B")]
|
---|
38 | [Item("SymbolicExpressionTreeBottomUpSimilarityCalculator", "A similarity calculator which uses the tree bottom-up distance as a similarity metric.")]
|
---|
39 | public class SymbolicExpressionTreeBottomUpSimilarityCalculator : SolutionSimilarityCalculator {
|
---|
40 | private readonly HashSet<string> commutativeSymbols = new HashSet<string> { "Addition", "Multiplication", "Average", "And", "Or", "Xor" };
|
---|
41 |
|
---|
42 | public SymbolicExpressionTreeBottomUpSimilarityCalculator() {
|
---|
43 | }
|
---|
44 |
|
---|
45 | protected override bool IsCommutative { get { return true; } }
|
---|
46 |
|
---|
47 | public bool MatchConstantValues { get; set; }
|
---|
48 | public bool MatchVariableWeights { get; set; }
|
---|
49 |
|
---|
50 | [StorableConstructor]
|
---|
51 | protected SymbolicExpressionTreeBottomUpSimilarityCalculator(StorableConstructorFlag _) : base(_) {
|
---|
52 | }
|
---|
53 |
|
---|
54 | protected SymbolicExpressionTreeBottomUpSimilarityCalculator(SymbolicExpressionTreeBottomUpSimilarityCalculator original, Cloner cloner)
|
---|
55 | : base(original, cloner) {
|
---|
56 | }
|
---|
57 |
|
---|
58 | public override IDeepCloneable Clone(Cloner cloner) {
|
---|
59 | return new SymbolicExpressionTreeBottomUpSimilarityCalculator(this, cloner);
|
---|
60 | }
|
---|
61 |
|
---|
62 | #region static methods
|
---|
63 | private static ISymbolicExpressionTreeNode ActualRoot(ISymbolicExpressionTree tree) {
|
---|
64 | return tree.Root.GetSubtree(0).GetSubtree(0);
|
---|
65 | }
|
---|
66 |
|
---|
67 | public static double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, bool strict = false) {
|
---|
68 | return CalculateSimilarity(ActualRoot(t1), ActualRoot(t2), strict);
|
---|
69 | }
|
---|
70 |
|
---|
71 | public static double CalculateSimilarity(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2, bool strict = false) {
|
---|
72 | var calculator = new SymbolicExpressionTreeBottomUpSimilarityCalculator { MatchConstantValues = strict, MatchVariableWeights = strict };
|
---|
73 | return CalculateSimilarity(n1, n2, strict);
|
---|
74 | }
|
---|
75 |
|
---|
76 | public static Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, bool strict = false) {
|
---|
77 | return ComputeBottomUpMapping(ActualRoot(t1), ActualRoot(t2), strict);
|
---|
78 | }
|
---|
79 |
|
---|
80 | public static Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2, bool strict = false) {
|
---|
81 | var calculator = new SymbolicExpressionTreeBottomUpSimilarityCalculator { MatchConstantValues = strict, MatchVariableWeights = strict };
|
---|
82 | return calculator.ComputeBottomUpMapping(n1, n2);
|
---|
83 | }
|
---|
84 | #endregion
|
---|
85 |
|
---|
86 | public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
|
---|
87 | return CalculateSimilarity(t1, t2, out Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> map);
|
---|
88 | }
|
---|
89 |
|
---|
90 | public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, out NodeMap map) {
|
---|
91 | if (t1 == t2) {
|
---|
92 | map = null;
|
---|
93 | return 1;
|
---|
94 | }
|
---|
95 | map = ComputeBottomUpMapping(t1, t2);
|
---|
96 | return 2.0 * map.Count / (t1.Length + t2.Length - 4); // -4 for skipping root and start symbols in the two trees
|
---|
97 | }
|
---|
98 |
|
---|
99 | public override double CalculateSolutionSimilarity(IScope leftSolution, IScope rightSolution) {
|
---|
100 | if (leftSolution == rightSolution)
|
---|
101 | return 1.0;
|
---|
102 |
|
---|
103 | var t1 = leftSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
|
---|
104 | var t2 = rightSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
|
---|
105 |
|
---|
106 | if (t1 == null || t2 == null)
|
---|
107 | throw new ArgumentException("Cannot calculate similarity when one of the arguments is null.");
|
---|
108 |
|
---|
109 | var similarity = CalculateSimilarity(t1, t2);
|
---|
110 | if (similarity > 1.0)
|
---|
111 | throw new Exception("Similarity value cannot be greater than 1");
|
---|
112 |
|
---|
113 | return similarity;
|
---|
114 | }
|
---|
115 |
|
---|
116 | public Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
|
---|
117 | return ComputeBottomUpMapping(ActualRoot(t1), ActualRoot(t2));
|
---|
118 | }
|
---|
119 |
|
---|
120 | public Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
|
---|
121 | var compactedGraph = Compact(n1, n2);
|
---|
122 |
|
---|
123 | IEnumerable<ISymbolicExpressionTreeNode> Subtrees(ISymbolicExpressionTreeNode node, bool commutative) {
|
---|
124 | var subtrees = node.IterateNodesPrefix();
|
---|
125 | return commutative ? subtrees.OrderBy(x => compactedGraph[x].Hash) : subtrees;
|
---|
126 | }
|
---|
127 |
|
---|
128 | var nodes1 = n1.IterateNodesPostfix().OrderByDescending(x => x.GetLength()); // by descending length so that largest subtrees are mapped first
|
---|
129 | var nodes2 = (List<ISymbolicExpressionTreeNode>)n2.IterateNodesPostfix();
|
---|
130 |
|
---|
131 | var forward = new NodeMap();
|
---|
132 | var reverse = new NodeMap();
|
---|
133 |
|
---|
134 | foreach (ISymbolicExpressionTreeNode v in nodes1) {
|
---|
135 | if (forward.ContainsKey(v))
|
---|
136 | continue;
|
---|
137 |
|
---|
138 | var kv = compactedGraph[v];
|
---|
139 | var commutative = v.SubtreeCount > 1 && commutativeSymbols.Contains(kv.Label);
|
---|
140 |
|
---|
141 | foreach (ISymbolicExpressionTreeNode w in nodes2) {
|
---|
142 | if (w.GetLength() != kv.Length || w.GetDepth() != kv.Depth || reverse.ContainsKey(w) || compactedGraph[w] != kv)
|
---|
143 | continue;
|
---|
144 |
|
---|
145 | // map one whole subtree to the other
|
---|
146 | foreach (var t in Subtrees(v, commutative).Zip(Subtrees(w, commutative), Tuple.Create)) {
|
---|
147 | forward[t.Item1] = t.Item2;
|
---|
148 | reverse[t.Item2] = t.Item1;
|
---|
149 | }
|
---|
150 |
|
---|
151 | break;
|
---|
152 | }
|
---|
153 | }
|
---|
154 |
|
---|
155 | return forward;
|
---|
156 | }
|
---|
157 |
|
---|
158 | /// <summary>
|
---|
159 | /// Creates a compact representation of the two trees as a directed acyclic graph
|
---|
160 | /// </summary>
|
---|
161 | /// <param name="n1">The root of the first tree</param>
|
---|
162 | /// <param name="n2">The root of the second tree</param>
|
---|
163 | /// <returns>The compacted DAG representing the two trees</returns>
|
---|
164 | private Dictionary<ISymbolicExpressionTreeNode, GraphNode> Compact(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
|
---|
165 | var nodeMap = new Dictionary<ISymbolicExpressionTreeNode, GraphNode>(); // K
|
---|
166 | var labelMap = new Dictionary<string, GraphNode>(); // L
|
---|
167 |
|
---|
168 | var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
|
---|
169 | var graph = new List<GraphNode>();
|
---|
170 |
|
---|
171 | IEnumerable<GraphNode> Subtrees(GraphNode g, bool commutative) {
|
---|
172 | var subtrees = g.SymbolicExpressionTreeNode.Subtrees.Select(x => nodeMap[x]);
|
---|
173 | return commutative ? subtrees.OrderBy(x => x.Hash) : subtrees;
|
---|
174 | }
|
---|
175 |
|
---|
176 | foreach (var node in nodes) {
|
---|
177 | var label = GetLabel(node);
|
---|
178 |
|
---|
179 | if (node.SubtreeCount == 0) {
|
---|
180 | if (!labelMap.ContainsKey(label)) {
|
---|
181 | labelMap[label] = new GraphNode(node, label);
|
---|
182 | }
|
---|
183 | nodeMap[node] = labelMap[label];
|
---|
184 | } else {
|
---|
185 | var v = new GraphNode(node, label);
|
---|
186 | bool found = false;
|
---|
187 | var commutative = node.SubtreeCount > 1 && commutativeSymbols.Contains(label);
|
---|
188 |
|
---|
189 | var vv = Subtrees(v, commutative);
|
---|
190 |
|
---|
191 | foreach (var w in graph) {
|
---|
192 | if (v.Depth != w.Depth || v.SubtreeCount != w.SubtreeCount || v.Length != w.Length || v.Label != w.Label) {
|
---|
193 | continue;
|
---|
194 | }
|
---|
195 |
|
---|
196 | var ww = Subtrees(w, commutative);
|
---|
197 | found = vv.SequenceEqual(ww);
|
---|
198 |
|
---|
199 | if (found) {
|
---|
200 | nodeMap[node] = w;
|
---|
201 | break;
|
---|
202 | }
|
---|
203 | }
|
---|
204 | if (!found) {
|
---|
205 | nodeMap[node] = v;
|
---|
206 | graph.Add(v);
|
---|
207 | }
|
---|
208 | }
|
---|
209 | }
|
---|
210 | return nodeMap;
|
---|
211 | }
|
---|
212 |
|
---|
213 | private string GetLabel(ISymbolicExpressionTreeNode node) {
|
---|
214 | if (node.SubtreeCount > 0)
|
---|
215 | return node.Symbol.Name;
|
---|
216 |
|
---|
217 | if (node is ConstantTreeNode constant)
|
---|
218 | return MatchConstantValues ? constant.Value.ToString(CultureInfo.InvariantCulture) : constant.Symbol.Name;
|
---|
219 |
|
---|
220 | if (node is VariableTreeNode variable)
|
---|
221 | return MatchVariableWeights ? variable.Weight + variable.VariableName : variable.VariableName;
|
---|
222 |
|
---|
223 | return node.ToString();
|
---|
224 | }
|
---|
225 |
|
---|
226 | private class GraphNode {
|
---|
227 | private GraphNode() { }
|
---|
228 |
|
---|
229 | public GraphNode(ISymbolicExpressionTreeNode node, string label) {
|
---|
230 | SymbolicExpressionTreeNode = node;
|
---|
231 | Label = label;
|
---|
232 | Hash = GetHashCode();
|
---|
233 | Depth = node.GetDepth();
|
---|
234 | Length = node.GetLength();
|
---|
235 | }
|
---|
236 |
|
---|
237 | public int Hash { get; }
|
---|
238 | public ISymbolicExpressionTreeNode SymbolicExpressionTreeNode { get; }
|
---|
239 | public string Label { get; }
|
---|
240 | public int Depth { get; }
|
---|
241 | public int SubtreeCount { get { return SymbolicExpressionTreeNode.SubtreeCount; } }
|
---|
242 | public int Length { get; }
|
---|
243 | }
|
---|
244 | }
|
---|
245 | } |
---|