Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2871: Rebuild from BackgroundWorker to async await

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