Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.GP.StructureIdentification/3.3/TreeEvaluatorBase.cs @ 1840

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

implemented persistence of tree evaluators in a common base class for tree evaluators. #615 (Evaluation of HL3 function trees should be equivalent to evaluation in HL2)

File size: 5.7 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  /// Base class for tree evaluators
34  /// </summary>
35  public abstract class TreeEvaluatorBase : ItemBase, ITreeEvaluator {
36    protected const double EPSILON = 1.0e-7;
37    protected double estimatedValueMax;
38    protected double estimatedValueMin;
39
40    protected class Instr {
41      public double d_arg0;
42      public short i_arg0;
43      public short i_arg1;
44      public byte arity;
45      public byte symbol;
46      public IFunction function;
47    }
48
49    protected Instr[] codeArr;
50    protected int PC;
51    protected Dataset dataset;
52    protected int sampleIndex;
53
54    public void ResetEvaluator(Dataset dataset, int targetVariable, int start, int end, double punishmentFactor) {
55      this.dataset = dataset;
56      double maximumPunishment = punishmentFactor * dataset.GetRange(targetVariable, start, end);
57
58      // get the mean of the values of the target variable to determine the max and min bounds of the estimated value
59      double targetMean = dataset.GetMean(targetVariable, start, end);
60      estimatedValueMin = targetMean - maximumPunishment;
61      estimatedValueMax = targetMean + maximumPunishment;
62    }
63
64    private Instr TranslateToInstr(LightWeightFunction f) {
65      Instr instr = new Instr();
66      instr.arity = f.arity;
67      instr.symbol = EvaluatorSymbolTable.MapFunction(f.functionType);
68      switch (instr.symbol) {
69        case EvaluatorSymbolTable.DIFFERENTIAL:
70        case EvaluatorSymbolTable.VARIABLE: {
71            instr.i_arg0 = (short)f.data[0]; // var
72            instr.d_arg0 = f.data[1]; // weight
73            instr.i_arg1 = (short)f.data[2]; // sample-offset
74            break;
75          }
76        case EvaluatorSymbolTable.CONSTANT: {
77            instr.d_arg0 = f.data[0]; // value
78            break;
79          }
80        case EvaluatorSymbolTable.UNKNOWN: {
81            instr.function = f.functionType;
82            break;
83          }
84      }
85      return instr;
86    }
87
88    public double Evaluate(IFunctionTree functionTree, int sampleIndex) {
89      BakedFunctionTree bakedTree = functionTree as BakedFunctionTree;
90      if (bakedTree == null) throw new ArgumentException("TreeEvaluators can only evaluate BakedFunctionTrees");
91
92      List<LightWeightFunction> linearRepresentation = bakedTree.LinearRepresentation;
93      codeArr = new Instr[linearRepresentation.Count];
94      int i = 0;
95      foreach (LightWeightFunction f in linearRepresentation) {
96        codeArr[i++] = TranslateToInstr(f);
97      }
98
99      PC = 0;
100      this.sampleIndex = sampleIndex;
101
102      double estimated = EvaluateBakedCode();
103      if (double.IsNaN(estimated) || double.IsInfinity(estimated)) {
104        estimated = estimatedValueMax;
105      } else if (estimated > estimatedValueMax) {
106        estimated = estimatedValueMax;
107      } else if (estimated < estimatedValueMin) {
108        estimated = estimatedValueMin;
109      }
110      return estimated;
111    }
112
113    // skips a whole branch
114    protected void SkipBakedCode() {
115      int i = 1;
116      while (i > 0) {
117        i += codeArr[PC++].arity;
118        i--;
119      }
120    }
121
122    protected abstract double EvaluateBakedCode();
123
124    public override object Clone(IDictionary<Guid, object> clonedObjects) {
125      TreeEvaluatorBase clone = (TreeEvaluatorBase)base.Clone(clonedObjects);
126      clone.dataset = (Dataset)dataset.Clone(clonedObjects);
127      clone.estimatedValueMax = estimatedValueMax;
128      clone.estimatedValueMin = estimatedValueMin;
129      return clone;
130    }
131
132    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
133      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
134      XmlAttribute minEstimatedValueAttr = document.CreateAttribute("MinEstimatedValue");
135      minEstimatedValueAttr.Value = XmlConvert.ToString(estimatedValueMin);
136      node.Attributes.Append(minEstimatedValueAttr);
137
138      XmlAttribute maxEstimatedValueAttr = document.CreateAttribute("MaxEstimatedValue");
139      maxEstimatedValueAttr.Value = XmlConvert.ToString(estimatedValueMax);
140      node.Attributes.Append(maxEstimatedValueAttr);
141
142      node.AppendChild(PersistenceManager.Persist("Dataset", dataset, document, persistedObjects));
143      return node;
144    }
145
146    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
147      base.Populate(node, restoredObjects);
148      estimatedValueMax = XmlConvert.ToDouble(node.Attributes["MaxEstimatedValue"].Value);
149      estimatedValueMin = XmlConvert.ToDouble(node.Attributes["MinEstimatedValue"].Value);
150
151      dataset = (Dataset)PersistenceManager.Restore(node.SelectSingleNode("Dataset"), restoredObjects);
152    }
153  }
154}
Note: See TracBrowser for help on using the repository browser.