Free cookie consent management tool by TermsFeed Policy Generator

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

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

Worked on #722 (IModel should provide a Predict() method to get predicted values for an input vector).
At the same time removed parameter PunishmentFactor from GP algorithms (this parameter is internal to TreeEvaluators now).

File size: 6.1 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 HeuristicLab.Core;
25using HeuristicLab.DataAnalysis;
26using HeuristicLab.GP.Interfaces;
27using System.Xml;
28
29namespace HeuristicLab.GP.StructureIdentification {
30  /// <summary>
31  /// Base class for tree evaluators
32  /// </summary>
33  public abstract class TreeEvaluatorBase : ItemBase, ITreeEvaluator {
34    protected const double EPSILON = 1.0e-7;
35    protected double maxValue = double.MaxValue;
36    protected double minValue = double.MinValue;
37    private double punishmentFactor = 10.0; // we should provide a view for treeevaluators that allows to change this value
38
39    protected class Instr {
40      public double d_arg0;
41      public short i_arg0;
42      public short i_arg1;
43      public byte arity;
44      public byte symbol;
45    }
46
47    protected Instr[] codeArr;
48    protected int PC;
49    protected Dataset dataset;
50    protected int sampleIndex;
51
52    public void PrepareForEvaluation(Dataset dataset, IFunctionTree functionTree) {
53      this.dataset = dataset;
54      codeArr = new Instr[functionTree.GetSize()];
55      int i = 0;
56      foreach (IFunctionTree tree in IteratePrefix(functionTree)) {
57        codeArr[i++] = TranslateToInstr(tree);
58      }
59    }
60
61    public void PrepareForEvaluation(Dataset dataset, int targetVariable, int start, int end, IFunctionTree functionTree) {
62      // calculate upper and lower bounds for the estimated value (mean +/- punishmentFactor * range)
63      double mean = dataset.GetMean(targetVariable, start, end);
64      double range = dataset.GetRange(targetVariable, start, end);
65      maxValue = mean + punishmentFactor * range;
66      minValue = mean - punishmentFactor * range;
67      PrepareForEvaluation(dataset, functionTree);
68    }
69
70    private IEnumerable<IFunctionTree> IteratePrefix(IFunctionTree functionTree) {
71      List<IFunctionTree> prefixForm = new List<IFunctionTree>();
72      prefixForm.Add(functionTree);
73      foreach (IFunctionTree subTree in functionTree.SubTrees) {
74        prefixForm.AddRange(IteratePrefix(subTree));
75      }
76      return prefixForm;
77    }
78
79    private Instr TranslateToInstr(IFunctionTree tree) {
80      Instr instr = new Instr();
81      instr.arity = (byte)tree.SubTrees.Count;
82      instr.symbol = EvaluatorSymbolTable.MapFunction(tree.Function);
83      switch (instr.symbol) {
84        case EvaluatorSymbolTable.DIFFERENTIAL:
85        case EvaluatorSymbolTable.VARIABLE: {
86            VariableFunctionTree varTree = (VariableFunctionTree)tree;
87            instr.i_arg0 = (short)dataset.GetVariableIndex(varTree.VariableName);
88            instr.d_arg0 = varTree.Weight;
89            instr.i_arg1 = (short)varTree.SampleOffset;
90            break;
91          }
92        case EvaluatorSymbolTable.CONSTANT: {
93            ConstantFunctionTree constTree = (ConstantFunctionTree)tree;
94            instr.d_arg0 = constTree.Value;
95            break;
96          }
97        case EvaluatorSymbolTable.UNKNOWN: {
98            throw new NotSupportedException("Unknown function symbol: " + instr.symbol);
99          }
100      }
101      return instr;
102    }
103
104    public double Evaluate(int sampleIndex) {
105      PC = 0;
106      this.sampleIndex = sampleIndex;
107
108      double estimated = EvaluateBakedCode();
109      if (double.IsNaN(estimated) || double.IsInfinity(estimated)) estimated = maxValue;
110      else if (estimated < minValue) estimated = minValue;
111      else if (estimated > maxValue) estimated = maxValue;
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      clone.maxValue = maxValue;
129      clone.minValue = minValue;
130      clone.punishmentFactor = punishmentFactor;
131      return clone;
132    }
133
134    public override System.Xml.XmlNode GetXmlNode(string name, System.Xml.XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
135      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
136      XmlAttribute maxValueAttribute = document.CreateAttribute("MaxPredictionValue");
137      XmlAttribute minValueAttribute = document.CreateAttribute("MinPredictionValue");
138      XmlAttribute punishmentFactorAttribute = document.CreateAttribute("PunishmentFactor");
139      maxValueAttribute.Value = XmlConvert.ToString(maxValue);
140      minValueAttribute.Value = XmlConvert.ToString(minValue);
141      punishmentFactorAttribute.Value = XmlConvert.ToString(punishmentFactor);
142
143      node.Attributes.Append(punishmentFactorAttribute);
144      node.Attributes.Append(minValueAttribute);
145      node.Attributes.Append(maxValueAttribute);
146      return node;
147    }
148
149    public override void Populate(System.Xml.XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
150      base.Populate(node, restoredObjects);
151      minValue = XmlConvert.ToDouble(node.Attributes["MinPredictionValue"].Value);
152      maxValue = XmlConvert.ToDouble(node.Attributes["MaxPredictionValue"].Value);
153      punishmentFactor = XmlConvert.ToDouble(node.Attributes["PunishmentFactor"].Value);
154    }
155  }
156}
Note: See TracBrowser for help on using the repository browser.