#region License Information
/* HeuristicLab
* Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
*
* This file is part of HeuristicLab.
*
* HeuristicLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HeuristicLab is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HeuristicLab. If not, see .
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
using HeuristicLab.Optimization.Operators;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
[StorableClass]
[Item("BottomUpSimilarityCalculator", "A similarity calculator which uses the tree bottom-up distance as a similarity metric.")]
public class BottomUpSimilarityCalculator : SingleObjectiveSolutionSimilarityCalculator {
private readonly HashSet commutativeSymbols = new HashSet { "Addition", "Multiplication", "Average", "And", "Or", "Xor" };
public BottomUpSimilarityCalculator() { }
public override IDeepCloneable Clone(Cloner cloner) {
return new BottomUpSimilarityCalculator(this, cloner);
}
protected BottomUpSimilarityCalculator(BottomUpSimilarityCalculator original, Cloner cloner)
: base(original, cloner) {
}
public override double CalculateSolutionSimilarity(IScope leftSolution, IScope rightSolution) {
var t1 = leftSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
var t2 = rightSolution.Variables[SolutionVariableName].Value as ISymbolicExpressionTree;
if (t1 == null || t2 == null)
throw new ArgumentException("Cannot calculate similarity when one of the arguments is null.");
return CalculateSolutionSimilarity(t1, t2);
}
public double CalculateSolutionSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
if (t1 == t2)
return 1;
var map = ComputeBottomUpMapping(t1.Root, t2.Root);
return 2.0 * map.Count / (t1.Length + t2.Length);
}
public Dictionary ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
var compactedGraph = Compact(n1, n2);
var forwardMap = new Dictionary(); // nodes of t1 => nodes of t2
var reverseMap = new Dictionary(); // nodes of t2 => nodes of t1
foreach (var v in n1.IterateNodesBreadth()) {
if (forwardMap.ContainsKey(v)) continue;
var kv = compactedGraph[v];
ISymbolicExpressionTreeNode w = null;
foreach (var t in n2.IterateNodesBreadth()) {
if (reverseMap.ContainsKey(t) || compactedGraph[t] != kv) continue;
w = t;
break;
}
if (w == null) continue;
// at this point we know that v and w are isomorphic, however, the mapping cannot be done directly (as in the paper) because the trees are unordered (subtree order might differ)
// the solution is to sort subtrees by label using IterateBreadthOrdered (this will work because the subtrees are isomorphic!) and simultaneously iterate over the two subtrees
var eV = IterateBreadthOrdered(v).GetEnumerator();
var eW = IterateBreadthOrdered(w).GetEnumerator();
while (eV.MoveNext() && eW.MoveNext()) {
var s = eV.Current;
var t = eW.Current;
forwardMap[s] = t;
reverseMap[t] = s;
}
}
return forwardMap;
}
///
/// Creates a compact representation of the two trees as a directed acyclic graph
///
/// The first tree
/// The second tree
/// The compacted DAG representing the two trees
private Dictionary Compact(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
var nodesToVertices = new Dictionary(); // K
var labelsToVertices = new Dictionary(); // L
var childrenCount = new Dictionary(); // Children
var vertices = new List(); // G
var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
var queue = new Queue();
foreach (var n in nodes) {
if (n.SubtreeCount == 0) {
var label = n.ToString();
var z = new Vertex { Content = n, Label = label };
labelsToVertices[z.Label] = z;
vertices.Add(z);
queue.Enqueue(n);
} else {
childrenCount[n] = n.SubtreeCount;
}
}
while (queue.Any()) {
var v = queue.Dequeue();
string label;
if (v.SubtreeCount == 0) {
label = v.ToString();
nodesToVertices[v] = labelsToVertices[label]; // 18
} else {
label = v.Symbol.Name;
bool found = false;
var height = v.GetDepth();
bool sort = commutativeSymbols.Contains(label);
var vSubtrees = v.Subtrees.Select(x => nodesToVertices[x]).ToList();
if (sort) vSubtrees.Sort((a, b) => String.Compare(a.Label, b.Label, StringComparison.Ordinal));
// for all nodes w in G in reverse order
for (int i = vertices.Count - 1; i >= 0; --i) {
var w = vertices[i];
var n = (ISymbolicExpressionTreeNode)w.Content;
if (n.SubtreeCount == 0) continue; // v is a function node so w will have to be a function node as well
if (height != (int)w.Weight || v.SubtreeCount != n.SubtreeCount || label != w.Label)
continue;
// sort V and W when the symbol is commutative because we are dealing with unordered trees
var wSubtrees = sort ? w.OutArcs.Select(x => x.Target).OrderBy(x => x.Label)
: w.OutArcs.Select(x => x.Target);
if (vSubtrees.SequenceEqual(wSubtrees)) {
nodesToVertices[v] = w;
found = true;
break;
}
} // 32: end for
if (!found) {
var w = new Vertex { Content = v, Label = label, Weight = height };
vertices.Add(w);
nodesToVertices[v] = w;
foreach (var u in v.Subtrees) {
AddArc(w, nodesToVertices[u]);
} // 40: end for
} // 41: end if
} // 42: end if
var p = v.Parent;
if (p == null)
continue;
childrenCount[p]--;
if (childrenCount[p] == 0)
queue.Enqueue(p);
}
return nodesToVertices;
}
private IEnumerable IterateBreadthOrdered(ISymbolicExpressionTreeNode node) {
var list = new List { node };
int i = 0;
while (i < list.Count) {
var n = list[i];
if (n.SubtreeCount > 0) {
var subtrees = commutativeSymbols.Contains(node.Symbol.Name) ? n.Subtrees.OrderBy(s => s.ToString()) : n.Subtrees;
list.AddRange(subtrees);
}
i++;
}
return list;
}
private static IArc AddArc(IVertex source, IVertex target) {
var arc = new Arc(source, target);
source.AddForwardArc(arc);
target.AddReverseArc(arc);
return arc;
}
}
}