Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17460 was 17449, checked in by pfleck, 5 years ago

#3040 Added Transformers for Vectors.
Added specialiced Transformers for double Dense/SparseVectorStorage and a generic mapper for the remaining (serializable) types.

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