Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 9904 was 9904, checked in by ascheibe, 11 years ago

#2031 updated chart analysis view to work with new progress handling

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