Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 17786 was 17786, checked in by pfleck, 3 years ago

#3040 Worked in DiffSharp for constant-opt.

File size: 18.7 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
32using DoubleVector = MathNet.Numerics.LinearAlgebra.Vector<double>;
33
34namespace HeuristicLab.Problems.DataAnalysis {
35  [Item("Dataset", "Represents a dataset containing data that should be analyzed.")]
36  [StorableType("49F4D145-50D7-4497-8D8A-D190CD556CC8")]
37  public class Dataset : NamedItem, IDataset {
38    [StorableConstructor]
39    protected Dataset(StorableConstructorFlag _) : base(_) { }
40    protected Dataset(Dataset original, Cloner cloner)
41      : base(original, cloner) {
42      // no need to clone the variable values because these can't be modified
43      variableValues = new Dictionary<string, IList>(original.variableValues);
44      variableNames = new List<string>(original.variableNames);
45      rows = original.rows;
46    }
47
48    public override IDeepCloneable Clone(Cloner cloner) { return new Dataset(this, cloner); }
49
50    public Dataset()
51      : base() {
52      Name = "-";
53      VariableNames = Enumerable.Empty<string>();
54      variableValues = new Dictionary<string, IList>();
55      rows = 0;
56    }
57
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>
63    public Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues)
64      : this(variableNames, variableValues, cloneValues: true) {
65    }
66
67    protected Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues, bool cloneValues = false) {
68      Name = "-";
69
70      if (variableNames.Any()) {
71        this.variableNames = new List<string>(variableNames);
72      } else {
73        this.variableNames = Enumerable.Range(0, variableValues.Count()).Select(x => "Column " + x).ToList();
74      }
75      // check if the arguments are consistent (no duplicate variables, same number of rows, correct data types, ...)
76      CheckArguments(this.variableNames, variableValues);
77
78      rows = variableValues.First().Count;
79
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);
88        }
89      }
90    }
91
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      }
104
105      rows = variableValues.GetLength(0);
106      this.variableNames = new List<string>(variableNames);
107
108      this.variableValues = new Dictionary<string, IList>(variableValues.GetLength(1));
109      for (int col = 0; col < variableValues.GetLength(1); col++) {
110        string columName = this.variableNames[col];
111        var values = new List<double>(variableValues.GetLength(0));
112        for (int row = 0; row < variableValues.GetLength(0); row++) {
113          values.Add(variableValues[row, col]);
114        }
115        this.variableValues.Add(columName, values);
116      }
117    }
118
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 });
146        else if (iter.Current[i] is DoubleVector dv)
147          transposed.Add(new List<DoubleVector>() { dv });
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
159    public ModifiableDataset ToModifiable() {
160      return new ModifiableDataset(variableNames, variableNames.Select(v => variableValues[v]), true);
161    }
162
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    }
172
173
174
175    #region Backwards compatible code, remove with 3.5
176    private double[,] storableData;
177    //name alias used to support backwards compatibility
178    [Storable(OldName = "data")]
179    private double[,] StorableData { set { storableData = value; } }
180
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];
188          var values = new List<double>(rows);
189          for (int row = 0; row < rows; row++) {
190            values.Add(storableData[row, col]);
191          }
192          variableValues.Add(columName, values);
193        }
194        storableData = null;
195      }
196    }
197    #endregion
198
199    [Storable(Name = "VariableValues")]
200    protected Dictionary<string, IList> variableValues;
201
202    protected List<string> variableNames;
203    [Storable]
204    public IEnumerable<string> VariableNames {
205      get { return variableNames; }
206      protected set {
207        if (variableNames != null) throw new InvalidOperationException();
208        variableNames = new List<string>(value);
209      }
210    }
211
212    public bool ContainsVariable(string variableName) {
213      return variableValues.ContainsKey(variableName);
214    }
215    public IEnumerable<string> DoubleVariables {
216      get { return variableValues.Where(p => p.Value is IList<double>).Select(p => p.Key); }
217    }
218    public IEnumerable<string> StringVariables {
219      get { return variableValues.Where(p => p.Value is IList<string>).Select(p => p.Key); }
220    }
221    public IEnumerable<string> DateTimeVariables {
222      get { return variableValues.Where(p => p.Value is IList<DateTime>).Select(p => p.Key); }
223    }
224    public IEnumerable<string> DoubleVectorVariables {
225      get { return variableValues.Where(p => p.Value is IList<DoubleVector>).Select(p => p.Key); }
226    }
227
228    public IEnumerable<double> GetDoubleValues(string variableName) {
229      return GetValues<double>(variableName);
230    }
231    public IEnumerable<string> GetStringValues(string variableName) {
232      return GetValues<string>(variableName);
233    }
234    public IEnumerable<DateTime> GetDateTimeValues(string variableName) {
235      return GetValues<DateTime>(variableName);
236    }
237    public IEnumerable<DoubleVector> GetDoubleVectorValues(string variableName) {
238      return GetValues<DoubleVector>(variableName);
239    }
240
241    public ReadOnlyCollection<double> GetReadOnlyDoubleValues(string variableName) {
242      var values = GetValues<double>(variableName);
243      return new ReadOnlyCollection<double>(values);
244    }
245    public double GetDoubleValue(string variableName, int row) {
246      var values = GetValues<double>(variableName);
247      return values[row];
248    }
249    public IEnumerable<double> GetDoubleValues(string variableName, IEnumerable<int> rows) {
250      return GetValues<double>(variableName, rows);
251    }
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);
262      return new ReadOnlyCollection<string>(values);
263    }
264
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    }
276
277    public DoubleVector GetDoubleVectorValue(string variableName, int row) {
278      var values = GetValues<DoubleVector>(variableName);
279      return values[row];
280    }
281    public IEnumerable<DoubleVector> GetDoubleVectorValues(string variableName, IEnumerable<int> rows) {
282      return GetValues<DoubleVector>(variableName, rows);
283    }
284    public ReadOnlyCollection<DoubleVector> GetReadOnlyDoubleVectorValues(string variableName) {
285      var values = GetValues<DoubleVector>(variableName);
286      return new ReadOnlyCollection<DoubleVector>(values);
287    }
288
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    }
293    private IList<T> GetValues<T>(string variableName) {
294      IList list;
295      if (!variableValues.TryGetValue(variableName, out list))
296        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
297      IList<T> values = list as IList<T>;
298      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a " + typeof(T) + " variable.");
299      return values;
300    }
301    public bool VariableHasType<T>(string variableName) {
302      return variableValues[variableName] is IList<T>;
303    }
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    }
311    protected static Type GetElementType(IList list) {
312      var type = list.GetType();
313      return type.IsGenericType ? type.GetGenericArguments()[0] : type.GetElementType();
314    }
315    protected static bool IsAllowedType(IList list) {
316      var type = GetElementType(list);
317      return IsAllowedType(type);
318    }
319    protected static bool IsAllowedType(Type type) {
320      return type == typeof(double) || type == typeof(string) || type == typeof(DateTime) || type == typeof(DoubleVector);
321    }
322
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
365      var doubleVectorValues = values as IList<DoubleVector>;
366      if (doubleVectorValues != null) return doubleVectorValues.Select(x => x.Clone()).ToList();
367
368      throw new ArgumentException(string.Format("Unsupported variable type {0}.", GetElementType(values)));
369    }
370
371    #region IStringConvertibleMatrix Members
372    [Storable]
373    private int rows;
374    public int Rows {
375      get { return rows; }
376      protected set { rows = value; }
377    }
378    int IStringConvertibleMatrix.Rows {
379      get { return Rows; }
380      set { throw new NotSupportedException(); }
381    }
382
383    public int Columns {
384      get { return variableNames.Count; }
385    }
386    int IStringConvertibleMatrix.Columns {
387      get { return Columns; }
388      set { throw new NotSupportedException(); }
389    }
390    bool IStringConvertibleMatrix.SortableView {
391      get { return false; }
392      set { throw new NotSupportedException(); }
393    }
394    bool IStringConvertibleMatrix.ReadOnly {
395      get { return true; }
396    }
397    IEnumerable<string> IStringConvertibleMatrix.ColumnNames {
398      get { return this.VariableNames; }
399      set { throw new NotSupportedException(); }
400    }
401    IEnumerable<string> IStringConvertibleMatrix.RowNames {
402      get { return Enumerable.Empty<string>(); }
403      set { throw new NotSupportedException(); }
404    }
405    string IStringConvertibleMatrix.GetValue(int rowIndex, int columnIndex) {
406      var value = variableValues[variableNames[columnIndex]][rowIndex];
407      if (value is DoubleVector vector) {
408        return $"[{vector.ToVectorString(10, 80, "..", " ", " ", d => d.ToString("G6", null))}]";
409      }
410
411      return value.ToString();
412    }
413    bool IStringConvertibleMatrix.SetValue(string value, int rowIndex, int columnIndex) {
414      throw new NotSupportedException();
415    }
416    bool IStringConvertibleMatrix.Validate(string value, out string errorMessage) {
417      throw new NotSupportedException();
418    }
419
420    public virtual event EventHandler ColumnsChanged { add { } remove { } }
421    public virtual event EventHandler RowsChanged { add { } remove { } }
422    public virtual event EventHandler ColumnNamesChanged { add { } remove { } }
423    public virtual event EventHandler RowNamesChanged { add { } remove { } }
424    public virtual event EventHandler SortableViewChanged { add { } remove { } }
425    public virtual event EventHandler<EventArgs<int, int>> ItemChanged { add { } remove { } }
426    public virtual event EventHandler Reset { add { } remove { } }
427    #endregion
428  }
429}
Note: See TracBrowser for help on using the repository browser.