Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11379 was 11379, checked in by ascheibe, 8 years ago

#2031 fixed some bugs

File size: 14.1 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      if (Content != null) {
89        UpdateDataTableComboBox();
90      }
91    }
92
93    protected override void RegisterContentEvents() {
94      base.RegisterContentEvents();
95      Content.ItemsAdded += Content_ItemsAdded;
96      Content.ItemsRemoved += Content_ItemsRemoved;
97      Content.CollectionReset += Content_CollectionReset;
98      Content.UpdateOfRunsInProgressChanged += Content_UpdateOfRunsInProgressChanged;
99      RegisterRunEvents(Content);
100    }
101
102    protected override void DeregisterContentEvents() {
103      base.DeregisterContentEvents();
104      Content.ItemsAdded -= Content_ItemsAdded;
105      Content.ItemsRemoved -= Content_ItemsRemoved;
106      Content.CollectionReset -= Content_CollectionReset;
107      Content.UpdateOfRunsInProgressChanged -= Content_UpdateOfRunsInProgressChanged;
108      DeregisterRunEvents(Content);
109    }
110
111    private void RegisterRunEvents(IEnumerable<IRun> runs) {
112      foreach (IRun run in runs) {
113        RegisterRunResultsEvents(run);
114      }
115    }
116
117    private void DeregisterRunEvents(IEnumerable<IRun> runs) {
118      foreach (IRun run in runs) {
119        DeregisterRunResultsEvents(run);
120      }
121    }
122
123    private void RegisterRunResultsEvents(IRun run) {
124      IObservableDictionary<string, IItem> dict = run.Results;
125      dict.ItemsAdded += run_Changed;
126      dict.ItemsRemoved += run_Changed;
127      dict.ItemsReplaced += run_Changed;
128      dict.CollectionReset += run_Changed;
129    }
130
131    private void DeregisterRunResultsEvents(IRun run) {
132      IObservableDictionary<string, IItem> dict = run.Results;
133      dict.ItemsAdded -= run_Changed;
134      dict.ItemsRemoved -= run_Changed;
135      dict.ItemsReplaced -= run_Changed;
136      dict.CollectionReset -= run_Changed;
137    }
138
139    private void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
140      DeregisterRunEvents(e.OldItems);
141      RegisterRunEvents(e.Items);
142      UpdateComboboxes();
143      RebuildDataTableAsync();
144    }
145
146    private void Content_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
147      DeregisterRunEvents(e.Items);
148      RebuildDataTableAsync();
149    }
150
151    private void Content_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
152      RegisterRunEvents(e.Items);
153      RebuildDataTableAsync();
154    }
155
156    private void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
157      suppressUpdates = Content.UpdateOfRunsInProgress;
158
159      if (!suppressUpdates && !valuesAdded) {
160        RebuildDataTableAsync();
161      }
162      if (valuesAdded) {
163        valuesAdded = false;
164      }
165    }
166
167    private void run_Changed(object sender, EventArgs e) {
168      if (InvokeRequired)
169        Invoke(new EventHandler(run_Changed), sender, e);
170      else if (!suppressUpdates) {
171        UpdateComboboxes();
172      }
173    }
174    #endregion
175
176    #region Events
177    private void DataGridView_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
178      if (e.RowIndex >= 0) {
179        IRun run = runs[stringConvertibleMatrixView.GetRowIndex(e.RowIndex)];
180        IContentView view = MainFormManager.MainForm.ShowContent(run);
181        if (view != null) {
182          view.ReadOnly = this.ReadOnly;
183          view.Locked = this.Locked;
184        }
185      }
186    }
187
188    private void dataTableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
189      UpdateDataRowComboBox();
190    }
191
192    private void dataRowComboBox_SelectedIndexChanged(object sender, EventArgs e) {
193      RebuildDataTableAsync();
194    }
195
196    private void addLineToChart_Click(object sender, EventArgs e) {
197      MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToView(this, "Adding fitted lines to charts...");
198
199      string resultName = (string)dataTableComboBox.SelectedItem;
200      string rowName = (string)dataRowComboBox.SelectedItem;
201
202      var task = Task.Factory.StartNew(() => AddLineToChart(resultName, rowName));
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(string resultName, string rowName) {
215      foreach (IRun run in runs) {
216        DataTable resTable = (DataTable)run.Results[resultName];
217        DataRow row = resTable.Rows[rowName];
218        var values = row.Values.ToArray();
219
220        var fittingAlg = fittingComboBox.SelectedItem as IFitting;
221        DataRow newRow = fittingAlg.CalculateFittedLine(values, row.Name + " (" + fittingAlg.ToString() + ")");
222
223        if (!resTable.Rows.ContainsKey(newRow.Name))
224          resTable.Rows.Add(newRow);
225      }
226    }
227
228    private void addValuesButton_Click(object sender, EventArgs e) {
229      string resultName = (string)dataTableComboBox.SelectedItem;
230      string rowName = (string)dataRowComboBox.SelectedItem;
231      DoubleMatrix sm = (DoubleMatrix)stringConvertibleMatrixView.Content;
232
233      Content.UpdateOfRunsInProgress = true;
234      for (int i = 0; i < runs.Count(); i++) {
235        IRun run = runs[i];
236
237        for (int j = 0; j < sm.ColumnNames.Count(); j++) {
238          if (stringConvertibleMatrixView.DataGridView.Columns[j].Visible) {
239            string newResultName = resultName + " " + rowName + " " + sm.ColumnNames.ElementAt(j);
240            if (!run.Results.ContainsKey(newResultName)) {
241              run.Results.Add(new KeyValuePair<string, Core.IItem>(newResultName, new DoubleValue(sm[i, j])));
242            }
243          }
244        }
245      }
246      valuesAdded = true;
247      Content.UpdateOfRunsInProgress = false;
248    }
249    #endregion
250
251    private void UpdateDataRowComboBox() {
252      string selectedItem = (string)this.dataRowComboBox.SelectedItem;
253
254      dataRowComboBox.Items.Clear();
255      var resultName = (string)dataTableComboBox.SelectedItem;
256      var dataTables = from run in Content
257                       where run.Results.ContainsKey(resultName)
258                       select run.Results[resultName] as DataTable;
259      var rowNames = (from dataTable in dataTables
260                      from row in dataTable.Rows
261                      select row.Name).Distinct().ToArray();
262
263      dataRowComboBox.Items.AddRange(rowNames);
264      if (selectedItem != null && dataRowComboBox.Items.Contains(selectedItem)) {
265        dataRowComboBox.SelectedItem = selectedItem;
266      } else if (dataRowComboBox.Items.Count > 0) {
267        dataRowComboBox.SelectedItem = dataRowComboBox.Items[0];
268      }
269    }
270
271    private void UpdateDataTableComboBox() {
272      string selectedItem = (string)this.dataTableComboBox.SelectedItem;
273
274      dataTableComboBox.Items.Clear();
275      var dataTables = (from run in Content
276                        from result in run.Results
277                        where result.Value is DataTable
278                        select result.Key).Distinct().ToArray();
279
280      dataTableComboBox.Items.AddRange(dataTables);
281      if (selectedItem != null && dataTableComboBox.Items.Contains(selectedItem)) {
282        dataTableComboBox.SelectedItem = selectedItem;
283      } else if (dataTableComboBox.Items.Count > 0) {
284        dataTableComboBox.SelectedItem = dataTableComboBox.Items[0];
285      }
286    }
287
288    private void RebuildDataTableAsync() {
289      progress = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToView(this, "Calculating values...");
290
291      string resultName = (string)dataTableComboBox.SelectedItem;
292      string rowName = (string)dataRowComboBox.SelectedItem;
293
294      var task = Task.Factory.StartNew(() => RebuildDataTable(resultName, rowName));
295
296      task.ContinueWith((t) => {
297        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
298        ErrorHandling.ShowErrorDialog("An error occured while calculating values. ", t.Exception);
299      }, TaskContinuationOptions.OnlyOnFaulted);
300
301      task.ContinueWith((t) => {
302        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
303      }, TaskContinuationOptions.OnlyOnRanToCompletion);
304    }
305
306    private void RebuildDataTable(string resultName, string rowName) {
307      LinearLeastSquaresFitting llsFitting = new LinearLeastSquaresFitting();
308      LogFitting logFitting = new LogFitting();
309      string[] columnNames = new string[] { "Count", "Minimum", "Maximum", "Average", "Median", "Standard Deviation", "Variance", "25th Percentile", "75th Percentile",
310        "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)" };
311
312      runs = Content.Where(x => x.Results.ContainsKey(resultName) && x.Visible).ToList();
313      DoubleMatrix dt = new DoubleMatrix(runs.Count(), columnNames.Count());
314      dt.RowNames = runs.Select(x => x.Name);
315      dt.ColumnNames = columnNames;
316
317      int i = 0;
318      foreach (Run run in runs) {
319        DataTable resTable = (DataTable)run.Results[resultName];
320        dt.SortableView = true;
321        DataRow row = resTable.Rows[rowName];
322        var values = row.Values.AsEnumerable();
323
324        double cnt = values.Count();
325        double min = values.Min();
326        double max = values.Max();
327        double avg = values.Average();
328        double median = values.Median();
329        double stdDev = values.StandardDeviation();
330        double variance = values.Variance();
331        double percentile25 = values.Percentile(0.25);
332        double percentile75 = values.Percentile(0.75);
333        double lowerAvg = values.OrderBy(x => x).Take((int)(values.Count() * 0.25)).Average();
334        double upperAvg = values.OrderByDescending(x => x).Take((int)(values.Count() * 0.25)).Average();
335        double firstAvg = values.Take((int)(values.Count() * 0.25)).Average();
336        double lastAvg = values.Skip((int)(values.Count() * 0.75)).Average();
337        double k, d, r, a, b;
338        llsFitting.Calculate(values.ToArray(), out k, out d);
339        r = llsFitting.CalculateError(values.ToArray(), k, d);
340        logFitting.Calculate(values.ToArray(), out a, out b);
341
342        dt[i, 0] = cnt;
343        dt[i, 1] = min;
344        dt[i, 2] = max;
345        dt[i, 3] = avg;
346        dt[i, 4] = median;
347        dt[i, 5] = stdDev;
348        dt[i, 6] = variance;
349        dt[i, 7] = percentile25;
350        dt[i, 8] = percentile75;
351        dt[i, 9] = upperAvg;
352        dt[i, 10] = lowerAvg;
353        dt[i, 11] = firstAvg;
354        dt[i, 12] = lastAvg;
355        dt[i, 13] = k;
356        dt[i, 14] = r;
357        dt[i, 15] = a;
358        dt[i, 16] = b;
359
360        i++;
361        progress.ProgressValue = ((double)runs.Count) / i;
362      }
363      stringConvertibleMatrixView.Content = dt;
364
365      for (i = 0; i < runs.Count(); i++) {
366        stringConvertibleMatrixView.DataGridView.Rows[i].DefaultCellStyle.ForeColor = runs[i].Color;
367      }
368    }
369  }
370}
Note: See TracBrowser for help on using the repository browser.