Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2031

  • made operations in ChartAnalysisView asynchronous
  • renamed views to go along with the other RunCollection views
File size: 12.4 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 Progress progress;
51    private ProgressView progressView;
52    private bool valuesAdded = false;
53
54    public ChartAnalysisView() {
55      InitializeComponent();
56      progress = new Progress() {
57        CanBeCanceled = false,
58        ProgressState = ProgressState.Finished
59      };
60      progressView = new ProgressView(this, progress);
61
62      stringConvertibleMatrixView.DataGridView.RowHeaderMouseDoubleClick += new DataGridViewCellMouseEventHandler(DataGridView_RowHeaderMouseDoubleClick);
63
64      var fittingAlgs = ApplicationManager.Manager.GetInstances<IFitting>();
65      foreach (var fit in fittingAlgs) {
66        fittingComboBox.Items.Add(fit);
67      }
68      fittingComboBox.SelectedIndex = 0;
69    }
70
71    /// <summary>
72    /// Clean up any resources being used.
73    /// </summary>
74    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
75    protected override void Dispose(bool disposing) {
76      if (disposing && (components != null)) {
77        stringConvertibleMatrixView.DataGridView.RowHeaderMouseDoubleClick -= new DataGridViewCellMouseEventHandler(DataGridView_RowHeaderMouseDoubleClick);
78        components.Dispose();
79      }
80      if (disposing)
81        progressView.Dispose();
82      base.Dispose(disposing);
83    }
84
85    #region Content Events
86    protected override void OnContentChanged() {
87      base.OnContentChanged();
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 += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
99      Content.ItemsRemoved += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
100      Content.CollectionReset += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
101      Content.UpdateOfRunsInProgressChanged += Content_UpdateOfRunsInProgressChanged;
102    }
103
104    protected override void DeregisterContentEvents() {
105      base.DeregisterContentEvents();
106      Content.ItemsAdded -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
107      Content.ItemsRemoved -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
108      Content.CollectionReset -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
109      Content.UpdateOfRunsInProgressChanged -= Content_UpdateOfRunsInProgressChanged;
110    }
111
112    private void Content_CollectionReset(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
113      RebuildDataTableAsync();
114    }
115
116    private void Content_ItemsRemoved(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
117      RebuildDataTableAsync();
118    }
119
120    private void Content_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
121      RebuildDataTableAsync();
122    }
123
124    void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
125      if (!Content.UpdateOfRunsInProgress && !valuesAdded) {
126        RebuildDataTableAsync();
127      }
128      if (valuesAdded) {
129        valuesAdded = false;
130      }
131    }
132    #endregion
133
134    #region Events
135    void DataGridView_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
136      if (e.RowIndex >= 0) {
137        IRun run = runs[stringConvertibleMatrixView.GetRowIndex(e.RowIndex)];
138        IContentView view = MainFormManager.MainForm.ShowContent(run);
139        if (view != null) {
140          view.ReadOnly = this.ReadOnly;
141          view.Locked = this.Locked;
142        }
143      }
144    }
145
146    private void dataTableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
147      UpdateDataRowComboBox();
148    }
149
150    private void dataRowComboBox_SelectedIndexChanged(object sender, EventArgs e) {
151      RebuildDataTableAsync();
152    }
153
154    private void addLineToChart_Click(object sender, EventArgs e) {
155      progress.Status = "Adding fitted lines to charts...";
156      progress.ProgressState = ProgressState.Started;
157      progress.ProgressValue = 0.0;
158
159      var task = System.Threading.Tasks.Task.Factory.StartNew(AddLineToChart);
160
161      task.ContinueWith((t) => {
162        progress.Finish();
163        ErrorHandling.ShowErrorDialog("An error occured while adding lines to charts. ", t.Exception);
164      }, TaskContinuationOptions.OnlyOnFaulted);
165
166      task.ContinueWith((t) => {
167        progress.Finish();
168      }, TaskContinuationOptions.OnlyOnRanToCompletion);
169    }
170
171    private void AddLineToChart() {
172      string resultName = (string)dataTableComboBox.SelectedItem;
173      string rowName = (string)dataRowComboBox.SelectedItem;
174
175      foreach (IRun run in runs) {
176        DataTable resTable = (DataTable)run.Results[resultName];
177        DataRow row = resTable.Rows[rowName];
178        var values = row.Values.ToArray();
179
180        var fittingAlg = fittingComboBox.SelectedItem as IFitting;
181        DataRow newRow = fittingAlg.CalculateFittedLine(values, row.Name + " (" + fittingAlg.ToString() + ")");
182
183        if (!resTable.Rows.ContainsKey(newRow.Name))
184          resTable.Rows.Add(newRow);
185      }
186    }
187
188    private void addValuesButton_Click(object sender, EventArgs e) {
189      string resultName = (string)dataTableComboBox.SelectedItem;
190      string rowName = (string)dataRowComboBox.SelectedItem;
191      DoubleMatrix sm = (DoubleMatrix)stringConvertibleMatrixView.Content;
192
193      Content.UpdateOfRunsInProgress = true;
194      for (int i = 0; i < runs.Count(); i++) {
195        IRun run = runs[i];
196
197        for (int j = 0; j < sm.ColumnNames.Count(); j++) {
198          if (stringConvertibleMatrixView.DataGridView.Columns[j].Visible) {
199            string newResultName = resultName + " " + rowName + " " + sm.ColumnNames.ElementAt(j);
200            if (!run.Results.ContainsKey(newResultName)) {
201              run.Results.Add(new KeyValuePair<string, Core.IItem>(newResultName, new DoubleValue(sm[i, j])));
202            }
203          }
204        }
205      }
206      valuesAdded = true;
207      Content.UpdateOfRunsInProgress = false;
208    }
209    #endregion
210
211    private void UpdateDataRowComboBox() {
212      dataRowComboBox.Items.Clear();
213      var resultName = (string)dataTableComboBox.SelectedItem;
214      var dataTables = from run in Content
215                       where run.Results.ContainsKey(resultName)
216                       select run.Results[resultName] as DataTable;
217      var rowNames = (from dataTable in dataTables
218                      from row in dataTable.Rows
219                      select row.Name).Distinct().ToArray();
220
221      dataRowComboBox.Items.AddRange(rowNames);
222      if (dataRowComboBox.Items.Count > 0) dataRowComboBox.SelectedItem = dataRowComboBox.Items[0];
223    }
224
225    private void UpdateDataTableComboBox() {
226      dataTableComboBox.Items.Clear();
227      var dataTables = (from run in Content
228                        from result in run.Results
229                        where result.Value is DataTable
230                        select result.Key).Distinct().ToArray();
231
232      dataTableComboBox.Items.AddRange(dataTables);
233      if (dataTableComboBox.Items.Count > 0) dataTableComboBox.SelectedItem = dataTableComboBox.Items[0];
234    }
235
236    private void RebuildDataTableAsync() {
237      progress.Status = "Calculating values...";
238      progress.ProgressState = ProgressState.Started;
239      progress.ProgressValue = 0.0;
240
241      var task = System.Threading.Tasks.Task.Factory.StartNew(RebuildDataTable);
242
243      task.ContinueWith((t) => {
244        progress.Finish();
245        ErrorHandling.ShowErrorDialog("An error occured while calculating values. ", t.Exception);
246      }, TaskContinuationOptions.OnlyOnFaulted);
247
248      task.ContinueWith((t) => {
249        progress.Finish();
250      }, TaskContinuationOptions.OnlyOnRanToCompletion);
251    }
252
253    private void RebuildDataTable() {
254      string resultName = (string)dataTableComboBox.SelectedItem;
255      string rowName = (string)dataRowComboBox.SelectedItem;
256      LinearLeastSquaresFitting llsFitting = new LinearLeastSquaresFitting();
257      LogFitting logFitting = new LogFitting();
258      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" };
259
260      runs = Content.Where(x => x.Results.ContainsKey(resultName) && x.Visible).ToList();
261      DoubleMatrix dt = new DoubleMatrix(runs.Count(), columnNames.Count());
262      dt.RowNames = runs.Select(x => x.Name);
263      dt.ColumnNames = columnNames;
264
265      int i = 0;
266      foreach (Run run in runs) {
267        DataTable resTable = (DataTable)run.Results[resultName];
268        dt.SortableView = true;
269        DataRow row = resTable.Rows[rowName];
270        var values = row.Values.AsEnumerable();
271
272        double cnt = values.Count();
273        double min = values.Min();
274        double max = values.Max();
275        double avg = values.Average();
276        double median = values.Median();
277        double stdDev = values.StandardDeviation();
278        double variance = values.Variance();
279        double percentile25 = values.Percentile(0.25);
280        double percentile75 = values.Percentile(0.75);
281        double lowerAvg = values.OrderBy(x => x).Take((int)(values.Count() * 0.25)).Average();
282        double upperAvg = values.OrderByDescending(x => x).Take((int)(values.Count() * 0.25)).Average();
283        double firstAvg = values.Take((int)(values.Count() * 0.25)).Average();
284        double lastAvg = values.Skip((int)(values.Count() * 0.75)).Average();
285        double k, d, r, a, b;
286        llsFitting.Calculate(values.ToArray(), out k, out d);
287        r = llsFitting.CalculateError(values.ToArray(), k, d);
288        logFitting.Calculate(values.ToArray(), out a, out b);
289
290        dt[i, 0] = cnt;
291        dt[i, 1] = min;
292        dt[i, 2] = max;
293        dt[i, 3] = avg;
294        dt[i, 4] = median;
295        dt[i, 5] = stdDev;
296        dt[i, 6] = variance;
297        dt[i, 7] = percentile25;
298        dt[i, 8] = percentile75;
299        dt[i, 9] = upperAvg;
300        dt[i, 10] = lowerAvg;
301        dt[i, 11] = firstAvg;
302        dt[i, 12] = lastAvg;
303        dt[i, 13] = k;
304        dt[i, 14] = r;
305        dt[i, 15] = a;
306        dt[i, 16] = b;
307
308        i++;
309      }
310      stringConvertibleMatrixView.Content = dt;
311
312      for (i = 0; i < runs.Count(); i++) {
313        stringConvertibleMatrixView.DataGridView.Rows[i].DefaultCellStyle.ForeColor = runs[i].Color;
314      }
315    }
316  }
317}
Note: See TracBrowser for help on using the repository browser.