Free cookie consent management tool by TermsFeed Policy Generator

source: tags/3.3.13/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionTableView.cs @ 17858

Last change on this file since 17858 was 13063, checked in by gkronber, 9 years ago

#2473: merged r13036 and r13054 from trunk to stable

File size: 11.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Linq;
26using System.Windows.Forms;
27using HeuristicLab.Collections;
28using HeuristicLab.Core;
29using HeuristicLab.Data.Views;
30using HeuristicLab.MainForm;
31
32namespace HeuristicLab.Optimization.Views {
33  [View("Table")]
34  [Content(typeof(RunCollection), false)]
35  public sealed partial class RunCollectionTableView : StringConvertibleMatrixView {
36    private int[] runToRowMapping;
37    private bool suppressUpdates = false;
38    public RunCollectionTableView() {
39      InitializeComponent();
40      dataGridView.RowHeaderMouseDoubleClick += new DataGridViewCellMouseEventHandler(dataGridView_RowHeaderMouseDoubleClick);
41    }
42
43    public override bool ReadOnly {
44      get { return true; }
45      set { /*not needed because results are always readonly */}
46    }
47
48    public new RunCollection Content {
49      get { return (RunCollection)base.Content; }
50      set { base.Content = value; }
51    }
52
53    protected override void OnContentChanged() {
54      base.OnContentChanged();
55      if (Content != null) {
56        UpdateRowAttributes();
57      }
58      UpdateCaption();
59    }
60
61    #region events
62    protected override void RegisterContentEvents() {
63      base.RegisterContentEvents();
64      Content.ItemsAdded += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
65      Content.ItemsRemoved += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
66      Content.CollectionReset += new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
67      Content.UpdateOfRunsInProgressChanged += new EventHandler(Content_UpdateOfRunsInProgressChanged);
68      Content.OptimizerNameChanged += new EventHandler(Content_AlgorithmNameChanged);
69      RegisterRunEvents(Content);
70    }
71    private void RegisterRunEvents(IEnumerable<IRun> runs) {
72      foreach (IRun run in runs)
73        run.PropertyChanged += run_PropertyChanged;
74    }
75    protected override void DeregisterContentEvents() {
76      base.DeregisterContentEvents();
77      Content.ItemsAdded -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsAdded);
78      Content.ItemsRemoved -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_ItemsRemoved);
79      Content.CollectionReset -= new HeuristicLab.Collections.CollectionItemsChangedEventHandler<IRun>(Content_CollectionReset);
80      Content.UpdateOfRunsInProgressChanged -= new EventHandler(Content_UpdateOfRunsInProgressChanged);
81      Content.OptimizerNameChanged -= new EventHandler(Content_AlgorithmNameChanged);
82      DeregisterRunEvents(Content);
83    }
84    private void DeregisterRunEvents(IEnumerable<IRun> runs) {
85      foreach (IRun run in runs)
86        run.PropertyChanged -= run_PropertyChanged;
87    }
88    private void Content_CollectionReset(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
89      DeregisterRunEvents(e.OldItems);
90      RegisterRunEvents(e.Items);
91    }
92    private void Content_ItemsRemoved(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
93      DeregisterRunEvents(e.Items);
94    }
95    private void Content_ItemsAdded(object sender, HeuristicLab.Collections.CollectionItemsChangedEventArgs<IRun> e) {
96      RegisterRunEvents(e.Items);
97    }
98    private void Content_AlgorithmNameChanged(object sender, EventArgs e) {
99      if (InvokeRequired)
100        Invoke(new EventHandler(Content_AlgorithmNameChanged), sender, e);
101      else UpdateCaption();
102    }
103    private void run_PropertyChanged(object sender, PropertyChangedEventArgs e) {
104      if (suppressUpdates) return;
105      if (InvokeRequired)
106        this.Invoke((Action<object, PropertyChangedEventArgs>)run_PropertyChanged, sender, e);
107      else {
108        IRun run = (IRun)sender;
109        if (e.PropertyName == "Color" || e.PropertyName == "Visible")
110          UpdateRun(run);
111      }
112    }
113    #endregion
114
115    private void UpdateCaption() {
116      Caption = Content != null ? Content.OptimizerName + " Table" : ViewAttribute.GetViewName(GetType());
117    }
118
119    protected override void UpdateData() {
120      if (suppressUpdates) return;
121      base.UpdateData();
122    }
123
124    protected override void UpdateColumnHeaders() {
125      string[] colNames = base.Content.ColumnNames.ToArray();
126      int colCount = colNames.Length;
127      for (int i = 0; i < dataGridView.ColumnCount; i++) {
128        if (i < colCount)
129          dataGridView.Columns[i].HeaderText = colNames[i];
130        else
131          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
132      }
133
134      HashSet<string> visibleColumnNames = new HashSet<string>(
135        dataGridView.Columns.OfType<DataGridViewColumn>()
136       .Where(c => c.Visible)
137       .Where(c => !string.IsNullOrEmpty(c.HeaderText))
138       .Where(c => !IsConstant(c.HeaderText))
139       .Select(c => c.HeaderText));
140
141      for (int i = 0; i < dataGridView.ColumnCount; i++) {
142        dataGridView.Columns[i].Visible = visibleColumnNames.Count == 0 || visibleColumnNames.Contains(dataGridView.Columns[i].HeaderText);
143      }
144    }
145
146    // returns true when all values in the column are the same (missing values are included in the count)
147    private bool IsConstant(string columnName) {
148      Func<IRun, string, string> GetStringValue = (IRun r, string colName) => {
149        // also include missing values in the count
150        IItem v = null;
151        if (r.Parameters.TryGetValue(colName, out v)) return v.ToString();
152        if (r.Results.TryGetValue(colName, out v)) return v.ToString();
153        return string.Empty;
154      };
155
156      var firstRun = Content.First();
157      string firstValue = GetStringValue(firstRun, columnName);
158      return Content.Skip(1).All(run => firstValue == GetStringValue(run, columnName));
159    }
160
161    private void UpdateRun(IRun run) {
162      foreach (int runIndex in GetIndexOfRun(run)) {
163        int rowIndex = runToRowMapping[runIndex];
164        this.dataGridView.Rows[rowIndex].Visible = run.Visible;
165        this.dataGridView.Rows[rowIndex].DefaultCellStyle.ForeColor = run.Color;
166      }
167      this.UpdateRowHeaders();
168    }
169
170
171    private void Content_UpdateOfRunsInProgressChanged(object sender, EventArgs e) {
172      if (InvokeRequired)
173        Invoke(new EventHandler(Content_UpdateOfRunsInProgressChanged), sender, e);
174      else {
175        suppressUpdates = Content.UpdateOfRunsInProgress;
176        if (!suppressUpdates) {
177          UpdateData();
178          UpdateRowAttributes();
179        }
180      }
181    }
182
183    private IEnumerable<int> GetIndexOfRun(IRun run) {
184      int i = 0;
185      foreach (IRun actualRun in Content) {
186        if (actualRun == run)
187          yield return i;
188        i++;
189      }
190    }
191
192    private void dataGridView_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
193      if (e.RowIndex >= 0) {
194        IRun run = Content.ElementAt(runToRowMapping.ToList().IndexOf(e.RowIndex));
195        IContentView view = MainFormManager.MainForm.ShowContent(run);
196        if (view != null) {
197          view.ReadOnly = this.ReadOnly;
198          view.Locked = this.Locked;
199        }
200      }
201    }
202
203    protected override void ClearSorting() {
204      base.ClearSorting();
205      UpdateRowAttributes();
206    }
207
208    protected override int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
209      int[] newSortedIndex = Enumerable.Range(0, Content.Count).ToArray();
210      RunCollectionRowComparer rowComparer = new RunCollectionRowComparer();
211      if (sortedColumns.Count() != 0) {
212        rowComparer.SortedIndices = sortedColumns;
213        rowComparer.Matrix = Content;
214        Array.Sort(newSortedIndex, rowComparer);
215      }
216
217      runToRowMapping = new int[newSortedIndex.Length];
218      int i = 0;
219      foreach (int runIndex in newSortedIndex) {
220        runToRowMapping[runIndex] = i;
221        i++;
222      }
223      UpdateRowAttributes(rebuild: false);
224      return newSortedIndex;
225    }
226
227    private void UpdateRowAttributes(bool rebuild = true) {
228      if (rebuild) runToRowMapping = Enumerable.Range(0, Content.Count).ToArray();
229      int runIndex = 0;
230      foreach (IRun run in Content) {
231        int rowIndex = this.runToRowMapping[runIndex];
232        this.dataGridView.Rows[rowIndex].Visible = run.Visible;
233        this.dataGridView.Rows[rowIndex].DefaultCellStyle.ForeColor = run.Color;
234        runIndex++;
235      }
236      rowsTextBox.Text = dataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible).ToString();
237      UpdateRowHeaders();
238    }
239
240    public class RunCollectionRowComparer : IComparer<int> {
241      public RunCollectionRowComparer() {
242      }
243
244      private List<KeyValuePair<int, SortOrder>> sortedIndices;
245      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndices {
246        get { return this.sortedIndices; }
247        set { sortedIndices = new List<KeyValuePair<int, SortOrder>>(value); }
248      }
249      private RunCollection matrix;
250      public RunCollection Matrix {
251        get { return this.matrix; }
252        set { this.matrix = value; }
253      }
254
255      public int Compare(int x, int y) {
256        int result = 0;
257        IItem value1, value2;
258        IComparable comparable1, comparable2;
259
260        if (matrix == null)
261          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
262        if (sortedIndices == null)
263          return 0;
264
265        foreach (KeyValuePair<int, SortOrder> pair in sortedIndices.Where(p => p.Value != SortOrder.None)) {
266          value1 = matrix.GetValue(x, pair.Key);
267          value2 = matrix.GetValue(y, pair.Key);
268          comparable1 = value1 as IComparable;
269          comparable2 = value2 as IComparable;
270          if (comparable1 != null)
271            result = comparable1.CompareTo(comparable2);
272          else {
273            string string1 = value1 != null ? value1.ToString() : string.Empty;
274            string string2 = value2 != null ? value2.ToString() : string.Empty;
275            result = string1.CompareTo(string2);
276          }
277          if (pair.Value == SortOrder.Descending)
278            result *= -1;
279          if (result != 0)
280            return result;
281        }
282        return result;
283      }
284    }
285  }
286}
Note: See TracBrowser for help on using the repository browser.