Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/FeatureCorrelationView.cs @ 8542

Last change on this file since 8542 was 8542, checked in by mkommend, 12 years ago

#1292: Integrated correlation analysis of datasets in the trunk.

File size: 12.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.ComponentModel;
25using System.Drawing;
26using System.Linq;
27using System.Text;
28using System.Windows.Forms;
29using HeuristicLab.Common;
30using HeuristicLab.Core.Views;
31using HeuristicLab.Data.Views;
32using HeuristicLab.MainForm;
33
34namespace HeuristicLab.Problems.DataAnalysis.Views {
35  [View("Feature Correlation View")]
36  [Content(typeof(FeatureCorrelation), true)]
37  public partial class FeatureCorrelationView : ItemView {
38
39    private int[] virtualRowIndices;
40    private List<KeyValuePair<int, SortOrder>> sortedColumnIndices;
41    private StringConvertibleMatrixView.RowComparer rowComparer;
42
43    public new FeatureCorrelation Content {
44      get { return (FeatureCorrelation)base.Content; }
45      set { base.Content = value; }
46    }
47
48    public FeatureCorrelationView() {
49      InitializeComponent();
50      sortedColumnIndices = new List<KeyValuePair<int, SortOrder>>();
51      rowComparer = new StringConvertibleMatrixView.RowComparer();
52    }
53
54    protected override void RegisterContentEvents() {
55      base.RegisterContentEvents();
56      Content.ProgressCalculation += new DataAnalysis.FeatureCorrelation.ProgressCalculationHandler(Content_ProgressCalculation);
57      Content.CorrelationCalculationFinished += new System.EventHandler(Content_CorrelationCalculationFinished);
58    }
59
60    protected override void DeregisterContentEvents() {
61      Content.CorrelationCalculationFinished -= new System.EventHandler(Content_CorrelationCalculationFinished);
62      Content.ProgressCalculation -= new DataAnalysis.FeatureCorrelation.ProgressCalculationHandler(Content_ProgressCalculation);
63      base.DeregisterContentEvents();
64    }
65
66    protected void Content_ProgressCalculation(object sender, ProgressChangedEventArgs e) {
67      if (!CalculatingPanel.Visible && e.ProgressPercentage != HeatMapProgressBar.Maximum) {
68        CalculatingPanel.Show();
69      } else if (e.ProgressPercentage == HeatMapProgressBar.Maximum) {
70        CalculatingPanel.Hide();
71      }
72      HeatMapProgressBar.Value = e.ProgressPercentage;
73    }
74
75    protected override void OnContentChanged() {
76      base.OnContentChanged();
77      if (Content != null) {
78        CorrelationCalcComboBox.DataSource = Content.CorrelationCalculators;
79        PartitionComboBox.DataSource = Content.Partitions;
80        CalculateCorrelation();
81      } else {
82        DataGridView.Columns.Clear();
83        DataGridView.Rows.Clear();
84      }
85    }
86
87    protected void CorrelationMeasureComboBox_SelectedIndexChanged(object sender, System.EventArgs e) {
88      CalculateCorrelation();
89    }
90    protected void PartitionComboBox_SelectedIndexChanged(object sender, System.EventArgs e) {
91      CalculateCorrelation();
92    }
93
94    protected virtual void CalculateCorrelation() {
95      string calc = (string)CorrelationCalcComboBox.SelectedItem;
96      string partition = (string)PartitionComboBox.SelectedItem;
97      if (calc != null && partition != null) {
98        DataGridView.Columns.Clear();
99        DataGridView.Enabled = false;
100        Content.Recalculate(calc, partition);
101      }
102    }
103
104    protected void UpdateDataGrid() {
105      virtualRowIndices = Enumerable.Range(0, Content.Rows).ToArray();
106      DataGridViewColumn[] columns = new DataGridViewColumn[Content.Columns];
107      for (int i = 0; i < columns.Length; ++i) {
108        var column = new DataGridViewTextBoxColumn();
109        column.FillWeight = 1;
110        columns[i] = column;
111      }
112
113      DataGridView.Columns.Clear();
114      DataGridView.Columns.AddRange(columns);
115
116      DataGridView.RowCount = Content.Rows;
117
118      ClearSorting();
119      UpdateColumnHeaders();
120      UpdateRowHeaders();
121
122      maximumLabel.Text = Content.Maximum.ToString();
123      minimumLabel.Text = Content.Minimum.ToString();
124
125      DataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
126      DataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
127      DataGridView.Enabled = true;
128    }
129
130    protected virtual void UpdateColumnHeaders() {
131      for (int i = 0; i < DataGridView.ColumnCount; i++) {
132        DataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
133      }
134    }
135    protected void UpdateRowHeaders() {
136      for (int i = 0; i < DataGridView.RowCount; i++) {
137        DataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(virtualRowIndices[i]);
138      }
139    }
140
141    protected void Content_CorrelationCalculationFinished(object sender, System.EventArgs e) {
142      if (InvokeRequired) {
143        Invoke(new EventHandler(Content_CorrelationCalculationFinished), sender, e);
144      } else {
145        UpdateDataGrid();
146      }
147    }
148
149    protected void DataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
150      if (Content == null) return;
151      int rowIndex = virtualRowIndices[e.RowIndex];
152      e.Value = Content[rowIndex, e.ColumnIndex];
153    }
154
155    protected void DataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
156      //if (Content != null && DataGridView.Enabled && e.RowIndex >= 0 && e.ColumnIndex >= 0 && e.PaintParts.HasFlag(DataGridViewPaintParts.Background)) {
157      //  int rowIndex = virtualRowIndices[e.RowIndex];
158      //e.CellStyle.BackColor = GetDataPointColor(Content[rowIndex, e.ColumnIndex], Content.Minimum, Content.Maximum);
159      //}
160      //e.Paint(e.CellBounds, e.PaintParts);
161
162      if (Content == null) return;
163      if (e.RowIndex < 0) return;
164      if (e.ColumnIndex < 0) return;
165      if (e.State.HasFlag(DataGridViewElementStates.Selected)) return;
166      if (!e.PaintParts.HasFlag(DataGridViewPaintParts.Background)) return;
167
168      int rowIndex = virtualRowIndices[e.RowIndex];
169      Color backColor = GetDataPointColor(Content[rowIndex, e.ColumnIndex], Content.Minimum, Content.Maximum);
170      using (Brush backColorBrush = new SolidBrush(backColor)) {
171        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
172      }
173      e.PaintContent(e.CellBounds);
174      e.Handled = true;
175    }
176
177    protected virtual Color GetDataPointColor(double value, double min, double max) {
178      IList<Color> colors = ColorGradient.Colors;
179      int index = (int)((colors.Count - 1) * (value - min) / (max - min));
180      if (index >= colors.Count) index = colors.Count - 1;
181      if (index < 0) index = 0;
182      return colors[index];
183    }
184
185    #region sort
186    protected void DataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
187      if (Content != null) {
188        if (e.Button == MouseButtons.Left && Content.SortableView) {
189          bool addToSortedIndices = (Control.ModifierKeys & Keys.Control) == Keys.Control;
190          SortOrder newSortOrder = SortOrder.Ascending;
191          if (sortedColumnIndices.Any(x => x.Key == e.ColumnIndex)) {
192            SortOrder oldSortOrder = sortedColumnIndices.Where(x => x.Key == e.ColumnIndex).First().Value;
193            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
194            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
195          }
196
197          if (!addToSortedIndices)
198            sortedColumnIndices.Clear();
199
200          if (sortedColumnIndices.Any(x => x.Key == e.ColumnIndex)) {
201            int sortedIndex = sortedColumnIndices.FindIndex(x => x.Key == e.ColumnIndex);
202            if (newSortOrder != SortOrder.None)
203              sortedColumnIndices[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
204            else
205              sortedColumnIndices.RemoveAt(sortedIndex);
206          } else
207            if (newSortOrder != SortOrder.None)
208              sortedColumnIndices.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
209          Sort();
210        }
211      }
212    }
213
214    protected virtual void ClearSorting() {
215      virtualRowIndices = Enumerable.Range(0, Content.Rows).ToArray();
216      sortedColumnIndices.Clear();
217      UpdateSortGlyph();
218    }
219
220    private void Sort() {
221      virtualRowIndices = Sort(sortedColumnIndices);
222      UpdateSortGlyph();
223      UpdateRowHeaders();
224      DataGridView.Invalidate();
225    }
226
227    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
228      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
229      if (sortedColumns.Count() != 0) {
230        rowComparer.SortedIndices = sortedColumns;
231        rowComparer.Matrix = Content;
232        Array.Sort(newSortedIndex, rowComparer);
233      }
234      return newSortedIndex;
235    }
236    private void UpdateSortGlyph() {
237      foreach (DataGridViewColumn col in this.DataGridView.Columns)
238        col.HeaderCell.SortGlyphDirection = SortOrder.None;
239      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndices)
240        this.DataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
241    }
242    #endregion
243
244    #region copy
245    private void DataGridView_KeyDown(object sender, KeyEventArgs e) {
246      if (e.Control && e.KeyCode == Keys.C)
247        CopyValuesFromDataGridView();
248    }
249
250    private void CopyValuesFromDataGridView() {
251      if (DataGridView.SelectedCells.Count == 0) return;
252      StringBuilder s = new StringBuilder();
253      int minRowIndex = DataGridView.SelectedCells[0].RowIndex;
254      int maxRowIndex = DataGridView.SelectedCells[DataGridView.SelectedCells.Count - 1].RowIndex;
255      int minColIndex = DataGridView.SelectedCells[0].ColumnIndex;
256      int maxColIndex = DataGridView.SelectedCells[DataGridView.SelectedCells.Count - 1].ColumnIndex;
257
258      if (minRowIndex > maxRowIndex) {
259        int temp = minRowIndex;
260        minRowIndex = maxRowIndex;
261        maxRowIndex = temp;
262      }
263      if (minColIndex > maxColIndex) {
264        int temp = minColIndex;
265        minColIndex = maxColIndex;
266        maxColIndex = temp;
267      }
268
269      bool addRowNames = DataGridView.AreAllCellsSelected(false) && Content.RowNames.Count() > 0;
270      bool addColumnNames = DataGridView.AreAllCellsSelected(false) && Content.ColumnNames.Count() > 0;
271
272      //add colum names
273      if (addColumnNames) {
274        if (addRowNames)
275          s.Append('\t');
276
277        DataGridViewColumn column = DataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
278        while (column != null) {
279          s.Append(column.HeaderText);
280          s.Append('\t');
281          column = DataGridView.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None);
282        }
283        s.Remove(s.Length - 1, 1); //remove last tab
284        s.Append(Environment.NewLine);
285      }
286
287      for (int i = minRowIndex; i <= maxRowIndex; i++) {
288        int rowIndex = this.virtualRowIndices[i];
289        if (addRowNames) {
290          s.Append(Content.RowNames.ElementAt(rowIndex));
291          s.Append('\t');
292        }
293
294        DataGridViewColumn column = DataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
295        while (column != null) {
296          DataGridViewCell cell = DataGridView[column.Index, i];
297          if (cell.Selected) {
298            s.Append(Content[rowIndex, column.Index]);
299            s.Append('\t');
300          }
301
302          column = DataGridView.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None);
303        }
304        s.Remove(s.Length - 1, 1); //remove last tab
305        s.Append(Environment.NewLine);
306      }
307      Clipboard.SetText(s.ToString());
308    }
309    #endregion
310  }
311}
Note: See TracBrowser for help on using the repository browser.