Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionVariableImpactsView.cs @ 15999

Last change on this file since 15999 was 15998, checked in by fholzing, 6 years ago

#2871: Implemented review

File size: 8.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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;
26using System.Threading.Tasks;
27using HeuristicLab.Common;
28using HeuristicLab.Data;
29using HeuristicLab.MainForm;
30
31namespace HeuristicLab.Problems.DataAnalysis.Views {
32  [View("Variable Impacts")]
33  [Content(typeof(IRegressionSolution))]
34  public partial class RegressionSolutionVariableImpactsView : DataAnalysisSolutionEvaluationView {
35    private CancellationTokenSource cancellationToken = new CancellationTokenSource();
36    private enum SortingCriteria {
37      ImpactValue,
38      Occurrence,
39      VariableName
40    }
41    private List<Tuple<string, double>> rawVariableImpacts = new List<Tuple<string, double>>();
42
43    public new IRegressionSolution Content {
44      get { return (IRegressionSolution)base.Content; }
45      set {
46        base.Content = value;
47      }
48    }
49
50    public RegressionSolutionVariableImpactsView()
51      : base() {
52      InitializeComponent();
53
54      //Set the default values
55      this.dataPartitionComboBox.SelectedIndex = 0;
56      this.replacementComboBox.SelectedIndex = 0;
57      this.factorVarReplComboBox.SelectedIndex = 0;
58      this.sortByComboBox.SelectedItem = SortingCriteria.ImpactValue;
59    }
60
61    protected override void RegisterContentEvents() {
62      base.RegisterContentEvents();
63      Content.ModelChanged += new EventHandler(Content_ModelChanged);
64      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
65    }
66
67    protected override void DeregisterContentEvents() {
68      base.DeregisterContentEvents();
69      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
70      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
71    }
72
73    protected virtual void Content_ProblemDataChanged(object sender, EventArgs e) {
74      OnContentChanged();
75    }
76
77    protected virtual void Content_ModelChanged(object sender, EventArgs e) {
78      OnContentChanged();
79    }
80
81    protected override void OnContentChanged() {
82      base.OnContentChanged();
83      if (Content == null) {
84        variableImactsArrayView.Content = null;
85      } else {
86        UpdateVariableImpact();
87      }
88    }
89
90    private void RegressionSolutionVariableImpactsView_VisibleChanged(object sender, EventArgs e) {
91      cancellationToken.Cancel();
92    }
93
94
95    private void dataPartitionComboBox_SelectedIndexChanged(object sender, EventArgs e) {
96      UpdateVariableImpact();
97    }
98
99    private void replacementComboBox_SelectedIndexChanged(object sender, EventArgs e) {
100      UpdateVariableImpact();
101    }
102
103    private void sortByComboBox_SelectedIndexChanged(object sender, EventArgs e) {
104      //Update the default ordering (asc,desc), but remove the eventHandler beforehand (otherwise the data would be ordered twice)
105      ascendingCheckBox.CheckedChanged -= ascendingCheckBox_CheckedChanged;
106      ascendingCheckBox.Checked = (SortingCriteria)sortByComboBox.SelectedItem != SortingCriteria.ImpactValue;
107      ascendingCheckBox.CheckedChanged += ascendingCheckBox_CheckedChanged;
108
109      UpdateOrdering();
110    }
111
112    private void ascendingCheckBox_CheckedChanged(object sender, EventArgs e) {
113      UpdateOrdering();
114    }
115
116
117    private async void UpdateVariableImpact() {
118      IProgress progress;
119
120      //Check if the selection is valid
121      if (Content == null) { return; }
122      if (replacementComboBox.SelectedIndex < 0) { return; }
123      if (dataPartitionComboBox.SelectedIndex < 0) { return; }
124      if (factorVarReplComboBox.SelectedIndex < 0) { return; }
125
126      //Prepare arguments
127      var mainForm = (MainForm.WindowsForms.MainForm)MainFormManager.MainForm;
128      var replMethod = (RegressionSolutionVariableImpactsCalculator.ReplacementMethodEnum)replacementComboBox.Items[replacementComboBox.SelectedIndex];
129      var factorReplMethod = (RegressionSolutionVariableImpactsCalculator.FactorReplacementMethodEnum)factorVarReplComboBox.Items[factorVarReplComboBox.SelectedIndex];
130      var dataPartition = (RegressionSolutionVariableImpactsCalculator.DataPartitionEnum)dataPartitionComboBox.SelectedItem;
131
132      variableImactsArrayView.Caption = Content.Name + " Variable Impacts";
133      progress = mainForm.AddOperationProgressToView(this, "Calculating variable impacts for " + Content.Name);
134      progress.ProgressValue = 0;
135
136      cancellationToken = new CancellationTokenSource();
137      //Remember the original ordering of the variables
138      try {
139        var impacts = await Task.Run(() => RegressionSolutionVariableImpactsCalculator.CalculateImpacts(Content, dataPartition, replMethod, factorReplMethod,
140          (i, s) => {
141            progress.ProgressValue = i;
142            progress.Status = s;
143            return cancellationToken.Token.IsCancellationRequested;
144          }), cancellationToken.Token);
145
146        if (cancellationToken.Token.IsCancellationRequested) { return; }
147        var problemData = Content.ProblemData;
148        var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(Content.Model.VariablesUsedForPrediction));
149        var originalVariableOrdering = problemData.Dataset.VariableNames.Where(v => inputvariables.Contains(v)).Where(problemData.Dataset.VariableHasType<double>).ToList();
150
151        rawVariableImpacts.Clear();
152        originalVariableOrdering.ForEach(v => rawVariableImpacts.Add(new Tuple<string, double>(v, impacts.First(vv => vv.Item1 == v).Item2)));
153        UpdateOrdering();
154      } finally {
155        ((MainForm.WindowsForms.MainForm)MainFormManager.MainForm).RemoveOperationProgressFromView(this);
156      }
157    }
158
159    /// <summary>
160    /// Updates the <see cref="variableImactsArrayView"/> according to the selected ordering <see cref="ascendingCheckBox"/> of the selected Column <see cref="sortByComboBox"/>
161    /// The default is "Descending" by "VariableImpact" (as in previous versions)
162    /// </summary>
163    private void UpdateOrdering() {
164      //Check if valid sortingCriteria is selected and data exists
165      if (sortByComboBox.SelectedIndex == -1) { return; }
166      if (rawVariableImpacts == null) { return; }
167      if (!rawVariableImpacts.Any()) { return; }
168
169      var selectedItem = (SortingCriteria)sortByComboBox.SelectedItem;
170      bool ascending = ascendingCheckBox.Checked;
171
172      IEnumerable<Tuple<string, double>> orderedEntries = null;
173
174      //Sort accordingly
175      switch (selectedItem) {
176        case SortingCriteria.ImpactValue:
177          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item2);
178          break;
179        case SortingCriteria.Occurrence:
180          orderedEntries = rawVariableImpacts;
181          break;
182        case SortingCriteria.VariableName:
183          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item1, new NaturalStringComparer());
184          break;
185        default:
186          throw new NotImplementedException("Ordering for selected SortingCriteria not implemented");
187      }
188
189      if (!ascending) { orderedEntries = orderedEntries.Reverse(); }
190
191      //Write the data back
192      var impactArray = new DoubleArray(orderedEntries.Select(i => i.Item2).ToArray()) {
193        ElementNames = orderedEntries.Select(i => i.Item1)
194      };
195
196      //Could be, if the View was closed
197      if (!variableImactsArrayView.IsDisposed) {
198        variableImactsArrayView.Content = (DoubleArray)impactArray.AsReadOnly();
199      }
200    }
201  }
202}
Note: See TracBrowser for help on using the repository browser.