Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2457: added line annotations to the network visu to highlight close solutions

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