Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataPreprocessing/HeuristicLab.DataPreprocessing/3.4/Implementations/TransactionalPreprocessingData.cs @ 11098

Last change on this file since 11098 was 11098, checked in by mkommend, 10 years ago

#2206: Bug fixes regarding the deletion of rows in the grid display and code simplifications.

File size: 11.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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;
24using System.Collections.Generic;
25using System.Globalization;
26using System.Linq;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Problems.DataAnalysis;
31
32namespace HeuristicLab.DataPreprocessing {
33
34  [Item("PreprocessingData", "Represents data used for preprocessing.")]
35  public class TransactionalPreprocessingData : PreprocessingData, ITransactionalPreprocessingData {
36
37    private class Snapshot {
38      public IList<IList> VariableValues { get; set; }
39      public IList<string> VariableNames { get; set; }
40
41      public IntRange TrainingPartition { get; set; }
42      public IntRange TestPartition { get; set; }
43      public IList<ITransformation> Transformations { get; set; }
44      public DataPreprocessingChangedEventType ChangedType { get; set; }
45
46      public int ChangedColumn { get; set; }
47      public int ChangedRow { get; set; }
48    }
49
50    private const int MAX_UNDO_DEPTH = 5;
51
52    private readonly IList<Snapshot> undoHistory = new List<Snapshot>();
53    private readonly Stack<DataPreprocessingChangedEventType> eventStack = new Stack<DataPreprocessingChangedEventType>();
54
55    public bool IsInTransaction { get { return eventStack.Count > 0; } }
56
57    public TransactionalPreprocessingData(IDataAnalysisProblemData problemData)
58      : base(problemData) {
59    }
60
61    private TransactionalPreprocessingData(TransactionalPreprocessingData original, Cloner cloner)
62      : base(original, cloner) {
63    }
64
65    private void SaveSnapshot(DataPreprocessingChangedEventType changedType, int column, int row) {
66      if (IsInTransaction) return;
67
68      var currentSnapshot = new Snapshot {
69        VariableValues = CopyVariableValues(variableValues),
70        VariableNames = new List<string>(variableNames),
71        TrainingPartition = new IntRange(TrainingPartition.Start, TrainingPartition.End),
72        TestPartition = new IntRange(TestPartition.Start, TestPartition.End),
73        Transformations = new List<ITransformation>(transformations),
74        ChangedType = changedType,
75        ChangedColumn = column,
76        ChangedRow = row
77      };
78
79      if (undoHistory.Count >= MAX_UNDO_DEPTH)
80        undoHistory.RemoveAt(0);
81
82      undoHistory.Add(currentSnapshot);
83    }
84
85    #region NamedItem abstract Member Implementations
86
87    public override IDeepCloneable Clone(Cloner cloner) {
88      return new TransactionalPreprocessingData(this, cloner);
89    }
90
91    #endregion
92
93    #region Overridden IPreprocessingData Members
94
95    public override T GetCell<T>(int columnIndex, int rowIndex) {
96      return (T)variableValues[columnIndex][rowIndex];
97    }
98
99    public override void SetCell<T>(int columnIndex, int rowIndex, T value) {
100      SaveSnapshot(DataPreprocessingChangedEventType.ChangeItem, columnIndex, rowIndex);
101      variableValues[columnIndex][rowIndex] = value;
102      if (!IsInTransaction)
103        OnChanged(DataPreprocessingChangedEventType.ChangeItem, columnIndex, rowIndex);
104    }
105
106    public override string GetCellAsString(int columnIndex, int rowIndex) {
107      return variableValues[columnIndex][rowIndex].ToString();
108    }
109
110    public override string GetVariableName(int columnIndex) {
111      return variableNames[columnIndex];
112    }
113
114    public override int GetColumnIndex(string variableName) {
115      return variableNames.IndexOf(variableName);
116    }
117
118    public override bool IsType<T>(int columnIndex) {
119      return variableValues[columnIndex] is List<T>;
120    }
121
122    [Obsolete("use the index based variant, is faster")]
123    public override IList<T> GetValues<T>(string variableName, bool considerSelection) {
124      return GetValues<T>(GetColumnIndex(variableName), considerSelection);
125    }
126
127    public override IList<T> GetValues<T>(int columnIndex, bool considerSelection) {
128      if (considerSelection) {
129        var list = new List<T>();
130        foreach (var rowIdx in selection[columnIndex]) {
131          list.Add((T)variableValues[columnIndex][rowIdx]);
132        }
133        return list;
134      } else {
135        return (IList<T>)variableValues[columnIndex];
136      }
137    }
138
139    public override void SetValues<T>(int columnIndex, IList<T> values) {
140      SaveSnapshot(DataPreprocessingChangedEventType.ChangeColumn, columnIndex, -1);
141      if (IsType<T>(columnIndex)) {
142        variableValues[columnIndex] = (IList)values;
143      } else {
144        throw new ArgumentException("The datatype of column " + columnIndex + " must be of type " + variableValues[columnIndex].GetType().Name + " but was " + typeof(T).Name);
145      }
146      if (!IsInTransaction)
147        OnChanged(DataPreprocessingChangedEventType.ChangeColumn, columnIndex, -1);
148    }
149
150    public override bool SetValue(string value, int columnIndex, int rowIndex) {
151      bool valid = false;
152      if (IsType<double>(columnIndex)) {
153        double val;
154        valid = double.TryParse(value, out val);
155        SetValueIfValid(columnIndex, rowIndex, valid, val);
156      } else if (IsType<string>(columnIndex)) {
157        valid = value != null;
158        SetValueIfValid(columnIndex, rowIndex, valid, value);
159      } else if (IsType<DateTime>(columnIndex)) {
160        DateTime date;
161        valid = DateTime.TryParse(value, out date);
162        SetValueIfValid(columnIndex, rowIndex, valid, date);
163      } else {
164        throw new ArgumentException("column " + columnIndex + " contains a non supported type.");
165      }
166
167      if (!IsInTransaction)
168        OnChanged(DataPreprocessingChangedEventType.ChangeColumn, columnIndex, -1);
169
170      return valid;
171    }
172
173    public override bool Validate(string value, out string errorMessage, int columnIndex) {
174      if (columnIndex < 0 || columnIndex > VariableNames.Count()) {
175        throw new ArgumentOutOfRangeException("column index is out of range");
176      }
177
178      bool valid = false;
179      errorMessage = string.Empty;
180      if (IsType<double>(columnIndex)) {
181        double val;
182        valid = double.TryParse(value, out val);
183        if (!valid) {
184          errorMessage = "Invalid Value (Valid Value Format: \"" + FormatPatterns.GetDoubleFormatPattern() + "\")";
185        }
186      } else if (IsType<string>(columnIndex)) {
187        valid = value != null;
188        if (!valid) {
189          errorMessage = "Invalid Value (string must not be null)";
190        }
191      } else if (IsType<DateTime>(columnIndex)) {
192        DateTime date;
193        valid = DateTime.TryParse(value, out date);
194        if (!valid) {
195          errorMessage = "Invalid Value (Valid Value Format: \"" + CultureInfo.CurrentCulture.DateTimeFormat + "\"";
196        }
197      } else {
198        throw new ArgumentException("column " + columnIndex + " contains a non supported type.");
199      }
200
201      return valid;
202    }
203
204    private void SetValueIfValid<T>(int columnIndex, int rowIndex, bool valid, T value) {
205      if (valid)
206        SetCell<T>(columnIndex, rowIndex, value);
207    }
208
209    public override bool AreAllStringColumns(IEnumerable<int> columnIndices) {
210      return columnIndices.All(x => IsType<string>(x));
211    }
212
213    public override void DeleteRowsWithIndices(IEnumerable<int> rows) {
214      SaveSnapshot(DataPreprocessingChangedEventType.AddRow, -1, -1);
215      foreach (int rowIndex in rows.OrderByDescending(x => x)) {
216        foreach (IList column in variableValues) {
217          column.RemoveAt(rowIndex);
218        }
219      }
220      if (!IsInTransaction)
221        OnChanged(DataPreprocessingChangedEventType.DeleteRow, -1, -1);
222    }
223
224    public override void InsertRow(int rowIndex) {
225      SaveSnapshot(DataPreprocessingChangedEventType.DeleteRow, -1, rowIndex);
226      foreach (IList column in variableValues) {
227        Type type = column.GetType().GetGenericArguments()[0];
228        column.Insert(rowIndex, type.IsValueType ? Activator.CreateInstance(type) : null);
229      }
230      if (!IsInTransaction)
231        OnChanged(DataPreprocessingChangedEventType.AddRow, -1, rowIndex);
232    }
233
234    public override void DeleteRow(int rowIndex) {
235      SaveSnapshot(DataPreprocessingChangedEventType.AddRow, -1, rowIndex);
236      foreach (IList column in variableValues) {
237        column.RemoveAt(rowIndex);
238      }
239      if (!IsInTransaction)
240        OnChanged(DataPreprocessingChangedEventType.DeleteRow, -1, rowIndex);
241    }
242
243    public override void InsertColumn<T>(string variableName, int columnIndex) {
244      SaveSnapshot(DataPreprocessingChangedEventType.DeleteColumn, columnIndex, -1);
245      variableValues.Insert(columnIndex, new List<T>(Rows));
246      variableNames.Insert(columnIndex, variableName);
247      if (!IsInTransaction)
248        OnChanged(DataPreprocessingChangedEventType.AddColumn, columnIndex, -1);
249    }
250
251    public override void DeleteColumn(int columnIndex) {
252      SaveSnapshot(DataPreprocessingChangedEventType.AddColumn, columnIndex, -1);
253      variableValues.RemoveAt(columnIndex);
254      variableNames.RemoveAt(columnIndex);
255      if (!IsInTransaction)
256        OnChanged(DataPreprocessingChangedEventType.DeleteColumn, columnIndex, -1);
257    }
258
259    public override Dataset ExportToDataset() {
260      IList<IList> values = new List<IList>();
261
262      for (int i = 0; i < Columns; ++i) {
263        values.Add(variableValues[i]);
264      }
265
266      var dataset = new Dataset(variableNames, values);
267      return dataset;
268    }
269
270    public override void ClearSelection() {
271      Selection = new Dictionary<int, IList<int>>();
272    }
273
274    public override event EventHandler SelectionChanged;
275
276    protected override void OnSelectionChanged() {
277      var listeners = SelectionChanged;
278      if (listeners != null) listeners(this, EventArgs.Empty);
279    }
280
281
282    #endregion
283
284    #region TransactionalPreprocessingData members
285
286    public bool IsUndoAvailable {
287      get { return undoHistory.Count > 0; }
288    }
289
290    public void Undo() {
291      if (IsUndoAvailable) {
292        Snapshot previousSnapshot = undoHistory[undoHistory.Count - 1];
293        variableValues = previousSnapshot.VariableValues;
294        variableNames = previousSnapshot.VariableNames;
295        TrainingPartition = previousSnapshot.TrainingPartition;
296        TestPartition = previousSnapshot.TestPartition;
297        transformations = previousSnapshot.Transformations;
298        undoHistory.Remove(previousSnapshot);
299        OnChanged(previousSnapshot.ChangedType,
300          previousSnapshot.ChangedColumn,
301          previousSnapshot.ChangedRow);
302      }
303    }
304
305    public void InTransaction(Action action, DataPreprocessingChangedEventType type = DataPreprocessingChangedEventType.Any) {
306      BeginTransaction(type);
307      action();
308      EndTransaction();
309    }
310
311    public void BeginTransaction(DataPreprocessingChangedEventType type) {
312      SaveSnapshot(type, -1, -1);
313      eventStack.Push(type);
314    }
315
316    public void EndTransaction() {
317      if (eventStack.Count == 0)
318        throw new InvalidOperationException("There is no open transaction that can be ended.");
319
320      var @event = eventStack.Pop();
321      OnChanged(@event, -1, -1);
322    }
323
324    #endregion
325  }
326}
Note: See TracBrowser for help on using the repository browser.