Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimization/3.3/RunCollection.cs @ 8694

Last change on this file since 8694 was 7798, checked in by mkommend, 13 years ago

#1843: Cleared dataType cache in RunCollection on collection reset.

File size: 17.2 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.Linq;
25using HeuristicLab.Collections;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Data;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Optimization {
32  [Item("Run Collection", "Represents a collection of runs.")]
33  [Creatable("Testing & Analysis")]
34  [StorableClass]
35  public class RunCollection : ItemCollection<IRun>, IStringConvertibleMatrix, IStorableContent {
36    public string Filename { get; set; }
37
38    [StorableConstructor]
39    protected RunCollection(bool deserializing)
40      : base(deserializing) {
41      updateOfRunsInProgress = false;
42    }
43    protected RunCollection(RunCollection original, Cloner cloner)
44      : base(original, cloner) {
45      updateOfRunsInProgress = false;
46      resultNames = new List<string>(original.resultNames);
47      parameterNames = new List<string>(original.parameterNames);
48      dataTypes = new Dictionary<string, HashSet<Type>>();
49      foreach (string s in original.dataTypes.Keys)
50        dataTypes[s] = new HashSet<Type>(original.dataTypes[s]);
51
52      constraints = new RunCollectionConstraintCollection(original.constraints.Select(x => cloner.Clone(x)));
53      modifiers = new CheckedItemList<IRunCollectionModifier>(original.modifiers.Select(cloner.Clone));
54      foreach (IRunCollectionConstraint constraint in constraints)
55        constraint.ConstrainedValue = this;
56      RegisterConstraintsEvents();
57      RegisterConstraintEvents(constraints);
58
59      UpdateFiltering(true);
60    }
61    public RunCollection() : base() { Initialize(); }
62    public RunCollection(int capacity) : base(capacity) { Initialize(); }
63    public RunCollection(IEnumerable<IRun> collection) : base(collection) { Initialize(); this.OnItemsAdded(collection); }
64    private void Initialize() {
65      updateOfRunsInProgress = false;
66      parameterNames = new List<string>();
67      resultNames = new List<string>();
68      dataTypes = new Dictionary<string, HashSet<Type>>();
69      constraints = new RunCollectionConstraintCollection();
70      modifiers = new CheckedItemList<IRunCollectionModifier>();
71      RegisterConstraintsEvents();
72    }
73
74    [Storable]
75    private Dictionary<string, HashSet<Type>> dataTypes;
76    public IEnumerable<Type> GetDataType(string columnName) {
77      if (!dataTypes.ContainsKey(columnName))
78        return new Type[0];
79      return dataTypes[columnName];
80    }
81
82    [Storable]
83    private RunCollectionConstraintCollection constraints;
84    public RunCollectionConstraintCollection Constraints {
85      get { return constraints; }
86    }
87
88    [Storable]
89    private CheckedItemList<IRunCollectionModifier> modifiers;
90    public CheckedItemList<IRunCollectionModifier> Modifiers {
91      get { return modifiers; }
92    }
93
94
95    private bool updateOfRunsInProgress;
96    public bool UpdateOfRunsInProgress {
97      get { return updateOfRunsInProgress; }
98      set {
99        if (updateOfRunsInProgress != value) {
100          updateOfRunsInProgress = value;
101          OnUpdateOfRunsInProgressChanged();
102        }
103      }
104    }
105
106    [StorableHook(HookType.AfterDeserialization)]
107    private void AfterDeserialization() {
108      if (constraints == null) constraints = new RunCollectionConstraintCollection();
109      if (modifiers == null) modifiers = new CheckedItemList<IRunCollectionModifier>();
110      RegisterConstraintsEvents();
111      RegisterConstraintEvents(constraints);
112      UpdateFiltering(true);
113    }
114
115    public override IDeepCloneable Clone(Cloner cloner) {
116      return new RunCollection(this, cloner);
117    }
118
119    public event EventHandler UpdateOfRunsInProgressChanged;
120    protected virtual void OnUpdateOfRunsInProgressChanged() {
121      var handler = UpdateOfRunsInProgressChanged;
122      if (handler != null) handler(this, EventArgs.Empty);
123    }
124
125    protected override void OnCollectionReset(IEnumerable<IRun> items, IEnumerable<IRun> oldItems) {
126      parameterNames.Clear();
127      resultNames.Clear();
128      dataTypes.Clear();
129      foreach (IRun run in items) {
130        foreach (KeyValuePair<string, IItem> parameter in run.Parameters)
131          AddParameter(parameter.Key, parameter.Value);
132        foreach (KeyValuePair<string, IItem> result in run.Results)
133          AddResult(result.Key, result.Value);
134      }
135      columnNameCache = null;
136      OnColumnsChanged();
137      OnColumnNamesChanged();
138      rowNamesCache = null;
139      base.OnCollectionReset(items, oldItems);
140      OnRowsChanged();
141      OnRowNamesChanged();
142      OnReset();
143      UpdateFiltering(false);
144    }
145    protected override void OnItemsAdded(IEnumerable<IRun> items) {
146      bool columnsChanged = false;
147      foreach (IRun run in items) {
148        foreach (KeyValuePair<string, IItem> parameter in run.Parameters)
149          columnsChanged |= AddParameter(parameter.Key, parameter.Value);
150        foreach (KeyValuePair<string, IItem> result in run.Results)
151          columnsChanged |= AddResult(result.Key, result.Value);
152      }
153      if (columnsChanged) columnNameCache = null;
154      rowNamesCache = null;
155      base.OnItemsAdded(items);
156      OnReset();
157      OnRowsChanged();
158      OnRowNamesChanged();
159      if (columnsChanged) {
160        OnColumnsChanged();
161        OnColumnNamesChanged();
162      }
163      UpdateFiltering(false);
164    }
165    protected override void OnItemsRemoved(IEnumerable<IRun> items) {
166      bool columnsChanged = false;
167      foreach (IRun run in items) {
168        foreach (string parameterName in run.Parameters.Keys)
169          columnsChanged |= RemoveParameterName(parameterName);
170        foreach (string resultName in run.Results.Keys)
171          columnsChanged |= RemoveResultName(resultName);
172      }
173      if (columnsChanged) columnNameCache = null;
174      rowNamesCache = null;
175      base.OnItemsRemoved(items);
176      OnReset();
177      OnRowsChanged();
178      OnRowNamesChanged();
179      if (columnsChanged) {
180        OnColumnsChanged();
181        OnColumnNamesChanged();
182      }
183    }
184
185    private bool AddParameter(string name, IItem value) {
186      if (value == null)
187        return false;
188      if (!parameterNames.Contains(name)) {
189        parameterNames.Add(name);
190        dataTypes[name] = new HashSet<Type>();
191        dataTypes[name].Add(value.GetType());
192        return true;
193      }
194      dataTypes[name].Add(value.GetType());
195      return false;
196    }
197    private bool AddResult(string name, IItem value) {
198      if (value == null)
199        return false;
200      if (!resultNames.Contains(name)) {
201        resultNames.Add(name);
202        dataTypes[name] = new HashSet<Type>();
203        dataTypes[name].Add(value.GetType());
204        return true;
205      }
206      dataTypes[name].Add(value.GetType());
207      return false;
208    }
209    private bool RemoveParameterName(string name) {
210      if (!list.Any(x => x.Parameters.ContainsKey(name))) {
211        parameterNames.Remove(name);
212        return true;
213      }
214      return false;
215    }
216    private bool RemoveResultName(string name) {
217      if (!list.Any(x => x.Results.ContainsKey(name))) {
218        resultNames.Remove(name);
219        return true;
220      }
221      return false;
222    }
223
224    public IItem GetValue(int rowIndex, int columnIndex) {
225      IRun run = this.list[rowIndex];
226      return GetValue(run, columnIndex);
227    }
228
229    public IItem GetValue(IRun run, int columnIndex) {
230      string name = ((IStringConvertibleMatrix)this).ColumnNames.ElementAt(columnIndex);
231      return GetValue(run, name);
232    }
233
234    public IItem GetValue(IRun run, string columnName) {
235      IItem value = null;
236      if (run.Parameters.ContainsKey(columnName))
237        value = run.Parameters[columnName];
238      else if (run.Results.ContainsKey(columnName))
239        value = run.Results[columnName];
240      return value;
241    }
242
243    #region IStringConvertibleMatrix Members
244    [Storable]
245    private List<string> parameterNames;
246    public IEnumerable<string> ParameterNames {
247      get { return this.parameterNames; }
248    }
249    [Storable]
250    private List<string> resultNames;
251    public IEnumerable<string> ResultNames {
252      get { return this.resultNames; }
253    }
254    int IStringConvertibleMatrix.Rows {
255      get { return this.Count; }
256      set { throw new NotSupportedException(); }
257    }
258    int IStringConvertibleMatrix.Columns {
259      get { return parameterNames.Count + resultNames.Count; }
260      set { throw new NotSupportedException(); }
261    }
262    private List<string> columnNameCache;
263    IEnumerable<string> IStringConvertibleMatrix.ColumnNames {
264      get {
265        if (columnNameCache == null) {
266          columnNameCache = new List<string>(parameterNames);
267          columnNameCache.AddRange(resultNames);
268          columnNameCache.Sort();
269        }
270        return columnNameCache;
271      }
272      set { throw new NotSupportedException(); }
273    }
274    private List<string> rowNamesCache;
275    IEnumerable<string> IStringConvertibleMatrix.RowNames {
276      get {
277        if (rowNamesCache == null)
278          rowNamesCache = list.Select(x => x.Name).ToList();
279        return rowNamesCache;
280      }
281      set { throw new NotSupportedException(); }
282    }
283    bool IStringConvertibleMatrix.SortableView {
284      get { return true; }
285      set { throw new NotSupportedException(); }
286    }
287    bool IStringConvertibleMatrix.ReadOnly {
288      get { return true; }
289    }
290
291    string IStringConvertibleMatrix.GetValue(int rowIndex, int columnIndex) {
292      IItem value = GetValue(rowIndex, columnIndex);
293      if (value == null)
294        return string.Empty;
295      return value.ToString();
296    }
297
298    public event EventHandler<EventArgs<int, int>> ItemChanged;
299    protected virtual void OnItemChanged(int rowIndex, int columnIndex) {
300      EventHandler<EventArgs<int, int>> handler = ItemChanged;
301      if (handler != null) handler(this, new EventArgs<int, int>(rowIndex, columnIndex));
302      OnToStringChanged();
303    }
304    public event EventHandler Reset;
305    protected virtual void OnReset() {
306      EventHandler handler = Reset;
307      if (handler != null) handler(this, EventArgs.Empty);
308      OnToStringChanged();
309    }
310    public event EventHandler ColumnsChanged;
311    protected virtual void OnColumnsChanged() {
312      var handler = ColumnsChanged;
313      if (handler != null) handler(this, EventArgs.Empty);
314    }
315    public event EventHandler RowsChanged;
316    protected virtual void OnRowsChanged() {
317      var handler = RowsChanged;
318      if (handler != null) handler(this, EventArgs.Empty);
319    }
320    public event EventHandler ColumnNamesChanged;
321    protected virtual void OnColumnNamesChanged() {
322      EventHandler handler = ColumnNamesChanged;
323      if (handler != null) handler(this, EventArgs.Empty);
324    }
325    public event EventHandler RowNamesChanged;
326    protected virtual void OnRowNamesChanged() {
327      EventHandler handler = RowNamesChanged;
328      if (handler != null) handler(this, EventArgs.Empty);
329    }
330    public event EventHandler SortableViewChanged;
331    protected virtual void OnSortableViewChanged() {
332      EventHandler handler = SortableViewChanged;
333      if (handler != null) handler(this, EventArgs.Empty);
334    }
335
336    public bool Validate(string value, out string errorMessage) { throw new NotSupportedException(); }
337    public bool SetValue(string value, int rowIndex, int columnIndex) { throw new NotSupportedException(); }
338    #endregion
339
340    #region Filtering
341    private void UpdateFiltering(bool reset) {
342      UpdateOfRunsInProgress = true;
343      if (reset)
344        list.ForEach(r => r.Visible = true);
345      foreach (IRunCollectionConstraint constraint in this.constraints)
346        constraint.Check();
347      UpdateOfRunsInProgress = false;
348    }
349
350    private void RegisterConstraintsEvents() {
351      constraints.ItemsAdded += new CollectionItemsChangedEventHandler<IRunCollectionConstraint>(Constraints_ItemsAdded);
352      constraints.ItemsRemoved += new CollectionItemsChangedEventHandler<IRunCollectionConstraint>(Constraints_ItemsRemoved);
353      constraints.CollectionReset += new CollectionItemsChangedEventHandler<IRunCollectionConstraint>(Constraints_CollectionReset);
354    }
355
356    protected virtual void RegisterConstraintEvents(IEnumerable<IRunCollectionConstraint> constraints) {
357      foreach (IRunCollectionConstraint constraint in constraints) {
358        constraint.ActiveChanged += new EventHandler(Constraint_ActiveChanged);
359        constraint.ConstrainedValueChanged += new EventHandler(Constraint_ConstrainedValueChanged);
360        constraint.ConstraintOperationChanged += new EventHandler(Constraint_ConstraintOperationChanged);
361        constraint.ConstraintDataChanged += new EventHandler(Constraint_ConstraintDataChanged);
362      }
363    }
364    protected virtual void DeregisterConstraintEvents(IEnumerable<IRunCollectionConstraint> constraints) {
365      foreach (IRunCollectionConstraint constraint in constraints) {
366        constraint.ActiveChanged -= new EventHandler(Constraint_ActiveChanged);
367        constraint.ConstrainedValueChanged -= new EventHandler(Constraint_ConstrainedValueChanged);
368        constraint.ConstraintOperationChanged -= new EventHandler(Constraint_ConstraintOperationChanged);
369        constraint.ConstraintDataChanged -= new EventHandler(Constraint_ConstraintDataChanged);
370      }
371    }
372
373    protected virtual void Constraints_CollectionReset(object sender, CollectionItemsChangedEventArgs<IRunCollectionConstraint> e) {
374      DeregisterConstraintEvents(e.OldItems);
375      RegisterConstraintEvents(e.Items);
376      this.UpdateFiltering(true);
377    }
378    protected virtual void Constraints_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IRunCollectionConstraint> e) {
379      RegisterConstraintEvents(e.Items);
380      foreach (IRunCollectionConstraint constraint in e.Items)
381        constraint.ConstrainedValue = this;
382      this.UpdateFiltering(false);
383    }
384    protected virtual void Constraints_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IRunCollectionConstraint> e) {
385      DeregisterConstraintEvents(e.Items);
386      this.UpdateFiltering(true);
387    }
388    protected virtual void Constraint_ActiveChanged(object sender, EventArgs e) {
389      IRunCollectionConstraint constraint = (IRunCollectionConstraint)sender;
390      this.UpdateFiltering(!constraint.Active);
391    }
392    protected virtual void Constraint_ConstrainedValueChanged(object sender, EventArgs e) {
393      //mkommend: this method is intentionally left empty, because the constrainedValue is set in the ItemsAdded method
394    }
395    protected virtual void Constraint_ConstraintOperationChanged(object sender, EventArgs e) {
396      IRunCollectionConstraint constraint = (IRunCollectionConstraint)sender;
397      if (constraint.Active)
398        this.UpdateFiltering(true);
399    }
400    protected virtual void Constraint_ConstraintDataChanged(object sender, EventArgs e) {
401      IRunCollectionConstraint constraint = (IRunCollectionConstraint)sender;
402      if (constraint.Active)
403        this.UpdateFiltering(true);
404    }
405    #endregion
406
407    #region Modification
408    public void Modify() {
409      UpdateOfRunsInProgress = true;
410      var runs = this.ToList();
411      var selectedRuns = runs.Where(r => r.Visible).ToList();
412      int nSelected = selectedRuns.Count;
413      if (nSelected > 0) {
414        foreach (var modifier in Modifiers.CheckedItems)
415          modifier.Value.Modify(selectedRuns);
416        if (nSelected != selectedRuns.Count || HaveDifferentOrder(selectedRuns, runs.Where(r => r.Visible))) {
417          Clear();
418          AddRange(ReplaceVisibleRuns(runs, selectedRuns));
419        } else if (runs.Count > 0) {
420          OnCollectionReset(this, runs);
421        }
422      }
423      UpdateOfRunsInProgress = false;
424    }
425
426    private static IEnumerable<IRun> ReplaceVisibleRuns(IEnumerable<IRun> runs, IEnumerable<IRun> visibleRuns) {
427      var newRuns = new List<IRun>();
428      var runIt = runs.GetEnumerator();
429      var visibleRunIt = visibleRuns.GetEnumerator();
430      while (runIt.MoveNext()) {
431        if (runIt.Current != null && !runIt.Current.Visible)
432          newRuns.Add(runIt.Current);
433        else if (visibleRunIt.MoveNext())
434          newRuns.Add(visibleRunIt.Current);
435      }
436      while (visibleRunIt.MoveNext())
437        newRuns.Add(visibleRunIt.Current);
438      return newRuns;
439    }
440
441    private static bool HaveDifferentOrder(IEnumerable<IRun> l1, IEnumerable<IRun> l2) {
442      return l1.Zip(l2, (r1, r2) => r1 != r2).Any();
443    }
444    #endregion
445  }
446}
Note: See TracBrowser for help on using the repository browser.