Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 232 was 232, checked in by gkronber, 16 years ago

implemented #144

File size: 8.5 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    Dictionary<int, Dictionary<int, double>>[] cachedMeans;
42    Dictionary<int, Dictionary<int, double>>[] cachedRanges;
43
44    public int Rows {
45      get { return rows; }
46      set { rows = value; }
47    }
48    private int columns;
49
50    public int Columns {
51      get { return columns; }
52      set { columns = value; }
53    }
54
55    public double GetValue(int i, int j) {
56      return samples[columns * i + j];
57    }
58
59    public void SetValue(int i, int j, double v) {
60      if(v != samples[columns * i + j]) {
61        samples[columns * i + j] = v;
62        CreateDictionaries();
63        FireChanged();
64      }
65    }
66
67    public double[] Samples {
68      get { return samples; }
69      set {
70        samples = value;
71        CreateDictionaries();
72        FireChanged();
73      }
74    }
75
76    private string[] variableNames;
77    public string[] VariableNames {
78      get { return variableNames; }
79      set { variableNames = value; }
80    }
81
82    public Dataset() {
83      Name = "-";
84      VariableNames = new string[] {"Var0"};
85      Columns = 1;
86      Rows = 1;
87      Samples = new double[1];
88    }
89
90    private void CreateDictionaries() {
91      // keep a means and ranges dictionary for each column (possible target variable) of the dataset.
92
93      cachedMeans = new Dictionary<int, Dictionary<int, double>>[columns];
94      cachedRanges = new Dictionary<int, Dictionary<int, double>>[columns];
95
96      for(int i = 0; i < columns; i++) {
97        cachedMeans[i] = new Dictionary<int, Dictionary<int, double>>();
98        cachedRanges[i] = new Dictionary<int, Dictionary<int, double>>();
99      }
100    }
101
102    public override IView CreateView() {
103      return new DatasetView(this);
104    }
105
106    public override object Clone(IDictionary<Guid, object> clonedObjects) {
107      Dataset clone = new Dataset();
108      clonedObjects.Add(Guid, clone);
109      double[] cloneSamples = new double[rows * columns];
110      Array.Copy(samples, cloneSamples, samples.Length);
111      clone.rows = rows;
112      clone.columns = columns;
113      clone.Samples = cloneSamples;
114      clone.Name = Name;
115      clone.VariableNames = new string[VariableNames.Length];
116      Array.Copy(VariableNames, clone.VariableNames, VariableNames.Length);
117      return clone;
118    }
119
120    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
121      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
122      XmlAttribute problemName = document.CreateAttribute("Name");
123      problemName.Value = Name;
124      node.Attributes.Append(problemName);
125      XmlAttribute dim1 = document.CreateAttribute("Dimension1");
126      dim1.Value = rows.ToString(CultureInfo.InvariantCulture.NumberFormat);
127      node.Attributes.Append(dim1);
128      XmlAttribute dim2 = document.CreateAttribute("Dimension2");
129      dim2.Value = columns.ToString(CultureInfo.InvariantCulture.NumberFormat);
130      node.Attributes.Append(dim2);
131
132      XmlAttribute variableNames = document.CreateAttribute("VariableNames");
133      variableNames.Value = GetVariableNamesString();
134      node.Attributes.Append(variableNames);
135
136      node.InnerText = ToString(CultureInfo.InvariantCulture.NumberFormat);
137      return node;
138    }
139
140    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
141      base.Populate(node, restoredObjects);
142      Name = node.Attributes["Name"].Value;
143      rows = int.Parse(node.Attributes["Dimension1"].Value, CultureInfo.InvariantCulture.NumberFormat);
144      columns = int.Parse(node.Attributes["Dimension2"].Value, CultureInfo.InvariantCulture.NumberFormat);
145     
146      VariableNames = ParseVariableNamesString(node.Attributes["VariableNames"].Value);
147
148      string[] tokens = node.InnerText.Split(';');
149      if(tokens.Length != rows * columns) throw new FormatException();
150      samples = new double[rows * columns];
151      for(int row = 0; row < rows; row++) {
152        for(int column = 0; column < columns; column++) {
153          if(double.TryParse(tokens[row * columns + column], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out samples[row*columns + column]) == false) {
154            throw new FormatException("Can't parse " + tokens[row * columns + column] + " as double value.");
155          }
156        }
157      }
158      CreateDictionaries();
159    }
160
161    public override string ToString() {
162      return ToString(CultureInfo.CurrentCulture.NumberFormat);
163    }
164
165    private string ToString(NumberFormatInfo format) {
166      StringBuilder builder = new StringBuilder();
167      for(int row = 0; row < rows; row++) {
168        for(int column = 0; column < columns; column++) {
169          builder.Append(";");
170          builder.Append(samples[row*columns+column].ToString(format));
171        }
172      }
173      if(builder.Length > 0) builder.Remove(0, 1);
174      return builder.ToString();
175    }
176
177    private string GetVariableNamesString() {
178      string s = "";
179      for (int i = 0; i < variableNames.Length; i++) {
180        s += variableNames[i] + "; ";
181      }
182
183      if (variableNames.Length > 0) {
184        s = s.TrimEnd(';', ' ');
185      }
186      return s;
187    }
188
189    private string[] ParseVariableNamesString(string p) {
190      p = p.Trim();
191      string[] tokens = p.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
192      return tokens;
193    }
194
195    public double GetMean(int column) {
196      return GetMean(column, 0, Rows-1);
197    }
198
199    public double GetMean(int column, int from, int to) {
200      if(!cachedMeans[column].ContainsKey(from) || !cachedMeans[column][from].ContainsKey(to)) {
201        double[] values = new double[to - from + 1];
202        for(int sample = from; sample <= to; sample++) {
203          values[sample - from] = GetValue(sample, column);
204        }
205        double mean = Statistics.Mean(values);
206        if(!cachedMeans[column].ContainsKey(from)) cachedMeans[column][from] = new Dictionary<int, double>();
207        cachedMeans[column][from][to] = mean;
208        return mean;
209      } else {
210        return cachedMeans[column][from][to];
211      }
212    }
213
214    public double GetRange(int column) {
215      return GetRange(column, 0, Rows-1);
216    }
217
218    public double GetRange(int column, int from, int to) {
219      if(!cachedRanges[column].ContainsKey(from) || !cachedRanges[column][from].ContainsKey(to)) {
220        double[] values = new double[to - from + 1];
221        for(int sample = from; sample <= to; sample++) {
222          values[sample - from] = GetValue(sample, column);
223        }
224        double range = Statistics.Range(values);
225        if(!cachedRanges[column].ContainsKey(from)) cachedRanges[column][from] = new Dictionary<int, double>();
226        cachedRanges[column][from][to] = range;
227        return range;
228      } else {
229        return cachedRanges[column][from][to];
230      }
231    }
232
233    public double GetMaximum(int column) {
234      double max = Double.NegativeInfinity;
235      for(int i = 0; i < Rows; i++) {
236        double val = GetValue(i, column);
237        if(val > max) max = val;
238      }
239      return max;
240    }
241
242    public double GetMinimum(int column) {
243      double min = Double.PositiveInfinity;
244      for(int i = 0; i < Rows; i++) {
245        double val = GetValue(i, column);
246        if(val < min) min = val;
247      }
248      return min;
249    }
250  }
251}
Note: See TracBrowser for help on using the repository browser.