Ignore:
Timestamp:
12/15/18 12:36:08 (11 months ago)
Author:
gkronber
Message:

#2892: Merging r15750:16382 (HEAD) from trunk to branch, resolving conflicts

Location:
branches/2892_LR-prediction-intervals
Files:
16 edited

Legend:

Unmodified
Added
Removed
  • branches/2892_LR-prediction-intervals

  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views

  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/ClassificationSolutionVariableImpactsView.Designer.cs

    r15729 r16388  
    170170      this.sortByComboBox.SelectedIndexChanged += new System.EventHandler(this.sortByComboBox_SelectedIndexChanged);
    171171      //
    172       // backgroundWorker
    173       //
    174       this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_DoWork);
    175       this.backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted);
    176       //
    177172      // ClassificationSolutionVariableImpactsView
    178173      //
     
    191186      this.Name = "ClassificationSolutionVariableImpactsView";
    192187      this.Size = new System.Drawing.Size(668, 365);
     188      this.VisibleChanged += new System.EventHandler(this.ClassificationSolutionVariableImpactsView_VisibleChanged);
    193189      this.ResumeLayout(false);
    194190      this.PerformLayout();
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/ClassificationSolutionVariableImpactsView.cs

    r15729 r16388  
    2323using System.Collections.Generic;
    2424using System.Linq;
     25using System.Threading;
     26using System.Threading.Tasks;
    2527using HeuristicLab.Common;
    2628using HeuristicLab.Data;
     
    3234  public partial class ClassificationSolutionVariableImpactsView : DataAnalysisSolutionEvaluationView {
    3335    #region Nested Types
    34     private class BackgroundWorkerArguments {
    35       internal MainForm.WindowsForms.MainForm mainForm;
    36       internal ClassificationSolutionVariableImpactsCalculator.ReplacementMethodEnum replMethod;
    37       internal ClassificationSolutionVariableImpactsCalculator.FactorReplacementMethodEnum factorReplMethod;
    38       internal ClassificationSolutionVariableImpactsCalculator.DataPartitionEnum dataPartition;
    39     }
    40 
    4136    private enum SortingCriteria {
    4237      ImpactValue,
     
    4843    #region Fields
    4944    private Dictionary<string, double> rawVariableImpacts = new Dictionary<string, double>();
     45    private Thread thread;
    5046    #endregion
    5147
     
    6460      InitializeComponent();
    6561
    66       //Little workaround. If you fill the ComboBox-Items in the other partial class, the UI-Designer will moan.
    6762      this.sortByComboBox.Items.AddRange(Enum.GetValues(typeof(SortingCriteria)).Cast<object>().ToArray());
    6863      this.sortByComboBox.SelectedItem = SortingCriteria.ImpactValue;
     
    10196        variableImactsArrayView.Content = null;
    10297      } else {
    103         StartBackgroundWorker();
    104       }
     98        UpdateVariableImpact();
     99      }
     100    }
     101
     102    private void ClassificationSolutionVariableImpactsView_VisibleChanged(object sender, EventArgs e) {
     103      if (thread == null) { return; }
     104
     105      if (thread.IsAlive) { thread.Abort(); }
     106      thread = null;
    105107    }
    106108
    107109
    108110    private void dataPartitionComboBox_SelectedIndexChanged(object sender, EventArgs e) {
    109       StartBackgroundWorker();
     111      UpdateVariableImpact();
    110112    }
    111113
    112114    private void replacementComboBox_SelectedIndexChanged(object sender, EventArgs e) {
    113       StartBackgroundWorker();
     115      UpdateVariableImpact();
    114116    }
    115117
     
    139141    }
    140142
    141 
    142     private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
    143       variableImactsArrayView.Caption = Content.Name + " Variable Impacts";
    144 
    145       var argument = e.Argument as BackgroundWorkerArguments;
    146       if (!(argument is BackgroundWorkerArguments)) {
    147         throw new ArgumentException("Argument for Backgroundworker must be of type BackgroundworkerArguments");
    148       }
    149 
    150       argument.mainForm.AddOperationProgressToView(this, "Calculating variable impacts for " + Content.Name);
    151       try {
    152         //Remember the original ordering of the variables
    153         var impacts = ClassificationSolutionVariableImpactsCalculator.CalculateImpacts(Content, argument.dataPartition, argument.replMethod, argument.factorReplMethod);
    154         var problemData = Content.ProblemData;
    155         var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(Content.Model.VariablesUsedForPrediction));
    156         var originalVariableOrdering = problemData.Dataset.VariableNames.Where(v => inputvariables.Contains(v)).Where(problemData.Dataset.VariableHasType<double>).ToList();
    157 
    158         rawVariableImpacts.Clear();
    159         originalVariableOrdering.ForEach(v => rawVariableImpacts.Add(v, impacts.First(vv => vv.Item1 == v).Item2));
    160       } finally {
    161         argument.mainForm.RemoveOperationProgressFromView(this);
    162       }
    163     }
    164 
    165     private void backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) {
    166       UpdateDataOrdering();
    167     }
    168     #endregion
    169 
    170     #region Helper Methods
    171     private void StartBackgroundWorker() {
     143    #endregion
     144
     145    #region Helper Methods   
     146    private void UpdateVariableImpact() {
    172147      //Check if the selection is valid
    173148      if (Content == null) { return; }
     
    181156      var factorReplMethod = (ClassificationSolutionVariableImpactsCalculator.FactorReplacementMethodEnum)factorVarReplComboBox.Items[factorVarReplComboBox.SelectedIndex];
    182157      var dataPartition = (ClassificationSolutionVariableImpactsCalculator.DataPartitionEnum)dataPartitionComboBox.SelectedItem;
    183       var args = new BackgroundWorkerArguments() {
    184         mainForm = mainForm,
    185         replMethod = replMethod,
    186         factorReplMethod = factorReplMethod,
    187         dataPartition = dataPartition
    188       };
    189 
    190       //Let the backgroundWorker do his job (unless he's already running)
    191       //fholzing: Possible bug -> A ContentChanged won't update the data if the backgroundworker is already running
    192       if (!backgroundWorker.IsBusy) { backgroundWorker.RunWorkerAsync(args); }
     158
     159      variableImactsArrayView.Caption = Content.Name + " Variable Impacts";
     160
     161      mainForm.AddOperationProgressToView(this, "Calculating variable impacts for " + Content.Name);
     162
     163      Task.Factory.StartNew(() => {
     164        thread = Thread.CurrentThread;
     165        //Remember the original ordering of the variables
     166        var impacts = ClassificationSolutionVariableImpactsCalculator.CalculateImpacts(Content, dataPartition, replMethod, factorReplMethod);
     167        var problemData = Content.ProblemData;
     168        var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(Content.Model.VariablesUsedForPrediction));
     169        var originalVariableOrdering = problemData.Dataset.VariableNames.Where(v => inputvariables.Contains(v)).Where(problemData.Dataset.VariableHasType<double>).ToList();
     170
     171        rawVariableImpacts.Clear();
     172        originalVariableOrdering.ForEach(v => rawVariableImpacts.Add(v, impacts.First(vv => vv.Item1 == v).Item2));
     173      }).ContinueWith((o) => {
     174        UpdateDataOrdering();
     175        mainForm.RemoveOperationProgressFromView(this);
     176        thread = null;
     177      }, TaskScheduler.FromCurrentSynchronizationContext());
    193178    }
    194179
     
    230215      };
    231216
    232       //Could be, if the View was closed during the BackgroundWorker-run
     217      //Could be, if the View was closed
    233218      if (!variableImactsArrayView.IsDisposed) {
    234219        variableImactsArrayView.Content = (DoubleArray)impactArray.AsReadOnly();
    235220      }
    236221    }
    237     #endregion
     222    #endregion  
    238223  }
    239224}
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Controls/FactorPartialDependencePlot.cs

    r15583 r16388  
    143143      // Configure axis
    144144      chart.CustomizeAllChartAreas();
    145       chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
    146       chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
    147       chart.ChartAreas[0].CursorX.Interval = 0;
    148 
    149       chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
    150       chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
    151       chart.ChartAreas[0].CursorY.Interval = 0;
     145      chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = false;
     146      chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = false;
     147
     148      chart.ChartAreas[0].Axes.ToList().ForEach(x => { x.ScaleView.Zoomable = false; });
    152149
    153150      Disposed += Control_Disposed;
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Controls/PartialDependencePlot.cs

    r15583 r16388  
    215215      // Configure axis
    216216      chart.CustomizeAllChartAreas();
    217       chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
    218       chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
    219       chart.ChartAreas[0].CursorX.Interval = 0;
    220 
    221       chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
    222       chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
    223       chart.ChartAreas[0].CursorY.Interval = 0;
     217      chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = false;
     218      chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = false;
     219
     220      chart.ChartAreas[0].Axes.ToList().ForEach(x => { x.ScaleView.Zoomable = false; });
    224221
    225222      configToolStripMenuItem = new ToolStripMenuItem("Configuration");
     
    351348
    352349    private void RecalculateTrainingLimits(bool initializeAxisRanges) {
    353       trainingMin = solutions.Select(s => s.ProblemData.Dataset.GetDoubleValues(freeVariable, s.ProblemData.TrainingIndices).Min()).Max();
    354       trainingMax = solutions.Select(s => s.ProblemData.Dataset.GetDoubleValues(freeVariable, s.ProblemData.TrainingIndices).Max()).Min();
     350      trainingMin = solutions.Select(s => s.ProblemData.Dataset.GetDoubleValues(freeVariable, s.ProblemData.TrainingIndices).Where(x => !double.IsNaN(x)).Min()).Max();
     351      trainingMax = solutions.Select(s => s.ProblemData.Dataset.GetDoubleValues(freeVariable, s.ProblemData.TrainingIndices).Where(x => !double.IsNaN(x)).Max()).Min();
    355352
    356353      if (initializeAxisRanges) {
     
    702699    private void config_Click(object sender, EventArgs e) {
    703700      configurationDialog.ShowDialog(this);
     701      OnZoomChanged(this, EventArgs.Empty);
    704702    }
    705703
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionErrorCharacteristicsCurveView.cs

    r15583 r16388  
    249249    protected virtual List<double> GetResiduals(IEnumerable<double> originalValues, IEnumerable<double> estimatedValues) {
    250250      switch (residualComboBox.SelectedItem.ToString()) {
    251         case "Absolute error": return originalValues.Zip(estimatedValues, (x, y) => Math.Abs(x - y)).ToList();
    252         case "Squared error": return originalValues.Zip(estimatedValues, (x, y) => (x - y) * (x - y)).ToList();
    253         case "Relative error": return originalValues.Zip(estimatedValues, (x, y) => x.IsAlmost(0.0) ? -1 : Math.Abs((x - y) / x))
    254           .Where(x => x > 0) // remove entries where the original value is 0
    255           .ToList();
     251        case "Absolute error": return originalValues.Zip(estimatedValues, (x, y) => Math.Abs(x - y))
     252            .Where(r => !double.IsNaN(r) && !double.IsInfinity(r)).ToList();
     253        case "Squared error": return originalValues.Zip(estimatedValues, (x, y) => (x - y) * (x - y))
     254            .Where(r => !double.IsNaN(r) && !double.IsInfinity(r)).ToList();
     255        case "Relative error":
     256          return originalValues.Zip(estimatedValues, (x, y) => x.IsAlmost(0.0) ? -1 : Math.Abs((x - y) / x))
     257            .Where(r => r > 0 && !double.IsNaN(r) && !double.IsInfinity(r)) // remove entries where the original value is 0
     258            .ToList();
    256259        default: throw new NotSupportedException();
    257260      }
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionLineChartViewBase.cs

    r15583 r16388  
    2020#endregion
    2121using System;
    22 using System.Collections.Generic;
    2322using System.Drawing;
    2423using System.Linq;
     
    7271        this.chart.Series[TARGETVARIABLE_SERIES_NAME].LegendText = TARGETVARIABLE_SERIES_NAME;
    7372        this.chart.Series[TARGETVARIABLE_SERIES_NAME].ChartType = SeriesChartType.FastLine;
    74         this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray(),
    75           Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToArray());
     73
     74        var rows = Enumerable.Range(0, Content.ProblemData.Dataset.Rows).ToArray();
     75        var targetValues = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable);
     76
     77
     78        this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.DataBindXY(rows.ToArray(), targetValues.Select(v => double.IsInfinity(v) ? double.NaN : v).ToArray());
    7679        // training series
    7780        this.chart.Series.Add(ESTIMATEDVALUES_TRAINING_SERIES_NAME);
     
    161164      var targetValues = this.chart.Series[TARGETVARIABLE_SERIES_NAME].Points.Select(x => x.YValues[0]).DefaultIfEmpty(1.0);
    162165      double estimatedValuesRange = estimatedValues.Max() - estimatedValues.Min();
    163       double targetValuesRange = targetValues.Max() - targetValues.Min();
     166      double targetValuesRange = targetValues.Where(v => !double.IsInfinity(v) && !double.IsNaN(v)).Max() -
     167                                 targetValues.Where(v => !double.IsInfinity(v) && !double.IsNaN(v)).Min();
    164168      double interestingValuesRange = Math.Min(Math.Max(targetValuesRange, 1.0), Math.Max(estimatedValuesRange, 1.0));
    165169      double digits = (int)Math.Log10(interestingValuesRange) - 3;
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionResidualAnalysisView.cs

    r15583 r16388  
    8989      var runs = new RunCollection();
    9090      // determine relevant variables (at least two different values)
    91       var doubleVars = ds.DoubleVariables.Where(vn => ds.GetDoubleValues(vn).Max() > ds.GetDoubleValues(vn).Min()).ToArray();
     91      var doubleVars = ds.DoubleVariables.Where(vn => ds.GetDoubleValues(vn).Distinct().Skip(1).Any()).ToArray();
    9292      var stringVars = ds.StringVariables.Where(vn => ds.GetStringValues(vn).Distinct().Skip(1).Any()).ToArray();
    9393      var dateTimeVars = ds.DateTimeVariables.Where(vn => ds.GetDateTimeValues(vn).Distinct().Skip(1).Any()).ToArray();
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionResidualHistogram.cs

    r15583 r16388  
    126126
    127127      for (int i = 0; i < solution.ProblemData.Dataset.Rows; i++) {
     128        if (double.IsNaN(estimatedValues[i]) || double.IsInfinity(estimatedValues[i])) continue;
     129        if (double.IsNaN(targetValues[i]) || double.IsInfinity(targetValues[i])) continue;
    128130        double residual = estimatedValues[i] - targetValues[i];
    129131        residuals.Add(residual);
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionResidualsLineChartView.cs

    r15583 r16388  
    3838      var target = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, idx).ToArray();
    3939      for (int i = 0; i < idx.Length; i++) {
    40         x[i] = target[i] - x[i];
     40        if (!double.IsInfinity(target[i]) && !double.IsNaN(target[i]) &&
     41            !double.IsInfinity(x[i]) && !double.IsNaN(x[i])) {
     42          x[i] = target[i] - x[i];
     43        } else {
     44          x[i] = 0.0;
     45        }
    4146      }
    4247    }
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionScatterPlotView.cs

    r15583 r16388  
    166166          this.chart.Series[TEST_SERIES].Points.DataBindXY(dataset.GetDoubleValues(targetVariableName, Content.ProblemData.TestIndices).ToArray(), "",
    167167            Content.EstimatedTestValues.ToArray(), "");
    168         double max = Content.EstimatedTrainingValues.Concat(Content.EstimatedTestValues.Concat(Content.EstimatedValues.Concat(dataset.GetDoubleValues(targetVariableName)))).Max();
    169         double min = Content.EstimatedTrainingValues.Concat(Content.EstimatedTestValues.Concat(Content.EstimatedValues.Concat(dataset.GetDoubleValues(targetVariableName)))).Min();
     168        double max = Content.EstimatedTrainingValues
     169          .Concat(Content.EstimatedTestValues
     170          .Concat(Content.EstimatedValues
     171          .Concat(dataset.GetDoubleValues(targetVariableName))))
     172          .Where(v => !double.IsNaN(v) && !double.IsInfinity(v)).Max();
     173        double min = Content.EstimatedTrainingValues
     174          .Concat(Content.EstimatedTestValues
     175          .Concat(Content.EstimatedValues
     176          .Concat(dataset.GetDoubleValues(targetVariableName))))
     177          .Where(v => !double.IsNaN(v) && !double.IsInfinity(v)).Min();
    170178
    171179        double axisMin, axisMax, axisInterval;
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionVariableImpactsView.Designer.cs

    r15728 r16388  
    1919 */
    2020#endregion
     21
    2122
    2223namespace HeuristicLab.Problems.DataAnalysis.Views {
     
    5556      this.dataPartitionComboBox = new System.Windows.Forms.ComboBox();
    5657      this.variableImactsArrayView = new HeuristicLab.Data.Views.StringConvertibleArrayView();
    57       this.backgroundWorker = new System.ComponentModel.BackgroundWorker();
    5858      this.SuspendLayout();
    5959      //
     
    8282      this.sortByComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
    8383      this.sortByComboBox.FormattingEnabled = true;
     84      this.sortByComboBox.Items.AddRange(new object[] {
     85            HeuristicLab.Problems.DataAnalysis.Views.RegressionSolutionVariableImpactsView.SortingCriteria.ImpactValue,
     86            HeuristicLab.Problems.DataAnalysis.Views.RegressionSolutionVariableImpactsView.SortingCriteria.Occurrence,
     87            HeuristicLab.Problems.DataAnalysis.Views.RegressionSolutionVariableImpactsView.SortingCriteria.VariableName});
    8488      this.sortByComboBox.Location = new System.Drawing.Point(407, 3);
    8589      this.sortByComboBox.Name = "sortByComboBox";
     
    160164      // variableImactsArrayView
    161165      //
    162       this.variableImactsArrayView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
    163             | System.Windows.Forms.AnchorStyles.Left) 
     166      this.variableImactsArrayView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
     167            | System.Windows.Forms.AnchorStyles.Left)
    164168            | System.Windows.Forms.AnchorStyles.Right)));
    165169      this.variableImactsArrayView.Caption = "StringConvertibleArray View";
     
    170174      this.variableImactsArrayView.Size = new System.Drawing.Size(706, 278);
    171175      this.variableImactsArrayView.TabIndex = 2;
    172       //
    173       // backgroundWorker
    174       //
    175       this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_DoWork);
    176       this.backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted);
    177176      //
    178177      // RegressionSolutionVariableImpactsView
     
    192191      this.Name = "RegressionSolutionVariableImpactsView";
    193192      this.Size = new System.Drawing.Size(712, 365);
     193      this.VisibleChanged += new System.EventHandler(this.RegressionSolutionVariableImpactsView_VisibleChanged);
    194194      this.ResumeLayout(false);
    195195      this.PerformLayout();
     
    209209    private System.Windows.Forms.ComboBox sortByComboBox;
    210210    private System.Windows.Forms.CheckBox ascendingCheckBox;
    211     private System.ComponentModel.BackgroundWorker backgroundWorker;
    212211  }
    213212}
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionVariableImpactsView.cs

    r15728 r16388  
    2323using System.Collections.Generic;
    2424using System.Linq;
     25using System.Threading;
     26using System.Threading.Tasks;
    2527using HeuristicLab.Common;
    2628using HeuristicLab.Data;
     
    3133  [Content(typeof(IRegressionSolution))]
    3234  public partial class RegressionSolutionVariableImpactsView : DataAnalysisSolutionEvaluationView {
    33     #region Nested Types
    34     private class BackgroundWorkerArguments {
    35       internal MainForm.WindowsForms.MainForm mainForm;
    36       internal RegressionSolutionVariableImpactsCalculator.ReplacementMethodEnum replMethod;
    37       internal RegressionSolutionVariableImpactsCalculator.FactorReplacementMethodEnum factorReplMethod;
    38       internal RegressionSolutionVariableImpactsCalculator.DataPartitionEnum dataPartition;
    39     }
    40 
     35    private CancellationTokenSource cancellationToken = new CancellationTokenSource();
    4136    private enum SortingCriteria {
    4237      ImpactValue,
     
    4439      VariableName
    4540    }
    46     #endregion
    47 
    48     #region Fields
    49     private Dictionary<string, double> rawVariableImpacts = new Dictionary<string, double>();
    50     #endregion
    51 
    52     #region Getter/Setter
     41    private List<Tuple<string, double>> rawVariableImpacts = new List<Tuple<string, double>>();
     42
    5343    public new IRegressionSolution Content {
    5444      get { return (IRegressionSolution)base.Content; }
     
    5747      }
    5848    }
    59     #endregion
    60 
    61     #region Ctor
     49
    6250    public RegressionSolutionVariableImpactsView()
    6351      : base() {
    6452      InitializeComponent();
    6553
    66       //Little workaround. If you fill the ComboBox-Items in the other partial class, the UI-Designer will moan.
    67       this.sortByComboBox.Items.AddRange(Enum.GetValues(typeof(SortingCriteria)).Cast<object>().ToArray());
    68       this.sortByComboBox.SelectedItem = SortingCriteria.ImpactValue;
    69 
    7054      //Set the default values
    7155      this.dataPartitionComboBox.SelectedIndex = 0;
    72       this.replacementComboBox.SelectedIndex = 0;
     56      this.replacementComboBox.SelectedIndex = 3;
    7357      this.factorVarReplComboBox.SelectedIndex = 0;
    74     }
    75     #endregion
    76 
    77     #region Events
     58      this.sortByComboBox.SelectedItem = SortingCriteria.ImpactValue;
     59    }
     60
    7861    protected override void RegisterContentEvents() {
    7962      base.RegisterContentEvents();
     
    10184        variableImactsArrayView.Content = null;
    10285      } else {
    103         StartBackgroundWorker();
    104       }
     86        UpdateVariableImpact();
     87      }
     88    }
     89
     90    private void RegressionSolutionVariableImpactsView_VisibleChanged(object sender, EventArgs e) {
     91      cancellationToken.Cancel();
    10592    }
    10693
    10794
    10895    private void dataPartitionComboBox_SelectedIndexChanged(object sender, EventArgs e) {
    109       StartBackgroundWorker();
     96      UpdateVariableImpact();
    11097    }
    11198
    11299    private void replacementComboBox_SelectedIndexChanged(object sender, EventArgs e) {
    113       StartBackgroundWorker();
     100      UpdateVariableImpact();
    114101    }
    115102
     
    117104      //Update the default ordering (asc,desc), but remove the eventHandler beforehand (otherwise the data would be ordered twice)
    118105      ascendingCheckBox.CheckedChanged -= ascendingCheckBox_CheckedChanged;
    119       switch ((SortingCriteria)sortByComboBox.SelectedItem) {
    120         case SortingCriteria.ImpactValue:
    121           ascendingCheckBox.Checked = false;
    122           break;
    123         case SortingCriteria.Occurrence:
    124           ascendingCheckBox.Checked = true;
    125           break;
    126         case SortingCriteria.VariableName:
    127           ascendingCheckBox.Checked = true;
    128           break;
    129         default:
    130           throw new NotImplementedException("Ordering for selected SortingCriteria not implemented");
    131       }
     106      ascendingCheckBox.Checked = (SortingCriteria)sortByComboBox.SelectedItem != SortingCriteria.ImpactValue;
    132107      ascendingCheckBox.CheckedChanged += ascendingCheckBox_CheckedChanged;
    133108
    134       UpdateDataOrdering();
     109      UpdateOrdering();
    135110    }
    136111
    137112    private void ascendingCheckBox_CheckedChanged(object sender, EventArgs e) {
    138       UpdateDataOrdering();
    139     }
    140 
    141 
    142     private void backgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
    143       variableImactsArrayView.Caption = Content.Name + " Variable Impacts";
    144 
    145       var argument = e.Argument as BackgroundWorkerArguments;
    146       if (!(argument is BackgroundWorkerArguments)) {
    147         throw new ArgumentException("Argument for Backgroundworker must be of type BackgroundworkerArguments");
    148       }
    149 
    150       argument.mainForm.AddOperationProgressToView(this, "Calculating variable impacts for " + Content.Name);
    151       try {
    152         //Remember the original ordering of the variables
    153         var impacts = RegressionSolutionVariableImpactsCalculator.CalculateImpacts(Content, argument.dataPartition, argument.replMethod, argument.factorReplMethod);
    154         var problemData = Content.ProblemData;
    155         var inputvariables = new HashSet<string>(problemData.AllowedInputVariables.Union(Content.Model.VariablesUsedForPrediction));
    156         var originalVariableOrdering = problemData.Dataset.VariableNames.Where(v => inputvariables.Contains(v)).Where(problemData.Dataset.VariableHasType<double>).ToList();
    157 
    158         rawVariableImpacts.Clear();
    159         originalVariableOrdering.ForEach(v => rawVariableImpacts.Add(v, impacts.First(vv => vv.Item1 == v).Item2));
    160       } finally {
    161         argument.mainForm.RemoveOperationProgressFromView(this);
    162       }
    163     }
    164 
    165     private void backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) {
    166       UpdateDataOrdering();
    167     }
    168     #endregion
    169 
    170     #region Helper Methods   
    171     private void StartBackgroundWorker() {
     113      UpdateOrdering();
     114    }
     115
     116
     117    private async void UpdateVariableImpact() {
     118      IProgress progress;
     119
    172120      //Check if the selection is valid
    173121      if (Content == null) { return; }
     
    181129      var factorReplMethod = (RegressionSolutionVariableImpactsCalculator.FactorReplacementMethodEnum)factorVarReplComboBox.Items[factorVarReplComboBox.SelectedIndex];
    182130      var dataPartition = (RegressionSolutionVariableImpactsCalculator.DataPartitionEnum)dataPartitionComboBox.SelectedItem;
    183       var args = new BackgroundWorkerArguments() {
    184         mainForm = mainForm,
    185         replMethod = replMethod,
    186         factorReplMethod = factorReplMethod,
    187         dataPartition = dataPartition
    188       };
    189 
    190       //Let the backgroundWorker do his job (unless he's already running)
    191       //fholzing: Possible bug -> A ContentChanged won't update the data if the backgroundworker is already running
    192       if (!backgroundWorker.IsBusy) { backgroundWorker.RunWorkerAsync(args); }
     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      }
    193160    }
    194161
     
    197164    /// The default is "Descending" by "VariableImpact" (as in previous versions)
    198165    /// </summary>
    199     private void UpdateDataOrdering() {
     166    private void UpdateOrdering() {
    200167      //Check if valid sortingCriteria is selected and data exists
    201168      if (sortByComboBox.SelectedIndex == -1) { return; }
     
    206173      bool ascending = ascendingCheckBox.Checked;
    207174
    208       IEnumerable<KeyValuePair<string, double>> orderedEntries = null;
     175      IEnumerable<Tuple<string, double>> orderedEntries = null;
    209176
    210177      //Sort accordingly
    211178      switch (selectedItem) {
    212179        case SortingCriteria.ImpactValue:
    213           orderedEntries = rawVariableImpacts.OrderBy(v => v.Value);
     180          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item2);
    214181          break;
    215182        case SortingCriteria.Occurrence:
     
    217184          break;
    218185        case SortingCriteria.VariableName:
    219           orderedEntries = rawVariableImpacts.OrderBy(v => v.Key, new NaturalStringComparer());
     186          orderedEntries = rawVariableImpacts.OrderBy(v => v.Item1, new NaturalStringComparer());
    220187          break;
    221188        default:
     
    226193
    227194      //Write the data back
    228       var impactArray = new DoubleArray(orderedEntries.Select(i => i.Value).ToArray()) {
    229         ElementNames = orderedEntries.Select(i => i.Key)
     195      var impactArray = new DoubleArray(orderedEntries.Select(i => i.Item2).ToArray()) {
     196        ElementNames = orderedEntries.Select(i => i.Item1)
    230197      };
    231198
    232       //Could be, if the View was closed during the BackgroundWorker-run
     199      //Could be, if the View was closed
    233200      if (!variableImactsArrayView.IsDisposed) {
    234201        variableImactsArrayView.Content = (DoubleArray)impactArray.AsReadOnly();
    235202      }
    236203    }
    237     #endregion
    238204  }
    239205}
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Solution Views/DataAnalysisSolutionView.cs

    r15583 r16388  
    141141
    142142        var solution = (IDataAnalysisSolution)Content.Clone();
    143         problemData.AdjustProblemDataProperties(solution.ProblemData);
    144 
    145143        solution.ProblemData = problemData;
    146144        if (!solution.Name.EndsWith(" with loaded problemData"))
     
    231229
    232230      try {
    233         problemData.AdjustProblemDataProperties(Content.ProblemData);
    234231        Content.ProblemData = problemData;
    235232
  • branches/2892_LR-prediction-intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/TimeSeriesPrognosis/TimeSeriesPrognosisResidualsLineChartView.cs

    r15583 r16388  
    2020#endregion
    2121
    22 using System;
    2322using System.Linq;
    24 using System.Windows.Forms.DataVisualization.Charting;
    2523using HeuristicLab.MainForm;
    2624
Note: See TracChangeset for help on using the changeset viewer.