Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/DataAnalysisProblemData.cs @ 14396

Last change on this file since 14396 was 14396, checked in by gkronber, 8 years ago

#2697: added methods to get training and test input matrizes from ProblemData

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