Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2389-EpsLexicase/HeuristicLab.Problems.DataAnalysis/3.4/Dataset.cs @ 18007

Last change on this file since 18007 was 15829, checked in by bburlacu, 7 years ago

#2897: Ensure cloning only happens in the Dataset constructor and ModifiableDataset cloning constructor.

File size: 15.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2018 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 HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31
32namespace HeuristicLab.Problems.DataAnalysis {
33  [Item("Dataset", "Represents a dataset containing data that should be analyzed.")]
34  [StorableClass]
35  public class Dataset : NamedItem, IDataset {
36    [StorableConstructor]
37    protected Dataset(bool deserializing) : base(deserializing) { }
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 ModifiableDataset ToModifiable() {
118      var values = new List<IList>();
119      foreach (var v in variableNames) {
120        if (VariableHasType<double>(v)) {
121          values.Add(new List<double>((IList<double>)variableValues[v]));
122        } else if (VariableHasType<string>(v)) {
123          values.Add(new List<string>((IList<string>)variableValues[v]));
124        } else if (VariableHasType<DateTime>(v)) {
125          values.Add(new List<DateTime>((IList<DateTime>)variableValues[v]));
126        } else {
127          throw new ArgumentException("Unknown variable type.");
128        }
129      }
130      return new ModifiableDataset(variableNames, values);
131    }
132
133    /// <summary>
134    /// Shuffle a dataset's rows
135    /// </summary>
136    /// <param name="random">Random number generator used for shuffling.</param>
137    /// <returns>A shuffled copy of the current dataset.</returns>
138    public Dataset Shuffle(IRandom random) {
139      var values = variableNames.Select(x => variableValues[x]).ToList();
140      return new Dataset(variableNames, values.ShuffleLists(random));
141    }
142
143    protected Dataset(Dataset dataset) : this(dataset.variableNames, dataset.variableValues.Values) { }
144
145    #region Backwards compatible code, remove with 3.5
146    private double[,] storableData;
147    //name alias used to suppport backwards compatibility
148    [Storable(Name = "data", AllowOneWay = true)]
149    private double[,] StorableData { set { storableData = value; } }
150
151    [StorableHook(HookType.AfterDeserialization)]
152    private void AfterDeserialization() {
153      if (variableValues == null) {
154        rows = storableData.GetLength(0);
155        variableValues = new Dictionary<string, IList>();
156        for (int col = 0; col < storableData.GetLength(1); col++) {
157          string columName = variableNames[col];
158          var values = new List<double>(rows);
159          for (int row = 0; row < rows; row++) {
160            values.Add(storableData[row, col]);
161          }
162          variableValues.Add(columName, values);
163        }
164        storableData = null;
165      }
166    }
167    #endregion
168
169    [Storable(Name = "VariableValues")]
170    protected Dictionary<string, IList> variableValues;
171
172    protected List<string> variableNames;
173    [Storable]
174    public IEnumerable<string> VariableNames {
175      get { return variableNames; }
176      protected set {
177        if (variableNames != null) throw new InvalidOperationException();
178        variableNames = new List<string>(value);
179      }
180    }
181    public IEnumerable<string> DoubleVariables {
182      get { return variableValues.Where(p => p.Value is IList<double>).Select(p => p.Key); }
183    }
184
185    public IEnumerable<string> StringVariables {
186      get { return variableValues.Where(p => p.Value is IList<string>).Select(p => p.Key); }
187    }
188
189    public IEnumerable<string> DateTimeVariables {
190      get { return variableValues.Where(p => p.Value is IList<DateTime>).Select(p => p.Key); }
191    }
192
193    public IEnumerable<double> GetDoubleValues(string variableName) {
194      return GetValues<double>(variableName);
195    }
196    public IEnumerable<string> GetStringValues(string variableName) {
197      return GetValues<string>(variableName);
198    }
199    public IEnumerable<DateTime> GetDateTimeValues(string variableName) {
200      return GetValues<DateTime>(variableName);
201    }
202
203    public ReadOnlyCollection<double> GetReadOnlyDoubleValues(string variableName) {
204      var values = GetValues<double>(variableName);
205      return new ReadOnlyCollection<double>(values);
206    }
207    public double GetDoubleValue(string variableName, int row) {
208      var values = GetValues<double>(variableName);
209      return values[row];
210    }
211    public IEnumerable<double> GetDoubleValues(string variableName, IEnumerable<int> rows) {
212      return GetValues<double>(variableName, rows);
213    }
214
215    public string GetStringValue(string variableName, int row) {
216      var values = GetValues<string>(variableName);
217      return values[row];
218    }
219
220    public IEnumerable<string> GetStringValues(string variableName, IEnumerable<int> rows) {
221      return GetValues<string>(variableName, rows);
222    }
223    public ReadOnlyCollection<string> GetReadOnlyStringValues(string variableName) {
224      var values = GetValues<string>(variableName);
225      return new ReadOnlyCollection<string>(values);
226    }
227
228    public DateTime GetDateTimeValue(string variableName, int row) {
229      var values = GetValues<DateTime>(variableName);
230      return values[row];
231    }
232    public IEnumerable<DateTime> GetDateTimeValues(string variableName, IEnumerable<int> rows) {
233      return GetValues<DateTime>(variableName, rows);
234    }
235    public ReadOnlyCollection<DateTime> GetReadOnlyDateTimeValues(string variableName) {
236      var values = GetValues<DateTime>(variableName);
237      return new ReadOnlyCollection<DateTime>(values);
238    }
239    private IEnumerable<T> GetValues<T>(string variableName, IEnumerable<int> rows) {
240      var values = GetValues<T>(variableName);
241      return rows.Select(x => values[x]);
242    }
243    private IList<T> GetValues<T>(string variableName) {
244      IList list;
245      if (!variableValues.TryGetValue(variableName, out list))
246        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
247      IList<T> values = list as IList<T>;
248      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a " + typeof(T) + " variable.");
249      return values;
250    }
251    public bool VariableHasType<T>(string variableName) {
252      return variableValues[variableName] is IList<T>;
253    }
254    protected Type GetVariableType(string variableName) {
255      IList list;
256      variableValues.TryGetValue(variableName, out list);
257      if (list == null)
258        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
259      return GetElementType(list);
260    }
261    protected static Type GetElementType(IList list) {
262      var type = list.GetType();
263      return type.IsGenericType ? type.GetGenericArguments()[0] : type.GetElementType();
264    }
265    protected static bool IsAllowedType(IList list) {
266      var type = GetElementType(list);
267      return IsAllowedType(type);
268    }
269    protected static bool IsAllowedType(Type type) {
270      return type == typeof(double) || type == typeof(string) || type == typeof(DateTime);
271    }
272
273    protected static void CheckArguments(IEnumerable<string> variableNames, IEnumerable<IList> variableValues) {
274      if (variableNames.Count() != variableValues.Count()) {
275        throw new ArgumentException("Number of variable names doesn't match the number of columns of variableValues");
276      } else if (!variableValues.All(list => list.Count == variableValues.First().Count)) {
277        throw new ArgumentException("The number of values must be equal for every variable");
278      } else if (variableNames.Distinct().Count() != variableNames.Count()) {
279        var duplicateVariableNames =
280          variableNames.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
281        string message = "The dataset cannot contain duplicate variables names: " + Environment.NewLine;
282        foreach (var duplicateVariableName in duplicateVariableNames)
283          message += duplicateVariableName + Environment.NewLine;
284        throw new ArgumentException(message);
285      }
286      // check if all the variables are supported
287      foreach (var t in variableNames.Zip(variableValues, Tuple.Create)) {
288        var variableName = t.Item1;
289        var values = t.Item2;
290
291        if (!IsAllowedType(values)) {
292          throw new ArgumentException(string.Format("Unsupported type {0} for variable {1}.", GetElementType(values), variableName));
293        }
294      }
295    }
296
297    protected static Dictionary<string, IList> CloneValues(Dictionary<string, IList> variableValues) {
298      return variableValues.ToDictionary(x => x.Key, x => CloneValues(x.Value));
299    }
300
301    protected static Dictionary<string, IList> CloneValues(IEnumerable<string> variableNames, IEnumerable<IList> variableValues) {
302      return variableNames.Zip(variableValues, Tuple.Create).ToDictionary(x => x.Item1, x => CloneValues(x.Item2));
303    }
304
305    protected static IList CloneValues(IList values) {
306      var doubleValues = values as IList<double>;
307      if (doubleValues != null) return new List<double>(doubleValues);
308
309      var stringValues = values as IList<string>;
310      if (stringValues != null) return new List<string>(stringValues);
311
312      var dateTimeValues = values as IList<DateTime>;
313      if (dateTimeValues != null) return new List<DateTime>(dateTimeValues);
314
315      throw new ArgumentException(string.Format("Unsupported variable type {0}.", GetElementType(values)));
316    }
317
318    #region IStringConvertibleMatrix Members
319    [Storable]
320    protected int rows;
321    public int Rows {
322      get { return rows; }
323    }
324    int IStringConvertibleMatrix.Rows {
325      get { return Rows; }
326      set { throw new NotSupportedException(); }
327    }
328
329    public int Columns {
330      get { return variableNames.Count; }
331    }
332    int IStringConvertibleMatrix.Columns {
333      get { return Columns; }
334      set { throw new NotSupportedException(); }
335    }
336    bool IStringConvertibleMatrix.SortableView {
337      get { return false; }
338      set { throw new NotSupportedException(); }
339    }
340    bool IStringConvertibleMatrix.ReadOnly {
341      get { return true; }
342    }
343    IEnumerable<string> IStringConvertibleMatrix.ColumnNames {
344      get { return this.VariableNames; }
345      set { throw new NotSupportedException(); }
346    }
347    IEnumerable<string> IStringConvertibleMatrix.RowNames {
348      get { return Enumerable.Empty<string>(); }
349      set { throw new NotSupportedException(); }
350    }
351    string IStringConvertibleMatrix.GetValue(int rowIndex, int columnIndex) {
352      return variableValues[variableNames[columnIndex]][rowIndex].ToString();
353    }
354    bool IStringConvertibleMatrix.SetValue(string value, int rowIndex, int columnIndex) {
355      throw new NotSupportedException();
356    }
357    bool IStringConvertibleMatrix.Validate(string value, out string errorMessage) {
358      throw new NotSupportedException();
359    }
360
361    public virtual event EventHandler ColumnsChanged { add { } remove { } }
362    public virtual event EventHandler RowsChanged { add { } remove { } }
363    public virtual event EventHandler ColumnNamesChanged { add { } remove { } }
364    public virtual event EventHandler RowNamesChanged { add { } remove { } }
365    public virtual event EventHandler SortableViewChanged { add { } remove { } }
366    public virtual event EventHandler<EventArgs<int, int>> ItemChanged { add { } remove { } }
367    public virtual event EventHandler Reset { add { } remove { } }
368    #endregion
369  }
370}
Note: See TracBrowser for help on using the repository browser.