Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 2281 was 2223, checked in by mkommend, 15 years ago

reintegrated branch new heuristic.modeling database backend (ticket #712)

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