float AI::evalTree(NDVector<node> & tree,space & sp) { if(sp.action == SPAWN) return 15; //TODO change to actually use the tree return rand()%11-5; unsigned int i; float partial=0; if(tree.value.op=='#') { return tree.value.number; } else { //operator if(tree.value.op == '+') { for(i=0;i<tree.size();i++) { partial+=evalTree(tree[i],sp); } } else if(tree.value.op == '*') { for(i=0;i<tree.size();i++) { partial*=evalTree(tree[i],sp); } } // else if(tree } return partial; }
long int evalTree(tree *t,bool debug) { if (t->action->type==INTEGER) return getValue(t->action); if (t->action->type==VARIABLE) return getValue(t->action); if (t->action->type==EOS) { if (debug) printf("Statement result: %ld\n",evalTree(t->left,debug)); else evalTree(t->left,debug); return evalTree(t->right,debug); } if (t->action->type==SET) { token * var=t->left->action; long int newval= evalTree(t->right,debug); if (debug) printf("Set %s=%ld\n",var->name,newval); setValue(var,newval); return newval; } if (t->action->type==WHILE) { tree * cond = t->left; tree * body = t->right; long int cval,bval=0; cval=evalTree(cond,debug); while(cval>0) { bval=evalTree(body,debug); if (debug) printf("While %ld : %ld\n",cval,bval); cval=evalTree(cond,debug); /* cval = bval; */ } if (debug) printf("While 0 ... final value is %ld\n",bval); return bval; } long int left=evalTree(t->left,debug); long int right=evalTree(t->right,debug); switch (t->action->type) { case PLUS: if (debug) printf("%ld + %ld = %ld\n",left,right,left+right); return left+right; case MINUS: if (debug) printf("%ld - %ld = %ld\n",left,right,left-right); return left-right; case MULTIPLY: if (debug) printf("%ld * %ld = %ld\n",left,right,left*right); return left*right; case DIVIDE: if (debug) printf("%ld / %ld = %ld\n",left,right,left/right); return left/right; default: printf("Unrecognized action for subtree Token: "); printToken(t->action); } return 0; }
int main(int argc,char **argv) { token * currentToken; char buffer[4096]; tree * t; bool debug=false; buffer[0]='\0'; if (argc < 2) { printf("Invoke as %s \"expression\"\n",argv[0]); return 1; } strcpy(buffer,argv[1]); currentToken=nextToken(NULL,buffer,false); t=getExpList(¤tToken,buffer); if (currentToken != NULL) { tokenError("Syntax error... data left after expression parsed",buffer,currentToken); buffer[currentToken->location]=0x00; } printf("%s = %ld\n",buffer,evalTree(t,debug)); freeTree(t); return 0; }
void PAlgebraModDerived<type>::evalTree(RX& res, shared_ptr< TNode<RX> > tree, const vector<RX>& crt1, long offset, long extent) const { if (extent == 1) res = crt1[offset]; else { long half = extent/2; RX lres, rres; evalTree(lres, tree->left, crt1, offset, half); evalTree(rres, tree->right, crt1, offset+half, extent-half); RX tmp1, tmp2; mul(tmp1, lres, tree->right->data); mul(tmp2, rres, tree->left->data); add(tmp1, tmp1, tmp2); res = tmp1; } }
void PAlgebraModDerived<type>::CRT_reconstruct(RX& H, vector<RX>& crt) const { if (isDryRun()) { H = RX::zero(); return; } FHE_TIMER_START; long nslots = zMStar.getNSlots(); const vector<RX>& ctab = crtTable; clear(H); RX tmp1, tmp2; bool easy = true; for (long i = 0; i < nslots; i++) if (!IsZero(crt[i]) && !IsOne(crt[i])) { easy = false; break; } if (easy) { for (long i=0; i<nslots; i++) if (!IsZero(crt[i])) H += ctab[i]; } else { vector<RX> crt1; crt1.resize(nslots); for (long i = 0; i < nslots; i++) MulMod(crt1[i], crt[i], crtCoeffs[i], factors[i]); evalTree(H, crtTree, crt1, 0, nslots); } FHE_TIMER_STOP; }
/** * Evaluate a tree. * * @param tree The tree to evaluate */ double evalTree(Tree *tree) { double left = 0.0; double right = 0.0; eval_error = 0; switch(tree->nodetype) { case operator_node: if (tree->body.an_operator.left != NULL) left = evalTree(tree->body.an_operator.left); if (eval_error) return; if (tree->body.an_operator.right != NULL) right = evalTree(tree->body.an_operator.right); if (eval_error) return; switch (tree->body.an_operator.oper) { case OP_ADD: if (tree->body.an_operator.left != NULL) return left + right; else return right; case OP_SUB: if (tree->body.an_operator.left != NULL) return left - right; else return -right; case OP_MUL: return left * right; case OP_DIV: if (right == 0) { xxerror("Divide by"," 0"); break; } return left / right; case M_SIN: return sin(right); case M_COS: return cos(right); case M_TAN: return tan(right); case M_COTAN: return 1/tan(right); case M_LOG: return log10(right); case M_LOG2: return log(right)/log(2); case M_LOGE: return log(right); case M_SQRT: if (right < 0) { xxerror("Square root of a number must not be negative","!"); break; } return sqrt(right); case M_CEIL: return ceil(right); case M_FLOOR: return floor(right); case OP_POW: return pow(left,right); case OP_MOD: return fmod(left,right); case OP_FACT: return fact(left); default: xxerror("Unknown ", "operator/function"); } break; case value_node: return tree->body.value; case variable_node: { int idx = findVAR(tree->body.variable, 1); if (idx == -1) { break; } Tree *tr = VARIABLES[idx].tree; if (tr == NULL) { xxerror("Bad variable:", tree->body.variable); break; } return evalTree(tr); } } eval_error = 1; return 0; }
int evalTree(struct tree* t, unsigned short number){ if(!t){ printf("try to evaluate an empty tree"); return 0; } if(!t->defined){ printf("error: undefined tree detected"); return 0; } int s1,s2; if(t->type == CONSTANT) return t->value != 0; if(t->type == VARIABLE){ return ((t->value) & number)!=0; } // operator switch (t->value){ case OPNOT: s1 = evalTree(t->son1,number); return !s1; case OPAND: s1 = evalTree(t->son1,number); s2 = evalTree(t->son2,number); return s1 && s2; case OPOR: s1 = evalTree(t->son1,number); s2 = evalTree(t->son2,number); return s1 || s2; case OPXOR: s1 = evalTree(t->son1,number); s2 = evalTree(t->son2,number); return s1 ^ s2; case OPCONDITIONAL: s1 = evalTree(t->son1,number); s2 = evalTree(t->son2,number); return !s1 || s2; case OPBICONDITIONAL: s1 = evalTree(t->son1,number); s2 = evalTree(t->son2,number); return s1==s2; } printf("unknown operator"); return -1; }
int main(int argc, char *argv[]){ /* Itteration Variables */ int i = 1; int gen = 0; double bestSSE = DBL_MAX; /* Creating performance variables */ double genDiv = 0; double genSSE[3] = {0,0,0}; /* worst, avg, best */ double sseError[MAXPOP]; double val[NUMPOINTS][2]; /* Genetic Paramenters */ int populationSize = 500; /* Population size (constant) */ int treeDepth = 15; /* Maximum Tree Depth */ int maxGenerations = 50; /* Maximum Number of generations */ double sseGoal = 0.5; /* SSE error goal (for spartan) */ double pruneFactor = 0.0; /* Probability that a branch will be prunned */ double constProb = 0.60; /* Probability that a leaf will be a randomly choose (0,1) constant */ double mutationRate = 0.20; /* Mutation Rate (probability that a node will be mutated */ double swapRate = 0.7; /* Probability that crossover will occur */ double tournamentFraction = 0.40; /* fraction of individuals selected by tournament */ double rankFraction = 0.50; /* fraction of individual selected by rank */ double spartanFraction = 0.1; /* fraction of individuals selected by rank, copied as is */ struct geneticParam genParam; /* compat representation of generation */ node *forest[MAXPOP]; /* Forest of trees */ node *bestTree; /* Output Variables */ int train = 1; int performance = 1; double evalPoint = 0; FILE *out = stdout; char bestTreeName[128]; char response[128] = "Y"; strcpy(bestTreeName,"bestTree"); /* Processing Command Line Inputs */ for (i = 1; i < argc; i++){ if (strcmp(argv[i],"--maxDepth")==0){ sscanf(argv[++i],"%d",&treeDepth); } else if (strcmp(argv[i],"--test")==0){ test(); return EXIT_SUCCESS; } else if (strcmp(argv[i],"--popSize")==0){ populationSize = atoi(argv[++i]); } else if (strcmp(argv[i],"--pruneFactor")==0){ pruneFactor = (double)atof(argv[++i]); } else if (strcmp(argv[i],"--constProb")==0){ constProb = (double)atof(argv[++i]); } else if (strcmp(argv[i],"--sseGoal")==0){ sseGoal = (double)atof(argv[++i]); } else if (strcmp(argv[i],"--mutationRate")==0){ mutationRate = (double)atof(argv[++i]); } else if (strcmp(argv[i],"--swapRate")==0){ swapRate = (double)atof(argv[++i]); } else if (strcmp(argv[i],"--tournamentFraction")==0){ tournamentFraction = (double) atof(argv[++i]); rankFraction = 1.0 - tournamentFraction; } else if (strcmp(argv[i],"--rankFraction")==0){ rankFraction = (double) atof(argv[++i]); } else if (strcmp(argv[i],"--spartanFraction")==0){ spartanFraction = (double) atof(argv[++i]); } else if (strcmp(argv[i],"--maxGen")==0){ maxGenerations = atoi(argv[++i]); } else if(strcmp(argv[i],"--bestTreeName")==0){ strcpy(bestTreeName,argv[++i]); } else if (strcmp(argv[i],"--help")==0){ usage(stdout,argv[0]); exit(EXIT_SUCCESS); } else{ fprintf(stderr,"Argument %s is not reconized\n",argv[i]); usage(stderr,argv[0]); exit(EXIT_FAILURE); } } /* Checking Input Arguments */ if (populationSize > MAXPOP){ fprintf(stderr,"population size is set to the max at %d. Change define for larger population\n",MAXPOP); populationSize = MAXPOP; } if (mutationRate > 1) mutationRate = 0.1; if (swapRate > 1) swapRate = 0.1; if (tournamentFraction + rankFraction > 1.0){ fprintf(stderr,"Tournament Fraction %5.3f and rank fraction %5.3f are greater than 1.0\n", tournamentFraction,rankFraction); fprintf(stderr,"Both are set to default values\n"); tournamentFraction = 0.9; rankFraction = 1.0 - tournamentFraction; } genParam.mutationRate = mutationRate; genParam.swapRate = swapRate; genParam.touramentFraction = tournamentFraction; genParam.rankFraction = rankFraction; genParam.spartanFraction = spartanFraction; genParam.constProb = constProb; genParam.maxDepth = treeDepth; genParam.pruneFraction = pruneFactor; splash(out); /* Train or Run? */ if (argc <= 1){ fprintf(stdout,"Preform symbolic regression with genetic programming [y/n]:\n"); fscanf(stdin,"%s",response); if (strcmp(response,"y")==0 || strcmp(response,"Y")==0) train = 1; else train = 0; fprintf(stdout,"Do you want to print the performance of the best tree [y/n]: \n"); fscanf(stdin,"%s",response); if (strcmp(response,"y")==0 || strcmp(response,"Y")==0) performance = 1; else performance = 0; } /* Run Information */ fprintf(out,"Parameters:\n"); fprintf(out,"\tPopulation Size: %d\n\tMax Tree Depth: %d\n",populationSize,treeDepth); fprintf(out,"\tPrune factor: %3.2f\n\tConstant Probability: %3.2f\n",pruneFactor,constProb); fprintf(out,"\tSSE Goal: %3.2f\n\tMax Generations: %d\n",sseGoal,maxGenerations); fprintf(out,"\tSpartan Fraction: %3.2f\n",spartanFraction); fprintf(out,"\tTournament Fraction: %3.2f\n\tRank Fraction: %5.2f\n",tournamentFraction,rankFraction); fprintf(out,"\tMutation Rate: %3.2f\n\tSwap Rate: %3.2f\n",mutationRate,swapRate); printSet(); /* Reading in the data file */ importData("proj2-data.dat",val); /* Creating the intitial population */ if (train){ srand( time(NULL)); fprintf(stdout,"Creating Intial Population\n"); rampedHalfHalf(forest,populationSize,&genParam); /* Running Generations */ fprintf(out,"Generation\tDiversity\tMean SSE\tBest SSE\n"); while(gen < maxGenerations && bestSSE > sseGoal){ /* Diversity and SSE */ genDiv = diversity(forest,populationSize); bestSSE = SSE(forest,populationSize,val,genSSE,sseError,bestTreeName); fprintf(out,"\t%d\t%3.2f\t\t%3.2e\t%3.2e\n",gen,genDiv,genSSE[1],genSSE[2]); /* Genetic Operations */ breedGeneration(forest,populationSize,sseError,&genParam); gen++; } /* Diversity and SSE */ genDiv = diversity(forest,populationSize); bestSSE = SSE(forest,populationSize,val,genSSE,sseError,bestTreeName); fprintf(out,"\t%d\t%3.2f\t\t%3.2e\t%3.2e\n",gen,genDiv,genSSE[1],genSSE[2]); /* Clean up, clean up, everybody do your share */ deleteForest(forest,populationSize); } /* Looking at the performance of the best tree */ if (performance){ sprintf(response,"%s.postfix",bestTreeName); bestTree = bestTreeSummary(out,response,val); if (argc <= 1){ fprintf(stdout,"Enter value on which to test the tree [n to escape]: \n"); while(fscanf(stdin,"%lf",&evalPoint)==1){ fprintf(stdout,"Tree(%5.3f) = %5.3f\n",evalPoint,evalTree(bestTree,evalPoint)); } deleteTree(bestTree); } } return EXIT_SUCCESS; }
//TODO Test if you can build something and act on it in one turn void AI::buildQueue() { for(unsigned int i=0;i<plants.size();i++) { //cout<<"Working on plant: "<<i<<endl; //cout<<"HP: "<<plants[i].health()<<endl; //if its my plant and it can do something if(plants[i].ownerID() == playerID() && plants[i].canAct()) { //Spam talk string message="This is plant[" + plants[i].objectID(); message+="] owned by Player: "+plants[i].ownerID(); message+=" on turn "+turnNumber(); //char * temp = message.c_str(); plants[i].talk((char*)(message.c_str())); if(i==0) { plants[i].talk((char*)("Did calling talk twice append or replace the usual string?")); } //if you don't have a leaf if(!plants[i].leaf()) { if(canDo(i,LEAF)) { //a place to try growing a leaf space sp(plants[i].x(), plants[i].y(),i,LEAF); sp.rating=evalTree(leafTree,sp); que.push(sp); } /* else { space sp(plants[i].x(), plants[i].y(),i,LEAF); cout<<"CANT DO: "; sp.display(); } */ } //if you want to generate light else { //cout<<"Pushing NOOP"<<endl; space sp(plants[i].x(), plants[i].y(),i,NOOP); sp.rating=evalTree(noopTree,sp); //que.push(sp); } //if it doesn't have a root if(!plants[i].root()) { //I can do a root if(canDo(i,ROOT)) { //a place to try growing a root space sp(plants[i].x(), plants[i].y(),i,ROOT); sp.rating=evalTree(rootTree,sp); que.push(sp); } /* else { space sp(plants[i].x(), plants[i].y(),i,ROOT); cout<<"CANT DO: "; sp.display(); } */ } //for expansion else { if(canDo(i,SPREAD)) { for(unsigned int r=0;r<4;r++) { space sp(plants[i].x()+xoff[r], plants[i].y()+yoff[r],i,SPREAD); if(canSpawnHere[sp.x+1][sp.y+1]) { sp.rating=evalTree(rootTree,sp); que.push(sp); } } } } //if it doesn't have a flower and can make one if(!plants[i].flower()) { if(canDo(i,FLOWER)) { //a place to try growing a flower space sp(plants[i].x(), plants[i].y(),i,FLOWER); sp.rating=evalTree(flowerTree,sp); que.push(sp); } } //if you have a flower and can spawn else { if(canDo(i,SPAWN)) { for(unsigned int r=0;r<4;r++) { space sp(plants[i].x()+xoff[r], plants[i].y()+yoff[r],i,SPAWN); if(canSpawnHere[sp.x+1][sp.y+1]) { sp.rating=evalTree(spawnTree,sp); que.push(sp); } } } } } } // //cout<<"Bot of Build QUE"<<endl; }