Free cookie consent management tool by TermsFeed Policy Generator

source: branches/LearningClassifierSystems/HeuristicLab.Problems.ConditionActionClassification/3.3/Implementation/ConditionActionClassificationProblemData.cs @ 9167

Last change on this file since 9167 was 9167, checked in by sforsten, 12 years ago

#1980:

  • change standard parameter settings in ConditionActionClassificationProblem
  • fixed bug: if a parent is copied instead of a crossover, the new individual is inserted in the population correctly
  • added missing attributes to ConditionActionClassificationProblemData
File size: 10.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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 HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Encodings.CombinedIntegerVectorEncoding;
29using HeuristicLab.Encodings.ConditionActionEncoding;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Problems.DataAnalysis;
33
34namespace HeuristicLab.Problems.ConditionActionClassification {
35  [StorableClass]
36  [Item("ConditionActionClassificationProblemData", "A problem data for LCS.")]
37  public class ConditionActionClassificationProblemData : ParameterizedNamedItem, IConditionActionProblemData {
38
39    #region default data
40    public static string[] defaultVariableNames = new string[] { "a", "b", "c", "d", "e", "f", "g" };
41    public static double[,] defaultData = new double[,]{
42      {0,0,1,1,0,0,0},
43      {0,1,1,1,0,0,0},
44      {0,0,1,0,0,0,1},
45      {1,0,1,0,1,1,0}
46    };
47    #endregion
48
49    #region parameter properites
50    public IFixedValueParameter<Dataset> DatasetParameter {
51      get { return (IFixedValueParameter<Dataset>)Parameters["Dataset"]; }
52    }
53    public IFixedValueParameter<ReadOnlyCheckedItemList<StringValue>> ConditionVariablesParameter {
54      get { return (IFixedValueParameter<ReadOnlyCheckedItemList<StringValue>>)Parameters["ConditionVariables"]; }
55    }
56    public IFixedValueParameter<ReadOnlyCheckedItemList<StringValue>> ActionVariablesParameter {
57      get { return (IFixedValueParameter<ReadOnlyCheckedItemList<StringValue>>)Parameters["ActionVariables"]; }
58    }
59    public IFixedValueParameter<IntValue> LengthParameter {
60      get { return (IFixedValueParameter<IntValue>)Parameters["Length"]; }
61    }
62    public IFixedValueParameter<IntValue> ActionLengthParameter {
63      get { return (IFixedValueParameter<IntValue>)Parameters["ActionLength"]; }
64    }
65    public IFixedValueParameter<IntMatrix> BoundsParameter {
66      get { return (IFixedValueParameter<IntMatrix>)Parameters["Bounds"]; }
67    }
68    public IFixedValueParameter<IntRange> TrainingPartitionParameter {
69      get { return (IFixedValueParameter<IntRange>)Parameters["TrainingPartition"]; }
70    }
71    public IFixedValueParameter<IntRange> TestPartitionParameter {
72      get { return (IFixedValueParameter<IntRange>)Parameters["TestPartition"]; }
73    }
74    #endregion
75
76    #region properties
77    public Dataset Dataset {
78      get { return DatasetParameter.Value; }
79    }
80    public ICheckedItemList<StringValue> ConditionVariables {
81      get { return ConditionVariablesParameter.Value; }
82    }
83    public ICheckedItemList<StringValue> ActionVariables {
84      get { return ActionVariablesParameter.Value; }
85    }
86    public IEnumerable<string> AllowedConditionVariables {
87      get { return ConditionVariables.CheckedItems.Select(x => x.Value.Value); }
88    }
89    public IEnumerable<string> AllowedActionVariables {
90      get { return ActionVariables.CheckedItems.Select(x => x.Value.Value); }
91    }
92    public IntRange TrainingPartition {
93      get { return TrainingPartitionParameter.Value; }
94    }
95    public IntRange TestPartition {
96      get { return TestPartitionParameter.Value; }
97    }
98    public IEnumerable<int> TrainingIndices {
99      get {
100        return Enumerable.Range(TrainingPartition.Start, Math.Max(0, TrainingPartition.End - TrainingPartition.Start))
101                         .Where(IsTrainingSample);
102      }
103    }
104    public IEnumerable<int> TestIndices {
105      get {
106        return Enumerable.Range(TestPartition.Start, Math.Max(0, TestPartition.End - TestPartition.Start))
107           .Where(IsTestSample);
108      }
109    }
110    public bool IsTrainingSample(int index) {
111      return index >= 0 && index < Dataset.Rows &&
112        TrainingPartition.Start <= index && index < TrainingPartition.End &&
113        (index < TestPartition.Start || TestPartition.End <= index);
114    }
115    public bool IsTestSample(int index) {
116      return index >= 0 && index < Dataset.Rows &&
117             TestPartition.Start <= index && index < TestPartition.End;
118    }
119    #endregion
120
121    private IDictionary<int, IClassifier> fetchClassifiersCache = new Dictionary<int, IClassifier>();
122
123
124    [StorableConstructor]
125    protected ConditionActionClassificationProblemData(bool deserializing) : base(deserializing) { }
126    protected ConditionActionClassificationProblemData(ConditionActionClassificationProblemData original, Cloner cloner)
127      : base(original, cloner) {
128    }
129    public override IDeepCloneable Clone(Cloner cloner) {
130      return new ConditionActionClassificationProblemData(this, cloner);
131    }
132
133    public ConditionActionClassificationProblemData(Dataset dataset, IEnumerable<string> allowedConditionVariables, IEnumerable<string> allowedActionVariables) {
134      if (dataset == null) throw new ArgumentNullException("The dataset must not be null.");
135      if (allowedActionVariables == null) throw new ArgumentNullException("The allowedActionVariables must not be null.");
136      if (allowedConditionVariables == null) throw new ArgumentNullException("The allowedActionVariables must not be null.");
137
138      if (allowedActionVariables.Except(dataset.DoubleVariables).Any())
139        throw new ArgumentException("All allowed action variables must be present in the dataset and of type double.");
140      if (allowedConditionVariables.Except(dataset.DoubleVariables).Any())
141        throw new ArgumentException("All allowed condition variables must be present in the dataset and of type double.");
142
143      var actionVariables = new CheckedItemList<StringValue>(dataset.DoubleVariables.Select(x => new StringValue(x)));
144      var conditionVariables = new CheckedItemList<StringValue>(actionVariables);
145      foreach (StringValue x in actionVariables) {
146        actionVariables.SetItemCheckedState(x, allowedActionVariables.Contains(x.Value));
147        conditionVariables.SetItemCheckedState(x, allowedConditionVariables.Contains(x.Value));
148      }
149
150      int trainingPartitionStart = 0;
151      int trainingPartitionEnd = dataset.Rows / 2;
152      int testPartitionStart = dataset.Rows / 2;
153      int testPartitionEnd = dataset.Rows;
154
155      Parameters.Add(new FixedValueParameter<Dataset>("Dataset", "", dataset));
156      Parameters.Add(new FixedValueParameter<ReadOnlyCheckedItemList<StringValue>>("ActionVariables", "", actionVariables.AsReadOnly()));
157      Parameters.Add(new FixedValueParameter<ReadOnlyCheckedItemList<StringValue>>("ConditionVariables", "", conditionVariables.AsReadOnly()));
158      Parameters.Add(new FixedValueParameter<IntValue>("Length", "", new IntValue(allowedConditionVariables.Count() + allowedActionVariables.Count())));
159      Parameters.Add(new FixedValueParameter<IntValue>("ActionLength", "", new IntValue(allowedActionVariables.Count())));
160      Parameters.Add(new FixedValueParameter<IntMatrix>("Bounds", "", GetBoundsMatrix(dataset, allowedConditionVariables, allowedActionVariables)));
161      Parameters.Add(new FixedValueParameter<IntRange>("TrainingPartition", "", new IntRange(trainingPartitionStart, trainingPartitionEnd)));
162      Parameters.Add(new FixedValueParameter<IntRange>("TestPartition", "", new IntRange(testPartitionStart, testPartitionEnd)));
163
164      ((ValueParameter<Dataset>)DatasetParameter).ReactOnValueToStringChangedAndValueItemImageChanged = false;
165    }
166
167    private IntMatrix GetBoundsMatrix(Dataset dataset, IEnumerable<string> conditionVariables, IEnumerable<string> actionVariables) {
168      IntMatrix bounds = new IntMatrix(conditionVariables.Count() + actionVariables.Count(), 2);
169      int index = 0;
170      foreach (var variable in conditionVariables) {
171        var values = dataset.GetDoubleValues(variable);
172        bounds[index, 0] = (int)values.Min();
173        bounds[index, 1] = (int)values.Max() + 2;
174        index++;
175      }
176      foreach (var variable in actionVariables) {
177        var values = dataset.GetDoubleValues(variable);
178        bounds[index, 0] = (int)values.Min();
179        bounds[index, 1] = (int)values.Max() + 1;
180        index++;
181      }
182      return bounds;
183    }
184
185    public event EventHandler Changed;
186    protected virtual void OnChanged() {
187      var listeners = Changed;
188      if (listeners != null) listeners(this, EventArgs.Empty);
189    }
190
191    public IntValue Length {
192      get { return LengthParameter.Value; }
193    }
194
195    public IntValue ActionLength {
196      get { return ActionLengthParameter.Value; }
197    }
198
199    public IntMatrix Bounds {
200      get { return BoundsParameter.Value; }
201    }
202
203    public IEnumerable<IClassifier> FetchClassifier(IEnumerable<int> rows) {
204      foreach (var row in rows) {
205        yield return FetchClassifier(row);
206      }
207    }
208
209    public IClassifier FetchClassifier(int rowNumber) {
210      if (!fetchClassifiersCache.ContainsKey(rowNumber)) {
211        int[] elements = new int[Length.Value];
212        var variableNamesList = Dataset.VariableNames.ToList();
213        int elementIndex = 0;
214        for (int i = 0; i < variableNamesList.Count; i++) {
215          if (AllowedConditionVariables.Contains(variableNamesList[i])) {
216            elements[elementIndex] = int.Parse(Dataset.GetValue(rowNumber, i));
217            elementIndex++;
218          }
219        }
220        for (int i = 0; i < variableNamesList.Count; i++) {
221          if (AllowedActionVariables.Contains(variableNamesList[i])) {
222            elements[elementIndex] = int.Parse(Dataset.GetValue(rowNumber, i));
223            elementIndex++;
224          }
225        }
226        if (elementIndex != Length.Value) {
227          throw new ArgumentException("Length of classifier is not equal to the number of allowed condition + action variables.");
228        }
229        fetchClassifiersCache.Add(rowNumber, new CombinedIntegerVector(elements, ActionLengthParameter.Value.Value, BoundsParameter.Value));
230      }
231      return fetchClassifiersCache[rowNumber];
232    }
233  }
234}
Note: See TracBrowser for help on using the repository browser.