Free cookie consent management tool by TermsFeed Policy Generator

source: branches/symbreg-factors-2650/HeuristicLab.Optimization.Views/3.3/RunCollectionViews/RunCollectionTableView.cs @ 14825

Last change on this file since 14825 was 14185, checked in by swagner, 8 years ago

#2526: Updated year of copyrights in license headers

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