Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysis/HeuristicLab.Problems.DataAnalysis.Views/3.3/RunCollectionVariableImpactView.cs @ 4892

Last change on this file since 4892 was 4143, checked in by gkronber, 14 years ago

Fixed calculation of p-values for variable impacts (the calculation procedure was implemented incorrectly because in r4121). #1011

File size: 9.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.Collections.Generic;
23using System.Linq;
24using System.Windows.Forms;
25using alglib;
26using HeuristicLab.Common;
27using HeuristicLab.Data;
28using HeuristicLab.MainForm;
29using HeuristicLab.MainForm.WindowsForms;
30using HeuristicLab.Optimization;
31using System;
32
33namespace HeuristicLab.Problems.DataAnalysis.Views {
34  [Content(typeof(RunCollection), false)]
35  [View("RunCollection Variable Impact View")]
36  public partial class RunCollectionVariableImpactView : AsynchronousContentView {
37    private const string variableImpactResultName = "Integrated variable frequencies";
38    public RunCollectionVariableImpactView() {
39      InitializeComponent();
40    }
41
42    public new RunCollection Content {
43      get { return (RunCollection)base.Content; }
44      set { base.Content = value; }
45    }
46
47    protected override void RegisterContentEvents() {
48      base.RegisterContentEvents();
49      this.Content.ItemsAdded += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
50      this.Content.ItemsRemoved += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
51      this.Content.CollectionReset += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
52    }
53    protected override void DeregisterContentEvents() {
54      base.RegisterContentEvents();
55      this.Content.ItemsAdded -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
56      this.Content.ItemsRemoved -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
57      this.Content.CollectionReset -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
58    }
59
60    protected override void OnContentChanged() {
61      base.OnContentChanged();
62      this.UpdateData();
63    }
64    private void Content_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
65      this.UpdateData();
66    }
67    private void Content_ItemsRemoved(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
68      this.UpdateData();
69    }
70    private void Content_CollectionReset(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
71      this.UpdateData();
72    }
73
74    private void UpdateData() {
75      matrixView.Content = CalculateVariableImpactMatrix();
76    }
77
78    private DoubleMatrix CalculateVariableImpactMatrix() {
79      DoubleMatrix matrix = null;
80      if (Content != null) {
81        List<IRun> runsWithVariables = Content.Where(r => r.Results.ContainsKey(variableImpactResultName)).ToList();
82        IEnumerable<DoubleMatrix> allVariableImpacts = (from run in runsWithVariables
83                                                        select run.Results[variableImpactResultName]).Cast<DoubleMatrix>();
84        IEnumerable<string> variableNames = (from variableImpact in allVariableImpacts
85                                             from variableName in variableImpact.RowNames
86                                             select variableName)
87                                            .Distinct();
88        // filter variableNames: only include names that have at least one non-zero value in a run
89        List<string> variableNamesList = (from variableName in variableNames
90                                          where GetVariableImpacts(variableName, allVariableImpacts).Any(x => !x.IsAlmost(0.0))
91                                          select variableName)
92                                         .ToList();
93
94        List<string> statictics = new List<string> { "Median Rank", "Mean", "StdDev", "pValue" };
95        List<string> columnNames = runsWithVariables.Select(r => r.Name).ToList();
96        columnNames.AddRange(statictics);
97        int runs = runsWithVariables.Count();
98
99        matrix = new DoubleMatrix(variableNamesList.Count, runs + statictics.Count);
100        matrix.SortableView = true;
101        matrix.RowNames = variableNamesList;
102        matrix.ColumnNames = columnNames;
103
104        for (int i = 0; i < runsWithVariables.Count; i++) {
105          IRun run = runsWithVariables[i];
106          DoubleMatrix runVariableImpacts = (DoubleMatrix)run.Results[variableImpactResultName];
107          for (int j = 0; j < runVariableImpacts.Rows; j++) {
108            int rowIndex = variableNamesList.FindIndex(s => s == runVariableImpacts.RowNames.ElementAt(j));
109            if (rowIndex > -1) {
110              matrix[rowIndex, i] = runVariableImpacts[j, 0];
111            }
112          }
113        }
114
115        List<List<double>> variableImpactsOverRuns = (from variableName in variableNamesList
116                                                      select GetVariableImpacts(variableName, allVariableImpacts).ToList())
117                                                     .ToList();
118        List<List<double>> variableRanks = (from variableName in variableNamesList
119                                            select GetVariableImpactRanks(variableName, allVariableImpacts).ToList())
120                                        .ToList();
121        if (variableImpactsOverRuns.Count() > 0) {
122          // the variable with the worst median impact value is chosen as the reference variable
123          // this is problematic if all variables are relevant, however works often in practice
124          List<double> referenceImpacts = (from impacts in variableImpactsOverRuns
125                                           let avg = impacts.Median()
126                                           orderby avg
127                                           select impacts)
128                                           .First();
129          // for all variables
130          for (int row = 0; row < variableImpactsOverRuns.Count; row++) {
131            // median rank
132            matrix[row, runs] = variableRanks[row].Median();
133            // also show mean and std.dev. of relative variable impacts to indicate the relative difference in impacts of variables
134            matrix[row, runs + 1] = variableImpactsOverRuns[row].Average();
135            matrix[row, runs + 2] = variableImpactsOverRuns[row].StandardDeviation();
136
137            double leftTail = 0; double rightTail = 0; double bothTails = 0;
138            // calc differences of impacts for current variable and reference variable
139            double[] z = new double[referenceImpacts.Count];
140            for (int i = 0; i < z.Length; i++) {
141              z[i] = variableImpactsOverRuns[row][i] - referenceImpacts[i];
142            }
143            // wilcoxon signed rank test is used because the impact values of two variables in a single run are not independent
144            alglib.wsr.wilcoxonsignedranktest(z, z.Length, 0, ref bothTails, ref leftTail, ref rightTail);
145            matrix[row, runs + 3] = bothTails;
146          }
147        }
148      }
149      return matrix;
150    }
151
152    private IEnumerable<double> GetVariableImpactRanks(string variableName, IEnumerable<DoubleMatrix> allVariableImpacts) {
153      foreach (DoubleMatrix runVariableImpacts in allVariableImpacts) {
154        // certainly not yet very efficient because ranks are computed multiple times for the same run
155        string[] variableNames = runVariableImpacts.RowNames.ToArray();
156        double[] values = (from row in Enumerable.Range(0, runVariableImpacts.Rows)
157                           select runVariableImpacts[row, 0] * -1)
158                          .ToArray();
159        Array.Sort(values, variableNames);
160        // calculate ranks
161        double[] ranks = new double[values.Length];
162        // check for tied ranks
163        int i = 0;
164        while (i < values.Length) {
165          ranks[i] = i + 1;
166          int j = i + 1;
167          while (j < values.Length && values[i].IsAlmost(values[j])) {
168            ranks[j] = ranks[i];
169            j++;
170          }
171          i = j;
172        }
173        int rankIndex = 0;
174        foreach (string rowVariableName in variableNames) {
175          if (rowVariableName == variableName)
176            yield return ranks[rankIndex];
177          rankIndex++;
178        }
179      }
180    }
181
182    private IEnumerable<double> GetVariableImpacts(string variableName, IEnumerable<DoubleMatrix> allVariableImpacts) {
183      foreach (DoubleMatrix runVariableImpacts in allVariableImpacts) {
184        int row = 0;
185        foreach (string rowName in runVariableImpacts.RowNames) {
186          if (rowName == variableName)
187            yield return runVariableImpacts[row, 0];
188          row++;
189        }
190      }
191    }
192
193  }
194}
Note: See TracBrowser for help on using the repository browser.