Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.DataPreprocessing/3.4/Implementations/ManipulationLogic.cs @ 11170

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

#2115 updated copyright year in stable branch

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