Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.DataAnalysis/3.2/Dataset.cs @ 2012

Last change on this file since 2012 was 2012, checked in by gkronber, 15 years ago

Fixed a few bugs introduced with r2000. #656 (CEDMA server should handle only one data set (problem) at a time)

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