Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2904_CalculateImpacts/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionVariableImpactsView.cs @ 16418

Last change on this file since 16418 was 16418, checked in by fholzing, 5 years ago

#2904: fixed bug (duplicated entries in VariableImpacts)

File size: 10.2 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 {
[15673]35    private enum SortingCriteria {
36      ImpactValue,
37      Occurrence,
38      VariableName
39    }
[16034]40    private CancellationTokenSource cancellationToken = new CancellationTokenSource();
[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;
[16021]56      this.replacementComboBox.SelectedIndex = 3;
[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    protected override void DeregisterContentEvents() {
67      base.DeregisterContentEvents();
68      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
69      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
70    }
71
72    protected virtual void Content_ProblemDataChanged(object sender, EventArgs e) {
73      OnContentChanged();
74    }
75    protected virtual void Content_ModelChanged(object sender, EventArgs e) {
76      OnContentChanged();
77    }
78    protected override void OnContentChanged() {
79      base.OnContentChanged();
[16416]80      rawVariableImpacts.Clear();
81
[14348]82      if (Content == null) {
[16042]83        variableImpactsArrayView.Content = null;
[14348]84      } else {
[15752]85        UpdateVariableImpact();
[14348]86      }
87    }
[15752]88    private void RegressionSolutionVariableImpactsView_VisibleChanged(object sender, EventArgs e) {
[15998]89      cancellationToken.Cancel();
[15752]90    }
91
[15665]92    private void dataPartitionComboBox_SelectedIndexChanged(object sender, EventArgs e) {
[16418]93      rawVariableImpacts.Clear();
[15752]94      UpdateVariableImpact();
[15665]95    }
96    private void replacementComboBox_SelectedIndexChanged(object sender, EventArgs e) {
[16418]97      rawVariableImpacts.Clear();
[15752]98      UpdateVariableImpact();
[15665]99    }
100    private void sortByComboBox_SelectedIndexChanged(object sender, EventArgs e) {
101      //Update the default ordering (asc,desc), but remove the eventHandler beforehand (otherwise the data would be ordered twice)
102      ascendingCheckBox.CheckedChanged -= ascendingCheckBox_CheckedChanged;
[15998]103      ascendingCheckBox.Checked = (SortingCriteria)sortByComboBox.SelectedItem != SortingCriteria.ImpactValue;
[15665]104      ascendingCheckBox.CheckedChanged += ascendingCheckBox_CheckedChanged;
105
[15998]106      UpdateOrdering();
[15665]107    }
108    private void ascendingCheckBox_CheckedChanged(object sender, EventArgs e) {
[15998]109      UpdateOrdering();
[15665]110    }
[15727]111
[15797]112    private async void UpdateVariableImpact() {
[15998]113      IProgress progress;
114
[15727]115      //Check if the selection is valid
[15673]116      if (Content == null) { return; }
117      if (replacementComboBox.SelectedIndex < 0) { return; }
118      if (dataPartitionComboBox.SelectedIndex < 0) { return; }
119      if (factorVarReplComboBox.SelectedIndex < 0) { return; }
120
[15727]121      //Prepare arguments
[15673]122      var mainForm = (MainForm.WindowsForms.MainForm)MainFormManager.MainForm;
123      var replMethod = (RegressionSolutionVariableImpactsCalculator.ReplacementMethodEnum)replacementComboBox.Items[replacementComboBox.SelectedIndex];
124      var factorReplMethod = (RegressionSolutionVariableImpactsCalculator.FactorReplacementMethodEnum)factorVarReplComboBox.Items[factorVarReplComboBox.SelectedIndex];
125      var dataPartition = (RegressionSolutionVariableImpactsCalculator.DataPartitionEnum)dataPartitionComboBox.SelectedItem;
126
[16042]127      variableImpactsArrayView.Caption = Content.Name + " Variable Impacts";
[15796]128      progress = mainForm.AddOperationProgressToView(this, "Calculating variable impacts for " + Content.Name);
129      progress.ProgressValue = 0;
[15752]130
[15797]131      cancellationToken = new CancellationTokenSource();
[16034]132
[15797]133      try {
134        var problemData = Content.ProblemData;
135        var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(Content.Model.VariablesUsedForPrediction));
[16034]136        //Remember the original ordering of the variables
[16015]137        var originalVariableOrdering = problemData.Dataset.VariableNames
138          .Where(v => inputvariables.Contains(v))
139          .Where(v => problemData.Dataset.VariableHasType<double>(v) || problemData.Dataset.VariableHasType<string>(v))
140          .ToList();
[15797]141
[16034]142        List<Tuple<string, double>> impacts = null;
143        await Task.Run(() => { impacts = CalculateVariableImpacts(originalVariableOrdering, Content.Model, problemData, Content.EstimatedValues, dataPartition, replMethod, factorReplMethod, cancellationToken.Token, progress); });
144        if (impacts == null) { return; }
145
[16051]146        rawVariableImpacts.AddRange(impacts);
[15998]147        UpdateOrdering();
[16034]148      }
149      finally {
[15797]150        ((MainForm.WindowsForms.MainForm)MainFormManager.MainForm).RemoveOperationProgressFromView(this);
[15796]151      }
[14348]152    }
[16034]153    private List<Tuple<string, double>> CalculateVariableImpacts(List<string> originalVariableOrdering,
154      IRegressionModel model,
155      IRegressionProblemData problemData,
156      IEnumerable<double> estimatedValues,
157      RegressionSolutionVariableImpactsCalculator.DataPartitionEnum dataPartition,
158      RegressionSolutionVariableImpactsCalculator.ReplacementMethodEnum replMethod,
159      RegressionSolutionVariableImpactsCalculator.FactorReplacementMethodEnum factorReplMethod,
160      CancellationToken token,
161      IProgress progress) {
162      List<Tuple<string, double>> impacts = new List<Tuple<string, double>>();
163      int count = originalVariableOrdering.Count;
164      int i = 0;
[16035]165      var modifiableDataset = ((Dataset)(problemData.Dataset).Clone()).ToModifiable();
166      IEnumerable<int> rows = RegressionSolutionVariableImpactsCalculator.GetPartitionRows(dataPartition, problemData);
[14348]167
[16035]168      //Calculate original quality-values (via calculator, default is R²)
[16041]169      IEnumerable<double> targetValuesPartition = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
170      IEnumerable<double> estimatedValuesPartition = Content.GetEstimatedValues(rows);
171
[16051]172      var originalCalculatorValue = RegressionSolutionVariableImpactsCalculator.CalculateQuality(targetValuesPartition, estimatedValuesPartition);
[16035]173
174      foreach (var variableName in originalVariableOrdering) {
[16034]175        if (cancellationToken.Token.IsCancellationRequested) { return null; }
176        progress.ProgressValue = (double)++i / count;
[16035]177        progress.Status = string.Format("Calculating impact for variable {0} ({1} of {2})", variableName, i, count);
[16034]178
[16041]179        double impact = 0;
180        //If the variable isn't used for prediction, it has zero impact.
181        if (model.VariablesUsedForPrediction.Contains(variableName)) {
[16051]182          impact = RegressionSolutionVariableImpactsCalculator.CalculateImpact(variableName, model, problemData, modifiableDataset, rows, replMethod, factorReplMethod, targetValuesPartition, originalCalculatorValue);
[16041]183        }
[16035]184        impacts.Add(new Tuple<string, double>(variableName, impact));
[16034]185      }
186
187      return impacts;
188    }
189
[15626]190    /// <summary>
[16042]191    /// Updates the <see cref="variableImpactsArrayView"/> according to the selected ordering <see cref="ascendingCheckBox"/> of the selected Column <see cref="sortByComboBox"/>
[15626]192    /// The default is "Descending" by "VariableImpact" (as in previous versions)
193    /// </summary>
[15998]194    private void UpdateOrdering() {
[15665]195      //Check if valid sortingCriteria is selected and data exists
[15673]196      if (sortByComboBox.SelectedIndex == -1) { return; }
197      if (rawVariableImpacts == null) { return; }
198      if (!rawVariableImpacts.Any()) { return; }
[15665]199
[15673]200      var selectedItem = (SortingCriteria)sortByComboBox.SelectedItem;
[15626]201      bool ascending = ascendingCheckBox.Checked;
202
[15998]203      IEnumerable<Tuple<string, double>> orderedEntries = null;
[15626]204
[15665]205      //Sort accordingly
206      switch (selectedItem) {
[15673]207        case SortingCriteria.ImpactValue:
[15998]208          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item2);
[15665]209          break;
[15673]210        case SortingCriteria.Occurrence:
211          orderedEntries = rawVariableImpacts;
[15665]212          break;
[15673]213        case SortingCriteria.VariableName:
[15998]214          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item1, new NaturalStringComparer());
[15665]215          break;
216        default:
[15673]217          throw new NotImplementedException("Ordering for selected SortingCriteria not implemented");
[15626]218      }
219
[15673]220      if (!ascending) { orderedEntries = orderedEntries.Reverse(); }
221
[15665]222      //Write the data back
[15998]223      var impactArray = new DoubleArray(orderedEntries.Select(i => i.Item2).ToArray()) {
224        ElementNames = orderedEntries.Select(i => i.Item1)
[15665]225      };
[15727]226
[15752]227      //Could be, if the View was closed
[16042]228      if (!variableImpactsArrayView.IsDisposed) {
229        variableImpactsArrayView.Content = (DoubleArray)impactArray.AsReadOnly();
[15727]230      }
[15626]231    }
[14348]232  }
233}
Note: See TracBrowser for help on using the repository browser.