Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2971_named_intervals/HeuristicLab.Problems.DataAnalysis/3.4/Dataset.cs @ 16640

Last change on this file since 16640 was 16640, checked in by gkronber, 5 years ago

#2971: merged r16565:16631 from trunk/HeuristicLab.Problems.DataAnalysis to branch/HeuristicLab.Problems.DataAnalysis (resolving all conflicts)

File size: 15.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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 HEAL.Attic;
31using HEAL.Attic;
32
33namespace HeuristicLab.Problems.DataAnalysis {
34  [Item("Dataset", "Represents a dataset containing data that should be analyzed.")]
35  [StorableType("49F4D145-50D7-4497-8D8A-D190CD556CC8")]
36  public class Dataset : NamedItem, IDataset {
37    [StorableConstructor]
38    protected Dataset(StorableConstructorFlag _) : base(_) { }
39    protected Dataset(Dataset original, Cloner cloner)
40      : base(original, cloner) {
41      // no need to clone the variable values because these can't be modified
42      variableValues = new Dictionary<string, IList>(original.variableValues);
43      variableNames = new List<string>(original.variableNames);
44      rows = original.rows;
45    }
46
47    public override IDeepCloneable Clone(Cloner cloner) { return new Dataset(this, cloner); }
48
49    public Dataset()
50      : base() {
51      Name = "-";
52      VariableNames = Enumerable.Empty<string>();
53      variableValues = new Dictionary<string, IList>();
54      rows = 0;
55    }
56
57    /// <summary>
58    /// Creates a new dataset. The variableValues are not cloned.
59    /// </summary>
60    /// <param name="variableNames">The names of the variables in the dataset</param>
61    /// <param name="variableValues">The values for the variables (column-oriented storage). Values are not cloned!</param>
62    public Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues)
63      : this(variableNames, variableValues, cloneValues: true) {
64    }
65
66    protected Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues, bool cloneValues = false) {
67      Name = "-";
68
69      if (variableNames.Any()) {
70        this.variableNames = new List<string>(variableNames);
71      } else {
72        this.variableNames = Enumerable.Range(0, variableValues.Count()).Select(x => "Column " + x).ToList();
73      }
74      // check if the arguments are consistent (no duplicate variables, same number of rows, correct data types, ...)
75      CheckArguments(this.variableNames, variableValues);
76
77      rows = variableValues.First().Count;
78
79      if (cloneValues) {
80        this.variableValues = CloneValues(this.variableNames, variableValues);
81      } else {
82        this.variableValues = new Dictionary<string, IList>(this.variableNames.Count);
83        for (int i = 0; i < this.variableNames.Count; i++) {
84          var variableName = this.variableNames[i];
85          var values = variableValues.ElementAt(i);
86          this.variableValues.Add(variableName, values);
87        }
88      }
89    }
90
91    public Dataset(IEnumerable<string> variableNames, double[,] variableValues) {
92      Name = "-";
93      if (variableNames.Count() != variableValues.GetLength(1)) {
94        throw new ArgumentException("Number of variable names doesn't match the number of columns of variableValues");
95      }
96      if (variableNames.Distinct().Count() != variableNames.Count()) {
97        var duplicateVariableNames = variableNames.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
98        string message = "The dataset cannot contain duplicate variables names: " + Environment.NewLine;
99        foreach (var duplicateVariableName in duplicateVariableNames)
100          message += duplicateVariableName + Environment.NewLine;
101        throw new ArgumentException(message);
102      }
103
104      rows = variableValues.GetLength(0);
105      this.variableNames = new List<string>(variableNames);
106
107      this.variableValues = new Dictionary<string, IList>(variableValues.GetLength(1));
108      for (int col = 0; col < variableValues.GetLength(1); col++) {
109        string columName = this.variableNames[col];
110        var values = new List<double>(variableValues.GetLength(0));
111        for (int row = 0; row < variableValues.GetLength(0); row++) {
112          values.Add(variableValues[row, col]);
113        }
114        this.variableValues.Add(columName, values);
115      }
116    }
117
118    public ModifiableDataset ToModifiable() {
119      return new ModifiableDataset(variableNames, variableNames.Select(v => variableValues[v]), true);
120    }
121
122    /// <summary>
123    /// Shuffle a dataset's rows
124    /// </summary>
125    /// <param name="random">Random number generator used for shuffling.</param>
126    /// <returns>A shuffled copy of the current dataset.</returns>
127    public Dataset Shuffle(IRandom random) {
128      var values = variableNames.Select(x => variableValues[x]).ToList();
129      return new Dataset(variableNames, values.ShuffleLists(random));
130    }
131
132
133
134    #region Backwards compatible code, remove with 3.5
135    private double[,] storableData;
136    //name alias used to suppport backwards compatibility
137    [Storable(Name = "data", AllowOneWay = true)]
138    private double[,] StorableData { set { storableData = value; } }
139
140    [StorableHook(HookType.AfterDeserialization)]
141    private void AfterDeserialization() {
142      if (variableValues == null) {
143        rows = storableData.GetLength(0);
144        variableValues = new Dictionary<string, IList>();
145        for (int col = 0; col < storableData.GetLength(1); col++) {
146          string columName = variableNames[col];
147          var values = new List<double>(rows);
148          for (int row = 0; row < rows; row++) {
149            values.Add(storableData[row, col]);
150          }
151          variableValues.Add(columName, values);
152        }
153        storableData = null;
154      }
155    }
156    #endregion
157
158    [Storable(Name = "VariableValues")]
159    protected Dictionary<string, IList> variableValues;
160
161    protected List<string> variableNames;
162    [Storable]
163    public IEnumerable<string> VariableNames {
164      get { return variableNames; }
165      protected set {
166        if (variableNames != null) throw new InvalidOperationException();
167        variableNames = new List<string>(value);
168      }
169    }
170
171    public bool ContainsVariable(string variableName) {
172      return variableValues.ContainsKey(variableName);
173    }
174    public IEnumerable<string> DoubleVariables {
175      get { return variableValues.Where(p => p.Value is IList<double>).Select(p => p.Key); }
176    }
177
178    public IEnumerable<string> StringVariables {
179      get { return variableValues.Where(p => p.Value is IList<string>).Select(p => p.Key); }
180    }
181
182    public IEnumerable<string> DateTimeVariables {
183      get { return variableValues.Where(p => p.Value is IList<DateTime>).Select(p => p.Key); }
184    }
185
186    public IEnumerable<double> GetDoubleValues(string variableName) {
187      return GetValues<double>(variableName);
188    }
189    public IEnumerable<string> GetStringValues(string variableName) {
190      return GetValues<string>(variableName);
191    }
192    public IEnumerable<DateTime> GetDateTimeValues(string variableName) {
193      return GetValues<DateTime>(variableName);
194    }
195
196    public ReadOnlyCollection<double> GetReadOnlyDoubleValues(string variableName) {
197      var values = GetValues<double>(variableName);
198      return new ReadOnlyCollection<double>(values);
199    }
200    public double GetDoubleValue(string variableName, int row) {
201      var values = GetValues<double>(variableName);
202      return values[row];
203    }
204    public IEnumerable<double> GetDoubleValues(string variableName, IEnumerable<int> rows) {
205      return GetValues<double>(variableName, rows);
206    }
207
208    public string GetStringValue(string variableName, int row) {
209      var values = GetValues<string>(variableName);
210      return values[row];
211    }
212
213    public IEnumerable<string> GetStringValues(string variableName, IEnumerable<int> rows) {
214      return GetValues<string>(variableName, rows);
215    }
216    public ReadOnlyCollection<string> GetReadOnlyStringValues(string variableName) {
217      var values = GetValues<string>(variableName);
218      return new ReadOnlyCollection<string>(values);
219    }
220
221    public DateTime GetDateTimeValue(string variableName, int row) {
222      var values = GetValues<DateTime>(variableName);
223      return values[row];
224    }
225    public IEnumerable<DateTime> GetDateTimeValues(string variableName, IEnumerable<int> rows) {
226      return GetValues<DateTime>(variableName, rows);
227    }
228    public ReadOnlyCollection<DateTime> GetReadOnlyDateTimeValues(string variableName) {
229      var values = GetValues<DateTime>(variableName);
230      return new ReadOnlyCollection<DateTime>(values);
231    }
232    private IEnumerable<T> GetValues<T>(string variableName, IEnumerable<int> rows) {
233      var values = GetValues<T>(variableName);
234      return rows.Select(x => values[x]);
235    }
236    private IList<T> GetValues<T>(string variableName) {
237      IList list;
238      if (!variableValues.TryGetValue(variableName, out list))
239        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
240      IList<T> values = list as IList<T>;
241      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a " + typeof(T) + " variable.");
242      return values;
243    }
244    public bool VariableHasType<T>(string variableName) {
245      return variableValues[variableName] is IList<T>;
246    }
247    protected Type GetVariableType(string variableName) {
248      IList list;
249      variableValues.TryGetValue(variableName, out list);
250      if (list == null)
251        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
252      return GetElementType(list);
253    }
254    protected static Type GetElementType(IList list) {
255      var type = list.GetType();
256      return type.IsGenericType ? type.GetGenericArguments()[0] : type.GetElementType();
257    }
258    protected static bool IsAllowedType(IList list) {
259      var type = GetElementType(list);
260      return IsAllowedType(type);
261    }
262    protected static bool IsAllowedType(Type type) {
263      return type == typeof(double) || type == typeof(string) || type == typeof(DateTime);
264    }
265
266    protected static void CheckArguments(IEnumerable<string> variableNames, IEnumerable<IList> variableValues) {
267      if (variableNames.Count() != variableValues.Count()) {
268        throw new ArgumentException("Number of variable names doesn't match the number of columns of variableValues");
269      } else if (!variableValues.All(list => list.Count == variableValues.First().Count)) {
270        throw new ArgumentException("The number of values must be equal for every variable");
271      } else if (variableNames.Distinct().Count() != variableNames.Count()) {
272        var duplicateVariableNames =
273          variableNames.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
274        string message = "The dataset cannot contain duplicate variables names: " + Environment.NewLine;
275        foreach (var duplicateVariableName in duplicateVariableNames)
276          message += duplicateVariableName + Environment.NewLine;
277        throw new ArgumentException(message);
278      }
279      // check if all the variables are supported
280      foreach (var t in variableNames.Zip(variableValues, Tuple.Create)) {
281        var variableName = t.Item1;
282        var values = t.Item2;
283
284        if (!IsAllowedType(values)) {
285          throw new ArgumentException(string.Format("Unsupported type {0} for variable {1}.", GetElementType(values), variableName));
286        }
287      }
288    }
289
290    protected static Dictionary<string, IList> CloneValues(Dictionary<string, IList> variableValues) {
291      return variableValues.ToDictionary(x => x.Key, x => CloneValues(x.Value));
292    }
293
294    protected static Dictionary<string, IList> CloneValues(IEnumerable<string> variableNames, IEnumerable<IList> variableValues) {
295      return variableNames.Zip(variableValues, Tuple.Create).ToDictionary(x => x.Item1, x => CloneValues(x.Item2));
296    }
297
298    protected static IList CloneValues(IList values) {
299      var doubleValues = values as IList<double>;
300      if (doubleValues != null) return new List<double>(doubleValues);
301
302      var stringValues = values as IList<string>;
303      if (stringValues != null) return new List<string>(stringValues);
304
305      var dateTimeValues = values as IList<DateTime>;
306      if (dateTimeValues != null) return new List<DateTime>(dateTimeValues);
307
308      throw new ArgumentException(string.Format("Unsupported variable type {0}.", GetElementType(values)));
309    }
310
311    #region IStringConvertibleMatrix Members
312    [Storable]
313    private int rows;
314    public int Rows {
315      get { return rows; }
316      protected set { rows = value; }
317    }
318    int IStringConvertibleMatrix.Rows {
319      get { return Rows; }
320      set { throw new NotSupportedException(); }
321    }
322
323    public int Columns {
324      get { return variableNames.Count; }
325    }
326    int IStringConvertibleMatrix.Columns {
327      get { return Columns; }
328      set { throw new NotSupportedException(); }
329    }
330    bool IStringConvertibleMatrix.SortableView {
331      get { return false; }
332      set { throw new NotSupportedException(); }
333    }
334    bool IStringConvertibleMatrix.ReadOnly {
335      get { return true; }
336    }
337    IEnumerable<string> IStringConvertibleMatrix.ColumnNames {
338      get { return this.VariableNames; }
339      set { throw new NotSupportedException(); }
340    }
341    IEnumerable<string> IStringConvertibleMatrix.RowNames {
342      get { return Enumerable.Empty<string>(); }
343      set { throw new NotSupportedException(); }
344    }
345    string IStringConvertibleMatrix.GetValue(int rowIndex, int columnIndex) {
346      return variableValues[variableNames[columnIndex]][rowIndex].ToString();
347    }
348    bool IStringConvertibleMatrix.SetValue(string value, int rowIndex, int columnIndex) {
349      throw new NotSupportedException();
350    }
351    bool IStringConvertibleMatrix.Validate(string value, out string errorMessage) {
352      throw new NotSupportedException();
353    }
354
355    public virtual event EventHandler ColumnsChanged { add { } remove { } }
356    public virtual event EventHandler RowsChanged { add { } remove { } }
357    public virtual event EventHandler ColumnNamesChanged { add { } remove { } }
358    public virtual event EventHandler RowNamesChanged { add { } remove { } }
359    public virtual event EventHandler SortableViewChanged { add { } remove { } }
360    public virtual event EventHandler<EventArgs<int, int>> ItemChanged { add { } remove { } }
361    public virtual event EventHandler Reset { add { } remove { } }
362    #endregion
363  }
364}
Note: See TracBrowser for help on using the repository browser.