Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Analysis.Statistics.Views/3.3/StatisticalTestsView.cs @ 12782

Last change on this file since 12782 was 12690, checked in by ascheibe, 9 years ago

#2270 fixed cross-threading issues in run collection views

File size: 19.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Common.Resources;
30using HeuristicLab.Core.Views;
31using HeuristicLab.Data;
32using HeuristicLab.MainForm;
33using HeuristicLab.Optimization;
34using HeuristicLab.Optimization.Views;
35
36namespace HeuristicLab.Analysis.Statistics.Views {
37  [View("Statistical Tests", "HeuristicLab.Analysis.Statistics.Views.InfoResources.StatisticalTestsInfo.rtf")]
38  [Content(typeof(RunCollection), false)]
39  public sealed partial class StatisticalTestsView : ItemView, IConfigureableView {
40    private double significanceLevel = 0.05;
41    private const int requiredSampleSize = 5;
42    private double[][] data;
43    private bool suppressUpdates;
44    private bool initializing;
45
46    public double SignificanceLevel {
47      get { return significanceLevel; }
48      set {
49        if (!significanceLevel.IsAlmost(value)) {
50          significanceLevel = value;
51          ResetUI();
52          CalculateValues();
53        }
54      }
55    }
56
57    public new RunCollection Content {
58      get { return (RunCollection)base.Content; }
59      set { base.Content = value; }
60    }
61
62    public override bool ReadOnly {
63      get { return true; }
64      set { /*not needed because results are always readonly */}
65    }
66
67    public StatisticalTestsView() {
68      InitializeComponent();
69    }
70
71    public void ShowConfiguration() {
72      using (StatisticalTestsConfigurationDialog dlg = new StatisticalTestsConfigurationDialog(this)) {
73        dlg.ShowDialog(this);
74      }
75    }
76
77    protected override void OnContentChanged() {
78      base.OnContentChanged();
79
80      if (Content != null) {
81        UpdateUI();
82      } else {
83        ResetUI();
84      }
85      UpdateCaption();
86    }
87
88    private void UpdateUI() {
89      initializing = true;
90      UpdateResultComboBox();
91      UpdateGroupsComboBox();
92      RebuildDataTable();
93      FillCompComboBox();
94      ResetUI();
95      CalculateValues();
96      initializing = false;
97    }
98
99    private void UpdateCaption() {
100      Caption = Content != null ? Content.OptimizerName + " Statistical Tests" : ViewAttribute.GetViewName(GetType());
101    }
102
103    #region events
104    protected override void RegisterContentEvents() {
105      base.RegisterContentEvents();
106      Content.ColumnsChanged += Content_ColumnsChanged;
107      Content.RowsChanged += Content_RowsChanged;
108      Content.CollectionReset += Content_CollectionReset;
109      Content.UpdateOfRunsInProgressChanged += Content_UpdateOfRunsInProgressChanged;
110    }
111
112    protected override void DeregisterContentEvents() {
113      base.DeregisterContentEvents();
114      Content.ColumnsChanged -= Content_ColumnsChanged;
115      Content.RowsChanged -= Content_RowsChanged;
116      Content.CollectionReset -= Content_CollectionReset;
117      Content.UpdateOfRunsInProgressChanged -= Content_UpdateOfRunsInProgressChanged;
118    }
119
120    void Content_RowsChanged(object sender, EventArgs e) {
121      if (suppressUpdates) return;
122      if (InvokeRequired) Invoke((Action<object, EventArgs>)Content_RowsChanged, sender, e);
123      else {
124        UpdateUI();
125      }
126    }
127
128    void Content_ColumnsChanged(object sender, EventArgs e) {
129      if (suppressUpdates) return;
130      if (InvokeRequired) Invoke((Action<object, EventArgs>)Content_ColumnsChanged, sender, e);
131      else {
132        UpdateUI();
133      }
134    }
135
136    private void Content_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRun> e) {
137      if (suppressUpdates) return;
138      if (InvokeRequired) Invoke((Action<object, CollectionItemsChangedEventArgs<IRun>>)Content_CollectionReset, sender, e);
139      else {
140        UpdateUI();
141      }
142    }
143
144    void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
145      if (InvokeRequired) Invoke((Action<object, EventArgs>)Content_UpdateOfRunsInProgressChanged, sender, e);
146      else {
147        suppressUpdates = Content.UpdateOfRunsInProgress;
148        if (!suppressUpdates) UpdateUI();
149      }
150    }
151
152    private void openBoxPlotToolStripMenuItem_Click(object sender, EventArgs e) {
153      RunCollectionBoxPlotView boxplotView = new RunCollectionBoxPlotView();
154      boxplotView.Content = Content;
155      boxplotView.SetXAxis(groupComboBox.SelectedItem.ToString());
156      boxplotView.SetYAxis(resultComboBox.SelectedItem.ToString());
157
158      boxplotView.Show();
159    }
160
161    private void groupCompComboBox_SelectedValueChanged(object sender, EventArgs e) {
162      if (initializing || suppressUpdates) return;
163      string curItem = (string)groupCompComboBox.SelectedItem;
164      CalculatePairwise(curItem);
165    }
166
167    private void resultComboBox_SelectedValueChanged(object sender, EventArgs e) {
168      if (initializing || suppressUpdates) return;
169      RebuildDataTable();
170      ResetUI();
171      CalculateValues();
172    }
173
174    private void groupComboBox_SelectedValueChanged(object sender, EventArgs e) {
175      if (initializing || suppressUpdates) return;
176      RebuildDataTable();
177      FillCompComboBox();
178      ResetUI();
179      CalculateValues();
180    }
181    #endregion
182
183    private void UpdateGroupsComboBox() {
184      string selectedItem = (string)groupComboBox.SelectedItem;
185
186      groupComboBox.Items.Clear();
187      var parameters = (from run in Content
188                        where run.Visible
189                        from param in run.Parameters
190                        select param.Key).Distinct().ToArray();
191
192      foreach (var p in parameters) {
193        var variations = (from run in Content
194                          where run.Visible && run.Parameters.ContainsKey(p) &&
195                          (run.Parameters[p] is IntValue || run.Parameters[p] is DoubleValue ||
196                          run.Parameters[p] is StringValue || run.Parameters[p] is BoolValue)
197                          select ((dynamic)run.Parameters[p]).Value).Distinct();
198
199        if (variations.Count() > 1) {
200          groupComboBox.Items.Add(p);
201        }
202      }
203
204      if (groupComboBox.Items.Count > 0) {
205        //try to select something different than "Seed" or "Algorithm Name" as this makes no sense
206        //and takes a long time to group
207        List<int> possibleIndizes = new List<int>();
208        for (int i = 0; i < groupComboBox.Items.Count; i++) {
209          if (groupComboBox.Items[i].ToString() != "Seed"
210            && groupComboBox.Items[i].ToString() != "Algorithm Name") {
211            possibleIndizes.Add(i);
212          }
213        }
214
215        if (selectedItem != null && groupComboBox.Items.Contains(selectedItem)) {
216          groupComboBox.SelectedItem = selectedItem;
217        } else if (possibleIndizes.Count > 0) {
218          groupComboBox.SelectedItem = groupComboBox.Items[possibleIndizes.First()];
219        }
220      }
221    }
222
223    private string[] GetColumnNames(IEnumerable<IRun> runs) {
224      string parameterName = (string)groupComboBox.SelectedItem;
225      var r = runs.Where(x => x.Parameters.ContainsKey(parameterName));
226      return r.Select(x => ((dynamic)x.Parameters[parameterName]).Value).Distinct().Select(x => (string)x.ToString()).ToArray();
227    }
228
229    private void UpdateResultComboBox() {
230      string selectedItem = (string)resultComboBox.SelectedItem;
231
232      resultComboBox.Items.Clear();
233      var results = (from run in Content
234                     where run.Visible
235                     from result in run.Results
236                     where result.Value is IntValue || result.Value is DoubleValue
237                     select result.Key).Distinct().ToArray();
238
239      resultComboBox.Items.AddRange(results);
240
241      if (selectedItem != null && resultComboBox.Items.Contains(selectedItem)) {
242        resultComboBox.SelectedItem = selectedItem;
243      } else if (resultComboBox.Items.Count > 0) {
244        resultComboBox.SelectedItem = resultComboBox.Items[0];
245      }
246    }
247
248    private void FillCompComboBox() {
249      string selectedItem = (string)groupCompComboBox.SelectedItem;
250      string parameterName = (string)groupComboBox.SelectedItem;
251      if (parameterName != null) {
252        string resultName = (string)resultComboBox.SelectedItem;
253        if (resultName != null) {
254          var runs = Content.Where(x => x.Results.ContainsKey(resultName) && x.Visible);
255          var columnNames = GetColumnNames(runs).ToList();
256          groupCompComboBox.Items.Clear();
257          columnNames.ForEach(x => groupCompComboBox.Items.Add(x));
258          if (selectedItem != null && groupCompComboBox.Items.Contains(selectedItem)) {
259            groupCompComboBox.SelectedItem = selectedItem;
260          } else if (groupCompComboBox.Items.Count > 0) {
261            groupCompComboBox.SelectedItem = groupCompComboBox.Items[0];
262          }
263        }
264      }
265    }
266
267    private void RebuildDataTable() {
268      string parameterName = (string)groupComboBox.SelectedItem;
269      if (parameterName != null) {
270        string resultName = (string)resultComboBox.SelectedItem;
271
272        var runs = Content.Where(x => x.Results.ContainsKey(resultName) && x.Visible);
273        var columnNames = GetColumnNames(runs);
274        var groups = GetGroups(columnNames, runs);
275        data = new double[columnNames.Count()][];
276
277        DoubleMatrix dt = new DoubleMatrix(groups.Select(x => x.Count()).Max(), columnNames.Count());
278        dt.ColumnNames = columnNames;
279        DataTable histogramDataTable = new DataTable(resultName);
280
281        for (int i = 0; i < columnNames.Count(); i++) {
282          int j = 0;
283          data[i] = new double[groups[i].Count()];
284          DataRow row = new DataRow(columnNames[i]);
285          row.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Histogram;
286          histogramDataTable.Rows.Add(row);
287
288          foreach (IRun run in groups[i]) {
289            dt[j, i] = (double)((dynamic)run.Results[resultName]).Value;
290            data[i][j] = dt[j, i];
291            row.Values.Add(dt[j, i]);
292            j++;
293          }
294        }
295
296        GenerateChart(histogramDataTable);
297        stringConvertibleMatrixView.Content = dt;
298      }
299    }
300
301    private void GenerateChart(DataTable histogramTable) {
302      histogramControl.ClearPoints();
303      foreach (var row in histogramTable.Rows) {
304        histogramControl.AddPoints(row.Name, row.Values, true);
305      }
306    }
307
308    private List<IEnumerable<IRun>> GetGroups(string[] columnNames, IEnumerable<IRun> runs) {
309      List<IEnumerable<IRun>> runCols = new List<IEnumerable<IRun>>();
310      string parameterName = (string)groupComboBox.SelectedItem;
311
312      foreach (string cn in columnNames) {
313        var tmpRuns = runs.Where(x => ((string)((dynamic)x.Parameters[parameterName]).Value.ToString()) == cn);
314        runCols.Add(tmpRuns);
315      }
316
317      return runCols;
318    }
319
320    private void ResetUI() {
321      normalityLabel.Image = null;
322      normalityTextLabel.Text = string.Empty;
323      groupCompLabel.Image = null;
324      groupComTextLabel.Text = string.Empty;
325      pairwiseLabel.Image = null;
326      pairwiseTextLabel.Text = string.Empty;
327
328      pValTextBox.Text = string.Empty;
329      equalDistsTextBox.Text = string.Empty;
330    }
331
332    private bool VerifyDataLength(bool showMessage) {
333      if (data == null || data.Length == 0)
334        return false;
335
336      //alglib needs at least 5 samples for computation
337      if (data.Any(x => x.Length < requiredSampleSize)) {
338        if (showMessage)
339          MessageBox.Show(this, "You need at least " + requiredSampleSize
340            + " samples per group for computing hypothesis tests.", "HeuristicLab", MessageBoxButtons.OK,
341            MessageBoxIcon.Error);
342        return false;
343      }
344      return true;
345    }
346
347    private void CalculateValues() {
348      if (!VerifyDataLength(true))
349        return;
350
351      if (data != null && data.All(x => x != null)) {
352        MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>()
353          .AddOperationProgressToView(this, "Calculating...");
354
355        string curItem = (string)groupCompComboBox.SelectedItem;
356        Task.Factory.StartNew(() => CalculateValuesAsync(curItem));
357      }
358    }
359
360    private void CalculateValuesAsync(string groupName) {
361      CalculateAllGroupsTest();
362      CalculateNormalityTest();
363      CalculatePairwiseTest(groupName);
364
365      MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(this);
366    }
367
368    private void CalculatePairwise(string groupName) {
369      if (groupName == null) return;
370      if (!VerifyDataLength(false))
371        return;
372
373      MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().AddOperationProgressToView(pairwiseTestGroupBox, "Calculating...");
374      Task.Factory.StartNew(() => CalculatePairwiseAsync(groupName));
375    }
376
377    private void CalculatePairwiseAsync(string groupName) {
378      CalculatePairwiseTest(groupName);
379
380      MainFormManager.GetMainForm<MainForm.WindowsForms.MainForm>().RemoveOperationProgressFromView(pairwiseTestGroupBox);
381    }
382
383    private void CalculateAllGroupsTest() {
384      double pval = KruskalWallisTest.Test(data);
385      DisplayAllGroupsTextResults(pval);
386    }
387
388    private void DisplayAllGroupsTextResults(double pval) {
389      if (InvokeRequired) {
390        Invoke((Action<double>)DisplayAllGroupsTextResults, pval);
391      } else {
392        pValTextBox.Text = pval.ToString();
393        if (pval < significanceLevel) {
394          groupCompLabel.Image = VSImageLibrary.Default;
395          groupComTextLabel.Text = "There are groups with different distributions";
396        } else {
397          groupCompLabel.Image = VSImageLibrary.Warning;
398          groupComTextLabel.Text = "Groups have an equal distribution";
399        }
400      }
401    }
402
403    private void CalculateNormalityTest() {
404      double val;
405      List<double> res = new List<double>();
406      DoubleMatrix pValsMatrix = new DoubleMatrix(1, stringConvertibleMatrixView.Content.Columns);
407      pValsMatrix.ColumnNames = stringConvertibleMatrixView.Content.ColumnNames;
408      pValsMatrix.RowNames = new[] { "p-Value" };
409
410      for (int i = 0; i < data.Length; i++) {
411        alglib.jarqueberatest(data[i], data[i].Length, out val);
412        res.Add(val);
413        pValsMatrix[0, i] = val;
414      }
415
416      // p-value is below significance level and thus the null hypothesis (data is normally distributed) is rejected
417      if (res.Any(x => x < significanceLevel)) {
418        Invoke(new Action(() => {
419          normalityLabel.Image = VSImageLibrary.Warning;
420          normalityTextLabel.Text = "Some groups may not be normally distributed";
421        }));
422      } else {
423        Invoke(new Action(() => {
424          normalityLabel.Image = VSImageLibrary.Default;
425          normalityTextLabel.Text = "All sample data is normally distributed";
426        }));
427      }
428
429      Invoke(new Action(() => {
430        normalityStringConvertibleMatrixView.Content = pValsMatrix;
431        normalityStringConvertibleMatrixView.DataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
432      }));
433    }
434
435    private void ShowPairwiseResult(int nrOfEqualDistributions) {
436      double ratio = ((double)nrOfEqualDistributions) / (data.Length - 1) * 100.0;
437      equalDistsTextBox.Text = ratio + " %";
438
439      if (nrOfEqualDistributions == 0) {
440        Invoke(new Action(() => {
441          pairwiseLabel.Image = VSImageLibrary.Default;
442          pairwiseTextLabel.Text = "All groups have different distributions";
443        }));
444      } else {
445        Invoke(new Action(() => {
446          pairwiseLabel.Image = VSImageLibrary.Warning;
447          pairwiseTextLabel.Text = "Some groups have equal distributions";
448        }));
449      }
450    }
451
452    private void CalculatePairwiseTest(string groupName) {
453      var columnNames = stringConvertibleMatrixView.Content.ColumnNames.ToList();
454      int colIndex = columnNames.IndexOf(groupName);
455      columnNames = columnNames.Where(x => x != groupName).ToList();
456
457      double[][] newData = FilterDataForPairwiseTest(colIndex);
458
459      var rowNames = new[] { "p-Value of Mann-Whitney U", "Adjusted p-Value of Mann-Whitney U",
460            "p-Value of T-Test", "Adjusted p-Value of T-Test", "Cohen's d", "Hedges' g" };
461
462      DoubleMatrix pValsMatrix = new DoubleMatrix(rowNames.Length, columnNames.Count());
463      pValsMatrix.ColumnNames = columnNames;
464      pValsMatrix.RowNames = rowNames;
465
466      double mwuBothTails;
467      double tTestBothTails;
468      double[] mwuPValues = new double[newData.Length];
469      double[] tTestPValues = new double[newData.Length];
470      bool[] decision = null;
471      double[] adjustedMwuPValues = null;
472      double[] adjustedTtestPValues = null;
473      int cnt = 0;
474
475      for (int i = 0; i < newData.Length; i++) {
476        mwuBothTails = PairwiseTest.MannWhitneyUTest(data[colIndex], newData[i]);
477        tTestBothTails = PairwiseTest.TTest(data[colIndex], newData[i]);
478        mwuPValues[i] = mwuBothTails;
479        tTestPValues[i] = tTestBothTails;
480
481        if (mwuBothTails > significanceLevel) {
482          cnt++;
483        }
484      }
485
486      adjustedMwuPValues = BonferroniHolm.Calculate(significanceLevel, mwuPValues, out decision);
487      adjustedTtestPValues = BonferroniHolm.Calculate(significanceLevel, tTestPValues, out decision);
488
489      for (int i = 0; i < newData.Length; i++) {
490        pValsMatrix[0, i] = mwuPValues[i];
491        pValsMatrix[1, i] = adjustedMwuPValues[i];
492        pValsMatrix[2, i] = tTestPValues[i];
493        pValsMatrix[3, i] = adjustedTtestPValues[i];
494        pValsMatrix[4, i] = SampleSizeDetermination.CalculateCohensD(data[colIndex], newData[i]);
495        pValsMatrix[5, i] = SampleSizeDetermination.CalculateHedgesG(data[colIndex], newData[i]);
496      }
497
498      Invoke(new Action(() => {
499        pairwiseStringConvertibleMatrixView.Content = pValsMatrix;
500        pairwiseStringConvertibleMatrixView.DataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
501      }));
502
503      ShowPairwiseResult(cnt);
504    }
505
506    private double[][] FilterDataForPairwiseTest(int columnToRemove) {
507      double[][] newData = new double[data.Length - 1][];
508
509      int i = 0;
510      int l = 0;
511      while (i < data.Length) {
512        if (i != columnToRemove) {
513          double[] row = new double[data[i].Length - 1];
514          newData[l] = row;
515
516          int j = 0, k = 0;
517          while (j < row.Length) {
518            if (i != columnToRemove) {
519              newData[l][j] = data[i][k];
520              j++;
521              k++;
522            } else {
523              k++;
524            }
525          }
526          i++;
527          l++;
528        } else {
529          i++;
530        }
531      }
532      return newData;
533    }
534  }
535}
Note: See TracBrowser for help on using the repository browser.