Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis/3.4/ModifiableDataset.cs @ 16120

Last change on this file since 16120 was 16120, checked in by mkommend, 6 years ago

#2939: Added utility methods GetRow and ClearValues in ModifiableDataset.

File size: 9.0 KB
Line 
1#region License Information
2
3/* HeuristicLab
4 * Copyright (C) 2002-2018 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
5 *
6 * This file is part of HeuristicLab.
7 *
8 * HeuristicLab is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * HeuristicLab is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#endregion
23
24using System;
25using System.Collections;
26using System.Collections.Generic;
27using System.Linq;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33namespace HeuristicLab.Problems.DataAnalysis {
34  [Item("ModifiableDataset", "Represents a dataset containing data that should be analyzed, which can be modified by adding or replacing variables and values.")]
35  [StorableClass]
36  public sealed class ModifiableDataset : Dataset, IStringConvertibleMatrix {
37    [StorableConstructor]
38    private ModifiableDataset(bool deserializing) : base(deserializing) { }
39
40    private ModifiableDataset(ModifiableDataset original, Cloner cloner) : base(original, cloner) {
41      variableNames = new List<string>(original.variableNames);
42      variableValues = CloneValues(original.variableValues);
43    }
44
45    public override IDeepCloneable Clone(Cloner cloner) { return new ModifiableDataset(this, cloner); }
46
47    public ModifiableDataset() { }
48
49    public ModifiableDataset(IEnumerable<string> variableNames, IEnumerable<IList> variableValues, bool cloneValues = false) :
50      base(variableNames, variableValues, cloneValues) { }
51
52    public Dataset ToDataset() {
53      return new Dataset(variableNames, variableNames.Select(v => variableValues[v]));
54    }
55
56
57    public IEnumerable<object> GetRow(int row) {
58      return variableValues.Select(x => x.Value[row]);
59    }
60
61    public void AddRow(IEnumerable<object> values) {
62      var list = values.ToList();
63      if (list.Count != variableNames.Count)
64        throw new ArgumentException("The number of values must be equal to the number of variable names.");
65      // check if all the values are of the correct type
66      for (int i = 0; i < list.Count; ++i) {
67        if (list[i].GetType() != GetVariableType(variableNames[i])) {
68          throw new ArgumentException("The type of the provided value does not match the variable type.");
69        }
70      }
71      // add values
72      for (int i = 0; i < list.Count; ++i) {
73        variableValues[variableNames[i]].Add(list[i]);
74      }
75      Rows++;
76      OnRowsChanged();
77      OnReset();
78    }
79
80    public void ReplaceRow(int row, IEnumerable<object> values) {
81      var list = values.ToList();
82      if (list.Count != variableNames.Count)
83        throw new ArgumentException("The number of values must be equal to the number of variable names.");
84      // check if all the values are of the correct type
85      for (int i = 0; i < list.Count; ++i) {
86        if (list[i].GetType() != GetVariableType(variableNames[i])) {
87          throw new ArgumentException("The type of the provided value does not match the variable type.");
88        }
89      }
90      // replace values
91      for (int i = 0; i < list.Count; ++i) {
92        variableValues[variableNames[i]][row] = list[i];
93      }
94      OnReset();
95    }
96
97    // slow, avoid using this
98    public void RemoveRow(int row) {
99      foreach (var list in variableValues.Values)
100        list.RemoveAt(row);
101      Rows--;
102      OnRowsChanged();
103      OnReset();
104    }
105
106    // adds a new variable to the dataset
107    public void AddVariable(string variableName, IList values) {
108      InsertVariable(variableName, Columns, values);
109    }
110
111    public void InsertVariable(string variableName, int position, IList values) {
112      if (variableValues.ContainsKey(variableName))
113        throw new ArgumentException(string.Format("Variable {0} is already present in the dataset.", variableName));
114
115      if (position < 0 || position > Columns)
116        throw new ArgumentException(string.Format("Incorrect position {0} specified. The position must be between 0 and {1}.", position, Columns));
117
118      if (values == null)
119        throw new ArgumentNullException("values", "Values must not be null. At least an empty list of values has to be provided.");
120
121      if (values.Count != Rows)
122        throw new ArgumentException(string.Format("{0} values are provided, but {1} rows are present in the dataset.", values.Count, Rows));
123
124      if (!IsAllowedType(values))
125        throw new ArgumentException(string.Format("Unsupported type {0} for variable {1}.", GetElementType(values), variableName));
126
127      variableNames.Insert(position, variableName);
128      variableValues[variableName] = values;
129
130      OnColumnsChanged();
131      OnColumnNamesChanged();
132      OnReset();
133    }
134
135    public void ReplaceVariable(string variableName, IList values) {
136      if (!variableValues.ContainsKey(variableName))
137        throw new ArgumentException(string.Format("Variable {0} is not present in the dataset.", variableName));
138      if (values.Count != variableValues[variableName].Count)
139        throw new ArgumentException("The number of values must coincide with the number of dataset rows.");
140      if (GetVariableType(variableName) != values[0].GetType())
141        throw new ArgumentException("The type of the provided value does not match the variable type.");
142      variableValues[variableName] = values;
143    }
144
145
146    public void RemoveVariable(string variableName) {
147      if (!variableValues.ContainsKey(variableName))
148        throw new ArgumentException(string.Format("The variable {0} does not exist in the dataset.", variableName));
149      variableValues.Remove(variableName);
150      variableNames.Remove(variableName);
151      OnColumnsChanged();
152      OnColumnNamesChanged();
153      OnReset();
154    }
155
156    public void ClearValues() {
157      foreach (var list in variableValues.Values) {
158        list.Clear();
159      }
160      Rows = 0;
161      OnRowsChanged();
162      OnReset();
163    }
164
165
166    public void SetVariableValue(object value, string variableName, int row) {
167      IList list;
168      variableValues.TryGetValue(variableName, out list);
169      if (list == null)
170        throw new ArgumentException("The variable " + variableName + " does not exist in the dataset.");
171      if (row < 0 || list.Count < row)
172        throw new ArgumentOutOfRangeException("Invalid row value");
173      if (GetVariableType(variableName) != value.GetType())
174        throw new ArgumentException("The type of the provided value does not match the variable type.");
175
176      list[row] = value;
177      OnItemChanged(row, variableNames.IndexOf(variableName));
178    }
179
180    bool IStringConvertibleMatrix.SetValue(string value, int rowIndex, int columnIndex) {
181      var variableName = variableNames[columnIndex];
182      // if value represents a double
183      double dv;
184      if (double.TryParse(value, out dv)) {
185        SetVariableValue(dv, variableName, rowIndex);
186        return true;
187      }
188      // if value represents a DateTime object
189      DateTime dt;
190      if (DateTime.TryParse(value, out dt)) {
191        SetVariableValue(dt, variableName, rowIndex);
192        return true;
193      }
194      // if value is simply a string
195      SetVariableValue(value, variableName, rowIndex);
196      return true;
197    }
198
199    bool IStringConvertibleMatrix.Validate(string value, out string errorMessage) {
200      errorMessage = string.Empty;
201      return true;
202    }
203
204    #region event handlers
205    public override event EventHandler RowsChanged;
206    private void OnRowsChanged() {
207      var handler = RowsChanged;
208      if (handler != null)
209        handler(this, EventArgs.Empty);
210    }
211
212    public override event EventHandler ColumnsChanged;
213    private void OnColumnsChanged() {
214      var handler = ColumnsChanged;
215      if (handler != null)
216        handler(this, EventArgs.Empty);
217    }
218
219    public override event EventHandler ColumnNamesChanged;
220    private void OnColumnNamesChanged() {
221      var handler = ColumnNamesChanged;
222      if (handler != null)
223        handler(this, EventArgs.Empty);
224    }
225
226    public override event EventHandler Reset;
227    private void OnReset() {
228      var handler = Reset;
229      if (handler != null)
230        handler(this, EventArgs.Empty);
231    }
232
233    public override event EventHandler<EventArgs<int, int>> ItemChanged;
234    private void OnItemChanged(int rowIndex, int columnIndex) {
235      var handler = ItemChanged;
236      if (handler != null) {
237        handler(this, new EventArgs<int, int>(rowIndex, columnIndex));
238      }
239    }
240    #endregion
241  }
242}
Note: See TracBrowser for help on using the repository browser.