Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.DataAnalysis/Dataset.cs @ 238

Last change on this file since 238 was 237, checked in by gkronber, 17 years ago

implemented #147

File size: 11.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Generic;
24using System.Xml;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
27using System.Globalization;
28using System.Text;
29
30namespace HeuristicLab.DataAnalysis {
31  public sealed class Dataset : ItemBase {
32
33    private string name;
34    public string Name {
35      get { return name; }
36      set { name = value; }
37    }
38
39    private double[] samples;
40    private int rows;
41    private Dictionary<int, Dictionary<int, double>>[] cachedMeans;
42    private Dictionary<int, Dictionary<int, double>>[] cachedRanges;
43    private double[] scalingFactor;
44    private double[] scalingOffset;
45
46    public int Rows {
47      get { return rows; }
48      set { rows = value; }
49    }
50    private int columns;
51
52    public int Columns {
53      get { return columns; }
54      set { columns = value; }
55    }
56
57    public double GetValue(int i, int j) {
58      return samples[columns * i + j];
59    }
60
61    public void SetValue(int i, int j, double v) {
62      if(v != samples[columns * i + j]) {
63        samples[columns * i + j] = v;
64        CreateDictionaries();
65        FireChanged();
66      }
67    }
68
69    public double[] Samples {
70      get { return samples; }
71      set {
72        scalingFactor = new double[columns];
73        scalingOffset = new double[columns];
74        for(int i = 0; i < scalingFactor.Length; i++) {
75          scalingFactor[i] = 1.0;
76          scalingOffset[i] = 0.0;
77        }
78        samples = value;
79        CreateDictionaries();
80        FireChanged();
81      }
82    }
83
84    private string[] variableNames;
85    public string[] VariableNames {
86      get { return variableNames; }
87      set { variableNames = value; }
88    }
89
90    public Dataset() {
91      Name = "-";
92      VariableNames = new string[] { "Var0" };
93      Columns = 1;
94      Rows = 1;
95      Samples = new double[1];
96      scalingOffset = new double[] { 0.0 };
97      scalingFactor = new double[] { 1.0 };
98    }
99
100    private void CreateDictionaries() {
101      // keep a means and ranges dictionary for each column (possible target variable) of the dataset.
102      cachedMeans = new Dictionary<int, Dictionary<int, double>>[columns];
103      cachedRanges = new Dictionary<int, Dictionary<int, double>>[columns];
104      for(int i = 0; i < columns; i++) {
105        cachedMeans[i] = new Dictionary<int, Dictionary<int, double>>();
106        cachedRanges[i] = new Dictionary<int, Dictionary<int, double>>();
107      }
108    }
109
110    public override IView CreateView() {
111      return new DatasetView(this);
112    }
113
114    public override object Clone(IDictionary<Guid, object> clonedObjects) {
115      Dataset clone = new Dataset();
116      clonedObjects.Add(Guid, clone);
117      double[] cloneSamples = new double[rows * columns];
118      Array.Copy(samples, cloneSamples, samples.Length);
119      clone.rows = rows;
120      clone.columns = columns;
121      clone.Samples = cloneSamples;
122      clone.Name = Name;
123      clone.VariableNames = new string[VariableNames.Length];
124      Array.Copy(VariableNames, clone.VariableNames, VariableNames.Length);
125      Array.Copy(scalingFactor, clone.scalingFactor, columns);
126      Array.Copy(scalingOffset, clone.scalingOffset, columns);
127      return clone;
128    }
129
130    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
131      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
132      XmlAttribute problemName = document.CreateAttribute("Name");
133      problemName.Value = Name;
134      node.Attributes.Append(problemName);
135      XmlAttribute dim1 = document.CreateAttribute("Dimension1");
136      dim1.Value = rows.ToString(CultureInfo.InvariantCulture.NumberFormat);
137      node.Attributes.Append(dim1);
138      XmlAttribute dim2 = document.CreateAttribute("Dimension2");
139      dim2.Value = columns.ToString(CultureInfo.InvariantCulture.NumberFormat);
140      node.Attributes.Append(dim2);
141      XmlAttribute variableNames = document.CreateAttribute("VariableNames");
142      variableNames.Value = GetVariableNamesString();
143      node.Attributes.Append(variableNames);
144      XmlAttribute scalingFactorsAttribute = document.CreateAttribute("ScalingFactors");
145      scalingFactorsAttribute.Value = GetString(scalingFactor);
146      node.Attributes.Append(scalingFactorsAttribute);
147      XmlAttribute scalingOffsetsAttribute = document.CreateAttribute("ScalingOffsets");
148      scalingOffsetsAttribute.Value = GetString(scalingOffset);
149      node.Attributes.Append(scalingOffsetsAttribute);
150      node.InnerText = ToString(CultureInfo.InvariantCulture.NumberFormat);
151      return node;
152    }
153
154    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
155      base.Populate(node, restoredObjects);
156      Name = node.Attributes["Name"].Value;
157      rows = int.Parse(node.Attributes["Dimension1"].Value, CultureInfo.InvariantCulture.NumberFormat);
158      columns = int.Parse(node.Attributes["Dimension2"].Value, CultureInfo.InvariantCulture.NumberFormat);
159
160      VariableNames = ParseVariableNamesString(node.Attributes["VariableNames"].Value);
161      if(node.Attributes["ScalingFactors"] != null)
162        scalingFactor = ParseDoubleString(node.Attributes["ScalingFactors"].Value);
163      else {
164        scalingFactor = new double[columns]; // compatibility with old serialization format
165        for(int i = 0; i < scalingFactor.Length; i++) scalingFactor[i] = 1.0;
166      }
167      if(node.Attributes["ScalingOffsets"] != null)
168        scalingOffset = ParseDoubleString(node.Attributes["ScalingOffsets"].Value);
169      else {
170        scalingOffset = new double[columns]; // compatibility with old serialization format
171        for(int i = 0; i < scalingOffset.Length; i++) scalingOffset[i] = 0.0;
172      }
173
174      string[] tokens = node.InnerText.Split(';');
175      if(tokens.Length != rows * columns) throw new FormatException();
176      samples = new double[rows * columns];
177      for(int row = 0; row < rows; row++) {
178        for(int column = 0; column < columns; column++) {
179          if(double.TryParse(tokens[row * columns + column], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out samples[row * columns + column]) == false) {
180            throw new FormatException("Can't parse " + tokens[row * columns + column] + " as double value.");
181          }
182        }
183      }
184      CreateDictionaries();
185    }
186
187    public override string ToString() {
188      return ToString(CultureInfo.CurrentCulture.NumberFormat);
189    }
190
191    private string ToString(NumberFormatInfo format) {
192      StringBuilder builder = new StringBuilder();
193      for(int row = 0; row < rows; row++) {
194        for(int column = 0; column < columns; column++) {
195          builder.Append(";");
196          builder.Append(samples[row * columns + column].ToString(format));
197        }
198      }
199      if(builder.Length > 0) builder.Remove(0, 1);
200      return builder.ToString();
201    }
202
203    private string GetVariableNamesString() {
204      string s = "";
205      for(int i = 0; i < variableNames.Length; i++) {
206        s += variableNames[i] + "; ";
207      }
208
209      if(variableNames.Length > 0) {
210        s = s.TrimEnd(';', ' ');
211      }
212      return s;
213    }
214    private string GetString(double[] xs) {
215      string s = "";
216      for(int i = 0; i < xs.Length; i++) {
217        s += xs[i].ToString(CultureInfo.InvariantCulture) + "; ";
218      }
219
220      if(xs.Length > 0) {
221        s = s.TrimEnd(';', ' ');
222      }
223      return s;
224    }
225
226    private string[] ParseVariableNamesString(string p) {
227      p = p.Trim();
228      string[] tokens = p.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
229      return tokens;
230    }
231    private double[] ParseDoubleString(string s) {
232      s = s.Trim();
233      string[] ss = s.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
234      double[] xs = new double[ss.Length];
235      for(int i = 0; i < xs.Length; i++) {
236        xs[i] = double.Parse(ss[i], CultureInfo.InvariantCulture);
237      }
238      return xs;
239    }
240
241    public double GetMean(int column) {
242      return GetMean(column, 0, Rows - 1);
243    }
244
245    public double GetMean(int column, int from, int to) {
246      if(!cachedMeans[column].ContainsKey(from) || !cachedMeans[column][from].ContainsKey(to)) {
247        double[] values = new double[to - from + 1];
248        for(int sample = from; sample <= to; sample++) {
249          values[sample - from] = GetValue(sample, column);
250        }
251        double mean = Statistics.Mean(values);
252        if(!cachedMeans[column].ContainsKey(from)) cachedMeans[column][from] = new Dictionary<int, double>();
253        cachedMeans[column][from][to] = mean;
254        return mean;
255      } else {
256        return cachedMeans[column][from][to];
257      }
258    }
259
260    public double GetRange(int column) {
261      return GetRange(column, 0, Rows - 1);
262    }
263
264    public double GetRange(int column, int from, int to) {
265      if(!cachedRanges[column].ContainsKey(from) || !cachedRanges[column][from].ContainsKey(to)) {
266        double[] values = new double[to - from + 1];
267        for(int sample = from; sample <= to; sample++) {
268          values[sample - from] = GetValue(sample, column);
269        }
270        double range = Statistics.Range(values);
271        if(!cachedRanges[column].ContainsKey(from)) cachedRanges[column][from] = new Dictionary<int, double>();
272        cachedRanges[column][from][to] = range;
273        return range;
274      } else {
275        return cachedRanges[column][from][to];
276      }
277    }
278
279    public double GetMaximum(int column) {
280      double max = Double.NegativeInfinity;
281      for(int i = 0; i < Rows; i++) {
282        double val = GetValue(i, column);
283        if(val > max) max = val;
284      }
285      return max;
286    }
287
288    public double GetMinimum(int column) {
289      double min = Double.PositiveInfinity;
290      for(int i = 0; i < Rows; i++) {
291        double val = GetValue(i, column);
292        if(val < min) min = val;
293      }
294      return min;
295    }
296
297    internal void ScaleVariable(int column) {
298      if(scalingFactor[column] == 1.0) {
299        double min = GetMinimum(column);
300        double max = GetMaximum(column);
301        double range = max - min;
302        scalingFactor[column] = range;
303        scalingOffset[column] = min;
304        for(int i = 0; i < Rows; i++) {
305          double origValue = samples[i * columns + column];
306          samples[i * columns + column] = (origValue - min) / range;
307        }
308      }
309      CreateDictionaries();
310      FireChanged();
311    }
312
313    internal void UnscaleVariable(int column) {
314      if(scalingFactor[column] != 1.0) {
315        for(int i = 0; i < rows; i++) {
316          double scaledValue = samples[i * columns + column];
317          samples[i * columns + column] = scaledValue * scalingFactor[column] + scalingOffset[column];
318        }
319        scalingFactor[column] = 1.0;
320        scalingOffset[column] = 0.0;
321      }
322    }
323  }
324}
Note: See TracBrowser for help on using the repository browser.