Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionTargetResponseGradientView.cs @ 14429

Last change on this file since 14429 was 14307, checked in by pfleck, 8 years ago

#2662 Fixed the event deregistration.

File size: 17.4 KB
RevLine 
[13817]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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
[13828]22using System;
[13817]23using System.Collections.Generic;
[13850]24using System.Drawing;
[14267]25using System.Globalization;
[13808]26using System.Linq;
[13843]27using System.Threading.Tasks;
[13808]28using System.Windows.Forms;
29using HeuristicLab.Common;
30using HeuristicLab.MainForm;
[13843]31using HeuristicLab.Visualization.ChartControlsExtensions;
[13808]32
33namespace HeuristicLab.Problems.DataAnalysis.Views {
[14014]34  [View("Target Response Gradients")]
[13808]35  [Content(typeof(IRegressionSolution))]
36  public partial class RegressionSolutionTargetResponseGradientView : DataAnalysisSolutionEvaluationView {
[13850]37    private readonly Dictionary<string, GradientChart> gradientCharts;
38    private readonly Dictionary<string, DensityChart> densityCharts;
39    private readonly Dictionary<string, Panel> groupingPanels;
[14267]40    private ModifiableDataset sharedFixedVariables;
[13850]41
[13831]42    private const int Points = 200;
[13995]43    private int MaxColumns = 4;
[13808]44
[13850]45    private IEnumerable<string> VisibleVariables {
46      get {
47        foreach (ListViewItem item in variableListView.CheckedItems)
48          yield return item.Text;
49      }
[13843]50    }
[13850]51    private IEnumerable<GradientChart> VisibleGradientCharts {
52      get { return VisibleVariables.Select(v => gradientCharts[v]); }
53    }
54    private IEnumerable<DensityChart> VisibleDensityCharts {
55      get { return VisibleVariables.Select(v => densityCharts[v]); }
56    }
57    private IEnumerable<Panel> VisibleChartsPanels {
58      get { return VisibleVariables.Select(v => groupingPanels[v]); }
59    }
[13843]60
[13808]61    public RegressionSolutionTargetResponseGradientView() {
62      InitializeComponent();
[13850]63      gradientCharts = new Dictionary<string, GradientChart>();
64      densityCharts = new Dictionary<string, DensityChart>();
65      groupingPanels = new Dictionary<string, Panel>();
[13846]66
67      limitView.Content = new DoubleLimit(0, 1);
[14021]68      limitView.Content.ValueChanged += limit_ValueChanged;
[13850]69
[14021]70      densityComboBox.SelectedIndex = 1; // select Training
71
[13850]72      // Avoid additional horizontal scrollbar
73      var vertScrollWidth = SystemInformation.VerticalScrollBarWidth;
74      scrollPanel.Padding = new Padding(0, 0, vertScrollWidth, 0);
75      scrollPanel.AutoScroll = true;
[13808]76    }
77
78    public new IRegressionSolution Content {
79      get { return (IRegressionSolution)base.Content; }
[13831]80      set { base.Content = value; }
[13808]81    }
82
83    protected override void RegisterContentEvents() {
84      base.RegisterContentEvents();
[13995]85      Content.ModelChanged += solution_ModelChanged;
[13808]86    }
87
88    protected override void DeregisterContentEvents() {
[13995]89      Content.ModelChanged -= solution_ModelChanged;
[13808]90      base.DeregisterContentEvents();
91    }
92
93    protected override void OnContentChanged() {
94      base.OnContentChanged();
[13817]95      if (Content == null) return;
[13831]96      var problemData = Content.ProblemData;
[13846]97
98      // Init Y-axis range
99      double min = double.MaxValue, max = double.MinValue;
100      var trainingTarget = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
101      foreach (var t in trainingTarget) {
102        if (t < min) min = t;
103        if (t > max) max = t;
104      }
105      double range = max - min;
106      const double scale = 1.0 / 3.0;
107      double axisMin, axisMax, axisInterval;
108      ChartUtil.CalculateAxisInterval(min - scale * range, max + scale * range, 5, out axisMin, out axisMax, out axisInterval);
109      automaticYAxisCheckBox.Checked = false;
110      limitView.ReadOnly = false;
111      limitView.Content.Lower = axisMin;
112      limitView.Content.Upper = axisMax;
113
[13828]114      // create dataset
[13845]115      var allowedInputVariables = Content.ProblemData.AllowedInputVariables;
116      var variableValues = allowedInputVariables.Select(x => new List<double> { problemData.Dataset.GetDoubleValues(x, problemData.TrainingIndices).Median() });
[14267]117      if (sharedFixedVariables != null)
[14307]118        sharedFixedVariables.ItemChanged -= SharedFixedVariables_ItemChanged;
[14267]119      sharedFixedVariables = new ModifiableDataset(allowedInputVariables, variableValues);
120      // ItemChanged eventhandler is registered later, after creating the gradient charts
[13850]121
122      // create controls
123      gradientCharts.Clear();
124      densityCharts.Clear();
125      groupingPanels.Clear();
[13845]126      foreach (var variableName in allowedInputVariables) {
[13850]127        var gradientChart = CreateGradientChart(variableName, sharedFixedVariables);
128        gradientCharts.Add(variableName, gradientChart);
129
130        var densityChart = new DensityChart() {
131          Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right,
132          Margin = Padding.Empty,
133          Height = 12,
[14131]134          Visible = false,
135          Top = (int)(gradientChart.Height * 0.1),
[13850]136        };
137        densityCharts.Add(variableName, densityChart);
138
[14089]139        gradientChart.ZoomChanged += (o, e) => {
140          var gradient = (GradientChart)o;
141          var density = densityCharts[gradient.FreeVariable];
142          density.Visible = densityComboBox.SelectedIndex != 0 && !gradient.IsZoomed;
143          if (density.Visible)
144            UpdateDensityChart(density, gradient.FreeVariable);
145        };
[14131]146        gradientChart.SizeChanged += (o, e) => {
147          var gradient = (GradientChart)o;
148          var density = densityCharts[gradient.FreeVariable];
149          density.Top = (int)(gradient.Height * 0.1);
150        };
[14089]151
[14158]152        // Initially, the inner plot areas are not initialized for hidden charts (scollpanel, ...)
153        // This event handler listens for the paint event once (where everything is already initialized) to do some manual layouting.
154        gradientChart.ChartPostPaint += OnGradientChartOnChartPostPaint;
155
[13850]156        var panel = new Panel() {
[13820]157          Dock = DockStyle.Fill,
158          Margin = Padding.Empty,
[13850]159          BackColor = Color.White
[13820]160        };
[13843]161
[13850]162        panel.Controls.Add(densityChart);
163        panel.Controls.Add(gradientChart);
164        groupingPanels.Add(variableName, panel);
[13808]165      }
[13850]166
[13828]167      // update variable list
[14021]168      variableListView.ItemChecked -= variableListView_ItemChecked;
[13828]169      variableListView.Items.Clear();
[13845]170      foreach (var variable in allowedInputVariables)
171        variableListView.Items.Add(key: variable, text: variable, imageIndex: 0);
172
[13948]173      foreach (var variable in Content.Model.VariablesUsedForPrediction)
[13845]174        variableListView.Items[variable].Checked = true;
[14021]175      variableListView.ItemChecked += variableListView_ItemChecked;
176
[14267]177      sharedFixedVariables.ItemChanged += SharedFixedVariables_ItemChanged;
178
[14021]179      RecalculateAndRelayoutCharts();
[13808]180    }
[14021]181
[14267]182    private void SharedFixedVariables_ItemChanged(object sender, EventArgs<int, int> e) {
183      double yValue = Content.Model.GetEstimatedValues(sharedFixedVariables, new[] { 0 }).Single();
184      string title = Content.ProblemData.TargetVariable + ": " + yValue.ToString("G5", CultureInfo.CurrentCulture);
185      foreach (var chart in gradientCharts.Values) {
186        if (!string.IsNullOrEmpty(chart.YAxisTitle)) { // only show title for first column in grid
187          chart.YAxisTitle = title;
188        }
189      }
190    }
191
[14158]192    private void OnGradientChartOnChartPostPaint(object o, EventArgs e) {
193      var gradient = (GradientChart)o;
194      var density = densityCharts[gradient.FreeVariable];
195
196      density.Width = gradient.Width;
197
198      var gcPlotPosition = gradient.InnerPlotPosition;
199      density.Left = (int)(gcPlotPosition.X / 100.0 * gradient.Width);
200      density.Width = (int)(gcPlotPosition.Width / 100.0 * gradient.Width);
201      gradient.UpdateTitlePosition();
202
203      // removed after succesful layouting due to performance reasons
204      if (gcPlotPosition.Width != 0)
205        gradient.ChartPostPaint -= OnGradientChartOnChartPostPaint;
206    }
207
[14021]208    private async void RecalculateAndRelayoutCharts() {
209      foreach (var variable in VisibleVariables) {
210        var gradientChart = gradientCharts[variable];
211        await gradientChart.RecalculateAsync();
212      }
213      gradientChartTableLayout.SuspendLayout();
214      SetupYAxis();
215      ReOrderControls();
216      SetStyles();
217      gradientChartTableLayout.ResumeLayout();
218      gradientChartTableLayout.Refresh();
219      foreach (var variable in VisibleVariables) {
220        var densityChart = densityCharts[variable];
221        UpdateDensityChart(densityChart, variable);
222      }
223    }
[13850]224    private GradientChart CreateGradientChart(string variableName, ModifiableDataset sharedFixedVariables) {
225      var gradientChart = new GradientChart {
226        Dock = DockStyle.Fill,
227        Margin = Padding.Empty,
228        ShowLegend = false,
229        ShowCursor = true,
[13855]230        ShowConfigButton = false,
[13850]231        YAxisTicks = 5,
232      };
233      gradientChart.VariableValueChanged += async (o, e) => {
234        var recalculations = VisibleGradientCharts.Except(new[] { (GradientChart)o }).Select(async chart => {
235          await chart.RecalculateAsync(updateOnFinish: false, resetYAxis: false);
236        }).ToList();
237        await Task.WhenAll(recalculations);
[13843]238
[13850]239        if (recalculations.All(t => t.IsCompleted))
240          SetupYAxis();
241      };
242      gradientChart.Configure(new[] { Content }, sharedFixedVariables, variableName, Points);
[13995]243      gradientChart.SolutionAdded += gradientChart_SolutionAdded;
244      gradientChart.SolutionRemoved += gradientChart_SolutionRemoved;
[13850]245      return gradientChart;
246    }
247
[13846]248    private void SetupYAxis() {
249      double axisMin, axisMax;
250      if (automaticYAxisCheckBox.Checked) {
251        double min = double.MaxValue, max = double.MinValue;
[13850]252        foreach (var chart in VisibleGradientCharts) {
[13846]253          if (chart.YMin < min) min = chart.YMin;
254          if (chart.YMax > max) max = chart.YMax;
255        }
256
257        double axisInterval;
258        ChartUtil.CalculateAxisInterval(min, max, 5, out axisMin, out axisMax, out axisInterval);
259      } else {
260        axisMin = limitView.Content.Lower;
261        axisMax = limitView.Content.Upper;
[13843]262      }
263
[13850]264      foreach (var chart in VisibleGradientCharts) {
[13843]265        chart.FixedYAxisMin = axisMin;
266        chart.FixedYAxisMax = axisMax;
267      }
268    }
269
[13850]270    // reorder chart controls so that they always appear in the same order as in the list view
271    // the table layout containing the controls should be suspended before calling this method
272    private void ReOrderControls() {
[13828]273      var tl = gradientChartTableLayout;
274      tl.Controls.Clear();
[13850]275      int row = 0, column = 0;
[14267]276      double yValue = Content.Model.GetEstimatedValues(sharedFixedVariables, new[] { 0 }).Single();
277      string title = Content.ProblemData.TargetVariable + ": " + yValue.ToString("G5", CultureInfo.CurrentCulture);
278
[14014]279      foreach (var v in VisibleVariables) {
280        var chartsPanel = groupingPanels[v];
[13850]281        tl.Controls.Add(chartsPanel, column, row);
[14014]282
[14021]283        var chart = gradientCharts[v];
[14267]284        chart.YAxisTitle = column == 0 ? title : string.Empty;
[13850]285        column++;
[14014]286
[13850]287        if (column == MaxColumns) {
288          row++;
289          column = 0;
290        }
291      }
[13828]292    }
[13808]293
[13995]294    private void SetStyles() {
295      var tl = gradientChartTableLayout;
296      tl.RowStyles.Clear();
297      tl.ColumnStyles.Clear();
298      int numVariables = VisibleVariables.Count();
299      if (numVariables == 0)
300        return;
301
302      // set column styles
303      tl.ColumnCount = Math.Min(numVariables, MaxColumns);
304      for (int c = 0; c < tl.ColumnCount; c++)
305        tl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100.0f / tl.ColumnCount));
306
307      // set row styles
308      tl.RowCount = (int)Math.Ceiling((double)numVariables / tl.ColumnCount);
309      var columnWidth = tl.Width / tl.ColumnCount; // assume all columns have the same width
310      var rowHeight = (int)(0.8 * columnWidth);
311      for (int r = 0; r < tl.RowCount; r++)
312        tl.RowStyles.Add(new RowStyle(SizeType.Absolute, rowHeight));
313    }
314
315    private async void gradientChart_SolutionAdded(object sender, EventArgs<IRegressionSolution> e) {
316      var solution = e.Value;
317      foreach (var chart in gradientCharts.Values) {
318        if (sender == chart) continue;
319        await chart.AddSolutionAsync(solution);
320      }
321    }
322
323    private async void gradientChart_SolutionRemoved(object sender, EventArgs<IRegressionSolution> e) {
324      var solution = e.Value;
325      foreach (var chart in gradientCharts.Values) {
326        if (sender == chart) continue;
327        await chart.RemoveSolutionAsync(solution);
328      }
329    }
330
[13842]331    private async void variableListView_ItemChecked(object sender, ItemCheckedEventArgs e) {
[13808]332      var item = e.Item;
333      var variable = item.Text;
[13850]334      var gradientChart = gradientCharts[variable];
335      var chartsPanel = groupingPanels[variable];
[13817]336      var tl = gradientChartTableLayout;
[13850]337
[13817]338      tl.SuspendLayout();
[13808]339      if (item.Checked) {
[13850]340        tl.Controls.Add(chartsPanel);
341        await gradientChart.RecalculateAsync();
[13808]342      } else {
[13850]343        tl.Controls.Remove(chartsPanel);
[13808]344      }
[13843]345
[13850]346      if (tl.Controls.Count > 0) {
347        SetupYAxis();
348        ReOrderControls();
[13995]349        SetStyles();
[13828]350      }
[13817]351      tl.ResumeLayout();
[14021]352      tl.Refresh();
353      densityComboBox_SelectedIndexChanged(this, EventArgs.Empty);
[13808]354    }
[13846]355
356    private void automaticYAxisCheckBox_CheckedChanged(object sender, EventArgs e) {
357      limitView.ReadOnly = automaticYAxisCheckBox.Checked;
358      SetupYAxis();
[14021]359      gradientChartTableLayout.Refresh();
360      densityComboBox_SelectedIndexChanged(this, EventArgs.Empty); // necessary to realign the density plots
[13846]361    }
362
363    private void limit_ValueChanged(object sender, EventArgs e) {
364      if (automaticYAxisCheckBox.Checked)
365        return;
366      SetupYAxis();
[14021]367      gradientChartTableLayout.Refresh();
368      densityComboBox_SelectedIndexChanged(this, EventArgs.Empty); // necessary to realign the density plots
[13846]369    }
[13850]370
371    private void densityComboBox_SelectedIndexChanged(object sender, EventArgs e) {
[14021]372      if (Content == null)
373        return;
374
[13850]375      int si = densityComboBox.SelectedIndex;
376      if (si == 0) {
377        foreach (var densityChart in densityCharts.Values)
378          densityChart.Visible = false;
379      } else {
380        var indices = GetDensityIndices(si).ToList();
381
382        foreach (var entry in densityCharts) {
383          var variableName = entry.Key;
384          var densityChart = entry.Value;
[14089]385          if (!VisibleVariables.Contains(variableName) || gradientCharts[variableName].IsZoomed)
[13850]386            continue;
[14089]387
[13850]388          UpdateDensityChart(densityChart, variableName, indices);
389        }
390      }
391    }
392    private IEnumerable<int> GetDensityIndices(int selectedIndex) {
393      var problemData = Content.ProblemData;
394      return
395        selectedIndex == 1 ? problemData.TrainingIndices :
396        selectedIndex == 2 ? problemData.TestIndices :
397        problemData.AllIndices;
398    }
399    private void UpdateDensityChart(DensityChart densityChart, string variable, IList<int> indices = null) {
400      if (densityComboBox.SelectedIndex == 0)
401        return;
402      if (indices == null) {
403        indices = GetDensityIndices(densityComboBox.SelectedIndex).ToList();
404      }
405      var data = Content.ProblemData.Dataset.GetDoubleValues(variable, indices).ToList();
406      var gradientChart = gradientCharts[variable];
407      var min = gradientChart.FixedXAxisMin;
408      var max = gradientChart.FixedXAxisMax;
409      var buckets = gradientChart.DrawingSteps;
410      if (min.HasValue && max.HasValue) {
411        densityChart.UpdateChart(data, min.Value, max.Value, buckets);
412        densityChart.Width = gradientChart.Width;
413
414        var gcPlotPosition = gradientChart.InnerPlotPosition;
415        densityChart.Left = (int)(gcPlotPosition.X / 100.0 * gradientChart.Width);
416        densityChart.Width = (int)(gcPlotPosition.Width / 100.0 * gradientChart.Width);
417
418        densityChart.Visible = true;
419      }
[14131]420
421      gradientChart.UpdateTitlePosition();
[13850]422    }
[13995]423
[14089]424    private void columnsNumericUpDown_ValueChanged(object sender, EventArgs e) {
425      MaxColumns = (int)columnsNumericUpDown.Value;
[13995]426      int columns = Math.Min(VisibleVariables.Count(), MaxColumns);
427      if (columns > 0) {
428        var tl = gradientChartTableLayout;
429        MaxColumns = columns;
430        tl.SuspendLayout();
431        ReOrderControls();
432        SetStyles();
[14021]433        tl.ResumeLayout();
434        tl.Refresh();
435        densityComboBox_SelectedIndexChanged(this, EventArgs.Empty);
[13995]436      }
437    }
438
[14021]439    private async void solution_ModelChanged(object sender, EventArgs e) {
440      foreach (var variable in VisibleVariables) {
441        var gradientChart = gradientCharts[variable];
442        var densityChart = densityCharts[variable];
443        // recalculate and refresh
444        await gradientChart.RecalculateAsync();
445        gradientChart.Refresh();
446        UpdateDensityChart(densityChart, variable);
[13996]447      }
[13995]448    }
[13808]449  }
450}
Note: See TracBrowser for help on using the repository browser.