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

Last change on this file since 14158 was 14158, checked in by pfleck, 6 years ago

#2597 Fixed an issue with wrongly positioned title and density chart after initialization.

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