Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Evaluators/SymbolicDataAnalysisEvaluator.cs @ 8974

Last change on this file since 8974 was 8974, checked in by mkommend, 11 years ago

#1951: Adapted SymbolicDataAnalysisEvaluator.CalculateWithScaling to the review comments

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.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Operators;
30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32using HeuristicLab.Random;
33
34namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
35  [StorableClass]
36  public abstract class SymbolicDataAnalysisEvaluator<T> : SingleSuccessorOperator,
37    ISymbolicDataAnalysisEvaluator<T>, ISymbolicDataAnalysisInterpreterOperator, ISymbolicDataAnalysisBoundedOperator
38  where T : class, IDataAnalysisProblemData {
39    private const string RandomParameterName = "Random";
40    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
41    private const string SymbolicDataAnalysisTreeInterpreterParameterName = "SymbolicExpressionTreeInterpreter";
42    private const string ProblemDataParameterName = "ProblemData";
43    private const string EstimationLimitsParameterName = "EstimationLimits";
44    private const string EvaluationPartitionParameterName = "EvaluationPartition";
45    private const string RelativeNumberOfEvaluatedSamplesParameterName = "RelativeNumberOfEvaluatedSamples";
46    private const string ApplyLinearScalingParameterName = "ApplyLinearScaling";
47    private const string ValidRowIndicatorParameterName = "ValidRowIndicator";
48
49    public override bool CanChangeName { get { return false; } }
50
51    #region parameter properties
52    public IValueLookupParameter<IRandom> RandomParameter {
53      get { return (IValueLookupParameter<IRandom>)Parameters[RandomParameterName]; }
54    }
55    public ILookupParameter<ISymbolicExpressionTree> SymbolicExpressionTreeParameter {
56      get { return (ILookupParameter<ISymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
57    }
58    public ILookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter> SymbolicDataAnalysisTreeInterpreterParameter {
59      get { return (ILookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>)Parameters[SymbolicDataAnalysisTreeInterpreterParameterName]; }
60    }
61    public IValueLookupParameter<T> ProblemDataParameter {
62      get { return (IValueLookupParameter<T>)Parameters[ProblemDataParameterName]; }
63    }
64
65    public IValueLookupParameter<IntRange> EvaluationPartitionParameter {
66      get { return (IValueLookupParameter<IntRange>)Parameters[EvaluationPartitionParameterName]; }
67    }
68    public IValueLookupParameter<DoubleLimit> EstimationLimitsParameter {
69      get { return (IValueLookupParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName]; }
70    }
71    public IValueLookupParameter<PercentValue> RelativeNumberOfEvaluatedSamplesParameter {
72      get { return (IValueLookupParameter<PercentValue>)Parameters[RelativeNumberOfEvaluatedSamplesParameterName]; }
73    }
74    public ILookupParameter<BoolValue> ApplyLinearScalingParameter {
75      get { return (ILookupParameter<BoolValue>)Parameters[ApplyLinearScalingParameterName]; }
76    }
77    public IValueLookupParameter<StringValue> ValidRowIndicatorParameter {
78      get { return (IValueLookupParameter<StringValue>)Parameters[ValidRowIndicatorParameterName]; }
79    }
80    #endregion
81
82
83    [StorableConstructor]
84    protected SymbolicDataAnalysisEvaluator(bool deserializing) : base(deserializing) { }
85    protected SymbolicDataAnalysisEvaluator(SymbolicDataAnalysisEvaluator<T> original, Cloner cloner)
86      : base(original, cloner) {
87    }
88    public SymbolicDataAnalysisEvaluator()
89      : base() {
90      Parameters.Add(new ValueLookupParameter<IRandom>(RandomParameterName, "The random generator to use."));
91      Parameters.Add(new LookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(SymbolicDataAnalysisTreeInterpreterParameterName, "The interpreter that should be used to calculate the output values of the symbolic data analysis tree."));
92      Parameters.Add(new LookupParameter<ISymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic data analysis solution encoded as a symbolic expression tree."));
93      Parameters.Add(new ValueLookupParameter<T>(ProblemDataParameterName, "The problem data on which the symbolic data analysis solution should be evaluated."));
94      Parameters.Add(new ValueLookupParameter<IntRange>(EvaluationPartitionParameterName, "The start index of the dataset partition on which the symbolic data analysis solution should be evaluated."));
95      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."));
96      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."));
97      Parameters.Add(new LookupParameter<BoolValue>(ApplyLinearScalingParameterName, "Flag that indicates if the individual should be linearly scaled before evaluating."));
98      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)."));
99    }
100
101    [StorableHook(HookType.AfterDeserialization)]
102    private void AfterDeserialization() {
103      if (Parameters.ContainsKey(ApplyLinearScalingParameterName) && !(Parameters[ApplyLinearScalingParameterName] is LookupParameter<BoolValue>))
104        Parameters.Remove(ApplyLinearScalingParameterName);
105      if (!Parameters.ContainsKey(ApplyLinearScalingParameterName))
106        Parameters.Add(new LookupParameter<BoolValue>(ApplyLinearScalingParameterName, "Flag that indicates if the individual should be linearly scaled before evaluating."));
107      if (!Parameters.ContainsKey(ValidRowIndicatorParameterName))
108        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)."));
109    }
110
111    protected IEnumerable<int> GenerateRowsToEvaluate() {
112      return GenerateRowsToEvaluate(RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value);
113    }
114
115    protected IEnumerable<int> GenerateRowsToEvaluate(double percentageOfRows) {
116      IEnumerable<int> rows;
117      int samplesStart = EvaluationPartitionParameter.ActualValue.Start;
118      int samplesEnd = EvaluationPartitionParameter.ActualValue.End;
119      int testPartitionStart = ProblemDataParameter.ActualValue.TestPartition.Start;
120      int testPartitionEnd = ProblemDataParameter.ActualValue.TestPartition.End;
121      if (samplesEnd < samplesStart) throw new ArgumentException("Start value is larger than end value.");
122
123      if (percentageOfRows.IsAlmost(1.0))
124        rows = Enumerable.Range(samplesStart, samplesEnd - samplesStart);
125      else {
126        int seed = RandomParameter.ActualValue.Next();
127        int count = (int)((samplesEnd - samplesStart) * percentageOfRows);
128        if (count == 0) count = 1;
129        rows = RandomEnumerable.SampleRandomNumbers(seed, samplesStart, samplesEnd, count);
130      }
131
132      rows = rows.Where(i => i < testPartitionStart || testPartitionEnd <= i);
133      if (ValidRowIndicatorParameter.ActualValue != null) {
134        string indicatorVar = ValidRowIndicatorParameter.ActualValue.Value;
135        var problemData = ProblemDataParameter.ActualValue;
136        var indicatorRow = problemData.Dataset.GetReadOnlyDoubleValues(indicatorVar);
137        rows = rows.Where(r => !indicatorRow[r].IsAlmost(0.0));
138      }
139      return rows;
140    }
141
142    [ThreadStatic]
143    private static double[] cache;
144    protected static void CalculateWithScaling(IEnumerable<double> targetValues, IEnumerable<double> estimatedValues,
145      double lowerEstimationLimit, double upperEstimationLimit,
146      IOnlineCalculator calculator, int maxRows) {
147      if (cache == null || cache.Length < maxRows) {
148        cache = new double[maxRows];
149      }
150
151      // calculate linear scaling
152      int i = 0;
153      var linearScalingCalculator = new OnlineLinearScalingParameterCalculator();
154      var targetValuesEnumerator = targetValues.GetEnumerator();
155      var estimatedValuesEnumerator = estimatedValues.GetEnumerator();
156      while (targetValuesEnumerator.MoveNext() & estimatedValuesEnumerator.MoveNext()) {
157        double target = targetValuesEnumerator.Current;
158        double estimated = estimatedValuesEnumerator.Current;
159        cache[i] = estimated;
160        if (!double.IsNaN(estimated) && !double.IsInfinity(estimated))
161          linearScalingCalculator.Add(estimated, target);
162        i++;
163      }
164      if (linearScalingCalculator.ErrorState == OnlineCalculatorError.None && (targetValuesEnumerator.MoveNext() || estimatedValuesEnumerator.MoveNext()))
165        throw new ArgumentException("Number of elements in target and estimated values enumeration do not match.");
166
167      double alpha = linearScalingCalculator.Alpha;
168      double beta = linearScalingCalculator.Beta;
169      if (linearScalingCalculator.ErrorState != OnlineCalculatorError.None) {
170        alpha = 0.0;
171        beta = 1.0;
172      }
173
174      //calculate the quality by using the passed online calculator
175      targetValuesEnumerator = targetValues.GetEnumerator();
176      var scaledBoundedEstimatedValuesEnumerator = Enumerable.Range(0, i).Select(x => cache[x] * beta + alpha)
177        .LimitToRange(lowerEstimationLimit, upperEstimationLimit).GetEnumerator();
178
179      while (targetValuesEnumerator.MoveNext() & scaledBoundedEstimatedValuesEnumerator.MoveNext()) {
180        calculator.Add(targetValuesEnumerator.Current, scaledBoundedEstimatedValuesEnumerator.Current);
181      }
182    }
183  }
184}
Note: See TracBrowser for help on using the repository browser.