Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataAnalysis/HeuristicLab.Problems.DataAnalysis/3.3/Symbolic/SimpleArithmeticExpressionInterpreter.cs @ 11247

Last change on this file since 11247 was 5275, checked in by gkronber, 14 years ago

Merged changes from trunk to data analysis exploration branch and added fractional distance metric evaluator. #1142

File size: 12.7 KB
RevLine 
[3253]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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;
[4068]23using System.Collections.Generic;
[5275]24using HeuristicLab.Common;
[3253]25using HeuristicLab.Core;
26using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[4068]27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Compiler;
[3462]28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
[4068]29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[3373]30using HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols;
[3253]31
[3373]32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
[3253]33  [StorableClass]
[3462]34  [Item("SimpleArithmeticExpressionInterpreter", "Interpreter for arithmetic symbolic expression trees including function calls.")]
[5275]35  public sealed class SimpleArithmeticExpressionInterpreter : NamedItem, ISymbolicExpressionTreeInterpreter {
[3462]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;
[3841]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 LagVariable = 19;
65      public const byte Constant = 20;
66      public const byte Arg = 21;
[3462]67    }
68
[3841]69    private Dictionary<Type, byte> symbolToOpcode = new Dictionary<Type, byte>() {
70      { typeof(Addition), OpCodes.Add },
71      { typeof(Subtraction), OpCodes.Sub },
72      { typeof(Multiplication), OpCodes.Mul },
73      { typeof(Division), OpCodes.Div },
74      { typeof(Sine), OpCodes.Sin },
75      { typeof(Cosine), OpCodes.Cos },
76      { typeof(Tangent), OpCodes.Tan },
77      { typeof(Logarithm), OpCodes.Log },
78      { typeof(Exponential), OpCodes.Exp },
79      { typeof(IfThenElse), OpCodes.IfThenElse },
80      { typeof(GreaterThan), OpCodes.GT },
81      { typeof(LessThan), OpCodes.LT },
82      { typeof(And), OpCodes.AND },
83      { typeof(Or), OpCodes.OR },
84      { typeof(Not), OpCodes.NOT},
85      { typeof(Average), OpCodes.Average},
86      { typeof(InvokeFunction), OpCodes.Call },
87      { typeof(HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols.Variable), OpCodes.Variable },
88      { typeof(LaggedVariable), OpCodes.LagVariable },
89      { typeof(Constant), OpCodes.Constant },
90      { typeof(Argument), OpCodes.Arg },
91    };
[3491]92    private const int ARGUMENT_STACK_SIZE = 1024;
[3513]93
[3545]94    public override bool CanChangeName {
95      get { return false; }
96    }
97    public override bool CanChangeDescription {
98      get { return false; }
99    }
100
[5275]101    [StorableConstructor]
102    private SimpleArithmeticExpressionInterpreter(bool deserializing) : base(deserializing) { }
103    private SimpleArithmeticExpressionInterpreter(SimpleArithmeticExpressionInterpreter original, Cloner cloner) : base(original, cloner) { }
104    public override IDeepCloneable Clone(Cloner cloner) {
105      return new SimpleArithmeticExpressionInterpreter(this, cloner);
106    }
107
[3513]108    public SimpleArithmeticExpressionInterpreter()
109      : base() {
110    }
111
[3462]112    public IEnumerable<double> GetSymbolicExpressionTreeValues(SymbolicExpressionTree tree, Dataset dataset, IEnumerable<int> rows) {
[3294]113      var compiler = new SymbolicExpressionTreeCompiler();
[5275]114      Instruction[] code = compiler.Compile(tree, MapSymbolToOpCode);
115
116      for (int i = 0; i < code.Length; i++) {
117        Instruction instr = code[i];
118        if (instr.opCode == OpCodes.Variable) {
119          var variableTreeNode = instr.dynamicNode as VariableTreeNode;
120          instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
121          code[i] = instr;
122        } else if (instr.opCode == OpCodes.LagVariable) {
123          var variableTreeNode = instr.dynamicNode as LaggedVariableTreeNode;
124          instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
125          code[i] = instr;
126        }
[3253]127      }
128
[5275]129      double[] argumentStack = new double[ARGUMENT_STACK_SIZE];
130      foreach (var rowEnum in rows) {
131        int row = rowEnum;
132        int pc = 0;
133        int argStackPointer = 0;
134        yield return Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]135      }
[3462]136    }
137
[5275]138    private double Evaluate(Dataset dataset, ref int row, Instruction[] code, ref int pc, double[] argumentStack, ref int argStackPointer) {
[4022]139      Instruction currentInstr = code[pc++];
[3462]140      switch (currentInstr.opCode) {
141        case OpCodes.Add: {
[5275]142            double s = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3996]143            for (int i = 1; i < currentInstr.nArguments; i++) {
[5275]144              s += Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3294]145            }
146            return s;
147          }
[3462]148        case OpCodes.Sub: {
[5275]149            double s = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3294]150            for (int i = 1; i < currentInstr.nArguments; i++) {
[5275]151              s -= Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3294]152            }
[3733]153            if (currentInstr.nArguments == 1) s = -s;
[3294]154            return s;
155          }
[3462]156        case OpCodes.Mul: {
[5275]157            double p = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3294]158            for (int i = 1; i < currentInstr.nArguments; i++) {
[5275]159              p *= Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3294]160            }
161            return p;
162          }
[3462]163        case OpCodes.Div: {
[5275]164            double p = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3294]165            for (int i = 1; i < currentInstr.nArguments; i++) {
[5275]166              p /= Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3294]167            }
[3733]168            if (currentInstr.nArguments == 1) p = 1.0 / p;
[3294]169            return p;
170          }
[3841]171        case OpCodes.Average: {
[5275]172            double sum = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]173            for (int i = 1; i < currentInstr.nArguments; i++) {
[5275]174              sum += Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]175            }
176            return sum / currentInstr.nArguments;
177          }
178        case OpCodes.Cos: {
[5275]179            return Math.Cos(Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer));
[3841]180          }
181        case OpCodes.Sin: {
[5275]182            return Math.Sin(Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer));
[3841]183          }
184        case OpCodes.Tan: {
[5275]185            return Math.Tan(Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer));
[3841]186          }
187        case OpCodes.Exp: {
[5275]188            return Math.Exp(Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer));
[3841]189          }
190        case OpCodes.Log: {
[5275]191            return Math.Log(Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer));
[3841]192          }
193        case OpCodes.IfThenElse: {
[5275]194            double condition = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]195            double result;
196            if (condition > 0.0) {
[5275]197              result = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer); SkipBakedCode(code, ref pc);
[3841]198            } else {
[5275]199              SkipBakedCode(code, ref pc); result = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]200            }
201            return result;
202          }
203        case OpCodes.AND: {
[5275]204            double result = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]205            for (int i = 1; i < currentInstr.nArguments; i++) {
[5275]206              if (result <= 0.0) SkipBakedCode(code, ref pc);
[3841]207              else {
[5275]208                result = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]209              }
210            }
211            return result <= 0.0 ? -1.0 : 1.0;
212          }
213        case OpCodes.OR: {
[5275]214            double result = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]215            for (int i = 1; i < currentInstr.nArguments; i++) {
[5275]216              if (result > 0.0) SkipBakedCode(code, ref pc);
[3841]217              else {
[5275]218                result = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]219              }
220            }
221            return result > 0.0 ? 1.0 : -1.0;
222          }
223        case OpCodes.NOT: {
[5275]224            return -Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]225          }
226        case OpCodes.GT: {
[5275]227            double x = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
228            double y = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]229            if (x > y) return 1.0;
230            else return -1.0;
231          }
232        case OpCodes.LT: {
[5275]233            double x = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
234            double y = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3841]235            if (x < y) return 1.0;
236            else return -1.0;
237          }
[3462]238        case OpCodes.Call: {
[3409]239            // evaluate sub-trees
[3491]240            // push on argStack in reverse order
[3409]241            for (int i = 0; i < currentInstr.nArguments; i++) {
[5275]242              argumentStack[argStackPointer + currentInstr.nArguments - i] = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3409]243            }
[3747]244            argStackPointer += currentInstr.nArguments;
[3491]245
[3409]246            // save the pc
247            int nextPc = pc;
248            // set pc to start of function 
249            pc = currentInstr.iArg0;
250            // evaluate the function
[5275]251            double v = Evaluate(dataset, ref row, code, ref pc, argumentStack, ref argStackPointer);
[3491]252
253            // decrease the argument stack pointer by the number of arguments pushed
254            // to set the argStackPointer back to the original location
255            argStackPointer -= currentInstr.nArguments;
256
[3409]257            // restore the pc => evaluation will continue at point after my subtrees 
258            pc = nextPc;
259            return v;
260          }
[3462]261        case OpCodes.Arg: {
[3491]262            return argumentStack[argStackPointer - currentInstr.iArg0];
[3409]263          }
[3462]264        case OpCodes.Variable: {
[3373]265            var variableTreeNode = currentInstr.dynamicNode as VariableTreeNode;
[3462]266            return dataset[row, currentInstr.iArg0] * variableTreeNode.Weight;
267          }
[3841]268        case OpCodes.LagVariable: {
[5275]269            var laggedVariableTreeNode = currentInstr.dynamicNode as LaggedVariableTreeNode;
270            int actualRow = row + laggedVariableTreeNode.Lag;
[3841]271            if (actualRow < 0 || actualRow >= dataset.Rows) throw new ArgumentException("Out of range access to dataset row: " + row);
[5275]272            return dataset[actualRow, currentInstr.iArg0] * laggedVariableTreeNode.Weight;
[3841]273          }
[3462]274        case OpCodes.Constant: {
[3373]275            var constTreeNode = currentInstr.dynamicNode as ConstantTreeNode;
[3462]276            return constTreeNode.Value;
[3294]277          }
278        default: throw new NotSupportedException();
[3253]279      }
280    }
[3841]281
[5275]282    private byte MapSymbolToOpCode(SymbolicExpressionTreeNode treeNode) {
283      if (symbolToOpcode.ContainsKey(treeNode.Symbol.GetType()))
284        return symbolToOpcode[treeNode.Symbol.GetType()];
285      else
286        throw new NotSupportedException("Symbol: " + treeNode.Symbol);
287    }
288
[3841]289    // skips a whole branch
[5275]290    private void SkipBakedCode(Instruction[] code, ref int pc) {
[3841]291      int i = 1;
292      while (i > 0) {
293        i += code[pc++].nArguments;
294        i--;
295      }
296    }
[3253]297  }
298}
Note: See TracBrowser for help on using the repository browser.