Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2839_HiveProjectManagement/HeuristicLab.Analysis.Statistics.Views/3.3/ChartAnalysisView.cs @ 16777

Last change on this file since 16777 was 16057, checked in by jkarder, 6 years ago

#2839:

File size: 13.6 KB
RevLine 
[9353]1#region License Information
2/* HeuristicLab
[16057]3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[9353]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;
[12631]25using System.Threading;
[9713]26using System.Threading.Tasks;
[9353]27using System.Windows.Forms;
[11376]28using HeuristicLab.Collections;
[9353]29using HeuristicLab.Common;
[11376]30using HeuristicLab.Core;
[9353]31using HeuristicLab.Core.Views;
32using HeuristicLab.Data;
33using HeuristicLab.MainForm;
34using HeuristicLab.Optimization;
[9706]35using HeuristicLab.PluginInfrastructure;
[9353]36
[11705]37namespace HeuristicLab.Analysis.Statistics.Views {
38  [View("Chart Analysis", "HeuristicLab.Analysis.Statistics.Views.InfoResources.ChartAnalysisInfo.rtf")]
[9353]39  [Content(typeof(RunCollection), false)]
[9377]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
[9378]51    private List<IRun> runs;
[9904]52    private IProgress progress;
[9713]53    private bool valuesAdded = false;
[11376]54    private bool suppressUpdates = false;
[12631]55    private SemaphoreSlim sem = new SemaphoreSlim(1, 1);
[9378]56
[9377]57    public ChartAnalysisView() {
[9353]58      InitializeComponent();
[9713]59
[11697]60      stringConvertibleMatrixView.DataGridView.RowHeaderMouseDoubleClick += DataGridView_RowHeaderMouseDoubleClick;
[9706]61
62      var fittingAlgs = ApplicationManager.Manager.GetInstances<IFitting>();
63      foreach (var fit in fittingAlgs) {
64        fittingComboBox.Items.Add(fit);
65      }
66      fittingComboBox.SelectedIndex = 0;
[9353]67    }
68
69    protected override void Dispose(bool disposing) {
70      if (disposing && (components != null)) {
[11697]71        stringConvertibleMatrixView.DataGridView.RowHeaderMouseDoubleClick -= DataGridView_RowHeaderMouseDoubleClick;
[9353]72        components.Dispose();
73      }
[9904]74
[9353]75      base.Dispose(disposing);
76    }
77
[9377]78    #region Content Events
[9353]79    protected override void OnContentChanged() {
80      base.OnContentChanged();
[11376]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() {
[9353]90      if (Content != null) {
91        UpdateDataTableComboBox();
92      }
93    }
94
95    protected override void RegisterContentEvents() {
96      base.RegisterContentEvents();
[11697]97      Content.ColumnsChanged += Content_ColumnsChanged;
98      Content.RowsChanged += Content_RowsChanged;
[11376]99      Content.CollectionReset += Content_CollectionReset;
[9378]100      Content.UpdateOfRunsInProgressChanged += Content_UpdateOfRunsInProgressChanged;
[9353]101    }
102
103    protected override void DeregisterContentEvents() {
104      base.DeregisterContentEvents();
[11697]105      Content.ColumnsChanged -= Content_ColumnsChanged;
106      Content.RowsChanged -= Content_RowsChanged;
[11376]107      Content.CollectionReset -= Content_CollectionReset;
[9378]108      Content.UpdateOfRunsInProgressChanged -= Content_UpdateOfRunsInProgressChanged;
[9353]109    }
110
[11697]111    void Content_RowsChanged(object sender, EventArgs e) {
[12599]112      if (suppressUpdates) return;
113      if (InvokeRequired) Invoke((Action<object, EventArgs>)Content_RowsChanged, sender, e);
114      else {
115        RebuildDataTableAsync();
116      }
[11376]117    }
118
[11697]119    void Content_ColumnsChanged(object sender, EventArgs e) {
[12599]120      if (suppressUpdates) return;
121      if (InvokeRequired) Invoke((Action<object, EventArgs>)Content_ColumnsChanged, sender, e);
122      else {
[12631]123        UpdateDataTableComboBox();
[12112]124        RebuildDataTableAsync();
125      }
[11376]126    }
127
128    private void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
[12599]129      if (suppressUpdates) return;
130      if (InvokeRequired) Invoke((Action<object, CollectionItemsChangedEventArgs<IRun>>)Content_CollectionReset, sender, e);
131      else {
132        UpdateComboboxes();
133        RebuildDataTableAsync();
134      }
[9353]135    }
136
[11378]137    private void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
[12599]138      if (InvokeRequired) Invoke((Action<object, EventArgs>)Content_UpdateOfRunsInProgressChanged, sender, e);
139      else {
140        suppressUpdates = Content.UpdateOfRunsInProgress;
[11376]141
[12599]142        if (!suppressUpdates && !valuesAdded) {
[12631]143          UpdateDataTableComboBox();
[12599]144          RebuildDataTableAsync();
145        }
146        if (valuesAdded) {
147          valuesAdded = false;
148        }
[9353]149      }
150    }
151    #endregion
152
[11697]153    #region events
[11378]154    private void DataGridView_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
[9377]155      if (e.RowIndex >= 0) {
[9378]156        IRun run = runs[stringConvertibleMatrixView.GetRowIndex(e.RowIndex)];
[9377]157        IContentView view = MainFormManager.MainForm.ShowContent(run);
158        if (view != null) {
159          view.ReadOnly = this.ReadOnly;
160          view.Locked = this.Locked;
161        }
162      }
[9353]163    }
164
165    private void dataTableComboBox_SelectedIndexChanged(object sender, EventArgs e) {
166      UpdateDataRowComboBox();
167    }
168
169    private void dataRowComboBox_SelectedIndexChanged(object sender, EventArgs e) {
[12631]170      if (suppressUpdates) return;
[9713]171      RebuildDataTableAsync();
[9353]172    }
173
[9377]174    private void addLineToChart_Click(object sender, EventArgs e) {
[11376]175      MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToView(this, "Adding fitted lines to charts...");
[9713]176
[11379]177      string resultName = (string)dataTableComboBox.SelectedItem;
178      string rowName = (string)dataRowComboBox.SelectedItem;
[9713]179
[11379]180      var task = Task.Factory.StartNew(() => AddLineToChart(resultName, rowName));
181
[9713]182      task.ContinueWith((t) => {
[11376]183        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
[9713]184        ErrorHandling.ShowErrorDialog("An error occured while adding lines to charts. ", t.Exception);
185      }, TaskContinuationOptions.OnlyOnFaulted);
186
187      task.ContinueWith((t) => {
[11376]188        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
[9713]189      }, TaskContinuationOptions.OnlyOnRanToCompletion);
190    }
191
[11379]192    private void AddLineToChart(string resultName, string rowName) {
[9378]193      foreach (IRun run in runs) {
[9377]194        DataTable resTable = (DataTable)run.Results[resultName];
195        DataRow row = resTable.Rows[rowName];
196        var values = row.Values.ToArray();
197
[9706]198        var fittingAlg = fittingComboBox.SelectedItem as IFitting;
[11914]199        DataRow newRow = fittingAlg.CalculateFittedLine(values);
200        newRow.Name = row.Name + " (" + fittingAlg + ")";
[9377]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;
[9378]210      DoubleMatrix sm = (DoubleMatrix)stringConvertibleMatrixView.Content;
[9377]211
212      Content.UpdateOfRunsInProgress = true;
213      for (int i = 0; i < runs.Count(); i++) {
[9378]214        IRun run = runs[i];
[9377]215
216        for (int j = 0; j < sm.ColumnNames.Count(); j++) {
[9378]217          if (stringConvertibleMatrixView.DataGridView.Columns[j].Visible) {
218            string newResultName = resultName + " " + rowName + " " + sm.ColumnNames.ElementAt(j);
219            if (!run.Results.ContainsKey(newResultName)) {
[11697]220              run.Results.Add(new KeyValuePair<string, IItem>(newResultName, new DoubleValue(sm[i, j])));
[9378]221            }
222          }
[9377]223        }
224      }
[9713]225      valuesAdded = true;
[9377]226      Content.UpdateOfRunsInProgress = false;
227    }
228    #endregion
229
[9353]230    private void UpdateDataRowComboBox() {
[11379]231      string selectedItem = (string)this.dataRowComboBox.SelectedItem;
232
[9353]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);
[11379]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      }
[9353]248    }
249
250    private void UpdateDataTableComboBox() {
[11379]251      string selectedItem = (string)this.dataTableComboBox.SelectedItem;
252
[9353]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);
[11379]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      }
[9353]265    }
266
[9713]267    private void RebuildDataTableAsync() {
[12599]268      string resultName = (string)dataTableComboBox.SelectedItem;
269      if (string.IsNullOrEmpty(resultName)) return;
[9713]270
[11379]271      string rowName = (string)dataRowComboBox.SelectedItem;
[9713]272
[12631]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      });
[11379]278
[9713]279      task.ContinueWith((t) => {
[11376]280        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
[9713]281        ErrorHandling.ShowErrorDialog("An error occured while calculating values. ", t.Exception);
[12631]282        sem.Release();
[9713]283      }, TaskContinuationOptions.OnlyOnFaulted);
284
285      task.ContinueWith((t) => {
[11376]286        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
[12631]287        sem.Release();
[9713]288      }, TaskContinuationOptions.OnlyOnRanToCompletion);
289    }
290
[11379]291    private void RebuildDataTable(string resultName, string rowName) {
[9713]292      LinearLeastSquaresFitting llsFitting = new LinearLeastSquaresFitting();
[9908]293      string[] columnNames = new string[] { "Count", "Minimum", "Maximum", "Average", "Median", "Standard Deviation", "Variance", "25th Percentile", "75th Percentile",
[11914]294        "Avg. of Upper 25 %", " Avg. of Lower 25 %", "Avg. of First 25 %", "Avg. of Last 25 %", "Slope", "Intercept", "Average Relative Error" };
[9353]295
[9378]296      runs = Content.Where(x => x.Results.ContainsKey(resultName) && x.Visible).ToList();
297      DoubleMatrix dt = new DoubleMatrix(runs.Count(), columnNames.Count());
[9353]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];
[9377]304        dt.SortableView = true;
[9353]305        DataRow row = resTable.Rows[rowName];
[11914]306        var values = row.Values.ToArray();
[9353]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();
[13051]315        double percentile25 = values.Quantile(0.25);
316        double percentile75 = values.Quantile(0.75);
[12117]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;
[11914]321        double slope, intercept, r;
322        llsFitting.Calculate(values, out slope, out intercept);
323        r = llsFitting.CalculateError(values, slope, intercept);
[9353]324
[9378]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;
[9713]334        dt[i, 9] = upperAvg;
335        dt[i, 10] = lowerAvg;
336        dt[i, 11] = firstAvg;
337        dt[i, 12] = lastAvg;
[11914]338        dt[i, 13] = slope;
339        dt[i, 14] = intercept;
340        dt[i, 15] = r;
[9353]341
342        i++;
[11376]343        progress.ProgressValue = ((double)runs.Count) / i;
[9353]344      }
[9378]345      stringConvertibleMatrixView.Content = dt;
[9353]346
[9378]347      for (i = 0; i < runs.Count(); i++) {
348        stringConvertibleMatrixView.DataGridView.Rows[i].DefaultCellStyle.ForeColor = runs[i].Color;
349      }
[9353]350    }
351  }
352}
Note: See TracBrowser for help on using the repository browser.