Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2457:

  • Added stripped-down version of FLA branch
  • Added appropriate calculators
  • Fixed detecting maximization in RLD view
File size: 39.3 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 HeuristicLab.Analysis;
23using HeuristicLab.Collections;
24using HeuristicLab.Core.Views;
25using HeuristicLab.Data;
26using HeuristicLab.MainForm;
27using HeuristicLab.MainForm.WindowsForms;
28using System;
29using System.Collections.Generic;
30using System.ComponentModel;
31using System.Drawing;
32using System.Globalization;
33using System.Linq;
34using System.Windows.Forms;
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,
89          YAxisMinimumAuto = false,
90          YAxisMaximumFixedValue = 1,
91          YAxisMaximumAuto = false
92        }
93      };
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 = {
97          YAxisTitle = "Proportion of unused budgets",
98          YAxisMinimumFixedValue = 0,
99          YAxisMinimumAuto = false,
100          YAxisMaximumFixedValue = 1,
101          YAxisMaximumAuto = false
102        }
103      };
104      byCostViewHost.Content = byCostDataTable;
105      suppressUpdates = false;
106    }
107
108    #region Content events
109    protected override void RegisterContentEvents() {
110      base.RegisterContentEvents();
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;
116    }
117    protected override void DeregisterContentEvents() {
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;
123      base.DeregisterContentEvents();
124    }
125
126    private void Content_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
127      if (suppressUpdates) return;
128      if (InvokeRequired) {
129        Invoke(new CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded), sender, e);
130        return;
131      }
132      UpdateGroupAndProblemComboBox();
133      UpdateDataTableComboBox();
134      foreach (var run in e.Items)
135        RegisterRunEvents(run);
136    }
137    private void Content_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
138      if (suppressUpdates) return;
139      if (InvokeRequired) {
140        Invoke(new CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved), sender, e);
141        return;
142      }
143      UpdateGroupAndProblemComboBox();
144      UpdateDataTableComboBox();
145      foreach (var run in e.Items)
146        DeregisterRunEvents(run);
147    }
148    private void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
149      if (suppressUpdates) return;
150      if (InvokeRequired) {
151        Invoke(new CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset), sender, e);
152        return;
153      }
154      UpdateGroupAndProblemComboBox();
155      UpdateDataTableComboBox();
156      foreach (var run in e.OldItems)
157        DeregisterRunEvents(run);
158    }
159    private void Content_AlgorithmNameChanged(object sender, EventArgs e) {
160      if (InvokeRequired)
161        Invoke(new EventHandler(Content_AlgorithmNameChanged), sender, e);
162      else UpdateCaption();
163    }
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;
170      if (!suppressUpdates) {
171        UpdateDataTableComboBox();
172        UpdateGroupAndProblemComboBox();
173        UpdateRuns();
174      }
175    }
176
177    private void RegisterRunEvents(IRun run) {
178      run.PropertyChanged += run_PropertyChanged;
179    }
180    private void DeregisterRunEvents(IRun run) {
181      run.PropertyChanged -= run_PropertyChanged;
182    }
183    private void run_PropertyChanged(object sender, PropertyChangedEventArgs e) {
184      if (suppressUpdates) return;
185      if (InvokeRequired) {
186        Invoke((Action<object, PropertyChangedEventArgs>)run_PropertyChanged, sender, e);
187      } else {
188        if (e.PropertyName == "Visible")
189          UpdateRuns();
190      }
191    }
192    #endregion
193
194    protected override void OnContentChanged() {
195      base.OnContentChanged();
196      dataTableComboBox.Items.Clear();
197      groupComboBox.Items.Clear();
198      byTargetDataTable.Rows.Clear();
199
200      UpdateCaption();
201      if (Content != null) {
202        UpdateGroupAndProblemComboBox();
203        UpdateDataTableComboBox();
204      }
205    }
206
207
208    private void UpdateGroupAndProblemComboBox() {
209      var selectedGroupItem = (string)groupComboBox.SelectedItem;
210
211      var groupings = Content.ParameterNames.OrderBy(x => x).ToArray();
212      groupComboBox.Items.Clear();
213      groupComboBox.Items.Add(AllRuns);
214      groupComboBox.Items.AddRange(groupings);
215      if (selectedGroupItem != null && groupComboBox.Items.Contains(selectedGroupItem)) {
216        groupComboBox.SelectedItem = selectedGroupItem;
217      } else if (groupComboBox.Items.Count > 0) {
218        groupComboBox.SelectedItem = groupComboBox.Items[0];
219      }
220
221      var problems = new HashSet<ProblemDescription>();
222      foreach (var run in Content) {
223        problems.Add(new ProblemDescription(run));
224      }
225
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;
229      var maximizationDifferent = problems.Select(x => x.Maximization).Distinct().Count() > 1;
230      var allEqual = !problemTypesDifferent && !problemNamesDifferent && !evaluatorDifferent && !maximizationDifferent;
231
232      var selectedProblemItem = (ProblemDescription)problemComboBox.SelectedItem;
233      problemComboBox.Items.Clear();
234      problemComboBox.Items.Add(ProblemDescription.MatchAll);
235      if (selectedProblemItem == null || selectedProblemItem == ProblemDescription.MatchAll)
236        problemComboBox.SelectedIndex = 0;
237      foreach (var prob in problems.OrderBy(x => x.ToString()).ToList()) {
238        prob.DisplayProblemType = problemTypesDifferent;
239        prob.DisplayProblemName = problemNamesDifferent || allEqual;
240        prob.DisplayEvaluator = evaluatorDifferent;
241        prob.DisplayMaximization = maximizationDifferent;
242        problemComboBox.Items.Add(prob);
243        if (prob.Equals(selectedProblemItem)) problemComboBox.SelectedItem = prob;
244      }
245      SetEnabledStateOfControls();
246    }
247
248    private void UpdateDataTableComboBox() {
249      string selectedItem = (string)dataTableComboBox.SelectedItem;
250
251      dataTableComboBox.Items.Clear();
252      var dataTables = (from run in Content
253                        from result in run.Results
254                        where result.Value is IndexedDataTable<double>
255                        select result.Key).Distinct().ToArray();
256
257      dataTableComboBox.Items.AddRange(dataTables);
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      }
263    }
264
265    protected override void SetEnabledStateOfControls() {
266      base.SetEnabledStateOfControls();
267      groupComboBox.Enabled = Content != null;
268      problemComboBox.Enabled = Content != null && problemComboBox.Items.Count > 1;
269      dataTableComboBox.Enabled = Content != null && dataTableComboBox.Items.Count > 1;
270      addTargetsAsResultButton.Enabled = Content != null && targets != null && dataTableComboBox.SelectedIndex >= 0;
271      addBudgetsAsResultButton.Enabled = Content != null && budgets != null && dataTableComboBox.SelectedIndex >= 0;
272    }
273
274    private Dictionary<string, Dictionary<ProblemDescription, Tuple<double, List<IRun>>>> GroupRuns() {
275      var groupedRuns = new Dictionary<string, Dictionary<ProblemDescription, Tuple<double, List<IRun>>>>();
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;
284      if (selectedProblem == null) return groupedRuns;
285
286      var targetsPerProblem = CalculateBestTargetPerProblemInstance(table);
287
288      foreach (var x in (from r in Content
289                         where (selectedGroup == AllRuns || r.Parameters.ContainsKey(selectedGroup))
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()))) {
295        var pDict = new Dictionary<ProblemDescription, Tuple<double, List<IRun>>>();
296        foreach (var y in (from r in x.Item2
297                           let pd = new ProblemDescription(r)
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
305      return groupedRuns;
306    }
307
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
317      if (targets == null) GenerateDefaultTargets();
318
319      var groupedRuns = GroupRuns();
320      if (groupedRuns.Count == 0) return;
321
322      var xAxisTitles = new HashSet<string>();
323      var colorCount = 0;
324      var lineStyleCount = 0;
325
326      foreach (var group in groupedRuns) {
327        var hits = new Dictionary<string, SortedList<double, double>>();
328        var maxLength = 0.0;
329
330        foreach (var problem in group.Value) {
331          foreach (var run in problem.Value.Item2) {
332            var resultsTable = (IndexedDataTable<double>)run.Results[table];
333            xAxisTitles.Add(resultsTable.VisualProperties.XAxisTitle);
334
335            if (eachOrAllTargetCheckBox.Checked) {
336              CalculateHitsForEachTarget(hits, resultsTable.Rows.First(), problem.Key, group.Key, group.Value.Count, problem.Value.Item1, problem.Value.Item2.Count);
337            } else {
338              maxLength = CalculateHitsForAllTargets(hits, resultsTable.Rows.First(), problem.Key, group.Key, group.Value.Count, problem.Value.Item1, problem.Value.Item2.Count);
339            }
340          }
341        }
342
343        foreach (var list in hits) {
344          var row = new IndexedDataRow<double>(list.Key) {
345            VisualProperties = {
346              ChartType = DataRowVisualProperties.DataRowChartType.StepLine,
347              LineWidth = 2,
348              Color = colors[colorCount],
349              LineStyle = lineStyles[lineStyleCount]
350            }
351          };
352
353          var total = 0.0;
354          foreach (var h in list.Value) {
355            total += h.Value;
356            row.Values.Add(Tuple.Create(h.Key, total));
357          }
358
359          if (maxLength > 0 && (row.Values.Count == 0 || row.Values.Last().Item1 < maxLength))
360            row.Values.Add(Tuple.Create(maxLength, total));
361
362          byTargetDataTable.Rows.Add(row);
363        }
364        colorCount = (colorCount + 1) % colors.Length;
365        if (colorCount == 0) lineStyleCount = (lineStyleCount + 1) % lineStyles.Length;
366      }
367
368      if (targets.Length == 1)
369        ByTargetDataTable.VisualProperties.YAxisTitle = "Probability to be " + (targets[0] * 100) + "% worse than best";
370      else ByTargetDataTable.VisualProperties.YAxisTitle = "Proportion of reached targets";
371      byTargetDataTable.VisualProperties.XAxisTitle = string.Join(" / ", xAxisTitles);
372      byTargetDataTable.VisualProperties.XAxisLogScale = byTargetDataTable.Rows.Count > 0 && targetLogScalingCheckBox.Checked;
373
374      UpdateErtTables(groupedRuns);
375    }
376
377    private void GenerateDefaultTargets() {
378      targets = new[] { 0.1, 0.05, 0.02, 0.01, 0 };
379      suppressTargetsEvents = true;
380      targetsTextBox.Text = string.Join("% ; ", targets.Select(x => x * 100)) + "%";
381      suppressTargetsEvents = false;
382    }
383
384    private void CalculateHitsForEachTarget(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, ProblemDescription problem, string group, int groupCount, double bestTarget, int problemCount) {
385      foreach (var l in targets.Select(x => (problem.IsMaximization() ? (1 - x) : (1 + x)) * bestTarget)) {
386        var key = group + "-" + l;
387        if (!hits.ContainsKey(key)) hits.Add(key, new SortedList<double, double>());
388        foreach (var v in row.Values) {
389          if (problem.IsMaximization() && v.Item2 >= l || !problem.IsMaximization() && v.Item2 <= l) {
390            if (hits[key].ContainsKey(v.Item1))
391              hits[key][v.Item1] += 1.0 / (groupCount * problemCount);
392            else hits[key][v.Item1] = 1.0 / (groupCount * problemCount);
393            break;
394          }
395        }
396      }
397    }
398
399    private double CalculateHitsForAllTargets(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, ProblemDescription problem, string group, int groupCount, double bestTarget, int problemCount) {
400      var values = row.Values;
401      if (!hits.ContainsKey(group)) hits.Add(group, new SortedList<double, double>());
402
403      var i = 0;
404      var j = 0;
405      while (i < targets.Length && j < values.Count) {
406        var target = (problem.IsMaximization() ? (1 - targets[i]) : (1 + targets[i])) * bestTarget;
407        var current = values[j];
408        if (problem.IsMaximization() && current.Item2 >= target
409          || !problem.IsMaximization() && current.Item2 <= target) {
410          if (!hits[group].ContainsKey(current.Item1)) hits[group][current.Item1] = 0;
411          hits[group][current.Item1] += 1.0 / (groupCount * problemCount * targets.Length);
412          i++;
413        } else {
414          j++;
415        }
416      }
417      if (j == values.Count) j--;
418      return values[j].Item1;
419    }
420
421    private void UpdateErtTables(Dictionary<string, Dictionary<ProblemDescription, Tuple<double, List<IRun>>>> groupedRuns) {
422      ertTableView.Content = null;
423      var columns = 1 + targets.Length + 1;
424      var matrix = new string[groupedRuns.Count * groupedRuns.Max(x => x.Value.Count) + groupedRuns.Max(x => x.Value.Count), columns];
425      var rowCount = 0;
426
427      var tableName = (string)dataTableComboBox.SelectedItem;
428      if (string.IsNullOrEmpty(tableName)) return;
429
430      var targetsPerProblem = CalculateBestTargetPerProblemInstance(tableName);
431
432      var colNames = new string[columns];
433      colNames[0] = colNames[colNames.Length - 1] = string.Empty;
434      for (var i = 0; i < targets.Length; i++) {
435        colNames[i + 1] = targets[i].ToString("0.0%");
436      }
437      var problems = groupedRuns.SelectMany(x => x.Value.Keys).Distinct().ToList();
438
439      foreach (var problem in problems) {
440        matrix[rowCount, 0] = problem.ToString();
441        for (var i = 0; i < targets.Length; i++) {
442          matrix[rowCount, i + 1] = (targetsPerProblem[problem] * (problem.IsMaximization() ? (1 - targets[i]) : (1 + targets[i]))).ToString(CultureInfo.CurrentCulture.NumberFormat);
443        }
444        matrix[rowCount, columns - 1] = "#succ";
445        rowCount++;
446
447        foreach (var group in groupedRuns) {
448          matrix[rowCount, 0] = group.Key;
449          if (!group.Value.ContainsKey(problem)) {
450            matrix[rowCount, columns - 1] = "N/A";
451            rowCount++;
452            continue;
453          }
454          var runs = group.Value[problem].Item2;
455          ErtCalculationResult result = default(ErtCalculationResult);
456          for (var i = 0; i < targets.Length; i++) {
457            result = ExpectedRuntimeHelper.CalculateErt(runs, tableName, (problem.IsMaximization() ? (1 - targets[i]) : (1 + targets[i])) * group.Value[problem].Item1, problem.IsMaximization());
458            matrix[rowCount, i + 1] = result.ToString();
459          }
460          matrix[rowCount, columns - 1] = targets.Length > 0 ? result.SuccessfulRuns + "/" + result.TotalRuns : "-";
461          rowCount++;
462        }
463      }
464      ertTableView.Content = new StringMatrix(matrix) { ColumnNames = colNames };
465      ertTableView.DataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
466    }
467    #endregion
468
469    #region Performance analysis by (multiple) budget(s)
470    private void UpdateResultsByCost() {
471      // necessary to reset log scale -> empty chart cannot use log scaling
472      byCostDataTable.VisualProperties.XAxisLogScale = false;
473      byCostDataTable.Rows.Clear();
474
475      var table = (string)dataTableComboBox.SelectedItem;
476      if (string.IsNullOrEmpty(table)) return;
477
478      if (budgets == null) GenerateDefaultBudgets(table);
479
480      var groupedRuns = GroupRuns();
481      if (groupedRuns.Count == 0) return;
482
483      var colorCount = 0;
484      var lineStyleCount = 0;
485
486      var targetsPerProblem = CalculateBestTargetPerProblemInstance((string)dataTableComboBox.SelectedItem);
487
488      foreach (var group in groupedRuns) {
489        var hits = new Dictionary<string, SortedList<double, double>>();
490
491        foreach (var problem in group.Value) {
492          foreach (var run in problem.Value.Item2) {
493            var resultsTable = (IndexedDataTable<double>)run.Results[table];
494
495            if (eachOrAllBudgetsCheckBox.Checked) {
496              CalculateHitsForEachBudget(hits, resultsTable.Rows.First(), group.Value.Count, problem.Key, group.Key, problem.Value.Item2.Count, targetsPerProblem[problem.Key]);
497            } else {
498              CalculateHitsForAllBudgets(hits, resultsTable.Rows.First(), group.Value.Count, problem.Key, group.Key, problem.Value.Item2.Count, targetsPerProblem[problem.Key]);
499            }
500          }
501        }
502
503        foreach (var list in hits) {
504          var row = new IndexedDataRow<double>(list.Key) {
505            VisualProperties = {
506              ChartType = DataRowVisualProperties.DataRowChartType.StepLine,
507              LineWidth = 2,
508              Color = colors[colorCount],
509              LineStyle = lineStyles[lineStyleCount]
510            }
511          };
512
513          var total = 0.0;
514          foreach (var h in list.Value) {
515            total += h.Value;
516            row.Values.Add(Tuple.Create(h.Key, total));
517          }
518
519          byCostDataTable.Rows.Add(row);
520        }
521        colorCount = (colorCount + 1) % colors.Length;
522        if (colorCount == 0) lineStyleCount = (lineStyleCount + 1) % lineStyles.Length;
523      }
524
525      byCostDataTable.VisualProperties.XAxisTitle = "Targets to Best-Known Ratio";
526      byCostDataTable.VisualProperties.XAxisLogScale = byCostDataTable.Rows.Count > 0 && budgetLogScalingCheckBox.Checked;
527    }
528
529    private void GenerateDefaultBudgets(string table) {
530      var runs = GroupRuns().SelectMany(x => x.Value.Values).SelectMany(x => x.Item2).ToList();
531      var min = runs.Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Select(y => y.Item1).Min()).Min();
532      var max = runs.Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Select(y => y.Item1).Max()).Max();
533
534      var maxMagnitude = (int)Math.Ceiling(Math.Log10(max));
535      var minMagnitude = (int)Math.Floor(Math.Log10(min));
536      if (maxMagnitude - minMagnitude >= 3) {
537        budgets = new double[maxMagnitude - minMagnitude];
538        for (var i = minMagnitude; i < maxMagnitude; i++) {
539          budgets[i - minMagnitude] = Math.Pow(10, i);
540        }
541      } else {
542        var range = max - min;
543        budgets = Enumerable.Range(0, 6).Select(x => min + (x / 5.0) * range).ToArray();
544      }
545      suppressBudgetsEvents = true;
546      budgetsTextBox.Text = string.Join(" ; ", budgets);
547      suppressBudgetsEvents = false;
548    }
549
550    private void CalculateHitsForEachBudget(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, int groupCount, ProblemDescription problem, string groupName, int problemCount, double bestTarget) {
551      foreach (var b in budgets) {
552        var key = groupName + "-" + b;
553        if (!hits.ContainsKey(key)) hits.Add(key, new SortedList<double, double>());
554        Tuple<double, double> prev = null;
555        foreach (var v in row.Values) {
556          if (v.Item1 >= b) {
557            // the budget may be too low to achieve any target
558            if (prev == null && v.Item1 != b) break;
559            var tgt = ((prev == null || v.Item1 == b) ? v.Item2 : prev.Item2);
560            tgt = problem.IsMaximization() ? bestTarget / tgt : tgt / bestTarget;
561            if (hits[key].ContainsKey(tgt))
562              hits[key][tgt] += 1.0 / (groupCount * problemCount);
563            else hits[key][tgt] = 1.0 / (groupCount * problemCount);
564            break;
565          }
566          prev = v;
567        }
568        if (hits[key].Count == 0) hits.Remove(key);
569      }
570    }
571
572    private void CalculateHitsForAllBudgets(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, int groupCount, ProblemDescription problem, string groupName, int problemCount, double bestTarget) {
573      var values = row.Values;
574      if (!hits.ContainsKey(groupName)) hits.Add(groupName, new SortedList<double, double>());
575
576      var i = 0;
577      var j = 0;
578      Tuple<double, double> prev = null;
579      while (i < budgets.Length && j < values.Count) {
580        var current = values[j];
581        if (current.Item1 >= budgets[i]) {
582          if (prev != null || current.Item1 == budgets[i]) {
583            var tgt = (prev == null || current.Item1 == budgets[i]) ? current.Item2 : prev.Item2;
584            tgt = problem.IsMaximization() ? bestTarget / tgt : tgt / bestTarget;
585            if (!hits[groupName].ContainsKey(tgt)) hits[groupName][tgt] = 0;
586            hits[groupName][tgt] += 1.0 / (groupCount * problemCount * budgets.Length);
587          }
588          i++;
589        } else {
590          j++;
591          prev = current;
592        }
593      }
594      var lastTgt = values.Last().Item2;
595      lastTgt = problem.IsMaximization() ? bestTarget / lastTgt : lastTgt / bestTarget;
596      if (i < budgets.Length && !hits[groupName].ContainsKey(lastTgt)) hits[groupName][lastTgt] = 0;
597      while (i < budgets.Length) {
598        hits[groupName][lastTgt] += 1.0 / (groupCount * problemCount * budgets.Length);
599        i++;
600      }
601    }
602    #endregion
603
604    private void UpdateCaption() {
605      Caption = Content != null ? Content.OptimizerName + " RLD View" : ViewAttribute.GetViewName(GetType());
606    }
607
608    private void groupComboBox_SelectedIndexChanged(object sender, EventArgs e) {
609      UpdateRuns();
610      SetEnabledStateOfControls();
611    }
612    private void problemComboBox_SelectedIndexChanged(object sender, EventArgs e) {
613      UpdateRuns();
614      SetEnabledStateOfControls();
615    }
616    private void dataTableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
617      if (dataTableComboBox.SelectedIndex >= 0)
618        GenerateDefaultBudgets((string)dataTableComboBox.SelectedItem);
619      UpdateRuns();
620      SetEnabledStateOfControls();
621    }
622
623    private void logScalingCheckBox_CheckedChanged(object sender, EventArgs e) {
624      byTargetDataTable.VisualProperties.XAxisLogScale = byTargetDataTable.Rows.Count > 0 && targetLogScalingCheckBox.Checked;
625      byCostDataTable.VisualProperties.XAxisLogScale = byCostDataTable.Rows.Count > 0 && budgetLogScalingCheckBox.Checked;
626    }
627
628    #region Event handlers for target analysis
629    private bool suppressTargetsEvents;
630    private void targetsTextBox_Validating(object sender, CancelEventArgs e) {
631      if (suppressTargetsEvents) return;
632      var targetStrings = targetsTextBox.Text.Split(new[] { '%', ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
633      var targetList = new List<decimal>();
634      foreach (var ts in targetStrings) {
635        decimal t;
636        if (!decimal.TryParse(ts, out t)) {
637          errorProvider.SetError(targetsTextBox, "Not all targets can be parsed: " + ts);
638          e.Cancel = true;
639          return;
640        }
641        targetList.Add(t / 100);
642      }
643      if (targetList.Count == 0) {
644        errorProvider.SetError(targetsTextBox, "Give at least one target value!");
645        e.Cancel = true;
646        return;
647      }
648      e.Cancel = false;
649      errorProvider.SetError(targetsTextBox, null);
650      targets = targetList.Select(x => (double)x).OrderByDescending(x => x).ToArray();
651      suppressTargetsEvents = true;
652      try { targetsTextBox.Text = string.Join("% ; ", targets.Select(x => x * 100)) + "%"; } finally { suppressTargetsEvents = false; }
653
654      UpdateResultsByTarget();
655      SetEnabledStateOfControls();
656    }
657
658    private void eachOrAllTargetCheckBox_CheckedChanged(object sender, EventArgs e) {
659      var each = eachOrAllTargetCheckBox.Checked;
660      eachOrAllTargetCheckBox.Text = each ? "each" : "all";
661      SuspendRepaint();
662      try {
663        UpdateResultsByTarget();
664      } finally { ResumeRepaint(true); }
665    }
666
667    private void generateTargetsButton_Click(object sender, EventArgs e) {
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 = dialog.Values.Select(x => (double)x).ToArray();
683            suppressTargetsEvents = true;
684            targetsTextBox.Text = string.Join("% ; ", targets);
685            suppressTargetsEvents = false;
686
687            UpdateResultsByTarget();
688            SetEnabledStateOfControls();
689          }
690        }
691      }
692    }
693
694    private void addTargetsAsResultButton_Click(object sender, EventArgs e) {
695      var table = (string)dataTableComboBox.SelectedItem;
696
697      var targetsPerProblem = CalculateBestTargetPerProblemInstance(table);
698
699      foreach (var run in Content) {
700        if (!run.Results.ContainsKey(table)) continue;
701        var resultsTable = (IndexedDataTable<double>)run.Results[table];
702        var values = resultsTable.Rows.First().Values;
703        var i = 0;
704        var j = 0;
705        var pd = new ProblemDescription(run);
706        while (i < targets.Length && j < values.Count) {
707          var target = (pd.IsMaximization() ? (1 - targets[i]) : (1 + targets[i])) * targetsPerProblem[pd];
708          var current = values[j];
709          if (pd.IsMaximization() && current.Item2 >= target
710              || !pd.IsMaximization() && current.Item2 <= target) {
711            run.Results[table + ".Target" + target] = new DoubleValue(current.Item1);
712            i++;
713          } else {
714            j++;
715          }
716        }
717      }
718    }
719    #endregion
720
721    #region Event handlers for cost analysis
722    private bool suppressBudgetsEvents;
723    private void budgetsTextBox_Validating(object sender, CancelEventArgs e) {
724      if (suppressBudgetsEvents) return;
725      var budgetStrings = budgetsTextBox.Text.Split(new[] { ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
726      var budgetList = new List<double>();
727      foreach (var ts in budgetStrings) {
728        double b;
729        if (!double.TryParse(ts, out b)) {
730          errorProvider.SetError(budgetsTextBox, "Not all targets can be parsed: " + ts);
731          e.Cancel = true;
732          return;
733        }
734        budgetList.Add(b);
735      }
736      if (budgetList.Count == 0) {
737        errorProvider.SetError(budgetsTextBox, "Give at least one target value!");
738        e.Cancel = true;
739        return;
740      }
741      e.Cancel = false;
742      errorProvider.SetError(budgetsTextBox, null);
743      budgets = budgetList.ToArray();
744      UpdateResultsByCost();
745      SetEnabledStateOfControls();
746    }
747
748    private void eachOrAllBudgetsCheckBox_CheckedChanged(object sender, EventArgs e) {
749      var each = eachOrAllBudgetsCheckBox.Checked;
750      eachOrAllBudgetsCheckBox.Text = each ? "each" : "all";
751      SuspendRepaint();
752      try {
753        UpdateResultsByCost();
754      } finally { ResumeRepaint(true); }
755    }
756
757    private void generateBudgetsButton_Click(object sender, EventArgs e) {
758      decimal max = 1, min = 0, count = 10;
759      if (budgets != null) {
760        max = (decimal)budgets.Max();
761        min = (decimal)budgets.Min();
762        count = budgets.Length;
763      } else if (Content.Count > 0 && dataTableComboBox.SelectedIndex >= 0) {
764        var table = (string)dataTableComboBox.SelectedItem;
765        min = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Min(y => y.Item1)).Min();
766        max = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Max(y => y.Item1)).Max();
767        count = 6;
768      }
769      using (var dialog = new DefineArithmeticProgressionDialog(false, min, max, (max - min) / count)) {
770        if (dialog.ShowDialog() == DialogResult.OK) {
771          if (dialog.Values.Any()) {
772            budgets = dialog.Values.OrderBy(x => x).Select(x => (double)x).ToArray();
773
774            suppressBudgetsEvents = true;
775            budgetsTextBox.Text = string.Join(" ; ", budgets);
776            suppressBudgetsEvents = false;
777
778            UpdateResultsByCost();
779            SetEnabledStateOfControls();
780          }
781        }
782      }
783    }
784
785    private void addBudgetsAsResultButton_Click(object sender, EventArgs e) {
786      var table = (string)dataTableComboBox.SelectedItem;
787      var budgetStrings = budgetsTextBox.Text.Split(new[] { ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
788      if (budgetStrings.Length == 0) {
789        MessageBox.Show("Define a number of budgets.");
790        return;
791      }
792      var budgetList = new List<double>();
793      foreach (var bs in budgetStrings) {
794        double v;
795        if (!double.TryParse(bs, out v)) {
796          MessageBox.Show("Budgets must be a valid number: " + bs);
797          return;
798        }
799        budgetList.Add(v);
800      }
801      budgetList.Sort();
802
803      foreach (var run in Content) {
804        if (!run.Results.ContainsKey(table)) continue;
805        var resultsTable = (IndexedDataTable<double>)run.Results[table];
806        var values = resultsTable.Rows.First().Values;
807        var i = 0;
808        var j = 0;
809        Tuple<double, double> prev = null;
810        while (i < budgetList.Count && j < values.Count) {
811          var current = values[j];
812          if (current.Item1 >= budgetList[i]) {
813            if (prev != null || current.Item1 == budgetList[i]) {
814              var tgt = (prev == null || current.Item1 == budgetList[i]) ? current.Item2 : prev.Item2;
815              run.Results[table + ".Cost" + budgetList[i]] = new DoubleValue(tgt);
816            }
817            i++;
818          } else {
819            j++;
820            prev = current;
821          }
822        }
823      }
824    }
825    #endregion
826
827    #region Helpers
828    private Dictionary<ProblemDescription, double> CalculateBestTargetPerProblemInstance(string table) {
829      return (from r in Content
830              where r.Visible
831              let pd = new ProblemDescription(r)
832              let target = r.Parameters.ContainsKey("BestKnownQuality")
833                           && r.Parameters["BestKnownQuality"] is DoubleValue
834                ? ((DoubleValue)r.Parameters["BestKnownQuality"]).Value
835                : ((IndexedDataTable<double>)r.Results[table]).Rows.First().Values.Last().Item2
836              group target by pd into g
837              select new { Problem = g.Key, Target = g.Key.IsMaximization() ? g.Max() : g.Min() })
838        .ToDictionary(x => x.Problem, x => x.Target);
839    }
840
841    private void UpdateRuns() {
842      if (InvokeRequired) {
843        Invoke((Action)UpdateRuns);
844        return;
845      }
846      SuspendRepaint();
847      try {
848        UpdateResultsByTarget();
849        UpdateResultsByCost();
850      } finally { ResumeRepaint(true); }
851    }
852    #endregion
853
854
855    private class ProblemDescription {
856      private readonly bool matchAll;
857      public static readonly ProblemDescription MatchAll = new ProblemDescription() {
858        ProblemName = "All with Best-Known"
859      };
860
861      private ProblemDescription() {
862        ProblemType = string.Empty;
863        ProblemName = string.Empty;
864        Evaluator = string.Empty;
865        Maximization = string.Empty;
866        DisplayProblemType = false;
867        DisplayProblemName = false;
868        DisplayEvaluator = false;
869        DisplayMaximization = false;
870        matchAll = true;
871      }
872
873      public ProblemDescription(IRun run) {
874        ProblemType = GetStringValueOrEmpty(run, "Problem Type");
875        ProblemName = GetStringValueOrEmpty(run, "Problem Name");
876        Evaluator = GetStringValueOrEmpty(run, "Evaluator");
877        Maximization = GetMaximizationValueOrEmpty(run, "Maximization");
878        DisplayProblemType = !string.IsNullOrEmpty(ProblemType);
879        DisplayProblemName = !string.IsNullOrEmpty(ProblemName);
880        DisplayEvaluator = !string.IsNullOrEmpty(Evaluator);
881        DisplayMaximization = !string.IsNullOrEmpty(Maximization);
882        matchAll = false;
883      }
884
885      public bool DisplayProblemType { get; set; }
886      public string ProblemType { get; set; }
887      public bool DisplayProblemName { get; set; }
888      public string ProblemName { get; set; }
889      public bool DisplayEvaluator { get; set; }
890      public string Evaluator { get; set; }
891      public bool DisplayMaximization { get; set; }
892      public string Maximization { get; set; }
893
894      public bool IsMaximization() {
895        return Maximization == "MAX";
896      }
897
898      public bool Match(IRun run) {
899        return matchAll ||
900               GetStringValueOrEmpty(run, "Problem Type") == ProblemType
901               && GetStringValueOrEmpty(run, "Problem Name") == ProblemName
902               && GetStringValueOrEmpty(run, "Evaluator") == Evaluator
903               && GetMaximizationValueOrEmpty(run, "Maximization") == Maximization;
904      }
905
906      private string GetStringValueOrEmpty(IRun run, string key) {
907        return run.Parameters.ContainsKey(key) ? ((StringValue)run.Parameters[key]).Value : string.Empty;
908      }
909
910      private string GetMaximizationValueOrEmpty(IRun run, string key) {
911        return run.Parameters.ContainsKey(key) ? (((BoolValue)run.Parameters[key]).Value ? "MAX" : "MIN") : string.Empty;
912      }
913
914      public override bool Equals(object obj) {
915        var other = obj as ProblemDescription;
916        if (other == null) return false;
917        return ProblemType == other.ProblemType
918               && ProblemName == other.ProblemName
919               && Evaluator == other.Evaluator
920               && Maximization == other.Maximization;
921      }
922
923      public override int GetHashCode() {
924        return ProblemType.GetHashCode() ^ ProblemName.GetHashCode() ^ Evaluator.GetHashCode() ^ Maximization.GetHashCode();
925      }
926
927      public override string ToString() {
928        return string.Join("  --  ", new[] {
929          (DisplayProblemType ? ProblemType : string.Empty),
930          (DisplayProblemName ? ProblemName : string.Empty),
931          (DisplayEvaluator ? Evaluator : string.Empty),
932          (DisplayMaximization ? Maximization : string.Empty)}.Where(x => !string.IsNullOrEmpty(x)));
933      }
934    }
935  }
936}
Note: See TracBrowser for help on using the repository browser.