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

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

#2597:

  • Moved variable name + cursor value to the top.
  • Fixed some warnings (missing async await).
File size: 15.4 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        var panel = new Panel() {
148          Dock = DockStyle.Fill,
149          Margin = Padding.Empty,
150          BackColor = Color.White
151        };
152
153        panel.Controls.Add(densityChart);
154        panel.Controls.Add(gradientChart);
155        groupingPanels.Add(variableName, panel);
156      }
157
158      // update variable list
159      variableListView.ItemChecked -= variableListView_ItemChecked;
160      variableListView.Items.Clear();
161      foreach (var variable in allowedInputVariables)
162        variableListView.Items.Add(key: variable, text: variable, imageIndex: 0);
163
164      foreach (var variable in Content.Model.VariablesUsedForPrediction)
165        variableListView.Items[variable].Checked = true;
166      variableListView.ItemChecked += variableListView_ItemChecked;
167
168      RecalculateAndRelayoutCharts();
169    }
170
171    private async void RecalculateAndRelayoutCharts() {
172      foreach (var variable in VisibleVariables) {
173        var gradientChart = gradientCharts[variable];
174        await gradientChart.RecalculateAsync();
175      }
176      gradientChartTableLayout.SuspendLayout();
177      SetupYAxis();
178      ReOrderControls();
179      SetStyles();
180      gradientChartTableLayout.ResumeLayout();
181      gradientChartTableLayout.Refresh();
182      foreach (var variable in VisibleVariables) {
183        var densityChart = densityCharts[variable];
184        UpdateDensityChart(densityChart, variable);
185      }
186    }
187    private GradientChart CreateGradientChart(string variableName, ModifiableDataset sharedFixedVariables) {
188      var gradientChart = new GradientChart {
189        Dock = DockStyle.Fill,
190        Margin = Padding.Empty,
191        ShowLegend = false,
192        ShowCursor = true,
193        ShowConfigButton = false,
194        YAxisTicks = 5,
195      };
196      gradientChart.VariableValueChanged += async (o, e) => {
197        var recalculations = VisibleGradientCharts.Except(new[] { (GradientChart)o }).Select(async chart => {
198          await chart.RecalculateAsync(updateOnFinish: false, resetYAxis: false);
199        }).ToList();
200        await Task.WhenAll(recalculations);
201
202        if (recalculations.All(t => t.IsCompleted))
203          SetupYAxis();
204      };
205      gradientChart.Configure(new[] { Content }, sharedFixedVariables, variableName, Points);
206      gradientChart.SolutionAdded += gradientChart_SolutionAdded;
207      gradientChart.SolutionRemoved += gradientChart_SolutionRemoved;
208      return gradientChart;
209    }
210
211    private void SetupYAxis() {
212      double axisMin, axisMax;
213      if (automaticYAxisCheckBox.Checked) {
214        double min = double.MaxValue, max = double.MinValue;
215        foreach (var chart in VisibleGradientCharts) {
216          if (chart.YMin < min) min = chart.YMin;
217          if (chart.YMax > max) max = chart.YMax;
218        }
219
220        double axisInterval;
221        ChartUtil.CalculateAxisInterval(min, max, 5, out axisMin, out axisMax, out axisInterval);
222      } else {
223        axisMin = limitView.Content.Lower;
224        axisMax = limitView.Content.Upper;
225      }
226
227      foreach (var chart in VisibleGradientCharts) {
228        chart.FixedYAxisMin = axisMin;
229        chart.FixedYAxisMax = axisMax;
230      }
231    }
232
233    // reorder chart controls so that they always appear in the same order as in the list view
234    // the table layout containing the controls should be suspended before calling this method
235    private void ReOrderControls() {
236      var tl = gradientChartTableLayout;
237      tl.Controls.Clear();
238      int row = 0, column = 0;
239      foreach (var v in VisibleVariables) {
240        var chartsPanel = groupingPanels[v];
241        tl.Controls.Add(chartsPanel, column, row);
242
243        var chart = gradientCharts[v];
244        chart.YAxisTitle = column == 0 ? Content.ProblemData.TargetVariable : string.Empty;
245        column++;
246
247        if (column == MaxColumns) {
248          row++;
249          column = 0;
250        }
251      }
252    }
253
254    private void SetStyles() {
255      var tl = gradientChartTableLayout;
256      tl.RowStyles.Clear();
257      tl.ColumnStyles.Clear();
258      int numVariables = VisibleVariables.Count();
259      if (numVariables == 0)
260        return;
261
262      // set column styles
263      tl.ColumnCount = Math.Min(numVariables, MaxColumns);
264      for (int c = 0; c < tl.ColumnCount; c++)
265        tl.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100.0f / tl.ColumnCount));
266
267      // set row styles
268      tl.RowCount = (int)Math.Ceiling((double)numVariables / tl.ColumnCount);
269      var columnWidth = tl.Width / tl.ColumnCount; // assume all columns have the same width
270      var rowHeight = (int)(0.8 * columnWidth);
271      for (int r = 0; r < tl.RowCount; r++)
272        tl.RowStyles.Add(new RowStyle(SizeType.Absolute, rowHeight));
273    }
274
275    private async void gradientChart_SolutionAdded(object sender, EventArgs<IRegressionSolution> e) {
276      var solution = e.Value;
277      foreach (var chart in gradientCharts.Values) {
278        if (sender == chart) continue;
279        await chart.AddSolutionAsync(solution);
280      }
281    }
282
283    private async void gradientChart_SolutionRemoved(object sender, EventArgs<IRegressionSolution> e) {
284      var solution = e.Value;
285      foreach (var chart in gradientCharts.Values) {
286        if (sender == chart) continue;
287        await chart.RemoveSolutionAsync(solution);
288      }
289    }
290
291    private async void variableListView_ItemChecked(object sender, ItemCheckedEventArgs e) {
292      var item = e.Item;
293      var variable = item.Text;
294      var gradientChart = gradientCharts[variable];
295      var chartsPanel = groupingPanels[variable];
296      var tl = gradientChartTableLayout;
297
298      tl.SuspendLayout();
299      if (item.Checked) {
300        tl.Controls.Add(chartsPanel);
301        await gradientChart.RecalculateAsync();
302      } else {
303        tl.Controls.Remove(chartsPanel);
304      }
305
306      if (tl.Controls.Count > 0) {
307        SetupYAxis();
308        ReOrderControls();
309        SetStyles();
310      }
311      tl.ResumeLayout();
312      tl.Refresh();
313      densityComboBox_SelectedIndexChanged(this, EventArgs.Empty);
314    }
315
316    private void automaticYAxisCheckBox_CheckedChanged(object sender, EventArgs e) {
317      limitView.ReadOnly = automaticYAxisCheckBox.Checked;
318      SetupYAxis();
319      gradientChartTableLayout.Refresh();
320      densityComboBox_SelectedIndexChanged(this, EventArgs.Empty); // necessary to realign the density plots
321    }
322
323    private void limit_ValueChanged(object sender, EventArgs e) {
324      if (automaticYAxisCheckBox.Checked)
325        return;
326      SetupYAxis();
327      gradientChartTableLayout.Refresh();
328      densityComboBox_SelectedIndexChanged(this, EventArgs.Empty); // necessary to realign the density plots
329    }
330
331    private void densityComboBox_SelectedIndexChanged(object sender, EventArgs e) {
332      if (Content == null)
333        return;
334
335      int si = densityComboBox.SelectedIndex;
336      if (si == 0) {
337        foreach (var densityChart in densityCharts.Values)
338          densityChart.Visible = false;
339      } else {
340        var indices = GetDensityIndices(si).ToList();
341
342        foreach (var entry in densityCharts) {
343          var variableName = entry.Key;
344          var densityChart = entry.Value;
345          if (!VisibleVariables.Contains(variableName) || gradientCharts[variableName].IsZoomed)
346            continue;
347
348          UpdateDensityChart(densityChart, variableName, indices);
349        }
350      }
351    }
352    private IEnumerable<int> GetDensityIndices(int selectedIndex) {
353      var problemData = Content.ProblemData;
354      return
355        selectedIndex == 1 ? problemData.TrainingIndices :
356        selectedIndex == 2 ? problemData.TestIndices :
357        problemData.AllIndices;
358    }
359    private void UpdateDensityChart(DensityChart densityChart, string variable, IList<int> indices = null) {
360      if (densityComboBox.SelectedIndex == 0)
361        return;
362      if (indices == null) {
363        indices = GetDensityIndices(densityComboBox.SelectedIndex).ToList();
364      }
365      var data = Content.ProblemData.Dataset.GetDoubleValues(variable, indices).ToList();
366      var gradientChart = gradientCharts[variable];
367      var min = gradientChart.FixedXAxisMin;
368      var max = gradientChart.FixedXAxisMax;
369      var buckets = gradientChart.DrawingSteps;
370      if (min.HasValue && max.HasValue) {
371        densityChart.UpdateChart(data, min.Value, max.Value, buckets);
372        densityChart.Width = gradientChart.Width;
373
374        var gcPlotPosition = gradientChart.InnerPlotPosition;
375        densityChart.Left = (int)(gcPlotPosition.X / 100.0 * gradientChart.Width);
376        densityChart.Width = (int)(gcPlotPosition.Width / 100.0 * gradientChart.Width);
377
378        densityChart.Visible = true;
379      }
380
381      gradientChart.UpdateTitlePosition();
382    }
383
384    private void columnsNumericUpDown_ValueChanged(object sender, EventArgs e) {
385      MaxColumns = (int)columnsNumericUpDown.Value;
386      int columns = Math.Min(VisibleVariables.Count(), MaxColumns);
387      if (columns > 0) {
388        var tl = gradientChartTableLayout;
389        MaxColumns = columns;
390        tl.SuspendLayout();
391        ReOrderControls();
392        SetStyles();
393        tl.ResumeLayout();
394        tl.Refresh();
395        densityComboBox_SelectedIndexChanged(this, EventArgs.Empty);
396      }
397    }
398
399    private async void solution_ModelChanged(object sender, EventArgs e) {
400      foreach (var variable in VisibleVariables) {
401        var gradientChart = gradientCharts[variable];
402        var densityChart = densityCharts[variable];
403        // recalculate and refresh
404        await gradientChart.RecalculateAsync();
405        gradientChart.Refresh();
406        UpdateDensityChart(densityChart, variable);
407      }
408    }
409  }
410}
Note: See TracBrowser for help on using the repository browser.