Free cookie consent management tool by TermsFeed Policy Generator

source: branches/XmlTextWriterBranch/HeuristicLab.DataAnalysis/Dataset.cs @ 160

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

created a branch that uses XmlTextWriter instead of XMLDocument to save documents. Investigating ticket #103.

File size: 10.0 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 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
42    public int Rows {
43      get { return rows; }
44      set { rows = value; }
45    }
46    private int columns;
47
48    public int Columns {
49      get { return columns; }
50      set { columns = value; }
51    }
52    private Dictionary<int, double[]>[] ranges;
53    private Dictionary<int, double[]>[] means;
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        FireChanged();
63      }
64    }
65
66    public double[] Samples {
67      get { return samples; }
68      set {
69        samples = value;
70        CreateDictionaries();
71        FireChanged();
72      }
73    }
74
75    private string[] variableNames;
76    public string[] VariableNames {
77      get { return variableNames; }
78      set { variableNames = value; }
79    }
80
81    public Dataset() {
82      Name = "-";
83      VariableNames = new string[] {"Var0"};
84      Columns = 1;
85      Rows = 1;
86      Samples = new double[1];
87    }
88
89    void samples_Changed(object sender, EventArgs e) {
90      CreateDictionaries();
91    }
92
93    private void CreateDictionaries() {
94      // keep a means and ranges dictionary for each column (possible target variable) of the dataset.
95
96      means = new Dictionary<int, double[]>[columns];
97      ranges = new Dictionary<int, double[]>[columns];
98
99      for(int i = 0; i < columns; i++) {
100        means[i] = new Dictionary<int, double[]>();
101        ranges[i] = new Dictionary<int, double[]>();
102      }
103    }
104
105    public override IView CreateView() {
106      return new DatasetView(this);
107    }
108
109    public override object Clone(IDictionary<Guid, object> clonedObjects) {
110      Dataset clone = new Dataset();
111      clonedObjects.Add(Guid, clone);
112      double[] cloneSamples = new double[rows * columns];
113      Array.Copy(samples, cloneSamples, samples.Length);
114      clone.rows = rows;
115      clone.columns = columns;
116      clone.Samples = cloneSamples;
117      clone.Name = Name;
118      clone.VariableNames = new string[VariableNames.Length];
119      Array.Copy(VariableNames, clone.VariableNames, VariableNames.Length);
120      return clone;
121    }
122
123    //public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
124    //  XmlNode node = base.GetXmlNode(name, document, persistedObjects);
125    //  XmlAttribute problemName = document.CreateAttribute("Name");
126    //  problemName.Value = Name;
127    //  node.Attributes.Append(problemName);
128    //  XmlAttribute dim1 = document.CreateAttribute("Dimension1");
129    //  dim1.Value = rows.ToString(CultureInfo.InvariantCulture.NumberFormat);
130    //  node.Attributes.Append(dim1);
131    //  XmlAttribute dim2 = document.CreateAttribute("Dimension2");
132    //  dim2.Value = columns.ToString(CultureInfo.InvariantCulture.NumberFormat);
133    //  node.Attributes.Append(dim2);
134
135    //  XmlAttribute variableNames = document.CreateAttribute("VariableNames");
136    //  variableNames.Value = GetVariableNamesString();
137    //  node.Attributes.Append(variableNames);
138
139    //  node.InnerText = ToString(CultureInfo.InvariantCulture.NumberFormat);
140    //  return node;
141    //}
142    public override void Persist(string name, XmlWriter writer, IDictionary<Guid, IStorable> persistedObjects) {
143      base.Persist(name, writer, persistedObjects);
144      writer.WriteAttributeString("Name", Name);
145      writer.WriteAttributeString("Dimension1", rows.ToString(CultureInfo.InvariantCulture.NumberFormat));
146      writer.WriteAttributeString("Dimension2", columns.ToString(CultureInfo.InvariantCulture.NumberFormat));
147      writer.WriteAttributeString("VariableNames", GetVariableNamesString());
148      writer.WriteValue(ToString(CultureInfo.InvariantCulture.NumberFormat));
149    }
150
151    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
152      base.Populate(node, restoredObjects);
153      Name = node.Attributes["Name"].Value;
154      rows = int.Parse(node.Attributes["Dimension1"].Value, CultureInfo.InvariantCulture.NumberFormat);
155      columns = int.Parse(node.Attributes["Dimension2"].Value, CultureInfo.InvariantCulture.NumberFormat);
156     
157      VariableNames = ParseVariableNamesString(node.Attributes["VariableNames"].Value);
158
159      string[] tokens = node.InnerText.Split(';');
160      if(tokens.Length != rows * columns) throw new FormatException();
161      samples = new double[rows * columns];
162      for(int row = 0; row < rows; row++) {
163        for(int column = 0; column < columns; column++) {
164          if(double.TryParse(tokens[row * columns + column], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out samples[row*columns + column]) == false) {
165            throw new FormatException("Can't parse " + tokens[row * columns + column] + " as double value.");
166          }
167        }
168      }
169      CreateDictionaries();
170    }
171
172    public override string ToString() {
173      return ToString(CultureInfo.CurrentCulture.NumberFormat);
174    }
175
176    private string ToString(NumberFormatInfo format) {
177      StringBuilder builder = new StringBuilder();
178      for(int row = 0; row < rows; row++) {
179        for(int column = 0; column < columns; column++) {
180          builder.Append(";");
181          builder.Append(samples[row*columns+column].ToString(format));
182        }
183      }
184      if(builder.Length > 0) builder.Remove(0, 1);
185      return builder.ToString();
186    }
187
188    private string GetVariableNamesString() {
189      string s = "";
190      for (int i = 0; i < variableNames.Length; i++) {
191        s += variableNames[i] + "; ";
192      }
193
194      if (variableNames.Length > 0) {
195        s = s.TrimEnd(';', ' ');
196      }
197      return s;
198    }
199
200    private string[] ParseVariableNamesString(string p) {
201      p = p.Trim();
202      string[] tokens = p.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries);
203      return tokens;
204    }
205
206
207    // return value of GetMean should be memoized because it is called repeatedly in Evaluators
208    public double GetMean(int column, int from, int to) {
209      Dictionary<int, double[]> columnMeans = means[column];
210      if(columnMeans.ContainsKey(from)) {
211        double[] fromMeans = columnMeans[from];
212        if(fromMeans[to-from] >= 0.0) {
213          // already calculated
214          return fromMeans[to-from];
215        } else {
216          // not yet calculated => calculate
217          fromMeans[to-from] = CalculateMean(column, from, to);
218          return fromMeans[to-from];
219        }
220      } else {
221        // never saw this from-index => create a new array, initialize and recalculate for to-index
222        double[] fromMeans = new double[rows - from];
223        // fill with negative values to indicate which means have already been calculated
224        for(int i=0;i<fromMeans.Length;i++) {fromMeans[i] = -1.0;}
225        // store new array in the dictionary
226        columnMeans[from] = fromMeans;
227        // calculate for specific to-index
228        fromMeans[to-from] = CalculateMean(column, from, to);
229        return fromMeans[to-from];
230      }
231    }
232
233    private double CalculateMean(int column, int from, int to) {
234      double[] values = new double[to - from +1];
235      for(int sample = from; sample <= to; sample++) {
236        values[sample - from] = GetValue(sample, column);
237      }
238
239      return Statistics.Mean(values);
240    }
241
242    // return value of GetRange should be memoized because it is called repeatedly in Evaluators
243    public double GetRange(int column, int from, int to) {
244      Dictionary<int, double[]> columnRanges = ranges[column];
245      if(columnRanges.ContainsKey(from)) {
246        double[] fromRanges = columnRanges[from];
247        if(fromRanges[to-from] >= 0.0) {
248          // already calculated
249          return fromRanges[to-from];
250        } else {
251          // not yet calculated => calculate
252          fromRanges[to-from] = CalculateRange(column, from, to);
253          return fromRanges[to-from];
254        }
255      } else {
256        // never saw this from-index => create a new array, initialize and recalculate for to-index
257        double[] fromRanges = new double[rows - from];
258        // fill with negative values to indicate which means have already been calculated
259        for(int i = 0; i < fromRanges.Length; i++) { fromRanges[i] = -1.0; }
260        // store in dictionary
261        columnRanges[from] = fromRanges;
262        // calculate for specific to-index
263        fromRanges[to-from] = CalculateRange(column, from, to);
264        return fromRanges[to-from];
265      }
266    }
267
268    private double CalculateRange(int column, int from, int to) {
269      double[] values = new double[to - from + 1];
270      for(int sample = from; sample <= to; sample++) {
271        values[sample - from] = GetValue(sample, column);
272      }
273
274      return Statistics.Range(values);
275    }
276  }
277}
Note: See TracBrowser for help on using the repository browser.