Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.GP.StructureIdentification/3.3/BakedTreeEvaluator.cs @ 1787

Last change on this file since 1787 was 1787, checked in by gkronber, 15 years ago

simplified code of BakedTreeEvaluator: removed constant expression folding and special cases for DIV and SUB with only one operand. #615 (Evaluation of HL3 function trees should be equivalent to evaluation in HL2)

File size: 10.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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 System.Text;
26using HeuristicLab.Core;
27using System.Xml;
28using System.Diagnostics;
29using HeuristicLab.DataAnalysis;
30
31namespace HeuristicLab.GP.StructureIdentification {
32  /// <summary>
33  /// Evaluates FunctionTrees recursively by interpretation of the function symbols in each node.
34  /// Not thread-safe!
35  /// </summary>
36  public class BakedTreeEvaluator {
37    private const double EPSILON = 1.0e-7;
38    private double estimatedValueMax;
39    private double estimatedValueMin;
40
41    private class Instr {
42      public double d_arg0;
43      public short i_arg0;
44      public short i_arg1;
45      public byte arity;
46      public byte symbol;
47      public IFunction function;
48    }
49
50    private Instr[] codeArr;
51    private int PC;
52    private Dataset dataset;
53    private int sampleIndex;
54
55    public void ResetEvaluator(BakedFunctionTree functionTree, Dataset dataset, int targetVariable, int start, int end, double punishmentFactor) {
56      this.dataset = dataset;
57      double maximumPunishment = punishmentFactor * dataset.GetRange(targetVariable, start, end);
58
59      // get the mean of the values of the target variable to determine the max and min bounds of the estimated value
60      double targetMean = dataset.GetMean(targetVariable, start, end);
61      estimatedValueMin = targetMean - maximumPunishment;
62      estimatedValueMax = targetMean + maximumPunishment;
63
64      List<LightWeightFunction> linearRepresentation = functionTree.LinearRepresentation;
65      codeArr = new Instr[linearRepresentation.Count];
66      int i = 0;
67      foreach (LightWeightFunction f in linearRepresentation) {
68        codeArr[i++] = TranslateToInstr(f);
69      }
70    }
71
72    private Instr TranslateToInstr(LightWeightFunction f) {
73      Instr instr = new Instr();
74      instr.arity = f.arity;
75      instr.symbol = EvaluatorSymbolTable.MapFunction(f.functionType);
76      switch (instr.symbol) {
77        case EvaluatorSymbolTable.DIFFERENTIAL:
78        case EvaluatorSymbolTable.VARIABLE: {
79            instr.i_arg0 = (short)f.data[0]; // var
80            instr.d_arg0 = f.data[1]; // weight
81            instr.i_arg1 = (short)f.data[2]; // sample-offset
82            break;
83          }
84        case EvaluatorSymbolTable.CONSTANT: {
85            instr.d_arg0 = f.data[0]; // value
86            break;
87          }
88        case EvaluatorSymbolTable.UNKNOWN: {
89            instr.function = f.functionType;
90            break;
91          }
92      }
93      return instr;
94    }
95
96    public double Evaluate(int sampleIndex) {
97      PC = 0;
98      this.sampleIndex = sampleIndex;
99
100      double estimated = EvaluateBakedCode();
101      if (double.IsNaN(estimated) || double.IsInfinity(estimated)) {
102        estimated = estimatedValueMax;
103      } else if (estimated > estimatedValueMax) {
104        estimated = estimatedValueMax;
105      } else if (estimated < estimatedValueMin) {
106        estimated = estimatedValueMin;
107      }
108      return estimated;
109    }
110
111    // skips a whole branch
112    private void SkipBakedCode() {
113      int i = 1;
114      while (i > 0) {
115        i += codeArr[PC++].arity;
116        i--;
117      }
118    }
119
120    private double EvaluateBakedCode() {
121      Instr currInstr = codeArr[PC++];
122      switch (currInstr.symbol) {
123        case EvaluatorSymbolTable.VARIABLE: {
124            int row = sampleIndex + currInstr.i_arg1;
125            if (row < 0 || row >= dataset.Rows) return double.NaN;
126            else return currInstr.d_arg0 * dataset.GetValue(row, currInstr.i_arg0);
127          }
128        case EvaluatorSymbolTable.CONSTANT: {
129            return currInstr.d_arg0;
130          }
131        case EvaluatorSymbolTable.DIFFERENTIAL: {
132            int row = sampleIndex + currInstr.i_arg1;
133            if (row < 0 || row >= dataset.Rows) return double.NaN;
134            else if (row < 1) return 0.0;
135            else {
136              double prevValue = dataset.GetValue(row - 1, currInstr.i_arg0);
137              if (double.IsNaN(prevValue) || double.IsInfinity(prevValue)) return 0.0;
138              else return currInstr.d_arg0 * (dataset.GetValue(row, currInstr.i_arg0) - prevValue);
139            }
140          }
141        case EvaluatorSymbolTable.MULTIPLICATION: {
142            double result = EvaluateBakedCode();
143            for (int i = 1; i < currInstr.arity; i++) {
144              result *= EvaluateBakedCode();
145            }
146            return result;
147          }
148        case EvaluatorSymbolTable.ADDITION: {
149            double sum = EvaluateBakedCode();
150            for (int i = 1; i < currInstr.arity; i++) {
151              sum += EvaluateBakedCode();
152            }
153            return sum;
154          }
155        case EvaluatorSymbolTable.SUBTRACTION: {
156            double result = EvaluateBakedCode();
157            for (int i = 1; i < currInstr.arity; i++) {
158              result -= EvaluateBakedCode();
159            }
160            return result;
161          }
162        case EvaluatorSymbolTable.DIVISION: {
163            double result;
164            result = EvaluateBakedCode();
165            for (int i = 1; i < currInstr.arity; i++) {
166              result /= EvaluateBakedCode();
167            }
168            if (double.IsInfinity(result)) return 0.0;
169            else return result;
170          }
171        case EvaluatorSymbolTable.AVERAGE: {
172            double sum = EvaluateBakedCode();
173            for (int i = 1; i < currInstr.arity; i++) {
174              sum += EvaluateBakedCode();
175            }
176            return sum / currInstr.arity;
177          }
178        case EvaluatorSymbolTable.COSINUS: {
179            return Math.Cos(EvaluateBakedCode());
180          }
181        case EvaluatorSymbolTable.SINUS: {
182            return Math.Sin(EvaluateBakedCode());
183          }
184        case EvaluatorSymbolTable.EXP: {
185            return Math.Exp(EvaluateBakedCode());
186          }
187        case EvaluatorSymbolTable.LOG: {
188            return Math.Log(EvaluateBakedCode());
189          }
190        case EvaluatorSymbolTable.POWER: {
191            double x = EvaluateBakedCode();
192            double p = EvaluateBakedCode();
193            return Math.Pow(x, p);
194          }
195        case EvaluatorSymbolTable.SIGNUM: {
196            double value = EvaluateBakedCode();
197            if (double.IsNaN(value)) return double.NaN;
198            else return Math.Sign(value);
199          }
200        case EvaluatorSymbolTable.SQRT: {
201            return Math.Sqrt(EvaluateBakedCode());
202          }
203        case EvaluatorSymbolTable.TANGENS: {
204            return Math.Tan(EvaluateBakedCode());
205          }
206        case EvaluatorSymbolTable.AND: { // only defined for inputs 1 and 0
207            double result = EvaluateBakedCode();
208            for (int i = 1; i < currInstr.arity; i++) {
209              if (result == 0.0) SkipBakedCode();
210              else {
211                result = EvaluateBakedCode();
212              }
213              Debug.Assert(result == 0.0 || result == 1.0);
214            }
215            return result;
216          }
217        case EvaluatorSymbolTable.EQU: {
218            double x = EvaluateBakedCode();
219            double y = EvaluateBakedCode();
220            if (Math.Abs(x - y) < EPSILON) return 1.0; else return 0.0;
221          }
222        case EvaluatorSymbolTable.GT: {
223            double x = EvaluateBakedCode();
224            double y = EvaluateBakedCode();
225            if (x > y) return 1.0;
226            else return 0.0;
227          }
228        case EvaluatorSymbolTable.IFTE: { // only defined for condition 0 or 1
229            double condition = EvaluateBakedCode();
230            Debug.Assert(condition == 0.0 || condition == 1.0);
231            double result;
232            if (condition == 0.0) {
233              result = EvaluateBakedCode(); SkipBakedCode();
234            } else {
235              SkipBakedCode(); result = EvaluateBakedCode();
236            }
237            return result;
238          }
239        case EvaluatorSymbolTable.LT: {
240            double x = EvaluateBakedCode();
241            double y = EvaluateBakedCode();
242            if (x < y) return 1.0;
243            else return 0.0;
244          }
245        case EvaluatorSymbolTable.NOT: { // only defined for inputs 0 or 1
246            double result = EvaluateBakedCode();
247            Debug.Assert(result == 0.0 || result == 1.0);
248            return Math.Abs(result - 1.0);
249          }
250        case EvaluatorSymbolTable.OR: { // only defined for inputs 0 or 1
251            double result = EvaluateBakedCode();
252            for (int i = 1; i < currInstr.arity; i++) {
253              if (result > 0.0) SkipBakedCode();
254              else {
255                result = EvaluateBakedCode();
256                Debug.Assert(result == 0.0 || result == 1.0);
257              }
258            }
259            return result;
260          }
261        case EvaluatorSymbolTable.XOR: { // only defined for inputs 0 or 1
262            double x = EvaluateBakedCode();
263            double y = EvaluateBakedCode();
264            return Math.Abs(x - y);
265          }
266        case EvaluatorSymbolTable.UNKNOWN: { // evaluate functions which are not statically defined directly
267            return currInstr.function.Apply();
268          }
269        default: {
270            throw new NotImplementedException();
271          }
272      }
273    }
274  }
275}
Note: See TracBrowser for help on using the repository browser.