Free cookie consent management tool by TermsFeed Policy Generator

source: branches/MemPRAlgorithm/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/DataAnalysisProblemData.cs @ 14562

Last change on this file since 14562 was 14562, checked in by abeham, 7 years ago

#2701: Updated branch to trunk

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