Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Analysis.Statistics.Views/3.3/ChartAnalysisView.cs @ 12599

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

#2270: Fixed several of the runcollection views

  • Added InvokeRequired checks where missing
  • Added suppressUpdates check where missing
  • Fixed some bugs, added some null checks
File size: 13.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.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.Views {
37  [View("Chart Analysis", "HeuristicLab.Analysis.Statistics.Views.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 += 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 -= 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.ColumnsChanged += Content_ColumnsChanged;
96      Content.RowsChanged += Content_RowsChanged;
97      Content.CollectionReset += Content_CollectionReset;
98      Content.UpdateOfRunsInProgressChanged += Content_UpdateOfRunsInProgressChanged;
99    }
100
101    protected override void DeregisterContentEvents() {
102      base.DeregisterContentEvents();
103      Content.ColumnsChanged -= Content_ColumnsChanged;
104      Content.RowsChanged -= Content_RowsChanged;
105      Content.CollectionReset -= Content_CollectionReset;
106      Content.UpdateOfRunsInProgressChanged -= Content_UpdateOfRunsInProgressChanged;
107    }
108
109    void Content_RowsChanged(object sender, EventArgs e) {
110      if (suppressUpdates) return;
111      if (InvokeRequired) Invoke((Action<object, EventArgs>)Content_RowsChanged, sender, e);
112      else {
113        RebuildDataTableAsync();
114      }
115    }
116
117    void Content_ColumnsChanged(object sender, EventArgs e) {
118      if (suppressUpdates) return;
119      if (InvokeRequired) Invoke((Action<object, EventArgs>)Content_ColumnsChanged, sender, e);
120      else {
121        RebuildDataTableAsync();
122      }
123    }
124
125    private void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
126      if (suppressUpdates) return;
127      if (InvokeRequired) Invoke((Action<object, CollectionItemsChangedEventArgs<IRun>>)Content_CollectionReset, sender, e);
128      else {
129        UpdateComboboxes();
130        RebuildDataTableAsync();
131      }
132    }
133
134    private void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
135      if (InvokeRequired) Invoke((Action<object, EventArgs>)Content_UpdateOfRunsInProgressChanged, sender, e);
136      else {
137        suppressUpdates = Content.UpdateOfRunsInProgress;
138
139        if (!suppressUpdates && !valuesAdded) {
140          RebuildDataTableAsync();
141        }
142        if (valuesAdded) {
143          valuesAdded = false;
144        }
145      }
146    }
147    #endregion
148
149    #region events
150    private void DataGridView_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
151      if (e.RowIndex >= 0) {
152        IRun run = runs[stringConvertibleMatrixView.GetRowIndex(e.RowIndex)];
153        IContentView view = MainFormManager.MainForm.ShowContent(run);
154        if (view != null) {
155          view.ReadOnly = this.ReadOnly;
156          view.Locked = this.Locked;
157        }
158      }
159    }
160
161    private void dataTableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
162      UpdateDataRowComboBox();
163    }
164
165    private void dataRowComboBox_SelectedIndexChanged(object sender, EventArgs e) {
166      RebuildDataTableAsync();
167    }
168
169    private void addLineToChart_Click(object sender, EventArgs e) {
170      MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToView(this, "Adding fitted lines to charts...");
171
172      string resultName = (string)dataTableComboBox.SelectedItem;
173      string rowName = (string)dataRowComboBox.SelectedItem;
174
175      var task = Task.Factory.StartNew(() => AddLineToChart(resultName, rowName));
176
177      task.ContinueWith((t) => {
178        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
179        ErrorHandling.ShowErrorDialog("An error occured while adding lines to charts. ", t.Exception);
180      }, TaskContinuationOptions.OnlyOnFaulted);
181
182      task.ContinueWith((t) => {
183        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
184      }, TaskContinuationOptions.OnlyOnRanToCompletion);
185    }
186
187    private void AddLineToChart(string resultName, string rowName) {
188      foreach (IRun run in runs) {
189        DataTable resTable = (DataTable)run.Results[resultName];
190        DataRow row = resTable.Rows[rowName];
191        var values = row.Values.ToArray();
192
193        var fittingAlg = fittingComboBox.SelectedItem as IFitting;
194        DataRow newRow = fittingAlg.CalculateFittedLine(values);
195        newRow.Name = row.Name + " (" + fittingAlg + ")";
196
197        if (!resTable.Rows.ContainsKey(newRow.Name))
198          resTable.Rows.Add(newRow);
199      }
200    }
201
202    private void addValuesButton_Click(object sender, EventArgs e) {
203      string resultName = (string)dataTableComboBox.SelectedItem;
204      string rowName = (string)dataRowComboBox.SelectedItem;
205      DoubleMatrix sm = (DoubleMatrix)stringConvertibleMatrixView.Content;
206
207      Content.UpdateOfRunsInProgress = true;
208      for (int i = 0; i < runs.Count(); i++) {
209        IRun run = runs[i];
210
211        for (int j = 0; j < sm.ColumnNames.Count(); j++) {
212          if (stringConvertibleMatrixView.DataGridView.Columns[j].Visible) {
213            string newResultName = resultName + " " + rowName + " " + sm.ColumnNames.ElementAt(j);
214            if (!run.Results.ContainsKey(newResultName)) {
215              run.Results.Add(new KeyValuePair<string, IItem>(newResultName, new DoubleValue(sm[i, j])));
216            }
217          }
218        }
219      }
220      valuesAdded = true;
221      Content.UpdateOfRunsInProgress = false;
222    }
223    #endregion
224
225    private void UpdateDataRowComboBox() {
226      string selectedItem = (string)this.dataRowComboBox.SelectedItem;
227
228      dataRowComboBox.Items.Clear();
229      var resultName = (string)dataTableComboBox.SelectedItem;
230      var dataTables = from run in Content
231                       where run.Results.ContainsKey(resultName)
232                       select run.Results[resultName] as DataTable;
233      var rowNames = (from dataTable in dataTables
234                      from row in dataTable.Rows
235                      select row.Name).Distinct().ToArray();
236
237      dataRowComboBox.Items.AddRange(rowNames);
238      if (selectedItem != null && dataRowComboBox.Items.Contains(selectedItem)) {
239        dataRowComboBox.SelectedItem = selectedItem;
240      } else if (dataRowComboBox.Items.Count > 0) {
241        dataRowComboBox.SelectedItem = dataRowComboBox.Items[0];
242      }
243    }
244
245    private void UpdateDataTableComboBox() {
246      string selectedItem = (string)this.dataTableComboBox.SelectedItem;
247
248      dataTableComboBox.Items.Clear();
249      var dataTables = (from run in Content
250                        from result in run.Results
251                        where result.Value is DataTable
252                        select result.Key).Distinct().ToArray();
253
254      dataTableComboBox.Items.AddRange(dataTables);
255      if (selectedItem != null && dataTableComboBox.Items.Contains(selectedItem)) {
256        dataTableComboBox.SelectedItem = selectedItem;
257      } else if (dataTableComboBox.Items.Count > 0) {
258        dataTableComboBox.SelectedItem = dataTableComboBox.Items[0];
259      }
260    }
261
262    private void RebuildDataTableAsync() {
263      string resultName = (string)dataTableComboBox.SelectedItem;
264      if (string.IsNullOrEmpty(resultName)) return;
265
266      string rowName = (string)dataRowComboBox.SelectedItem;
267
268      progress = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToView(this, "Calculating values...");
269      var task = Task.Factory.StartNew(() => RebuildDataTable(resultName, rowName));
270
271      task.ContinueWith((t) => {
272        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
273        ErrorHandling.ShowErrorDialog("An error occured while calculating values. ", t.Exception);
274      }, TaskContinuationOptions.OnlyOnFaulted);
275
276      task.ContinueWith((t) => {
277        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
278      }, TaskContinuationOptions.OnlyOnRanToCompletion);
279    }
280
281    private void RebuildDataTable(string resultName, string rowName) {
282      LinearLeastSquaresFitting llsFitting = new LinearLeastSquaresFitting();
283      string[] columnNames = new string[] { "Count", "Minimum", "Maximum", "Average", "Median", "Standard Deviation", "Variance", "25th Percentile", "75th Percentile",
284        "Avg. of Upper 25 %", " Avg. of Lower 25 %", "Avg. of First 25 %", "Avg. of Last 25 %", "Slope", "Intercept", "Average Relative Error" };
285
286      runs = Content.Where(x => x.Results.ContainsKey(resultName) && x.Visible).ToList();
287      DoubleMatrix dt = new DoubleMatrix(runs.Count(), columnNames.Count());
288      dt.RowNames = runs.Select(x => x.Name);
289      dt.ColumnNames = columnNames;
290
291      int i = 0;
292      foreach (Run run in runs) {
293        DataTable resTable = (DataTable)run.Results[resultName];
294        dt.SortableView = true;
295        DataRow row = resTable.Rows[rowName];
296        var values = row.Values.ToArray();
297
298        double cnt = values.Count();
299        double min = values.Min();
300        double max = values.Max();
301        double avg = values.Average();
302        double median = values.Median();
303        double stdDev = values.StandardDeviation();
304        double variance = values.Variance();
305        double percentile25 = values.Percentile(0.25);
306        double percentile75 = values.Percentile(0.75);
307        double lowerAvg = values.Count() > 4 ? values.OrderBy(x => x).Take((int)(values.Count() * 0.25)).Average() : double.NaN;
308        double upperAvg = values.Count() > 4 ? values.OrderByDescending(x => x).Take((int)(values.Count() * 0.25)).Average() : double.NaN;
309        double firstAvg = values.Count() > 4 ? values.Take((int)(values.Count() * 0.25)).Average() : double.NaN;
310        double lastAvg = values.Count() > 4 ? values.Skip((int)(values.Count() * 0.75)).Average() : double.NaN;
311        double slope, intercept, r;
312        llsFitting.Calculate(values, out slope, out intercept);
313        r = llsFitting.CalculateError(values, slope, intercept);
314
315        dt[i, 0] = cnt;
316        dt[i, 1] = min;
317        dt[i, 2] = max;
318        dt[i, 3] = avg;
319        dt[i, 4] = median;
320        dt[i, 5] = stdDev;
321        dt[i, 6] = variance;
322        dt[i, 7] = percentile25;
323        dt[i, 8] = percentile75;
324        dt[i, 9] = upperAvg;
325        dt[i, 10] = lowerAvg;
326        dt[i, 11] = firstAvg;
327        dt[i, 12] = lastAvg;
328        dt[i, 13] = slope;
329        dt[i, 14] = intercept;
330        dt[i, 15] = r;
331
332        i++;
333        progress.ProgressValue = ((double)runs.Count) / i;
334      }
335      stringConvertibleMatrixView.Content = dt;
336
337      for (i = 0; i < runs.Count(); i++) {
338        stringConvertibleMatrixView.DataGridView.Rows[i].DefaultCellStyle.ForeColor = runs[i].Color;
339      }
340    }
341  }
342}
Note: See TracBrowser for help on using the repository browser.