Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Operator Architecture Refactoring/HeuristicLab.GP.StructureIdentification/3.3/TreeEvaluatorBase.cs @ 2298

Last change on this file since 2298 was 1891, checked in by gkronber, 16 years ago

Fixed #645 (Tree evaluators precompile the model for each evaluation of a row).

File size: 5.9 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    public void PrepareForEvaluation(IFunctionTree functionTree) {
65      BakedFunctionTree bakedTree = functionTree as BakedFunctionTree;
66      if (bakedTree == null) throw new ArgumentException("TreeEvaluators can only evaluate BakedFunctionTrees");
67
68      List<LightWeightFunction> linearRepresentation = bakedTree.LinearRepresentation;
69      codeArr = new Instr[linearRepresentation.Count];
70      int i = 0;
71      foreach (LightWeightFunction f in linearRepresentation) {
72        codeArr[i++] = TranslateToInstr(f);
73      }
74    }
75
76    private Instr TranslateToInstr(LightWeightFunction f) {
77      Instr instr = new Instr();
78      instr.arity = f.arity;
79      instr.symbol = EvaluatorSymbolTable.MapFunction(f.functionType);
80      switch (instr.symbol) {
81        case EvaluatorSymbolTable.DIFFERENTIAL:
82        case EvaluatorSymbolTable.VARIABLE: {
83            instr.i_arg0 = (short)f.data[0]; // var
84            instr.d_arg0 = f.data[1]; // weight
85            instr.i_arg1 = (short)f.data[2]; // sample-offset
86            break;
87          }
88        case EvaluatorSymbolTable.CONSTANT: {
89            instr.d_arg0 = f.data[0]; // value
90            break;
91          }
92        case EvaluatorSymbolTable.UNKNOWN: {
93            instr.function = f.functionType;
94            break;
95          }
96      }
97      return instr;
98    }
99
100    public double Evaluate(int sampleIndex) {
101      PC = 0;
102      this.sampleIndex = sampleIndex;
103
104      double estimated = EvaluateBakedCode();
105      if (double.IsNaN(estimated) || double.IsInfinity(estimated)) {
106        estimated = estimatedValueMax;
107      } else if (estimated > estimatedValueMax) {
108        estimated = estimatedValueMax;
109      } else if (estimated < estimatedValueMin) {
110        estimated = estimatedValueMin;
111      }
112      return estimated;
113    }
114
115    // skips a whole branch
116    protected void SkipBakedCode() {
117      int i = 1;
118      while (i > 0) {
119        i += codeArr[PC++].arity;
120        i--;
121      }
122    }
123
124    protected abstract double EvaluateBakedCode();
125
126    public override object Clone(IDictionary<Guid, object> clonedObjects) {
127      TreeEvaluatorBase clone = (TreeEvaluatorBase)base.Clone(clonedObjects);
128      if (!clonedObjects.ContainsKey(dataset.Guid)) {
129        clone.dataset = (Dataset)dataset.Clone(clonedObjects);
130      } else {
131        clone.dataset = (Dataset)clonedObjects[dataset.Guid];
132      }
133      clone.estimatedValueMax = estimatedValueMax;
134      clone.estimatedValueMin = estimatedValueMin;
135      return clone;
136    }
137
138    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
139      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
140      XmlAttribute minEstimatedValueAttr = document.CreateAttribute("MinEstimatedValue");
141      minEstimatedValueAttr.Value = XmlConvert.ToString(estimatedValueMin);
142      node.Attributes.Append(minEstimatedValueAttr);
143
144      XmlAttribute maxEstimatedValueAttr = document.CreateAttribute("MaxEstimatedValue");
145      maxEstimatedValueAttr.Value = XmlConvert.ToString(estimatedValueMax);
146      node.Attributes.Append(maxEstimatedValueAttr);
147
148      node.AppendChild(PersistenceManager.Persist("Dataset", dataset, document, persistedObjects));
149      return node;
150    }
151
152    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
153      base.Populate(node, restoredObjects);
154      estimatedValueMax = XmlConvert.ToDouble(node.Attributes["MaxEstimatedValue"].Value);
155      estimatedValueMin = XmlConvert.ToDouble(node.Attributes["MinEstimatedValue"].Value);
156
157      dataset = (Dataset)PersistenceManager.Restore(node.SelectSingleNode("Dataset"), restoredObjects);
158    }
159  }
160}
Note: See TracBrowser for help on using the repository browser.