Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.DataPreprocessing/3.4/Implementations/TransactionalPreprocessingData.cs @ 12217

Last change on this file since 12217 was 12009, checked in by ascheibe, 10 years ago

#2212 updated copyright year

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