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
RevLine 
[2]1#region License Information
2/* HeuristicLab
[16640]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;
[3376]27using HeuristicLab.Common;
[3253]28using HeuristicLab.Core;
[4068]29using HeuristicLab.Data;
[16628]30using HEAL.Attic;
[16640]31using HEAL.Attic;
[2]32
[3253]33namespace HeuristicLab.Problems.DataAnalysis {
34  [Item("Dataset", "Represents a dataset containing data that should be analyzed.")]
[16640]35  [StorableType("49F4D145-50D7-4497-8D8A-D190CD556CC8")]
[12509]36  public class Dataset : NamedItem, IDataset {
[3933]37    [StorableConstructor]
[16628]38    protected Dataset(StorableConstructorFlag _) : base(_) { }
[12509]39    protected Dataset(Dataset original, Cloner cloner)
[4722]40      : base(original, cloner) {
[15829]41      // no need to clone the variable values because these can't be modified
[6740]42      variableValues = new Dictionary<string, IList>(original.variableValues);
43      variableNames = new List<string>(original.variableNames);
44      rows = original.rows;
[2319]45    }
[15829]46
[6740]47    public override IDeepCloneable Clone(Cloner cloner) { return new Dataset(this, cloner); }
[5552]48
[5847]49    public Dataset()
50      : base() {
51      Name = "-";
52      VariableNames = Enumerable.Empty<string>();
[6740]53      variableValues = new Dictionary<string, IList>();
54      rows = 0;
[5847]55    }
56
[13419]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>
[6740]62    public Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues)
[15829]63      : this(variableNames, variableValues, cloneValues: true) {
64    }
65
66    protected Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues, bool cloneValues = false) {
[2319]67      Name = "-";
[15829]68
69      if (variableNames.Any()) {
70        this.variableNames = new List<string>(variableNames);
71      } else {
[6740]72        this.variableNames = Enumerable.Range(0, variableValues.Count()).Select(x => "Column " + x).ToList();
[3264]73      }
[15829]74      // check if the arguments are consistent (no duplicate variables, same number of rows, correct data types, ...)
75      CheckArguments(this.variableNames, variableValues);
76
[6740]77      rows = variableValues.First().Count;
[15769]78
[15829]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);
[15769]87        }
[6740]88      }
[2038]89    }
90
[6740]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      }
[5552]103
[6740]104      rows = variableValues.GetLength(0);
105      this.variableNames = new List<string>(variableNames);
106
[7736]107      this.variableValues = new Dictionary<string, IList>(variableValues.GetLength(1));
[6740]108      for (int col = 0; col < variableValues.GetLength(1); col++) {
109        string columName = this.variableNames[col];
[7736]110        var values = new List<double>(variableValues.GetLength(0));
[6740]111        for (int row = 0; row < variableValues.GetLength(0); row++) {
112          values.Add(variableValues[row, col]);
[5552]113        }
[6740]114        this.variableValues.Add(columName, values);
[5552]115      }
[333]116    }
117
[13760]118    public ModifiableDataset ToModifiable() {
[16084]119      return new ModifiableDataset(variableNames, variableNames.Select(v => variableValues[v]), true);
[13760]120    }
[15769]121
[14864]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    }
[13760]131
[12509]132
[16063]133
[6740]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; } }
[2]139
[6740]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];
[7921]147          var values = new List<double>(rows);
148          for (int row = 0; row < rows; row++) {
[6740]149            values.Add(storableData[row, col]);
150          }
151          variableValues.Add(columName, values);
152        }
153        storableData = null;
[3839]154      }
155    }
[6740]156    #endregion
[3933]157
[6749]158    [Storable(Name = "VariableValues")]
[12509]159    protected Dictionary<string, IList> variableValues;
[6749]160
[12509]161    protected List<string> variableNames;
[6740]162    [Storable]
163    public IEnumerable<string> VariableNames {
164      get { return variableNames; }
[12509]165      protected set {
[6740]166        if (variableNames != null) throw new InvalidOperationException();
167        variableNames = new List<string>(value);
168      }
[1287]169    }
[16241]170
171    public bool ContainsVariable(string variableName) {
172      return variableValues.ContainsKey(variableName);
173    }
[6740]174    public IEnumerable<string> DoubleVariables {
[15013]175      get { return variableValues.Where(p => p.Value is IList<double>).Select(p => p.Key); }
[3994]176    }
[14826]177
178    public IEnumerable<string> StringVariables {
[15013]179      get { return variableValues.Where(p => p.Value is IList<string>).Select(p => p.Key); }
[14826]180    }
181
[15094]182    public IEnumerable<string> DateTimeVariables {
183      get { return variableValues.Where(p => p.Value is IList<DateTime>).Select(p => p.Key); }
184    }
185
[6740]186    public IEnumerable<double> GetDoubleValues(string variableName) {
[12509]187      return GetValues<double>(variableName);
[3994]188    }
[11114]189    public IEnumerable<string> GetStringValues(string variableName) {
[12509]190      return GetValues<string>(variableName);
[11114]191    }
192    public IEnumerable<DateTime> GetDateTimeValues(string variableName) {
[12509]193      return GetValues<DateTime>(variableName);
[11114]194    }
195
[6740]196    public ReadOnlyCollection<double> GetReadOnlyDoubleValues(string variableName) {
[12509]197      var values = GetValues<double>(variableName);
[15013]198      return new ReadOnlyCollection<double>(values);
[3994]199    }
[6740]200    public double GetDoubleValue(string variableName, int row) {
[12509]201      var values = GetValues<double>(variableName);
[6740]202      return values[row];
[4031]203    }
[6740]204    public IEnumerable<double> GetDoubleValues(string variableName, IEnumerable<int> rows) {
[12509]205      return GetValues<double>(variableName, rows);
206    }
[14826]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);
[15013]218      return new ReadOnlyCollection<string>(values);
[14826]219    }
220
[15094]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    }
[12509]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    }
[15013]236    private IList<T> GetValues<T>(string variableName) {
[6740]237      IList list;
238      if (!variableValues.TryGetValue(variableName, out list))
239        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
[15013]240      IList<T> values = list as IList<T>;
[12509]241      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a " + typeof(T) + " variable.");
242      return values;
[2319]243    }
[11156]244    public bool VariableHasType<T>(string variableName) {
[11114]245      return variableValues[variableName] is IList<T>;
246    }
[15769]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    }
[15829]254    protected static Type GetElementType(IList list) {
[15769]255      var type = list.GetType();
256      return type.IsGenericType ? type.GetGenericArguments()[0] : type.GetElementType();
257    }
[15829]258    protected static bool IsAllowedType(IList list) {
[15769]259      var type = GetElementType(list);
260      return IsAllowedType(type);
261    }
[15829]262    protected static bool IsAllowedType(Type type) {
[15769]263      return type == typeof(double) || type == typeof(string) || type == typeof(DateTime);
264    }
265
[15829]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
[3253]311    #region IStringConvertibleMatrix Members
[6740]312    [Storable]
[16063]313    private int rows;
[3253]314    public int Rows {
[6740]315      get { return rows; }
[16063]316      protected set { rows = value; }
[13539]317    }
318    int IStringConvertibleMatrix.Rows {
319      get { return Rows; }
[3933]320      set { throw new NotSupportedException(); }
[2]321    }
[13539]322
[3253]323    public int Columns {
[6740]324      get { return variableNames.Count; }
[13539]325    }
326    int IStringConvertibleMatrix.Columns {
327      get { return Columns; }
[3933]328      set { throw new NotSupportedException(); }
[2]329    }
[13427]330    bool IStringConvertibleMatrix.SortableView {
[3933]331      get { return false; }
332      set { throw new NotSupportedException(); }
[3321]333    }
[13427]334    bool IStringConvertibleMatrix.ReadOnly {
[3933]335      get { return true; }
[3430]336    }
[3308]337    IEnumerable<string> IStringConvertibleMatrix.ColumnNames {
338      get { return this.VariableNames; }
[3933]339      set { throw new NotSupportedException(); }
[3308]340    }
[3311]341    IEnumerable<string> IStringConvertibleMatrix.RowNames {
[5552]342      get { return Enumerable.Empty<string>(); }
[3933]343      set { throw new NotSupportedException(); }
[3311]344    }
[13427]345    string IStringConvertibleMatrix.GetValue(int rowIndex, int columnIndex) {
[6740]346      return variableValues[variableNames[columnIndex]][rowIndex].ToString();
[2]347    }
[12509]348    bool IStringConvertibleMatrix.SetValue(string value, int rowIndex, int columnIndex) {
[3933]349      throw new NotSupportedException();
[237]350    }
[12509]351    bool IStringConvertibleMatrix.Validate(string value, out string errorMessage) {
[5552]352      throw new NotSupportedException();
353    }
[237]354
[12509]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 { } }
[2012]362    #endregion
[2]363  }
364}
Note: See TracBrowser for help on using the repository browser.