Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis/3.4/Dataset.cs @ 16841

Last change on this file since 16841 was 16820, checked in by abeham, 6 years ago

#3002: Implement static methods to build dataset from row-wise data and added unit test

File size: 17.3 KB
RevLine 
[2]1#region License Information
2/* HeuristicLab
[16565]3 * Copyright (C) 2002-2019 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[2]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;
[6740]23using System.Collections;
[2]24using System.Collections.Generic;
[6740]25using System.Collections.ObjectModel;
[2285]26using System.Linq;
[16820]27using HEAL.Attic;
[3376]28using HeuristicLab.Common;
[3253]29using HeuristicLab.Core;
[4068]30using HeuristicLab.Data;
[2]31
[3253]32namespace HeuristicLab.Problems.DataAnalysis {
33  [Item("Dataset", "Represents a dataset containing data that should be analyzed.")]
[16565]34  [StorableType("49F4D145-50D7-4497-8D8A-D190CD556CC8")]
[12509]35  public class Dataset : NamedItem, IDataset {
[3933]36    [StorableConstructor]
[16565]37    protected Dataset(StorableConstructorFlag _) : base(_) { }
[12509]38    protected Dataset(Dataset original, Cloner cloner)
[4722]39      : base(original, cloner) {
[15829]40      // no need to clone the variable values because these can't be modified
[6740]41      variableValues = new Dictionary<string, IList>(original.variableValues);
42      variableNames = new List<string>(original.variableNames);
43      rows = original.rows;
[2319]44    }
[15829]45
[6740]46    public override IDeepCloneable Clone(Cloner cloner) { return new Dataset(this, cloner); }
[5552]47
[5847]48    public Dataset()
49      : base() {
50      Name = "-";
51      VariableNames = Enumerable.Empty<string>();
[6740]52      variableValues = new Dictionary<string, IList>();
53      rows = 0;
[5847]54    }
55
[13419]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>
[6740]61    public Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues)
[15829]62      : this(variableNames, variableValues, cloneValues: true) {
63    }
64
65    protected Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues, bool cloneValues = false) {
[2319]66      Name = "-";
[15829]67
68      if (variableNames.Any()) {
69        this.variableNames = new List<string>(variableNames);
70      } else {
[6740]71        this.variableNames = Enumerable.Range(0, variableValues.Count()).Select(x => "Column " + x).ToList();
[3264]72      }
[15829]73      // check if the arguments are consistent (no duplicate variables, same number of rows, correct data types, ...)
74      CheckArguments(this.variableNames, variableValues);
75
[6740]76      rows = variableValues.First().Count;
[15769]77
[15829]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);
[15769]86        }
[6740]87      }
[2038]88    }
89
[6740]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      }
[5552]102
[6740]103      rows = variableValues.GetLength(0);
104      this.variableNames = new List<string>(variableNames);
105
[7736]106      this.variableValues = new Dictionary<string, IList>(variableValues.GetLength(1));
[6740]107      for (int col = 0; col < variableValues.GetLength(1); col++) {
108        string columName = this.variableNames[col];
[7736]109        var values = new List<double>(variableValues.GetLength(0));
[6740]110        for (int row = 0; row < variableValues.GetLength(0); row++) {
111          values.Add(variableValues[row, col]);
[5552]112        }
[6740]113        this.variableValues.Add(columName, values);
[5552]114      }
[333]115    }
116
[16820]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 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()));
145      }
146      if (transposed.Count < vnames.Count) throw new ArgumentException("There are less variables in data, than variable names.", nameof(variableNames));
147      while (iter.MoveNext()) {
148        for (var i = 0; i < iter.Current.Count; i++)
149          if (transposed[i].Add(iter.Current[i]) < 0)
150            throw new ArgumentException(string.Format("Variable {0} has invalid value ({1})", vnames[i], iter.Current[i]), nameof(data));
151      }
152      return new Dataset(vnames, transposed);
153    }
154
[13760]155    public ModifiableDataset ToModifiable() {
[16084]156      return new ModifiableDataset(variableNames, variableNames.Select(v => variableValues[v]), true);
[13760]157    }
[15769]158
[14864]159    /// <summary>
160    /// Shuffle a dataset's rows
161    /// </summary>
162    /// <param name="random">Random number generator used for shuffling.</param>
163    /// <returns>A shuffled copy of the current dataset.</returns>
164    public Dataset Shuffle(IRandom random) {
165      var values = variableNames.Select(x => variableValues[x]).ToList();
166      return new Dataset(variableNames, values.ShuffleLists(random));
167    }
[13760]168
[12509]169
[16063]170
[6740]171    #region Backwards compatible code, remove with 3.5
172    private double[,] storableData;
[16796]173    //name alias used to support backwards compatibility
174    [Storable(OldName = "data")]
[6740]175    private double[,] StorableData { set { storableData = value; } }
[2]176
[6740]177    [StorableHook(HookType.AfterDeserialization)]
178    private void AfterDeserialization() {
179      if (variableValues == null) {
180        rows = storableData.GetLength(0);
181        variableValues = new Dictionary<string, IList>();
182        for (int col = 0; col < storableData.GetLength(1); col++) {
183          string columName = variableNames[col];
[7921]184          var values = new List<double>(rows);
185          for (int row = 0; row < rows; row++) {
[6740]186            values.Add(storableData[row, col]);
187          }
188          variableValues.Add(columName, values);
189        }
190        storableData = null;
[3839]191      }
192    }
[6740]193    #endregion
[3933]194
[6749]195    [Storable(Name = "VariableValues")]
[12509]196    protected Dictionary<string, IList> variableValues;
[6749]197
[12509]198    protected List<string> variableNames;
[6740]199    [Storable]
200    public IEnumerable<string> VariableNames {
201      get { return variableNames; }
[12509]202      protected set {
[6740]203        if (variableNames != null) throw new InvalidOperationException();
204        variableNames = new List<string>(value);
205      }
[1287]206    }
[16241]207
208    public bool ContainsVariable(string variableName) {
209      return variableValues.ContainsKey(variableName);
210    }
[6740]211    public IEnumerable<string> DoubleVariables {
[15013]212      get { return variableValues.Where(p => p.Value is IList<double>).Select(p => p.Key); }
[3994]213    }
[14826]214
215    public IEnumerable<string> StringVariables {
[15013]216      get { return variableValues.Where(p => p.Value is IList<string>).Select(p => p.Key); }
[14826]217    }
218
[15094]219    public IEnumerable<string> DateTimeVariables {
220      get { return variableValues.Where(p => p.Value is IList<DateTime>).Select(p => p.Key); }
221    }
222
[6740]223    public IEnumerable<double> GetDoubleValues(string variableName) {
[12509]224      return GetValues<double>(variableName);
[3994]225    }
[11114]226    public IEnumerable<string> GetStringValues(string variableName) {
[12509]227      return GetValues<string>(variableName);
[11114]228    }
229    public IEnumerable<DateTime> GetDateTimeValues(string variableName) {
[12509]230      return GetValues<DateTime>(variableName);
[11114]231    }
232
[6740]233    public ReadOnlyCollection<double> GetReadOnlyDoubleValues(string variableName) {
[12509]234      var values = GetValues<double>(variableName);
[15013]235      return new ReadOnlyCollection<double>(values);
[3994]236    }
[6740]237    public double GetDoubleValue(string variableName, int row) {
[12509]238      var values = GetValues<double>(variableName);
[6740]239      return values[row];
[4031]240    }
[6740]241    public IEnumerable<double> GetDoubleValues(string variableName, IEnumerable<int> rows) {
[12509]242      return GetValues<double>(variableName, rows);
243    }
[14826]244
245    public string GetStringValue(string variableName, int row) {
246      var values = GetValues<string>(variableName);
247      return values[row];
248    }
249
250    public IEnumerable<string> GetStringValues(string variableName, IEnumerable<int> rows) {
251      return GetValues<string>(variableName, rows);
252    }
253    public ReadOnlyCollection<string> GetReadOnlyStringValues(string variableName) {
254      var values = GetValues<string>(variableName);
[15013]255      return new ReadOnlyCollection<string>(values);
[14826]256    }
257
[15094]258    public DateTime GetDateTimeValue(string variableName, int row) {
259      var values = GetValues<DateTime>(variableName);
260      return values[row];
261    }
262    public IEnumerable<DateTime> GetDateTimeValues(string variableName, IEnumerable<int> rows) {
263      return GetValues<DateTime>(variableName, rows);
264    }
265    public ReadOnlyCollection<DateTime> GetReadOnlyDateTimeValues(string variableName) {
266      var values = GetValues<DateTime>(variableName);
267      return new ReadOnlyCollection<DateTime>(values);
268    }
[12509]269    private IEnumerable<T> GetValues<T>(string variableName, IEnumerable<int> rows) {
270      var values = GetValues<T>(variableName);
271      return rows.Select(x => values[x]);
272    }
[15013]273    private IList<T> GetValues<T>(string variableName) {
[6740]274      IList list;
275      if (!variableValues.TryGetValue(variableName, out list))
276        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
[15013]277      IList<T> values = list as IList<T>;
[12509]278      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a " + typeof(T) + " variable.");
279      return values;
[2319]280    }
[11156]281    public bool VariableHasType<T>(string variableName) {
[11114]282      return variableValues[variableName] is IList<T>;
283    }
[15769]284    protected Type GetVariableType(string variableName) {
285      IList list;
286      variableValues.TryGetValue(variableName, out list);
287      if (list == null)
288        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
289      return GetElementType(list);
290    }
[15829]291    protected static Type GetElementType(IList list) {
[15769]292      var type = list.GetType();
293      return type.IsGenericType ? type.GetGenericArguments()[0] : type.GetElementType();
294    }
[15829]295    protected static bool IsAllowedType(IList list) {
[15769]296      var type = GetElementType(list);
297      return IsAllowedType(type);
298    }
[15829]299    protected static bool IsAllowedType(Type type) {
[15769]300      return type == typeof(double) || type == typeof(string) || type == typeof(DateTime);
301    }
302
[15829]303    protected static void CheckArguments(IEnumerable<string> variableNames, IEnumerable<IList> variableValues) {
304      if (variableNames.Count() != variableValues.Count()) {
305        throw new ArgumentException("Number of variable names doesn't match the number of columns of variableValues");
306      } else if (!variableValues.All(list => list.Count == variableValues.First().Count)) {
307        throw new ArgumentException("The number of values must be equal for every variable");
308      } else if (variableNames.Distinct().Count() != variableNames.Count()) {
309        var duplicateVariableNames =
310          variableNames.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
311        string message = "The dataset cannot contain duplicate variables names: " + Environment.NewLine;
312        foreach (var duplicateVariableName in duplicateVariableNames)
313          message += duplicateVariableName + Environment.NewLine;
314        throw new ArgumentException(message);
315      }
316      // check if all the variables are supported
317      foreach (var t in variableNames.Zip(variableValues, Tuple.Create)) {
318        var variableName = t.Item1;
319        var values = t.Item2;
320
321        if (!IsAllowedType(values)) {
322          throw new ArgumentException(string.Format("Unsupported type {0} for variable {1}.", GetElementType(values), variableName));
323        }
324      }
325    }
326
327    protected static Dictionary<string, IList> CloneValues(Dictionary<string, IList> variableValues) {
328      return variableValues.ToDictionary(x => x.Key, x => CloneValues(x.Value));
329    }
330
331    protected static Dictionary<string, IList> CloneValues(IEnumerable<string> variableNames, IEnumerable<IList> variableValues) {
332      return variableNames.Zip(variableValues, Tuple.Create).ToDictionary(x => x.Item1, x => CloneValues(x.Item2));
333    }
334
335    protected static IList CloneValues(IList values) {
336      var doubleValues = values as IList<double>;
337      if (doubleValues != null) return new List<double>(doubleValues);
338
339      var stringValues = values as IList<string>;
340      if (stringValues != null) return new List<string>(stringValues);
341
342      var dateTimeValues = values as IList<DateTime>;
343      if (dateTimeValues != null) return new List<DateTime>(dateTimeValues);
344
345      throw new ArgumentException(string.Format("Unsupported variable type {0}.", GetElementType(values)));
346    }
347
[3253]348    #region IStringConvertibleMatrix Members
[6740]349    [Storable]
[16063]350    private int rows;
[3253]351    public int Rows {
[6740]352      get { return rows; }
[16063]353      protected set { rows = value; }
[13539]354    }
355    int IStringConvertibleMatrix.Rows {
356      get { return Rows; }
[3933]357      set { throw new NotSupportedException(); }
[2]358    }
[13539]359
[3253]360    public int Columns {
[6740]361      get { return variableNames.Count; }
[13539]362    }
363    int IStringConvertibleMatrix.Columns {
364      get { return Columns; }
[3933]365      set { throw new NotSupportedException(); }
[2]366    }
[13427]367    bool IStringConvertibleMatrix.SortableView {
[3933]368      get { return false; }
369      set { throw new NotSupportedException(); }
[3321]370    }
[13427]371    bool IStringConvertibleMatrix.ReadOnly {
[3933]372      get { return true; }
[3430]373    }
[3308]374    IEnumerable<string> IStringConvertibleMatrix.ColumnNames {
375      get { return this.VariableNames; }
[3933]376      set { throw new NotSupportedException(); }
[3308]377    }
[3311]378    IEnumerable<string> IStringConvertibleMatrix.RowNames {
[5552]379      get { return Enumerable.Empty<string>(); }
[3933]380      set { throw new NotSupportedException(); }
[3311]381    }
[13427]382    string IStringConvertibleMatrix.GetValue(int rowIndex, int columnIndex) {
[6740]383      return variableValues[variableNames[columnIndex]][rowIndex].ToString();
[2]384    }
[12509]385    bool IStringConvertibleMatrix.SetValue(string value, int rowIndex, int columnIndex) {
[3933]386      throw new NotSupportedException();
[237]387    }
[12509]388    bool IStringConvertibleMatrix.Validate(string value, out string errorMessage) {
[5552]389      throw new NotSupportedException();
390    }
[237]391
[12509]392    public virtual event EventHandler ColumnsChanged { add { } remove { } }
393    public virtual event EventHandler RowsChanged { add { } remove { } }
394    public virtual event EventHandler ColumnNamesChanged { add { } remove { } }
395    public virtual event EventHandler RowNamesChanged { add { } remove { } }
396    public virtual event EventHandler SortableViewChanged { add { } remove { } }
397    public virtual event EventHandler<EventArgs<int, int>> ItemChanged { add { } remove { } }
398    public virtual event EventHandler Reset { add { } remove { } }
[2012]399    #endregion
[2]400  }
401}
Note: See TracBrowser for help on using the repository browser.