source: branches/DataPreprocessing/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/DataAnalysisProblemData.cs @ 11009

Last change on this file since 11009 was 11009, checked in by pfleck, 6 years ago
  • Merged trunk into preprocessing branch.
File size: 9.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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.Linq;
25using System.Text;
26using HeuristicLab.Collections;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis.Transformations;
33
34namespace HeuristicLab.Problems.DataAnalysis {
35  [StorableClass]
36  public abstract class DataAnalysisProblemData : ParameterizedNamedItem, IDataAnalysisProblemData {
37    protected const string DatasetParameterName = "Dataset";
38    protected const string InputVariablesParameterName = "InputVariables";
39    protected const string TrainingPartitionParameterName = "TrainingPartition";
40    protected const string TestPartitionParameterName = "TestPartition";
41    protected const string TransformationsParameterName = "Transformations";
42
43    #region parameter properites
44    public IFixedValueParameter<Dataset> DatasetParameter {
45      get { return (IFixedValueParameter<Dataset>)Parameters[DatasetParameterName]; }
46    }
47    public IFixedValueParameter<ReadOnlyCheckedItemList<StringValue>> InputVariablesParameter {
48      get { return (IFixedValueParameter<ReadOnlyCheckedItemList<StringValue>>)Parameters[InputVariablesParameterName]; }
49    }
50    public IFixedValueParameter<IntRange> TrainingPartitionParameter {
51      get { return (IFixedValueParameter<IntRange>)Parameters[TrainingPartitionParameterName]; }
52    }
53    public IFixedValueParameter<IntRange> TestPartitionParameter {
54      get { return (IFixedValueParameter<IntRange>)Parameters[TestPartitionParameterName]; }
55    }
56    public IFixedValueParameter<ReadOnlyItemList<ITransformation>> TransformationsParameter {
57      get { return (IFixedValueParameter<ReadOnlyItemList<ITransformation>>)Parameters[TransformationsParameterName]; }
58    }
59    #endregion
60
61    #region properties
62    protected bool isEmpty = false;
63    public bool IsEmpty {
64      get { return isEmpty; }
65    }
66    public Dataset Dataset {
67      get { return DatasetParameter.Value; }
68    }
69    public ICheckedItemList<StringValue> InputVariables {
70      get { return InputVariablesParameter.Value; }
71    }
72    public IEnumerable<string> AllowedInputVariables {
73      get { return InputVariables.CheckedItems.Select(x => x.Value.Value); }
74    }
75
76    public IntRange TrainingPartition {
77      get { return TrainingPartitionParameter.Value; }
78    }
79    public IntRange TestPartition {
80      get { return TestPartitionParameter.Value; }
81    }
82
83    public virtual IEnumerable<int> TrainingIndices {
84      get {
85        return Enumerable.Range(TrainingPartition.Start, Math.Max(0, TrainingPartition.End - TrainingPartition.Start))
86                         .Where(IsTrainingSample);
87      }
88    }
89    public virtual IEnumerable<int> TestIndices {
90      get {
91        return Enumerable.Range(TestPartition.Start, Math.Max(0, TestPartition.End - TestPartition.Start))
92           .Where(IsTestSample);
93      }
94    }
95
96    public IEnumerable<ITransformation> Transformations {
97      get { return TransformationsParameter.Value; }
98    }
99
100    public virtual bool IsTrainingSample(int index) {
101      return index >= 0 && index < Dataset.Rows &&
102        TrainingPartition.Start <= index && index < TrainingPartition.End &&
103        (index < TestPartition.Start || TestPartition.End <= index);
104    }
105
106    public virtual bool IsTestSample(int index) {
107      return index >= 0 && index < Dataset.Rows &&
108             TestPartition.Start <= index && index < TestPartition.End;
109    }
110    #endregion
111
112    protected DataAnalysisProblemData(DataAnalysisProblemData original, Cloner cloner)
113      : base(original, cloner) {
114      isEmpty = original.isEmpty;
115      RegisterEventHandlers();
116    }
117    [StorableConstructor]
118    protected DataAnalysisProblemData(bool deserializing) : base(deserializing) { }
119
120    [StorableHook(HookType.AfterDeserialization)]
121    private void AfterDeserialization() {
122      if (!Parameters.ContainsKey(TransformationsParameterName)) {
123        Parameters.Add(new FixedValueParameter<ReadOnlyItemList<ITransformation>>(TransformationsParameterName, "", new ItemList<ITransformation>().AsReadOnly()));
124        TransformationsParameter.Hidden = true;
125      }
126      RegisterEventHandlers();
127    }
128
129    protected DataAnalysisProblemData(Dataset dataset, IEnumerable<string> allowedInputVariables, IList<ITransformation> transformations) {
130      if (dataset == null) throw new ArgumentNullException("The dataset must not be null.");
131      if (allowedInputVariables == null) throw new ArgumentNullException("The allowedInputVariables must not be null.");
132
133      if (allowedInputVariables.Except(dataset.DoubleVariables).Any())
134        throw new ArgumentException("All allowed input variables must be present in the dataset and of type double.");
135
136      if (transformations == null) throw new ArgumentNullException("The transformations must not be null.");
137
138      var inputVariables = new CheckedItemList<StringValue>(dataset.DoubleVariables.Select(x => new StringValue(x)));
139      foreach (StringValue x in inputVariables)
140        inputVariables.SetItemCheckedState(x, allowedInputVariables.Contains(x.Value));
141
142      int trainingPartitionStart = 0;
143      int trainingPartitionEnd = dataset.Rows / 2;
144      int testPartitionStart = dataset.Rows / 2;
145      int testPartitionEnd = dataset.Rows;
146
147      var transformationsList = new ItemList<ITransformation>(transformations);
148
149      Parameters.Add(new FixedValueParameter<Dataset>(DatasetParameterName, "", dataset));
150      Parameters.Add(new FixedValueParameter<ReadOnlyCheckedItemList<StringValue>>(InputVariablesParameterName, "", inputVariables.AsReadOnly()));
151      Parameters.Add(new FixedValueParameter<IntRange>(TrainingPartitionParameterName, "", new IntRange(trainingPartitionStart, trainingPartitionEnd)));
152      Parameters.Add(new FixedValueParameter<IntRange>(TestPartitionParameterName, "", new IntRange(testPartitionStart, testPartitionEnd)));
153      Parameters.Add(new FixedValueParameter<ReadOnlyItemList<ITransformation>>(TransformationsParameterName, "", transformationsList.AsReadOnly()));
154
155      TransformationsParameter.Hidden = true;
156
157      ((ValueParameter<Dataset>)DatasetParameter).ReactOnValueToStringChangedAndValueItemImageChanged = false;
158      RegisterEventHandlers();
159    }
160
161    private void RegisterEventHandlers() {
162      DatasetParameter.ValueChanged += new EventHandler(Parameter_ValueChanged);
163      InputVariables.CheckedItemsChanged += new CollectionItemsChangedEventHandler<IndexedItem<StringValue>>(InputVariables_CheckedItemsChanged);
164      TrainingPartition.ValueChanged += new EventHandler(Parameter_ValueChanged);
165      TestPartition.ValueChanged += new EventHandler(Parameter_ValueChanged);
166      TransformationsParameter.ValueChanged += new EventHandler(Parameter_ValueChanged);
167    }
168
169    private void InputVariables_CheckedItemsChanged(object sender, CollectionItemsChangedEventArgs<IndexedItem<StringValue>> e) {
170      OnChanged();
171    }
172
173    private void Parameter_ValueChanged(object sender, EventArgs e) {
174      OnChanged();
175    }
176
177    public event EventHandler Changed;
178    protected virtual void OnChanged() {
179      var listeners = Changed;
180      if (listeners != null) listeners(this, EventArgs.Empty);
181    }
182
183    protected virtual bool IsProblemDataCompatible(IDataAnalysisProblemData problemData, out string errorMessage) {
184      errorMessage = string.Empty;
185      if (problemData == null) throw new ArgumentNullException("problemData", "The provided problemData is null.");
186
187      //check allowed input variables
188      StringBuilder message = new StringBuilder();
189      var variables = new HashSet<string>(problemData.InputVariables.Select(x => x.Value));
190      foreach (var item in AllowedInputVariables) {
191        if (!variables.Contains(item))
192          message.AppendLine("Input variable '" + item + "' is not present in the new problem data.");
193      }
194
195      if (message.Length != 0) {
196        errorMessage = message.ToString();
197        return false;
198      }
199      return true;
200
201    }
202
203    public virtual void AdjustProblemDataProperties(IDataAnalysisProblemData problemData) {
204      DataAnalysisProblemData data = problemData as DataAnalysisProblemData;
205      if (data == null) throw new ArgumentException("The problem data is not a data analysis problem data. Instead a " + problemData.GetType().GetPrettyName() + " was provided.", "problemData");
206
207      string errorMessage;
208      if (!data.IsProblemDataCompatible(this, out errorMessage)) {
209        throw new InvalidOperationException(errorMessage);
210      }
211
212      foreach (var inputVariable in InputVariables) {
213        var variable = data.InputVariables.FirstOrDefault(i => i.Value == inputVariable.Value);
214        InputVariables.SetItemCheckedState(inputVariable, variable != null && data.InputVariables.ItemChecked(variable));
215      }
216
217      TrainingPartition.Start = TrainingPartition.End = 0;
218      TestPartition.Start = 0;
219      TestPartition.End = Dataset.Rows;
220    }
221  }
222}
Note: See TracBrowser for help on using the repository browser.