Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GrammaticalEvolution/HeuristicLab.Problems.GrammaticalEvolution/Symbolic/GESymbolicDataAnalysisEvaluator.cs @ 10073

Last change on this file since 10073 was 10073, checked in by sawinkle, 11 years ago

#2109:

  • Renamed all identifiers within the files to include 'GE', where necessary.
  • Changed the namespaces of all files to 'HeuristicLab.Problems.GrammaticalEvolution'.
  • Added the parameters IntegerVector, GenotypeToPhenotype and SymbolicExpressionTreeGrammar to the Evaluator classes, where necessary.
  • Changed the SolutionCreator from ISymbolicDataAnalysisSolutionCreator to IIntegerVectorCreator; changed the Evaluator from ISymbolicDataAnalysisEvaluator<T> to IGESymbolicDataAnalysisEvaluator<T>; the problem data class/interface IDataAnalysisProblemData stays the same.
  • The methods Evaluate() and Calculate() of the specific Evaluators won't change -> the genotype-to-phenotype mapping process is done within the Apply() method.
File size: 12.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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.IntegerVectorEncoding;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Operators;
31using HeuristicLab.Optimization;
32using HeuristicLab.Parameters;
33using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
34using HeuristicLab.Problems.DataAnalysis;
35using HeuristicLab.Problems.DataAnalysis.Symbolic;
36using HeuristicLab.Problems.GrammaticalEvolution.Mappers;
37using HeuristicLab.Random;
38
39namespace HeuristicLab.Problems.GrammaticalEvolution {
40  [StorableClass]
41  public abstract class GESymbolicDataAnalysisEvaluator<T> : SingleSuccessorOperator,
42    IGESymbolicDataAnalysisEvaluator<T>, ISymbolicDataAnalysisInterpreterOperator, ISymbolicDataAnalysisBoundedOperator, IStochasticOperator
43  where T : class, IDataAnalysisProblemData {
44    private const string RandomParameterName = "Random";
45    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
46    private const string SymbolicDataAnalysisTreeInterpreterParameterName = "SymbolicExpressionTreeInterpreter";
47    private const string ProblemDataParameterName = "ProblemData";
48    private const string IntegerVectorParameterName = "IntegerVector";
49    private const string GenotypeToPhenotypeMapperParameterName = "GenotypeToPhenotypeMapper";
50    private const string SymbolicExpressionTreeGrammarParameterName = "SymbolicExpressionTreeGrammar";
51
52    private const string EstimationLimitsParameterName = "EstimationLimits";
53    private const string EvaluationPartitionParameterName = "EvaluationPartition";
54    private const string RelativeNumberOfEvaluatedSamplesParameterName = "RelativeNumberOfEvaluatedSamples";
55    private const string ApplyLinearScalingParameterName = "ApplyLinearScaling";
56    private const string ValidRowIndicatorParameterName = "ValidRowIndicator";
57
58    public override bool CanChangeName { get { return false; } }
59
60    #region parameter properties
61    ILookupParameter<IRandom> IStochasticOperator.RandomParameter {
62      get { return RandomParameter; }
63    }
64
65    public IValueLookupParameter<IRandom> RandomParameter {
66      get { return (IValueLookupParameter<IRandom>)Parameters[RandomParameterName]; }
67    }
68    public ILookupParameter<ISymbolicExpressionTree> SymbolicExpressionTreeParameter {
69      get { return (ILookupParameter<ISymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
70    }
71    public ILookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter> SymbolicDataAnalysisTreeInterpreterParameter {
72      get { return (ILookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>)Parameters[SymbolicDataAnalysisTreeInterpreterParameterName]; }
73    }
74    public IValueLookupParameter<T> ProblemDataParameter {
75      get { return (IValueLookupParameter<T>)Parameters[ProblemDataParameterName]; }
76    }
77    public ILookupParameter<IntegerVector> IntegerVectorParameter {
78      get { return (ILookupParameter<IntegerVector>)Parameters[IntegerVectorParameterName]; }
79    }
80    public ILookupParameter<IGenotypeToPhenotypeMapper> GenotypeToPhenotypeMapperParameter {
81      get { return (ILookupParameter<IGenotypeToPhenotypeMapper>)Parameters[GenotypeToPhenotypeMapperParameterName]; }
82    }
83    public IValueLookupParameter<ISymbolicDataAnalysisGrammar> SymbolicExpressionTreeGrammarParameter {
84      get { return (IValueLookupParameter<ISymbolicDataAnalysisGrammar>)Parameters[SymbolicExpressionTreeGrammarParameterName]; }
85    }
86
87    public IValueLookupParameter<IntRange> EvaluationPartitionParameter {
88      get { return (IValueLookupParameter<IntRange>)Parameters[EvaluationPartitionParameterName]; }
89    }
90    public IValueLookupParameter<DoubleLimit> EstimationLimitsParameter {
91      get { return (IValueLookupParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName]; }
92    }
93    public IValueLookupParameter<PercentValue> RelativeNumberOfEvaluatedSamplesParameter {
94      get { return (IValueLookupParameter<PercentValue>)Parameters[RelativeNumberOfEvaluatedSamplesParameterName]; }
95    }
96    public ILookupParameter<BoolValue> ApplyLinearScalingParameter {
97      get { return (ILookupParameter<BoolValue>)Parameters[ApplyLinearScalingParameterName]; }
98    }
99    public IValueLookupParameter<StringValue> ValidRowIndicatorParameter {
100      get { return (IValueLookupParameter<StringValue>)Parameters[ValidRowIndicatorParameterName]; }
101    }
102    #endregion
103
104
105    [StorableConstructor]
106    protected GESymbolicDataAnalysisEvaluator(bool deserializing) : base(deserializing) { }
107    protected GESymbolicDataAnalysisEvaluator(GESymbolicDataAnalysisEvaluator<T> original, Cloner cloner)
108      : base(original, cloner) {
109    }
110    public GESymbolicDataAnalysisEvaluator()
111      : base() {
112      Parameters.Add(new ValueLookupParameter<IRandom>(RandomParameterName, "The random generator to use."));
113      Parameters.Add(new LookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(SymbolicDataAnalysisTreeInterpreterParameterName, "The interpreter that should be used to calculate the output values of the symbolic data analysis tree."));
114      Parameters.Add(new LookupParameter<ISymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic data analysis solution encoded as a symbolic expression tree."));
115      Parameters.Add(new ValueLookupParameter<T>(ProblemDataParameterName, "The problem data on which the symbolic data analysis solution should be evaluated."));
116      Parameters.Add(new LookupParameter<IntegerVector>(IntegerVectorParameterName, "The symbolic data analysis solution encoded as an integer vector genome."));
117      Parameters.Add(new LookupParameter<IGenotypeToPhenotypeMapper>(GenotypeToPhenotypeMapperParameterName, "Maps the genotype (an integer vector) to the phenotype (a symbolic expression tree)."));
118      Parameters.Add(new ValueLookupParameter<ISymbolicDataAnalysisGrammar>(SymbolicExpressionTreeGrammarParameterName, "The tree grammar that defines the correct syntax of symbolic expression trees that should be created."));
119
120      Parameters.Add(new ValueLookupParameter<IntRange>(EvaluationPartitionParameterName, "The start index of the dataset partition on which the symbolic data analysis solution should be evaluated."));
121      Parameters.Add(new ValueLookupParameter<DoubleLimit>(EstimationLimitsParameterName, "The upper and lower limit that should be used as cut off value for the output values of symbolic data analysis trees."));
122      Parameters.Add(new ValueLookupParameter<PercentValue>(RelativeNumberOfEvaluatedSamplesParameterName, "The relative number of samples of the dataset partition, which should be randomly chosen for evaluation between the start and end index."));
123      Parameters.Add(new LookupParameter<BoolValue>(ApplyLinearScalingParameterName, "Flag that indicates if the individual should be linearly scaled before evaluating."));
124      Parameters.Add(new ValueLookupParameter<StringValue>(ValidRowIndicatorParameterName, "An indicator variable in the data set that specifies which rows should be evaluated (those for which the indicator <> 0) (optional)."));
125    }
126
127    [StorableHook(HookType.AfterDeserialization)]
128    private void AfterDeserialization() {
129      if (Parameters.ContainsKey(ApplyLinearScalingParameterName) && !(Parameters[ApplyLinearScalingParameterName] is LookupParameter<BoolValue>))
130        Parameters.Remove(ApplyLinearScalingParameterName);
131      if (!Parameters.ContainsKey(ApplyLinearScalingParameterName))
132        Parameters.Add(new LookupParameter<BoolValue>(ApplyLinearScalingParameterName, "Flag that indicates if the individual should be linearly scaled before evaluating."));
133      if (!Parameters.ContainsKey(ValidRowIndicatorParameterName))
134        Parameters.Add(new ValueLookupParameter<StringValue>(ValidRowIndicatorParameterName, "An indicator variable in the data set that specifies which rows should be evaluated (those for which the indicator <> 0) (optional)."));
135    }
136
137    protected IEnumerable<int> GenerateRowsToEvaluate() {
138      return GenerateRowsToEvaluate(RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value);
139    }
140
141    protected IEnumerable<int> GenerateRowsToEvaluate(double percentageOfRows) {
142      IEnumerable<int> rows;
143      int samplesStart = EvaluationPartitionParameter.ActualValue.Start;
144      int samplesEnd = EvaluationPartitionParameter.ActualValue.End;
145      int testPartitionStart = ProblemDataParameter.ActualValue.TestPartition.Start;
146      int testPartitionEnd = ProblemDataParameter.ActualValue.TestPartition.End;
147      if (samplesEnd < samplesStart) throw new ArgumentException("Start value is larger than end value.");
148
149      if (percentageOfRows.IsAlmost(1.0))
150        rows = Enumerable.Range(samplesStart, samplesEnd - samplesStart);
151      else {
152        int seed = RandomParameter.ActualValue.Next();
153        int count = (int)((samplesEnd - samplesStart) * percentageOfRows);
154        if (count == 0) count = 1;
155        rows = RandomEnumerable.SampleRandomNumbers(seed, samplesStart, samplesEnd, count);
156      }
157
158      rows = rows.Where(i => i < testPartitionStart || testPartitionEnd <= i);
159      if (ValidRowIndicatorParameter.ActualValue != null) {
160        string indicatorVar = ValidRowIndicatorParameter.ActualValue.Value;
161        var problemData = ProblemDataParameter.ActualValue;
162        var indicatorRow = problemData.Dataset.GetReadOnlyDoubleValues(indicatorVar);
163        rows = rows.Where(r => !indicatorRow[r].IsAlmost(0.0));
164      }
165      return rows;
166    }
167
168    [ThreadStatic]
169    private static double[] cache;
170    protected static void CalculateWithScaling(IEnumerable<double> targetValues, IEnumerable<double> estimatedValues,
171      double lowerEstimationLimit, double upperEstimationLimit,
172      IOnlineCalculator calculator, int maxRows) {
173      if (cache == null || cache.Length < maxRows) {
174        cache = new double[maxRows];
175      }
176
177      // calculate linear scaling
178      int i = 0;
179      var linearScalingCalculator = new OnlineLinearScalingParameterCalculator();
180      var targetValuesEnumerator = targetValues.GetEnumerator();
181      var estimatedValuesEnumerator = estimatedValues.GetEnumerator();
182      while (targetValuesEnumerator.MoveNext() & estimatedValuesEnumerator.MoveNext()) {
183        double target = targetValuesEnumerator.Current;
184        double estimated = estimatedValuesEnumerator.Current;
185        cache[i] = estimated;
186        if (!double.IsNaN(estimated) && !double.IsInfinity(estimated))
187          linearScalingCalculator.Add(estimated, target);
188        i++;
189      }
190      if (linearScalingCalculator.ErrorState == OnlineCalculatorError.None && (targetValuesEnumerator.MoveNext() || estimatedValuesEnumerator.MoveNext()))
191        throw new ArgumentException("Number of elements in target and estimated values enumeration do not match.");
192
193      double alpha = linearScalingCalculator.Alpha;
194      double beta = linearScalingCalculator.Beta;
195      if (linearScalingCalculator.ErrorState != OnlineCalculatorError.None) {
196        alpha = 0.0;
197        beta = 1.0;
198      }
199
200      //calculate the quality by using the passed online calculator
201      targetValuesEnumerator = targetValues.GetEnumerator();
202      var scaledBoundedEstimatedValuesEnumerator = Enumerable.Range(0, i).Select(x => cache[x] * beta + alpha)
203        .LimitToRange(lowerEstimationLimit, upperEstimationLimit).GetEnumerator();
204
205      while (targetValuesEnumerator.MoveNext() & scaledBoundedEstimatedValuesEnumerator.MoveNext()) {
206        calculator.Add(targetValuesEnumerator.Current, scaledBoundedEstimatedValuesEnumerator.Current);
207      }
208    }
209  }
210}
Note: See TracBrowser for help on using the repository browser.