Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2457, #2431: updated from trunk, worked on okb connection for downloading knowledge base

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