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, 12 years ago

#1951: Adapted SymbolicDataAnalysisEvaluator.CalculateWithScaling to the review comments

File size: 10.6 KB
RevLine 
[5500]1#region License Information
2/* HeuristicLab
[7259]3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[5500]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 {
[5689]35  [StorableClass]
[5509]36  public abstract class SymbolicDataAnalysisEvaluator<T> : SingleSuccessorOperator,
[5720]37    ISymbolicDataAnalysisEvaluator<T>, ISymbolicDataAnalysisInterpreterOperator, ISymbolicDataAnalysisBoundedOperator
[5509]38  where T : class, IDataAnalysisProblemData {
[5500]39    private const string RandomParameterName = "Random";
40    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
[5514]41    private const string SymbolicDataAnalysisTreeInterpreterParameterName = "SymbolicExpressionTreeInterpreter";
[5500]42    private const string ProblemDataParameterName = "ProblemData";
[5770]43    private const string EstimationLimitsParameterName = "EstimationLimits";
[5759]44    private const string EvaluationPartitionParameterName = "EvaluationPartition";
[5500]45    private const string RelativeNumberOfEvaluatedSamplesParameterName = "RelativeNumberOfEvaluatedSamples";
[8664]46    private const string ApplyLinearScalingParameterName = "ApplyLinearScaling";
[8798]47    private const string ValidRowIndicatorParameterName = "ValidRowIndicator";
[5500]48
[5618]49    public override bool CanChangeName { get { return false; } }
50
[5500]51    #region parameter properties
[5514]52    public IValueLookupParameter<IRandom> RandomParameter {
53      get { return (IValueLookupParameter<IRandom>)Parameters[RandomParameterName]; }
[5500]54    }
55    public ILookupParameter<ISymbolicExpressionTree> SymbolicExpressionTreeParameter {
56      get { return (ILookupParameter<ISymbolicExpressionTree>)Parameters[SymbolicExpressionTreeParameterName]; }
57    }
[5649]58    public ILookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter> SymbolicDataAnalysisTreeInterpreterParameter {
59      get { return (ILookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>)Parameters[SymbolicDataAnalysisTreeInterpreterParameterName]; }
[5500]60    }
[5514]61    public IValueLookupParameter<T> ProblemDataParameter {
62      get { return (IValueLookupParameter<T>)Parameters[ProblemDataParameterName]; }
[5500]63    }
64
[5759]65    public IValueLookupParameter<IntRange> EvaluationPartitionParameter {
66      get { return (IValueLookupParameter<IntRange>)Parameters[EvaluationPartitionParameterName]; }
[5500]67    }
[5770]68    public IValueLookupParameter<DoubleLimit> EstimationLimitsParameter {
69      get { return (IValueLookupParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName]; }
[5500]70    }
[5759]71    public IValueLookupParameter<PercentValue> RelativeNumberOfEvaluatedSamplesParameter {
72      get { return (IValueLookupParameter<PercentValue>)Parameters[RelativeNumberOfEvaluatedSamplesParameterName]; }
[5500]73    }
[8664]74    public ILookupParameter<BoolValue> ApplyLinearScalingParameter {
75      get { return (ILookupParameter<BoolValue>)Parameters[ApplyLinearScalingParameterName]; }
76    }
[8798]77    public IValueLookupParameter<StringValue> ValidRowIndicatorParameter {
78      get { return (IValueLookupParameter<StringValue>)Parameters[ValidRowIndicatorParameterName]; }
79    }
[5500]80    #endregion
81
82
83    [StorableConstructor]
84    protected SymbolicDataAnalysisEvaluator(bool deserializing) : base(deserializing) { }
[5509]85    protected SymbolicDataAnalysisEvaluator(SymbolicDataAnalysisEvaluator<T> original, Cloner cloner)
[5500]86      : base(original, cloner) {
87    }
88    public SymbolicDataAnalysisEvaluator()
89      : base() {
[5514]90      Parameters.Add(new ValueLookupParameter<IRandom>(RandomParameterName, "The random generator to use."));
[5649]91      Parameters.Add(new LookupParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(SymbolicDataAnalysisTreeInterpreterParameterName, "The interpreter that should be used to calculate the output values of the symbolic data analysis tree."));
[5618]92      Parameters.Add(new LookupParameter<ISymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic data analysis solution encoded as a symbolic expression tree."));
[5514]93      Parameters.Add(new ValueLookupParameter<T>(ProblemDataParameterName, "The problem data on which the symbolic data analysis solution should be evaluated."));
[5759]94      Parameters.Add(new ValueLookupParameter<IntRange>(EvaluationPartitionParameterName, "The start index of the dataset partition on which the symbolic data analysis solution should be evaluated."));
[5770]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."));
[5759]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."));
[8664]97      Parameters.Add(new LookupParameter<BoolValue>(ApplyLinearScalingParameterName, "Flag that indicates if the individual should be linearly scaled before evaluating."));
[8798]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)."));
[5500]99    }
100
[8664]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."));
[8798]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)."));
[8664]109    }
110
[5500]111    protected IEnumerable<int> GenerateRowsToEvaluate() {
[5914]112      return GenerateRowsToEvaluate(RelativeNumberOfEvaluatedSamplesParameter.ActualValue.Value);
113    }
114
115    protected IEnumerable<int> GenerateRowsToEvaluate(double percentageOfRows) {
116      IEnumerable<int> rows;
[5759]117      int samplesStart = EvaluationPartitionParameter.ActualValue.Start;
118      int samplesEnd = EvaluationPartitionParameter.ActualValue.End;
[5823]119      int testPartitionStart = ProblemDataParameter.ActualValue.TestPartition.Start;
120      int testPartitionEnd = ProblemDataParameter.ActualValue.TestPartition.End;
[5759]121      if (samplesEnd < samplesStart) throw new ArgumentException("Start value is larger than end value.");
[5914]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
[8798]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;
[5500]140    }
[8664]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) {
[8974]147      if (cache == null || cache.Length < maxRows) {
[8664]148        cache = new double[maxRows];
149      }
150
[8838]151      // calculate linear scaling
[8664]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    }
[5500]183  }
184}
Note: See TracBrowser for help on using the repository browser.