Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RegressionBenchmarks/HeuristicLab.Problems.DataAnalysis/3.4/Dataset.cs @ 7698

Last change on this file since 7698 was 7337, checked in by sforsten, 13 years ago

#1752: some methods were added to Dataset to easier obtain string and Datetime values

File size: 15.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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 sealed class Dataset : NamedItem, IStringConvertibleMatrix {
36    [StorableConstructor]
37    private Dataset(bool deserializing) : base(deserializing) { }
38    private 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    public Dataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues)
55      : base() {
56      Name = "-";
57      if (!variableNames.Any()) {
58        this.variableNames = Enumerable.Range(0, variableValues.Count()).Select(x => "Column " + x).ToList();
59      } else if (variableNames.Count() != variableValues.Count()) {
60        throw new ArgumentException("Number of variable names doesn't match the number of columns of variableValues");
61      } else if (!variableValues.All(list => list.Count == variableValues.First().Count)) {
62        throw new ArgumentException("The number of values must be equal for every variable");
63      } else if (variableNames.Distinct().Count() != variableNames.Count()) {
64        var duplicateVariableNames =
65          variableNames.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
66        string message = "The dataset cannot contain duplicate variables names: " + Environment.NewLine;
67        foreach (var duplicateVariableName in duplicateVariableNames)
68          message += duplicateVariableName + Environment.NewLine;
69        throw new ArgumentException(message);
70      }
71
72      rows = variableValues.First().Count;
73      this.variableNames = new List<string>(variableNames);
74      this.variableValues = new Dictionary<string, IList>();
75      for (int i = 0; i < this.variableNames.Count; i++) {
76        var values = variableValues.ElementAt(i);
77        IList clonedValues = null;
78        if (values is List<double>)
79          clonedValues = new List<double>(values.Cast<double>());
80        else if (values is List<string>)
81          clonedValues = new List<string>(values.Cast<string>());
82        else if (values is List<DateTime>)
83          clonedValues = new List<DateTime>(values.Cast<DateTime>());
84        else {
85          this.variableNames = new List<string>();
86          this.variableValues = new Dictionary<string, IList>();
87          throw new ArgumentException("The variable values must be of type List<double>, List<string> or List<DateTime>");
88        }
89        this.variableValues.Add(this.variableNames[i], clonedValues);
90      }
91    }
92
93    public Dataset(IEnumerable<string> variableNames, double[,] variableValues) {
94      Name = "-";
95      if (variableNames.Count() != variableValues.GetLength(1)) {
96        throw new ArgumentException("Number of variable names doesn't match the number of columns of variableValues");
97      }
98      if (variableNames.Distinct().Count() != variableNames.Count()) {
99        var duplicateVariableNames = variableNames.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
100        string message = "The dataset cannot contain duplicate variables names: " + Environment.NewLine;
101        foreach (var duplicateVariableName in duplicateVariableNames)
102          message += duplicateVariableName + Environment.NewLine;
103        throw new ArgumentException(message);
104      }
105
106      rows = variableValues.GetLength(0);
107      this.variableNames = new List<string>(variableNames);
108
109      this.variableValues = new Dictionary<string, IList>();
110      for (int col = 0; col < variableValues.GetLength(1); col++) {
111        string columName = this.variableNames[col];
112        var values = new List<double>();
113        for (int row = 0; row < variableValues.GetLength(0); row++) {
114          values.Add(variableValues[row, col]);
115        }
116        this.variableValues.Add(columName, values);
117      }
118    }
119
120    #region Backwards compatible code, remove with 3.5
121    private double[,] storableData;
122    //name alias used to suppport backwards compatibility
123    [Storable(Name = "data", AllowOneWay = true)]
124    private double[,] StorableData { set { storableData = value; } }
125
126    [StorableHook(HookType.AfterDeserialization)]
127    private void AfterDeserialization() {
128      if (variableValues == null) {
129        rows = storableData.GetLength(0);
130        variableValues = new Dictionary<string, IList>();
131        for (int col = 0; col < storableData.GetLength(1); col++) {
132          string columName = variableNames[col];
133          var values = new List<double>();
134          for (int row = 0; row < storableData.GetLength(0); row++) {
135            values.Add(storableData[row, col]);
136          }
137          variableValues.Add(columName, values);
138        }
139        storableData = null;
140      }
141    }
142    #endregion
143
144    [Storable(Name = "VariableValues")]
145    private Dictionary<string, IList> variableValues;
146
147    private List<string> variableNames;
148    [Storable]
149    public IEnumerable<string> VariableNames {
150      get { return variableNames; }
151      private set {
152        if (variableNames != null) throw new InvalidOperationException();
153        variableNames = new List<string>(value);
154      }
155    }
156
157    #region Double
158    public IEnumerable<string> DoubleVariables {
159      get { return variableValues.Where(p => p.Value is List<double>).Select(p => p.Key); }
160    }
161
162    public IEnumerable<double> GetDoubleValues(string variableName) {
163      IList list;
164      if (!variableValues.TryGetValue(variableName, out list))
165        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
166      List<double> values = list as List<double>;
167      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a double variable.");
168
169      //mkommend yield return used to enable lazy evaluation
170      foreach (double value in values)
171        yield return value;
172    }
173    public ReadOnlyCollection<double> GetReadOnlyDoubleValues(string variableName) {
174      IList list;
175      if (!variableValues.TryGetValue(variableName, out list))
176        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
177      List<double> values = list as List<double>;
178      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a double variable.");
179      return values.AsReadOnly();
180    }
181    public double GetDoubleValue(string variableName, int row) {
182      IList list;
183      if (!variableValues.TryGetValue(variableName, out list))
184        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
185      List<double> values = list as List<double>;
186      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a double variable.");
187      return values[row];
188    }
189    public IEnumerable<double> GetDoubleValues(string variableName, IEnumerable<int> rows) {
190      IList list;
191      if (!variableValues.TryGetValue(variableName, out list))
192        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
193      List<double> values = list as List<double>;
194      if (values == null) throw new ArgumentException("The varialbe " + variableName + " is not a double variable.");
195
196      foreach (int index in rows)
197        yield return values[index];
198    }
199    #endregion
200
201    #region String
202    public IEnumerable<string> StringVariables {
203      get { return variableValues.Where(p => p.Value is List<string>).Select(p => p.Key); }
204    }
205
206    public IEnumerable<string> GetStringValues(string variableName) {
207      IList list;
208      if (!variableValues.TryGetValue(variableName, out list))
209        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
210      List<string> values = list as List<string>;
211      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a string variable.");
212
213      //mkommend yield return used to enable lazy evaluation
214      foreach (string value in values)
215        yield return value;
216    }
217    public ReadOnlyCollection<string> GetReadOnlyStringValues(string variableName) {
218      IList list;
219      if (!variableValues.TryGetValue(variableName, out list))
220        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
221      List<string> values = list as List<string>;
222      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a string variable.");
223      return values.AsReadOnly();
224    }
225    public string GetStringValue(string variableName, int row) {
226      IList list;
227      if (!variableValues.TryGetValue(variableName, out list))
228        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
229      List<string> values = list as List<string>;
230      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a string variable.");
231      return values[row];
232    }
233    public IEnumerable<string> GetStringValues(string variableName, IEnumerable<int> rows) {
234      IList list;
235      if (!variableValues.TryGetValue(variableName, out list))
236        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
237      List<string> values = list as List<string>;
238      if (values == null) throw new ArgumentException("The varialbe " + variableName + " is not a string variable.");
239
240      foreach (int index in rows)
241        yield return values[index];
242    }
243    #endregion
244
245    #region DateTime
246    public IEnumerable<string> DateTimeVariables {
247      get { return variableValues.Where(p => p.Value is List<DateTime>).Select(p => p.Key); }
248    }
249
250    public IEnumerable<DateTime> GetDateTimeValues(string variableName) {
251      IList list;
252      if (!variableValues.TryGetValue(variableName, out list))
253        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
254      List<DateTime> values = list as List<DateTime>;
255      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a DateTime variable.");
256
257      //mkommend yield return used to enable lazy evaluation
258      foreach (DateTime value in values)
259        yield return value;
260    }
261    public ReadOnlyCollection<DateTime> GetReadOnlyDateTimeValues(string variableName) {
262      IList list;
263      if (!variableValues.TryGetValue(variableName, out list))
264        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
265      List<DateTime> values = list as List<DateTime>;
266      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a DateTime variable.");
267      return values.AsReadOnly();
268    }
269    public DateTime GetDateTimeValue(string variableName, int row) {
270      IList list;
271      if (!variableValues.TryGetValue(variableName, out list))
272        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
273      List<DateTime> values = list as List<DateTime>;
274      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a DateTime variable.");
275      return values[row];
276    }
277    public IEnumerable<DateTime> GetDateTimeValues(string variableName, IEnumerable<int> rows) {
278      IList list;
279      if (!variableValues.TryGetValue(variableName, out list))
280        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
281      List<DateTime> values = list as List<DateTime>;
282      if (values == null) throw new ArgumentException("The varialbe " + variableName + " is not a DateTime variable.");
283
284      foreach (int index in rows)
285        yield return values[index];
286    }
287    #endregion
288
289    #region IStringConvertibleMatrix Members
290    [Storable]
291    private int rows;
292    public int Rows {
293      get { return rows; }
294      set { throw new NotSupportedException(); }
295    }
296    public int Columns {
297      get { return variableNames.Count; }
298      set { throw new NotSupportedException(); }
299    }
300
301    public bool SortableView {
302      get { return false; }
303      set { throw new NotSupportedException(); }
304    }
305    public bool ReadOnly {
306      get { return true; }
307    }
308
309    IEnumerable<string> IStringConvertibleMatrix.ColumnNames {
310      get { return this.VariableNames; }
311      set { throw new NotSupportedException(); }
312    }
313    IEnumerable<string> IStringConvertibleMatrix.RowNames {
314      get { return Enumerable.Empty<string>(); }
315      set { throw new NotSupportedException(); }
316    }
317
318    public string GetValue(int rowIndex, int columnIndex) {
319      return variableValues[variableNames[columnIndex]][rowIndex].ToString();
320    }
321    public bool SetValue(string value, int rowIndex, int columnIndex) {
322      throw new NotSupportedException();
323    }
324    public bool Validate(string value, out string errorMessage) {
325      throw new NotSupportedException();
326    }
327
328    public event EventHandler ColumnsChanged { add { } remove { } }
329    public event EventHandler RowsChanged { add { } remove { } }
330    public event EventHandler ColumnNamesChanged { add { } remove { } }
331    public event EventHandler RowNamesChanged { add { } remove { } }
332    public event EventHandler SortableViewChanged { add { } remove { } }
333    public event EventHandler<EventArgs<int, int>> ItemChanged { add { } remove { } }
334    public event EventHandler Reset { add { } remove { } }
335    #endregion
336  }
337}
Note: See TracBrowser for help on using the repository browser.