Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PerformanceComparison/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionRLDView.cs @ 14035

Last change on this file since 14035 was 14035, checked in by abeham, 8 years ago

#2431:

  • Fixed bug that occurs when runs of unequal length are aggregated over multiple problem instances
File size: 42.2 KB
RevLine 
[7980]1#region License Information
2/* HeuristicLab
[12012]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[7980]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
[13583]22using HeuristicLab.Analysis;
23using HeuristicLab.Collections;
24using HeuristicLab.Core.Views;
25using HeuristicLab.Data;
26using HeuristicLab.MainForm;
27using HeuristicLab.MainForm.WindowsForms;
[7980]28using System;
29using System.Collections.Generic;
[11344]30using System.ComponentModel;
[12822]31using System.Drawing;
[12841]32using System.Globalization;
[7980]33using System.Linq;
[12771]34using System.Windows.Forms;
[7980]35
36namespace HeuristicLab.Optimization.Views {
[12803]37  [View("Run-length Distribution View")]
[7980]38  [Content(typeof(RunCollection), false)]
[12803]39  public partial class RunCollectionRLDView : ItemView {
[12771]40    private const string AllRuns = "All Runs";
[7980]41
[12822]42    private static readonly Color[] colors = new[] {
[12838]43      Color.FromArgb(0x40, 0x6A, 0xB7),
44      Color.FromArgb(0xB1, 0x6D, 0x01),
45      Color.FromArgb(0x4E, 0x8A, 0x06),
[12822]46      Color.FromArgb(0x75, 0x50, 0x7B),
47      Color.FromArgb(0x72, 0x9F, 0xCF),
48      Color.FromArgb(0xA4, 0x00, 0x00),
49      Color.FromArgb(0xAD, 0x7F, 0xA8),
[12838]50      Color.FromArgb(0x29, 0x50, 0xCF),
51      Color.FromArgb(0x90, 0xB0, 0x60),
52      Color.FromArgb(0xF5, 0x89, 0x30),
[12822]53      Color.FromArgb(0x55, 0x57, 0x53),
[12838]54      Color.FromArgb(0xEF, 0x59, 0x59),
55      Color.FromArgb(0xED, 0xD4, 0x30),
56      Color.FromArgb(0x63, 0xC2, 0x16),
[12822]57    };
[12838]58    private static readonly DataRowVisualProperties.DataRowLineStyle[] lineStyles = new[] {
59      DataRowVisualProperties.DataRowLineStyle.Solid,
60      DataRowVisualProperties.DataRowLineStyle.Dash,
61      DataRowVisualProperties.DataRowLineStyle.DashDot,
62      DataRowVisualProperties.DataRowLineStyle.Dot
63    };
[12822]64
[7980]65    public new RunCollection Content {
66      get { return (RunCollection)base.Content; }
67      set { base.Content = value; }
68    }
69
[12838]70    private double[] targets;
71    private double[] budgets;
[12804]72
[7980]73    private bool suppressUpdates;
[12838]74    private readonly IndexedDataTable<double> byTargetDataTable;
75    public IndexedDataTable<double> ByTargetDataTable {
76      get { return byTargetDataTable; }
[7980]77    }
[12838]78    private readonly IndexedDataTable<double> byCostDataTable;
79    public IndexedDataTable<double> ByCostDataTable {
80      get { return byCostDataTable; }
81    }
[7980]82
[12803]83    public RunCollectionRLDView() {
[8108]84      InitializeComponent();
[12838]85      byTargetDataTable = new IndexedDataTable<double>("ECDF by Target", "A data table containing the ECDF of each of a number of groups.") {
[12808]86        VisualProperties = {
87          YAxisTitle = "Proportion of reached targets",
[13583]88          YAxisMinimumFixedValue = 0,
89          YAxisMinimumAuto = false,
90          YAxisMaximumFixedValue = 1,
91          YAxisMaximumAuto = false
[12808]92        }
[12771]93      };
[12838]94      byTargetViewHost.Content = byTargetDataTable;
95      byCostDataTable = new IndexedDataTable<double>("ECDF by Cost", "A data table containing the ECDF of each of a number of groups.") {
96        VisualProperties = {
[12888]97          YAxisTitle = "Proportion of unused budgets",
[13583]98          YAxisMinimumFixedValue = 0,
99          YAxisMinimumAuto = false,
100          YAxisMaximumFixedValue = 1,
101          YAxisMaximumAuto = false
[12838]102        }
103      };
104      byCostViewHost.Content = byCostDataTable;
[8108]105      suppressUpdates = false;
106    }
107
[7980]108    #region Content events
109    protected override void RegisterContentEvents() {
110      base.RegisterContentEvents();
[12631]111      Content.ItemsAdded += Content_ItemsAdded;
112      Content.ItemsRemoved += Content_ItemsRemoved;
113      Content.CollectionReset += Content_CollectionReset;
114      Content.UpdateOfRunsInProgressChanged += Content_UpdateOfRunsInProgressChanged;
115      Content.OptimizerNameChanged += Content_AlgorithmNameChanged;
[7980]116    }
117    protected override void DeregisterContentEvents() {
[12631]118      Content.ItemsAdded -= Content_ItemsAdded;
119      Content.ItemsRemoved -= Content_ItemsRemoved;
120      Content.CollectionReset -= Content_CollectionReset;
121      Content.UpdateOfRunsInProgressChanged -= Content_UpdateOfRunsInProgressChanged;
122      Content.OptimizerNameChanged -= Content_AlgorithmNameChanged;
[7980]123      base.DeregisterContentEvents();
124    }
125
126    private void Content_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
[12631]127      if (suppressUpdates) return;
[7980]128      if (InvokeRequired) {
129        Invoke(new CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded), sender, e);
130        return;
131      }
[12841]132      UpdateGroupAndProblemComboBox();
[12631]133      UpdateDataTableComboBox();
[12771]134      foreach (var run in e.Items)
135        RegisterRunEvents(run);
[7980]136    }
137    private void Content_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
[12631]138      if (suppressUpdates) return;
[7980]139      if (InvokeRequired) {
140        Invoke(new CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved), sender, e);
141        return;
142      }
[12841]143      UpdateGroupAndProblemComboBox();
[12631]144      UpdateDataTableComboBox();
[12771]145      foreach (var run in e.Items)
146        DeregisterRunEvents(run);
[7980]147    }
148    private void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
[12631]149      if (suppressUpdates) return;
[7980]150      if (InvokeRequired) {
151        Invoke(new CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset), sender, e);
152        return;
153      }
[12841]154      UpdateGroupAndProblemComboBox();
[12631]155      UpdateDataTableComboBox();
[12771]156      foreach (var run in e.OldItems)
157        DeregisterRunEvents(run);
[7980]158    }
[8738]159    private void Content_AlgorithmNameChanged(object sender, EventArgs e) {
160      if (InvokeRequired)
161        Invoke(new EventHandler(Content_AlgorithmNameChanged), sender, e);
162      else UpdateCaption();
163    }
[7980]164    private void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
165      if (InvokeRequired) {
166        Invoke(new EventHandler(Content_UpdateOfRunsInProgressChanged), sender, e);
167        return;
168      }
169      suppressUpdates = Content.UpdateOfRunsInProgress;
[12631]170      if (!suppressUpdates) {
171        UpdateDataTableComboBox();
[12841]172        UpdateGroupAndProblemComboBox();
[12771]173        UpdateRuns();
[12631]174      }
[7980]175    }
176
177    private void RegisterRunEvents(IRun run) {
[11344]178      run.PropertyChanged += run_PropertyChanged;
[7980]179    }
180    private void DeregisterRunEvents(IRun run) {
[11344]181      run.PropertyChanged -= run_PropertyChanged;
[7980]182    }
[11344]183    private void run_PropertyChanged(object sender, PropertyChangedEventArgs e) {
[7980]184      if (suppressUpdates) return;
[11344]185      if (InvokeRequired) {
186        Invoke((Action<object, PropertyChangedEventArgs>)run_PropertyChanged, sender, e);
187      } else {
[12771]188        if (e.PropertyName == "Visible")
189          UpdateRuns();
[11344]190      }
[7980]191    }
192    #endregion
193
194    protected override void OnContentChanged() {
195      base.OnContentChanged();
196      dataTableComboBox.Items.Clear();
[12771]197      groupComboBox.Items.Clear();
[12838]198      byTargetDataTable.Rows.Clear();
[7980]199
[8738]200      UpdateCaption();
[7980]201      if (Content != null) {
[12841]202        UpdateGroupAndProblemComboBox();
[7980]203        UpdateDataTableComboBox();
204      }
205    }
206
[12806]207
[12841]208    private void UpdateGroupAndProblemComboBox() {
209      var selectedGroupItem = (string)groupComboBox.SelectedItem;
[12599]210
[12774]211      var groupings = Content.ParameterNames.OrderBy(x => x).ToArray();
[12771]212      groupComboBox.Items.Clear();
213      groupComboBox.Items.Add(AllRuns);
214      groupComboBox.Items.AddRange(groupings);
[12841]215      if (selectedGroupItem != null && groupComboBox.Items.Contains(selectedGroupItem)) {
216        groupComboBox.SelectedItem = selectedGroupItem;
[12771]217      } else if (groupComboBox.Items.Count > 0) {
218        groupComboBox.SelectedItem = groupComboBox.Items[0];
[7980]219      }
[12841]220
221      var problems = new HashSet<ProblemDescription>();
222      foreach (var run in Content) {
223        problems.Add(new ProblemDescription(run));
224      }
225
[12864]226      var problemTypesDifferent = problems.Select(x => x.ProblemType).Where(x => !string.IsNullOrEmpty(x)).Distinct().Count() > 1;
227      var problemNamesDifferent = problems.Select(x => x.ProblemName).Where(x => !string.IsNullOrEmpty(x)).Distinct().Count() > 1;
228      var evaluatorDifferent = problems.Select(x => x.Evaluator).Where(x => !string.IsNullOrEmpty(x)).Distinct().Count() > 1;
[13583]229      var maximizationDifferent = problems.Select(x => x.Maximization).Distinct().Count() > 1;
230      var allEqual = !problemTypesDifferent && !problemNamesDifferent && !evaluatorDifferent && !maximizationDifferent;
[12841]231
232      var selectedProblemItem = (ProblemDescription)problemComboBox.SelectedItem;
233      problemComboBox.Items.Clear();
[12864]234      problemComboBox.Items.Add(ProblemDescription.MatchAll);
235      if (selectedProblemItem == null || selectedProblemItem == ProblemDescription.MatchAll)
236        problemComboBox.SelectedIndex = 0;
[12841]237      foreach (var prob in problems.OrderBy(x => x.ToString()).ToList()) {
238        prob.DisplayProblemType = problemTypesDifferent;
239        prob.DisplayProblemName = problemNamesDifferent || allEqual;
240        prob.DisplayEvaluator = evaluatorDifferent;
[13583]241        prob.DisplayMaximization = maximizationDifferent;
[12841]242        problemComboBox.Items.Add(prob);
243        if (prob.Equals(selectedProblemItem)) problemComboBox.SelectedItem = prob;
244      }
245      SetEnabledStateOfControls();
[7980]246    }
247
248    private void UpdateDataTableComboBox() {
[12631]249      string selectedItem = (string)dataTableComboBox.SelectedItem;
250
[7986]251      dataTableComboBox.Items.Clear();
[7980]252      var dataTables = (from run in Content
253                        from result in run.Results
[12771]254                        where result.Value is IndexedDataTable<double>
[7980]255                        select result.Key).Distinct().ToArray();
256
257      dataTableComboBox.Items.AddRange(dataTables);
[12631]258      if (selectedItem != null && dataTableComboBox.Items.Contains(selectedItem)) {
259        dataTableComboBox.SelectedItem = selectedItem;
260      } else if (dataTableComboBox.Items.Count > 0) {
261        dataTableComboBox.SelectedItem = dataTableComboBox.Items[0];
262      }
[7980]263    }
264
[12838]265    protected override void SetEnabledStateOfControls() {
266      base.SetEnabledStateOfControls();
267      groupComboBox.Enabled = Content != null;
[12841]268      problemComboBox.Enabled = Content != null && problemComboBox.Items.Count > 1;
269      dataTableComboBox.Enabled = Content != null && dataTableComboBox.Items.Count > 1;
[12838]270      addTargetsAsResultButton.Enabled = Content != null && targets != null && dataTableComboBox.SelectedIndex >= 0;
271      addBudgetsAsResultButton.Enabled = Content != null && budgets != null && dataTableComboBox.SelectedIndex >= 0;
272    }
273
[13583]274    private Dictionary<string, Dictionary<ProblemDescription, Tuple<double, List<IRun>>>> GroupRuns() {
275      var groupedRuns = new Dictionary<string, Dictionary<ProblemDescription, Tuple<double, List<IRun>>>>();
[12841]276
277      var table = (string)dataTableComboBox.SelectedItem;
278      if (string.IsNullOrEmpty(table)) return groupedRuns;
279
280      var selectedGroup = (string)groupComboBox.SelectedItem;
281      if (string.IsNullOrEmpty(selectedGroup)) return groupedRuns;
282
283      var selectedProblem = (ProblemDescription)problemComboBox.SelectedItem;
[12864]284      if (selectedProblem == null) return groupedRuns;
[12841]285
[13583]286      var targetsPerProblem = CalculateBestTargetPerProblemInstance(table);
[12841]287
[12864]288      foreach (var x in (from r in Content
[12888]289                         where (selectedGroup == AllRuns || r.Parameters.ContainsKey(selectedGroup))
[12864]290                           && selectedProblem.Match(r)
291                           && r.Results.ContainsKey(table)
292                           && r.Visible
293                         group r by selectedGroup == AllRuns ? AllRuns : r.Parameters[selectedGroup].ToString() into g
294                         select Tuple.Create(g.Key, g.ToList()))) {
[13583]295        var pDict = new Dictionary<ProblemDescription, Tuple<double, List<IRun>>>();
[12864]296        foreach (var y in (from r in x.Item2
[13583]297                           let pd = new ProblemDescription(r)
[12864]298                           group r by pd into g
299                           select Tuple.Create(g.Key, g.ToList()))) {
300          pDict[y.Item1] = Tuple.Create(targetsPerProblem[y.Item1], y.Item2);
301        }
302        groupedRuns[x.Item1] = pDict;
303      }
304
[12841]305      return groupedRuns;
306    }
307
[12838]308    #region Performance analysis by (multiple) target(s)
309    private void UpdateResultsByTarget() {
310      // necessary to reset log scale -> empty chart cannot use log scaling
311      byTargetDataTable.VisualProperties.XAxisLogScale = false;
312      byTargetDataTable.Rows.Clear();
313
314      var table = (string)dataTableComboBox.SelectedItem;
315      if (string.IsNullOrEmpty(table)) return;
316
[12864]317      if (targets == null) GenerateDefaultTargets();
[12838]318
[12841]319      var groupedRuns = GroupRuns();
320      if (groupedRuns.Count == 0) return;
[12838]321
322      var xAxisTitles = new HashSet<string>();
323      var colorCount = 0;
324      var lineStyleCount = 0;
325
[14035]326      var maxEfforts = new Dictionary<ProblemDescription, double>();
[12838]327      foreach (var group in groupedRuns) {
[14035]328        foreach (var problem in group.Value) {
329          double eff;
330          if (!maxEfforts.TryGetValue(problem.Key, out eff)) {
331            eff = 0.0;
332          }
333          foreach (var run in problem.Value.Item2) {
334            var maxEff = ((IndexedDataTable<double>)run.Results[table]).Rows.First().Values.Last().Item1;
335            if (maxEff > eff) eff = maxEff;
336          }
337          maxEfforts[problem.Key] = eff;
338        }
339      }
340      // if the group contains multiple different problems we want to use the minimal maximal observed effort
341      // otherwise we run into situations where we don't have data for a certain problem instance anymore
342      // this is a special case when aggregating over multiple problem instances
343      var maxEffort = maxEfforts.Values.Min();
344
345      foreach (var group in groupedRuns) {
[13736]346        // hits describes the number of target hits at a certain time for a certain group
347        var hits = new Dictionary<string, SortedList<double, int>>();
348        // misses describes the number of target misses after a certain time for a certain group
349        // for instance when a run ends, but has not achieved all targets, misses describes
350        // how many targets have been left open at the point when the run ended
351        var misses = new Dictionary<string, SortedList<double, int>>();
[12838]352        var maxLength = 0.0;
353
[13736]354        var noRuns = 0;
[12864]355        foreach (var problem in group.Value) {
356          foreach (var run in problem.Value.Item2) {
357            var resultsTable = (IndexedDataTable<double>)run.Results[table];
358            xAxisTitles.Add(resultsTable.VisualProperties.XAxisTitle);
[12838]359
[12864]360            if (eachOrAllTargetCheckBox.Checked) {
[14035]361              CalculateHitsForEachTarget(hits, misses, resultsTable.Rows.First(), problem.Key, group.Key, problem.Value.Item1, maxEffort);
[13736]362              // achiving each target can be seen as a separate run for that target only
363              noRuns += targets.Length;
[12864]364            } else {
[14035]365              var length = CalculateHitsForAllTargets(hits, misses, resultsTable.Rows.First(), problem.Key, group.Key, problem.Value.Item1, maxEffort);
[13736]366              maxLength = Math.Max(length, maxLength);
367              noRuns++;
[12864]368            }
[12838]369          }
370        }
371
372        foreach (var list in hits) {
373          var row = new IndexedDataRow<double>(list.Key) {
374            VisualProperties = {
375              ChartType = DataRowVisualProperties.DataRowChartType.StepLine,
376              LineWidth = 2,
377              Color = colors[colorCount],
[13745]378              LineStyle = lineStyles[lineStyleCount],
379              StartIndexZero = false
[12838]380            }
381          };
382
[13736]383          var ecdf = 0.0;
384          var iter = misses[list.Key].GetEnumerator();
385          iter.MoveNext();
386          var sumTargets = noRuns * targets.Length;
[12838]387          foreach (var h in list.Value) {
[13736]388            ecdf += h.Value;
389            while (iter.Current.Key < h.Key) {
390              sumTargets -= iter.Current.Value;
391              if (!iter.MoveNext()) break;
392            }
393            row.Values.Add(Tuple.Create(h.Key, ecdf / sumTargets));
[12838]394          }
395
396          if (maxLength > 0 && (row.Values.Count == 0 || row.Values.Last().Item1 < maxLength))
[13736]397            row.Values.Add(Tuple.Create(maxLength, ecdf / sumTargets));
[12838]398
399          byTargetDataTable.Rows.Add(row);
400        }
401        colorCount = (colorCount + 1) % colors.Length;
402        if (colorCount == 0) lineStyleCount = (lineStyleCount + 1) % lineStyles.Length;
403      }
404
[12888]405      if (targets.Length == 1)
406        ByTargetDataTable.VisualProperties.YAxisTitle = "Probability to be " + (targets[0] * 100) + "% worse than best";
407      else ByTargetDataTable.VisualProperties.YAxisTitle = "Proportion of reached targets";
[12838]408      byTargetDataTable.VisualProperties.XAxisTitle = string.Join(" / ", xAxisTitles);
409      byTargetDataTable.VisualProperties.XAxisLogScale = byTargetDataTable.Rows.Count > 0 && targetLogScalingCheckBox.Checked;
[12841]410
411      UpdateErtTables(groupedRuns);
[12838]412    }
413
[12864]414    private void GenerateDefaultTargets() {
415      targets = new[] { 0.1, 0.05, 0.02, 0.01, 0 };
[12838]416      suppressTargetsEvents = true;
[12888]417      targetsTextBox.Text = string.Join("% ; ", targets.Select(x => x * 100)) + "%";
[12838]418      suppressTargetsEvents = false;
419    }
420
[13736]421    private void CalculateHitsForEachTarget(Dictionary<string, SortedList<double, int>> hits,
422                                            Dictionary<string, SortedList<double, int>> misses,
423                                            IndexedDataRow<double> row, ProblemDescription problem,
[14035]424                                            string group, double bestTarget, double maxEffort) {
[13583]425      foreach (var l in targets.Select(x => (problem.IsMaximization() ? (1 - x) : (1 + x)) * bestTarget)) {
[12864]426        var key = group + "-" + l;
[13736]427        if (!hits.ContainsKey(key)) {
428          hits.Add(key, new SortedList<double, int>());
429          misses.Add(key, new SortedList<double, int>());
430        }
431        var hit = false;
[12838]432        foreach (var v in row.Values) {
[14035]433          if (v.Item1 > maxEffort) break;
[13583]434          if (problem.IsMaximization() && v.Item2 >= l || !problem.IsMaximization() && v.Item2 <= l) {
[12838]435            if (hits[key].ContainsKey(v.Item1))
[13736]436              hits[key][v.Item1]++;
437            else hits[key][v.Item1] = 1;
438            hit = true;
[12838]439            break;
440          }
441        }
[13736]442        if (!hit) {
[14035]443          var max = Math.Min(row.Values.Last().Item1, maxEffort);
444          if (misses[key].ContainsKey(max))
445            misses[key][max]++;
446          else misses[key][max] = 1;
[13736]447        }
[12838]448      }
449    }
450
[13736]451    private double CalculateHitsForAllTargets(Dictionary<string, SortedList<double, int>> hits,
452                                              Dictionary<string, SortedList<double, int>> misses,
453                                              IndexedDataRow<double> row, ProblemDescription problem,
[14035]454                                              string group, double bestTarget, double maxEffort) {
[12838]455      var values = row.Values;
[13736]456      if (!hits.ContainsKey(group)) {
457        hits.Add(group, new SortedList<double, int>());
458        misses.Add(group, new SortedList<double, int>());
459      }
[12838]460
461      var i = 0;
462      var j = 0;
463      while (i < targets.Length && j < values.Count) {
[13583]464        var target = (problem.IsMaximization() ? (1 - targets[i]) : (1 + targets[i])) * bestTarget;
[12838]465        var current = values[j];
[14035]466        if (current.Item1 > maxEffort) break;
[13583]467        if (problem.IsMaximization() && current.Item2 >= target
468          || !problem.IsMaximization() && current.Item2 <= target) {
[13736]469          if (hits[group].ContainsKey(current.Item1)) hits[group][current.Item1]++;
470          else hits[group][current.Item1] = 1;
[12838]471          i++;
472        } else {
473          j++;
474        }
475      }
476      if (j == values.Count) j--;
[14035]477      var effort = Math.Min(values[j].Item1, maxEffort);
[13736]478      if (i < targets.Length) {
[14035]479        if (misses[group].ContainsKey(effort))
480          misses[group][effort] += targets.Length - i;
481        else misses[group][effort] = targets.Length - i;
[13736]482      }
[14035]483      return effort;
[12838]484    }
[12841]485
[13583]486    private void UpdateErtTables(Dictionary<string, Dictionary<ProblemDescription, Tuple<double, List<IRun>>>> groupedRuns) {
[12888]487      ertTableView.Content = null;
[12841]488      var columns = 1 + targets.Length + 1;
[12864]489      var matrix = new string[groupedRuns.Count * groupedRuns.Max(x => x.Value.Count) + groupedRuns.Max(x => x.Value.Count), columns];
[12841]490      var rowCount = 0;
491
[12956]492      var tableName = (string)dataTableComboBox.SelectedItem;
493      if (string.IsNullOrEmpty(tableName)) return;
[12864]494
[13583]495      var targetsPerProblem = CalculateBestTargetPerProblemInstance(tableName);
[12956]496
[12841]497      var colNames = new string[columns];
498      colNames[0] = colNames[colNames.Length - 1] = string.Empty;
499      for (var i = 0; i < targets.Length; i++) {
[12864]500        colNames[i + 1] = targets[i].ToString("0.0%");
[12841]501      }
[12864]502      var problems = groupedRuns.SelectMany(x => x.Value.Keys).Distinct().ToList();
[12841]503
[12864]504      foreach (var problem in problems) {
[13583]505        matrix[rowCount, 0] = problem.ToString();
[12841]506        for (var i = 0; i < targets.Length; i++) {
[13583]507          matrix[rowCount, i + 1] = (targetsPerProblem[problem] * (problem.IsMaximization() ? (1 - targets[i]) : (1 + targets[i]))).ToString(CultureInfo.CurrentCulture.NumberFormat);
[12841]508        }
[12864]509        matrix[rowCount, columns - 1] = "#succ";
[12841]510        rowCount++;
[12864]511
512        foreach (var group in groupedRuns) {
513          matrix[rowCount, 0] = group.Key;
[12939]514          if (!group.Value.ContainsKey(problem)) {
515            matrix[rowCount, columns - 1] = "N/A";
516            rowCount++;
517            continue;
518          }
[12864]519          var runs = group.Value[problem].Item2;
[12956]520          ErtCalculationResult result = default(ErtCalculationResult);
[12864]521          for (var i = 0; i < targets.Length; i++) {
[13583]522            result = ExpectedRuntimeHelper.CalculateErt(runs, tableName, (problem.IsMaximization() ? (1 - targets[i]) : (1 + targets[i])) * group.Value[problem].Item1, problem.IsMaximization());
[12956]523            matrix[rowCount, i + 1] = result.ToString();
[12864]524          }
[12956]525          matrix[rowCount, columns - 1] = targets.Length > 0 ? result.SuccessfulRuns + "/" + result.TotalRuns : "-";
[12864]526          rowCount++;
527        }
[12841]528      }
[12888]529      ertTableView.Content = new StringMatrix(matrix) { ColumnNames = colNames };
530      ertTableView.DataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
[12841]531    }
[12838]532    #endregion
533
534    #region Performance analysis by (multiple) budget(s)
535    private void UpdateResultsByCost() {
536      // necessary to reset log scale -> empty chart cannot use log scaling
537      byCostDataTable.VisualProperties.XAxisLogScale = false;
538      byCostDataTable.Rows.Clear();
539
540      var table = (string)dataTableComboBox.SelectedItem;
541      if (string.IsNullOrEmpty(table)) return;
542
543      if (budgets == null) GenerateDefaultBudgets(table);
544
[12841]545      var groupedRuns = GroupRuns();
546      if (groupedRuns.Count == 0) return;
[12838]547
548      var colorCount = 0;
549      var lineStyleCount = 0;
550
[13583]551      var targetsPerProblem = CalculateBestTargetPerProblemInstance((string)dataTableComboBox.SelectedItem);
[12865]552
[12838]553      foreach (var group in groupedRuns) {
554        var hits = new Dictionary<string, SortedList<double, double>>();
555
[12864]556        foreach (var problem in group.Value) {
557          foreach (var run in problem.Value.Item2) {
558            var resultsTable = (IndexedDataTable<double>)run.Results[table];
[12838]559
[12864]560            if (eachOrAllBudgetsCheckBox.Checked) {
[13583]561              CalculateHitsForEachBudget(hits, resultsTable.Rows.First(), group.Value.Count, problem.Key, group.Key, problem.Value.Item2.Count, targetsPerProblem[problem.Key]);
[12864]562            } else {
[13583]563              CalculateHitsForAllBudgets(hits, resultsTable.Rows.First(), group.Value.Count, problem.Key, group.Key, problem.Value.Item2.Count, targetsPerProblem[problem.Key]);
[12864]564            }
[12838]565          }
566        }
567
568        foreach (var list in hits) {
569          var row = new IndexedDataRow<double>(list.Key) {
570            VisualProperties = {
571              ChartType = DataRowVisualProperties.DataRowChartType.StepLine,
572              LineWidth = 2,
573              Color = colors[colorCount],
[13745]574              LineStyle = lineStyles[lineStyleCount],
575              StartIndexZero = false
[12838]576            }
577          };
578
579          var total = 0.0;
580          foreach (var h in list.Value) {
581            total += h.Value;
582            row.Values.Add(Tuple.Create(h.Key, total));
583          }
584
585          byCostDataTable.Rows.Add(row);
586        }
587        colorCount = (colorCount + 1) % colors.Length;
588        if (colorCount == 0) lineStyleCount = (lineStyleCount + 1) % lineStyles.Length;
589      }
590
[12865]591      byCostDataTable.VisualProperties.XAxisTitle = "Targets to Best-Known Ratio";
[12838]592      byCostDataTable.VisualProperties.XAxisLogScale = byCostDataTable.Rows.Count > 0 && budgetLogScalingCheckBox.Checked;
593    }
594
595    private void GenerateDefaultBudgets(string table) {
[12864]596      var runs = GroupRuns().SelectMany(x => x.Value.Values).SelectMany(x => x.Item2).ToList();
[12841]597      var min = runs.Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Select(y => y.Item1).Min()).Min();
598      var max = runs.Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Select(y => y.Item1).Max()).Max();
[12838]599
600      var maxMagnitude = (int)Math.Ceiling(Math.Log10(max));
601      var minMagnitude = (int)Math.Floor(Math.Log10(min));
602      if (maxMagnitude - minMagnitude >= 3) {
603        budgets = new double[maxMagnitude - minMagnitude];
604        for (var i = minMagnitude; i < maxMagnitude; i++) {
605          budgets[i - minMagnitude] = Math.Pow(10, i);
606        }
607      } else {
608        var range = max - min;
609        budgets = Enumerable.Range(0, 6).Select(x => min + (x / 5.0) * range).ToArray();
610      }
611      suppressBudgetsEvents = true;
612      budgetsTextBox.Text = string.Join(" ; ", budgets);
613      suppressBudgetsEvents = false;
614    }
615
[13583]616    private void CalculateHitsForEachBudget(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, int groupCount, ProblemDescription problem, string groupName, int problemCount, double bestTarget) {
[12838]617      foreach (var b in budgets) {
618        var key = groupName + "-" + b;
619        if (!hits.ContainsKey(key)) hits.Add(key, new SortedList<double, double>());
620        Tuple<double, double> prev = null;
621        foreach (var v in row.Values) {
622          if (v.Item1 >= b) {
623            // the budget may be too low to achieve any target
624            if (prev == null && v.Item1 != b) break;
[12865]625            var tgt = ((prev == null || v.Item1 == b) ? v.Item2 : prev.Item2);
[13583]626            tgt = problem.IsMaximization() ? bestTarget / tgt : tgt / bestTarget;
[12838]627            if (hits[key].ContainsKey(tgt))
[12864]628              hits[key][tgt] += 1.0 / (groupCount * problemCount);
629            else hits[key][tgt] = 1.0 / (groupCount * problemCount);
[12838]630            break;
631          }
632          prev = v;
633        }
634        if (hits[key].Count == 0) hits.Remove(key);
635      }
636    }
637
[13583]638    private void CalculateHitsForAllBudgets(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, int groupCount, ProblemDescription problem, string groupName, int problemCount, double bestTarget) {
[12838]639      var values = row.Values;
640      if (!hits.ContainsKey(groupName)) hits.Add(groupName, new SortedList<double, double>());
641
642      var i = 0;
643      var j = 0;
644      Tuple<double, double> prev = null;
645      while (i < budgets.Length && j < values.Count) {
646        var current = values[j];
647        if (current.Item1 >= budgets[i]) {
648          if (prev != null || current.Item1 == budgets[i]) {
649            var tgt = (prev == null || current.Item1 == budgets[i]) ? current.Item2 : prev.Item2;
[13583]650            tgt = problem.IsMaximization() ? bestTarget / tgt : tgt / bestTarget;
[12838]651            if (!hits[groupName].ContainsKey(tgt)) hits[groupName][tgt] = 0;
[12864]652            hits[groupName][tgt] += 1.0 / (groupCount * problemCount * budgets.Length);
[12838]653          }
654          i++;
655        } else {
656          j++;
657          prev = current;
658        }
659      }
660      var lastTgt = values.Last().Item2;
[13583]661      lastTgt = problem.IsMaximization() ? bestTarget / lastTgt : lastTgt / bestTarget;
[12838]662      if (i < budgets.Length && !hits[groupName].ContainsKey(lastTgt)) hits[groupName][lastTgt] = 0;
663      while (i < budgets.Length) {
[12864]664        hits[groupName][lastTgt] += 1.0 / (groupCount * problemCount * budgets.Length);
[12838]665        i++;
666      }
667    }
668    #endregion
669
[8738]670    private void UpdateCaption() {
[12803]671      Caption = Content != null ? Content.OptimizerName + " RLD View" : ViewAttribute.GetViewName(GetType());
[8738]672    }
673
[12771]674    private void groupComboBox_SelectedIndexChanged(object sender, EventArgs e) {
675      UpdateRuns();
[12806]676      SetEnabledStateOfControls();
[7980]677    }
[12841]678    private void problemComboBox_SelectedIndexChanged(object sender, EventArgs e) {
679      UpdateRuns();
680      SetEnabledStateOfControls();
681    }
[12631]682    private void dataTableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
[12838]683      if (dataTableComboBox.SelectedIndex >= 0)
684        GenerateDefaultBudgets((string)dataTableComboBox.SelectedItem);
[12771]685      UpdateRuns();
[12806]686      SetEnabledStateOfControls();
[7980]687    }
[12771]688
689    private void logScalingCheckBox_CheckedChanged(object sender, EventArgs e) {
[12838]690      byTargetDataTable.VisualProperties.XAxisLogScale = byTargetDataTable.Rows.Count > 0 && targetLogScalingCheckBox.Checked;
691      byCostDataTable.VisualProperties.XAxisLogScale = byCostDataTable.Rows.Count > 0 && budgetLogScalingCheckBox.Checked;
[7980]692    }
[12804]693
[12838]694    #region Event handlers for target analysis
[12804]695    private bool suppressTargetsEvents;
696    private void targetsTextBox_Validating(object sender, CancelEventArgs e) {
697      if (suppressTargetsEvents) return;
[12864]698      var targetStrings = targetsTextBox.Text.Split(new[] { '%', ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
699      var targetList = new List<decimal>();
[12804]700      foreach (var ts in targetStrings) {
[12864]701        decimal t;
702        if (!decimal.TryParse(ts, out t)) {
[12804]703          errorProvider.SetError(targetsTextBox, "Not all targets can be parsed: " + ts);
704          e.Cancel = true;
705          return;
706        }
[12864]707        targetList.Add(t / 100);
[12804]708      }
709      if (targetList.Count == 0) {
710        errorProvider.SetError(targetsTextBox, "Give at least one target value!");
711        e.Cancel = true;
712        return;
713      }
714      e.Cancel = false;
715      errorProvider.SetError(targetsTextBox, null);
[12888]716      targets = targetList.Select(x => (double)x).OrderByDescending(x => x).ToArray();
717      suppressTargetsEvents = true;
718      try { targetsTextBox.Text = string.Join("% ; ", targets.Select(x => x * 100)) + "%"; } finally { suppressTargetsEvents = false; }
719
[12838]720      UpdateResultsByTarget();
[12806]721      SetEnabledStateOfControls();
[12804]722    }
[12806]723
[12838]724    private void eachOrAllTargetCheckBox_CheckedChanged(object sender, EventArgs e) {
725      var each = eachOrAllTargetCheckBox.Checked;
726      eachOrAllTargetCheckBox.Text = each ? "each" : "all";
727      SuspendRepaint();
728      try {
729        UpdateResultsByTarget();
730      } finally { ResumeRepaint(true); }
731    }
732
[12806]733    private void generateTargetsButton_Click(object sender, EventArgs e) {
734      decimal max = 1, min = 0, count = 10;
[12838]735      if (targets != null) {
736        max = (decimal)targets.Max();
737        min = (decimal)targets.Min();
738        count = targets.Length;
[12806]739      } else if (Content.Count > 0 && dataTableComboBox.SelectedIndex >= 0) {
740        var table = (string)dataTableComboBox.SelectedItem;
[12838]741        max = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Max(y => y.Item2)).Max();
742        min = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Min(y => y.Item2)).Min();
743        count = 6;
[12806]744      }
745      using (var dialog = new DefineArithmeticProgressionDialog(false, min, max, (max - min) / count)) {
746        if (dialog.ShowDialog() == DialogResult.OK) {
747          if (dialog.Values.Any()) {
[13583]748            targets = dialog.Values.Select(x => (double)x).ToArray();
[12808]749            suppressTargetsEvents = true;
[12864]750            targetsTextBox.Text = string.Join("% ; ", targets);
[12808]751            suppressTargetsEvents = false;
752
[12838]753            UpdateResultsByTarget();
[12806]754            SetEnabledStateOfControls();
755          }
756        }
757      }
758    }
759
[12838]760    private void addTargetsAsResultButton_Click(object sender, EventArgs e) {
[12806]761      var table = (string)dataTableComboBox.SelectedItem;
[12864]762
[13583]763      var targetsPerProblem = CalculateBestTargetPerProblemInstance(table);
[12864]764
[12806]765      foreach (var run in Content) {
[12808]766        if (!run.Results.ContainsKey(table)) continue;
[12806]767        var resultsTable = (IndexedDataTable<double>)run.Results[table];
768        var values = resultsTable.Rows.First().Values;
769        var i = 0;
770        var j = 0;
[12864]771        var pd = new ProblemDescription(run);
[12838]772        while (i < targets.Length && j < values.Count) {
[13583]773          var target = (pd.IsMaximization() ? (1 - targets[i]) : (1 + targets[i])) * targetsPerProblem[pd];
[12838]774          var current = values[j];
[13583]775          if (pd.IsMaximization() && current.Item2 >= target
776              || !pd.IsMaximization() && current.Item2 <= target) {
[12864]777            run.Results[table + ".Target" + target] = new DoubleValue(current.Item1);
[12806]778            i++;
779          } else {
780            j++;
781          }
782        }
783      }
784    }
[12838]785    #endregion
[12806]786
[12838]787    #region Event handlers for cost analysis
788    private bool suppressBudgetsEvents;
789    private void budgetsTextBox_Validating(object sender, CancelEventArgs e) {
790      if (suppressBudgetsEvents) return;
791      var budgetStrings = budgetsTextBox.Text.Split(new[] { ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
792      var budgetList = new List<double>();
793      foreach (var ts in budgetStrings) {
794        double b;
795        if (!double.TryParse(ts, out b)) {
796          errorProvider.SetError(budgetsTextBox, "Not all targets can be parsed: " + ts);
797          e.Cancel = true;
798          return;
799        }
800        budgetList.Add(b);
801      }
802      if (budgetList.Count == 0) {
803        errorProvider.SetError(budgetsTextBox, "Give at least one target value!");
804        e.Cancel = true;
805        return;
806      }
807      e.Cancel = false;
808      errorProvider.SetError(budgetsTextBox, null);
809      budgets = budgetList.ToArray();
810      UpdateResultsByCost();
811      SetEnabledStateOfControls();
812    }
813
814    private void eachOrAllBudgetsCheckBox_CheckedChanged(object sender, EventArgs e) {
815      var each = eachOrAllBudgetsCheckBox.Checked;
816      eachOrAllBudgetsCheckBox.Text = each ? "each" : "all";
817      SuspendRepaint();
818      try {
819        UpdateResultsByCost();
820      } finally { ResumeRepaint(true); }
821    }
822
823    private void generateBudgetsButton_Click(object sender, EventArgs e) {
824      decimal max = 1, min = 0, count = 10;
825      if (budgets != null) {
826        max = (decimal)budgets.Max();
827        min = (decimal)budgets.Min();
828        count = budgets.Length;
829      } else if (Content.Count > 0 && dataTableComboBox.SelectedIndex >= 0) {
830        var table = (string)dataTableComboBox.SelectedItem;
831        min = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Min(y => y.Item1)).Min();
832        max = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Max(y => y.Item1)).Max();
833        count = 6;
834      }
835      using (var dialog = new DefineArithmeticProgressionDialog(false, min, max, (max - min) / count)) {
836        if (dialog.ShowDialog() == DialogResult.OK) {
837          if (dialog.Values.Any()) {
838            budgets = dialog.Values.OrderBy(x => x).Select(x => (double)x).ToArray();
839
840            suppressBudgetsEvents = true;
841            budgetsTextBox.Text = string.Join(" ; ", budgets);
842            suppressBudgetsEvents = false;
843
844            UpdateResultsByCost();
845            SetEnabledStateOfControls();
846          }
847        }
848      }
849    }
850
851    private void addBudgetsAsResultButton_Click(object sender, EventArgs e) {
[12806]852      var table = (string)dataTableComboBox.SelectedItem;
853      var budgetStrings = budgetsTextBox.Text.Split(new[] { ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
854      if (budgetStrings.Length == 0) {
855        MessageBox.Show("Define a number of budgets.");
856        return;
857      }
858      var budgetList = new List<double>();
859      foreach (var bs in budgetStrings) {
860        double v;
861        if (!double.TryParse(bs, out v)) {
862          MessageBox.Show("Budgets must be a valid number: " + bs);
863          return;
864        }
865        budgetList.Add(v);
866      }
867      budgetList.Sort();
868
869      foreach (var run in Content) {
[12808]870        if (!run.Results.ContainsKey(table)) continue;
[12806]871        var resultsTable = (IndexedDataTable<double>)run.Results[table];
872        var values = resultsTable.Rows.First().Values;
873        var i = 0;
874        var j = 0;
[12838]875        Tuple<double, double> prev = null;
876        while (i < budgetList.Count && j < values.Count) {
877          var current = values[j];
878          if (current.Item1 >= budgetList[i]) {
879            if (prev != null || current.Item1 == budgetList[i]) {
880              var tgt = (prev == null || current.Item1 == budgetList[i]) ? current.Item2 : prev.Item2;
881              run.Results[table + ".Cost" + budgetList[i]] = new DoubleValue(tgt);
882            }
[12806]883            i++;
884          } else {
885            j++;
886            prev = current;
887          }
888        }
889      }
890    }
[12838]891    #endregion
[12808]892
[12838]893    #region Helpers
[13583]894    private Dictionary<ProblemDescription, double> CalculateBestTargetPerProblemInstance(string table) {
[12888]895      return (from r in Content
896              where r.Visible
[13583]897              let pd = new ProblemDescription(r)
[12888]898              let target = r.Parameters.ContainsKey("BestKnownQuality")
899                           && r.Parameters["BestKnownQuality"] is DoubleValue
900                ? ((DoubleValue)r.Parameters["BestKnownQuality"]).Value
901                : ((IndexedDataTable<double>)r.Results[table]).Rows.First().Values.Last().Item2
902              group target by pd into g
[13583]903              select new { Problem = g.Key, Target = g.Key.IsMaximization() ? g.Max() : g.Min() })
[12888]904        .ToDictionary(x => x.Problem, x => x.Target);
905    }
906
907    private void UpdateRuns() {
908      if (InvokeRequired) {
909        Invoke((Action)UpdateRuns);
910        return;
911      }
912      SuspendRepaint();
913      try {
914        UpdateResultsByTarget();
915        UpdateResultsByCost();
916      } finally { ResumeRepaint(true); }
917    }
[12838]918    #endregion
[12841]919
920
921    private class ProblemDescription {
922      private readonly bool matchAll;
[12864]923      public static readonly ProblemDescription MatchAll = new ProblemDescription() {
924        ProblemName = "All with Best-Known"
925      };
[12841]926
927      private ProblemDescription() {
928        ProblemType = string.Empty;
929        ProblemName = string.Empty;
930        Evaluator = string.Empty;
[13583]931        Maximization = string.Empty;
[12841]932        DisplayProblemType = false;
933        DisplayProblemName = false;
934        DisplayEvaluator = false;
[13583]935        DisplayMaximization = false;
[12841]936        matchAll = true;
937      }
938
939      public ProblemDescription(IRun run) {
940        ProblemType = GetStringValueOrEmpty(run, "Problem Type");
941        ProblemName = GetStringValueOrEmpty(run, "Problem Name");
942        Evaluator = GetStringValueOrEmpty(run, "Evaluator");
[13583]943        Maximization = GetMaximizationValueOrEmpty(run, "Maximization");
[12841]944        DisplayProblemType = !string.IsNullOrEmpty(ProblemType);
945        DisplayProblemName = !string.IsNullOrEmpty(ProblemName);
946        DisplayEvaluator = !string.IsNullOrEmpty(Evaluator);
[13583]947        DisplayMaximization = !string.IsNullOrEmpty(Maximization);
[12841]948        matchAll = false;
949      }
950
951      public bool DisplayProblemType { get; set; }
952      public string ProblemType { get; set; }
953      public bool DisplayProblemName { get; set; }
954      public string ProblemName { get; set; }
955      public bool DisplayEvaluator { get; set; }
956      public string Evaluator { get; set; }
[13583]957      public bool DisplayMaximization { get; set; }
958      public string Maximization { get; set; }
[12841]959
[13583]960      public bool IsMaximization() {
961        return Maximization == "MAX";
962      }
963
[12841]964      public bool Match(IRun run) {
965        return matchAll ||
966               GetStringValueOrEmpty(run, "Problem Type") == ProblemType
967               && GetStringValueOrEmpty(run, "Problem Name") == ProblemName
[13583]968               && GetStringValueOrEmpty(run, "Evaluator") == Evaluator
969               && GetMaximizationValueOrEmpty(run, "Maximization") == Maximization;
[12841]970      }
971
972      private string GetStringValueOrEmpty(IRun run, string key) {
973        return run.Parameters.ContainsKey(key) ? ((StringValue)run.Parameters[key]).Value : string.Empty;
974      }
975
[13583]976      private string GetMaximizationValueOrEmpty(IRun run, string key) {
977        return run.Parameters.ContainsKey(key) ? (((BoolValue)run.Parameters[key]).Value ? "MAX" : "MIN") : string.Empty;
978      }
979
[12841]980      public override bool Equals(object obj) {
981        var other = obj as ProblemDescription;
982        if (other == null) return false;
983        return ProblemType == other.ProblemType
984               && ProblemName == other.ProblemName
[13583]985               && Evaluator == other.Evaluator
986               && Maximization == other.Maximization;
[12841]987      }
988
989      public override int GetHashCode() {
[13583]990        return ProblemType.GetHashCode() ^ ProblemName.GetHashCode() ^ Evaluator.GetHashCode() ^ Maximization.GetHashCode();
[12841]991      }
992
993      public override string ToString() {
994        return string.Join("  --  ", new[] {
995          (DisplayProblemType ? ProblemType : string.Empty),
996          (DisplayProblemName ? ProblemName : string.Empty),
[13583]997          (DisplayEvaluator ? Evaluator : string.Empty),
998          (DisplayMaximization ? Maximization : string.Empty)}.Where(x => !string.IsNullOrEmpty(x)));
[12841]999      }
1000    }
[7980]1001  }
1002}
Note: See TracBrowser for help on using the repository browser.