Free cookie consent management tool by TermsFeed Policy Generator

Changeset 11224


Ignore:
Timestamp:
07/24/14 16:57:38 (10 years ago)
Author:
bburlacu
Message:

#2215: Added checks for debugging purposes in the BottomUpSimilarityCalculator and refactored the SymbolicDataAnalysisInternalDiversityAnalyzer.

Location:
branches/HeuristicLab.BottomUpTreeDistance/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • branches/HeuristicLab.BottomUpTreeDistance/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Analyzers/SymbolicDataAnalysisInternalDiversityAnalyzer.cs

    r11221 r11224  
    2020#endregion
    2121
     22using System;
     23using System.Collections.Generic;
    2224using System.Linq;
    2325using HeuristicLab.Analysis;
    2426using HeuristicLab.Common;
    2527using HeuristicLab.Core;
     28using HeuristicLab.Data;
    2629using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
    2730using HeuristicLab.Operators;
     
    3538  public class SymbolicDataAnalysisInternalDiversityAnalyzer : SingleSuccessorOperator, ISymbolicDataAnalysisAnalyzer {
    3639    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
     40    private const string QualityParameterName = "Quality";
     41    private const string PercentageOfBestSolutionsParameterName = "PercentageOfBestSolutions";
     42
    3743    private const string ResultCollectionParameterName = "Results";
    3844    private readonly BottomUpSimilarityCalculator busCalculator;
     
    4248
    4349      Parameters.Add(new ScopeTreeLookupParameter<ISymbolicExpressionTree>(SymbolicExpressionTreeParameterName));
     50      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>(QualityParameterName));
    4451      Parameters.Add(new LookupParameter<ResultCollection>(ResultCollectionParameterName));
     52      Parameters.Add(new FixedValueParameter<PercentValue>(PercentageOfBestSolutionsParameterName));
    4553    }
    4654
     
    5361    }
    5462
     63    #region parameter properties
    5564    public IScopeTreeLookupParameter<ISymbolicExpressionTree> SymbolicExpressionTreeParameter {
    5665      get { return (IScopeTreeLookupParameter<ISymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
    5766    }
     67
     68    public IScopeTreeLookupParameter<DoubleValue> QualityParameter {
     69      get { return (IScopeTreeLookupParameter<DoubleValue>)Parameters[QualityParameterName]; }
     70    }
     71
    5872    public ILookupParameter<ResultCollection> ResultCollectionParameter {
    5973      get { return (ILookupParameter<ResultCollection>)Parameters[ResultCollectionParameterName]; }
     74    }
     75
     76    public IFixedValueParameter<PercentValue> PercentageOfBestSolutionsParameter {
     77      get { return (IFixedValueParameter<PercentValue>)Parameters[PercentageOfBestSolutionsParameterName]; }
     78    }
     79    #endregion
     80
     81    public double PercentageOfBestSolutions {
     82      get { return PercentageOfBestSolutionsParameter.Value.Value; }
     83      set { PercentageOfBestSolutionsParameter.Value.Value = value; }
    6084    }
    6185
     
    6993      if (!results.ContainsKey("Avg. Internal Diversity")) {
    7094        table = new DataTable("Internal Diversity") { VisualProperties = { YAxisTitle = "Internal Diversity" } };
    71         table.Rows.Add(new DataRow("Avg. Internal Diversity"));
     95        var row = new DataRow("Avg. Internal Diversity") { VisualProperties = { StartIndexZero = true } };
     96        table.Rows.Add(row);
    7297        results.Add(new Result("Avg. Internal Diversity", table));
    7398      } else {
     
    75100      }
    76101
    77       double diversity = 0;
    78       var trees = SymbolicExpressionTreeParameter.ActualValue;
    79       foreach (var tree in trees) {
    80         diversity += CalculateInternalDiversity(tree);
    81       }
     102      var trees = SymbolicExpressionTreeParameter.ActualValue.ToArray();
     103      var qualities = QualityParameter.ActualValue.ToArray();
    82104
    83       table.Rows["Avg. Internal Diversity"].Values.Add(diversity / trees.Length);
     105      Array.Sort(qualities, trees, new ReverseComparer());
     106      int n = (int)Math.Floor(trees.Length * PercentageOfBestSolutions);
     107
     108      double avgInternalDiversity = trees.Take(n).Average(tree => CalculateInternalDiversity(tree));
     109
     110      table.Rows["Avg. Internal Diversity"].Values.Add(avgInternalDiversity);
    84111      return base.Apply();
    85112    }
     
    109136    }
    110137  }
     138
     139  internal class ReverseComparer : IComparer<DoubleValue> {
     140    public int Compare(DoubleValue x, DoubleValue y) {
     141      return y.CompareTo(x);
     142    }
     143  }
    111144}
  • branches/HeuristicLab.BottomUpTreeDistance/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/SimilarityCalculators/BottomUpSimilarityCalculator.cs

    r11221 r11224  
    2222using System;
    2323using System.Collections.Generic;
     24using System.Drawing;
     25using System.Globalization;
    2426using System.Linq;
     27using System.Text;
    2528using HeuristicLab.Common;
    2629using HeuristicLab.Core;
    2730using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
     31using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
    2832using HeuristicLab.Optimization.Operators;
    2933using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     
    5256        throw new ArgumentException("Cannot calculate similarity when one of the arguments is null.");
    5357
    54       return CalculateSolutionSimilarity(t1, t2);
     58      var similarity = CalculateSolutionSimilarity(t1, t2);
     59      if (similarity > 1.0)
     60        throw new Exception("Similarity value cannot be greater than 1");
     61
     62      return similarity;
    5563    }
    5664
     
    6977      var reverseMap = new Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>(); // nodes of t2 => nodes of t1
    7078
    71       foreach (var v in n1.IterateNodesBreadth()) {
     79      foreach (var v in IterateBreadthOrdered(n1)) {
    7280        if (forwardMap.ContainsKey(v)) continue;
    7381        var kv = compactedGraph[v];
    7482        ISymbolicExpressionTreeNode w = null;
    75         foreach (var t in n2.IterateNodesBreadth()) {
     83        foreach (var t in IterateBreadthOrdered(n2)) {
    7684          if (reverseMap.ContainsKey(t) || compactedGraph[t] != kv) continue;
    7785          w = t;
     
    8896          var s = eV.Current;
    8997          var t = eW.Current;
     98          if (reverseMap.ContainsKey(t))
     99            throw new Exception("Mapping already present");
    90100          forwardMap[s] = t;
    91101          reverseMap[t] = s;
     
    201211      return arc;
    202212    }
     213
     214    // debugging
     215    private static string FormatMapping(ISymbolicExpressionTree t1, ISymbolicExpressionTree t2, Dictionary<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode> map) {
     216      var symbolNameMap = new Dictionary<string, string>
     217    {
     218      {"ProgramRootSymbol", "Prog"},
     219      {"StartSymbol","RPB"},
     220      {"Multiplication", "$\\times$"},
     221      {"Division", "$\\div$"},
     222      {"Addition", "$+$"},
     223      {"Subtraction", "$-$"},
     224      {"Exponential", "$\\exp$"},
     225      {"Logarithm", "$\\log$"}
     226    };
     227
     228      var sb = new StringBuilder();
     229      var nodeIds = new Dictionary<ISymbolicExpressionTreeNode, string>();
     230      int offset = 0;
     231      var layoutEngine = new ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode>(x => x.Subtrees);
     232      var nodeCoordinates = layoutEngine.CalculateLayout(t1.Root).ToDictionary(n => n.Content, n => new PointF(n.X, n.Y));
     233
     234      double ws = 0.5;
     235      double hs = 0.5;
     236
     237      var nl = Environment.NewLine;
     238      sb.Append("\\documentclass[class=minimal,border=0pt]{standalone}" + nl +
     239                 "\\usepackage{tikz}" + nl +
     240                 "\\begin{document}" + nl +
     241                 "\\begin{tikzpicture}" + nl +
     242                 "\\def\\ws{1}" + nl +
     243                 "\\def\\hs{0.7}" + nl +
     244                 "\\def\\offs{" + offset + "}" + nl);
     245
     246      foreach (var node in t1.IterateNodesBreadth()) {
     247        var id = Guid.NewGuid().ToString();
     248        nodeIds[node] = id;
     249        var coord = nodeCoordinates[node];
     250        var nodeName = symbolNameMap.ContainsKey(node.Symbol.Name) ? symbolNameMap[node.Symbol.Name] : node.ToString();
     251        sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\node ({0}) at (\\ws*{1} + \\offs,\\hs*{2}) {{{3}}};", nodeIds[node], ws * coord.X, -hs * coord.Y, EscapeLatexString(nodeName)));
     252      }
     253
     254      foreach (ISymbolicExpressionTreeNode t in t1.IterateNodesBreadth()) {
     255        var n = t;
     256        foreach (var s in t.Subtrees) {
     257          sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\draw ({0}) -- ({1});", nodeIds[n], nodeIds[s]));
     258        }
     259      }
     260
     261      nodeCoordinates = layoutEngine.CalculateLayout(t2.Root).ToDictionary(n => n.Content, n => new PointF(n.X, n.Y));
     262
     263      offset = 20;
     264      sb.Append("\\def\\offs{" + offset + "}" + nl);
     265      foreach (var node in t2.IterateNodesBreadth()) {
     266        var id = Guid.NewGuid().ToString();
     267        nodeIds[node] = id;
     268        var coord = nodeCoordinates[node];
     269        var nodeName = symbolNameMap.ContainsKey(node.Symbol.Name) ? symbolNameMap[node.Symbol.Name] : node.ToString();
     270        sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\node ({0}) at (\\ws*{1} + \\offs,\\hs*{2}) {{{3}}};", nodeIds[node], ws * coord.X, -hs * coord.Y, EscapeLatexString(nodeName)));
     271      }
     272
     273      foreach (ISymbolicExpressionTreeNode t in t2.IterateNodesBreadth()) {
     274        var n = t;
     275        foreach (var s in t.Subtrees) {
     276          sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "\\draw ({0}) -- ({1});", nodeIds[n], nodeIds[s]));
     277        }
     278      }
     279
     280      foreach (var p in map) {
     281        var id1 = nodeIds[p.Key];
     282        var id2 = nodeIds[p.Value];
     283
     284        sb.Append(string.Format(CultureInfo.InvariantCulture, "\\path[draw,->,color=gray] ({0}) edge[bend left,dashed] ({1});" + Environment.NewLine, id1, id2));
     285      }
     286      sb.Append("\\end{tikzpicture}" + nl +
     287                "\\end{document}" + nl);
     288      return sb.ToString();
     289    }
     290
     291    private static string EscapeLatexString(string s) {
     292      return s.Replace("\\", "\\\\").Replace("{", "\\{").Replace("}", "\\}").Replace("_", "\\_");
     293    }
    203294  }
    204295}
Note: See TracChangeset for help on using the changeset viewer.