Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.DataPreprocessing/3.4/Data/TransactionalPreprocessingData.cs @ 15428

Last change on this file since 15428 was 15110, checked in by pfleck, 7 years ago

#2709: merged branch to trunk

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