Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2708_ScopedAlgorithms/HeuristicLab.Analysis.Statistics.Views/3.3/ChartAnalysisView.cs @ 18242

Last change on this file since 18242 was 13051, checked in by gkronber, 9 years ago

#2491: removed usage of Percentile extension method

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