Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12888 was 12888, checked in by abeham, 9 years ago

#2431:

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