Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2431: fixed analysis for runs that terminated earlier than others

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