Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/Symbolic/SimpleArithmeticExpressionInterpreter.cs @ 3462

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

Refactored symbolic expression tree encoding and problem classes for symbolic regression. #937 , #938

File size: 5.9 KB
Line 
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;
23using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using System.Collections.Generic;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Symbols;
29using HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols;
30using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Compiler;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
33  [StorableClass]
34  [Item("SimpleArithmeticExpressionInterpreter", "Interpreter for arithmetic symbolic expression trees including function calls.")]
35  public class SimpleArithmeticExpressionInterpreter : Item, 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      public const byte Variable = 5;
42      public const byte Constant = 6;
43      public const byte Call = 100;
44      public const byte Arg = 101;
45    }
46
47    private Dataset dataset;
48    private int row;
49    private Instruction[] code;
50    private int pc;
51
52    public IEnumerable<double> GetSymbolicExpressionTreeValues(SymbolicExpressionTree tree, Dataset dataset, IEnumerable<int> rows) {
53      this.dataset = dataset;
54      var compiler = new SymbolicExpressionTreeCompiler();
55      compiler.AddInstructionPostProcessingHook(PostProcessInstruction);
56      code = compiler.Compile(tree, MapSymbolToOpCode);
57      foreach (var row in rows) {
58        this.row = row;
59        pc = 0;
60        argumentStack.Clear();
61        var estimatedValue = Evaluate();
62        if (double.IsNaN(estimatedValue) || double.IsInfinity(estimatedValue)) yield return 0.0;
63        else yield return estimatedValue;
64      }
65    }
66
67    private Instruction PostProcessInstruction(Instruction instr) {
68      if (instr.opCode == OpCodes.Variable) {
69        var variableTreeNode = instr.dynamicNode as VariableTreeNode;
70        instr.iArg0 = (ushort)dataset.GetVariableIndex(variableTreeNode.VariableName);
71      }
72      return instr;
73    }
74
75    private byte MapSymbolToOpCode(SymbolicExpressionTreeNode treeNode) {
76      if (treeNode.Symbol is Addition) return OpCodes.Add;
77      if (treeNode.Symbol is Subtraction) return OpCodes.Sub;
78      if (treeNode.Symbol is Multiplication) return OpCodes.Mul;
79      if (treeNode.Symbol is Division) return OpCodes.Div;
80      if (treeNode.Symbol is HeuristicLab.Problems.DataAnalysis.Symbolic.Symbols.Variable) return OpCodes.Variable;
81      if (treeNode.Symbol is Constant) return OpCodes.Constant;
82      if (treeNode.Symbol is InvokeFunction) return OpCodes.Call;
83      if (treeNode.Symbol is Argument) return OpCodes.Arg;
84      throw new NotSupportedException("Symbol: " + treeNode.Symbol);
85    }
86
87    private Stack<List<double>> argumentStack = new Stack<List<double>>();
88    public double Evaluate() {
89      var currentInstr = code[pc++];
90      switch (currentInstr.opCode) {
91        case OpCodes.Add: {
92            double s = 0.0;
93            for (int i = 0; i < currentInstr.nArguments; i++) {
94              s += Evaluate();
95            }
96            return s;
97          }
98        case OpCodes.Sub: {
99            double s = Evaluate();
100            for (int i = 1; i < currentInstr.nArguments; i++) {
101              s -= Evaluate();
102            }
103            return s;
104          }
105        case OpCodes.Mul: {
106            double p = Evaluate();
107            for (int i = 1; i < currentInstr.nArguments; i++) {
108              p *= Evaluate();
109            }
110            return p;
111          }
112        case OpCodes.Div: {
113            double p = Evaluate();
114            for (int i = 1; i < currentInstr.nArguments; i++) {
115              p /= Evaluate();
116            }
117            return p;
118          }
119        case OpCodes.Call: {
120            // save current arguments
121            List<double> arguments = new List<double>();
122            // evaluate sub-trees
123            for (int i = 0; i < currentInstr.nArguments; i++) {
124              arguments.Add(Evaluate());
125            }
126            argumentStack.Push(arguments);
127            // save the pc
128            int nextPc = pc;
129            // set pc to start of function 
130            pc = currentInstr.iArg0;
131            // evaluate the function
132            double v = Evaluate();
133            argumentStack.Pop();
134            // restore the pc => evaluation will continue at point after my subtrees 
135            pc = nextPc;
136            return v;
137          }
138        case OpCodes.Arg: {
139            return argumentStack.Peek()[currentInstr.iArg0];
140          }
141        case OpCodes.Variable: {
142            var variableTreeNode = currentInstr.dynamicNode as VariableTreeNode;
143            return dataset[row, currentInstr.iArg0] * variableTreeNode.Weight;
144          }
145        case OpCodes.Constant: {
146            var constTreeNode = currentInstr.dynamicNode as ConstantTreeNode;
147            return constTreeNode.Value;
148          }
149        default: throw new NotSupportedException();
150      }
151    }
152  }
153}
Note: See TracBrowser for help on using the repository browser.