Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2871: Fixed bug where factory-variables would be ignored

File size: 8.3 KB
RevLine 
[14348]1#region License Information
2/* HeuristicLab
[15583]3 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[14348]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
[15665]21
[14348]22using System;
[15626]23using System.Collections.Generic;
[14348]24using System.Linq;
[15797]25using System.Threading;
26using System.Threading.Tasks;
[15637]27using HeuristicLab.Common;
[14348]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 {
[15797]35    private CancellationTokenSource cancellationToken = new CancellationTokenSource();
[15673]36    private enum SortingCriteria {
37      ImpactValue,
38      Occurrence,
39      VariableName
40    }
[15998]41    private List<Tuple<string, double>> rawVariableImpacts = new List<Tuple<string, double>>();
[15626]42
[14348]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();
[15665]53
[15727]54      //Set the default values
[14348]55      this.dataPartitionComboBox.SelectedIndex = 0;
56      this.replacementComboBox.SelectedIndex = 0;
[14826]57      this.factorVarReplComboBox.SelectedIndex = 0;
[15998]58      this.sortByComboBox.SelectedItem = SortingCriteria.ImpactValue;
[14348]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 {
[15752]86        UpdateVariableImpact();
[14348]87      }
88    }
89
[15752]90    private void RegressionSolutionVariableImpactsView_VisibleChanged(object sender, EventArgs e) {
[15998]91      cancellationToken.Cancel();
[15752]92    }
93
94
[15665]95    private void dataPartitionComboBox_SelectedIndexChanged(object sender, EventArgs e) {
[15752]96      UpdateVariableImpact();
[15665]97    }
98
99    private void replacementComboBox_SelectedIndexChanged(object sender, EventArgs e) {
[15752]100      UpdateVariableImpact();
[15665]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;
[15998]106      ascendingCheckBox.Checked = (SortingCriteria)sortByComboBox.SelectedItem != SortingCriteria.ImpactValue;
[15665]107      ascendingCheckBox.CheckedChanged += ascendingCheckBox_CheckedChanged;
108
[15998]109      UpdateOrdering();
[15665]110    }
111
112    private void ascendingCheckBox_CheckedChanged(object sender, EventArgs e) {
[15998]113      UpdateOrdering();
[15665]114    }
[15727]115
[15665]116
[15797]117    private async void UpdateVariableImpact() {
[15998]118      IProgress progress;
119
[15727]120      //Check if the selection is valid
[15673]121      if (Content == null) { return; }
122      if (replacementComboBox.SelectedIndex < 0) { return; }
123      if (dataPartitionComboBox.SelectedIndex < 0) { return; }
124      if (factorVarReplComboBox.SelectedIndex < 0) { return; }
125
[15727]126      //Prepare arguments
[15673]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
[15752]132      variableImactsArrayView.Caption = Content.Name + " Variable Impacts";
[15796]133      progress = mainForm.AddOperationProgressToView(this, "Calculating variable impacts for " + Content.Name);
134      progress.ProgressValue = 0;
[15752]135
[15797]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,
[15799]140          (i, s) => {
[15797]141            progress.ProgressValue = i;
[15799]142            progress.Status = s;
[15797]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));
[16015]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();
[15797]153
154        rawVariableImpacts.Clear();
[15998]155        originalVariableOrdering.ForEach(v => rawVariableImpacts.Add(new Tuple<string, double>(v, impacts.First(vv => vv.Item1 == v).Item2)));
156        UpdateOrdering();
[15797]157      } finally {
158        ((MainForm.WindowsForms.MainForm)MainFormManager.MainForm).RemoveOperationProgressFromView(this);
[15796]159      }
[14348]160    }
161
[15626]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>
[15998]166    private void UpdateOrdering() {
[15665]167      //Check if valid sortingCriteria is selected and data exists
[15673]168      if (sortByComboBox.SelectedIndex == -1) { return; }
169      if (rawVariableImpacts == null) { return; }
170      if (!rawVariableImpacts.Any()) { return; }
[15665]171
[15673]172      var selectedItem = (SortingCriteria)sortByComboBox.SelectedItem;
[15626]173      bool ascending = ascendingCheckBox.Checked;
174
[15998]175      IEnumerable<Tuple<string, double>> orderedEntries = null;
[15626]176
[15665]177      //Sort accordingly
178      switch (selectedItem) {
[15673]179        case SortingCriteria.ImpactValue:
[15998]180          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item2);
[15665]181          break;
[15673]182        case SortingCriteria.Occurrence:
183          orderedEntries = rawVariableImpacts;
[15665]184          break;
[15673]185        case SortingCriteria.VariableName:
[15998]186          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item1, new NaturalStringComparer());
[15665]187          break;
188        default:
[15673]189          throw new NotImplementedException("Ordering for selected SortingCriteria not implemented");
[15626]190      }
191
[15673]192      if (!ascending) { orderedEntries = orderedEntries.Reverse(); }
193
[15665]194      //Write the data back
[15998]195      var impactArray = new DoubleArray(orderedEntries.Select(i => i.Item2).ToArray()) {
196        ElementNames = orderedEntries.Select(i => i.Item1)
[15665]197      };
[15727]198
[15752]199      //Could be, if the View was closed
[15727]200      if (!variableImactsArrayView.IsDisposed) {
201        variableImactsArrayView.Content = (DoubleArray)impactArray.AsReadOnly();
202      }
[15626]203    }
[14348]204  }
205}
Note: See TracBrowser for help on using the repository browser.