Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12599 was 12599, checked in by abeham, 9 years ago

#2270: Fixed several of the runcollection views

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