Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2431:

  • Added calculation of ERT results tables
  • Added grouping by problem to avoid having different problems in one graph
  • Some restructuring to avoid duplicate code
File size: 37.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 required 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).Distinct().Count() > 1;
223      var problemNamesDifferent = problems.Select(x => x.ProblemName).Distinct().Count() > 1;
224      var evaluatorDifferent = problems.Select(x => x.Evaluator).Distinct().Count() > 1;
225      var allEqual = !problemTypesDifferent && !problemNamesDifferent && !evaluatorDifferent;
226
227      var selectedProblemItem = (ProblemDescription)problemComboBox.SelectedItem;
228      problemComboBox.Items.Clear();
229      foreach (var prob in problems.OrderBy(x => x.ToString()).ToList()) {
230        prob.DisplayProblemType = problemTypesDifferent;
231        prob.DisplayProblemName = problemNamesDifferent || allEqual;
232        prob.DisplayEvaluator = evaluatorDifferent;
233        problemComboBox.Items.Add(prob);
234        if (prob.Equals(selectedProblemItem)) problemComboBox.SelectedItem = prob;
235      }
236      SetEnabledStateOfControls();
237    }
238
239    private void UpdateDataTableComboBox() {
240      string selectedItem = (string)dataTableComboBox.SelectedItem;
241
242      dataTableComboBox.Items.Clear();
243      var dataTables = (from run in Content
244                        from result in run.Results
245                        where result.Value is IndexedDataTable<double>
246                        select result.Key).Distinct().ToArray();
247
248      dataTableComboBox.Items.AddRange(dataTables);
249      if (selectedItem != null && dataTableComboBox.Items.Contains(selectedItem)) {
250        dataTableComboBox.SelectedItem = selectedItem;
251      } else if (dataTableComboBox.Items.Count > 0) {
252        dataTableComboBox.SelectedItem = dataTableComboBox.Items[0];
253      }
254    }
255
256    protected override void SetEnabledStateOfControls() {
257      base.SetEnabledStateOfControls();
258      groupComboBox.Enabled = Content != null;
259      problemComboBox.Enabled = Content != null && problemComboBox.Items.Count > 1;
260      dataTableComboBox.Enabled = Content != null && dataTableComboBox.Items.Count > 1;
261      addTargetsAsResultButton.Enabled = Content != null && targets != null && dataTableComboBox.SelectedIndex >= 0;
262      addBudgetsAsResultButton.Enabled = Content != null && budgets != null && dataTableComboBox.SelectedIndex >= 0;
263    }
264
265    private List<Tuple<string, List<IRun>>> GroupRuns() {
266      var groupedRuns = new List<Tuple<string, List<IRun>>>();
267
268      var table = (string)dataTableComboBox.SelectedItem;
269      if (string.IsNullOrEmpty(table)) return groupedRuns;
270
271      var selectedGroup = (string)groupComboBox.SelectedItem;
272      if (string.IsNullOrEmpty(selectedGroup)) return groupedRuns;
273
274      var selectedProblem = (ProblemDescription)problemComboBox.SelectedItem;
275      if (selectedProblem == null) selectedProblem = ProblemDescription.MatchAll;
276
277      if (selectedGroup == AllRuns)
278        groupedRuns = new List<Tuple<string, List<IRun>>> {
279          Tuple.Create(AllRuns, Content.Where(r => selectedProblem.Match(r) && r.Results.ContainsKey(table) && r.Visible).ToList())
280        };
281      else
282        groupedRuns = (from r in Content
283                       where r.Parameters.ContainsKey(selectedGroup)
284                             && selectedProblem.Match(r)
285                             && r.Results.ContainsKey(table)
286                             && r.Visible
287                       group r by r.Parameters[selectedGroup].ToString()
288                         into g
289                         select Tuple.Create(g.Key, g.ToList())).ToList();
290
291      return groupedRuns;
292    }
293
294    private void UpdateRuns() {
295      if (InvokeRequired) {
296        Invoke((Action)UpdateRuns);
297        return;
298      }
299      SuspendRepaint();
300      try {
301        UpdateResultsByTarget();
302        UpdateResultsByCost();
303      } finally { ResumeRepaint(true); }
304    }
305
306    #region Performance analysis by (multiple) target(s)
307    private void UpdateResultsByTarget() {
308      // necessary to reset log scale -> empty chart cannot use log scaling
309      byTargetDataTable.VisualProperties.XAxisLogScale = false;
310      byTargetDataTable.Rows.Clear();
311
312      var table = (string)dataTableComboBox.SelectedItem;
313      if (string.IsNullOrEmpty(table)) return;
314
315      if (targets == null) GenerateDefaultTargets(table);
316
317      var groupedRuns = GroupRuns();
318      if (groupedRuns.Count == 0) return;
319
320      var xAxisTitles = new HashSet<string>();
321      var colorCount = 0;
322      var lineStyleCount = 0;
323      var maximization = IsMaximization();
324
325      foreach (var group in groupedRuns) {
326        var hits = new Dictionary<string, SortedList<double, double>>();
327        var maxLength = 0.0;
328
329        foreach (var run in group.Item2) {
330          var resultsTable = (IndexedDataTable<double>)run.Results[table];
331          xAxisTitles.Add(resultsTable.VisualProperties.XAxisTitle);
332
333          if (eachOrAllTargetCheckBox.Checked) {
334            CalculateHitsForEachTarget(hits, resultsTable.Rows.First(), maximization, group.Item2.Count, group.Item1);
335          } else {
336            maxLength = CalculateHitsForAllTargets(hits, resultsTable.Rows.First(), maximization, group.Item2.Count, group.Item1);
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      byTargetDataTable.VisualProperties.XAxisTitle = string.Join(" / ", xAxisTitles);
366      byTargetDataTable.VisualProperties.XAxisLogScale = byTargetDataTable.Rows.Count > 0 && targetLogScalingCheckBox.Checked;
367
368      UpdateErtTables(groupedRuns);
369    }
370
371    private void GenerateDefaultTargets(string table) {
372      var runs = GroupRuns().SelectMany(x => x.Item2).ToList();
373      var worst = runs.Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Select(y => y.Item2).Min()).Min();
374      var best = runs.Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Select(y => y.Item2).Max()).Max();
375      var maximization = IsMaximization();
376      if (!maximization) {
377        var h = worst;
378        worst = best;
379        best = h;
380      }
381
382      if (best == 0 || Math.Abs(best - worst) < Math.Abs(best * 2))
383        targets = Enumerable.Range(0, 11).Select(x => worst + (x / 10.0) * (best - worst)).ToArray();
384      else if (best > 0) targets = Enumerable.Range(0, 11).Select(x => best * (1.0 + (10 - x) / 10.0)).ToArray();
385      else if (best < 0) targets = Enumerable.Range(0, 11).Select(x => best / (1.0 + (10 - x) / 10.0)).ToArray();
386
387      suppressTargetsEvents = true;
388      targetsTextBox.Text = string.Join(" ; ", targets);
389      suppressTargetsEvents = false;
390    }
391
392    private void CalculateHitsForEachTarget(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, bool maximization, int groupCount, string groupName) {
393      foreach (var l in targets) {
394        var key = groupName + "-" + l;
395        if (!hits.ContainsKey(key)) hits.Add(key, new SortedList<double, double>());
396        foreach (var v in row.Values) {
397          if (maximization && v.Item2 >= l || !maximization && v.Item2 <= l) {
398            if (hits[key].ContainsKey(v.Item1))
399              hits[key][v.Item1] += 1.0 / groupCount;
400            else hits[key][v.Item1] = 1.0 / groupCount;
401            break;
402          }
403        }
404      }
405    }
406
407    private double CalculateHitsForAllTargets(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, bool maximization, int groupCount, string groupName) {
408      var values = row.Values;
409      if (!hits.ContainsKey(groupName)) hits.Add(groupName, new SortedList<double, double>());
410
411      var i = 0;
412      var j = 0;
413      while (i < targets.Length && j < values.Count) {
414        var current = values[j];
415        if (maximization && current.Item2 >= targets[i]
416          || !maximization && current.Item2 <= targets[i]) {
417          if (!hits[groupName].ContainsKey(current.Item1)) hits[groupName][current.Item1] = 0;
418          hits[groupName][current.Item1] += 1.0 / (groupCount * targets.Length);
419          i++;
420        } else {
421          j++;
422        }
423      }
424      if (j == values.Count) j--;
425      return values[j].Item1;
426    }
427
428    private void UpdateErtTables(List<Tuple<string, List<IRun>>> groupedRuns) {
429      ertViewHost.Content = null;
430      var columns = 1 + targets.Length + 1;
431      var matrix = new string[groupedRuns.Count + 1, columns];
432      var rowCount = 0;
433      var maximization = IsMaximization();
434
435      var colNames = new string[columns];
436      colNames[0] = colNames[colNames.Length - 1] = string.Empty;
437      for (var i = 0; i < targets.Length; i++) {
438        colNames[i + 1] = maximization ? (targets[targets.Length - 1] / targets[i] - 1).ToString("0.0%")
439                                       : (targets[i] / targets[targets.Length - 1] - 1).ToString("0.0%");
440        matrix[rowCount, 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.Item1;
447        var bestSucc = string.Empty;
448        for (var i = 0; i < targets.Length; i++) {
449          string succ;
450          matrix[rowCount, i + 1] = CalculateExpectedRunTime(group.Item2, targets[i], maximization, out succ);
451          if (i == targets.Length - 1) bestSucc = succ;
452        }
453        matrix[rowCount, columns - 1] = bestSucc;
454        rowCount++;
455      }
456      ertViewHost.Content = new StringMatrix(matrix) { ColumnNames = colNames };
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      var maximization = IsMaximization();
503
504      foreach (var group in groupedRuns) {
505        var hits = new Dictionary<string, SortedList<double, double>>();
506
507        foreach (var run in group.Item2) {
508          var resultsTable = (IndexedDataTable<double>)run.Results[table];
509
510          if (eachOrAllBudgetsCheckBox.Checked) {
511            CalculateHitsForEachBudget(hits, resultsTable.Rows.First(), maximization, group.Item2.Count, group.Item1);
512          } else {
513            CalculateHitsForAllBudgets(hits, resultsTable.Rows.First(), maximization, group.Item2.Count, group.Item1);
514          }
515        }
516
517        foreach (var list in hits) {
518          var row = new IndexedDataRow<double>(list.Key) {
519            VisualProperties = {
520              ChartType = DataRowVisualProperties.DataRowChartType.StepLine,
521              LineWidth = 2,
522              Color = colors[colorCount],
523              LineStyle = lineStyles[lineStyleCount]
524            }
525          };
526
527          var total = 0.0;
528          foreach (var h in list.Value) {
529            total += h.Value;
530            row.Values.Add(Tuple.Create(h.Key, total));
531          }
532
533          byCostDataTable.Rows.Add(row);
534        }
535        colorCount = (colorCount + 1) % colors.Length;
536        if (colorCount == 0) lineStyleCount = (lineStyleCount + 1) % lineStyles.Length;
537      }
538
539      byCostDataTable.VisualProperties.XAxisTitle = "Targets";
540      byCostDataTable.VisualProperties.XAxisLogScale = byCostDataTable.Rows.Count > 0 && budgetLogScalingCheckBox.Checked;
541    }
542
543    private void GenerateDefaultBudgets(string table) {
544      var runs = GroupRuns().SelectMany(x => x.Item2).ToList();
545      var min = runs.Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Select(y => y.Item1).Min()).Min();
546      var max = runs.Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Select(y => y.Item1).Max()).Max();
547
548      var maxMagnitude = (int)Math.Ceiling(Math.Log10(max));
549      var minMagnitude = (int)Math.Floor(Math.Log10(min));
550      if (maxMagnitude - minMagnitude >= 3) {
551        budgets = new double[maxMagnitude - minMagnitude];
552        for (var i = minMagnitude; i < maxMagnitude; i++) {
553          budgets[i - minMagnitude] = Math.Pow(10, i);
554        }
555      } else {
556        var range = max - min;
557        budgets = Enumerable.Range(0, 6).Select(x => min + (x / 5.0) * range).ToArray();
558      }
559      suppressBudgetsEvents = true;
560      budgetsTextBox.Text = string.Join(" ; ", budgets);
561      suppressBudgetsEvents = false;
562    }
563
564    private void CalculateHitsForEachBudget(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, bool maximization, int groupCount, string groupName) {
565      foreach (var b in budgets) {
566        var key = groupName + "-" + b;
567        if (!hits.ContainsKey(key)) hits.Add(key, new SortedList<double, double>());
568        Tuple<double, double> prev = null;
569        foreach (var v in row.Values) {
570          if (v.Item1 >= b) {
571            // the budget may be too low to achieve any target
572            if (prev == null && v.Item1 != b) break;
573            var tgt = (prev == null || v.Item1 == b) ? v.Item2 : prev.Item2;
574            if (hits[key].ContainsKey(tgt))
575              hits[key][tgt] += 1.0 / groupCount;
576            else hits[key][tgt] = 1.0 / groupCount;
577            break;
578          }
579          prev = v;
580        }
581        if (hits[key].Count == 0) hits.Remove(key);
582      }
583    }
584
585    private void CalculateHitsForAllBudgets(Dictionary<string, SortedList<double, double>> hits, IndexedDataRow<double> row, bool maximization, int groupCount, string groupName) {
586      var values = row.Values;
587      if (!hits.ContainsKey(groupName)) hits.Add(groupName, new SortedList<double, double>());
588
589      var i = 0;
590      var j = 0;
591      Tuple<double, double> prev = null;
592      while (i < budgets.Length && j < values.Count) {
593        var current = values[j];
594        if (current.Item1 >= budgets[i]) {
595          if (prev != null || current.Item1 == budgets[i]) {
596            var tgt = (prev == null || current.Item1 == budgets[i]) ? current.Item2 : prev.Item2;
597            if (!hits[groupName].ContainsKey(tgt)) hits[groupName][tgt] = 0;
598            hits[groupName][tgt] += 1.0 / (groupCount * budgets.Length);
599          }
600          i++;
601        } else {
602          j++;
603          prev = current;
604        }
605      }
606      var lastTgt = values.Last().Item2;
607      if (i < budgets.Length && !hits[groupName].ContainsKey(lastTgt)) hits[groupName][lastTgt] = 0;
608      while (i < budgets.Length) {
609        hits[groupName][lastTgt] += 1.0 / (groupCount * budgets.Length);
610        i++;
611      }
612    }
613    #endregion
614
615    private void UpdateCaption() {
616      Caption = Content != null ? Content.OptimizerName + " RLD View" : ViewAttribute.GetViewName(GetType());
617    }
618
619    private void groupComboBox_SelectedIndexChanged(object sender, EventArgs e) {
620      UpdateRuns();
621      SetEnabledStateOfControls();
622    }
623    private void problemComboBox_SelectedIndexChanged(object sender, EventArgs e) {
624      if (dataTableComboBox.SelectedIndex >= 0)
625        GenerateDefaultTargets((string)dataTableComboBox.SelectedItem);
626      UpdateRuns();
627      SetEnabledStateOfControls();
628    }
629    private void dataTableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
630      if (dataTableComboBox.SelectedIndex >= 0)
631        GenerateDefaultBudgets((string)dataTableComboBox.SelectedItem);
632      UpdateRuns();
633      SetEnabledStateOfControls();
634    }
635
636    private void logScalingCheckBox_CheckedChanged(object sender, EventArgs e) {
637      byTargetDataTable.VisualProperties.XAxisLogScale = byTargetDataTable.Rows.Count > 0 && targetLogScalingCheckBox.Checked;
638      byCostDataTable.VisualProperties.XAxisLogScale = byCostDataTable.Rows.Count > 0 && budgetLogScalingCheckBox.Checked;
639    }
640
641    #region Event handlers for target analysis
642    private bool suppressTargetsEvents;
643    private void targetsTextBox_Validating(object sender, CancelEventArgs e) {
644      if (suppressTargetsEvents) return;
645      var targetStrings = targetsTextBox.Text.Split(new[] { ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
646      var targetList = new List<double>();
647      foreach (var ts in targetStrings) {
648        double t;
649        if (!double.TryParse(ts, out t)) {
650          errorProvider.SetError(targetsTextBox, "Not all targets can be parsed: " + ts);
651          e.Cancel = true;
652          return;
653        }
654        targetList.Add(t);
655      }
656      if (targetList.Count == 0) {
657        errorProvider.SetError(targetsTextBox, "Give at least one target value!");
658        e.Cancel = true;
659        return;
660      }
661      e.Cancel = false;
662      errorProvider.SetError(targetsTextBox, null);
663      targets = targetList.ToArray();
664      UpdateResultsByTarget();
665      SetEnabledStateOfControls();
666    }
667
668    private void eachOrAllTargetCheckBox_CheckedChanged(object sender, EventArgs e) {
669      var each = eachOrAllTargetCheckBox.Checked;
670      eachOrAllTargetCheckBox.Text = each ? "each" : "all";
671      SuspendRepaint();
672      try {
673        UpdateResultsByTarget();
674      } finally { ResumeRepaint(true); }
675    }
676
677    private void generateTargetsButton_Click(object sender, EventArgs e) {
678      var maximization = IsMaximization();
679      decimal max = 1, min = 0, count = 10;
680      if (targets != null) {
681        max = (decimal)targets.Max();
682        min = (decimal)targets.Min();
683        count = targets.Length;
684      } else if (Content.Count > 0 && dataTableComboBox.SelectedIndex >= 0) {
685        var table = (string)dataTableComboBox.SelectedItem;
686        max = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Max(y => y.Item2)).Max();
687        min = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Min(y => y.Item2)).Min();
688        count = 6;
689      }
690      using (var dialog = new DefineArithmeticProgressionDialog(false, min, max, (max - min) / count)) {
691        if (dialog.ShowDialog() == DialogResult.OK) {
692          if (dialog.Values.Any()) {
693            targets = maximization ? dialog.Values.Select(x => (double)x).ToArray()
694                                  : dialog.Values.Reverse().Select(x => (double)x).ToArray();
695            suppressTargetsEvents = true;
696            targetsTextBox.Text = string.Join(" ; ", targets);
697            suppressTargetsEvents = false;
698
699            UpdateResultsByTarget();
700            SetEnabledStateOfControls();
701          }
702        }
703      }
704    }
705
706    private void addTargetsAsResultButton_Click(object sender, EventArgs e) {
707      var table = (string)dataTableComboBox.SelectedItem;
708      var maximization = IsMaximization();
709      foreach (var run in Content) {
710        if (!run.Results.ContainsKey(table)) continue;
711        var resultsTable = (IndexedDataTable<double>)run.Results[table];
712        var values = resultsTable.Rows.First().Values;
713        var i = 0;
714        var j = 0;
715        while (i < targets.Length && j < values.Count) {
716          var current = values[j];
717          if (maximization && current.Item2 >= targets[i]
718              || !maximization && current.Item2 <= targets[i]) {
719            run.Results[table + ".Target" + targets[i]] = new DoubleValue(current.Item1);
720            i++;
721          } else {
722            j++;
723          }
724        }
725      }
726    }
727    #endregion
728
729    #region Event handlers for cost analysis
730    private bool suppressBudgetsEvents;
731    private void budgetsTextBox_Validating(object sender, CancelEventArgs e) {
732      if (suppressBudgetsEvents) return;
733      var budgetStrings = budgetsTextBox.Text.Split(new[] { ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
734      var budgetList = new List<double>();
735      foreach (var ts in budgetStrings) {
736        double b;
737        if (!double.TryParse(ts, out b)) {
738          errorProvider.SetError(budgetsTextBox, "Not all targets can be parsed: " + ts);
739          e.Cancel = true;
740          return;
741        }
742        budgetList.Add(b);
743      }
744      if (budgetList.Count == 0) {
745        errorProvider.SetError(budgetsTextBox, "Give at least one target value!");
746        e.Cancel = true;
747        return;
748      }
749      e.Cancel = false;
750      errorProvider.SetError(budgetsTextBox, null);
751      budgets = budgetList.ToArray();
752      UpdateResultsByCost();
753      SetEnabledStateOfControls();
754    }
755
756    private void eachOrAllBudgetsCheckBox_CheckedChanged(object sender, EventArgs e) {
757      var each = eachOrAllBudgetsCheckBox.Checked;
758      eachOrAllBudgetsCheckBox.Text = each ? "each" : "all";
759      SuspendRepaint();
760      try {
761        UpdateResultsByCost();
762      } finally { ResumeRepaint(true); }
763    }
764
765    private void generateBudgetsButton_Click(object sender, EventArgs e) {
766      decimal max = 1, min = 0, count = 10;
767      if (budgets != null) {
768        max = (decimal)budgets.Max();
769        min = (decimal)budgets.Min();
770        count = budgets.Length;
771      } else if (Content.Count > 0 && dataTableComboBox.SelectedIndex >= 0) {
772        var table = (string)dataTableComboBox.SelectedItem;
773        min = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Min(y => y.Item1)).Min();
774        max = (decimal)Content.Where(x => x.Results.ContainsKey(table)).Select(x => ((IndexedDataTable<double>)x.Results[table]).Rows.First().Values.Max(y => y.Item1)).Max();
775        count = 6;
776      }
777      using (var dialog = new DefineArithmeticProgressionDialog(false, min, max, (max - min) / count)) {
778        if (dialog.ShowDialog() == DialogResult.OK) {
779          if (dialog.Values.Any()) {
780            budgets = dialog.Values.OrderBy(x => x).Select(x => (double)x).ToArray();
781
782            suppressBudgetsEvents = true;
783            budgetsTextBox.Text = string.Join(" ; ", budgets);
784            suppressBudgetsEvents = false;
785
786            UpdateResultsByCost();
787            SetEnabledStateOfControls();
788          }
789        }
790      }
791    }
792
793    private void addBudgetsAsResultButton_Click(object sender, EventArgs e) {
794      var table = (string)dataTableComboBox.SelectedItem;
795      var budgetStrings = budgetsTextBox.Text.Split(new[] { ';', '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries);
796      if (budgetStrings.Length == 0) {
797        MessageBox.Show("Define a number of budgets.");
798        return;
799      }
800      var budgetList = new List<double>();
801      foreach (var bs in budgetStrings) {
802        double v;
803        if (!double.TryParse(bs, out v)) {
804          MessageBox.Show("Budgets must be a valid number: " + bs);
805          return;
806        }
807        budgetList.Add(v);
808      }
809      budgetList.Sort();
810
811      foreach (var run in Content) {
812        if (!run.Results.ContainsKey(table)) continue;
813        var resultsTable = (IndexedDataTable<double>)run.Results[table];
814        var values = resultsTable.Rows.First().Values;
815        var i = 0;
816        var j = 0;
817        Tuple<double, double> prev = null;
818        while (i < budgetList.Count && j < values.Count) {
819          var current = values[j];
820          if (current.Item1 >= budgetList[i]) {
821            if (prev != null || current.Item1 == budgetList[i]) {
822              var tgt = (prev == null || current.Item1 == budgetList[i]) ? current.Item2 : prev.Item2;
823              run.Results[table + ".Cost" + budgetList[i]] = new DoubleValue(tgt);
824            }
825            i++;
826          } else {
827            j++;
828            prev = current;
829          }
830        }
831      }
832    }
833    #endregion
834
835    #region Helpers
836    // Determines if the RunCollection contains maximization or minimization runs
837    private bool IsMaximization() {
838      if (Content == null) return false;
839      if (Content.Count > 0) {
840        foreach (var run in Content.Where(x => x.Parameters.ContainsKey("Maximization")
841                                            && x.Parameters["Maximization"] is BoolValue)) {
842          if (((BoolValue)run.Parameters["Maximization"]).Value) {
843            return true;
844          } else {
845            return false;
846          }
847        }
848        if (dataTableComboBox.SelectedIndex >= 0) {
849          var selectedTable = (string)dataTableComboBox.SelectedItem;
850          foreach (var run in Content.Where(x => x.Results.ContainsKey(selectedTable))) {
851            var table = run.Results[selectedTable] as IndexedDataTable<double>;
852            if (table == null) continue;
853            var firstRowValues = table.Rows.First().Values;
854            if (firstRowValues.Count < 2) continue;
855            return firstRowValues[0].Item2 < firstRowValues[firstRowValues.Count - 1].Item2;
856          }
857        }
858      }
859      // assume minimization by default
860      return false;
861    }
862    #endregion
863
864
865    private class ProblemDescription {
866      private readonly bool matchAll;
867      public static readonly ProblemDescription MatchAll = new ProblemDescription();
868
869      private ProblemDescription() {
870        ProblemType = string.Empty;
871        ProblemName = string.Empty;
872        Evaluator = string.Empty;
873        DisplayProblemType = false;
874        DisplayProblemName = false;
875        DisplayEvaluator = false;
876        matchAll = true;
877      }
878
879      public ProblemDescription(IRun run) {
880        ProblemType = GetStringValueOrEmpty(run, "Problem Type");
881        ProblemName = GetStringValueOrEmpty(run, "Problem Name");
882        Evaluator = GetStringValueOrEmpty(run, "Evaluator");
883        DisplayProblemType = !string.IsNullOrEmpty(ProblemType);
884        DisplayProblemName = !string.IsNullOrEmpty(ProblemName);
885        DisplayEvaluator = !string.IsNullOrEmpty(Evaluator);
886        matchAll = false;
887      }
888
889      public bool DisplayProblemType { get; set; }
890      public string ProblemType { get; set; }
891      public bool DisplayProblemName { get; set; }
892      public string ProblemName { get; set; }
893      public bool DisplayEvaluator { get; set; }
894      public string Evaluator { get; set; }
895
896      public bool Match(IRun run) {
897        return matchAll ||
898               GetStringValueOrEmpty(run, "Problem Type") == ProblemType
899               && GetStringValueOrEmpty(run, "Problem Name") == ProblemName
900               && GetStringValueOrEmpty(run, "Evaluator") == Evaluator;
901      }
902
903      private string GetStringValueOrEmpty(IRun run, string key) {
904        return run.Parameters.ContainsKey(key) ? ((StringValue)run.Parameters[key]).Value : string.Empty;
905      }
906
907      public override bool Equals(object obj) {
908        var other = obj as ProblemDescription;
909        if (other == null) return false;
910        return ProblemType == other.ProblemType
911               && ProblemName == other.ProblemName
912               && Evaluator == other.Evaluator;
913      }
914
915      public override int GetHashCode() {
916        return ProblemType.GetHashCode() ^ ProblemName.GetHashCode() ^ Evaluator.GetHashCode();
917      }
918
919      public override string ToString() {
920        return string.Join("  --  ", new[] {
921          (DisplayProblemType ? ProblemType : string.Empty),
922          (DisplayProblemName ? ProblemName : string.Empty),
923          (DisplayEvaluator ? Evaluator : string.Empty) }.Where(x => !string.IsNullOrEmpty(x)));
924      }
925    }
926  }
927}
Note: See TracBrowser for help on using the repository browser.