Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2031 adapted views to new help system

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