Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3040_VectorBasedGP/HeuristicLab.Problems.DataAnalysis/3.4/Dataset.cs @ 17365

Last change on this file since 17365 was 17365, checked in by pfleck, 4 years ago

#3040 Added explicit vector types to avoid type-missmatches when representing vectors as IList<T>, List<T> or IReadOnlyList<T>.

File size: 21.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Collections.ObjectModel;
26using System.Linq;
27using HEAL.Attic;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31
32namespace HeuristicLab.Problems.DataAnalysis {
33  [Item("Dataset", "Represents a dataset containing data that should be analyzed.")]
34  [StorableType("49F4D145-50D7-4497-8D8A-D190CD556CC8")]
35  public class Dataset : NamedItem, IDataset {
36    [StorableConstructor]
37    protected Dataset(StorableConstructorFlag _) : base(_) { }
38    protected Dataset(Dataset original, Cloner cloner)
39      : base(original, cloner) {
40      // no need to clone the variable values because these can't be modified
41      variableValues = new Dictionary<string, IList>(original.variableValues);
42      variableNames = new List<string>(original.variableNames);
43      rows = original.rows;
44    }
45
46    public override IDeepCloneable Clone(Cloner cloner) { return new Dataset(this, cloner); }
47
48    public Dataset()
49      : base() {
50      Name = "-";
51      VariableNames = Enumerable.Empty<string>();
52      variableValues = new Dictionary<string, IList>();
53      rows = 0;
54    }
55
56    /// <summary>
57    /// Creates a new dataset. The variableValues are not cloned.
58    /// </summary>
59    /// <param name="variableNames">The names of the variables in the dataset</param>
60    /// <param name="variableValues">The values for the variables (column-oriented storage). Values are not cloned!</param>
61    public Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues)
62      : this(variableNames, variableValues, cloneValues: true) {
63    }
64
65    protected Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues, bool cloneValues = false) {
66      Name = "-";
67
68      if (variableNames.Any()) {
69        this.variableNames = new List<string>(variableNames);
70      } else {
71        this.variableNames = Enumerable.Range(0, variableValues.Count()).Select(x => "Column " + x).ToList();
72      }
73      // check if the arguments are consistent (no duplicate variables, same number of rows, correct data types, ...)
74      CheckArguments(this.variableNames, variableValues);
75
76      rows = variableValues.First().Count;
77
78      if (cloneValues) {
79        this.variableValues = CloneValues(this.variableNames, variableValues);
80      } else {
81        this.variableValues = new Dictionary<string, IList>(this.variableNames.Count);
82        for (int i = 0; i < this.variableNames.Count; i++) {
83          var variableName = this.variableNames[i];
84          var values = variableValues.ElementAt(i);
85          this.variableValues.Add(variableName, values);
86        }
87      }
88    }
89
90    public Dataset(IEnumerable<string> variableNames, double[,] variableValues) {
91      Name = "-";
92      if (variableNames.Count() != variableValues.GetLength(1)) {
93        throw new ArgumentException("Number of variable names doesn't match the number of columns of variableValues");
94      }
95      if (variableNames.Distinct().Count() != variableNames.Count()) {
96        var duplicateVariableNames = variableNames.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
97        string message = "The dataset cannot contain duplicate variables names: " + Environment.NewLine;
98        foreach (var duplicateVariableName in duplicateVariableNames)
99          message += duplicateVariableName + Environment.NewLine;
100        throw new ArgumentException(message);
101      }
102
103      rows = variableValues.GetLength(0);
104      this.variableNames = new List<string>(variableNames);
105
106      this.variableValues = new Dictionary<string, IList>(variableValues.GetLength(1));
107      for (int col = 0; col < variableValues.GetLength(1); col++) {
108        string columName = this.variableNames[col];
109        var values = new List<double>(variableValues.GetLength(0));
110        for (int row = 0; row < variableValues.GetLength(0); row++) {
111          values.Add(variableValues[row, col]);
112        }
113        this.variableValues.Add(columName, values);
114      }
115    }
116
117    public static Dataset FromRowData(IEnumerable<string> variableNames, double[,] data) {
118      var colWise = new List<IList>(data.GetLength(1));
119      for (var col = 0; col < data.GetLength(1); col++) {
120        var column = new List<double>(data.GetLength(0));
121        for (var row = 0; row < data.GetLength(0); row++) {
122          column.Add(data[row, col]);
123        }
124        colWise.Add(column);
125      }
126      return new Dataset(variableNames, colWise);
127    }
128
129    public static Dataset FromRowData(IEnumerable<string> variableNames, IEnumerable<IList> data) {
130      var vnames = variableNames.ToList();
131      var transposed = new List<IList>();
132      var iter = data.GetEnumerator();
133      if (!iter.MoveNext()) throw new ArgumentException("Data does not contain any rows", nameof(data));
134      for (var i = 0; i < iter.Current.Count; i++) {
135        if (i >= vnames.Count) throw new ArgumentException("There are more variables in data, than variable names.", nameof(variableNames));
136        if (iter.Current[i] == null) throw new ArgumentException("Null values are not supported.", nameof(data));
137        if (!IsAllowedType(iter.Current[i].GetType())) throw new ArgumentException("Data contains types that are not allowed.", nameof(data));
138        if (iter.Current[i] is double d)
139          transposed.Add(new List<double>() { d });
140        else if (iter.Current[i] is DateTime dt)
141          transposed.Add(new List<DateTime>() { dt });
142        else if (iter.Current[i] is string s)
143          transposed.Add(new List<string>() { s });
144        else if (iter.Current[i] is DoubleVector dv)
145          transposed.Add(new List<DoubleVector>() { dv });
146        else if (iter.Current[i] is StringVector sv)
147          transposed.Add(new List<StringVector>() { sv });
148        else if (iter.Current[i] is DateTimeVector dtv)
149          transposed.Add(new List<DateTimeVector>() { dtv });
150        else throw new NotSupportedException(string.Format("Variable {0} has type {1}. This is not supported when converting from row-wise data.", vnames[i], iter.Current[i].GetType()));
151      }
152      if (transposed.Count < vnames.Count) throw new ArgumentException("There are less variables in data, than variable names.", nameof(variableNames));
153      while (iter.MoveNext()) {
154        for (var i = 0; i < iter.Current.Count; i++)
155          if (transposed[i].Add(iter.Current[i]) < 0)
156            throw new ArgumentException(string.Format("Variable {0} has invalid value ({1})", vnames[i], iter.Current[i]), nameof(data));
157      }
158      return new Dataset(vnames, transposed);
159    }
160
161    public ModifiableDataset ToModifiable() {
162      return new ModifiableDataset(variableNames, variableNames.Select(v => variableValues[v]), true);
163    }
164
165    /// <summary>
166    /// Shuffle a dataset's rows
167    /// </summary>
168    /// <param name="random">Random number generator used for shuffling.</param>
169    /// <returns>A shuffled copy of the current dataset.</returns>
170    public Dataset Shuffle(IRandom random) {
171      var values = variableNames.Select(x => variableValues[x]).ToList();
172      return new Dataset(variableNames, values.ShuffleLists(random));
173    }
174
175
176
177    #region Backwards compatible code, remove with 3.5
178    private double[,] storableData;
179    //name alias used to support backwards compatibility
180    [Storable(OldName = "data")]
181    private double[,] StorableData { set { storableData = value; } }
182
183    [StorableHook(HookType.AfterDeserialization)]
184    private void AfterDeserialization() {
185      if (variableValues == null) {
186        rows = storableData.GetLength(0);
187        variableValues = new Dictionary<string, IList>();
188        for (int col = 0; col < storableData.GetLength(1); col++) {
189          string columName = variableNames[col];
190          var values = new List<double>(rows);
191          for (int row = 0; row < rows; row++) {
192            values.Add(storableData[row, col]);
193          }
194          variableValues.Add(columName, values);
195        }
196        storableData = null;
197      }
198    }
199    #endregion
200
201    [Storable(Name = "VariableValues")]
202    protected Dictionary<string, IList> variableValues;
203
204    protected List<string> variableNames;
205    [Storable]
206    public IEnumerable<string> VariableNames {
207      get { return variableNames; }
208      protected set {
209        if (variableNames != null) throw new InvalidOperationException();
210        variableNames = new List<string>(value);
211      }
212    }
213
214    public bool ContainsVariable(string variableName) {
215      return variableValues.ContainsKey(variableName);
216    }
217    public IEnumerable<string> DoubleVariables {
218      get { return variableValues.Where(p => p.Value is IList<double>).Select(p => p.Key); }
219    }
220    public IEnumerable<string> StringVariables {
221      get { return variableValues.Where(p => p.Value is IList<string>).Select(p => p.Key); }
222    }
223    public IEnumerable<string> DateTimeVariables {
224      get { return variableValues.Where(p => p.Value is IList<DateTime>).Select(p => p.Key); }
225    }
226    public IEnumerable<string> DoubleVectorVariables {
227      get { return variableValues.Where(p => p.Value is IList<DoubleVector>).Select(p => p.Key); }
228    }
229    public IEnumerable<string> StringVectorVariables {
230      get { return variableValues.Where(p => p.Value is IList<StringVector>).Select(p => p.Key); }
231    }
232    public IEnumerable<string> DateTimeVectorVariables {
233      get { return variableValues.Where(p => p.Value is IList<DateTimeVector>).Select(p => p.Key); }
234    }
235
236    public IEnumerable<double> GetDoubleValues(string variableName) {
237      return GetValues<double>(variableName);
238    }
239    public IEnumerable<string> GetStringValues(string variableName) {
240      return GetValues<string>(variableName);
241    }
242    public IEnumerable<DateTime> GetDateTimeValues(string variableName) {
243      return GetValues<DateTime>(variableName);
244    }
245    public IEnumerable<DoubleVector> GetDoubleVectorValues(string variableName) {
246      return GetValues<DoubleVector>(variableName);
247    }
248    public IEnumerable<StringVector> GetStringVectorValues(string variableName) {
249      return GetValues<StringVector>(variableName);
250    }
251    public IEnumerable<DateTimeVector> GetDateTimeVectorValues(string variableName) {
252      return GetValues<DateTimeVector>(variableName);
253    }
254
255    public ReadOnlyCollection<double> GetReadOnlyDoubleValues(string variableName) {
256      var values = GetValues<double>(variableName);
257      return new ReadOnlyCollection<double>(values);
258    }
259    public double GetDoubleValue(string variableName, int row) {
260      var values = GetValues<double>(variableName);
261      return values[row];
262    }
263    public IEnumerable<double> GetDoubleValues(string variableName, IEnumerable<int> rows) {
264      return GetValues<double>(variableName, rows);
265    }
266
267    public string GetStringValue(string variableName, int row) {
268      var values = GetValues<string>(variableName);
269      return values[row];
270    }
271    public IEnumerable<string> GetStringValues(string variableName, IEnumerable<int> rows) {
272      return GetValues<string>(variableName, rows);
273    }
274    public ReadOnlyCollection<string> GetReadOnlyStringValues(string variableName) {
275      var values = GetValues<string>(variableName);
276      return new ReadOnlyCollection<string>(values);
277    }
278
279    public DateTime GetDateTimeValue(string variableName, int row) {
280      var values = GetValues<DateTime>(variableName);
281      return values[row];
282    }
283    public IEnumerable<DateTime> GetDateTimeValues(string variableName, IEnumerable<int> rows) {
284      return GetValues<DateTime>(variableName, rows);
285    }
286    public ReadOnlyCollection<DateTime> GetReadOnlyDateTimeValues(string variableName) {
287      var values = GetValues<DateTime>(variableName);
288      return new ReadOnlyCollection<DateTime>(values);
289    }
290
291    public DoubleVector GetDoubleVectorValue(string variableName, int row) {
292      var values = GetValues<DoubleVector>(variableName);
293      return values[row];
294    }
295    public IEnumerable<DoubleVector> GetDoubleVectorValues(string variableName, IEnumerable<int> rows) {
296      return GetValues<DoubleVector>(variableName, rows);
297    }
298    public ReadOnlyCollection<DoubleVector> GetReadOnlyDoubleVectorValues(string variableName) {
299      var values = GetValues<DoubleVector>(variableName);
300      return new ReadOnlyCollection<DoubleVector>(values);
301    }
302
303    public StringVector GetStringVectorValue(string variableName, int row) {
304      var values = GetValues<StringVector>(variableName);
305      return values[row];
306    }
307    public IEnumerable<StringVector> GetStringVectorValues(string variableName, IEnumerable<int> rows) {
308      return GetValues<StringVector>(variableName, rows);
309    }
310    public ReadOnlyCollection<StringVector> GetReadOnlyStringVectorValues(string variableName) {
311      var values = GetValues<StringVector>(variableName);
312      return new ReadOnlyCollection<StringVector>(values);
313    }
314
315    public DateTimeVector GetDateTimeVectorValue(string variableName, int row) {
316      var values = GetValues<DateTimeVector>(variableName);
317      return values[row];
318    }
319    public IEnumerable<DateTimeVector> GetDateTimeVectorValues(string variableName, IEnumerable<int> rows) {
320      return GetValues<DateTimeVector>(variableName, rows);
321    }
322    public ReadOnlyCollection<DateTimeVector> GetReadOnlyDateTimeVectorValues(string variableName) {
323      var values = GetValues<DateTimeVector>(variableName);
324      return new ReadOnlyCollection<DateTimeVector>(values);
325    }
326
327    private IEnumerable<T> GetValues<T>(string variableName, IEnumerable<int> rows) {
328      var values = GetValues<T>(variableName);
329      return rows.Select(x => values[x]);
330    }
331    private IList<T> GetValues<T>(string variableName) {
332      IList list;
333      if (!variableValues.TryGetValue(variableName, out list))
334        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
335      IList<T> values = list as IList<T>;
336      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a " + typeof(T) + " variable.");
337      return values;
338    }
339    public bool VariableHasType<T>(string variableName) {
340      return variableValues[variableName] is IList<T>;
341    }
342    protected Type GetVariableType(string variableName) {
343      IList list;
344      variableValues.TryGetValue(variableName, out list);
345      if (list == null)
346        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
347      return GetElementType(list);
348    }
349    protected static Type GetElementType(IList list) {
350      var type = list.GetType();
351      return type.IsGenericType ? type.GetGenericArguments()[0] : type.GetElementType();
352    }
353    protected static bool IsAllowedType(IList list) {
354      var type = GetElementType(list);
355      return IsAllowedType(type);
356    }
357    protected static bool IsAllowedType(Type type) {
358      return type == typeof(double) || type == typeof(string) || type == typeof(DateTime)
359             || type == typeof(DoubleVector) || type == typeof(StringVector) || type == typeof(DateTimeVector);
360    }
361
362    protected static void CheckArguments(IEnumerable<string> variableNames, IEnumerable<IList> variableValues) {
363      if (variableNames.Count() != variableValues.Count()) {
364        throw new ArgumentException("Number of variable names doesn't match the number of columns of variableValues");
365      } else if (!variableValues.All(list => list.Count == variableValues.First().Count)) {
366        throw new ArgumentException("The number of values must be equal for every variable");
367      } else if (variableNames.Distinct().Count() != variableNames.Count()) {
368        var duplicateVariableNames =
369          variableNames.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
370        string message = "The dataset cannot contain duplicate variables names: " + Environment.NewLine;
371        foreach (var duplicateVariableName in duplicateVariableNames)
372          message += duplicateVariableName + Environment.NewLine;
373        throw new ArgumentException(message);
374      }
375      // check if all the variables are supported
376      foreach (var t in variableNames.Zip(variableValues, Tuple.Create)) {
377        var variableName = t.Item1;
378        var values = t.Item2;
379
380        if (!IsAllowedType(values)) {
381          throw new ArgumentException(string.Format("Unsupported type {0} for variable {1}.", GetElementType(values), variableName));
382        }
383      }
384    }
385
386    protected static Dictionary<string, IList> CloneValues(Dictionary<string, IList> variableValues) {
387      return variableValues.ToDictionary(x => x.Key, x => CloneValues(x.Value));
388    }
389
390    protected static Dictionary<string, IList> CloneValues(IEnumerable<string> variableNames, IEnumerable<IList> variableValues) {
391      return variableNames.Zip(variableValues, Tuple.Create).ToDictionary(x => x.Item1, x => CloneValues(x.Item2));
392    }
393
394    protected static IList CloneValues(IList values) {
395      var doubleValues = values as IList<double>;
396      if (doubleValues != null) return new List<double>(doubleValues);
397
398      var stringValues = values as IList<string>;
399      if (stringValues != null) return new List<string>(stringValues);
400
401      var dateTimeValues = values as IList<DateTime>;
402      if (dateTimeValues != null) return new List<DateTime>(dateTimeValues);
403
404      var doubleVectorValues = values as IList<DoubleVector>;
405      if (doubleVectorValues != null) return doubleVectorValues.Select(x => new DoubleVector(x)).ToList();
406
407      var stringVectorValues = values as IList<StringVector>;
408      if (stringVectorValues != null) return stringVectorValues.Select(x => new StringVector(x)).ToList();
409
410      var dateTimeVectorValues = values as IList<DateTimeVector>;
411      if (dateTimeVectorValues != null) return dateTimeVectorValues.Select(x => new DateTimeVector(x)).ToList();
412
413      throw new ArgumentException(string.Format("Unsupported variable type {0}.", GetElementType(values)));
414    }
415
416    #region IStringConvertibleMatrix Members
417    [Storable]
418    private int rows;
419    public int Rows {
420      get { return rows; }
421      protected set { rows = value; }
422    }
423    int IStringConvertibleMatrix.Rows {
424      get { return Rows; }
425      set { throw new NotSupportedException(); }
426    }
427
428    public int Columns {
429      get { return variableNames.Count; }
430    }
431    int IStringConvertibleMatrix.Columns {
432      get { return Columns; }
433      set { throw new NotSupportedException(); }
434    }
435    bool IStringConvertibleMatrix.SortableView {
436      get { return false; }
437      set { throw new NotSupportedException(); }
438    }
439    bool IStringConvertibleMatrix.ReadOnly {
440      get { return true; }
441    }
442    IEnumerable<string> IStringConvertibleMatrix.ColumnNames {
443      get { return this.VariableNames; }
444      set { throw new NotSupportedException(); }
445    }
446    IEnumerable<string> IStringConvertibleMatrix.RowNames {
447      get { return Enumerable.Empty<string>(); }
448      set { throw new NotSupportedException(); }
449    }
450    string IStringConvertibleMatrix.GetValue(int rowIndex, int columnIndex) {
451      var value = variableValues[variableNames[columnIndex]][rowIndex];
452      if (value is IVector vector)
453        return $"[{string.Join(", ", vector.Cast<object>())}]";
454      return value.ToString();
455    }
456    bool IStringConvertibleMatrix.SetValue(string value, int rowIndex, int columnIndex) {
457      throw new NotSupportedException();
458    }
459    bool IStringConvertibleMatrix.Validate(string value, out string errorMessage) {
460      throw new NotSupportedException();
461    }
462
463    public virtual event EventHandler ColumnsChanged { add { } remove { } }
464    public virtual event EventHandler RowsChanged { add { } remove { } }
465    public virtual event EventHandler ColumnNamesChanged { add { } remove { } }
466    public virtual event EventHandler RowNamesChanged { add { } remove { } }
467    public virtual event EventHandler SortableViewChanged { add { } remove { } }
468    public virtual event EventHandler<EventArgs<int, int>> ItemChanged { add { } remove { } }
469    public virtual event EventHandler Reset { add { } remove { } }
470    #endregion
471  }
472}
Note: See TracBrowser for help on using the repository browser.