Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 11376 was 11376, checked in by ascheibe, 10 years ago

#2031 fixed RunCollection event handling in ChartAnalysisView

File size: 14.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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 {
37  [View("Chart Analysis", "HeuristicLab.Analysis.Statistics.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 += new DataGridViewCellMouseEventHandler(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 -= new DataGridViewCellMouseEventHandler(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      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 += Content_ItemsAdded;
99      Content.ItemsRemoved += Content_ItemsRemoved;
100      Content.CollectionReset += Content_CollectionReset;
101      Content.UpdateOfRunsInProgressChanged += Content_UpdateOfRunsInProgressChanged;
102      RegisterRunEvents(Content);
103    }
104
105    protected override void DeregisterContentEvents() {
106      base.DeregisterContentEvents();
107      Content.ItemsAdded -= Content_ItemsAdded;
108      Content.ItemsRemoved -= Content_ItemsRemoved;
109      Content.CollectionReset -= Content_CollectionReset;
110      Content.UpdateOfRunsInProgressChanged -= Content_UpdateOfRunsInProgressChanged;
111      DeregisterRunEvents(Content);
112    }
113
114    private void RegisterRunEvents(IEnumerable<IRun> runs) {
115      foreach (IRun run in runs) {
116        RegisterRunParametersEvents(run);
117        RegisterRunResultsEvents(run);
118      }
119    }
120
121    private void DeregisterRunEvents(IEnumerable<IRun> runs) {
122      foreach (IRun run in runs) {
123        DeregisterRunParametersEvents(run);
124        DeregisterRunResultsEvents(run);
125      }
126    }
127
128    private void RegisterRunParametersEvents(IRun run) {
129      IObservableDictionary<string, IItem> dict = run.Parameters;
130      dict.ItemsAdded += run_Changed;
131      dict.ItemsRemoved += run_Changed;
132      dict.ItemsReplaced += run_Changed;
133      dict.CollectionReset += run_Changed;
134    }
135
136    private void RegisterRunResultsEvents(IRun run) {
137      IObservableDictionary<string, IItem> dict = run.Results;
138      dict.ItemsAdded += run_Changed;
139      dict.ItemsRemoved += run_Changed;
140      dict.ItemsReplaced += run_Changed;
141      dict.CollectionReset += run_Changed;
142    }
143
144    private void DeregisterRunParametersEvents(IRun run) {
145      IObservableDictionary<string, IItem> dict = run.Parameters;
146      dict.ItemsAdded -= run_Changed;
147      dict.ItemsRemoved -= run_Changed;
148      dict.ItemsReplaced -= run_Changed;
149      dict.CollectionReset -= run_Changed;
150    }
151
152    private void DeregisterRunResultsEvents(IRun run) {
153      IObservableDictionary<string, IItem> dict = run.Results;
154      dict.ItemsAdded -= run_Changed;
155      dict.ItemsRemoved -= run_Changed;
156      dict.ItemsReplaced -= run_Changed;
157      dict.CollectionReset -= run_Changed;
158    }
159
160    private void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
161      DeregisterRunEvents(e.OldItems);
162      RegisterRunEvents(e.Items);
163      UpdateComboboxes();
164      RebuildDataTableAsync();
165    }
166
167    private void Content_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRun> e) {
168      DeregisterRunEvents(e.Items);
169      RebuildDataTableAsync();
170    }
171
172    private void Content_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRun> e) {
173      RegisterRunEvents(e.Items);
174      RebuildDataTableAsync();
175    }
176
177    void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
178      suppressUpdates = Content.UpdateOfRunsInProgress;
179
180      if (!suppressUpdates && !valuesAdded) {
181        RebuildDataTableAsync();
182      }
183      if (valuesAdded) {
184        valuesAdded = false;
185      }
186    }
187
188    private void run_Changed(object sender, EventArgs e) {
189      if (InvokeRequired)
190        Invoke(new EventHandler(run_Changed), sender, e);
191      else if (!suppressUpdates) {
192        UpdateComboboxes();
193      }
194    }
195    #endregion
196
197    #region Events
198    void DataGridView_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
199      if (e.RowIndex >= 0) {
200        IRun run = runs[stringConvertibleMatrixView.GetRowIndex(e.RowIndex)];
201        IContentView view = MainFormManager.MainForm.ShowContent(run);
202        if (view != null) {
203          view.ReadOnly = this.ReadOnly;
204          view.Locked = this.Locked;
205        }
206      }
207    }
208
209    private void dataTableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
210      UpdateDataRowComboBox();
211    }
212
213    private void dataRowComboBox_SelectedIndexChanged(object sender, EventArgs e) {
214      RebuildDataTableAsync();
215    }
216
217    private void addLineToChart_Click(object sender, EventArgs e) {
218      MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToView(this, "Adding fitted lines to charts...");
219
220      var task = Task.Factory.StartNew(AddLineToChart);
221
222      task.ContinueWith((t) => {
223        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
224        ErrorHandling.ShowErrorDialog("An error occured while adding lines to charts. ", t.Exception);
225      }, TaskContinuationOptions.OnlyOnFaulted);
226
227      task.ContinueWith((t) => {
228        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
229      }, TaskContinuationOptions.OnlyOnRanToCompletion);
230    }
231
232    private void AddLineToChart() {
233      string resultName = (string)dataTableComboBox.SelectedItem;
234      string rowName = (string)dataRowComboBox.SelectedItem;
235
236      foreach (IRun run in runs) {
237        DataTable resTable = (DataTable)run.Results[resultName];
238        DataRow row = resTable.Rows[rowName];
239        var values = row.Values.ToArray();
240
241        var fittingAlg = fittingComboBox.SelectedItem as IFitting;
242        DataRow newRow = fittingAlg.CalculateFittedLine(values, row.Name + " (" + fittingAlg.ToString() + ")");
243
244        if (!resTable.Rows.ContainsKey(newRow.Name))
245          resTable.Rows.Add(newRow);
246      }
247    }
248
249    private void addValuesButton_Click(object sender, EventArgs e) {
250      string resultName = (string)dataTableComboBox.SelectedItem;
251      string rowName = (string)dataRowComboBox.SelectedItem;
252      DoubleMatrix sm = (DoubleMatrix)stringConvertibleMatrixView.Content;
253
254      Content.UpdateOfRunsInProgress = true;
255      for (int i = 0; i < runs.Count(); i++) {
256        IRun run = runs[i];
257
258        for (int j = 0; j < sm.ColumnNames.Count(); j++) {
259          if (stringConvertibleMatrixView.DataGridView.Columns[j].Visible) {
260            string newResultName = resultName + " " + rowName + " " + sm.ColumnNames.ElementAt(j);
261            if (!run.Results.ContainsKey(newResultName)) {
262              run.Results.Add(new KeyValuePair<string, Core.IItem>(newResultName, new DoubleValue(sm[i, j])));
263            }
264          }
265        }
266      }
267      valuesAdded = true;
268      Content.UpdateOfRunsInProgress = false;
269    }
270    #endregion
271
272    private void UpdateDataRowComboBox() {
273      dataRowComboBox.Items.Clear();
274      var resultName = (string)dataTableComboBox.SelectedItem;
275      var dataTables = from run in Content
276                       where run.Results.ContainsKey(resultName)
277                       select run.Results[resultName] as DataTable;
278      var rowNames = (from dataTable in dataTables
279                      from row in dataTable.Rows
280                      select row.Name).Distinct().ToArray();
281
282      dataRowComboBox.Items.AddRange(rowNames);
283      if (dataRowComboBox.Items.Count > 0) dataRowComboBox.SelectedItem = dataRowComboBox.Items[0];
284    }
285
286    private void UpdateDataTableComboBox() {
287      dataTableComboBox.Items.Clear();
288      var dataTables = (from run in Content
289                        from result in run.Results
290                        where result.Value is DataTable
291                        select result.Key).Distinct().ToArray();
292
293      dataTableComboBox.Items.AddRange(dataTables);
294      if (dataTableComboBox.Items.Count > 0) dataTableComboBox.SelectedItem = dataTableComboBox.Items[0];
295    }
296
297    private void RebuildDataTableAsync() {
298      progress = MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToView(this, "Calculating values...");
299
300      var task = Task.Factory.StartNew(RebuildDataTable);
301
302      task.ContinueWith((t) => {
303        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
304        ErrorHandling.ShowErrorDialog("An error occured while calculating values. ", t.Exception);
305      }, TaskContinuationOptions.OnlyOnFaulted);
306
307      task.ContinueWith((t) => {
308        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
309      }, TaskContinuationOptions.OnlyOnRanToCompletion);
310    }
311
312    private void RebuildDataTable() {
313      string resultName = (string)dataTableComboBox.SelectedItem;
314      string rowName = (string)dataRowComboBox.SelectedItem;
315      LinearLeastSquaresFitting llsFitting = new LinearLeastSquaresFitting();
316      LogFitting logFitting = new LogFitting();
317      string[] columnNames = new string[] { "Count", "Minimum", "Maximum", "Average", "Median", "Standard Deviation", "Variance", "25th Percentile", "75th Percentile",
318        "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)" };
319
320      runs = Content.Where(x => x.Results.ContainsKey(resultName) && x.Visible).ToList();
321      DoubleMatrix dt = new DoubleMatrix(runs.Count(), columnNames.Count());
322      dt.RowNames = runs.Select(x => x.Name);
323      dt.ColumnNames = columnNames;
324
325      int i = 0;
326      foreach (Run run in runs) {
327        DataTable resTable = (DataTable)run.Results[resultName];
328        dt.SortableView = true;
329        DataRow row = resTable.Rows[rowName];
330        var values = row.Values.AsEnumerable();
331
332        double cnt = values.Count();
333        double min = values.Min();
334        double max = values.Max();
335        double avg = values.Average();
336        double median = values.Median();
337        double stdDev = values.StandardDeviation();
338        double variance = values.Variance();
339        double percentile25 = values.Percentile(0.25);
340        double percentile75 = values.Percentile(0.75);
341        double lowerAvg = values.OrderBy(x => x).Take((int)(values.Count() * 0.25)).Average();
342        double upperAvg = values.OrderByDescending(x => x).Take((int)(values.Count() * 0.25)).Average();
343        double firstAvg = values.Take((int)(values.Count() * 0.25)).Average();
344        double lastAvg = values.Skip((int)(values.Count() * 0.75)).Average();
345        double k, d, r, a, b;
346        llsFitting.Calculate(values.ToArray(), out k, out d);
347        r = llsFitting.CalculateError(values.ToArray(), k, d);
348        logFitting.Calculate(values.ToArray(), out a, out b);
349
350        dt[i, 0] = cnt;
351        dt[i, 1] = min;
352        dt[i, 2] = max;
353        dt[i, 3] = avg;
354        dt[i, 4] = median;
355        dt[i, 5] = stdDev;
356        dt[i, 6] = variance;
357        dt[i, 7] = percentile25;
358        dt[i, 8] = percentile75;
359        dt[i, 9] = upperAvg;
360        dt[i, 10] = lowerAvg;
361        dt[i, 11] = firstAvg;
362        dt[i, 12] = lastAvg;
363        dt[i, 13] = k;
364        dt[i, 14] = r;
365        dt[i, 15] = a;
366        dt[i, 16] = b;
367
368        i++;
369        progress.ProgressValue = ((double)runs.Count) / i;
370      }
371      stringConvertibleMatrixView.Content = dt;
372
373      for (i = 0; i < runs.Count(); i++) {
374        stringConvertibleMatrixView.DataGridView.Rows[i].DefaultCellStyle.ForeColor = runs[i].Color;
375      }
376    }
377  }
378}
Note: See TracBrowser for help on using the repository browser.