Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2915-AbsoluteSymbol/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionVariableImpactsView.cs @ 16654

Last change on this file since 16654 was 16240, checked in by gkronber, 6 years ago

#2915: merged changes in the trunk up to current HEAD (r15951:16232) into the branch

File size: 8.3 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      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
150          .Where(v => inputvariables.Contains(v))
151          .Where(v => problemData.Dataset.VariableHasType<double>(v) || problemData.Dataset.VariableHasType<string>(v))
152          .ToList();
153
154        rawVariableImpacts.Clear();
155        originalVariableOrdering.ForEach(v => rawVariableImpacts.Add(new Tuple<string, double>(v, impacts.First(vv => vv.Item1 == v).Item2)));
156        UpdateOrdering();
157      } finally {
158        ((MainForm.WindowsForms.MainForm)MainFormManager.MainForm).RemoveOperationProgressFromView(this);
159      }
160    }
161
162    /// <summary>
163    /// Updates the <see cref="variableImactsArrayView"/> according to the selected ordering <see cref="ascendingCheckBox"/> of the selected Column <see cref="sortByComboBox"/>
164    /// The default is "Descending" by "VariableImpact" (as in previous versions)
165    /// </summary>
166    private void UpdateOrdering() {
167      //Check if valid sortingCriteria is selected and data exists
168      if (sortByComboBox.SelectedIndex == -1) { return; }
169      if (rawVariableImpacts == null) { return; }
170      if (!rawVariableImpacts.Any()) { return; }
171
172      var selectedItem = (SortingCriteria)sortByComboBox.SelectedItem;
173      bool ascending = ascendingCheckBox.Checked;
174
175      IEnumerable<Tuple<string, double>> orderedEntries = null;
176
177      //Sort accordingly
178      switch (selectedItem) {
179        case SortingCriteria.ImpactValue:
180          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item2);
181          break;
182        case SortingCriteria.Occurrence:
183          orderedEntries = rawVariableImpacts;
184          break;
185        case SortingCriteria.VariableName:
186          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item1, new NaturalStringComparer());
187          break;
188        default:
189          throw new NotImplementedException("Ordering for selected SortingCriteria not implemented");
190      }
191
192      if (!ascending) { orderedEntries = orderedEntries.Reverse(); }
193
194      //Write the data back
195      var impactArray = new DoubleArray(orderedEntries.Select(i => i.Item2).ToArray()) {
196        ElementNames = orderedEntries.Select(i => i.Item1)
197      };
198
199      //Could be, if the View was closed
200      if (!variableImactsArrayView.IsDisposed) {
201        variableImactsArrayView.Content = (DoubleArray)impactArray.AsReadOnly();
202      }
203    }
204  }
205}
Note: See TracBrowser for help on using the repository browser.