Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2457: added line annotations to the network visu to highlight close solutions

File size: 41.1 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
326      foreach (var group in groupedRuns) {
[13736]327        // hits describes the number of target hits at a certain time for a certain group
328        var hits = new Dictionary<string, SortedList<double, int>>();
329        // misses describes the number of target misses after a certain time for a certain group
330        // for instance when a run ends, but has not achieved all targets, misses describes
331        // how many targets have been left open at the point when the run ended
332        var misses = new Dictionary<string, SortedList<double, int>>();
[12838]333        var maxLength = 0.0;
334
[13736]335        var noRuns = 0;
[12864]336        foreach (var problem in group.Value) {
337          foreach (var run in problem.Value.Item2) {
338            var resultsTable = (IndexedDataTable<double>)run.Results[table];
339            xAxisTitles.Add(resultsTable.VisualProperties.XAxisTitle);
[12838]340
[12864]341            if (eachOrAllTargetCheckBox.Checked) {
[13736]342              CalculateHitsForEachTarget(hits, misses, resultsTable.Rows.First(), problem.Key, group.Key, problem.Value.Item1);
343              // achiving each target can be seen as a separate run for that target only
344              noRuns += targets.Length;
[12864]345            } else {
[13736]346              var length = CalculateHitsForAllTargets(hits, misses, resultsTable.Rows.First(), problem.Key, group.Key, problem.Value.Item1);
347              maxLength = Math.Max(length, maxLength);
348              noRuns++;
[12864]349            }
[12838]350          }
351        }
352
353        foreach (var list in hits) {
354          var row = new IndexedDataRow<double>(list.Key) {
355            VisualProperties = {
356              ChartType = DataRowVisualProperties.DataRowChartType.StepLine,
357              LineWidth = 2,
358              Color = colors[colorCount],
[13745]359              LineStyle = lineStyles[lineStyleCount],
360              StartIndexZero = false
[12838]361            }
362          };
363
[13736]364          var ecdf = 0.0;
365          var iter = misses[list.Key].GetEnumerator();
366          iter.MoveNext();
367          var sumTargets = noRuns * targets.Length;
[12838]368          foreach (var h in list.Value) {
[13736]369            ecdf += h.Value;
370            while (iter.Current.Key < h.Key) {
371              sumTargets -= iter.Current.Value;
372              if (!iter.MoveNext()) break;
373            }
374            row.Values.Add(Tuple.Create(h.Key, ecdf / sumTargets));
[12838]375          }
376
377          if (maxLength > 0 && (row.Values.Count == 0 || row.Values.Last().Item1 < maxLength))
[13736]378            row.Values.Add(Tuple.Create(maxLength, ecdf / sumTargets));
[12838]379
380          byTargetDataTable.Rows.Add(row);
381        }
382        colorCount = (colorCount + 1) % colors.Length;
383        if (colorCount == 0) lineStyleCount = (lineStyleCount + 1) % lineStyles.Length;
384      }
385
[12888]386      if (targets.Length == 1)
387        ByTargetDataTable.VisualProperties.YAxisTitle = "Probability to be " + (targets[0] * 100) + "% worse than best";
388      else ByTargetDataTable.VisualProperties.YAxisTitle = "Proportion of reached targets";
[12838]389      byTargetDataTable.VisualProperties.XAxisTitle = string.Join(" / ", xAxisTitles);
390      byTargetDataTable.VisualProperties.XAxisLogScale = byTargetDataTable.Rows.Count > 0 && targetLogScalingCheckBox.Checked;
[12841]391
392      UpdateErtTables(groupedRuns);
[12838]393    }
394
[12864]395    private void GenerateDefaultTargets() {
396      targets = new[] { 0.1, 0.05, 0.02, 0.01, 0 };
[12838]397      suppressTargetsEvents = true;
[12888]398      targetsTextBox.Text = string.Join("% ; ", targets.Select(x => x * 100)) + "%";
[12838]399      suppressTargetsEvents = false;
400    }
401
[13736]402    private void CalculateHitsForEachTarget(Dictionary<string, SortedList<double, int>> hits,
403                                            Dictionary<string, SortedList<double, int>> misses,
404                                            IndexedDataRow<double> row, ProblemDescription problem,
405                                            string group, double bestTarget) {
[13583]406      foreach (var l in targets.Select(x => (problem.IsMaximization() ? (1 - x) : (1 + x)) * bestTarget)) {
[12864]407        var key = group + "-" + l;
[13736]408        if (!hits.ContainsKey(key)) {
409          hits.Add(key, new SortedList<double, int>());
410          misses.Add(key, new SortedList<double, int>());
411        }
412        var hit = false;
[12838]413        foreach (var v in row.Values) {
[13583]414          if (problem.IsMaximization() && v.Item2 >= l || !problem.IsMaximization() && v.Item2 <= l) {
[12838]415            if (hits[key].ContainsKey(v.Item1))
[13736]416              hits[key][v.Item1]++;
417            else hits[key][v.Item1] = 1;
418            hit = true;
[12838]419            break;
420          }
421        }
[13736]422        if (!hit) {
423          var max = row.Values.Last();
424          if (misses[key].ContainsKey(max.Item1))
425            misses[key][max.Item1]++;
426          else misses[key][max.Item1] = 1;
427        }
[12838]428      }
429    }
430
[13736]431    private double CalculateHitsForAllTargets(Dictionary<string, SortedList<double, int>> hits,
432                                              Dictionary<string, SortedList<double, int>> misses,
433                                              IndexedDataRow<double> row, ProblemDescription problem,
434                                              string group, double bestTarget) {
[12838]435      var values = row.Values;
[13736]436      if (!hits.ContainsKey(group)) {
437        hits.Add(group, new SortedList<double, int>());
438        misses.Add(group, new SortedList<double, int>());
439      }
[12838]440
441      var i = 0;
442      var j = 0;
443      while (i < targets.Length && j < values.Count) {
[13583]444        var target = (problem.IsMaximization() ? (1 - targets[i]) : (1 + targets[i])) * bestTarget;
[12838]445        var current = values[j];
[13583]446        if (problem.IsMaximization() && current.Item2 >= target
447          || !problem.IsMaximization() && current.Item2 <= target) {
[13736]448          if (hits[group].ContainsKey(current.Item1)) hits[group][current.Item1]++;
449          else hits[group][current.Item1] = 1;
[12838]450          i++;
451        } else {
452          j++;
453        }
454      }
455      if (j == values.Count) j--;
[13736]456      if (i < targets.Length) {
457        if (misses[group].ContainsKey(values[j].Item1))
458          misses[group][values[j].Item1] += targets.Length - i;
459        else misses[group][values[j].Item1] = targets.Length - i;
460      }
[12838]461      return values[j].Item1;
462    }
[12841]463
[13583]464    private void UpdateErtTables(Dictionary<string, Dictionary<ProblemDescription, Tuple<double, List<IRun>>>> groupedRuns) {
[12888]465      ertTableView.Content = null;
[12841]466      var columns = 1 + targets.Length + 1;
[12864]467      var matrix = new string[groupedRuns.Count * groupedRuns.Max(x => x.Value.Count) + groupedRuns.Max(x => x.Value.Count), columns];
[12841]468      var rowCount = 0;
469
[12956]470      var tableName = (string)dataTableComboBox.SelectedItem;
471      if (string.IsNullOrEmpty(tableName)) return;
[12864]472
[13583]473      var targetsPerProblem = CalculateBestTargetPerProblemInstance(tableName);
[12956]474
[12841]475      var colNames = new string[columns];
476      colNames[0] = colNames[colNames.Length - 1] = string.Empty;
477      for (var i = 0; i < targets.Length; i++) {
[12864]478        colNames[i + 1] = targets[i].ToString("0.0%");
[12841]479      }
[12864]480      var problems = groupedRuns.SelectMany(x => x.Value.Keys).Distinct().ToList();
[12841]481
[12864]482      foreach (var problem in problems) {
[13583]483        matrix[rowCount, 0] = problem.ToString();
[12841]484        for (var i = 0; i < targets.Length; i++) {
[13583]485          matrix[rowCount, i + 1] = (targetsPerProblem[problem] * (problem.IsMaximization() ? (1 - targets[i]) : (1 + targets[i]))).ToString(CultureInfo.CurrentCulture.NumberFormat);
[12841]486        }
[12864]487        matrix[rowCount, columns - 1] = "#succ";
[12841]488        rowCount++;
[12864]489
490        foreach (var group in groupedRuns) {
491          matrix[rowCount, 0] = group.Key;
[12939]492          if (!group.Value.ContainsKey(problem)) {
493            matrix[rowCount, columns - 1] = "N/A";
494            rowCount++;
495            continue;
496          }
[12864]497          var runs = group.Value[problem].Item2;
[12956]498          ErtCalculationResult result = default(ErtCalculationResult);
[12864]499          for (var i = 0; i < targets.Length; i++) {
[13583]500            result = ExpectedRuntimeHelper.CalculateErt(runs, tableName, (problem.IsMaximization() ? (1 - targets[i]) : (1 + targets[i])) * group.Value[problem].Item1, problem.IsMaximization());
[12956]501            matrix[rowCount, i + 1] = result.ToString();
[12864]502          }
[12956]503          matrix[rowCount, columns - 1] = targets.Length > 0 ? result.SuccessfulRuns + "/" + result.TotalRuns : "-";
[12864]504          rowCount++;
505        }
[12841]506      }
[12888]507      ertTableView.Content = new StringMatrix(matrix) { ColumnNames = colNames };
508      ertTableView.DataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
[12841]509    }
[12838]510    #endregion
511
512    #region Performance analysis by (multiple) budget(s)
513    private void UpdateResultsByCost() {
514      // necessary to reset log scale -> empty chart cannot use log scaling
515      byCostDataTable.VisualProperties.XAxisLogScale = false;
516      byCostDataTable.Rows.Clear();
517
518      var table = (string)dataTableComboBox.SelectedItem;
519      if (string.IsNullOrEmpty(table)) return;
520
521      if (budgets == null) GenerateDefaultBudgets(table);
522
[12841]523      var groupedRuns = GroupRuns();
524      if (groupedRuns.Count == 0) return;
[12838]525
526      var colorCount = 0;
527      var lineStyleCount = 0;
528
[13583]529      var targetsPerProblem = CalculateBestTargetPerProblemInstance((string)dataTableComboBox.SelectedItem);
[12865]530
[12838]531      foreach (var group in groupedRuns) {
532        var hits = new Dictionary<string, SortedList<double, double>>();
533
[12864]534        foreach (var problem in group.Value) {
535          foreach (var run in problem.Value.Item2) {
536            var resultsTable = (IndexedDataTable<double>)run.Results[table];
[12838]537
[12864]538            if (eachOrAllBudgetsCheckBox.Checked) {
[13583]539              CalculateHitsForEachBudget(hits, resultsTable.Rows.First(), group.Value.Count, problem.Key, group.Key, problem.Value.Item2.Count, targetsPerProblem[problem.Key]);
[12864]540            } else {
[13583]541              CalculateHitsForAllBudgets(hits, resultsTable.Rows.First(), group.Value.Count, problem.Key, group.Key, problem.Value.Item2.Count, targetsPerProblem[problem.Key]);
[12864]542            }
[12838]543          }
544        }
545
546        foreach (var list in hits) {
547          var row = new IndexedDataRow<double>(list.Key) {
548            VisualProperties = {
549              ChartType = DataRowVisualProperties.DataRowChartType.StepLine,
550              LineWidth = 2,
551              Color = colors[colorCount],
[13745]552              LineStyle = lineStyles[lineStyleCount],
553              StartIndexZero = false
[12838]554            }
555          };
556
557          var total = 0.0;
558          foreach (var h in list.Value) {
559            total += h.Value;
560            row.Values.Add(Tuple.Create(h.Key, total));
561          }
562
563          byCostDataTable.Rows.Add(row);
564        }
565        colorCount = (colorCount + 1) % colors.Length;
566        if (colorCount == 0) lineStyleCount = (lineStyleCount + 1) % lineStyles.Length;
567      }
568
[12865]569      byCostDataTable.VisualProperties.XAxisTitle = "Targets to Best-Known Ratio";
[12838]570      byCostDataTable.VisualProperties.XAxisLogScale = byCostDataTable.Rows.Count > 0 && budgetLogScalingCheckBox.Checked;
571    }
572
573    private void GenerateDefaultBudgets(string table) {
[12864]574      var runs = GroupRuns().SelectMany(x => x.Value.Values).SelectMany(x => x.Item2).ToList();
[12841]575      var min = runs.Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Select(y => y.Item1).Min()).Min();
576      var max = runs.Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Select(y => y.Item1).Max()).Max();
[12838]577
578      var maxMagnitude = (int)Math.Ceiling(Math.Log10(max));
579      var minMagnitude = (int)Math.Floor(Math.Log10(min));
580      if (maxMagnitude - minMagnitude >= 3) {
581        budgets = new double[maxMagnitude - minMagnitude];
582        for (var i = minMagnitude; i < maxMagnitude; i++) {
583          budgets[i - minMagnitude] = Math.Pow(10, i);
584        }
585      } else {
586        var range = max - min;
587        budgets = Enumerable.Range(0, 6).Select(x => min + (x / 5.0) * range).ToArray();
588      }
589      suppressBudgetsEvents = true;
590      budgetsTextBox.Text = string.Join(" ; ", budgets);
591      suppressBudgetsEvents = false;
592    }
593
[13583]594    private void CalculateHitsForEachBudget(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, int groupCount, ProblemDescription problem, string groupName, int problemCount, double bestTarget) {
[12838]595      foreach (var b in budgets) {
596        var key = groupName + "-" + b;
597        if (!hits.ContainsKey(key)) hits.Add(key, new SortedList<double, double>());
598        Tuple<double, double> prev = null;
599        foreach (var v in row.Values) {
600          if (v.Item1 >= b) {
601            // the budget may be too low to achieve any target
602            if (prev == null && v.Item1 != b) break;
[12865]603            var tgt = ((prev == null || v.Item1 == b) ? v.Item2 : prev.Item2);
[13583]604            tgt = problem.IsMaximization() ? bestTarget / tgt : tgt / bestTarget;
[12838]605            if (hits[key].ContainsKey(tgt))
[12864]606              hits[key][tgt] += 1.0 / (groupCount * problemCount);
607            else hits[key][tgt] = 1.0 / (groupCount * problemCount);
[12838]608            break;
609          }
610          prev = v;
611        }
612        if (hits[key].Count == 0) hits.Remove(key);
613      }
614    }
615
[13583]616    private void CalculateHitsForAllBudgets(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, int groupCount, ProblemDescription problem, string groupName, int problemCount, double bestTarget) {
[12838]617      var values = row.Values;
618      if (!hits.ContainsKey(groupName)) hits.Add(groupName, new SortedList<double, double>());
619
620      var i = 0;
621      var j = 0;
622      Tuple<double, double> prev = null;
623      while (i < budgets.Length && j < values.Count) {
624        var current = values[j];
625        if (current.Item1 >= budgets[i]) {
626          if (prev != null || current.Item1 == budgets[i]) {
627            var tgt = (prev == null || current.Item1 == budgets[i]) ? current.Item2 : prev.Item2;
[13583]628            tgt = problem.IsMaximization() ? bestTarget / tgt : tgt / bestTarget;
[12838]629            if (!hits[groupName].ContainsKey(tgt)) hits[groupName][tgt] = 0;
[12864]630            hits[groupName][tgt] += 1.0 / (groupCount * problemCount * budgets.Length);
[12838]631          }
632          i++;
633        } else {
634          j++;
635          prev = current;
636        }
637      }
638      var lastTgt = values.Last().Item2;
[13583]639      lastTgt = problem.IsMaximization() ? bestTarget / lastTgt : lastTgt / bestTarget;
[12838]640      if (i < budgets.Length && !hits[groupName].ContainsKey(lastTgt)) hits[groupName][lastTgt] = 0;
641      while (i < budgets.Length) {
[12864]642        hits[groupName][lastTgt] += 1.0 / (groupCount * problemCount * budgets.Length);
[12838]643        i++;
644      }
645    }
646    #endregion
647
[8738]648    private void UpdateCaption() {
[12803]649      Caption = Content != null ? Content.OptimizerName + " RLD View" : ViewAttribute.GetViewName(GetType());
[8738]650    }
651
[12771]652    private void groupComboBox_SelectedIndexChanged(object sender, EventArgs e) {
653      UpdateRuns();
[12806]654      SetEnabledStateOfControls();
[7980]655    }
[12841]656    private void problemComboBox_SelectedIndexChanged(object sender, EventArgs e) {
657      UpdateRuns();
658      SetEnabledStateOfControls();
659    }
[12631]660    private void dataTableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
[12838]661      if (dataTableComboBox.SelectedIndex >= 0)
662        GenerateDefaultBudgets((string)dataTableComboBox.SelectedItem);
[12771]663      UpdateRuns();
[12806]664      SetEnabledStateOfControls();
[7980]665    }
[12771]666
667    private void logScalingCheckBox_CheckedChanged(object sender, EventArgs e) {
[12838]668      byTargetDataTable.VisualProperties.XAxisLogScale = byTargetDataTable.Rows.Count > 0 && targetLogScalingCheckBox.Checked;
669      byCostDataTable.VisualProperties.XAxisLogScale = byCostDataTable.Rows.Count > 0 && budgetLogScalingCheckBox.Checked;
[7980]670    }
[12804]671
[12838]672    #region Event handlers for target analysis
[12804]673    private bool suppressTargetsEvents;
674    private void targetsTextBox_Validating(object sender, CancelEventArgs e) {
675      if (suppressTargetsEvents) return;
[12864]676      var targetStrings = targetsTextBox.Text.Split(new[] { '%', ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
677      var targetList = new List<decimal>();
[12804]678      foreach (var ts in targetStrings) {
[12864]679        decimal t;
680        if (!decimal.TryParse(ts, out t)) {
[12804]681          errorProvider.SetError(targetsTextBox, "Not all targets can be parsed: " + ts);
682          e.Cancel = true;
683          return;
684        }
[12864]685        targetList.Add(t / 100);
[12804]686      }
687      if (targetList.Count == 0) {
688        errorProvider.SetError(targetsTextBox, "Give at least one target value!");
689        e.Cancel = true;
690        return;
691      }
692      e.Cancel = false;
693      errorProvider.SetError(targetsTextBox, null);
[12888]694      targets = targetList.Select(x => (double)x).OrderByDescending(x => x).ToArray();
695      suppressTargetsEvents = true;
696      try { targetsTextBox.Text = string.Join("% ; ", targets.Select(x => x * 100)) + "%"; } finally { suppressTargetsEvents = false; }
697
[12838]698      UpdateResultsByTarget();
[12806]699      SetEnabledStateOfControls();
[12804]700    }
[12806]701
[12838]702    private void eachOrAllTargetCheckBox_CheckedChanged(object sender, EventArgs e) {
703      var each = eachOrAllTargetCheckBox.Checked;
704      eachOrAllTargetCheckBox.Text = each ? "each" : "all";
705      SuspendRepaint();
706      try {
707        UpdateResultsByTarget();
708      } finally { ResumeRepaint(true); }
709    }
710
[12806]711    private void generateTargetsButton_Click(object sender, EventArgs e) {
712      decimal max = 1, min = 0, count = 10;
[12838]713      if (targets != null) {
714        max = (decimal)targets.Max();
715        min = (decimal)targets.Min();
716        count = targets.Length;
[12806]717      } else if (Content.Count > 0 && dataTableComboBox.SelectedIndex >= 0) {
718        var table = (string)dataTableComboBox.SelectedItem;
[12838]719        max = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Max(y => y.Item2)).Max();
720        min = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Min(y => y.Item2)).Min();
721        count = 6;
[12806]722      }
723      using (var dialog = new DefineArithmeticProgressionDialog(false, min, max, (max - min) / count)) {
724        if (dialog.ShowDialog() == DialogResult.OK) {
725          if (dialog.Values.Any()) {
[13583]726            targets = dialog.Values.Select(x => (double)x).ToArray();
[12808]727            suppressTargetsEvents = true;
[12864]728            targetsTextBox.Text = string.Join("% ; ", targets);
[12808]729            suppressTargetsEvents = false;
730
[12838]731            UpdateResultsByTarget();
[12806]732            SetEnabledStateOfControls();
733          }
734        }
735      }
736    }
737
[12838]738    private void addTargetsAsResultButton_Click(object sender, EventArgs e) {
[12806]739      var table = (string)dataTableComboBox.SelectedItem;
[12864]740
[13583]741      var targetsPerProblem = CalculateBestTargetPerProblemInstance(table);
[12864]742
[12806]743      foreach (var run in Content) {
[12808]744        if (!run.Results.ContainsKey(table)) continue;
[12806]745        var resultsTable = (IndexedDataTable<double>)run.Results[table];
746        var values = resultsTable.Rows.First().Values;
747        var i = 0;
748        var j = 0;
[12864]749        var pd = new ProblemDescription(run);
[12838]750        while (i < targets.Length && j < values.Count) {
[13583]751          var target = (pd.IsMaximization() ? (1 - targets[i]) : (1 + targets[i])) * targetsPerProblem[pd];
[12838]752          var current = values[j];
[13583]753          if (pd.IsMaximization() && current.Item2 >= target
754              || !pd.IsMaximization() && current.Item2 <= target) {
[12864]755            run.Results[table + ".Target" + target] = new DoubleValue(current.Item1);
[12806]756            i++;
757          } else {
758            j++;
759          }
760        }
761      }
762    }
[12838]763    #endregion
[12806]764
[12838]765    #region Event handlers for cost analysis
766    private bool suppressBudgetsEvents;
767    private void budgetsTextBox_Validating(object sender, CancelEventArgs e) {
768      if (suppressBudgetsEvents) return;
769      var budgetStrings = budgetsTextBox.Text.Split(new[] { ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
770      var budgetList = new List<double>();
771      foreach (var ts in budgetStrings) {
772        double b;
773        if (!double.TryParse(ts, out b)) {
774          errorProvider.SetError(budgetsTextBox, "Not all targets can be parsed: " + ts);
775          e.Cancel = true;
776          return;
777        }
778        budgetList.Add(b);
779      }
780      if (budgetList.Count == 0) {
781        errorProvider.SetError(budgetsTextBox, "Give at least one target value!");
782        e.Cancel = true;
783        return;
784      }
785      e.Cancel = false;
786      errorProvider.SetError(budgetsTextBox, null);
787      budgets = budgetList.ToArray();
788      UpdateResultsByCost();
789      SetEnabledStateOfControls();
790    }
791
792    private void eachOrAllBudgetsCheckBox_CheckedChanged(object sender, EventArgs e) {
793      var each = eachOrAllBudgetsCheckBox.Checked;
794      eachOrAllBudgetsCheckBox.Text = each ? "each" : "all";
795      SuspendRepaint();
796      try {
797        UpdateResultsByCost();
798      } finally { ResumeRepaint(true); }
799    }
800
801    private void generateBudgetsButton_Click(object sender, EventArgs e) {
802      decimal max = 1, min = 0, count = 10;
803      if (budgets != null) {
804        max = (decimal)budgets.Max();
805        min = (decimal)budgets.Min();
806        count = budgets.Length;
807      } else if (Content.Count > 0 && dataTableComboBox.SelectedIndex >= 0) {
808        var table = (string)dataTableComboBox.SelectedItem;
809        min = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Min(y => y.Item1)).Min();
810        max = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Max(y => y.Item1)).Max();
811        count = 6;
812      }
813      using (var dialog = new DefineArithmeticProgressionDialog(false, min, max, (max - min) / count)) {
814        if (dialog.ShowDialog() == DialogResult.OK) {
815          if (dialog.Values.Any()) {
816            budgets = dialog.Values.OrderBy(x => x).Select(x => (double)x).ToArray();
817
818            suppressBudgetsEvents = true;
819            budgetsTextBox.Text = string.Join(" ; ", budgets);
820            suppressBudgetsEvents = false;
821
822            UpdateResultsByCost();
823            SetEnabledStateOfControls();
824          }
825        }
826      }
827    }
828
829    private void addBudgetsAsResultButton_Click(object sender, EventArgs e) {
[12806]830      var table = (string)dataTableComboBox.SelectedItem;
831      var budgetStrings = budgetsTextBox.Text.Split(new[] { ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
832      if (budgetStrings.Length == 0) {
833        MessageBox.Show("Define a number of budgets.");
834        return;
835      }
836      var budgetList = new List<double>();
837      foreach (var bs in budgetStrings) {
838        double v;
839        if (!double.TryParse(bs, out v)) {
840          MessageBox.Show("Budgets must be a valid number: " + bs);
841          return;
842        }
843        budgetList.Add(v);
844      }
845      budgetList.Sort();
846
847      foreach (var run in Content) {
[12808]848        if (!run.Results.ContainsKey(table)) continue;
[12806]849        var resultsTable = (IndexedDataTable<double>)run.Results[table];
850        var values = resultsTable.Rows.First().Values;
851        var i = 0;
852        var j = 0;
[12838]853        Tuple<double, double> prev = null;
854        while (i < budgetList.Count && j < values.Count) {
855          var current = values[j];
856          if (current.Item1 >= budgetList[i]) {
857            if (prev != null || current.Item1 == budgetList[i]) {
858              var tgt = (prev == null || current.Item1 == budgetList[i]) ? current.Item2 : prev.Item2;
859              run.Results[table + ".Cost" + budgetList[i]] = new DoubleValue(tgt);
860            }
[12806]861            i++;
862          } else {
863            j++;
864            prev = current;
865          }
866        }
867      }
868    }
[12838]869    #endregion
[12808]870
[12838]871    #region Helpers
[13583]872    private Dictionary<ProblemDescription, double> CalculateBestTargetPerProblemInstance(string table) {
[12888]873      return (from r in Content
874              where r.Visible
[13583]875              let pd = new ProblemDescription(r)
[12888]876              let target = r.Parameters.ContainsKey("BestKnownQuality")
877                           && r.Parameters["BestKnownQuality"] is DoubleValue
878                ? ((DoubleValue)r.Parameters["BestKnownQuality"]).Value
879                : ((IndexedDataTable<double>)r.Results[table]).Rows.First().Values.Last().Item2
880              group target by pd into g
[13583]881              select new { Problem = g.Key, Target = g.Key.IsMaximization() ? g.Max() : g.Min() })
[12888]882        .ToDictionary(x => x.Problem, x => x.Target);
883    }
884
885    private void UpdateRuns() {
886      if (InvokeRequired) {
887        Invoke((Action)UpdateRuns);
888        return;
889      }
890      SuspendRepaint();
891      try {
892        UpdateResultsByTarget();
893        UpdateResultsByCost();
894      } finally { ResumeRepaint(true); }
895    }
[12838]896    #endregion
[12841]897
898
899    private class ProblemDescription {
900      private readonly bool matchAll;
[12864]901      public static readonly ProblemDescription MatchAll = new ProblemDescription() {
902        ProblemName = "All with Best-Known"
903      };
[12841]904
905      private ProblemDescription() {
906        ProblemType = string.Empty;
907        ProblemName = string.Empty;
908        Evaluator = string.Empty;
[13583]909        Maximization = string.Empty;
[12841]910        DisplayProblemType = false;
911        DisplayProblemName = false;
912        DisplayEvaluator = false;
[13583]913        DisplayMaximization = false;
[12841]914        matchAll = true;
915      }
916
917      public ProblemDescription(IRun run) {
918        ProblemType = GetStringValueOrEmpty(run, "Problem Type");
919        ProblemName = GetStringValueOrEmpty(run, "Problem Name");
920        Evaluator = GetStringValueOrEmpty(run, "Evaluator");
[13583]921        Maximization = GetMaximizationValueOrEmpty(run, "Maximization");
[12841]922        DisplayProblemType = !string.IsNullOrEmpty(ProblemType);
923        DisplayProblemName = !string.IsNullOrEmpty(ProblemName);
924        DisplayEvaluator = !string.IsNullOrEmpty(Evaluator);
[13583]925        DisplayMaximization = !string.IsNullOrEmpty(Maximization);
[12841]926        matchAll = false;
927      }
928
929      public bool DisplayProblemType { get; set; }
930      public string ProblemType { get; set; }
931      public bool DisplayProblemName { get; set; }
932      public string ProblemName { get; set; }
933      public bool DisplayEvaluator { get; set; }
934      public string Evaluator { get; set; }
[13583]935      public bool DisplayMaximization { get; set; }
936      public string Maximization { get; set; }
[12841]937
[13583]938      public bool IsMaximization() {
939        return Maximization == "MAX";
940      }
941
[12841]942      public bool Match(IRun run) {
943        return matchAll ||
944               GetStringValueOrEmpty(run, "Problem Type") == ProblemType
945               && GetStringValueOrEmpty(run, "Problem Name") == ProblemName
[13583]946               && GetStringValueOrEmpty(run, "Evaluator") == Evaluator
947               && GetMaximizationValueOrEmpty(run, "Maximization") == Maximization;
[12841]948      }
949
950      private string GetStringValueOrEmpty(IRun run, string key) {
951        return run.Parameters.ContainsKey(key) ? ((StringValue)run.Parameters[key]).Value : string.Empty;
952      }
953
[13583]954      private string GetMaximizationValueOrEmpty(IRun run, string key) {
955        return run.Parameters.ContainsKey(key) ? (((BoolValue)run.Parameters[key]).Value ? "MAX" : "MIN") : string.Empty;
956      }
957
[12841]958      public override bool Equals(object obj) {
959        var other = obj as ProblemDescription;
960        if (other == null) return false;
961        return ProblemType == other.ProblemType
962               && ProblemName == other.ProblemName
[13583]963               && Evaluator == other.Evaluator
964               && Maximization == other.Maximization;
[12841]965      }
966
967      public override int GetHashCode() {
[13583]968        return ProblemType.GetHashCode() ^ ProblemName.GetHashCode() ^ Evaluator.GetHashCode() ^ Maximization.GetHashCode();
[12841]969      }
970
971      public override string ToString() {
972        return string.Join("  --  ", new[] {
973          (DisplayProblemType ? ProblemType : string.Empty),
974          (DisplayProblemName ? ProblemName : string.Empty),
[13583]975          (DisplayEvaluator ? Evaluator : string.Empty),
976          (DisplayMaximization ? Maximization : string.Empty)}.Where(x => !string.IsNullOrEmpty(x)));
[12841]977      }
978    }
[7980]979  }
980}
Note: See TracBrowser for help on using the repository browser.