ECF 1.5
Evaluator.cpp
1#include "Evaluator.h"
2#include <cmath>
3
4
5
6bool Evaluator::initialize()
7{
8 initFunctionNames();
9 data.clear();
10 values = std::vector<double>(MAX_SUBTREES,0);
11 valueFlags = std::vector<bool>(MAX_SUBTREES, false);
12 return true;
13}
14
15
16void Evaluator::initFunctionNames()
17{
18 termNames.clear();
19 termNames.push_back("x1");
20 termNames.push_back("x2");
21
22 funcNames.clear();
23 funcNames.push_back("+");
24 funcNames.push_back("-");
25 funcNames.push_back("*");
26 funcNames.push_back("/");
27 funcNames.push_back("sin");
28 funcNames.push_back("cos");
29}
30
31
32double Evaluator::executeParsedExpression(uint sample, uint iTree)
33{
34 iExpression = iTree;
35 if (iSample != sample){
36 valueFlags = std::vector<bool>(MAX_SUBTREES, false); // This is VERY expensive and slows down the program
37 }
38 iSample = sample;
39 position = -1;
40
41 return execute();
42}
43
44
45double Evaluator::execute()
46{
47 position++;
48
49 switch(parsedExpression[iExpression][position])
50 {
51 case ADD:
52 return execute() + execute();
53 break;
54 case SUB:
55 return execute() - execute();
56 break;
57 case MUL:
58 return execute() * execute();
59 break;
60 case DIV: {
61 double d1 = execute();
62 double d2 = execute();
63 if(fabs(d2) < 0.00000001)
64 return 1;
65 else
66 return d1/d2;
67 break;
68 }
69 case SIN:
70 return sin(execute());
71 break;
72 case COS:
73 return cos(execute());
74 break;
75 default:
76 if( parsedExpression[iExpression][position] >= SUBTREES){
77 // Backup variables
78 uint iExpression_ = iExpression;
79 uint iSample_ = iSample;
80 int position_ = position;
81 // Get subtree index
82 uint subtree = parsedExpression[iExpression][position] - SUBTREES + 1;
83 double returnValue;
84 // Check whether this subtree has already been evaluated
85 if (valueFlags[subtree - 1]){
86 returnValue = values[subtree - 1];
87 }
88 else{
89 // Execute subtree expression
90 returnValue = values[subtree - 1] = executeParsedExpression(iSample, subtree);
91 valueFlags[subtree - 1] = true;
92 }
93 // Restore variables
94 iExpression = iExpression_;
95 iSample = iSample_;
96 position = position_;
97 return returnValue;
98 }
99 else return data[iSample][parsedExpression[iExpression][position] - TERMINALS];
100 break;
101 }
102}