Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2845_EnhancedProgress/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionVariableImpactsView.cs @ 16312

Last change on this file since 16312 was 16312, checked in by pfleck, 5 years ago

#2845 Adapted new Hive-Project-Management and RegressionSolutionVariableImpactsView to Progress updates.

File size: 8.0 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 = 3;
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      //Check if the selection is valid
119      if (Content == null) { return; }
120      if (replacementComboBox.SelectedIndex < 0) { return; }
121      if (dataPartitionComboBox.SelectedIndex < 0) { return; }
122      if (factorVarReplComboBox.SelectedIndex < 0) { return; }
123
124      //Prepare arguments
125      var replMethod = (RegressionSolutionVariableImpactsCalculator.ReplacementMethodEnum)replacementComboBox.Items[replacementComboBox.SelectedIndex];
126      var factorReplMethod = (RegressionSolutionVariableImpactsCalculator.FactorReplacementMethodEnum)factorVarReplComboBox.Items[factorVarReplComboBox.SelectedIndex];
127      var dataPartition = (RegressionSolutionVariableImpactsCalculator.DataPartitionEnum)dataPartitionComboBox.SelectedItem;
128
129      variableImactsArrayView.Caption = Content.Name + " Variable Impacts";
130      var progress = Progress.Show(this, "Calculating variable impacts for " + Content.Name);
131      cancellationToken = new CancellationTokenSource();
132      //Remember the original ordering of the variables
133      try {
134        var impacts = await Task.Run(() => RegressionSolutionVariableImpactsCalculator.CalculateImpacts(Content, dataPartition, replMethod, factorReplMethod,
135          (i, s) => {
136            progress.ProgressValue = i;
137            progress.Message = s;
138            return cancellationToken.Token.IsCancellationRequested;
139          }), cancellationToken.Token);
140
141        if (cancellationToken.Token.IsCancellationRequested) { return; }
142        var problemData = Content.ProblemData;
143        var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(Content.Model.VariablesUsedForPrediction));
144        var originalVariableOrdering = problemData.Dataset.VariableNames
145          .Where(v => inputvariables.Contains(v))
146          .Where(v => problemData.Dataset.VariableHasType<double>(v) || problemData.Dataset.VariableHasType<string>(v))
147          .ToList();
148
149        rawVariableImpacts.Clear();
150        originalVariableOrdering.ForEach(v => rawVariableImpacts.Add(new Tuple<string, double>(v, impacts.First(vv => vv.Item1 == v).Item2)));
151        UpdateOrdering();
152      } finally {
153        Progress.Hide(this);
154      }
155    }
156
157    /// <summary>
158    /// Updates the <see cref="variableImactsArrayView"/> according to the selected ordering <see cref="ascendingCheckBox"/> of the selected Column <see cref="sortByComboBox"/>
159    /// The default is "Descending" by "VariableImpact" (as in previous versions)
160    /// </summary>
161    private void UpdateOrdering() {
162      //Check if valid sortingCriteria is selected and data exists
163      if (sortByComboBox.SelectedIndex == -1) { return; }
164      if (rawVariableImpacts == null) { return; }
165      if (!rawVariableImpacts.Any()) { return; }
166
167      var selectedItem = (SortingCriteria)sortByComboBox.SelectedItem;
168      bool ascending = ascendingCheckBox.Checked;
169
170      IEnumerable<Tuple<string, double>> orderedEntries = null;
171
172      //Sort accordingly
173      switch (selectedItem) {
174        case SortingCriteria.ImpactValue:
175          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item2);
176          break;
177        case SortingCriteria.Occurrence:
178          orderedEntries = rawVariableImpacts;
179          break;
180        case SortingCriteria.VariableName:
181          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item1, new NaturalStringComparer());
182          break;
183        default:
184          throw new NotImplementedException("Ordering for selected SortingCriteria not implemented");
185      }
186
187      if (!ascending) { orderedEntries = orderedEntries.Reverse(); }
188
189      //Write the data back
190      var impactArray = new DoubleArray(orderedEntries.Select(i => i.Item2).ToArray()) {
191        ElementNames = orderedEntries.Select(i => i.Item1)
192      };
193
194      //Could be, if the View was closed
195      if (!variableImactsArrayView.IsDisposed) {
196        variableImactsArrayView.Content = (DoubleArray)impactArray.AsReadOnly();
197      }
198    }
199  }
200}
Note: See TracBrowser for help on using the repository browser.