Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.DataPreprocessing/3.4/Logic/ManipulationLogic.cs @ 14886

Last change on this file since 14886 was 14886, checked in by mkommend, 8 years ago

#2778: Refactored and corrected shuffling in DataPreprocessing.

File size: 14.7 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.Linq;
25using HeuristicLab.Data;
26using HeuristicLab.Random;
27
28namespace HeuristicLab.DataPreprocessing {
29  public class ManipulationLogic {
30    private readonly ITransactionalPreprocessingData preprocessingData;
31    private readonly StatisticsLogic statisticsLogic;
32    private readonly SearchLogic searchLogic;
33
34    public IEnumerable<string> VariableNames {
35      get { return preprocessingData.VariableNames; }
36    }
37
38    public ITransactionalPreprocessingData PreProcessingData {
39      get { return preprocessingData; }
40    }
41
42    public ManipulationLogic(ITransactionalPreprocessingData _prepocessingData, SearchLogic theSearchLogic, StatisticsLogic theStatisticsLogic) {
43      preprocessingData = _prepocessingData;
44      searchLogic = theSearchLogic;
45      statisticsLogic = theStatisticsLogic;
46    }
47
48    public void ReplaceIndicesByValue<T>(int columnIndex, IEnumerable<int> rowIndices, T value) {
49      foreach (int index in rowIndices) {
50        preprocessingData.SetCell<T>(columnIndex, index, value);
51      }
52    }
53
54    public void ReplaceIndicesByAverageValue(IDictionary<int, IList<int>> cells, bool considerSelection = false) {
55      preprocessingData.InTransaction(() => {
56        foreach (var column in cells) {
57          if (preprocessingData.VariableHasType<double>(column.Key)) {
58            double average = statisticsLogic.GetAverage(column.Key, considerSelection);
59            ReplaceIndicesByValue<double>(column.Key, column.Value, average);
60          } else if (preprocessingData.VariableHasType<DateTime>(column.Key)) {
61            DateTime average = statisticsLogic.GetAverageDateTime(column.Key, considerSelection);
62            ReplaceIndicesByValue<DateTime>(column.Key, column.Value, average);
63          }
64        }
65      });
66    }
67
68    public void ReplaceIndicesByMedianValue(IDictionary<int, IList<int>> cells, bool considerSelection = false) {
69      preprocessingData.InTransaction(() => {
70        foreach (var column in cells) {
71          if (preprocessingData.VariableHasType<double>(column.Key)) {
72            double median = statisticsLogic.GetMedian(column.Key, considerSelection);
73            ReplaceIndicesByValue<double>(column.Key, column.Value, median);
74          } else if (preprocessingData.VariableHasType<DateTime>(column.Key)) {
75            DateTime median = statisticsLogic.GetMedianDateTime(column.Key, considerSelection);
76            ReplaceIndicesByValue<DateTime>(column.Key, column.Value, median);
77          }
78        }
79      });
80    }
81
82    public void ReplaceIndicesByRandomValue(IDictionary<int, IList<int>> cells, bool considerSelection = false) {
83      preprocessingData.InTransaction(() => {
84        System.Random r = new System.Random();
85
86        foreach (var column in cells) {
87          if (preprocessingData.VariableHasType<double>(column.Key)) {
88            double max = statisticsLogic.GetMax<double>(column.Key, double.NaN, considerSelection);
89            double min = statisticsLogic.GetMin<double>(column.Key, double.NaN, considerSelection);
90            double randMultiplier = (max - min);
91            foreach (int index in column.Value) {
92              double rand = r.NextDouble() * randMultiplier + min;
93              preprocessingData.SetCell<double>(column.Key, index, rand);
94            }
95          } else if (preprocessingData.VariableHasType<DateTime>(column.Key)) {
96            DateTime min = statisticsLogic.GetMin<DateTime>(column.Key, DateTime.MinValue, considerSelection);
97            DateTime max = statisticsLogic.GetMax<DateTime>(column.Key, DateTime.MinValue, considerSelection);
98            double randMultiplier = (max - min).TotalSeconds;
99            foreach (int index in column.Value) {
100              double rand = r.NextDouble() * randMultiplier;
101              preprocessingData.SetCell<DateTime>(column.Key, index, min.AddSeconds(rand));
102            }
103          }
104        }
105      });
106    }
107
108    public void ReplaceIndicesByLinearInterpolationOfNeighbours(IDictionary<int, IList<int>> cells) {
109      preprocessingData.InTransaction(() => {
110        foreach (var column in cells) {
111          int countValues = 0;
112          if (preprocessingData.VariableHasType<double>(column.Key)) {
113            countValues = preprocessingData.GetValues<double>(column.Key).Count();
114          } else if (preprocessingData.VariableHasType<DateTime>(column.Key)) {
115            countValues = preprocessingData.GetValues<DateTime>(column.Key).Count();
116          }
117
118          IList<Tuple<int, int>> startEndings = GetStartAndEndingsForInterpolation(column);
119          foreach (var tuple in startEndings) {
120            Interpolate(column, tuple.Item1, tuple.Item2);
121          }
122        }
123      });
124    }
125
126    private List<Tuple<int, int>> GetStartAndEndingsForInterpolation(KeyValuePair<int, IList<int>> column) {
127      List<Tuple<int, int>> startEndings = new List<Tuple<int, int>>();
128      var rowIndices = column.Value;
129      rowIndices = rowIndices.OrderBy(x => x).ToList();
130      var count = rowIndices.Count;
131      int start = int.MinValue;
132      for (int i = 0; i < count; ++i) {
133        if (start == int.MinValue) {
134          start = indexOfPrevPresentValue(column.Key, rowIndices[i]);
135        }
136        if (i + 1 == count || (i + 1 < count && rowIndices[i + 1] - rowIndices[i] > 1)) {
137          int next = indexOfNextPresentValue(column.Key, rowIndices[i]);
138          if (start > 0 && next < preprocessingData.Rows) {
139            startEndings.Add(new Tuple<int, int>(start, next));
140          }
141          start = int.MinValue;
142        }
143      }
144      return startEndings;
145    }
146
147    public void ReplaceIndicesBySmoothing(IDictionary<int, IList<int>> cells) {
148      preprocessingData.InTransaction(() => {
149        foreach (var column in cells) {
150          int countValues = preprocessingData.Rows;
151
152          foreach (int index in column.Value) {
153            // dont replace first or last values
154            if (index > 0 && index < countValues) {
155              int prevIndex = indexOfPrevPresentValue(column.Key, index);
156              int nextIndex = indexOfNextPresentValue(column.Key, index);
157
158              // no neighbours found
159              if (prevIndex < 0 || nextIndex >= countValues) {
160                continue;
161              }
162
163              Interpolate(column, prevIndex, nextIndex);
164            }
165          }
166        }
167      });
168    }
169
170    private void Interpolate(KeyValuePair<int, IList<int>> column, int prevIndex, int nextIndex) {
171      int valuesToInterpolate = nextIndex - prevIndex;
172
173      if (preprocessingData.VariableHasType<double>(column.Key)) {
174        double prev = preprocessingData.GetCell<double>(column.Key, prevIndex);
175        double next = preprocessingData.GetCell<double>(column.Key, nextIndex);
176        double interpolationStep = (next - prev) / valuesToInterpolate;
177
178        for (int i = prevIndex; i < nextIndex; ++i) {
179          double interpolated = prev + (interpolationStep * (i - prevIndex));
180          preprocessingData.SetCell<double>(column.Key, i, interpolated);
181        }
182      } else if (preprocessingData.VariableHasType<DateTime>(column.Key)) {
183        DateTime prev = preprocessingData.GetCell<DateTime>(column.Key, prevIndex);
184        DateTime next = preprocessingData.GetCell<DateTime>(column.Key, nextIndex);
185        double interpolationStep = (next - prev).TotalSeconds / valuesToInterpolate;
186
187        for (int i = prevIndex; i < nextIndex; ++i) {
188          DateTime interpolated = prev.AddSeconds(interpolationStep * (i - prevIndex));
189          preprocessingData.SetCell<DateTime>(column.Key, i, interpolated);
190        }
191      }
192    }
193
194    private int indexOfPrevPresentValue(int columnIndex, int start) {
195      int offset = start - 1;
196      while (offset >= 0 && searchLogic.IsMissingValue(columnIndex, offset)) {
197        offset--;
198      }
199
200      return offset;
201    }
202
203    private int indexOfNextPresentValue(int columnIndex, int start) {
204      int offset = start + 1;
205      while (offset < preprocessingData.Rows && searchLogic.IsMissingValue(columnIndex, offset)) {
206        offset++;
207      }
208
209      return offset;
210    }
211
212    public void ReplaceIndicesByMostCommonValue(IDictionary<int, IList<int>> cells, bool considerSelection = false) {
213      preprocessingData.InTransaction(() => {
214        foreach (var column in cells) {
215          if (preprocessingData.VariableHasType<double>(column.Key)) {
216            ReplaceIndicesByValue<double>(column.Key, column.Value, statisticsLogic.GetMostCommonValue<double>(column.Key, double.NaN, considerSelection));
217          } else if (preprocessingData.VariableHasType<string>(column.Key)) {
218            ReplaceIndicesByValue<string>(column.Key, column.Value, statisticsLogic.GetMostCommonValue<string>(column.Key, string.Empty, considerSelection));
219          } else if (preprocessingData.VariableHasType<DateTime>(column.Key)) {
220            ReplaceIndicesByValue<DateTime>(column.Key, column.Value, statisticsLogic.GetMostCommonValue<DateTime>(column.Key, DateTime.MinValue, considerSelection));
221          } else {
222            throw new ArgumentException("column with index: " + column.Key + " contains a non supported type.");
223          }
224        }
225      });
226    }
227
228    public void Shuffle(bool shuffleRangesSeparately) {
229      var random = new FastRandom();
230
231      if (shuffleRangesSeparately) {
232        var ranges = new[] { preprocessingData.TestPartition, preprocessingData.TrainingPartition };
233        preprocessingData.InTransaction(() => {
234          // process all given ranges - e.g. TrainingPartition, TestPartition
235          foreach (IntRange range in ranges) {
236            var indices = Enumerable.Range(0, preprocessingData.Rows).ToArray();
237            var shuffledIndices = Enumerable.Range(range.Start, range.Size).Shuffle(random).ToArray();
238            for (int i = range.Start, j = 0; i < range.End; i++, j++)
239              indices[i] = shuffledIndices[j];
240
241            ReOrderToIndices(indices);
242          }
243        });
244
245      } else {
246        preprocessingData.InTransaction(() => {
247          var indices = Enumerable.Range(0, preprocessingData.Rows);
248          var shuffledIndices = indices.Shuffle(random).ToArray();
249          ReOrderToIndices(shuffledIndices);
250        });
251      }
252    }
253
254    public void ReOrderToIndices(int[] indices) {
255      preprocessingData.InTransaction(() => {
256        for (int i = 0; i < preprocessingData.Columns; ++i) {
257          if (preprocessingData.VariableHasType<double>(i)) {
258            ReOrderToIndices<double>(i, indices);
259          } else if (preprocessingData.VariableHasType<string>(i)) {
260            ReOrderToIndices<string>(i, indices);
261          } else if (preprocessingData.VariableHasType<DateTime>(i)) {
262            ReOrderToIndices<DateTime>(i, indices);
263          }
264        }
265      });
266    }
267
268    private void ReOrderToIndices<T>(int columnIndex, int[] indices) {
269      List<T> originalData = new List<T>(preprocessingData.GetValues<T>(columnIndex));
270      if (indices.Length != originalData.Count) throw new InvalidOperationException("The number of provided indices does not match the values.");
271
272      for (int i = 0; i < indices.Length; i++) {
273        int originalIndex = i;
274        int replaceIndex = indices[i];
275
276        T replaceValue = originalData.ElementAt<T>(replaceIndex);
277        preprocessingData.SetCell<T>(columnIndex, originalIndex, replaceValue);
278      }
279    }
280
281    public void ReplaceIndicesByValue(IDictionary<int, IList<int>> cells, string value) {
282      preprocessingData.InTransaction(() => {
283        foreach (var column in cells) {
284          foreach (var rowIdx in column.Value) {
285            preprocessingData.SetValue(value, column.Key, rowIdx);
286          }
287        }
288      });
289    }
290
291
292    public List<int> RowsWithMissingValuesGreater(double percent) {
293
294      List<int> rows = new List<int>();
295
296      for (int i = 0; i < preprocessingData.Rows; ++i) {
297        int missingCount = statisticsLogic.GetRowMissingValueCount(i);
298        if (100f / preprocessingData.Columns * missingCount > percent) {
299          rows.Add(i);
300        }
301      }
302
303      return rows;
304    }
305
306    public List<int> ColumnsWithMissingValuesGreater(double percent) {
307
308      List<int> columns = new List<int>();
309      for (int i = 0; i < preprocessingData.Columns; ++i) {
310        int missingCount = statisticsLogic.GetMissingValueCount(i);
311        if (100f / preprocessingData.Rows * missingCount > percent) {
312          columns.Add(i);
313        }
314      }
315
316      return columns;
317    }
318
319    public List<int> ColumnsWithVarianceSmaller(double variance) {
320
321      List<int> columns = new List<int>();
322      for (int i = 0; i < preprocessingData.Columns; ++i) {
323        if (preprocessingData.VariableHasType<double>(i) || preprocessingData.VariableHasType<DateTime>(i)) {
324          double columnVariance = statisticsLogic.GetVariance(i);
325          if (columnVariance < variance) {
326            columns.Add(i);
327          }
328        }
329      }
330      return columns;
331    }
332
333    public void DeleteRowsWithMissingValuesGreater(double percent) {
334      DeleteRows(RowsWithMissingValuesGreater(percent));
335    }
336
337    public void DeleteColumnsWithMissingValuesGreater(double percent) {
338      DeleteColumns(ColumnsWithMissingValuesGreater(percent));
339    }
340
341    public void DeleteColumnsWithVarianceSmaller(double variance) {
342      DeleteColumns(ColumnsWithVarianceSmaller(variance));
343    }
344
345    private void DeleteRows(List<int> rows) {
346      rows.Sort();
347      rows.Reverse();
348      preprocessingData.InTransaction(() => {
349        foreach (int row in rows) {
350          preprocessingData.DeleteRow(row);
351        }
352      });
353    }
354
355    private void DeleteColumns(List<int> columns) {
356      columns.Sort();
357      columns.Reverse();
358      preprocessingData.InTransaction(() => {
359        foreach (int column in columns) {
360          preprocessingData.DeleteColumn(column);
361        }
362      });
363    }
364
365  }
366}
Note: See TracBrowser for help on using the repository browser.