Free cookie consent management tool by TermsFeed Policy Generator

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

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

Applied patch from mkommend for variable impact calculators and adapted data-modeling algorithms to use the new operators for variable impact calculation. #728

File size: 17.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;
29using System.Linq;
30
31namespace HeuristicLab.DataAnalysis {
32  public sealed class Dataset : ItemBase {
33    private Dictionary<int, Dictionary<int, double>>[] cachedMeans;
34    private Dictionary<int, Dictionary<int, double>>[] cachedRanges;
35    private bool cachedValuesInvalidated = true;
36   
37    public Dataset()
38      : this(new double[,] { { 0.0 } }) {
39    }
40
41    public Dataset(double[,] samples) {
42      Name = "-";
43      Rows = samples.GetLength(0);
44      Columns = samples.GetLength(1);
45      double[] values = new double[Rows * Columns];
46      int i = 0;
47      for (int row = 0; row < Rows; row++) {
48        for (int column = 0; column < columns; column++) {
49          values[i++] = samples[row, column];
50        }
51      }
52      Samples = values;
53      fireChangeEvents = true;
54    }
55
56    #region Properties
57    private string name;
58    public string Name {
59      get { return name; }
60      set { name = value; }
61    }
62
63    private int rows;
64    public int Rows {
65      get { return rows; }
66      set { rows = value; }
67    }
68
69    private int columns;
70    public int Columns {
71      get { return columns; }
72      set {
73        columns = value;
74        if (variableNames == null || variableNames.Length != columns) {
75          variableNames = new string[columns];
76        }
77      }
78    }
79
80    private string[] variableNames;
81    public IEnumerable<string> VariableNames {
82      get { return variableNames; }
83    }
84
85    private double[] samples;
86    public double[] Samples {
87      get { return samples; }
88      set {
89        variableNames = Enumerable.Range(1, columns).Select(x => "Var" + x.ToString("###")).ToArray();
90        scalingFactor = new double[columns];
91        scalingOffset = new double[columns];
92        for (int i = 0; i < scalingFactor.Length; i++) {
93          scalingFactor[i] = 1.0;
94          scalingOffset[i] = 0.0;
95        }
96        samples = value;
97        cachedValuesInvalidated = true;
98        if (fireChangeEvents) FireChanged();
99      }
100    }
101
102    private bool fireChangeEvents = true;
103    public bool FireChangeEvents {
104      get { return fireChangeEvents; }
105      set { fireChangeEvents = value; }
106    }
107
108    private double[] scalingFactor;
109    public double[] ScalingFactor {
110      get { return scalingFactor; }
111      set {
112        if (value.Length != scalingFactor.Length)
113          throw new ArgumentException("Length of scaling factor array doesn't match number of variables");
114        scalingFactor = value;
115      }
116    }
117
118    private double[] scalingOffset;
119    public double[] ScalingOffset {
120      get { return scalingOffset; }
121      set {
122        if (value.Length != scalingOffset.Length)
123          throw new ArgumentException("Length of scaling offset array doesn't match number of variables");
124        scalingOffset = value;
125      }
126    }
127    #endregion
128
129    #region Modify and get values
130    public double GetValue(int i, int j) {
131      return samples[columns * i + j];
132    }
133
134    public double[] GetVariableValues(int variableIndex, int start, int end) {
135      if (start < 0 || !(start <= end))
136        throw new ArgumentException("Start must be between 0 and end (" + end + ").");
137      if (end > rows || end < start)
138        throw new ArgumentException("End must be between start (" + start + ") and dataset rows (" + rows + ").");
139
140      double[] values = new double[end - start];
141      for (int i = 0; i < end - start; i++)
142        values[i] = GetValue(i + start, variableIndex);
143      return values;
144    }
145
146    public double[] GetVariableValues(int variableIndex) {
147      return GetVariableValues(variableIndex, 0, this.rows);
148    }
149
150    public double[] GetVariableValues(string variableName, int start, int end) {
151      return GetVariableValues(GetVariableIndex(variableName), start, end);
152    }
153
154    public double[] GetVariableValues(string variableName) {
155      return GetVariableValues(variableName, 0, this.rows);
156    }
157
158    public void SetValue(int i, int j, double v) {
159      if (v != samples[columns * i + j]) {
160        samples[columns * i + j] = v;
161        cachedValuesInvalidated = true;
162        if (fireChangeEvents) FireChanged();
163      }
164    }
165
166    public IEnumerable<double> ReplaceVariableValues(int variableIndex, IEnumerable<double> newValues, int start, int end) {
167      double[] oldValues = new double[end - start];
168      for (int i = 0; i < end - start; i++) oldValues[i] = this.GetValue(i + start, variableIndex);
169      if (newValues.Count() != end - start) throw new ArgumentException("The length of the new values sequence doesn't match the required length (number of replaced values)");
170
171      int index = start;
172      this.FireChangeEvents = false;
173      foreach (double v in newValues) {
174        this.SetValue(index++, variableIndex, v);
175      }
176      this.FireChangeEvents = true;
177      this.FireChanged();
178      return oldValues;
179    }
180
181    public IEnumerable<double> ReplaceVariableValues(string variableName, IEnumerable<double> newValues, int start, int end) {
182      return ReplaceVariableValues(this.GetVariableIndex(variableName), newValues, start, end);
183    }
184    #endregion
185
186    #region Variable name methods
187    public string GetVariableName(int variableIndex) {
188      return variableNames[variableIndex];
189    }
190
191    public int GetVariableIndex(string variableName) {
192      for (int i = 0; i < variableNames.Length; i++) {
193        if (variableNames[i].Equals(variableName)) return i;
194      }
195      throw new ArgumentException("The variable name " + variableName + " was not found.");
196    }
197
198    public void SetVariableName(int variableIndex, string name) {
199      variableNames[variableIndex] = name;
200    }
201
202    public bool ContainsVariableName(string variableName) {
203      return this.variableNames.Contains(variableName);
204    }
205    #endregion
206
207    public override IView CreateView() {
208      return new DatasetView(this);
209    }
210
211
212    #region Variable statistics
213    public double GetMean(string variableName) {
214      return GetMean(GetVariableIndex(variableName));
215    }
216
217    public double GetMean(string variableName, int start, int end) {
218      return GetMean(GetVariableIndex(variableName), start, end);
219    }
220
221    public double GetMean(int column) {
222      return GetMean(column, 0, Rows);
223    }
224
225    public double GetMean(int column, int start, int end) {
226      if (cachedValuesInvalidated) CreateDictionaries();
227      if (!cachedMeans[column].ContainsKey(start) || !cachedMeans[column][start].ContainsKey(end)) {
228        double[] values = new double[end - start];
229        for (int sample = start; sample < end; sample++) {
230          values[sample - start] = GetValue(sample, column);
231        }
232        double mean = Statistics.Mean(values);
233        if (!cachedMeans[column].ContainsKey(start)) cachedMeans[column][start] = new Dictionary<int, double>();
234        cachedMeans[column][start][end] = mean;
235        return mean;
236      } else {
237        return cachedMeans[column][start][end];
238      }
239    }
240
241    public double GetRange(string variableName) {
242      return GetRange(this.GetVariableIndex(variableName));
243    }
244
245    public double GetRange(int column) {
246      return GetRange(column, 0, Rows);
247    }
248
249    public double GetRange(string variableName, int start, int end) {
250      return GetRange(this.GetVariableIndex(variableName), start, end);
251    }
252
253    public double GetRange(int column, int start, int end) {
254      if (cachedValuesInvalidated) CreateDictionaries();
255      if (!cachedRanges[column].ContainsKey(start) || !cachedRanges[column][start].ContainsKey(end)) {
256        double[] values = new double[end - start];
257        for (int sample = start; sample < end; sample++) {
258          values[sample - start] = GetValue(sample, column);
259        }
260        double range = Statistics.Range(values);
261        if (!cachedRanges[column].ContainsKey(start)) cachedRanges[column][start]= new Dictionary<int, double>();
262        cachedRanges[column][start][end] = range;
263        return range;
264      } else {
265        return cachedRanges[column][start][end];
266      }
267    }
268
269    public double GetMaximum(string variableName) {
270      return GetMaximum(this.GetVariableIndex(variableName));
271    }
272
273    public double GetMaximum(int column) {
274      return GetMaximum(column, 0, Rows);
275    }
276
277    public double GetMaximum(string variableName, int start, int end) {
278      return GetMaximum(this.GetVariableIndex(variableName), start, end);
279    }
280
281    public double GetMaximum(int column, int start, int end) {
282      double max = Double.NegativeInfinity;
283      for (int i = start; i < end; i++) {
284        double val = GetValue(i, column);
285        if (!double.IsNaN(val) && val > max) max = val;
286      }
287      return max;
288    }
289
290    public double GetMinimum(string variableName) {
291      return GetMinimum(GetVariableIndex(variableName));
292    }
293
294    public double GetMinimum(int column) {
295      return GetMinimum(column, 0, Rows);
296    }
297
298    public double GetMinimum(string variableName, int start, int end) {
299      return GetMinimum(this.GetVariableIndex(variableName), start, end);
300    }
301
302    public double GetMinimum(int column, int start, int end) {
303      double min = Double.PositiveInfinity;
304      for (int i = start; i < end; i++) {
305        double val = GetValue(i, column);
306        if (!double.IsNaN(val) && val < min) min = val;
307      }
308      return min;
309    }
310    #endregion
311
312    internal void ScaleVariable(int column) {
313      if (scalingFactor[column] == 1.0 && scalingOffset[column] == 0.0) {
314        double min = GetMinimum(column);
315        double max = GetMaximum(column);
316        double range = max - min;
317        if (range == 0) ScaleVariable(column, 1.0, -min);
318        else ScaleVariable(column, 1.0 / range, -min);
319      }
320      cachedValuesInvalidated = true;
321      if (fireChangeEvents) FireChanged();
322    }
323
324    internal void ScaleVariable(int column, double factor, double offset) {
325      scalingFactor[column] = factor;
326      scalingOffset[column] = offset;
327      for (int i = 0; i < Rows; i++) {
328        double origValue = samples[i * columns + column];
329        samples[i * columns + column] = (origValue + offset) * factor;
330      }
331      cachedValuesInvalidated = true;
332      if (fireChangeEvents) FireChanged();
333    }
334
335    internal void UnscaleVariable(int column) {
336      if (scalingFactor[column] != 1.0 || scalingOffset[column] != 0.0) {
337        for (int i = 0; i < rows; i++) {
338          double scaledValue = samples[i * columns + column];
339          samples[i * columns + column] = scaledValue / scalingFactor[column] - scalingOffset[column];
340        }
341        scalingFactor[column] = 1.0;
342        scalingOffset[column] = 0.0;
343      }
344      cachedValuesInvalidated = true;
345      if (fireChangeEvents) FireChanged();
346    }
347
348    private void CreateDictionaries() {
349      // keep a means and ranges dictionary for each column (possible target variable) of the dataset.
350      cachedMeans = new Dictionary<int, Dictionary<int, double>>[columns];
351      cachedRanges = new Dictionary<int, Dictionary<int, double>>[columns];
352      for (int i = 0; i < columns; i++) {
353        cachedMeans[i] = new Dictionary<int, Dictionary<int, double>>();
354        cachedRanges[i] = new Dictionary<int, Dictionary<int, double>>();
355      }
356      cachedValuesInvalidated = false;
357    }
358
359    #region persistence
360    public override object Clone(IDictionary<Guid, object> clonedObjects) {
361      Dataset clone = new Dataset();
362      clonedObjects.Add(Guid, clone);
363      double[] cloneSamples = new double[rows * columns];
364      Array.Copy(samples, cloneSamples, samples.Length);
365      clone.rows = rows;
366      clone.columns = columns;
367      clone.Samples = cloneSamples;
368      clone.Name = Name;
369      clone.variableNames = new string[variableNames.Length];
370      Array.Copy(variableNames, clone.variableNames, variableNames.Length);
371      Array.Copy(scalingFactor, clone.scalingFactor, columns);
372      Array.Copy(scalingOffset, clone.scalingOffset, columns);
373      return clone;
374    }
375
376    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
377      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
378      XmlAttribute problemName = document.CreateAttribute("Name");
379      problemName.Value = Name;
380      node.Attributes.Append(problemName);
381      XmlAttribute dim1 = document.CreateAttribute("Dimension1");
382      dim1.Value = rows.ToString(CultureInfo.InvariantCulture.NumberFormat);
383      node.Attributes.Append(dim1);
384      XmlAttribute dim2 = document.CreateAttribute("Dimension2");
385      dim2.Value = columns.ToString(CultureInfo.InvariantCulture.NumberFormat);
386      node.Attributes.Append(dim2);
387      XmlAttribute variableNames = document.CreateAttribute("VariableNames");
388      variableNames.Value = GetVariableNamesString();
389      node.Attributes.Append(variableNames);
390      XmlAttribute scalingFactorsAttribute = document.CreateAttribute("ScalingFactors");
391      scalingFactorsAttribute.Value = GetString(scalingFactor);
392      node.Attributes.Append(scalingFactorsAttribute);
393      XmlAttribute scalingOffsetsAttribute = document.CreateAttribute("ScalingOffsets");
394      scalingOffsetsAttribute.Value = GetString(scalingOffset);
395      node.Attributes.Append(scalingOffsetsAttribute);
396      node.InnerText = ToString(CultureInfo.InvariantCulture.NumberFormat);
397      return node;
398    }
399
400    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
401      base.Populate(node, restoredObjects);
402      Name = node.Attributes["Name"].Value;
403      rows = int.Parse(node.Attributes["Dimension1"].Value, CultureInfo.InvariantCulture.NumberFormat);
404      columns = int.Parse(node.Attributes["Dimension2"].Value, CultureInfo.InvariantCulture.NumberFormat);
405
406      variableNames = ParseVariableNamesString(node.Attributes["VariableNames"].Value);
407      if (node.Attributes["ScalingFactors"] != null)
408        scalingFactor = ParseDoubleString(node.Attributes["ScalingFactors"].Value);
409      else {
410        scalingFactor = new double[columns]; // compatibility with old serialization format
411        for (int i = 0; i < scalingFactor.Length; i++) scalingFactor[i] = 1.0;
412      }
413      if (node.Attributes["ScalingOffsets"] != null)
414        scalingOffset = ParseDoubleString(node.Attributes["ScalingOffsets"].Value);
415      else {
416        scalingOffset = new double[columns]; // compatibility with old serialization format
417        for (int i = 0; i < scalingOffset.Length; i++) scalingOffset[i] = 0.0;
418      }
419
420      string[] tokens = node.InnerText.Split(';');
421      if (tokens.Length != rows * columns) throw new FormatException();
422      samples = new double[rows * columns];
423      for (int row = 0; row < rows; row++) {
424        for (int column = 0; column < columns; column++) {
425          if (double.TryParse(tokens[row * columns + column], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out samples[row * columns + column]) == false) {
426            throw new FormatException("Can't parse " + tokens[row * columns + column] + " as double value.");
427          }
428        }
429      }
430    }
431
432    public override string ToString() {
433      return ToString(CultureInfo.CurrentCulture.NumberFormat);
434    }
435
436    private string ToString(NumberFormatInfo format) {
437      StringBuilder builder = new StringBuilder();
438      for (int row = 0; row < rows; row++) {
439        for (int column = 0; column < columns; column++) {
440          builder.Append(";");
441          builder.Append(samples[row * columns + column].ToString("r", format));
442        }
443      }
444      if (builder.Length > 0) builder.Remove(0, 1);
445      return builder.ToString();
446    }
447
448    private string GetVariableNamesString() {
449      string s = "";
450      for (int i = 0; i < variableNames.Length; i++) {
451        s += variableNames[i] + "; ";
452      }
453
454      if (variableNames.Length > 0) {
455        s = s.TrimEnd(';', ' ');
456      }
457      return s;
458    }
459    private string GetString(double[] xs) {
460      string s = "";
461      for (int i = 0; i < xs.Length; i++) {
462        s += xs[i].ToString("r", CultureInfo.InvariantCulture) + "; ";
463      }
464
465      if (xs.Length > 0) {
466        s = s.TrimEnd(';', ' ');
467      }
468      return s;
469    }
470
471    private string[] ParseVariableNamesString(string p) {
472      p = p.Trim();
473      string[] tokens = p.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
474      for (int i = 0; i < tokens.Length; i++) tokens[i] = tokens[i].Trim();
475      return tokens;
476    }
477    private double[] ParseDoubleString(string s) {
478      s = s.Trim();
479      string[] ss = s.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
480      double[] xs = new double[ss.Length];
481      for (int i = 0; i < xs.Length; i++) {
482        xs[i] = double.Parse(ss[i], CultureInfo.InvariantCulture);
483      }
484      return xs;
485    }
486    #endregion
487  }
488}
Note: See TracBrowser for help on using the repository browser.