Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Hive_Milestone3/sources/HeuristicLab.DataAnalysis/3.2/Dataset.cs @ 6629

Last change on this file since 6629 was 2038, checked in by gkronber, 15 years ago
  • Renamed VariableImpactCalculator to VariableQualityImpactCalculator and calculate the ratio of new quality value to old quality value to get an idea how the quality value is influenced by each variable.
  • Changes in Dataset to improve the speed of SetValue (only set a dirty flag instead of reallocating the caches)

#644 (Variable impact of CEDMA models should be calculated and stored in the result DB)

File size: 13.4 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    }
72    public double[] ScalingOffset {
73      get { return scalingOffset; }
74    }
75
76    public double GetValue(int i, int j) {
77      return samples[columns * i + j];
78    }
79
80    public void SetValue(int i, int j, double v) {
81      if (v != samples[columns * i + j]) {
82        samples[columns * i + j] = v;
83        cachedValuesInvalidated = true;
84        if (fireChangeEvents) FireChanged();
85      }
86    }
87
88    public double[] Samples {
89      get { return samples; }
90      set {
91        scalingFactor = new double[columns];
92        scalingOffset = new double[columns];
93        for (int i = 0; i < scalingFactor.Length; i++) {
94          scalingFactor[i] = 1.0;
95          scalingOffset[i] = 0.0;
96        }
97        samples = value;
98        cachedValuesInvalidated = true;
99        if (fireChangeEvents) FireChanged();
100      }
101    }
102
103    private string[] variableNames;
104
105    public Dataset() {
106      Name = "-";
107      variableNames = new string[] { "Var0" };
108      Columns = 1;
109      Rows = 1;
110      Samples = new double[1];
111      scalingOffset = new double[] { 0.0 };
112      scalingFactor = new double[] { 1.0 };
113      cachedValuesInvalidated = true;
114      fireChangeEvents = true;
115    }
116
117    public string GetVariableName(int variableIndex) {
118      return variableNames[variableIndex];
119    }
120
121    public int GetVariableIndex(string variableName) {
122      for (int i = 0; i < variableNames.Length; i++) {
123        if (variableNames[i].Equals(variableName)) return i;
124      }
125      throw new ArgumentException("The variable name " + variableName + " was not found.");
126    }
127
128    public void SetVariableName(int variableIndex, string name) {
129      variableNames[variableIndex] = name;
130    }
131
132    public override IView CreateView() {
133      return new DatasetView(this);
134    }
135
136    #region persistence
137    public override object Clone(IDictionary<Guid, object> clonedObjects) {
138      Dataset clone = new Dataset();
139      clonedObjects.Add(Guid, clone);
140      double[] cloneSamples = new double[rows * columns];
141      Array.Copy(samples, cloneSamples, samples.Length);
142      clone.rows = rows;
143      clone.columns = columns;
144      clone.Samples = cloneSamples;
145      clone.Name = Name;
146      clone.variableNames = new string[variableNames.Length];
147      Array.Copy(variableNames, clone.variableNames, variableNames.Length);
148      Array.Copy(scalingFactor, clone.scalingFactor, columns);
149      Array.Copy(scalingOffset, clone.scalingOffset, columns);
150      return clone;
151    }
152
153    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
154      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
155      XmlAttribute problemName = document.CreateAttribute("Name");
156      problemName.Value = Name;
157      node.Attributes.Append(problemName);
158      XmlAttribute dim1 = document.CreateAttribute("Dimension1");
159      dim1.Value = rows.ToString(CultureInfo.InvariantCulture.NumberFormat);
160      node.Attributes.Append(dim1);
161      XmlAttribute dim2 = document.CreateAttribute("Dimension2");
162      dim2.Value = columns.ToString(CultureInfo.InvariantCulture.NumberFormat);
163      node.Attributes.Append(dim2);
164      XmlAttribute variableNames = document.CreateAttribute("VariableNames");
165      variableNames.Value = GetVariableNamesString();
166      node.Attributes.Append(variableNames);
167      XmlAttribute scalingFactorsAttribute = document.CreateAttribute("ScalingFactors");
168      scalingFactorsAttribute.Value = GetString(scalingFactor);
169      node.Attributes.Append(scalingFactorsAttribute);
170      XmlAttribute scalingOffsetsAttribute = document.CreateAttribute("ScalingOffsets");
171      scalingOffsetsAttribute.Value = GetString(scalingOffset);
172      node.Attributes.Append(scalingOffsetsAttribute);
173      node.InnerText = ToString(CultureInfo.InvariantCulture.NumberFormat);
174      return node;
175    }
176
177    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
178      base.Populate(node, restoredObjects);
179      Name = node.Attributes["Name"].Value;
180      rows = int.Parse(node.Attributes["Dimension1"].Value, CultureInfo.InvariantCulture.NumberFormat);
181      columns = int.Parse(node.Attributes["Dimension2"].Value, CultureInfo.InvariantCulture.NumberFormat);
182
183      variableNames = ParseVariableNamesString(node.Attributes["VariableNames"].Value);
184      if (node.Attributes["ScalingFactors"] != null)
185        scalingFactor = ParseDoubleString(node.Attributes["ScalingFactors"].Value);
186      else {
187        scalingFactor = new double[columns]; // compatibility with old serialization format
188        for (int i = 0; i < scalingFactor.Length; i++) scalingFactor[i] = 1.0;
189      }
190      if (node.Attributes["ScalingOffsets"] != null)
191        scalingOffset = ParseDoubleString(node.Attributes["ScalingOffsets"].Value);
192      else {
193        scalingOffset = new double[columns]; // compatibility with old serialization format
194        for (int i = 0; i < scalingOffset.Length; i++) scalingOffset[i] = 0.0;
195      }
196
197      string[] tokens = node.InnerText.Split(';');
198      if (tokens.Length != rows * columns) throw new FormatException();
199      samples = new double[rows * columns];
200      for (int row = 0; row < rows; row++) {
201        for (int column = 0; column < columns; column++) {
202          if (double.TryParse(tokens[row * columns + column], NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out samples[row * columns + column]) == false) {
203            throw new FormatException("Can't parse " + tokens[row * columns + column] + " as double value.");
204          }
205        }
206      }
207    }
208
209    public override string ToString() {
210      return ToString(CultureInfo.CurrentCulture.NumberFormat);
211    }
212
213    private string ToString(NumberFormatInfo format) {
214      StringBuilder builder = new StringBuilder();
215      for (int row = 0; row < rows; row++) {
216        for (int column = 0; column < columns; column++) {
217          builder.Append(";");
218          builder.Append(samples[row * columns + column].ToString("r", format));
219        }
220      }
221      if (builder.Length > 0) builder.Remove(0, 1);
222      return builder.ToString();
223    }
224
225    private string GetVariableNamesString() {
226      string s = "";
227      for (int i = 0; i < variableNames.Length; i++) {
228        s += variableNames[i] + "; ";
229      }
230
231      if (variableNames.Length > 0) {
232        s = s.TrimEnd(';', ' ');
233      }
234      return s;
235    }
236    private string GetString(double[] xs) {
237      string s = "";
238      for (int i = 0; i < xs.Length; i++) {
239        s += xs[i].ToString("r", CultureInfo.InvariantCulture) + "; ";
240      }
241
242      if (xs.Length > 0) {
243        s = s.TrimEnd(';', ' ');
244      }
245      return s;
246    }
247
248    private string[] ParseVariableNamesString(string p) {
249      p = p.Trim();
250      string[] tokens = p.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
251      for (int i = 0; i < tokens.Length; i++) tokens[i] = tokens[i].Trim();
252      return tokens;
253    }
254    private double[] ParseDoubleString(string s) {
255      s = s.Trim();
256      string[] ss = s.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
257      double[] xs = new double[ss.Length];
258      for (int i = 0; i < xs.Length; i++) {
259        xs[i] = double.Parse(ss[i], CultureInfo.InvariantCulture);
260      }
261      return xs;
262    }
263    #endregion
264
265    public double GetMean(int column) {
266      return GetMean(column, 0, Rows);
267    }
268
269    public double GetMean(int column, int from, int to) {
270      if (cachedValuesInvalidated) CreateDictionaries();
271      if (!cachedMeans[column].ContainsKey(from) || !cachedMeans[column][from].ContainsKey(to)) {
272        double[] values = new double[to - from];
273        for (int sample = from; sample < to; sample++) {
274          values[sample - from] = GetValue(sample, column);
275        }
276        double mean = Statistics.Mean(values);
277        if (!cachedMeans[column].ContainsKey(from)) cachedMeans[column][from] = new Dictionary<int, double>();
278        cachedMeans[column][from][to] = mean;
279        return mean;
280      } else {
281        return cachedMeans[column][from][to];
282      }
283    }
284
285    public double GetRange(int column) {
286      return GetRange(column, 0, Rows);
287    }
288
289    public double GetRange(int column, int from, int to) {
290      if (cachedValuesInvalidated) CreateDictionaries();
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      cachedValuesInvalidated = true;
332      if (fireChangeEvents) 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      cachedValuesInvalidated = true;
343      if (fireChangeEvents) 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      cachedValuesInvalidated = true;
356      if (fireChangeEvents) FireChanged();
357    }
358
359    private void CreateDictionaries() {
360      // keep a means and ranges dictionary for each column (possible target variable) of the dataset.
361      cachedMeans = new Dictionary<int, Dictionary<int, double>>[columns];
362      cachedRanges = new Dictionary<int, Dictionary<int, double>>[columns];
363      for (int i = 0; i < columns; i++) {
364        cachedMeans[i] = new Dictionary<int, Dictionary<int, double>>();
365        cachedRanges[i] = new Dictionary<int, Dictionary<int, double>>();
366      }
367    }
368  }
369}
Note: See TracBrowser for help on using the repository browser.