Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2898_GeneralizedAdditiveModels/HeuristicLab.Problems.DataAnalysis/3.4/Dataset.cs @ 16375

Last change on this file since 16375 was 15769, checked in by bburlacu, 7 years ago

#2897: Add type checks in Dataset constructor, remove cloning of values in the ModifiableDataset.AddVariable method. Provide small fix in GradientBoostingRegressionAlgorithm for AddVariable.

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