Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2719_HeuristicLab.DatastreamAnalysis/HeuristicLab.Problems.DataAnalysis/3.4/Dataset.cs @ 15838

Last change on this file since 15838 was 15030, checked in by jzenisek, 8 years ago

#2719 merged with trunk (revision 15029)

File size: 12.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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 values = variableValues.ElementAt(i);
81        this.variableValues.Add(this.variableNames[i], values);
82      }
83    }
84
85    public Dataset(IEnumerable<string> variableNames, double[,] variableValues) {
86      Name = "-";
87      if (variableNames.Count() != variableValues.GetLength(1)) {
88        throw new ArgumentException("Number of variable names doesn't match the number of columns of variableValues");
89      }
90      if (variableNames.Distinct().Count() != variableNames.Count()) {
91        var duplicateVariableNames = variableNames.GroupBy(v => v).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
92        string message = "The dataset cannot contain duplicate variables names: " + Environment.NewLine;
93        foreach (var duplicateVariableName in duplicateVariableNames)
94          message += duplicateVariableName + Environment.NewLine;
95        throw new ArgumentException(message);
96      }
97
98      rows = variableValues.GetLength(0);
99      this.variableNames = new List<string>(variableNames);
100
101      this.variableValues = new Dictionary<string, IList>(variableValues.GetLength(1));
102      for (int col = 0; col < variableValues.GetLength(1); col++) {
103        string columName = this.variableNames[col];
104        var values = new List<double>(variableValues.GetLength(0));
105        for (int row = 0; row < variableValues.GetLength(0); row++) {
106          values.Add(variableValues[row, col]);
107        }
108        this.variableValues.Add(columName, values);
109      }
110    }
111
112    public ModifiableDataset ToModifiable() {
113      var values = new List<IList>();
114      foreach (var v in variableNames) {
115        if (VariableHasType<double>(v)) {
116          values.Add(new List<double>((IList<double>)variableValues[v]));
117        } else if (VariableHasType<string>(v)) {
118          values.Add(new List<string>((IList<string>)variableValues[v]));
119        } else if (VariableHasType<DateTime>(v)) {
120          values.Add(new List<DateTime>((IList<DateTime>)variableValues[v]));
121        } else {
122          throw new ArgumentException("Unknown variable type.");
123        }
124      }
125      return new ModifiableDataset(variableNames, values);
126    }
127    /// <summary>
128    /// Shuffle a dataset's rows
129    /// </summary>
130    /// <param name="random">Random number generator used for shuffling.</param>
131    /// <returns>A shuffled copy of the current dataset.</returns>
132    public Dataset Shuffle(IRandom random) {
133      var values = variableNames.Select(x => variableValues[x]).ToList();
134      return new Dataset(variableNames, values.ShuffleLists(random));
135    }
136
137    protected Dataset(Dataset dataset) : this(dataset.variableNames, dataset.variableValues.Values) { }
138
139    #region Backwards compatible code, remove with 3.5
140    private double[,] storableData;
141    //name alias used to suppport backwards compatibility
142    [Storable(Name = "data", AllowOneWay = true)]
143    private double[,] StorableData { set { storableData = value; } }
144
145    [StorableHook(HookType.AfterDeserialization)]
146    private void AfterDeserialization() {
147      if (variableValues == null) {
148        rows = storableData.GetLength(0);
149        variableValues = new Dictionary<string, IList>();
150        for (int col = 0; col < storableData.GetLength(1); col++) {
151          string columName = variableNames[col];
152          var values = new List<double>(rows);
153          for (int row = 0; row < rows; row++) {
154            values.Add(storableData[row, col]);
155          }
156          variableValues.Add(columName, values);
157        }
158        storableData = null;
159      }
160    }
161    #endregion
162
163    [Storable(Name = "VariableValues")]
164    protected Dictionary<string, IList> variableValues;
165
166    protected List<string> variableNames;
167    [Storable]
168    public IEnumerable<string> VariableNames {
169      get { return variableNames; }
170      protected set {
171        if (variableNames != null) throw new InvalidOperationException();
172        variableNames = new List<string>(value);
173      }
174    }
175    public IEnumerable<string> DoubleVariables {
176      get { return variableValues.Where(p => p.Value is IList<double>).Select(p => p.Key); }
177    }
178
179    public IEnumerable<string> StringVariables {
180      get { return variableValues.Where(p => p.Value is IList<string>).Select(p => p.Key); }
181    }
182
183    public IEnumerable<double> GetDoubleValues(string variableName) {
184      return GetValues<double>(variableName);
185    }
186    public IEnumerable<string> GetStringValues(string variableName) {
187      return GetValues<string>(variableName);
188    }
189    public IEnumerable<DateTime> GetDateTimeValues(string variableName) {
190      return GetValues<DateTime>(variableName);
191    }
192
193    public ReadOnlyCollection<double> GetReadOnlyDoubleValues(string variableName) {
194      var values = GetValues<double>(variableName);
195      return new ReadOnlyCollection<double>(values);
196    }
197    public double GetDoubleValue(string variableName, int row) {
198      var values = GetValues<double>(variableName);
199      return values[row];
200    }
201    public IEnumerable<double> GetDoubleValues(string variableName, IEnumerable<int> rows) {
202      return GetValues<double>(variableName, rows);
203    }
204
205    public string GetStringValue(string variableName, int row) {
206      var values = GetValues<string>(variableName);
207      return values[row];
208    }
209
210    public IEnumerable<string> GetStringValues(string variableName, IEnumerable<int> rows) {
211      return GetValues<string>(variableName, rows);
212    }
213    public ReadOnlyCollection<string> GetReadOnlyStringValues(string variableName) {
214      var values = GetValues<string>(variableName);
215      return new ReadOnlyCollection<string>(values);
216    }
217
218    private IEnumerable<T> GetValues<T>(string variableName, IEnumerable<int> rows) {
219      var values = GetValues<T>(variableName);
220      return rows.Select(x => values[x]);
221    }
222    private IList<T> GetValues<T>(string variableName) {
223      IList list;
224      if (!variableValues.TryGetValue(variableName, out list))
225        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
226      IList<T> values = list as IList<T>;
227      if (values == null) throw new ArgumentException("The variable " + variableName + " is not a " + typeof(T) + " variable.");
228      return values;
229    }
230    public bool VariableHasType<T>(string variableName) {
231      return variableValues[variableName] is IList<T>;
232    }
233
234    #region IStringConvertibleMatrix Members
235    [Storable]
236    protected int rows;
237    public int Rows {
238      get { return rows; }
239    }
240    int IStringConvertibleMatrix.Rows {
241      get { return Rows; }
242      set { throw new NotSupportedException(); }
243    }
244
245    public int Columns {
246      get { return variableNames.Count; }
247    }
248    int IStringConvertibleMatrix.Columns {
249      get { return Columns; }
250      set { throw new NotSupportedException(); }
251    }
252    bool IStringConvertibleMatrix.SortableView {
253      get { return false; }
254      set { throw new NotSupportedException(); }
255    }
256    bool IStringConvertibleMatrix.ReadOnly {
257      get { return true; }
258    }
259    IEnumerable<string> IStringConvertibleMatrix.ColumnNames {
260      get { return this.VariableNames; }
261      set { throw new NotSupportedException(); }
262    }
263    IEnumerable<string> IStringConvertibleMatrix.RowNames {
264      get { return Enumerable.Empty<string>(); }
265      set { throw new NotSupportedException(); }
266    }
267    string IStringConvertibleMatrix.GetValue(int rowIndex, int columnIndex) {
268      return variableValues[variableNames[columnIndex]][rowIndex].ToString();
269    }
270    bool IStringConvertibleMatrix.SetValue(string value, int rowIndex, int columnIndex) {
271      throw new NotSupportedException();
272    }
273    bool IStringConvertibleMatrix.Validate(string value, out string errorMessage) {
274      throw new NotSupportedException();
275    }
276
277    public virtual event EventHandler ColumnsChanged { add { } remove { } }
278    public virtual event EventHandler RowsChanged { add { } remove { } }
279    public virtual event EventHandler ColumnNamesChanged { add { } remove { } }
280    public virtual event EventHandler RowNamesChanged { add { } remove { } }
281    public virtual event EventHandler SortableViewChanged { add { } remove { } }
282    public virtual event EventHandler<EventArgs<int, int>> ItemChanged { add { } remove { } }
283    public virtual event EventHandler Reset { add { } remove { } }
284    #endregion
285  }
286}
Note: See TracBrowser for help on using the repository browser.