source: branches/DataPreprocessing Enhancements/HeuristicLab.DataPreprocessing.Views/3.4/ScatterPlotMultiView.cs @ 14462

Last change on this file since 14462 was 14462, checked in by pfleck, 4 years ago

#2709

  • Added a separate MultiScatterPlot entry and removed the ViewHost views-icon instead.
  • Moved legend of DataCompletenessChart to the top and removed the title instead.
File size: 17.5 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Drawing;
4using System.Linq;
5using System.Windows.Forms;
6using HeuristicLab.Analysis;
7using HeuristicLab.Analysis.Views;
8using HeuristicLab.Collections;
9using HeuristicLab.Common;
10using HeuristicLab.Data;
11using HeuristicLab.MainForm;
12using HeuristicLab.MainForm.WindowsForms;
13
14namespace HeuristicLab.DataPreprocessing.Views {
15  [View("Scatter Plot Multi View")]
16  [Content(typeof(MultiScatterPlotContent), true)]
17  public partial class ScatterPlotMultiView : PreprocessingCheckedVariablesView {
18    private readonly IDictionary<string, Label> columnHeaderCache;
19    private readonly IDictionary<string, Label> rowHeaderCache;
20    private readonly IDictionary<Tuple<string/*col*/, string/*row*/>, Control> bodyCache;
21
22    public ScatterPlotMultiView() {
23      InitializeComponent();
24
25      #region Initialize Scrollbars
26      columnHeaderScrollPanel.HorizontalScroll.Enabled = true;
27      columnHeaderScrollPanel.VerticalScroll.Enabled = false;
28      columnHeaderScrollPanel.HorizontalScroll.Visible = false;
29      columnHeaderScrollPanel.VerticalScroll.Visible = false;
30
31      rowHeaderScrollPanel.HorizontalScroll.Enabled = false;
32      rowHeaderScrollPanel.VerticalScroll.Enabled = true;
33      rowHeaderScrollPanel.HorizontalScroll.Visible = false;
34      rowHeaderScrollPanel.VerticalScroll.Visible = false;
35
36      bodyScrollPanel.HorizontalScroll.Enabled = true;
37      bodyScrollPanel.VerticalScroll.Enabled = true;
38      bodyScrollPanel.HorizontalScroll.Visible = true;
39      bodyScrollPanel.VerticalScroll.Visible = true;
40      bodyScrollPanel.AutoScroll = true;
41      #endregion
42
43      columnHeaderCache = new Dictionary<string, Label>();
44      rowHeaderCache = new Dictionary<string, Label>();
45      bodyCache = new Dictionary<Tuple<string, string>, Control>();
46
47      bodyScrollPanel.MouseWheel += bodyScrollPanel_MouseWheel;
48    }
49
50    public new MultiScatterPlotContent Content {
51      get { return (MultiScatterPlotContent)base.Content; }
52      set { base.Content = value; }
53    }
54
55    protected override void OnContentChanged() {
56      base.OnContentChanged();
57      if (Content != null) {
58        GenerateCharts();
59      }
60    }
61
62    protected override void CheckedItemsChanged(object sender, CollectionItemsChangedEventArgs<IndexedItem<StringValue>> checkedItems) {
63      base.CheckedItemsChanged(sender, checkedItems);
64      foreach (var variable in checkedItems.Items.Select(i => i.Value.Value)) {
65        if (IsVariableChecked(variable))
66          AddChartToTable(variable);
67        else
68          RemoveChartFromTable(variable);
69      }
70    }
71
72    #region Add and remove charts
73    private void AddChartToTable(string variable) {
74      frameTableLayoutPanel.SuspendLayout();
75
76      // find index to insert
77      var variables = checkedItemList.Content.Select(v => v.Value).ToList();
78      int idx = variables              // all variables
79        .TakeWhile(t => t != variable) // ... until the variable that was checked
80        .Count(IsVariableChecked);     // ... how many checked variables
81
82      // add column header
83      var colH = columnHeaderTableLayoutPanel;
84      AddColumnHelper(colH, idx, _ => GetColumnHeader(variable));
85
86      // add row header
87      var rowH = rowHeaderTableLayoutPanel;
88      AddRowHelper(rowH, idx, _ => GetRowHeader(variable));
89
90      // add body
91      var body = bodyTableLayoutPanel;
92      var vars = GetCheckedVariables();
93      var varsMinus = vars.Except(new[] { variable }).ToList();
94      AddColumnHelper(body, idx, r => GetBody(variable, varsMinus[r])); // exclude "variable" because the row for it does not exist yet
95      AddRowHelper(body, idx, c => GetBody(vars[c], variable));
96
97      frameTableLayoutPanel.ResumeLayout(true);
98    }
99    private void AddColumnHelper(TableLayoutPanel tlp, int idx, Func<int, Control> creatorFunc) {
100      // add column
101      tlp.ColumnCount++;
102      tlp.ColumnStyles.Insert(idx, new ColumnStyle(SizeType.Absolute, GetColumnWidth()));
103      // shift right
104      for (int c = tlp.ColumnCount; c >  idx - 1; c--) {
105        for (int r = 0; r < tlp.RowCount; r++) {
106          var control = tlp.GetControlFromPosition(c, r);
107          if (control != null) {
108            tlp.SetColumn(control, c + 1);
109          }
110        }
111      }
112      // add controls
113      for (int r = 0; r < tlp.RowCount; r++) {
114        if (tlp.GetControlFromPosition(idx, r) == null)
115          tlp.Controls.Add(creatorFunc(r), idx, r);
116      }
117
118    }
119    private void AddRowHelper(TableLayoutPanel tlp, int idx, Func<int, Control> creatorFunc) {
120      // add row
121      tlp.RowCount++;
122      tlp.RowStyles.Insert(idx, new RowStyle(SizeType.Absolute, GetRowHeight()));
123      // shift right
124      for (int r = tlp.RowCount; r > idx - 1; r--) {
125        for (int c = 0; c < tlp.ColumnCount; c++) {
126          var control = tlp.GetControlFromPosition(c, r);
127          if (control != null) {
128            tlp.SetRow(control, r + 1);
129          }
130        }
131      }
132      // add controls
133      for (int c = 0; c < tlp.ColumnCount; c++)
134        if (tlp.GetControlFromPosition(c, idx) == null)
135          tlp.Controls.Add(creatorFunc(c), c, idx);
136    }
137
138    private void RemoveChartFromTable(string variable) {
139      frameTableLayoutPanel.SuspendLayout();
140
141      // remove column header
142      var colH = columnHeaderTableLayoutPanel;
143      int colIdx = colH.GetColumn(colH.Controls[variable]);
144      RemoveColumnHelper(colH, colIdx);
145
146      // remove row header
147      var rowH = rowHeaderTableLayoutPanel;
148      int rowIdx = rowH.GetRow(rowH.Controls[variable]);
149      RemoveRowHelper(rowH, rowIdx);
150
151      // remove from body
152      var body = bodyTableLayoutPanel;
153      RemoveColumnHelper(body, colIdx);
154      RemoveRowHelper(body, rowIdx);
155
156      frameTableLayoutPanel.ResumeLayout(true);
157    }
158    private void RemoveColumnHelper(TableLayoutPanel tlp, int idx) {
159      // remove controls
160      for (int r = 0; r < tlp.RowCount; r++)
161        tlp.Controls.Remove(tlp.GetControlFromPosition(idx, r));
162      // shift left
163      for (int c = idx + 1; c < tlp.ColumnCount; c++) {
164        for (int r = 0; r < tlp.RowCount; r++) {
165          var control = tlp.GetControlFromPosition(c, r);
166          if (control != null) {
167            tlp.SetColumn(control, c - 1);
168          }
169        }
170      }
171      // delete column
172      tlp.ColumnStyles.RemoveAt(tlp.ColumnCount - 1);
173      tlp.ColumnCount--;
174    }
175    private void RemoveRowHelper(TableLayoutPanel tlp, int idx) {
176      // remove controls
177      for (int c = 0; c < tlp.ColumnCount; c++)
178        tlp.Controls.Remove(tlp.GetControlFromPosition(c, idx));
179      // shift left
180      for (int r = idx + 1; r < tlp.RowCount; r++) {
181        for (int c = 0; c < tlp.ColumnCount; c++) {
182          var control = tlp.GetControlFromPosition(c, r);
183          if (control != null) {
184            tlp.SetRow(control, r - 1);
185          }
186        }
187      }
188      // delete rows
189      tlp.RowStyles.RemoveAt(tlp.RowCount - 1);
190      tlp.RowCount--;
191    }
192    #endregion
193
194    #region Add/Remove/Update Variable
195    protected override void AddVariable(string name) {
196      base.AddVariable(name);
197      if (IsVariableChecked(name))
198        AddChartToTable(name);
199    }
200    protected override void RemoveVariable(string name) {
201      base.RemoveVariable(name);
202
203      // clear caches
204      columnHeaderCache.Remove(name);
205      rowHeaderCache.Remove(name);
206      var keys = bodyCache.Keys.Where(t => t.Item1 == name || t.Item2 == name).ToList();
207      foreach (var key in keys)
208        bodyCache.Remove(key);
209
210      if (IsVariableChecked(name)) {
211        RemoveChartFromTable(name);
212      }
213    }
214    protected override void UpdateVariable(string name) {
215      base.UpdateVariable(name);
216      RemoveVariable(name);
217      AddVariable(name);
218    }
219    protected override void ResetAllVariables() {
220      GenerateCharts();
221    }
222    #endregion
223
224    #region Creating Headers and Body
225    private Label GetColumnHeader(string variable) {
226      if (!columnHeaderCache.ContainsKey(variable)) {
227        columnHeaderCache.Add(variable, new Label() {
228          Text = variable,
229          TextAlign = ContentAlignment.MiddleCenter,
230          Name = variable,
231          Height = columnHeaderTableLayoutPanel.Height,
232          Dock = DockStyle.Fill,
233          Margin = new Padding(3)
234        });
235      }
236      return columnHeaderCache[variable];
237    }
238    private Label GetRowHeader(string variable) {
239      if (!rowHeaderCache.ContainsKey(variable)) {
240        rowHeaderCache.Add(variable, new Label() {
241          Text = variable,
242          TextAlign = ContentAlignment.MiddleCenter,
243          Name = variable,
244          Width = rowHeaderTableLayoutPanel.Width,
245          Dock = DockStyle.Fill,
246          Margin = new Padding(3)
247        });
248      }
249      return rowHeaderCache[variable];
250    }
251    private Control GetBody(string colVariable, string rowVariable) {
252      var key = Tuple.Create(colVariable, rowVariable);
253      if (!bodyCache.ContainsKey(key)) {
254        if (rowVariable == colVariable) { // use historgram if x and y variable are equal
255          var dataTable = new DataTable();
256          DataRow dataRow = Content.CreateDataRow(rowVariable, DataRowVisualProperties.DataRowChartType.Histogram);
257          dataRow.VisualProperties.IsVisibleInLegend = false;
258          dataTable.Rows.Add(dataRow);
259          var pcv = new DataTableControl {
260            Name = key.ToString(),
261            Content = dataTable,
262            Dock = DockStyle.Fill,
263            //ShowLegend = false,
264            //XAxisFormat = "G3"
265          };
266          //pcv.ChartDoubleClick += HistogramDoubleClick;
267          bodyCache.Add(key, pcv);
268        } else { //scatter plot
269          var scatterPlot = Content.CreateScatterPlot(colVariable, rowVariable);
270          scatterPlot.VisualProperties.Title = string.Empty;
271          var scatterPlotControl = new /*Preprocessing*/ScatterPlotControl {
272            Name = key.ToString(),
273            Content = scatterPlot,
274            Dock = DockStyle.Fill,
275            //ShowLegend = false,
276            //XAxisFormat = "G3"
277          };
278          scatterPlotControl.DoubleClick += ScatterPlotDoubleClick; // ToDo: not working; double click is already handled by the chart
279          bodyCache.Add(key, scatterPlotControl);
280        }
281      }
282      return bodyCache[key];
283    }
284    #endregion
285
286    #region Generate Charts
287    private void GenerateCharts() {
288      var variables = GetCheckedVariables();
289
290      // Clear old layouts and cache
291      foreach (var tableLayoutPanel in new[] { columnHeaderTableLayoutPanel, rowHeaderTableLayoutPanel, bodyTableLayoutPanel }) {
292        tableLayoutPanel.Controls.Clear();
293        tableLayoutPanel.ColumnStyles.Clear();
294        tableLayoutPanel.RowStyles.Clear();
295      }
296      columnHeaderCache.Clear();
297      rowHeaderCache.Clear();
298      bodyCache.Clear();
299
300      // Set row and column count
301      columnHeaderTableLayoutPanel.ColumnCount = variables.Count;
302      rowHeaderTableLayoutPanel.RowCount = variables.Count;
303      bodyTableLayoutPanel.ColumnCount = variables.Count;
304      bodyTableLayoutPanel.RowCount = variables.Count;
305
306      // Set column and row layout
307      for (int i = 0; i < variables.Count; i++) {
308        columnHeaderTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, GetColumnWidth()));
309        rowHeaderTableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, GetRowHeight()));
310        bodyTableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, GetColumnWidth()));
311        bodyTableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, GetRowHeight()));
312      }
313
314      frameTableLayoutPanel.SuspendLayout();
315      AddHeaderToTableLayoutPanels();
316      AddChartsToTableLayoutPanel();
317      UpdateHeaderMargin();
318      frameTableLayoutPanel.ResumeLayout(true);
319    }
320
321    private void AddHeaderToTableLayoutPanels() {
322      int i = 0;
323      foreach (var variable in GetCheckedVariables()) {
324        columnHeaderTableLayoutPanel.Controls.Add(GetColumnHeader(variable), i, 0);
325        rowHeaderTableLayoutPanel.Controls.Add(GetRowHeader(variable), 0, i);
326        i++;
327      }
328    }
329    private void AddChartsToTableLayoutPanel() {
330      int c = 0;
331      foreach (var colVar in GetCheckedVariables()) {
332        if (!IsVariableChecked(colVar)) continue;
333        int r = 0;
334        foreach (var rowVar in GetCheckedVariables()) {
335          if (!IsVariableChecked(rowVar)) continue;
336          bodyTableLayoutPanel.Controls.Add(GetBody(colVar, rowVar), c, r);
337          r++;
338        }
339        c++;
340      }
341    }
342
343    #endregion
344
345    #region DoubleClick Events
346    //Open scatter plot in new tab with new content when double clicked
347    private void ScatterPlotDoubleClick(object sender, EventArgs e) {
348      var scatterPlotControl = (ScatterPlotControl)sender;
349      ScatterPlotContent scatterContent = new ScatterPlotContent(Content, new Cloner());  // create new content
350      ScatterPlot scatterPlot = scatterPlotControl.Content;
351
352      //Extract variable names from scatter plot and set them in content
353      if (scatterPlot.Rows.Count == 1) {
354        string[] variables = scatterPlot.Rows.ElementAt(0).Name.Split(new string[] { " - " }, StringSplitOptions.None); // extract variable names from string
355        scatterContent.SelectedXVariable = variables[0];
356        scatterContent.SelectedYVariable = variables[1];
357      }
358
359      MainFormManager.MainForm.ShowContent(scatterContent, typeof(ScatterPlotSingleView));  // open in new tab
360    }
361
362    //open histogram in new tab with new content when double clicked
363    private void HistogramDoubleClick(object sender, EventArgs e) {
364      DataTableControl pcv = (DataTableControl)sender;
365      HistogramContent histoContent = new HistogramContent(Content.PreprocessingData);  // create new content     
366      histoContent.VariableItemList = Content.CreateVariableItemList();
367      var dataTable = pcv.Content;
368
369      //Set variable item list from with variable from data table
370      if (dataTable.Rows.Count == 1) { // only one data row should be in data table
371        string variableName = dataTable.Rows.ElementAt(0).Name;
372
373        // set only variable name checked
374        foreach (var checkedItem in histoContent.VariableItemList) {
375          histoContent.VariableItemList.SetItemCheckedState(checkedItem, checkedItem.Value == variableName);
376        }
377      }
378      MainFormManager.MainForm.ShowContent(histoContent, typeof(HistogramView));  // open in new tab
379    }
380    #endregion
381
382    #region Scrolling
383    private void bodyScrollPanel_Scroll(object sender, ScrollEventArgs e) {
384      SyncScroll();
385
386      UpdateHeaderMargin();
387    }
388    private void bodyScrollPanel_MouseWheel(object sender, MouseEventArgs e) {
389      // Scrolling with the mouse wheel is not captured in the Scoll event
390      SyncScroll();
391    }
392    private void SyncScroll() {
393      frameTableLayoutPanel.SuspendRepaint();
394
395      columnHeaderScrollPanel.HorizontalScroll.Minimum = bodyScrollPanel.HorizontalScroll.Minimum;
396      columnHeaderScrollPanel.HorizontalScroll.Maximum = bodyScrollPanel.HorizontalScroll.Maximum;
397      rowHeaderScrollPanel.VerticalScroll.Minimum = bodyScrollPanel.VerticalScroll.Minimum;
398      rowHeaderScrollPanel.VerticalScroll.Maximum = bodyScrollPanel.VerticalScroll.Maximum;
399
400      columnHeaderScrollPanel.HorizontalScroll.Value = Math.Max(bodyScrollPanel.HorizontalScroll.Value, 1);
401      rowHeaderScrollPanel.VerticalScroll.Value = Math.Max(bodyScrollPanel.VerticalScroll.Value, 1);
402      // minimum 1 is nececary  because of two factors:
403      // - setting the Value-property of Horizontal/VerticalScroll updates the internal state but the Value-property stays 0
404      // - setting the same number of the Value-property has no effect
405      // since the Value-property is always 0, setting it to 0 would have no effect; so it is set to 1 instead
406
407      frameTableLayoutPanel.ResumeRepaint(true);
408    }
409    // add a margin to the header table layouts if the scollbar is visible to account for the width/height of the scrollbar
410    private void UpdateHeaderMargin() {
411      columnHeaderScrollPanel.Margin = new Padding(0, 0, bodyScrollPanel.VerticalScroll.Visible ? SystemInformation.VerticalScrollBarWidth : 0, 0);
412      rowHeaderScrollPanel.Margin = new Padding(0, 0, 0, bodyScrollPanel.HorizontalScroll.Visible ? SystemInformation.HorizontalScrollBarHeight : 0);
413    }
414    #endregion
415
416    #region Sizing of Charts
417    private int GetColumnWidth() { return (int)(bodyScrollPanel.Width * ((float)widthTrackBar.Value / 100)); }
418    private int GetRowHeight() { return (int)(bodyScrollPanel.Height * ((float)heightTrackBar.Value / 100)); }
419    private void widthTrackBar_ValueChanged(object sender, EventArgs e) {
420      frameTableLayoutPanel.SuspendRepaint();
421      for (int i = 0; i < columnHeaderTableLayoutPanel.ColumnCount; i++) {
422        columnHeaderTableLayoutPanel.ColumnStyles[i].Width = GetColumnWidth();
423        bodyTableLayoutPanel.ColumnStyles[i].Width = GetColumnWidth();
424      }
425      frameTableLayoutPanel.ResumeRepaint(true);
426    }
427    private void heightTrackBar_ValueChanged(object sender, EventArgs e) {
428      frameTableLayoutPanel.SuspendRepaint();
429
430      for (int i = 0; i < rowHeaderTableLayoutPanel.RowCount; i++) {
431        rowHeaderTableLayoutPanel.RowStyles[i].Height = GetRowHeight();
432        bodyTableLayoutPanel.RowStyles[i].Height = GetRowHeight();
433      }
434      frameTableLayoutPanel.ResumeRepaint(true);
435    }
436    #endregion
437  }
438}
Note: See TracBrowser for help on using the repository browser.