Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Matching/SymbolicExpressionTreeNodeComparer.cs @ 10563

Last change on this file since 10563 was 10562, checked in by bburlacu, 9 years ago

#2164: Committed initial version of the tree matching functionality.

File size: 1.6 KB
Line 
1using System;
2using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
3
4namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
5  // this comparer considers that a < b if the type of a is "greater" than the type of b, for example:
6  // - A function node is "greater" than a terminal node
7  // - A variable terminal is "greater" than a constant terminal
8  // - used for bringing subtrees to a "canonical" form when the operation allows reordering of arguments
9  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
18      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);
31    }
32  }
33}
Note: See TracBrowser for help on using the repository browser.