Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2971_named_intervals/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionPartialDependencePlotView.cs @ 18190

Last change on this file since 18190 was 17208, checked in by gkronber, 5 years ago

#2971: merged r17180:17184 from trunk to branch

File size: 27.0 KB
RevLine 
[13817]1#region License Information
2/* HeuristicLab
[17208]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[13817]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
[13828]22using System;
[14826]23using System.Collections;
[13817]24using System.Collections.Generic;
[13850]25using System.Drawing;
[14267]26using System.Globalization;
[13808]27using System.Linq;
[13843]28using System.Threading.Tasks;
[13808]29using System.Windows.Forms;
30using HeuristicLab.Common;
31using HeuristicLab.MainForm;
[13843]32using HeuristicLab.Visualization.ChartControlsExtensions;
[13808]33
34namespace HeuristicLab.Problems.DataAnalysis.Views {
[14852]35  [View("Partial Dependence Plots")]
[13808]36  [Content(typeof(IRegressionSolution))]
[14852]37  public partial class RegressionSolutionPartialDependencePlotView : DataAnalysisSolutionEvaluationView {
38    private readonly Dictionary<string, IPartialDependencePlot> partialDependencePlots;
[13850]39    private readonly Dictionary<string, DensityChart> densityCharts;
40    private readonly Dictionary<string, Panel> groupingPanels;
[14267]41    private ModifiableDataset sharedFixedVariables;
[13850]42
[13831]43    private const int Points = 200;
[13995]44    private int MaxColumns = 4;
[13808]45
[13850]46    private IEnumerable<string> VisibleVariables {
47      get {
48        foreach (ListViewItem item in variableListView.CheckedItems)
49          yield return item.Text;
50      }
[13843]51    }
[14852]52    private IEnumerable<IPartialDependencePlot> VisiblePartialDependencePlots {
53      get { return VisibleVariables.Select(v => partialDependencePlots[v]); }
[13850]54    }
55    private IEnumerable<DensityChart> VisibleDensityCharts {
56      get { return VisibleVariables.Select(v => densityCharts[v]); }
57    }
58    private IEnumerable<Panel> VisibleChartsPanels {
59      get { return VisibleVariables.Select(v => groupingPanels[v]); }
60    }
[13843]61
[14852]62    public RegressionSolutionPartialDependencePlotView() {
[13808]63      InitializeComponent();
[14852]64      partialDependencePlots = new Dictionary<string, IPartialDependencePlot>();
[13850]65      densityCharts = new Dictionary<string, DensityChart>();
66      groupingPanels = new Dictionary<string, Panel>();
[13846]67
68      limitView.Content = new DoubleLimit(0, 1);
[14021]69      limitView.Content.ValueChanged += limit_ValueChanged;
[13850]70
[14021]71      densityComboBox.SelectedIndex = 1; // select Training
72
[13850]73      // Avoid additional horizontal scrollbar
74      var vertScrollWidth = SystemInformation.VerticalScrollBarWidth;
75      scrollPanel.Padding = new Padding(0, 0, vertScrollWidth, 0);
76      scrollPanel.AutoScroll = true;
[13808]77    }
78
79    public new IRegressionSolution Content {
80      get { return (IRegressionSolution)base.Content; }
[13831]81      set { base.Content = value; }
[13808]82    }
83
84    protected override void RegisterContentEvents() {
85      base.RegisterContentEvents();
[13995]86      Content.ModelChanged += solution_ModelChanged;
[13808]87    }
88
89    protected override void DeregisterContentEvents() {
[13995]90      Content.ModelChanged -= solution_ModelChanged;
[13808]91      base.DeregisterContentEvents();
92    }
93
94    protected override void OnContentChanged() {
95      base.OnContentChanged();
[13817]96      if (Content == null) return;
[13831]97      var problemData = Content.ProblemData;
[13846]98
[16519]99      if (sharedFixedVariables != null) {
100        sharedFixedVariables.ItemChanged -= SharedFixedVariables_ItemChanged;
101        sharedFixedVariables.Reset -= SharedFixedVariables_Reset;
102      }
103
[13846]104      // Init Y-axis range
105      double min = double.MaxValue, max = double.MinValue;
106      var trainingTarget = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
107      foreach (var t in trainingTarget) {
108        if (t < min) min = t;
109        if (t > max) max = t;
110      }
111      double range = max - min;
112      const double scale = 1.0 / 3.0;
113      double axisMin, axisMax, axisInterval;
114      ChartUtil.CalculateAxisInterval(min - scale * range, max + scale * range, 5, out axisMin, out axisMax, out axisInterval);
115      automaticYAxisCheckBox.Checked = false;
116      limitView.ReadOnly = false;
117      limitView.Content.Lower = axisMin;
118      limitView.Content.Upper = axisMax;
119
[14464]120      // create dataset of problemData input variables and model input variables
121      // necessary workaround to have the variables in the occuring order
122      var inputvariables =
123        new HashSet<string>(Content.ProblemData.AllowedInputVariables.Union(Content.Model.VariablesUsedForPrediction));
124      var allowedInputVariables =
125        Content.ProblemData.Dataset.VariableNames.Where(v => inputvariables.Contains(v)).ToList();
126
[14826]127      var doubleVariables = allowedInputVariables.Where(problemData.Dataset.VariableHasType<double>);
[16519]128      var doubleVariableValues = (IEnumerable<IList>)doubleVariables.Select(x => new List<double> {
129        problemData.Dataset.GetDoubleValue(x, 0)
130      });
[14826]131
132      var factorVariables = allowedInputVariables.Where(problemData.Dataset.VariableHasType<string>);
133      var factorVariableValues = (IEnumerable<IList>)factorVariables.Select(x => new List<string> {
[16519]134        problemData.Dataset.GetStringValue(x, 0)
[14826]135      });
136
137      sharedFixedVariables = new ModifiableDataset(doubleVariables.Concat(factorVariables), doubleVariableValues.Concat(factorVariableValues));
[16519]138      variableValuesModeComboBox.SelectedItem = "Median"; // triggers UpdateVariableValue and changes shardFixedVariables
[14826]139
[13850]140      // create controls
[14852]141      partialDependencePlots.Clear();
[13850]142      densityCharts.Clear();
143      groupingPanels.Clear();
[14826]144      foreach (var variableName in doubleVariables) {
[14852]145        var plot = CreatePartialDependencePlot(variableName, sharedFixedVariables);
146        partialDependencePlots.Add(variableName, plot);
[13850]147
148        var densityChart = new DensityChart() {
149          Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right,
150          Margin = Padding.Empty,
151          Height = 12,
[14131]152          Visible = false,
[14852]153          Top = (int)(plot.Height * 0.1),
[13850]154        };
155        densityCharts.Add(variableName, densityChart);
156
[14852]157        plot.ZoomChanged += (o, e) => {
158          var pdp = (PartialDependencePlot)o;
159          var density = densityCharts[pdp.FreeVariable];
160          density.Visible = densityComboBox.SelectedIndex != 0 && !pdp.IsZoomed;
[14089]161          if (density.Visible)
[14852]162            UpdateDensityChart(density, pdp.FreeVariable);
[14089]163        };
[14852]164        plot.SizeChanged += (o, e) => {
165          var pdp = (PartialDependencePlot)o;
166          var density = densityCharts[pdp.FreeVariable];
167          density.Top = (int)(pdp.Height * 0.1);
[14131]168        };
[14089]169
[16519]170        // Initially, the inner plot areas are not initialized for hidden charts (scrollpanel, ...)
[14158]171        // This event handler listens for the paint event once (where everything is already initialized) to do some manual layouting.
[14852]172        plot.ChartPostPaint += OnPartialDependencePlotPostPaint;
[14158]173
[13850]174        var panel = new Panel() {
[13820]175          Dock = DockStyle.Fill,
176          Margin = Padding.Empty,
[13850]177          BackColor = Color.White
[13820]178        };
[13843]179
[13850]180        panel.Controls.Add(densityChart);
[14852]181        panel.Controls.Add(plot);
[13850]182        groupingPanels.Add(variableName, panel);
[13808]183      }
[14826]184      foreach (var variableName in factorVariables) {
[14852]185        var plot = CreateFactorPartialDependencePlot(variableName, sharedFixedVariables);
186        partialDependencePlots.Add(variableName, plot);
[13850]187
[14826]188        var densityChart = new DensityChart() {
189          Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right,
190          Margin = Padding.Empty,
191          Height = 12,
192          Visible = false,
[14852]193          Top = (int)(plot.Height * 0.1),
[14826]194        };
195        densityCharts.Add(variableName, densityChart);
[14852]196        plot.ZoomChanged += (o, e) => {
197          var pdp = (FactorPartialDependencePlot)o;
198          var density = densityCharts[pdp.FreeVariable];
199          density.Visible = densityComboBox.SelectedIndex != 0 && !pdp.IsZoomed;
[14826]200          if (density.Visible)
[14852]201            UpdateDensityChart(density, pdp.FreeVariable);
[14826]202        };
[14852]203        plot.SizeChanged += (o, e) => {
204          var pdp = (FactorPartialDependencePlot)o;
205          var density = densityCharts[pdp.FreeVariable];
206          density.Top = (int)(pdp.Height * 0.1);
[14826]207        };
208
[16519]209        // Initially, the inner plot areas are not initialized for hidden charts (scrollpanel, ...)
[14826]210        // This event handler listens for the paint event once (where everything is already initialized) to do some manual layouting.
[14852]211        plot.ChartPostPaint += OnFactorPartialDependencePlotPostPaint;
[14826]212
213        var panel = new Panel() {
214          Dock = DockStyle.Fill,
215          Margin = Padding.Empty,
216          BackColor = Color.White
217        };
218
219        panel.Controls.Add(densityChart);
[14852]220        panel.Controls.Add(plot);
[14826]221        groupingPanels.Add(variableName, panel);
222      }
[13828]223      // update variable list
[14021]224      variableListView.ItemChecked -= variableListView_ItemChecked;
[13828]225      variableListView.Items.Clear();
[13845]226      foreach (var variable in allowedInputVariables)
227        variableListView.Items.Add(key: variable, text: variable, imageIndex: 0);
228
[13948]229      foreach (var variable in Content.Model.VariablesUsedForPrediction)
[13845]230        variableListView.Items[variable].Checked = true;
[14021]231      variableListView.ItemChecked += variableListView_ItemChecked;
232
[14267]233      sharedFixedVariables.ItemChanged += SharedFixedVariables_ItemChanged;
[16519]234      sharedFixedVariables.Reset += SharedFixedVariables_Reset;
[14267]235
[16519]236      rowNrNumericUpDown.Maximum = Content.ProblemData.Dataset.Rows - 1;
237
[14021]238      RecalculateAndRelayoutCharts();
[13808]239    }
[14021]240
[14267]241    private void SharedFixedVariables_ItemChanged(object sender, EventArgs<int, int> e) {
[16519]242      SharedFixedVariablesChanged();
243    }
244    private void SharedFixedVariables_Reset(object sender, EventArgs e) {
245      SharedFixedVariablesChanged();
246    }
247    private void SharedFixedVariablesChanged() {
248      if (!setVariableValues) // set mode to "nothing" if change was not initiated from a "mode change"
249        variableValuesModeComboBox.SelectedIndex = -1;
250
[14267]251      double yValue = Content.Model.GetEstimatedValues(sharedFixedVariables, new[] { 0 }).Single();
252      string title = Content.ProblemData.TargetVariable + ": " + yValue.ToString("G5", CultureInfo.CurrentCulture);
[14852]253      foreach (var chart in partialDependencePlots.Values) {
[14267]254        if (!string.IsNullOrEmpty(chart.YAxisTitle)) { // only show title for first column in grid
255          chart.YAxisTitle = title;
256        }
257      }
258    }
259
[14852]260    private void OnPartialDependencePlotPostPaint(object o, EventArgs e) {
261      var plot = (PartialDependencePlot)o;
262      var density = densityCharts[plot.FreeVariable];
[14158]263
[14852]264      density.Width = plot.Width;
[14158]265
[14852]266      var gcPlotPosition = plot.InnerPlotPosition;
267      density.Left = (int)(gcPlotPosition.X / 100.0 * plot.Width);
268      density.Width = (int)(gcPlotPosition.Width / 100.0 * plot.Width);
269      plot.UpdateTitlePosition();
[14158]270
271      // removed after succesful layouting due to performance reasons
272      if (gcPlotPosition.Width != 0)
[14852]273        plot.ChartPostPaint -= OnPartialDependencePlotPostPaint;
[14158]274    }
275
[14852]276    private void OnFactorPartialDependencePlotPostPaint(object o, EventArgs e) {
277      var plot = (FactorPartialDependencePlot)o;
278      var density = densityCharts[plot.FreeVariable];
[14826]279
[14852]280      density.Width = plot.Width;
[14826]281
[14852]282      var gcPlotPosition = plot.InnerPlotPosition;
283      density.Left = (int)(gcPlotPosition.X / 100.0 * plot.Width);
284      density.Width = (int)(gcPlotPosition.Width / 100.0 * plot.Width);
285      plot.UpdateTitlePosition();
[14826]286
287      // removed after succesful layouting due to performance reasons
288      if (gcPlotPosition.Width != 0)
[14852]289        plot.ChartPostPaint -= OnFactorPartialDependencePlotPostPaint;
[14826]290    }
291
[14021]292    private async void RecalculateAndRelayoutCharts() {
293      foreach (var variable in VisibleVariables) {
[14852]294        var plot = partialDependencePlots[variable];
295        await plot.RecalculateAsync(false, false);
[14021]296      }
[14852]297      partialDependencePlotTableLayout.SuspendLayout();
[14021]298      SetupYAxis();
299      ReOrderControls();
300      SetStyles();
[14852]301      partialDependencePlotTableLayout.ResumeLayout();
302      partialDependencePlotTableLayout.Refresh();
[14021]303      foreach (var variable in VisibleVariables) {
[14826]304        DensityChart densityChart;
305        if (densityCharts.TryGetValue(variable, out densityChart)) {
306          UpdateDensityChart(densityChart, variable);
307        }
[14021]308      }
309    }
[14852]310    private PartialDependencePlot CreatePartialDependencePlot(string variableName, ModifiableDataset sharedFixedVariables) {
311      var plot = new PartialDependencePlot {
[13850]312        Dock = DockStyle.Fill,
313        Margin = Padding.Empty,
314        ShowLegend = false,
315        ShowCursor = true,
[13855]316        ShowConfigButton = false,
[13850]317        YAxisTicks = 5,
318      };
[14852]319      plot.VariableValueChanged += async (o, e) => {
320        var recalculations = VisiblePartialDependencePlots
321          .Except(new[] { (IPartialDependencePlot)o })
[14826]322          .Select(async chart => {
323            await chart.RecalculateAsync(updateOnFinish: false, resetYAxis: false);
324          }).ToList();
[13850]325        await Task.WhenAll(recalculations);
[13843]326
[13850]327        if (recalculations.All(t => t.IsCompleted))
328          SetupYAxis();
329      };
[14852]330      plot.Configure(new[] { Content }, sharedFixedVariables, variableName, Points);
331      plot.SolutionAdded += partialDependencePlot_SolutionAdded;
332      plot.SolutionRemoved += partialDependencePlot_SolutionRemoved;
333      return plot;
[13850]334    }
[14852]335    private FactorPartialDependencePlot CreateFactorPartialDependencePlot(string variableName, ModifiableDataset sharedFixedVariables) {
336      var plot = new FactorPartialDependencePlot {
[14826]337        Dock = DockStyle.Fill,
338        Margin = Padding.Empty,
339        ShowLegend = false,
340        ShowCursor = true,
341        YAxisTicks = 5,
342      };
[14852]343      plot.VariableValueChanged += async (o, e) => {
344        var recalculations = VisiblePartialDependencePlots
345          .Except(new[] { (FactorPartialDependencePlot)o })
[14826]346          .Select(async chart => {
347            await chart.RecalculateAsync(updateOnFinish: false, resetYAxis: false);
348          }).ToList();
349        await Task.WhenAll(recalculations);
[13850]350
[14826]351        if (recalculations.All(t => t.IsCompleted))
352          SetupYAxis();
353      };
354      var variableValues = Content.ProblemData.Dataset.GetStringValues(variableName).Distinct().OrderBy(n => n).ToList();
[14852]355      plot.Configure(new[] { Content }, sharedFixedVariables, variableName, variableValues);
356      plot.SolutionAdded += partialDependencePlot_SolutionAdded;
357      plot.SolutionRemoved += partialDependencePlot_SolutionRemoved;
358      return plot;
[14826]359    }
[13846]360    private void SetupYAxis() {
361      double axisMin, axisMax;
362      if (automaticYAxisCheckBox.Checked) {
363        double min = double.MaxValue, max = double.MinValue;
[14852]364        foreach (var chart in VisiblePartialDependencePlots) {
[13846]365          if (chart.YMin < min) min = chart.YMin;
366          if (chart.YMax > max) max = chart.YMax;
367        }
368
369        double axisInterval;
370        ChartUtil.CalculateAxisInterval(min, max, 5, out axisMin, out axisMax, out axisInterval);
371      } else {
372        axisMin = limitView.Content.Lower;
373        axisMax = limitView.Content.Upper;
[13843]374      }
375
[14852]376      foreach (var chart in VisiblePartialDependencePlots) {
[13843]377        chart.FixedYAxisMin = axisMin;
378        chart.FixedYAxisMax = axisMax;
379      }
380    }
381
[13850]382    // reorder chart controls so that they always appear in the same order as in the list view
383    // the table layout containing the controls should be suspended before calling this method
384    private void ReOrderControls() {
[14852]385      var tl = partialDependencePlotTableLayout;
[13828]386      tl.Controls.Clear();
[13850]387      int row = 0, column = 0;
[14267]388      double yValue = Content.Model.GetEstimatedValues(sharedFixedVariables, new[] { 0 }).Single();
389      string title = Content.ProblemData.TargetVariable + ": " + yValue.ToString("G5", CultureInfo.CurrentCulture);
390
[14014]391      foreach (var v in VisibleVariables) {
392        var chartsPanel = groupingPanels[v];
[13850]393        tl.Controls.Add(chartsPanel, column, row);
[14014]394
[14852]395        var chart = partialDependencePlots[v];
[14267]396        chart.YAxisTitle = column == 0 ? title : string.Empty;
[13850]397        column++;
[14014]398
[13850]399        if (column == MaxColumns) {
400          row++;
401          column = 0;
402        }
403      }
[13828]404    }
[13808]405
[13995]406    private void SetStyles() {
[14852]407      var tl = partialDependencePlotTableLayout;
[13995]408      tl.RowStyles.Clear();
409      tl.ColumnStyles.Clear();
410      int numVariables = VisibleVariables.Count();
411      if (numVariables == 0)
412        return;
413
414      // set column styles
415      tl.ColumnCount = Math.Min(numVariables, MaxColumns);
416      for (int c = 0; c < tl.ColumnCount; c++)
417        tl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100.0f / tl.ColumnCount));
418
419      // set row styles
420      tl.RowCount = (int)Math.Ceiling((double)numVariables / tl.ColumnCount);
421      var columnWidth = tl.Width / tl.ColumnCount; // assume all columns have the same width
422      var rowHeight = (int)(0.8 * columnWidth);
423      for (int r = 0; r < tl.RowCount; r++)
424        tl.RowStyles.Add(new RowStyle(SizeType.Absolute, rowHeight));
425    }
426
[14852]427    private async void partialDependencePlot_SolutionAdded(object sender, EventArgs<IRegressionSolution> e) {
[13995]428      var solution = e.Value;
[14852]429      foreach (var chart in partialDependencePlots.Values) {
[13995]430        if (sender == chart) continue;
431        await chart.AddSolutionAsync(solution);
432      }
433    }
434
[14852]435    private async void partialDependencePlot_SolutionRemoved(object sender, EventArgs<IRegressionSolution> e) {
[13995]436      var solution = e.Value;
[14852]437      foreach (var chart in partialDependencePlots.Values) {
[13995]438        if (sender == chart) continue;
439        await chart.RemoveSolutionAsync(solution);
440      }
441    }
442
[13842]443    private async void variableListView_ItemChecked(object sender, ItemCheckedEventArgs e) {
[13808]444      var item = e.Item;
445      var variable = item.Text;
[14852]446      var plot = partialDependencePlots[variable];
[13850]447      var chartsPanel = groupingPanels[variable];
[14852]448      var tl = partialDependencePlotTableLayout;
[13850]449
[13817]450      tl.SuspendLayout();
[13808]451      if (item.Checked) {
[13850]452        tl.Controls.Add(chartsPanel);
[14852]453        await plot.RecalculateAsync(false, false);
[13808]454      } else {
[13850]455        tl.Controls.Remove(chartsPanel);
[13808]456      }
[13843]457
[13850]458      if (tl.Controls.Count > 0) {
459        SetupYAxis();
460        ReOrderControls();
[13995]461        SetStyles();
[13828]462      }
[13817]463      tl.ResumeLayout();
[14021]464      tl.Refresh();
465      densityComboBox_SelectedIndexChanged(this, EventArgs.Empty);
[13808]466    }
[13846]467
468    private void automaticYAxisCheckBox_CheckedChanged(object sender, EventArgs e) {
469      limitView.ReadOnly = automaticYAxisCheckBox.Checked;
470      SetupYAxis();
[14852]471      partialDependencePlotTableLayout.Refresh();
[14021]472      densityComboBox_SelectedIndexChanged(this, EventArgs.Empty); // necessary to realign the density plots
[13846]473    }
474
475    private void limit_ValueChanged(object sender, EventArgs e) {
476      if (automaticYAxisCheckBox.Checked)
477        return;
478      SetupYAxis();
[14852]479      partialDependencePlotTableLayout.Refresh();
[14021]480      densityComboBox_SelectedIndexChanged(this, EventArgs.Empty); // necessary to realign the density plots
[13846]481    }
[13850]482
483    private void densityComboBox_SelectedIndexChanged(object sender, EventArgs e) {
[14021]484      if (Content == null)
485        return;
486
[13850]487      int si = densityComboBox.SelectedIndex;
488      if (si == 0) {
489        foreach (var densityChart in densityCharts.Values)
490          densityChart.Visible = false;
491      } else {
492        var indices = GetDensityIndices(si).ToList();
493
494        foreach (var entry in densityCharts) {
495          var variableName = entry.Key;
496          var densityChart = entry.Value;
[14852]497          if (!VisibleVariables.Contains(variableName) || partialDependencePlots[variableName].IsZoomed)
[13850]498            continue;
[14089]499
[13850]500          UpdateDensityChart(densityChart, variableName, indices);
501        }
502      }
503    }
504    private IEnumerable<int> GetDensityIndices(int selectedIndex) {
505      var problemData = Content.ProblemData;
506      return
507        selectedIndex == 1 ? problemData.TrainingIndices :
508        selectedIndex == 2 ? problemData.TestIndices :
509        problemData.AllIndices;
510    }
511    private void UpdateDensityChart(DensityChart densityChart, string variable, IList<int> indices = null) {
512      if (densityComboBox.SelectedIndex == 0)
513        return;
514      if (indices == null) {
515        indices = GetDensityIndices(densityComboBox.SelectedIndex).ToList();
516      }
[14826]517      if (Content.ProblemData.Dataset.VariableHasType<double>(variable)) {
518        var data = Content.ProblemData.Dataset.GetDoubleValues(variable, indices).ToList();
[14852]519        var plot = partialDependencePlots[variable] as PartialDependencePlot;
520        if (plot != null) {
521          var min = plot.FixedXAxisMin;
522          var max = plot.FixedXAxisMax;
523          var buckets = plot.DrawingSteps;
[14826]524          if (min.HasValue && max.HasValue) {
525            densityChart.UpdateChart(data, min.Value, max.Value, buckets);
[14852]526            densityChart.Width = plot.Width;
[13850]527
[14852]528            var gcPlotPosition = plot.InnerPlotPosition;
529            densityChart.Left = (int)(gcPlotPosition.X / 100.0 * plot.Width);
530            densityChart.Width = (int)(gcPlotPosition.Width / 100.0 * plot.Width);
[13850]531
[14826]532            densityChart.Visible = true;
533          }
[14852]534          plot.UpdateTitlePosition();
[14826]535        }
536      } else if (Content.ProblemData.Dataset.VariableHasType<string>(variable)) {
537        var data = Content.ProblemData.Dataset.GetStringValues(variable).ToList();
[14852]538        var plot = partialDependencePlots[variable] as FactorPartialDependencePlot;
539        if (plot != null) {
[14826]540          densityChart.UpdateChart(data);
[14852]541          densityChart.Width = plot.Width;
[14826]542
[14852]543          var gcPlotPosition = plot.InnerPlotPosition;
544          densityChart.Left = (int)(gcPlotPosition.X / 100.0 * plot.Width);
545          densityChart.Width = (int)(gcPlotPosition.Width / 100.0 * plot.Width);
[14826]546
547          densityChart.Visible = true;
548
[14852]549          plot.UpdateTitlePosition();
[14826]550        }
[13850]551      }
552    }
[13995]553
[14089]554    private void columnsNumericUpDown_ValueChanged(object sender, EventArgs e) {
555      MaxColumns = (int)columnsNumericUpDown.Value;
[13995]556      int columns = Math.Min(VisibleVariables.Count(), MaxColumns);
557      if (columns > 0) {
[14852]558        var tl = partialDependencePlotTableLayout;
[13995]559        MaxColumns = columns;
560        tl.SuspendLayout();
561        ReOrderControls();
562        SetStyles();
[14021]563        tl.ResumeLayout();
564        tl.Refresh();
565        densityComboBox_SelectedIndexChanged(this, EventArgs.Empty);
[13995]566      }
567    }
568
[14021]569    private async void solution_ModelChanged(object sender, EventArgs e) {
570      foreach (var variable in VisibleVariables) {
[14852]571        var pdp = partialDependencePlots[variable];
[14021]572        var densityChart = densityCharts[variable];
573        // recalculate and refresh
[14852]574        await pdp.RecalculateAsync(false, false);
575        pdp.Refresh();
[14021]576        UpdateDensityChart(densityChart, variable);
[13996]577      }
[13995]578    }
[16519]579
580    // flag that the current change is not triggered by a manual change from within a single plot
581    private bool setVariableValues = false;
582    private void variableValuesComboBox_SelectedValueChanged(object sender, EventArgs e) {
583      if (variableValuesModeComboBox.SelectedIndex == -1)
584        return; // changed to "manual" due to manual change of a variable
585      setVariableValues = true;
586      UpdateVariableValues();
587      setVariableValues = false;
588    }
589    private void rowNrNumericUpDown_ValueChanged(object sender, EventArgs e) {
590      if ((string)variableValuesModeComboBox.SelectedItem != "Row") {
591        variableValuesModeComboBox.SelectedItem = "Row"; // triggers UpdateVariableValues
592      } else {
593        setVariableValues = true;
594        UpdateVariableValues();
595        setVariableValues = false;
596      }
597    }
598    private void UpdateVariableValues() {
599      string mode = (string)variableValuesModeComboBox.SelectedItem;
600
601      var dataset = Content.ProblemData.Dataset;
602      object[] newRow;
603
604      if (mode == "Row") {
605        int rowNumber = (int)rowNrNumericUpDown.Value;
606        newRow = sharedFixedVariables.VariableNames
607          .Select<string, object>(variableName => {
608            if (dataset.DoubleVariables.Contains(variableName)) {
609              return dataset.GetDoubleValue(variableName, rowNumber);
610            } else if (dataset.StringVariables.Contains(variableName)) {
611              return dataset.GetStringValue(variableName, rowNumber);
612            } else {
613              throw new NotSupportedException("Only double and string(factor) columns are currently supported.");
614            }
615          }).ToArray();
616      } else {
617        newRow = sharedFixedVariables.VariableNames
618          .Select<string, object>(variableName => {
619            if (dataset.DoubleVariables.Contains(variableName)) {
620              var values = dataset.GetDoubleValues(variableName);
621              return
622                mode == "Mean" ? values.Average() :
623                mode == "Median" ? values.Median() :
624                mode == "Most Common" ? MostCommon(values) :
625                throw new NotSupportedException();
626            } else if (dataset.StringVariables.Contains(variableName)) {
627              var values = dataset.GetStringValues(variableName);
628              return
629                mode == "Mean" ? MostCommon(values) :
630                mode == "Median" ? MostCommon(values) :
631                mode == "Most Common" ? MostCommon(values) :
632                throw new NotSupportedException();
633            } else {
634              throw new NotSupportedException("Only double and string(factor) columns are currently supported.");
635            }
636          }).ToArray();
637      }
638
639      sharedFixedVariables.ReplaceRow(0, newRow);
640    }
641
642    private static T MostCommon<T>(IEnumerable<T> values) {
643      return values.GroupBy(x => x).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
644    }
645
646    // ToolTips cannot be shown longer than 5000ms, only by using ToolTip.Show manually
647    // See: https://stackoverflow.com/questions/8225807/c-sharp-tooltip-doesnt-display-long-enough
648    private void variableValuesModeComboBox_MouseHover(object sender, EventArgs e) {
649      string tooltipText = @"Sets each variable to a specific value:
650    Row - Selects the value based on a specified row of the dataset.
651    Mean - Sets the value to the arithmetic mean of the variable.
652    Median - Sets the value to the median of the variable.
653    Most Common - Sets the value to the most common value of the variable (first if multiple).
654
655Note: For categorical values, the most common value is used when selecting Mean, Median or Most Common.";
656      toolTip.Show(tooltipText, variableValuesModeComboBox, 30000);
657      toolTip.Active = true;
658    }
659    private void variableValuesModeComboBox_MouseLeave(object sender, EventArgs e) {
660      toolTip.Active = false;
661    }
[13808]662  }
663}
Note: See TracBrowser for help on using the repository browser.