Free cookie consent management tool by TermsFeed Policy Generator

source: branches/dataset-ids-2695/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/DataAnalysisProblemData.cs @ 15297

Last change on this file since 15297 was 15297, checked in by gkronber, 7 years ago

#2695: added a parameter to DataAnalysisProblemData to select an id column and extended RegressionLinechartViewBase to show the id on the xAxis

File size: 15.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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;
24using System.Collections.Generic;
25using System.Linq;
26using System.Text;
27using HeuristicLab.Collections;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
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    protected const string IdVariableParameterName = "Id Variable";
43    protected const string EmptyIdVariableName = "-";
44    #region parameter properites
45    //mkommend: inserted parameter caching due to performance reasons
46    private IFixedValueParameter<Dataset> datasetParameter;
47    public IFixedValueParameter<Dataset> DatasetParameter {
48      get {
49        if (datasetParameter == null) datasetParameter = (IFixedValueParameter<Dataset>)Parameters[DatasetParameterName];
50        return datasetParameter;
51      }
52    }
53
54    private IFixedValueParameter<ReadOnlyCheckedItemList<StringValue>> inputVariablesParameter;
55    public IFixedValueParameter<ReadOnlyCheckedItemList<StringValue>> InputVariablesParameter {
56      get {
57        if (inputVariablesParameter == null) inputVariablesParameter = (IFixedValueParameter<ReadOnlyCheckedItemList<StringValue>>)Parameters[InputVariablesParameterName];
58        return inputVariablesParameter;
59      }
60    }
61
62    private IConstrainedValueParameter<StringValue> idVariableParameter;
63    public IConstrainedValueParameter<StringValue> IdVariableParameter {
64      get {
65        if (idVariableParameter == null) idVariableParameter = (IConstrainedValueParameter<StringValue>)Parameters[IdVariableParameterName];
66        return idVariableParameter;
67      }
68    }
69
70    private IFixedValueParameter<IntRange> trainingPartitionParameter;
71    public IFixedValueParameter<IntRange> TrainingPartitionParameter {
72      get {
73        if (trainingPartitionParameter == null) trainingPartitionParameter = (IFixedValueParameter<IntRange>)Parameters[TrainingPartitionParameterName];
74        return trainingPartitionParameter;
75      }
76    }
77
78    private IFixedValueParameter<IntRange> testPartitionParameter;
79    public IFixedValueParameter<IntRange> TestPartitionParameter {
80      get {
81        if (testPartitionParameter == null) testPartitionParameter = (IFixedValueParameter<IntRange>)Parameters[TestPartitionParameterName];
82        return testPartitionParameter;
83      }
84    }
85
86    public IFixedValueParameter<ReadOnlyItemList<ITransformation>> TransformationsParameter {
87      get { return (IFixedValueParameter<ReadOnlyItemList<ITransformation>>)Parameters[TransformationsParameterName]; }
88    }
89    #endregion
90
91    #region properties
92    protected bool isEmpty = false;
93    public bool IsEmpty {
94      get { return isEmpty; }
95    }
96    public IDataset Dataset {
97      get { return DatasetParameter.Value; }
98    }
99    public ICheckedItemList<StringValue> InputVariables {
100      get { return InputVariablesParameter.Value; }
101    }
102    public IEnumerable<string> AllowedInputVariables {
103      get { return InputVariables.CheckedItems.Select(x => x.Value.Value); }
104    }
105    public string IdVariable {
106      get { return IdVariableParameter.Value.Value; }
107      // set only possible via parameter
108    }
109    public IEnumerable AllIds {
110      get {
111        var idVar = IdVariable;
112        if (idVar == EmptyIdVariableName) return Enumerable.Range(0, Dataset.Rows);
113        else if (Dataset.VariableHasType<double>(idVar)) return Dataset.GetDoubleValues(idVar);
114        else if (Dataset.VariableHasType<DateTime>(idVar)) return Dataset.GetDateTimeValues(idVar);
115        else if (Dataset.VariableHasType<string>(idVar)) return Dataset.GetStringValues(idVar);
116        else throw new NotSupportedException("The data type of the id variable is not supported");
117      }
118    }
119    public IEnumerable TrainingIds {
120      get {
121        var idVar = IdVariable;
122        if (idVar == EmptyIdVariableName) return TrainingIndices;
123        else if (Dataset.VariableHasType<double>(idVar)) return Dataset.GetDoubleValues(idVar, TrainingIndices);
124        else if (Dataset.VariableHasType<DateTime>(idVar)) return Dataset.GetDateTimeValues(idVar, TrainingIndices);
125        else if (Dataset.VariableHasType<string>(idVar)) return Dataset.GetStringValues(idVar, TrainingIndices);
126        else throw new NotSupportedException("The data type of the id variable is not supported");
127      }
128    }
129    public IEnumerable TestIds {
130      get {
131        var idVar = IdVariable;
132        if (idVar == EmptyIdVariableName) return TestIndices;
133        else if (Dataset.VariableHasType<double>(idVar)) return Dataset.GetDoubleValues(idVar, TestIndices);
134        else if (Dataset.VariableHasType<DateTime>(idVar)) return Dataset.GetDateTimeValues(idVar, TestIndices);
135        else if (Dataset.VariableHasType<string>(idVar)) return Dataset.GetStringValues(idVar, TestIndices);
136        else throw new NotSupportedException("The data type of the id variable is not supported");
137      }
138    }
139
140    public double[,] AllowedInputsTrainingValues {
141      get { return Dataset.ToArray(AllowedInputVariables, TrainingIndices); }
142    }
143
144    public double[,] AllowedInputsTestValues { get { return Dataset.ToArray(AllowedInputVariables, TestIndices); } }
145    public IntRange TrainingPartition {
146      get { return TrainingPartitionParameter.Value; }
147    }
148    public IntRange TestPartition {
149      get { return TestPartitionParameter.Value; }
150    }
151
152    public virtual IEnumerable<int> AllIndices {
153      get { return Enumerable.Range(0, Dataset.Rows); }
154    }
155    public virtual IEnumerable<int> TrainingIndices {
156      get {
157        return Enumerable.Range(TrainingPartition.Start, Math.Max(0, TrainingPartition.End - TrainingPartition.Start))
158                         .Where(IsTrainingSample);
159      }
160    }
161    public virtual IEnumerable<int> TestIndices {
162      get {
163        return Enumerable.Range(TestPartition.Start, Math.Max(0, TestPartition.End - TestPartition.Start))
164           .Where(IsTestSample);
165      }
166    }
167
168    public IEnumerable<ITransformation> Transformations {
169      get { return TransformationsParameter.Value; }
170    }
171
172    public virtual bool IsTrainingSample(int index) {
173      return index >= 0 && index < Dataset.Rows &&
174             TrainingPartition.Start <= index && index < TrainingPartition.End &&
175             (index < TestPartition.Start || TestPartition.End <= index);
176    }
177
178    public virtual bool IsTestSample(int index) {
179      return index >= 0 && index < Dataset.Rows &&
180             TestPartition.Start <= index && index < TestPartition.End;
181    }
182    #endregion
183
184    protected DataAnalysisProblemData(DataAnalysisProblemData original, Cloner cloner)
185      : base(original, cloner) {
186      isEmpty = original.isEmpty;
187      RegisterEventHandlers();
188    }
189    [StorableConstructor]
190    protected DataAnalysisProblemData(bool deserializing) : base(deserializing) { }
191
192    [StorableHook(HookType.AfterDeserialization)]
193    private void AfterDeserialization() {
194      if (!Parameters.ContainsKey(TransformationsParameterName)) {
195        Parameters.Add(new FixedValueParameter<ReadOnlyItemList<ITransformation>>(TransformationsParameterName, "", new ItemList<ITransformation>().AsReadOnly()));
196        TransformationsParameter.Hidden = true;
197      }
198      if (!Parameters.ContainsKey(IdVariableParameterName)) {
199        var allIdVars = new ItemSet<StringValue>(GetIdVariableNames());
200        var idVar = allIdVars.First();
201        Parameters.Add(new ConstrainedValueParameter<StringValue>(IdVariableParameterName, "", allIdVars, idVar));
202        TransformationsParameter.Hidden = true;
203      }
204      RegisterEventHandlers();
205    }
206
207    private IEnumerable<StringValue> GetIdVariableNames() {
208      // all variables with number of different values == number of rows
209      // + a separate entry for row id
210      // select separate entry for row id as default
211      // use event to update when the dataset is changed
212      var nRows = Dataset.Rows;
213      var potentialDoubleIdVars = Dataset.DoubleVariables
214        .Where(vn => Dataset.GetReadOnlyDoubleValues(vn).Distinct().Count() == nRows).ToArray();
215      var potentialStringIdVars = Dataset.StringVariables
216        .Where(vn => Dataset.GetReadOnlyStringValues(vn).Distinct().Count() == nRows).ToArray();
217      var potentialDateTimeIdVars = Dataset.DateTimeVariables
218        .Where(vn => Dataset.GetReadOnlyDateTimeValues(vn).Distinct().Count() == nRows).ToArray();
219      return
220        new string[] { EmptyIdVariableName }
221        .Concat(potentialStringIdVars)
222        .Concat(potentialDateTimeIdVars)
223        .Concat(potentialDoubleIdVars)
224        .Select(s => new StringValue(s));
225    }
226
227    protected DataAnalysisProblemData(IDataset dataset, IEnumerable<string> allowedInputVariables, IEnumerable<ITransformation> transformations = null) {
228      if (dataset == null) throw new ArgumentNullException("The dataset must not be null.");
229      if (allowedInputVariables == null) throw new ArgumentNullException("The allowed input variables must not be null.");
230
231      if (allowedInputVariables.Except(dataset.DoubleVariables).Except(dataset.StringVariables).Any())
232        throw new ArgumentException("All allowed input variables must be present in the dataset and of type double or string.");
233
234      var variables = dataset.VariableNames.Where(variable => dataset.VariableHasType<double>(variable) || dataset.VariableHasType<string>(variable));
235      var inputVariables = new CheckedItemList<StringValue>(variables.Select(x => new StringValue(x)));
236      foreach (StringValue x in inputVariables)
237        inputVariables.SetItemCheckedState(x, allowedInputVariables.Contains(x.Value));
238
239      int trainingPartitionStart = 0;
240      int trainingPartitionEnd = dataset.Rows / 2;
241      int testPartitionStart = dataset.Rows / 2;
242      int testPartitionEnd = dataset.Rows;
243
244      var transformationsList = new ItemList<ITransformation>(transformations ?? Enumerable.Empty<ITransformation>());
245
246      Parameters.Add(new FixedValueParameter<Dataset>(DatasetParameterName, "", (Dataset)dataset));
247      Parameters.Add(new FixedValueParameter<ReadOnlyCheckedItemList<StringValue>>(InputVariablesParameterName, "", inputVariables.AsReadOnly()));
248      Parameters.Add(new FixedValueParameter<IntRange>(TrainingPartitionParameterName, "", new IntRange(trainingPartitionStart, trainingPartitionEnd)));
249      Parameters.Add(new FixedValueParameter<IntRange>(TestPartitionParameterName, "", new IntRange(testPartitionStart, testPartitionEnd)));
250      Parameters.Add(new FixedValueParameter<ReadOnlyItemList<ITransformation>>(TransformationsParameterName, "", transformationsList.AsReadOnly()));
251      TransformationsParameter.Hidden = true;
252      var allIdVars = new ItemSet<StringValue>(GetIdVariableNames());
253      Parameters.Add(new ConstrainedValueParameter<StringValue>(IdVariableParameterName, "The variable to use as an ID column", allIdVars, allIdVars.First()));
254
255      ((ValueParameter<Dataset>)DatasetParameter).ReactOnValueToStringChangedAndValueItemImageChanged = false;
256      RegisterEventHandlers();
257    }
258
259    private void RegisterEventHandlers() {
260      DatasetParameter.ValueChanged += new EventHandler(Parameter_ValueChanged);
261      InputVariables.CheckedItemsChanged += new CollectionItemsChangedEventHandler<IndexedItem<StringValue>>(InputVariables_CheckedItemsChanged);
262      TrainingPartition.ValueChanged += new EventHandler(Parameter_ValueChanged);
263      TestPartition.ValueChanged += new EventHandler(Parameter_ValueChanged);
264      TransformationsParameter.ValueChanged += new EventHandler(Parameter_ValueChanged);
265    }
266
267    private void InputVariables_CheckedItemsChanged(object sender, CollectionItemsChangedEventArgs<IndexedItem<StringValue>> e) {
268      OnChanged();
269    }
270
271    private void Parameter_ValueChanged(object sender, EventArgs e) {
272      // update list of possible id variables and set currently set id variable if possible
273      var curId = IdVariable;
274      var newIdVars = GetIdVariableNames().ToArray();
275      var matchingIdVar = newIdVars.FirstOrDefault(var => var.Value == curId);
276      if (matchingIdVar == null) matchingIdVar = newIdVars.First();
277      IdVariableParameter.ValidValues.Clear();
278      var validValues = IdVariableParameter.ValidValues;
279      foreach(var entry in newIdVars) validValues.Add(entry);
280      IdVariableParameter.Value = matchingIdVar;
281
282      OnChanged();
283    }
284
285    public event EventHandler Changed;
286    protected virtual void OnChanged() {
287      var listeners = Changed;
288      if (listeners != null) listeners(this, EventArgs.Empty);
289    }
290
291    protected virtual bool IsProblemDataCompatible(IDataAnalysisProblemData problemData, out string errorMessage) {
292      errorMessage = string.Empty;
293      if (problemData == null) throw new ArgumentNullException("problemData", "The provided problemData is null.");
294
295      //check allowed input variables
296      StringBuilder message = new StringBuilder();
297      var variables = new HashSet<string>(problemData.InputVariables.Select(x => x.Value));
298      foreach (var item in AllowedInputVariables) {
299        if (!variables.Contains(item))
300          message.AppendLine("Input variable '" + item + "' is not present in the new problem data.");
301      }
302
303      if (message.Length != 0) {
304        errorMessage = message.ToString();
305        return false;
306      }
307      return true;
308
309    }
310
311    public virtual void AdjustProblemDataProperties(IDataAnalysisProblemData problemData) {
312      DataAnalysisProblemData data = problemData as DataAnalysisProblemData;
313      if (data == null) throw new ArgumentException("The problem data is not a data analysis problem data. Instead a " + problemData.GetType().GetPrettyName() + " was provided.", "problemData");
314
315      string errorMessage;
316      if (!data.IsProblemDataCompatible(this, out errorMessage)) {
317        throw new InvalidOperationException(errorMessage);
318      }
319
320      foreach (var inputVariable in InputVariables) {
321        var variable = data.InputVariables.FirstOrDefault(i => i.Value == inputVariable.Value);
322        InputVariables.SetItemCheckedState(inputVariable, variable != null && data.InputVariables.ItemChecked(variable));
323      }
324    }
325  }
326}
Note: See TracBrowser for help on using the repository browser.