inline bool Type_::GiveTerm(Evaluator & theEvaluator) { if ( this->thisExpression.IsEmpty() ) { return false; } Expression::FormRange<Form> theFormRange(this->thisExpression); assert(theFormRange); if ( theFormRange->GetOperator().IsEmpty() ) { Operand theOperand; { Form::OperandRange<Operand> theOperandRange(*theFormRange); assert(theOperandRange); theOperand.Swap(*theOperandRange); } this->thisExpression.FrontPopTerm(); theEvaluator.TakeOperand( *this, theOperand ); } else { Operator theOperator; this->thisExpression.FrontGiveTerm(theOperator); theEvaluator.TakeOperator( *this, theOperator ); } return true; }
void ui() { Evaluator eval; std::string input; std::cout << "\ntype an expression, \"exit\" to end\n"; while (true) { std::cout << ">>> "; std::getline(std::cin, input); if (input[0] == 'e' || input[0] == 'E') break; try { std::cout << eval.eval(input) << std::endl; } catch (std::invalid_argument err) { std::cout << "Error: " << err.what() << std::endl; } } }
int main() { Evaluator eval; vector<string> expression = { "1+2*3","2+2^2*3" ,"1==2", "1+3 > 2", "(4>=4) && 0", "(1+2)*3" }; //<--expressions we wish to evaluate go here vector<string>::iterator exprItr; for (exprItr = expression.begin(); exprItr != expression.end(); exprItr++) { try { int result = eval.eval(*exprItr); cout << eval.infix_expression.c_str() << " = " << result << endl << endl; } catch (Syntax_Error e) { cout << eval.infix_expression.c_str() << endl << e.what() << " " << "@ char: " << eval.position << endl << endl; } } system("pause"); return 0; }
bool FieldmlSession::getDelegateEvaluators( FmlObjectHandle handle, vector<FmlObjectHandle> &stack, set<FmlObjectHandle> &delegates ) { set<FmlObjectHandle> evaluators; if( handle == FML_INVALID_HANDLE ) { //Convenience so that callers don't have to check return true; } if( FmlUtil::contains( stack, handle ) ) { //Recursive dependency! return false; } //TODO: Figure out why this works even though there's no popping happening. stack.push_back( handle ); Evaluator *evaluator = Evaluator::checkedCast( this, handle ); if( evaluator != NULL ) { if( evaluator->addDelegates( evaluators ) ) { if( !getDelegateEvaluators( evaluators, stack, delegates ) ) { return false; } } } return true; }
/*static*/ void Thread::ThreadProc(void* pvoid) { // Create an evaluator Evaluator eval; // Run code eval.Eval((Object*)pvoid); }
int main(int argc, char** argv) { std::string expr = "w x z - +"; Evaluator* sentence = new Evaluator(expr); std::map<std::string, Expr*> variables = new std::map<std::string, Expr*>(); variables.put("w", new Number(5)); variables.put("x", new Number(10)); variables.put("z", new Number(32)); int result = sentence->interpret(variables); std::cout << "Computation result: " << result << std::endl; }
int evaluate(T& src) { Evaluator e; try { e.eval(src); return 0; } catch (const Error& e) { std::cerr << DASHES << std::endl; std::cerr << "Unhandled exception!" << std::endl << std::endl; std::cerr << e.what() << std::endl; std::cerr << DASHES << std::endl; return 1; } }
JNIEXPORT jstring JNICALL Java_com_starlon_libscriptable_UtilsEvaluator_evaluate( JNIEnv *env, jclass clazz, jobject obj, jstring str) { Evaluator *eval = getObjectFromCPtr<Evaluator *>( env, obj ); jboolean isCopy; const char * _str = env->GetStringUTFChars(str, &isCopy); std::string val = eval->Eval((std::string)_str); env->ReleaseStringUTFChars(str, _str); return env->NewStringUTF(val.c_str()); }
int32 SearchAlgorithm::BeginSearch(int32 a_turn, uint32 a_depthRemain, Board &a_board, Evaluator &a_evaluator, uint32 &a_countNodes) { m_bestMoves.clear(); m_bestMoves.resize(MAX_SEARCH_DEPTH); a_board.ClearTakenChesses(); a_evaluator.Evaluate(a_board); m_transpositionTable->InitByBoard(a_turn, a_board); m_currentDepth = 0; int32 score = Search(a_turn, a_depthRemain, a_board, a_evaluator, a_countNodes); if (!GetBestMoves().empty()) { MovePos bestMove = *(GetBestMoves().begin()); GetTranspositionTable()->ChangeKeyByMoving(a_board.GetTypeAt(bestMove.from), bestMove.from, a_board.GetTypeAt(bestMove.to), bestMove.to); m_boardLog.push_back(GetTranspositionTable()->GetCurrentKey()); GetTranspositionTable()->ChangeKeyByMoving(a_board.GetTypeAt(bestMove.from), bestMove.from, a_board.GetTypeAt(bestMove.to), bestMove.to); } ++m_currentPlay; return score; }
// This method is called by the Solver object at every iteration. bool RandomSearcher::search(const unsigned int max_dim, const double delta, const double * poll_center, std::vector<AugmentedPoint *> & list_of_points, Evaluator & eval) { if (display_factor >= 3) { cout << "\nStart of random search: " << search_pts << " points, "; cout << "delta = "<< delta << "\n-----------------------\nPoll center ("; for (unsigned int i = 0; i < max_dim - 1; i++) cout << poll_center[i] << " "; cout << poll_center[max_dim - 1] << ")\n"; cout << "\nCurrent best iterate: "; eval.showIncumbent(); cout << "\n"; } // createArrays(max_dim, delta, poll_center); /* This function call returns the number of points the random search will generate. */ double nb_of_points = generateHowManyPts(max_dim); /* This function creates the list of points that will be sent to 'Evaluator', from the list of shuffled points. */ fillTheList(max_dim, delta, poll_center, nb_of_points, list_of_points); // The 'complete_search' variable is returned. return (complete_search); }
int main(int argc, const char** argv) { std::unique_ptr<Expr> c1(new Constant(1.1)); std::unique_ptr<Expr> c2(new Constant(2.2)); std::unique_ptr<Expr> p1(new BinaryPlus(*c1, *c2)); std::unique_ptr<Expr> p2(new BinaryPlus(*p1, *c2)); Stringifier s; p2->Accept(&s); std::cout << s.GetStringForExpr(*p2) << "\n"; Evaluator e; p2->Accept(&e); std::cout << e.GetValueForExpr(*p2) << "\n"; return 0; }
Expr* get_length(Layout_decl const* layout) { Evaluator eval; Expr* e = 0; for (Decl* d : layout->fields()) { Type const* t1 = d->type(); // If member is constant, just add in the constant value if (has_constant_length(t1)) e = add(e, make_int(precision(t1))); // Otherwise, we have to form a call to the function // that would compute this type. else { // FIXME: Do this right! throw std::runtime_error("unimplemented dynamic length calc."); e = add(e, zero()); } } // Compute ceil(e / 8). Expr* b = make_int(8); // bits per byte Expr* r = div(sub(add(e, b), one()), b); // Try folding the result. If it works, good. If not, // just return the previously computed expression. // // TODO: Maximally reduce the expression so that we only // add the constant bits to the non-constant bits. Since // addition is associative and commutative, we can // partition the sequence of terms into constants and // non-constants, and then sum the constant parts. try { Value v = eval.eval(r); if (v.is_integer()) return make_int(v.get_integer()); else throw std::runtime_error("failed to synth length"); } catch(...) { return r; } }
// Compare solution with a randomly generated opponent, return whichever // has the higher fitness void hill_climb::binary_tournament(Random & rand, vector<bool> & solution, float & fitness, Evaluator& evaluator) { auto guess = rand_vector(rand, solution.size()); float guess_fitness = evaluator.evaluate(guess); if (fitness < guess_fitness) { solution = guess; fitness = guess_fitness; } }
bool TestDocument::evaluate(Evaluator &evaluator) { bool rval = true; XMLSize_t numpass = 0; XMLSize_t numfail = 0; std::map<char *, bool, ltcstr> test_state; XMLCh *TEST = xercesc::XMLString::transcode("test"); XMLCh *PREREQ = xercesc::XMLString::transcode("prereq"); xercesc::DOMElement *root = doc->dom->getDocument()->getDocumentElement(); xercesc::DOMNodeList *tests = root->getElementsByTagName(TEST); XMLSize_t numtests = tests->getLength(); std::cout << numtests << " tests found in " << doc->path << std::endl; for (int i = 0; i < numtests; i++) { xercesc::DOMElement *e = static_cast<xercesc::DOMElement*>(tests->item(i)); Test test(*this, e); bool testval = true; std::cout << "test " << (i+1) << " of " << numtests << ": " << test.id << "... "; if (e->hasAttribute(PREREQ)) { char *prereqs = xercesc::XMLString::transcode(e->getAttribute(PREREQ)); char *scan = prereqs; std::stringstream prereq; while (char c = *scan++) { if (c == ' ' || c == ',') { testval = __checkPrereq(test, test_state, prereq) && testval; prereq.str(""); } else { prereq << c; } } testval = __checkPrereq(test, test_state, prereq) && testval; xercesc::XMLString::release(&prereqs); } if (testval) { testval = evaluator.evaluate(*this, test) && testval; testval = js_evaluator.evaluate(*this, test) && testval; } if (testval) { std::cout << "[OK]"; numpass++; } else { std::cout << "[FAIL] (" << test.messages.str() << ")"; numfail++; } std::cout << std::endl; test_state[xercesc::XMLString::replicate(test.id)] = testval; rval = testval && rval; } for (std::map<char *, bool, ltcstr>::iterator i = test_state.begin(); i != test_state.end(); i++) { xercesc::XMLString::release((char**)&i->first); } xercesc::XMLString::release(&TEST); xercesc::XMLString::release(&PREREQ); std::cout << numpass << " of " << numtests << " tests passed, " << numfail << " failed (" << ( ((double)numpass) / ((double)numtests) * 100.0 ) << "%)" << std::endl; return rval; }
void main(){ // Construct the Context first map<string,int> Dict; Dict["一"] = 1; Dict["二"] = 2; Dict["三"] = 3; Dict["四"] = 4; Dict["五"] = 5; Dict["六"] = 6; Dict["七"] = 7; Dict["八"] = 8; Dict["九"] = 9; Evaluator myEvaluator = Evaluator(); myEvaluator.Construct("五加二"); double result = myEvaluator.Interprete(Dict); cout<<result<<endl; while(1){ } }
void run(){ while (RUN_CONSUMER){ RawPacketElem raw_data; ParsedPacketElem parsed_data; get(&raw_data); if (parse(&raw_data, &parsed_data)){ stats->put(&(parsed_data.ip_layer.src_addr), &parsed_data); } } }
Expr* gather(Expr_seq const& subkeys) { // maintain the largest allowable key buffer uint512_t buf = 0; Evaluator ev; // maintain the position to start writing int pos = 0; for (auto subkey : subkeys) { // get the precision of the subkey int prec = precision(subkey->type()); Value const& val = ev.eval(subkey); // FIXME: for now we're only dealing with unsigned integer values assert(val.is_integer()); std::stringstream ss; ss << val.get_integer().decimal_str(); uint512_t i = 0; ss >> i; // shift the integer over by the amount already written i = i << pos; // add the length of the current integer to the pos pos += prec; // log-and the integer into the buffer buf |= i; } char* bytes = new char[pos / 8]; char* key = reinterpret_cast<char*>(&buf); std::copy(key, key + (pos / 8), bytes); Array_value arr { bytes, (size_t) pos / 8 }; Type const* z = get_integer_type(); Expr* n = new Literal_expr(z, arr.len + 1); // Create the array type. Type const* c = get_character_type(); Type const* t = get_array_type(c, n); return new Literal_expr(t, arr); }
double backtracking_linear_search( Evaluator& evaluator, // class of objective function value evaluation double *xp, // backup place for x double *p, // negative of search direction double *fx, // current function value at x double c, // sufficient decrease condition threshold double init_step, // initial step length double r, // scale factor in backtracking int *evaluateCnt // counter ){ double *x=0; //current points int n=evaluator.get_current_parameter(x); double *g=evaluator.get_gradient_vec(); double dec=vec_dot(g,p,n); //cout<<"#IN_LINEAR_SEARCH unit decrease of g'p="<<dec<<endl; if(dec<0){ // non suitable step,p is not a descent search direction return -1; } // for(int i=0;i<5;i++) cout<<"x["<<i<<"]="<<x[i]<<" p["<<i<<"]="<<p[i]<<endl; double alpha=init_step; //vec_add(xp,x,p,n,1,-alpha); // p is the negative of search of direction //TODO: do it better for(int i=0;i<n;++i) xp[i]=(x[i]-alpha*p[i]<1e-6)?0:(x[i]-alpha*p[i]); double old_fx=*fx; *fx=evaluator.evaluate(xp,g); ++(*evaluateCnt); int trials=0; while( *fx > old_fx-alpha*c*dec ){ //cout<<"-----try step length "<<alpha<<" get obj="<<*fx<<" dec="<<old_fx-*fx<<" require min dec="<<alpha*c*dec<<endl; alpha*=r; //vec_add(xp,x,p,n,1,-alpha); //TODO: do it better for(int i=0;i<n;++i) xp[i]=(x[i]-alpha*p[i]<1e-6)?0:(x[i]-alpha*p[i]); *fx=evaluator.evaluate(xp,g); ++(*evaluateCnt); ++trials; } //cout<<"#IN_LINEAR_SEARCH success linear search, get alpha="<<alpha<<" obj="<<*fx<<" dec="<<old_fx-*fx<<" required min dec="<<alpha*c*dec<<" trails="<<trials<<endl; return alpha; }
int main() { Evaluator eval; string input; cout<<"'exit' to quit"<<endl<<endl; while (true) { cout<<"Enter expression: "; std::getline(cin, input, '\n'); if (input == "exit") break; try { Object obj = eval.evaluate(input); cout<<obj.symbol()<<" = "<<obj.value().value()<<endl; } catch (Error error) { cout<<error.message<<endl; } } return 0; }
// Constructor. RandomSearcher::RandomSearcher(const unsigned int how_many_pts, const bool complete, Evaluator & eval) : Searcher(how_many_pts, complete) { // 'r_max' contains the largest possible random number generated. r_max = RAND_MAX; // If there are bound constraints... if (eval.getConstraints() ) { // ...we point to them with 'lower' and 'upper'. lower = eval.getLowerBounds(); upper = eval.getUpperBounds(); } else // There are no bound constraints. { lower = NULL; upper = NULL; } // The arrays are NULL at the start. left = NULL; total = NULL; }
void CorrectionEngine::evaluate(const std::string& path, std::string& sResult) const { std::string resource; if (!boost::filesystem::exists(path)) resource = workdir_; else if(!boost::filesystem::is_directory(path)) resource = workdir_; else resource = path; std::ofstream out; out.open("errors", std::ofstream::out | std::ofstream::trunc); boost::filesystem::directory_iterator end; for(boost::filesystem::directory_iterator it(resource) ; it != end ; ++it) { const std::string p = it->path().string(); if(boost::filesystem::is_regular_file(p)) { if (!EvaluatorFactory::isValid(p)) continue; Evaluator* evaluator = EvaluatorFactory::load(p); Evaluator::iterator it = evaluator->begin(); for (; it != evaluator->end(); ++it) { std::string result; double freq = 0.0; correct(it->userQuery(), result, freq); evaluator->isCorrect(out, result); } EvaluatorFactory::destory(evaluator); } } out.close(); Evaluator::toString(sResult); Evaluator::clear(); }
int analyzeEvalBin() { Loggers::error.addStream(std::cerr, "\x1b[31m", "\x1b[39m"); Loggers::warning.addStream(std::cerr, "\x1b[33m", "\x1b[39m"); Loggers::message.addStream(std::cerr); Loggers::send.addStream(std::cerr, true, true, "\x1b[34m", "\x1b[39m"); Loggers::receive.addStream(std::cerr, true, true, "\x1b[35m", "\x1b[39m"); #ifndef NDEBUG Loggers::debug.addStream(std::cerr, "\x1b[36m", "\x1b[39m"); Loggers::develop.addStream(std::cerr, "\x1b[37m", "\x1b[39m"); #endif // NDEBUG Evaluator eval; eval.readFile(); Evaluator::ValueType max = 0; int64_t magnitude = 0ll; int32_t nonZero = 0; auto func = [](const Evaluator::ValueType& e, Evaluator::ValueType& max, int64_t& magnitude, int32_t& nonZero) { max = std::max(max, (Evaluator::ValueType)std::abs(e)); magnitude += std::abs(e); nonZero += e != 0 ? 1 : 0; }; for (int i = 0; i < Evaluator::size(); i++) { func(((Evaluator::ValueType*)eval.t_)[i], max, magnitude, nonZero); } Loggers::message << "max=" << max << "\tmagnitude=" << magnitude << "\tnonZero=" << nonZero << "\tzero=" << (Evaluator::size() - nonZero); return 1; }
// Compute error function void UnconstrainedOptimizer::F() { memcpy(vecGradient.get(),x,n*sizeof(double)); currentModel->setWeights(vecGradient); if(currentModel->getDebugLevel() >= 2) std::cout << "Compute error..." << std::endl; f = currentEvaluator->computeError(currentDataset, currentModel); if(currentModel->getDebugLevel() >= 3) { // printf(" Iteration # = %i Nb error eval = %i Nb gradient eval = %i\n\n", cnls, cnf, cng); // printf("F = %-0.10lg\n",f); std::cout << " Iteration # = " << cnls << " Nb error eval = " <<cnf << " Nb gradient eval = " << cng <<std::endl << std::endl; std::cout << "F = " << f << std::endl; std::cout.flush(); } }
// Attempt to flip each bit in a random order, accepting improvements // as they are found. Test each bit exactly once for improvement void hill_climb::once_each(Random & rand, vector<bool> & solution, float & fitness, Evaluator& evaluator) { vector<int> options(solution.size()); iota(options.begin(), options.end(), 0); float new_fitness; std::shuffle(options.begin(), options.end(), rand); for (const auto& index : options) { // flip the bit and evaluate new fitness solution[index] = not solution[index]; new_fitness = evaluator.evaluate(solution); if (fitness < new_fitness) { fitness = new_fitness; } else { solution[index] = not solution[index]; } } }
BitMoveOrderingIterator::BitMoveOrderingIterator( const Board& board, Evaluator<Board>& eval) : board_(board), sorted_next_() { std::vector<eval_t> sort_key; BitBoard::data_type moves = board.get_move_bit(); while (moves.any()) { BitBoard::data_type next = moves.get_next_bit(); unsigned pos = next.get_next(); BitBoard next_board(board); next_board.try_move(pos); eval_t v = eval.evaluate(next_board, BLACK); sort_insert(sort_key, sorted_next_, v, pos); moves ^= next; } current_ = sorted_next_.begin(); }
// Only modify the solution once you know which single bit change will // result in the best fitness improvement void hill_climb::steepest_ascent(Random & rand, vector<bool> & solution, float & fitness, Evaluator& evaluator) { float new_fitness; bool improved; // keep a list of which locations are tied for the most improvement vector<size_t> bests; // Stores which bit was flipped to create the current solution size_t previous = -1; // Keep looping until there is no single bit flip improvement do { improved = false; for (size_t working = 0; working < solution.size(); working++) { if (working != previous) { // flip the bit and determine the new fitness solution[working] = not solution[working]; new_fitness = evaluator.evaluate(solution); if (fitness <= new_fitness) { // strict improvements clear out the old list if (fitness < new_fitness) { fitness = new_fitness; improved = true; bests.clear(); } // Record the index of each solution that obtained the best fitness bests.push_back(working); } // revert the change solution[working] = not solution[working]; } } if (improved) { // choose a random gene from those resulting in an equally large improvement int index = std::uniform_int_distribution<int>(0, bests.size() - 1)(rand); previous = bests[index]; solution[previous] = not solution[previous]; bests.clear(); } } while (improved); }
std::vector<std::shared_ptr<Solution>> GeneticAlgorithm::solveImpl(Evaluator& evaluator, TerminationCriteria& termination) { //遺伝子の初期化 std::vector<std::shared_ptr<Solution>> genes(inits.size()); std::transform(inits.begin(), inits.end(), genes.begin(), [](std::shared_ptr<Solution> init) { return std::make_shared<Solution>(*init); }); //初回の評価 evaluation(evaluator, genes, *getHistory(), randomEngine); getHistory()->addGeneration(genes); //世代を進める while (!termination.meets(evaluator.getEvaluationCount(), *getHistory())) { advanceGeneration(evaluator, genes); getHistory()->addGeneration(genes); } //解を良い順に並べて返す std::sort(genes.begin(), genes.end(), [](std::shared_ptr<Solution> lhs, std::shared_ptr<Solution> rhs){ return lhs->getFitness() < rhs->getFitness(); }); return genes; }
// Iteratively tests bits in a random order, accepting improvements as they // are found. Tracks bits that have been tested since the last modification // to prevent waste. void hill_climb::first_improvement(Random & rand, vector<bool> & solution, float & fitness, Evaluator& evaluator) { // Set up data structure for random bit selection vector<int> options(solution.size()); iota(options.begin(), options.end(), 0); float new_fitness; bool improvement; // keep track of locations already tried since last improvement std::unordered_set<int> tried; // Keep looping until there is no single bit flip improvement do { improvement = false; // Test the bits in a random order std::shuffle(options.begin(), options.end(), rand); for (const auto& index : options) { // If this location has already been tried, skip to the next one if (tried.count(index) != 0) { continue; } // flip and evaluate the modification solution[index] = not solution[index]; new_fitness = evaluator.evaluate(solution); if (fitness < new_fitness) { // Keep change, update variables fitness = new_fitness; improvement = true; tried.clear(); } else { // Revert the change solution[index] = not solution[index]; } tried.insert(index); } } while (improvement); }
void MyDomain::received(char* str) { static double Tottime=0; static long TotNoEval=0; //printf("\n %s", str); if (strncmp(str, "quit", 4)==0) { l.exit(); return; } if (strncmp(str, "pos ", 4)!=0) return; b.setState(str+4); if (verbose) { printf("\n\n==========================================\n"); printf(str+4); } int state = b.validState(); if ((state != Board::valid1) && (state != Board::valid2)) { printf("%s\n", Board::stateDescription(state)); switch(state) { case Board::timeout1: case Board::timeout2: case Board::win1: case Board::win2: printf("\nTotal run time for player "); printf("%s ", (myColor == Board::color1) ? "O":"X"); printf(" = %lf\n", (Tottime/1000)); printf("Absolute evaluations = %ld\n ", TotNoEval); printf("Evaluations per sec = %lf \n", (TotNoEval*1000/Tottime)); l.exit(); default: break; } return; } if (b.actColor() & myColor) { struct timeval t1, t2; gettimeofday(&t1,0); Move m = b.bestMove(); gettimeofday(&t2,0); int msecsPassed = (1000* t2.tv_sec + t2.tv_usec / 1000) - (1000* t1.tv_sec + t1.tv_usec / 1000); printf("%s ", (myColor == Board::color1) ? "O":"X"); if (m.type == Move::none) { printf(" can not draw any move ?! Sorry.\n"); return; } printf("draws '%s' (after %d.%03d secs)...\n", m.name(), msecsPassed/1000, msecsPassed%1000); Tottime += msecsPassed; b.playMove(m, msecsPassed); sendBoard(); if (changeEval) ev.changeEvaluation(); // Sum up evaluations TotNoEval += ev.getNoEval(); /* stop player at win position */ int state = b.validState(); if ((state != Board::valid1) && (state != Board::valid2)) { printf("%s\n", Board::stateDescription(state)); switch(state) { case Board::timeout1: case Board::timeout2: case Board::win1: case Board::win2: printf("\nTotal run time for player "); printf("%s ", (myColor == Board::color1) ? "O":"X"); printf(" = %lf\n", (Tottime/1000)); printf("Absolute evaluations = %ld\n ", TotNoEval); printf("Evaluations per sec = %lf \n", (TotNoEval*1000/Tottime)); l.exit(); default: break; } } maxMoves--; if (maxMoves == 0) { //printf("\n %s", str); printf("Terminating because given number of moves drawn.\n"); broadcast("quit\n"); l.exit(); } } }
/** * Pops two values off the stack and returns the first raised to the power of the reciprocal of the second. * @param evaluator The current evaluation. * @return The second value'th root of the first popped value. */ double RootNode::evaluate(Evaluator& evaluator) const { double arg2 = evaluator.pop(); double arg1 = evaluator.pop(); return pow(arg1, 1.0 / arg2); }