Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Problems.DataAnalysis/3.4/Dataset.cs @ 15160

Last change on this file since 15160 was 13539, checked in by mkommend, 9 years ago

#2536: Implemented rows and columns explicitly in the Dataset.

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