Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.ExternalEvaluation.GP/3.3/Interpretation/TreeInterpreter.cs @ 6934

Last change on this file since 6934 was 5445, checked in by swagner, 14 years ago

Updated year of copyrights (#1406)

File size: 9.5 KB
RevLine 
[4089]1#region License Information
2/* HeuristicLab
[5445]3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[4089]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;
[4722]24using HeuristicLab.Common;
[4089]25using HeuristicLab.Core;
26using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Compiler;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
30
31namespace HeuristicLab.Problems.ExternalEvaluation.GP {
32  [StorableClass]
33  [Item("TreeInterpreter", "Interpreter for arithmetic symbolic expression trees including function calls.")]
34  // not thread safe!
35  public class TreeInterpreter : NamedItem, ISymbolicExpressionTreeInterpreter {
36    private class OpCodes {
37      public const byte Add = 1;
38      public const byte Sub = 2;
39      public const byte Mul = 3;
40      public const byte Div = 4;
41
42      public const byte Sin = 5;
43      public const byte Cos = 6;
44      public const byte Tan = 7;
45
46      public const byte Log = 8;
47      public const byte Exp = 9;
48
49      public const byte IfThenElse = 10;
50
51      public const byte GT = 11;
52      public const byte LT = 12;
53
54      public const byte AND = 13;
55      public const byte OR = 14;
56      public const byte NOT = 15;
57
58
59      public const byte Average = 16;
60
61      public const byte Call = 17;
62
63      public const byte Variable = 18;
64      public const byte Constant = 19;
65      public const byte Arg = 20;
66    }
67
68    private Dictionary<Type, byte> symbolToOpcode = new Dictionary<Type, byte>() {
69      { typeof(Addition), OpCodes.Add },
70      { typeof(Subtraction), OpCodes.Sub },
71      { typeof(Multiplication), OpCodes.Mul },
72      { typeof(Division), OpCodes.Div },
73      { typeof(Sine), OpCodes.Sin },
74      { typeof(Cosine), OpCodes.Cos },
75      { typeof(Tangent), OpCodes.Tan },
76      { typeof(Logarithm), OpCodes.Log },
77      { typeof(Exponential), OpCodes.Exp },
78      { typeof(IfThenElse), OpCodes.IfThenElse },
79      { typeof(GreaterThan), OpCodes.GT },
80      { typeof(LessThan), OpCodes.LT },
81      { typeof(And), OpCodes.AND },
82      { typeof(Or), OpCodes.OR },
83      { typeof(Not), OpCodes.NOT},
84      { typeof(Average), OpCodes.Average},
85      { typeof(InvokeFunction), OpCodes.Call },
86      { typeof(Variable), OpCodes.Variable },
87      { typeof(Constant), OpCodes.Constant },
88      { typeof(Argument), OpCodes.Arg },
89    };
90    private const int ARGUMENT_STACK_SIZE = 1024;
91
92    private Dictionary<string, double> variables;
93    private Instruction[] code;
94    private int pc;
[4722]95
[4089]96    public override bool CanChangeName {
97      get { return false; }
98    }
99    public override bool CanChangeDescription {
100      get { return false; }
101    }
102
[4722]103
104    [StorableConstructor]
105    protected TreeInterpreter(bool deserializing) : base(deserializing) { }
106    protected TreeInterpreter(TreeInterpreter original, Cloner cloner) : base(original, cloner) { }
107    public override IDeepCloneable Clone(Cloner cloner) {
108      return new TreeInterpreter(this, cloner);
[4089]109    }
[4722]110    public TreeInterpreter() : base() { }
[4089]111
[4108]112    public void Prepare(SymbolicExpressionTree tree) {
[4089]113      var compiler = new SymbolicExpressionTreeCompiler();
114      code = compiler.Compile(tree, MapSymbolToOpCode);
[4108]115    }
116
117    public double InterpretTree(Dictionary<string, double> variables) {
118      this.variables = variables;
[4089]119      pc = 0;
120      argStackPointer = 0;
121      return Evaluate();
122    }
123
124    private byte MapSymbolToOpCode(SymbolicExpressionTreeNode treeNode) {
125      if (symbolToOpcode.ContainsKey(treeNode.Symbol.GetType()))
126        return symbolToOpcode[treeNode.Symbol.GetType()];
127      else
128        throw new NotSupportedException("Symbol: " + treeNode.Symbol);
129    }
130
131    private double[] argumentStack = new double[ARGUMENT_STACK_SIZE];
132    private int argStackPointer;
133
[4108]134    private double Evaluate() {
[4089]135      var currentInstr = code[pc++];
136      switch (currentInstr.opCode) {
137        case OpCodes.Add: {
138            double s = 0.0;
139            for (int i = 0; i < currentInstr.nArguments; i++) {
140              s += Evaluate();
141            }
142            return s;
143          }
144        case OpCodes.Sub: {
145            double s = Evaluate();
146            for (int i = 1; i < currentInstr.nArguments; i++) {
147              s -= Evaluate();
148            }
149            if (currentInstr.nArguments == 1) s = -s;
150            return s;
151          }
152        case OpCodes.Mul: {
153            double p = Evaluate();
154            for (int i = 1; i < currentInstr.nArguments; i++) {
155              p *= Evaluate();
156            }
157            return p;
158          }
159        case OpCodes.Div: {
160            double p = Evaluate();
161            for (int i = 1; i < currentInstr.nArguments; i++) {
162              p /= Evaluate();
163            }
164            if (currentInstr.nArguments == 1) p = 1.0 / p;
165            return p;
166          }
167        case OpCodes.Average: {
168            double sum = Evaluate();
169            for (int i = 1; i < currentInstr.nArguments; i++) {
170              sum += Evaluate();
171            }
172            return sum / currentInstr.nArguments;
173          }
174        case OpCodes.Cos: {
175            return Math.Cos(Evaluate());
176          }
177        case OpCodes.Sin: {
178            return Math.Sin(Evaluate());
179          }
180        case OpCodes.Tan: {
181            return Math.Tan(Evaluate());
182          }
183        case OpCodes.Exp: {
184            return Math.Exp(Evaluate());
185          }
186        case OpCodes.Log: {
187            return Math.Log(Evaluate());
188          }
189        case OpCodes.IfThenElse: {
190            double condition = Evaluate();
191            double result;
192            if (condition > 0.0) {
193              result = Evaluate(); SkipBakedCode();
194            } else {
195              SkipBakedCode(); result = Evaluate();
196            }
197            return result;
198          }
199        case OpCodes.AND: {
200            double result = Evaluate();
201            for (int i = 1; i < currentInstr.nArguments; i++) {
202              if (result <= 0.0) SkipBakedCode();
203              else {
204                result = Evaluate();
205              }
206            }
207            return result <= 0.0 ? -1.0 : 1.0;
208          }
209        case OpCodes.OR: {
210            double result = Evaluate();
211            for (int i = 1; i < currentInstr.nArguments; i++) {
212              if (result > 0.0) SkipBakedCode();
213              else {
214                result = Evaluate();
215              }
216            }
217            return result > 0.0 ? 1.0 : -1.0;
218          }
219        case OpCodes.NOT: {
220            return -Evaluate();
221          }
222        case OpCodes.GT: {
223            double x = Evaluate();
224            double y = Evaluate();
225            if (x > y) return 1.0;
226            else return -1.0;
227          }
228        case OpCodes.LT: {
229            double x = Evaluate();
230            double y = Evaluate();
231            if (x < y) return 1.0;
232            else return -1.0;
233          }
234        case OpCodes.Call: {
235            // evaluate sub-trees
236            // push on argStack in reverse order
237            for (int i = 0; i < currentInstr.nArguments; i++) {
238              argumentStack[argStackPointer + currentInstr.nArguments - i] = Evaluate();
239            }
240            argStackPointer += currentInstr.nArguments;
241
242            // save the pc
243            int nextPc = pc;
244            // set pc to start of function 
245            pc = currentInstr.iArg0;
246            // evaluate the function
247            double v = Evaluate();
248
249            // decrease the argument stack pointer by the number of arguments pushed
250            // to set the argStackPointer back to the original location
251            argStackPointer -= currentInstr.nArguments;
252
253            // restore the pc => evaluation will continue at point after my subtrees 
254            pc = nextPc;
255            return v;
256          }
257        case OpCodes.Arg: {
258            return argumentStack[argStackPointer - currentInstr.iArg0];
259          }
260        case OpCodes.Variable: {
261            var variableTreeNode = currentInstr.dynamicNode as VariableTreeNode;
[4117]262            if (variables.ContainsKey(variableTreeNode.VariableName))
263              return variables[variableTreeNode.VariableName] * variableTreeNode.Weight;
264            else return -1.0 * variableTreeNode.Weight;
[4089]265          }
266        case OpCodes.Constant: {
267            var constTreeNode = currentInstr.dynamicNode as ConstantTreeNode;
268            return constTreeNode.Value;
269          }
270        default: throw new NotSupportedException();
271      }
272    }
273
274    // skips a whole branch
275    protected void SkipBakedCode() {
276      int i = 1;
277      while (i > 0) {
278        i += code[pc++].nArguments;
279        i--;
280      }
281    }
282  }
283}
Note: See TracBrowser for help on using the repository browser.