Free cookie consent management tool by TermsFeed Policy Generator

source: branches/symbreg-factors-2650/HeuristicLab.Problems.DataAnalysis/3.4/Implementation/DataAnalysisProblemData.cs @ 14693

Last change on this file since 14693 was 14693, checked in by mkommend, 7 years ago

#2650: Fixed ordering of variables in problem data.

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