Free cookie consent management tool by TermsFeed Policy Generator

source: branches/StatisticalTesting/HeuristicLab.Analysis.Statistics/3.3/ChartAnalysisView.cs @ 11378

Last change on this file since 11378 was 11378, checked in by ascheibe, 10 years ago

#2031 improved correlation view and some clean ups

File size: 13.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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.Linq;
25using System.Threading.Tasks;
26using System.Windows.Forms;
27using HeuristicLab.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Core.Views;
31using HeuristicLab.Data;
32using HeuristicLab.MainForm;
33using HeuristicLab.Optimization;
34using HeuristicLab.PluginInfrastructure;
35
36namespace HeuristicLab.Analysis.Statistics {
37  [View("Chart Analysis", "HeuristicLab.Analysis.Statistics.InfoResources.ChartAnalysisInfo.rtf")]
38  [Content(typeof(RunCollection), false)]
39  public sealed partial class ChartAnalysisView : ItemView {
40    public new RunCollection Content {
41      get { return (RunCollection)base.Content; }
42      set { base.Content = value; }
43    }
44
45    public override bool ReadOnly {
46      get { return true; }
47      set { /*not needed because results are always readonly */}
48    }
49
50    private List<IRun> runs;
51    private IProgress progress;
52    private bool valuesAdded = false;
53    private bool suppressUpdates = false;
54
55    public ChartAnalysisView() {
56      InitializeComponent();
57
58      stringConvertibleMatrixView.DataGridView.RowHeaderMouseDoubleClick += new DataGridViewCellMouseEventHandler(DataGridView_RowHeaderMouseDoubleClick);
59
60      var fittingAlgs = ApplicationManager.Manager.GetInstances<IFitting>();
61      foreach (var fit in fittingAlgs) {
62        fittingComboBox.Items.Add(fit);
63      }
64      fittingComboBox.SelectedIndex = 0;
65    }
66
67    protected override void Dispose(bool disposing) {
68      if (disposing && (components != null)) {
69        stringConvertibleMatrixView.DataGridView.RowHeaderMouseDoubleClick -= new DataGridViewCellMouseEventHandler(DataGridView_RowHeaderMouseDoubleClick);
70        components.Dispose();
71      }
72
73      base.Dispose(disposing);
74    }
75
76    #region Content Events
77    protected override void OnContentChanged() {
78      base.OnContentChanged();
79      UpdateComboboxes();
80      UpdateCaption();
81    }
82
83    private void UpdateCaption() {
84      Caption = Content != null ? Content.OptimizerName + " Chart Analysis" : ViewAttribute.GetViewName(GetType());
85    }
86
87    private void UpdateComboboxes() {
88      dataTableComboBox.Items.Clear();
89      dataRowComboBox.Items.Clear();
90
91      if (Content != null) {
92        UpdateDataTableComboBox();
93      }
94    }
95
96    protected override void RegisterContentEvents() {
97      base.RegisterContentEvents();
98      Content.ItemsAdded += Content_ItemsAdded;
99      Content.ItemsRemoved += Content_ItemsRemoved;
100      Content.CollectionReset += Content_CollectionReset;
101      Content.UpdateOfRunsInProgressChanged += Content_UpdateOfRunsInProgressChanged;
102      RegisterRunEvents(Content);
103    }
104
105    protected override void DeregisterContentEvents() {
106      base.DeregisterContentEvents();
107      Content.ItemsAdded -= Content_ItemsAdded;
108      Content.ItemsRemoved -= Content_ItemsRemoved;
109      Content.CollectionReset -= Content_CollectionReset;
110      Content.UpdateOfRunsInProgressChanged -= Content_UpdateOfRunsInProgressChanged;
111      DeregisterRunEvents(Content);
112    }
113
114    private void RegisterRunEvents(IEnumerable<IRun> runs) {
115      foreach (IRun run in runs) {
116        RegisterRunResultsEvents(run);
117      }
118    }
119
120    private void DeregisterRunEvents(IEnumerable<IRun> runs) {
121      foreach (IRun run in runs) {
122        DeregisterRunResultsEvents(run);
123      }
124    }
125
126    private void RegisterRunResultsEvents(IRun run) {
127      IObservableDictionary<string, IItem> dict = run.Results;
128      dict.ItemsAdded += run_Changed;
129      dict.ItemsRemoved += run_Changed;
130      dict.ItemsReplaced += run_Changed;
131      dict.CollectionReset += run_Changed;
132    }
133
134    private void DeregisterRunResultsEvents(IRun run) {
135      IObservableDictionary<string, IItem> dict = run.Results;
136      dict.ItemsAdded -= run_Changed;
137      dict.ItemsRemoved -= run_Changed;
138      dict.ItemsReplaced -= run_Changed;
139      dict.CollectionReset -= run_Changed;
140    }
141
142    private void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
143      DeregisterRunEvents(e.OldItems);
144      RegisterRunEvents(e.Items);
145      UpdateComboboxes();
146      RebuildDataTableAsync();
147    }
148
149    private void Content_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
150      DeregisterRunEvents(e.Items);
151      RebuildDataTableAsync();
152    }
153
154    private void Content_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
155      RegisterRunEvents(e.Items);
156      RebuildDataTableAsync();
157    }
158
159    private void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
160      suppressUpdates = Content.UpdateOfRunsInProgress;
161
162      if (!suppressUpdates && !valuesAdded) {
163        RebuildDataTableAsync();
164      }
165      if (valuesAdded) {
166        valuesAdded = false;
167      }
168    }
169
170    private void run_Changed(object sender, EventArgs e) {
171      if (InvokeRequired)
172        Invoke(new EventHandler(run_Changed), sender, e);
173      else if (!suppressUpdates) {
174        UpdateComboboxes();
175      }
176    }
177    #endregion
178
179    #region Events
180    private void DataGridView_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
181      if (e.RowIndex >= 0) {
182        IRun run = runs[stringConvertibleMatrixView.GetRowIndex(e.RowIndex)];
183        IContentView view = MainFormManager.MainForm.ShowContent(run);
184        if (view != null) {
185          view.ReadOnly = this.ReadOnly;
186          view.Locked = this.Locked;
187        }
188      }
189    }
190
191    private void dataTableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
192      UpdateDataRowComboBox();
193    }
194
195    private void dataRowComboBox_SelectedIndexChanged(object sender, EventArgs e) {
196      RebuildDataTableAsync();
197    }
198
199    private void addLineToChart_Click(object sender, EventArgs e) {
200      MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToView(this, "Adding fitted lines to charts...");
201
202      var task = Task.Factory.StartNew(AddLineToChart);
203
204      task.ContinueWith((t) => {
205        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
206        ErrorHandling.ShowErrorDialog("An error occured while adding lines to charts. ", t.Exception);
207      }, TaskContinuationOptions.OnlyOnFaulted);
208
209      task.ContinueWith((t) => {
210        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
211      }, TaskContinuationOptions.OnlyOnRanToCompletion);
212    }
213
214    private void AddLineToChart() {
215      string resultName = (string)dataTableComboBox.SelectedItem;
216      string rowName = (string)dataRowComboBox.SelectedItem;
217
218      foreach (IRun run in runs) {
219        DataTable resTable = (DataTable)run.Results[resultName];
220        DataRow row = resTable.Rows[rowName];
221        var values = row.Values.ToArray();
222
223        var fittingAlg = fittingComboBox.SelectedItem as IFitting;
224        DataRow newRow = fittingAlg.CalculateFittedLine(values, row.Name + " (" + fittingAlg.ToString() + ")");
225
226        if (!resTable.Rows.ContainsKey(newRow.Name))
227          resTable.Rows.Add(newRow);
228      }
229    }
230
231    private void addValuesButton_Click(object sender, EventArgs e) {
232      string resultName = (string)dataTableComboBox.SelectedItem;
233      string rowName = (string)dataRowComboBox.SelectedItem;
234      DoubleMatrix sm = (DoubleMatrix)stringConvertibleMatrixView.Content;
235
236      Content.UpdateOfRunsInProgress = true;
237      for (int i = 0; i < runs.Count(); i++) {
238        IRun run = runs[i];
239
240        for (int j = 0; j < sm.ColumnNames.Count(); j++) {
241          if (stringConvertibleMatrixView.DataGridView.Columns[j].Visible) {
242            string newResultName = resultName + " " + rowName + " " + sm.ColumnNames.ElementAt(j);
243            if (!run.Results.ContainsKey(newResultName)) {
244              run.Results.Add(new KeyValuePair<string, Core.IItem>(newResultName, new DoubleValue(sm[i, j])));
245            }
246          }
247        }
248      }
249      valuesAdded = true;
250      Content.UpdateOfRunsInProgress = false;
251    }
252    #endregion
253
254    private void UpdateDataRowComboBox() {
255      dataRowComboBox.Items.Clear();
256      var resultName = (string)dataTableComboBox.SelectedItem;
257      var dataTables = from run in Content
258                       where run.Results.ContainsKey(resultName)
259                       select run.Results[resultName] as DataTable;
260      var rowNames = (from dataTable in dataTables
261                      from row in dataTable.Rows
262                      select row.Name).Distinct().ToArray();
263
264      dataRowComboBox.Items.AddRange(rowNames);
265      if (dataRowComboBox.Items.Count > 0) dataRowComboBox.SelectedItem = dataRowComboBox.Items[0];
266    }
267
268    private void UpdateDataTableComboBox() {
269      dataTableComboBox.Items.Clear();
270      var dataTables = (from run in Content
271                        from result in run.Results
272                        where result.Value is DataTable
273                        select result.Key).Distinct().ToArray();
274
275      dataTableComboBox.Items.AddRange(dataTables);
276      if (dataTableComboBox.Items.Count > 0) dataTableComboBox.SelectedItem = dataTableComboBox.Items[0];
277    }
278
279    private void RebuildDataTableAsync() {
280      progress = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToView(this, "Calculating values...");
281
282      var task = Task.Factory.StartNew(RebuildDataTable);
283
284      task.ContinueWith((t) => {
285        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
286        ErrorHandling.ShowErrorDialog("An error occured while calculating values. ", t.Exception);
287      }, TaskContinuationOptions.OnlyOnFaulted);
288
289      task.ContinueWith((t) => {
290        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
291      }, TaskContinuationOptions.OnlyOnRanToCompletion);
292    }
293
294    private void RebuildDataTable() {
295      string resultName = (string)dataTableComboBox.SelectedItem;
296      string rowName = (string)dataRowComboBox.SelectedItem;
297      LinearLeastSquaresFitting llsFitting = new LinearLeastSquaresFitting();
298      LogFitting logFitting = new LogFitting();
299      string[] columnNames = new string[] { "Count", "Minimum", "Maximum", "Average", "Median", "Standard Deviation", "Variance", "25th Percentile", "75th Percentile",
300        "Avg. of Upper 25 %", " Avg. of Lower 25 %", "Avg. of First 25 %", "Avg. of Last 25 %", "Linear Gradient", "Relative Error", "a (log fitted)", "b (log fitted)" };
301
302      runs = Content.Where(x => x.Results.ContainsKey(resultName) && x.Visible).ToList();
303      DoubleMatrix dt = new DoubleMatrix(runs.Count(), columnNames.Count());
304      dt.RowNames = runs.Select(x => x.Name);
305      dt.ColumnNames = columnNames;
306
307      int i = 0;
308      foreach (Run run in runs) {
309        DataTable resTable = (DataTable)run.Results[resultName];
310        dt.SortableView = true;
311        DataRow row = resTable.Rows[rowName];
312        var values = row.Values.AsEnumerable();
313
314        double cnt = values.Count();
315        double min = values.Min();
316        double max = values.Max();
317        double avg = values.Average();
318        double median = values.Median();
319        double stdDev = values.StandardDeviation();
320        double variance = values.Variance();
321        double percentile25 = values.Percentile(0.25);
322        double percentile75 = values.Percentile(0.75);
323        double lowerAvg = values.OrderBy(x => x).Take((int)(values.Count() * 0.25)).Average();
324        double upperAvg = values.OrderByDescending(x => x).Take((int)(values.Count() * 0.25)).Average();
325        double firstAvg = values.Take((int)(values.Count() * 0.25)).Average();
326        double lastAvg = values.Skip((int)(values.Count() * 0.75)).Average();
327        double k, d, r, a, b;
328        llsFitting.Calculate(values.ToArray(), out k, out d);
329        r = llsFitting.CalculateError(values.ToArray(), k, d);
330        logFitting.Calculate(values.ToArray(), out a, out b);
331
332        dt[i, 0] = cnt;
333        dt[i, 1] = min;
334        dt[i, 2] = max;
335        dt[i, 3] = avg;
336        dt[i, 4] = median;
337        dt[i, 5] = stdDev;
338        dt[i, 6] = variance;
339        dt[i, 7] = percentile25;
340        dt[i, 8] = percentile75;
341        dt[i, 9] = upperAvg;
342        dt[i, 10] = lowerAvg;
343        dt[i, 11] = firstAvg;
344        dt[i, 12] = lastAvg;
345        dt[i, 13] = k;
346        dt[i, 14] = r;
347        dt[i, 15] = a;
348        dt[i, 16] = b;
349
350        i++;
351        progress.ProgressValue = ((double)runs.Count) / i;
352      }
353      stringConvertibleMatrixView.Content = dt;
354
355      for (i = 0; i < runs.Count(); i++) {
356        stringConvertibleMatrixView.DataGridView.Rows[i].DefaultCellStyle.ForeColor = runs[i].Color;
357      }
358    }
359  }
360}
Note: See TracBrowser for help on using the repository browser.