Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
07/19/20 19:07:40 (4 years ago)
Author:
fbaching
Message:

#1837: merged changes from trunk

  • apply changes from Attic release to all SlidingWindow specific code files (replace StorableClass with StorableType)
Location:
branches/1837_Sliding Window GP/HeuristicLab.Problems.DataAnalysis.Symbolic
Files:
2 deleted
4 edited
4 copied
1 moved

Legend:

Unmodified
Added
Removed
  • branches/1837_Sliding Window GP/HeuristicLab.Problems.DataAnalysis.Symbolic

  • branches/1837_Sliding Window GP/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeBottomUpSimilarityCalculator.cs

    r15681 r17687  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    2222using System;
    2323using System.Collections.Generic;
    24 using System.Diagnostics;
    2524using System.Globalization;
    2625using System.Linq;
     
    2928using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    3029using HeuristicLab.Optimization.Operators;
    31 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     30using HEAL.Attic;
     31
     32using NodeMap = System.Collections.Generic.Dictionary<HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ISymbolicExpressionTreeNode, HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.ISymbolicExpressionTreeNode>;
    3233
    3334namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
    34   [StorableClass]
     35  [StorableType("63ACB7A4-137F-468F-BE42-A4CA6B62C63B")]
    3536  [Item("SymbolicExpressionTreeBottomUpSimilarityCalculator", "A similarity calculator which uses the tree bottom-up distance as a similarity metric.")]
    3637  public class SymbolicExpressionTreeBottomUpSimilarityCalculator : SolutionSimilarityCalculator {
     
    4041    protected override bool IsCommutative { get { return true; } }
    4142
     43    public bool MatchConstantValues { get; set; }
     44    public bool MatchVariableWeights { get; set; }
     45
    4246    [StorableConstructor]
    43     protected SymbolicExpressionTreeBottomUpSimilarityCalculator(bool deserializing)
    44       : base(deserializing) {
     47    protected SymbolicExpressionTreeBottomUpSimilarityCalculator(StorableConstructorFlag _) : base(_) {
    4548    }
    4649
     
    5356    }
    5457
     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      var calculator = new SymbolicExpressionTreeBottomUpSimilarityCalculator { MatchConstantValues = strict, MatchVariableWeights = strict };
     69      return CalculateSimilarity(n1, n2, strict);
     70    }
     71
     72    public static Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, bool strict = false) {
     73      return ComputeBottomUpMapping(ActualRoot(t1), ActualRoot(t2), strict);
     74    }
     75
     76    public static Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2, bool strict = false) {
     77      var calculator = new SymbolicExpressionTreeBottomUpSimilarityCalculator { MatchConstantValues = strict, MatchVariableWeights = strict };
     78      return calculator.ComputeBottomUpMapping(n1, n2);
     79    }
     80    #endregion
     81
    5582    public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
    56       if (t1 == t2)
     83      return CalculateSimilarity(t1, t2, out Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> map);
     84    }
     85
     86    public double CalculateSimilarity(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, out NodeMap map) {
     87      if (t1 == t2) {
     88        map = null;
    5789        return 1;
    58 
    59       var map = ComputeBottomUpMapping(t1.Root, t2.Root);
    60       return 2.0 * map.Count / (t1.Length + t2.Length);
     90      }
     91      map = ComputeBottomUpMapping(t1, t2);
     92      return 2.0 * map.Count / (t1.Length + t2.Length - 4); // -4 for skipping root and start symbols in the two trees
    6193    }
    6294
     
    78110    }
    79111
     112    public Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2) {
     113      return ComputeBottomUpMapping(ActualRoot(t1), ActualRoot(t2));
     114    }
     115
    80116    public Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> ComputeBottomUpMapping(ISymbolicExpressionTreeNode n1, ISymbolicExpressionTreeNode n2) {
    81       var comparer = new SymbolicExpressionTreeNodeComparer(); // use a node comparer because it's faster than calling node.ToString() (strings are expensive) and comparing strings
    82117      var compactedGraph = Compact(n1, n2);
    83118
    84       var forwardMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t1 => nodes of t2
    85       var reverseMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t2 => nodes of t1
    86 
    87       // visit nodes in order of decreasing height to ensure correct mapping
    88       var nodes1 = n1.IterateNodesPrefix().OrderByDescending(x => x.GetDepth()).ToList();
    89       var nodes2 = n2.IterateNodesPrefix().ToList();
    90       for (int i = 0; i < nodes1.Count; ++i) {
    91         var v = nodes1[i];
    92         if (forwardMap.ContainsKey(v))
     119      IEnumerable<ISymbolicExpressionTreeNode> Subtrees(ISymbolicExpressionTreeNode node, bool commutative) {
     120        var subtrees = node.IterateNodesPrefix();
     121        return commutative ? subtrees.OrderBy(x => compactedGraph[x].Hash) : subtrees;
     122      }
     123
     124      var nodes1 = n1.IterateNodesPostfix().OrderByDescending(x => x.GetLength()); // by descending length so that largest subtrees are mapped first
     125      var nodes2 = (List<ISymbolicExpressionTreeNode>)n2.IterateNodesPostfix();
     126
     127      var forward = new NodeMap();
     128      var reverse = new NodeMap();
     129
     130      foreach (ISymbolicExpressionTreeNode v in nodes1) {
     131        if (forward.ContainsKey(v))
    93132          continue;
     133
    94134        var kv = compactedGraph[v];
    95         ISymbolicExpressionTreeNode w = null;
    96         for (int j = 0; j < nodes2.Count; ++j) {
    97           var t = nodes2[j];
    98           if (reverseMap.ContainsKey(t) || compactedGraph[t] != kv)
     135        var commutative = v.SubtreeCount > 1 && commutativeSymbols.Contains(kv.Label);
     136
     137        foreach (ISymbolicExpressionTreeNode w in nodes2) {
     138          if (w.GetLength() != kv.Length || w.GetDepth() != kv.Depth || reverse.ContainsKey(w) || compactedGraph[w] != kv)
    99139            continue;
    100           w = t;
     140
     141          // map one whole subtree to the other
     142          foreach (var t in Subtrees(v, commutative).Zip(Subtrees(w, commutative), Tuple.Create)) {
     143            forward[t.Item1] = t.Item2;
     144            reverse[t.Item2] = t.Item1;
     145          }
     146
    101147          break;
    102148        }
    103         if (w == null) continue;
    104 
    105         // at this point we know that v and w are isomorphic, however, the mapping cannot be done directly
    106         // (as in the paper) because the trees are unordered (subtree order might differ). the solution is
    107         // to sort subtrees from under commutative labels (this will work because the subtrees are isomorphic!)
    108         // while iterating over the two subtrees
    109         var vv = IterateBreadthOrdered(v, comparer).ToList();
    110         var ww = IterateBreadthOrdered(w, comparer).ToList();
    111         int len = Math.Min(vv.Count, ww.Count);
    112         for (int j = 0; j < len; ++j) {
    113           var s = vv[j];
    114           var t = ww[j];
    115           Debug.Assert(!reverseMap.ContainsKey(t));
    116 
    117           forwardMap[s] = t;
    118           reverseMap[t] = s;
    119         }
    120       }
    121 
    122       return forwardMap;
     149      }
     150
     151      return forward;
    123152    }
    124153
     
    132161      var nodeMap = new Dictionary<ISymbolicExpressionTreeNode, GraphNode>(); // K
    133162      var labelMap = new Dictionary<string, GraphNode>(); // L
    134       var childrenCount = new Dictionary<ISymbolicExpressionTreeNode, int>(); // Children
    135163
    136164      var nodes = n1.IterateNodesPostfix().Concat(n2.IterateNodesPostfix()); // the disjoint union F
    137       var list = new List<GraphNode>();
    138       var queue = new Queue<ISymbolicExpressionTreeNode>();
    139 
    140       foreach (var n in nodes) {
    141         if (n.SubtreeCount == 0) {
    142           var label = GetLabel(n);
     165      var graph = new List<GraphNode>();
     166
     167      IEnumerable<GraphNode> Subtrees(GraphNode g, bool commutative) {
     168        var subtrees = g.SymbolicExpressionTreeNode.Subtrees.Select(x => nodeMap[x]);
     169        return commutative ? subtrees.OrderBy(x => x.Hash) : subtrees;
     170      }
     171
     172      foreach (var node in nodes) {
     173        var label = GetLabel(node);
     174
     175        if (node.SubtreeCount == 0) {
    143176          if (!labelMap.ContainsKey(label)) {
    144             var z = new GraphNode { SymbolicExpressionTreeNode = n, Label = label };
    145             labelMap[z.Label] = z;
    146           }
    147           nodeMap[n] = labelMap[label];
    148           queue.Enqueue(n);
     177            labelMap[label] = new GraphNode(node, label);
     178          }
     179          nodeMap[node] = labelMap[label];
    149180        } else {
    150           childrenCount[n] = n.SubtreeCount;
    151         }
    152       }
    153       while (queue.Any()) {
    154         var n = queue.Dequeue();
    155         if (n.SubtreeCount > 0) {
     181          var v = new GraphNode(node, label);
    156182          bool found = false;
    157           var label = n.Symbol.Name;
    158           var depth = n.GetDepth();
    159 
    160           bool sort = n.SubtreeCount > 1 && commutativeSymbols.Contains(label);
    161           var nSubtrees = n.Subtrees.Select(x => nodeMap[x]).ToList();
    162           if (sort) nSubtrees.Sort((a, b) => string.CompareOrdinal(a.Label, b.Label));
    163 
    164           for (int i = list.Count - 1; i >= 0; --i) {
    165             var w = list[i];
    166             if (!(n.SubtreeCount == w.SubtreeCount && label == w.Label && depth == w.Depth))
     183          var commutative = node.SubtreeCount > 1 && commutativeSymbols.Contains(label);
     184
     185          var vv = Subtrees(v, commutative);
     186
     187          foreach (var w in graph) {
     188            if (v.Depth != w.Depth || v.SubtreeCount != w.SubtreeCount || v.Length != w.Length || v.Label != w.Label) {
    167189              continue;
    168 
    169             // sort V and W when the symbol is commutative because we are dealing with unordered trees
    170             var m = w.SymbolicExpressionTreeNode;
    171             var mSubtrees = m.Subtrees.Select(x => nodeMap[x]).ToList();
    172             if (sort) mSubtrees.Sort((a, b) => string.CompareOrdinal(a.Label, b.Label));
    173 
    174             found = nSubtrees.SequenceEqual(mSubtrees);
     190            }
     191
     192            var ww = Subtrees(w, commutative);
     193            found = vv.SequenceEqual(ww);
     194
    175195            if (found) {
    176               nodeMap[n] = w;
     196              nodeMap[node] = w;
    177197              break;
    178198            }
    179199          }
    180 
    181200          if (!found) {
    182             var w = new GraphNode { SymbolicExpressionTreeNode = n, Label = label, Depth = depth };
    183             list.Add(w);
    184             nodeMap[n] = w;
     201            nodeMap[node] = v;
     202            graph.Add(v);
    185203          }
    186204        }
    187 
    188         if (n == n1 || n == n2)
    189           continue;
    190 
    191         var p = n.Parent;
    192         if (p == null)
    193           continue;
    194 
    195         childrenCount[p]--;
    196 
    197         if (childrenCount[p] == 0)
    198           queue.Enqueue(p);
    199       }
    200 
     205      }
    201206      return nodeMap;
    202207    }
    203208
    204     private IEnumerable<ISymbolicExpressionTreeNode> IterateBreadthOrdered(ISymbolicExpressionTreeNode node, ISymbolicExpressionTreeNodeComparer comparer) {
    205       var list = new List<ISymbolicExpressionTreeNode> { node };
    206       int i = 0;
    207       while (i < list.Count) {
    208         var n = list[i];
    209         if (n.SubtreeCount > 0) {
    210           var subtrees = commutativeSymbols.Contains(node.Symbol.Name) ? n.Subtrees.OrderBy(x => x, comparer) : n.Subtrees;
    211           list.AddRange(subtrees);
    212         }
    213         i++;
    214       }
    215       return list;
    216     }
    217 
    218     private static string GetLabel(ISymbolicExpressionTreeNode node) {
     209    private string GetLabel(ISymbolicExpressionTreeNode node) {
    219210      if (node.SubtreeCount > 0)
    220211        return node.Symbol.Name;
    221212
    222       var constant = node as ConstantTreeNode;
    223       if (constant != null)
    224         return constant.Value.ToString(CultureInfo.InvariantCulture);
    225 
    226       var variable = node as VariableTreeNode;
    227       if (variable != null)
    228         return variable.Weight + variable.VariableName;
     213      if (node is ConstantTreeNode constant)
     214        return MatchConstantValues ? constant.Value.ToString(CultureInfo.InvariantCulture) : constant.Symbol.Name;
     215
     216      if (node is VariableTreeNode variable)
     217        return MatchVariableWeights ? variable.Weight + variable.VariableName : variable.VariableName;
    229218
    230219      return node.ToString();
     
    232221
    233222    private class GraphNode {
    234       public ISymbolicExpressionTreeNode SymbolicExpressionTreeNode;
    235       public string Label;
    236       public int Depth;
     223      private GraphNode() { }
     224
     225      public GraphNode(ISymbolicExpressionTreeNode node, string label) {
     226        SymbolicExpressionTreeNode = node;
     227        Label = label;
     228        Hash = GetHashCode();
     229        Depth = node.GetDepth();
     230        Length = node.GetLength();
     231      }
     232
     233      public int Hash { get; }
     234      public ISymbolicExpressionTreeNode SymbolicExpressionTreeNode { get; }
     235      public string Label { get; }
     236      public int Depth { get; }
    237237      public int SubtreeCount { get { return SymbolicExpressionTreeNode.SubtreeCount; } }
     238      public int Length { get; }
    238239    }
    239240  }
  • branches/1837_Sliding Window GP/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeEqualityComparer.cs

    r10562 r17687  
    22using System.Collections.Generic;
    33using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
     4using HEAL.Attic;
    45
    56namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
     7  [StorableType("535830d4-551e-4b53-97e3-9605bd7e785f")]
    68  public class SymbolicExpressionTreeEqualityComparer : IEqualityComparer<ISymbolicExpressionTree> {
    7     public SymbolicExpressionTreeNodeSimilarityComparer SimilarityComparer { get; set; }
     9    [Storable]
     10    public SymbolicExpressionTreeNodeEqualityComparer SimilarityComparer { get; set; }
     11
     12
     13    [StorableConstructor]
     14    protected SymbolicExpressionTreeEqualityComparer(StorableConstructorFlag _) { }
     15    public SymbolicExpressionTreeEqualityComparer() { }
    816
    917    public bool Equals(ISymbolicExpressionTree a, ISymbolicExpressionTree b) {
    1018      if (SimilarityComparer == null) throw new Exception("SimilarityComparer needs to be initialized first.");
    11       return a.Length == b.Length &&
    12              SymbolicExpressionTreeMatching.Match(a.Root, b.Root, SimilarityComparer) == Math.Min(a.Length, b.Length);
     19      return a.Length == b.Length && SymbolicExpressionTreeMatching.Match(a.Root, b.Root, SimilarityComparer) == Math.Min(a.Length, b.Length);
    1320    }
    1421
     
    1623      return (tree.Length << 8) % 12345;
    1724    }
     25
    1826  }
    1927}
  • branches/1837_Sliding Window GP/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeMatching.cs

    r10562 r17687  
    1 using System;
     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
     23
     24using System;
    225using System.Collections.Generic;
    326using System.Linq;
     
    730namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
    831  public static class SymbolicExpressionTreeMatching {
    9     public static bool ContainsSubtree(this ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode subtree, SymbolicExpressionTreeNodeSimilarityComparer comparer) {
     32    public static bool ContainsSubtree(this ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode subtree, SymbolicExpressionTreeNodeEqualityComparer comparer) {
    1033      return FindMatches(root, subtree, comparer).Any();
    1134    }
    12     public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTree tree, ISymbolicExpressionTreeNode subtree, SymbolicExpressionTreeNodeSimilarityComparer comparer) {
     35    public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTree tree, ISymbolicExpressionTreeNode subtree, SymbolicExpressionTreeNodeEqualityComparer comparer) {
    1336      return FindMatches(tree.Root, subtree, comparer);
    1437    }
    1538
    16     public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode subtree, SymbolicExpressionTreeNodeSimilarityComparer comp) {
     39    public static IEnumerable<ISymbolicExpressionTreeNode> FindMatches(ISymbolicExpressionTreeNode root, ISymbolicExpressionTreeNode subtree, SymbolicExpressionTreeNodeEqualityComparer comp) {
    1740      var fragmentLength = subtree.GetLength();
    1841      // below, we use ">=" for Match(n, subtree, comp) >= fragmentLength because in case of relaxed conditions,
     
    2952    /// </summary>
    3053    /// <returns>Number of pairs that were matched</returns>
    31     public static int Match(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b, SymbolicExpressionTreeNodeSimilarityComparer comp) {
     54    public static int Match(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b, ISymbolicExpressionTreeNodeSimilarityComparer comp) {
    3255      if (!comp.Equals(a, b)) return 0;
    3356      int m = a.SubtreeCount;
     
    4568      return matrix[m, n] + 1;
    4669    }
     70
     71    /// <summary>
     72    /// Calculates the difference between two symbolic expression trees.
     73    /// </summary>
     74    /// <param name="tree">The first symbolic expression tree</param>
     75    /// <param name="other">The second symbolic expression tree</param>
     76    /// <returns>Returns the root of the subtree (from T1) by which T1 differs from T2, or null if no difference is found.</returns>
     77    public static ISymbolicExpressionTreeNode Difference(this ISymbolicExpressionTree tree, ISymbolicExpressionTree other) {
     78      return Difference(tree.Root, other.Root);
     79    }
     80
     81    public static ISymbolicExpressionTreeNode Difference(this ISymbolicExpressionTreeNode node, ISymbolicExpressionTreeNode other) {
     82      var a = node.IterateNodesPrefix().ToList();
     83      var b = other.IterateNodesPrefix().ToList();
     84      var list = new List<ISymbolicExpressionTreeNode>();
     85      for (int i = 0, j = 0; i < a.Count && j < b.Count; ++i, ++j) {
     86        var s1 = a[i].ToString();
     87        var s2 = b[j].ToString();
     88        if (s1 == s2) continue;
     89        list.Add(a[i]);
     90        // skip subtrees since the parents are already different
     91        i += a[i].SubtreeCount;
     92        j += b[j].SubtreeCount;
     93      }
     94      ISymbolicExpressionTreeNode result = list.Count > 0 ? LowestCommonAncestor(node, list) : null;
     95      return result;
     96    }
     97
     98    private static ISymbolicExpressionTreeNode LowestCommonAncestor(ISymbolicExpressionTreeNode root, List<ISymbolicExpressionTreeNode> nodes) {
     99      if (nodes.Count == 0)
     100        throw new ArgumentException("The nodes list should contain at least one element.");
     101
     102      if (nodes.Count == 1)
     103        return nodes[0];
     104
     105      int minLevel = nodes.Min(x => root.GetBranchLevel(x));
     106
     107      // bring the nodes in the nodes to the same level (relative to the root)
     108      for (int i = 0; i < nodes.Count; ++i) {
     109        var node = nodes[i];
     110        var level = root.GetBranchLevel(node);
     111        for (int j = minLevel; j < level; ++j)
     112          node = node.Parent;
     113        nodes[i] = node;
     114      }
     115
     116      // while not all the elements in the nodes are equal, go one level up
     117      while (nodes.Any(x => x != nodes[0])) {
     118        for (int i = 0; i < nodes.Count; ++i)
     119          nodes[i] = nodes[i].Parent;
     120      }
     121
     122      return nodes[0];
     123    }
    47124  }
    48125}
  • branches/1837_Sliding Window GP/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeMaxCommonSubtreeSimilarityCalculator.cs

    r15681 r17687  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    2525using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2626using HeuristicLab.Optimization.Operators;
    27 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     27using HEAL.Attic;
    2828
    2929namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
    30   [StorableClass]
     30  [StorableType("2634824A-D8E6-4047-9146-79EDF50BEED8")]
    3131  [Item("SymbolicExpressionTreeMaxCommonSubtreeSimilarityCalculator", "A similarity calculator based on the size of the maximum common subtree between two trees")]
    3232  public class SymbolicExpressionTreeMaxCommonSubtreeSimilarityCalculator : SolutionSimilarityCalculator {
     
    4646
    4747    [StorableConstructor]
    48     protected SymbolicExpressionTreeMaxCommonSubtreeSimilarityCalculator(bool deserializing) : base(deserializing) { }
     48    protected SymbolicExpressionTreeMaxCommonSubtreeSimilarityCalculator(StorableConstructorFlag _) : base(_) { }
    4949
    5050    public override IDeepCloneable Clone(Cloner cloner) {
  • branches/1837_Sliding Window GP/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeNodeComparer.cs

    r10562 r17687  
    1 using System;
     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;
    223using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
     24using HEAL.Attic;
    325
    426namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
     27  [StorableType("eabf848e-d10c-499e-8c48-c771232ede0e")]
    528  // this comparer considers that a < b if the type of a is "greater" than the type of b, for example:
    629  // - A function node is "greater" than a terminal node
     
    831  // - used for bringing subtrees to a "canonical" form when the operation allows reordering of arguments
    932  public class SymbolicExpressionTreeNodeComparer : ISymbolicExpressionTreeNodeComparer {
    10     public int Compare(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) {
    11       if (!(a is SymbolicExpressionTreeTerminalNode)) {
    12         return b is SymbolicExpressionTreeTerminalNode
    13           ? -1
    14           : string.Compare(a.Symbol.Name, b.Symbol.Name, StringComparison.Ordinal);
    15       }
    16       if (!(b is SymbolicExpressionTreeTerminalNode)) return 1;
    17       // at this point we know a and b are terminal nodes
     33    public static int CompareNodes(ISymbolicExpressionTreeNode a, ISymbolicExpressionTreeNode b) {
     34      var ta = a as SymbolicExpressionTreeTerminalNode;
     35      var tb = b as SymbolicExpressionTreeTerminalNode;
     36
     37      if (ta == null)
     38        return tb == null ? String.CompareOrdinal(a.Symbol.Name, b.Symbol.Name) : -1;
     39
     40      if (tb == null)
     41        return 1;
     42
     43      // at this point we know a and b are both terminals
    1844      var va = a as VariableTreeNode;
    19       if (va != null) {
    20         if (b is ConstantTreeNode) return -1;
    21         var vb = (VariableTreeNode)b;
    22         return (va.VariableName.Equals(vb.VariableName)
    23           ? va.Weight.CompareTo(vb.Weight)
    24           : string.Compare(va.VariableName, vb.VariableName, StringComparison.Ordinal));
    25       }
    26       // at this point we know for sure that a is a constant tree node
    27       if (b is VariableTreeNode) return 1;
    28       var ca = (ConstantTreeNode)a;
    29       var cb = (ConstantTreeNode)b;
    30       return ca.Value.CompareTo(cb.Value);
     45      var vb = b as VariableTreeNode;
     46
     47      if (va != null)
     48        return vb == null ? -1 : CompareVariables(va, vb);
     49
     50      if (vb != null)
     51        return 1;
     52
     53      // at this point we know a and b are not variables
     54      var ca = a as ConstantTreeNode;
     55      var cb = b as ConstantTreeNode;
     56
     57      if (ca != null && cb != null)
     58        return ca.Value.CompareTo(cb.Value);
     59
     60      // for other unknown terminal types, compare strings
     61      return string.CompareOrdinal(a.ToString(), b.ToString());
     62    }
     63
     64    private static int CompareVariables(VariableTreeNode a, VariableTreeNode b) {
     65      int result = string.CompareOrdinal(a.VariableName, b.VariableName);
     66      return result == 0 ? a.Weight.CompareTo(b.Weight) : result;
     67    }
     68
     69    public int Compare(ISymbolicExpressionTreeNode x, ISymbolicExpressionTreeNode y) {
     70      return CompareNodes(x, y);
    3171    }
    3272  }
     73
    3374}
  • branches/1837_Sliding Window GP/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreeNodeEqualityComparer.cs

    r15681 r17687  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    2323using HeuristicLab.Core;
    2424using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    25 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     25using HEAL.Attic;
    2626
    2727namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
    2828  [Item("SymbolicExpressionTreeNodeEqualityComparer", "An operator that checks node equality based on different similarity measures.")]
    29   [StorableClass]
     29  [StorableType("F5BC06AA-3F08-4692-93E8-E44CE8205A46")]
    3030  public class SymbolicExpressionTreeNodeEqualityComparer : Item, ISymbolicExpressionTreeNodeSimilarityComparer {
    3131    [StorableConstructor]
    32     protected SymbolicExpressionTreeNodeEqualityComparer(bool deserializing) : base(deserializing) { }
     32    protected SymbolicExpressionTreeNodeEqualityComparer(StorableConstructorFlag _) : base(_) { }
    3333    protected SymbolicExpressionTreeNodeEqualityComparer(SymbolicExpressionTreeNodeEqualityComparer original, Cloner cloner)
    3434      : base(original, cloner) {
  • branches/1837_Sliding Window GP/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/TreeMatching/SymbolicExpressionTreePhenotypicSimilarityCalculator.cs

    r15681 r17687  
    11#region License Information
    22/* HeuristicLab
    3  * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
     3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
    44 *
    55 * This file is part of HeuristicLab.
     
    2626using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2727using HeuristicLab.Optimization.Operators;
    28 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     28using HEAL.Attic;
    2929
    3030namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
    3131  [Item("SymbolicExpressionTreePhenotypicSimilarityCalculator", "An operator that calculates the similarity betweeon two trees based on the correlation of their outputs.")]
    32   [StorableClass]
     32  [StorableType("163CE915-506E-472B-B77F-156ECC9D9C05")]
    3333  public class SymbolicExpressionTreePhenotypicSimilarityCalculator : SolutionSimilarityCalculator {
    3434    [Storable]
     
    4040
    4141    [StorableConstructor]
    42     protected SymbolicExpressionTreePhenotypicSimilarityCalculator(bool deserializing) : base(deserializing) { }
     42    protected SymbolicExpressionTreePhenotypicSimilarityCalculator(StorableConstructorFlag _) : base(_) { }
    4343
    4444    public SymbolicExpressionTreePhenotypicSimilarityCalculator(SymbolicExpressionTreePhenotypicSimilarityCalculator original, Cloner cloner)
Note: See TracChangeset for help on using the changeset viewer.