int split_arg(const char *format, t_dbllist *lst_arg, t_dbllist *lst_str, int *i) { t_arg sarg; t_str sstr; int ret; ini_sarg(&sarg); ini_sstr(&sstr); if ((ret = checks(format, i, &sarg)) == -1) return (-1); *i = *i + 1; if (ret == -2) { ft_lstdbladd(lst_arg, &sarg, sizeof(t_arg)); sstr.str = ft_strdup(sarg.spec); ft_lstdbladd(lst_str, &sstr, sizeof(t_str)); recover_arg(format, lst_arg, lst_str, i); } else { ft_lstdbladd(lst_arg, &sarg, sizeof(t_arg)); sstr.str = ft_strdup(sarg.spec); ft_lstdbladd(lst_str, &sstr, sizeof(t_str)); if (format[*i] != '\0') recover_arg(format, lst_arg, lst_str, i); } return (1); }
// Export to R RcppExport SEXP rflann_RadiusSearch(SEXP query_SEXP, SEXP ref_SEXP, SEXP radiusSEXP, SEXP max_neighbourSEXP, SEXP buildSEXP, SEXP coresSEXP, SEXP checksSEXP) { BEGIN_RCPP Rcpp::RObject __result; Rcpp::RNGScope __rngScope; Rcpp::traits::input_parameter< Rcpp::NumericMatrix >::type query_(query_SEXP); Rcpp::traits::input_parameter< Rcpp::NumericMatrix >::type ref_(ref_SEXP); Rcpp::traits::input_parameter< double >::type radius(radiusSEXP); Rcpp::traits::input_parameter< int >::type max_neighbour(max_neighbourSEXP); Rcpp::traits::input_parameter< std::string >::type build(buildSEXP); Rcpp::traits::input_parameter< int >::type cores(coresSEXP); Rcpp::traits::input_parameter< int >::type checks(checksSEXP); __result = Rcpp::wrap(RadiusSearch(query_, ref_, radius, max_neighbour, build, cores, checks)); return __result; END_RCPP }
double strategytdexp4::getOutputBackgammonLossValue( const vector<double>& middles, const board& brd ) const { // special case - if the player 0 has taken any pieces in, the gammon loss prob is zero if( brd.bornIn0Raw() > 0 ) return 0; // also if there are no player 0 pieces in player 1's box, the backgammon win prob is zero vector<int> checks( brd.checkers0Raw() ); bool foundOne = brd.hit0Raw() > 0; if( !foundOne ) for( int i=18; i<24; i++ ) if( checks.at(i) > 0 ) { foundOne = true; break; } if( !foundOne ) return 0; // otherwise calculate the network value double val=0; for( int i=0; i<nMiddle; i++ ) val += outputBackgammonLossWeights.at(i) * middles.at(i); val += outputBackgammonLossWeights.at(nMiddle); // bias node return 1. / ( 1 + exp( -val ) ); }
t_map *check_map(t_map *map) { int x; int y; char cur; int enter_exists; y = 0; enter_exists = 0; while (y < map->height) { x = 0; while (x < map->width) { cur = map->map[y][x]; checks(cur, &enter_exists); if (cur != WALL_CHAR && (y == 0 || y == map->height - 1 || x == 0 || x == map->width - 1)) err_inside("Invalid map, holes exist on the edges.", 1); x++; } y++; } if (!enter_exists) err_inside("No entry for spawning player character on the map.", 1); return (map); }
int main(int argc, char *argv[]) { if (argc > 1) { if ((argc == 2) && (strcmp("--list", argv[1]) == 0)) { int i; for (i=0; testcases[i].locale != NULL; i++) { printf("%s\n", testcases[i].locale); } return 0; } else { int i; fprintf(stderr, "Illegal command line. Aborting.\n"); fprintf(stderr, "argc: %03d\n", argc); for (i=0; i<argc; i++) { fprintf(stderr, "%03d \"%s\"\n", i, argv[i]); } return 1; } } else { int ret = checks(); printf("Test result: %s\n", (ret)?"success":"failure"); return (ret)?0:1; } return -1; }
int main(int argc, char **argv, char **envp) { FILE *fp; char buf[BUFSIZ]; char *key; if (argc != 2) { puts("usage: prog keyname"); return 1; } key = argv[1]; if ((fp = fopen("input", "r")) == NULL) { perror("input"); return 1; } while (fgets(buf, sizeof(buf), fp) != NULL) { if (buf[strlen(buf)-1] == '\n') buf[strlen(buf)-1] = 0; printf("---> [%s] (%s)\n", buf, key); // checks("name", buf); // check name* first checks(key, buf); // check type:name then printf("\n\n\n"); } fclose(fp); return 0; }
int main() { int i, j; long long flag; clrscr(); printf("Enter the size of the matrix : "); scanf("%d", &n); for(i = 1; i < n-1; i++) { for(j = 1; j < n-1; j++) { c[i][j] = ' '; } } food(); c[s][x] = '>'; while(1) { clrscr(); c[g][h] = '$'; prints(); if(kbhit()) { hits(); if(checks()) { printf("\nGAME OVER.\n"); getch(); return 0; } delay(500); continue; } blank(); c[g][h] = ' '; pressed_key(); eat(); if(checks()) { printf("\nGAME OVER.\n"); getch(); return 0; } add_length(); delay(500); } }
int main (int argc, char* argv[]) { int fd1, fd2, nread1, nread2, rcomp=0, counter=0; char buffer1[1024], buffer2[1024]; int options[3]={0,0,0}; //correspoding to options[s,d,u] int arg = checks(argc, argv, options); if(arg < 0) return -1; fd1 = open(argv[1], 0); fd2 = open(argv[2], 0); int i; while (rcomp >= 0) { nread1 = read(fd1, buffer1, 1024); nread2 = read(fd2, buffer2, 1024); if(nread1<0 || nread2<0 ) { printf("Error in reading!\n"); rcomp=-1; } else { rcomp=compare(buffer1, buffer2, fd1, fd2, counter, options); } counter++; } //option -d if(options[1]==1) { int difference, lpos1, lpos2; lpos1=lseek(fd1, 0, 2); lpos2=lseek(fd2, 0, 2); if(lpos1>lpos2) difference=lpos1-lpos2; else difference=lpos2-lpos1; printf("The difference in File Lengths of %s and %s is %d\n", argv[1], argv[2], difference); } close(fd1); close(fd2); }
int main(){ initscr(); start_color(); colorStuff(); noecho(); while((ch=getch())!='q'){ erase(); curs_set(0); plinp(ch); checks(); draw(); drawPlayer(); } endwin(); curs_set(1); return 0; }
void dfs(vector<vector<char> > &board, int i, int j) { if (found) return; if (i == N*N) { found = true; return; } if (j == N*N) { dfs(board,i+1,0); return; } if (board[i][j] == '.') { vector<bool> checks(N*N+1, true); for (int t = 0; t < N*N; ++t) { if (board[t][j] != '.') { checks[board[t][j]-'0'] = false; } if (board[i][t] != '.') { checks[board[i][t]-'0'] = false; } } int s = (i/N)*N; int t = (j/N)*N; for (int ii = 0; ii < N; ++ii) { for (int jj = 0; jj < N; ++jj) { if (board[s+ii][t+jj] != '.') { checks[board[s+ii][t+jj]-'0'] = false; } } } for (int ii = 1; ii <= N*N && !found; ++ii) { if (checks[ii]) { board[i][j] = ii+'0'; dfs(board, i, j+1); } } if (!found) board[i][j] = '.'; } else { dfs(board,i, j+1); } }
int main(){ initscr(); start_color(); colorContent(); printw("What's your name?\n"); scanw("%s",pName); printw("Wow, %s? That's a really gay name.", pName); noecho(); while((ch=getch()) != 'q' && health > 0){ varReset(); erase(); if(pInput(ch)==1) hunger--; checks(); checkMath(); caps(); drawMap(); } erase(); attron(COLOR_PAIR(6)); printw("GAME OVER"); getch(); printw("\n"); attron(COLOR_PAIR(4)); if(ch=='q'){ printw("\nYou quit."); } else if(health==0){ printw("\nYou died."); } printw("\nPress 'q' to exit."); while((ch=getch())!='q'){ attron(COLOR_PAIR(6)); mvprintw(3,0,"Press 'q' to exit."); } endwin(); return 0; }
void compile(boost::program_options::variables_map vm, string out_file_name, string routine_name, map<string,type*>& inputs, map<string,type*>& inouts, map<string,type*>& outputs, vector<stmt*> const& prog) { // set up signal to end search after certain amount of time int sMinutes = vm["limit"].as<int>(); if (sMinutes > 0) { int sSeconds = sMinutes * 60; signal(SIGALRM, sig_alarm_handler); alarm(sSeconds); } // search strategy enum search_strategy {exhaustive, orthogonal, random, hybrid_orthogonal, ga, debug, thread}; search_strategy strat = ga; if (vm["search"].as<std::string>().compare("ex") == 0) { strat = exhaustive; } else if (vm["search"].as<std::string>().compare("debug") == 0) { strat = debug; } else if (vm["search"].as<std::string>().compare("orthogonal") == 0) { strat = orthogonal; } else if (vm["search"].as<std::string>().compare("random") == 0) { strat = random; } else if (vm["search"].as<std::string>().compare("hybrid_orthogonal") == 0) { strat = hybrid_orthogonal; } else if (vm["search"].as<std::string>().compare("ga") == 0) { strat = ga; } else if (vm["search"].as<std::string>().compare("thread") == 0) { strat = thread; } else { std::cout << "Error: unknown search strategy (--search):" << vm["search"].as<std::string>() << "\n\n"; exit(0); } // which backend bool noptr; if (vm["backend"].as<std::string>().compare("noptr") == 0) { noptr = true; } else { noptr = false; } std::cout << noptr << std::endl; // partitiong FIXME can't turn off anymore? /* bool partitionSet = true; if (vm.count("partition_off")) { partitionSet = false; } */ bool mpi = false; if (vm.count("distributed")) { mpi = true; } string pathToTop = getcwd(NULL,0); pathToTop += "/"; // std::cout << pathToTop << std::endl; // set up temporary workspace string tmpPath, fileName, path; if (setUpWorkSpace(out_file_name, fileName, path, tmpPath, pathToTop, vm.count("delete_tmp"))) { std::cout << "Failed to set up temporary directory for unique implementations\n"; return; } // set all work to be performed in temporary work directory out_file_name = tmpPath + fileName; // {{{ COST MODELS std::list<versionData*> orderedVersions; string testParam = vm["test_param"].as<std::string>(); string start, stop, step; string::size_type pos = testParam.find_first_of(":"); if (pos != string::npos) start = testParam.substr(0, pos); string::size_type last = pos+1; pos = testParam.find_first_of(":",last); if (pos != string::npos) stop = testParam.substr(last, pos-last); step = testParam.substr(pos+1,string::npos); if (boost::lexical_cast<int>(start) > boost::lexical_cast<int>(stop)) { std::cout << "Test parameters are illegal (start > stop)\n"; std::cout << "\tstart: " << start << "\n"; std::cout << "\tstop: " << stop << "\n"; return; } modelMsg msg(boost::lexical_cast<int>(start), boost::lexical_cast<int>(stop), boost::lexical_cast<int>(step)); msg.pathToTop = pathToTop; // build_machine 0 -> parallel, 1 -> serial // msg.parallelArch = build_machine((char*)(pathToTop.c_str()),0); if (msg.parallelArch == NULL) { std:: cout << "Error attempting to get cost with parallel analytic model\n"; //return; } // msg.serialArch = build_machine((char*)(pathToTop.c_str()),1); // if (msg.serialArch == NULL) { // std:: cout << "Error attempting to get cost with parallel analytic model\n"; //return; // } // analyticSerial, tempCount, analyticParallel, symbolic, noModel vector<model_typ> models; models.clear(); // the model we want to rank with should go first in this list //models.push_back(noModel); models.push_back(analyticParallel); //models.push_back(analyticSerial); //models.push_back(tempCount); // }}} precision_type = vm["precision"].as<std::string>(); #ifdef MODEL_TIME // time spent in memmodel routines boost::timer memmodelTimer; double memmodelTotal = 0.0; #endif /* Model deprecated double threshold; if (vm.count("use_model")) { std::cout << "\nAnalytic model enabled\n"; threshold = vm["threshold"].as<double>(); } */ std::vector<std::pair<int, double> >::iterator itr; graph g; std::vector<algo> algos; //std::cerr << "finished parsing" << std::endl; program2graph(prog, inputs, inouts, outputs, g); //std::cerr << "graph created" << std::endl; //std::ofstream out44("lower0.dot"); //print_graph(out44, g); //out44.close(); //use yices to compute types externally //#define TYPES #ifdef TYPES std::ofstream out("lower0.dot"); print_graph(out, g); out.close(); generate_constraints(g); #endif compute_types(g); #ifdef TYPES std::ofstream out("lower1.dot"); print_graph(out, g); out.close(); exit(0); #endif update_sizes(g); update_dim_info(g); init_algos(algos); assign_algorithms(algos, g); //std::cerr << "algorithms assigned" << std::endl; assign_work(algos, g); //std::cerr << "work assigned" << std::endl; rewrite_fun rewriters[] = { flip_transpose, //0 flip_transpose_stride, //1 merge_tmp_output, //2 merge_tmp_cast_output, //3 remove_intermediate_temporary, //4 merge_gets, //5 merge_sumto_store, //6 move_temporary, //7 remove_cast_to_output, //8 remove_input_to_cast, //9 remove_cast_to_cast, //10 merge_same_cast, //11 straighten_top_level_scalar_ops,//12 reduce_reductions //13 }; optim_fun optimizers[] = { fuse_loops, //0 fuse_loops_nested, //1 merge_scalars, //2 pipeline, //3 fuse_loops_n //4 }; optim_fun_chk checkers[] = { check_fuse_loops, check_fuse_loops_nested, check_merge_scalars, check_pipeline, check_fuse_loops_n }; partition_fun partition[] = { part_mult_left_result, //0 part_mult_right_result, //1 part_mult_left_right, //2 part_mult_scl_row, //3 part_mult_scl_col, //4 partition_add_col, //5 partition_add_row, //6 part_mult_scl, //7 partition_add //8 }; rewrite_fun part_checkers[] = { check_part_mult_left_result, check_part_mult_right_result, check_part_mult_left_right, check_part_mult_scl_row, check_part_mult_scl_col, check_partition_add_col, check_partition_add_row, check_part_mult_scl, check_partition_add }; vector<rewrite_fun> rewrites(rewriters, rewriters + sizeof(rewriters) / sizeof(rewrite_fun)); vector<optim_fun> optimizations(optimizers, optimizers + sizeof(optimizers) / sizeof(optim_fun)); vector<optim_fun_chk> checks(checkers, checkers + sizeof(checkers) / sizeof(optim_fun_chk)); vector<rewrite_fun> part_checks(part_checkers, part_checkers + sizeof(part_checkers)/sizeof(rewrite_fun)); vector<partition_fun> partitioners(partition, partition + sizeof(partition) / sizeof(partition_fun)); //std::cerr << "about to start lowering and optimizine" << std::endl; std::stack<work_item> s; string history = ""; #ifdef DUMP_DOT_FILES std::ofstream out("lower1.dot"); print_graph(out, g); out.close(); #endif #ifdef DUMP_GRAPHS graphToQuery(g,out_file_name,0,0); #endif if (vm.count("correctness")) { createCorrectnessTest(g, routine_name, out_file_name, inputs, outputs,msg,noptr); } // keep copy of base graph around graph *baseGraph = new graph(g); // {{{ Partition Space code_generation codetype = threadtile; string spec = vm["level1"].as<std::string>(); if (!spec.empty()) { string::size_type pos = spec.find_first_of(" "); if (pos == string::npos) { std::cout << "Bad format for level1 arg:" << spec << endl; exit(0); } else { string codetype_str = spec.substr(0, pos); if (codetype_str == "thread") { codetype = threadtile; } else if (codetype_str == "cache") { codetype = cachetile; } else { std::cout << "Bad format for level1 arg:" << spec << endl; std::cout << "needs to be thread or cache" << endl; exit(0); } } int err = parse_range(&partition_bounds[0][0], &partition_bounds[0][1], &partition_bounds[0][2], spec.substr(pos+1)); if (err) { std::cout << "Couldn't parse range for level1: " << spec << endl; exit(0); } if (partition_bounds[0][0] > partition_bounds[0][1]) { std::cout << "Test parameters are illegal (start > stop)\n"; std::cout << "\tstart: " << partition_bounds[0][0] << "\n"; std::cout << "\tstop: " << partition_bounds[0][1] << "\n"; exit(0); } // Now level 2 string spec = vm["level2"].as<std::string>(); std::cout << "spec:" << spec << endl; if (!spec.empty()) { MAX_PARTS = 2; string::size_type pos = spec.find_first_of(" "); cout << "pos = " << pos << endl; if (pos == string::npos) { std::cout << "Bad format for level2 arg:" << spec << endl; exit(0); } else { string codetype_str = spec.substr(0, pos); cout << "codetype_str: '" << codetype_str << "'" << endl; if (codetype_str == "thread" && codetype==cachetile) { std::cout << "ERROR: threads inside tile loops not supported" << endl; std::cout << "consider swapping level1 and level2 args" << endl; exit(0); } else if (codetype_str == "cache" && codetype==threadtile) { codetype = bothtile; } else { std::cout << "Bad format for level2 arg:" << spec << endl; std::cout << "needs to be thread or cache" << endl; exit(0); } } int err = parse_range(&partition_bounds[1][0], &partition_bounds[1][1], &partition_bounds[1][2], spec.substr(pos+1)); if (err) { std::cout << "Couldn't parse range for level2: " << spec.substr(pos) << endl; exit(0); } if (partition_bounds[1][0] > partition_bounds[1][1]) { std::cout << "Test parameters are illegal (start > stop)\n"; std::cout << "\tstart: " << partition_bounds[1][0] << "\n"; std::cout << "\tstop: " << partition_bounds[1][1] << "\n"; exit(0); } } else { // Only 1 level specified MAX_PARTS = 1; } } else { // no idea what this will do! // Maybe we should just throw an error here? Or at least a warning? std::cout << "WARNING: No threading or cache tiling specified" << endl; std::cout << "Performing Loop fusion only, search may get confused" << endl; MAX_PARTS = 0; } // }}} // initializing the partition type forest // cout << "initializing partition forest..." << endl; vector< partitionTree_t* > partitionForest; buildForest(partitionForest, g, MAX_PARTS); // cout << "success" << endl; /* for (int i = 0; i < partitionForest.size(); ++i) { partitionTree_t *t = partitionForest[i]; if (t != NULL) { stringstream o; o << "tree" << i << ".dot"; ofstream treefile(o.str().c_str()); printTree(treefile, t); } } */ initial_lower(g, algos, rewrites); //std::cout << "finished lowering and rewriting" << std::endl; #ifdef DUMP_DOT_FILES std::ofstream out2("lower2.dot"); print_graph(out2, g); out2.close(); #endif #if 0 for (int i = 0; i < g.num_vertices(); ++i) if (g.info(i).op & OP_ANY_ARITHMATIC) cout << i << "\t"; cout << "\n"; #endif int reps = vm["empirical_reps"].as<int>(); if (vm.count("distributed")) { createMPIEmpiricalTest(g, routine_name, out_file_name, inputs, outputs, noptr, reps); } else if (!vm.count("empirical_off")) { createEmpiricalTest(g, routine_name, out_file_name, inputs, outputs, noptr, reps); } compile_details_t cDetails(routine_name,tmpPath,fileName, vm.count("correctness"), vm.count("use_model"), !vm.count("empirical_off"), noptr, mpi, codetype, &inputs, &inouts, &outputs); build_details_t bDetails(&part_checks, &partitioners, &checks, &optimizations, &algos, &rewrites, &models, &msg); // int maxT = max(0,msg.parallelArch->threads); // std::cout << "Testing with " << maxT << " threads, step = " << min(4,maxT) << std::endl; // int stride = 2; // {{{ Strategy cases switch (strat) { case exhaustive: { std::cout << "entering exhaustive search" << endl; //int numVersions = 5; int bestVersion = smart_exhaustive(g, *baseGraph, cDetails, bDetails); // One way or another we have selected a version we are calling the best // or we failed if (bestVersion < 0) { std::cout << "All versions failed to generate or compile\n"; return; } else { std::cout << "\n----------------------------------\n"; std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n"; } // copy best version to same directory as input .m file // and report location handleBestVersion(fileName,path,tmpPath,bestVersion); break; } case orthogonal: { std::cout << "entering orthogonal search" << endl; //int numVersions = 5; int bestVersion = orthogonal_search(g, *baseGraph, cDetails, bDetails); // One way or another we have selected a version we are calling the best // or we failed if (bestVersion < 0) { std::cout << "All versions failed to generate or compile\n"; return; } else { std::cout << "\n----------------------------------\n"; std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n"; } // copy best version to same directory as input .m file // and report location handleBestVersion(fileName,path,tmpPath,bestVersion); break; } case random: { std::cout << "entering random search" << endl; int seconds = vm["random_count"].as<int>(); int bestVersion = genetic_algorithm_search(g, *baseGraph, partitionForest, seconds, 1, false, cDetails, bDetails).best_version; // pop = 1 // One way or another we have selected a version we are calling the best // or we failed if (bestVersion < 0) { std::cout << "All versions failed to generate or compile\n"; return; } else { std::cout << "\n----------------------------------\n"; std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n"; } // copy best version to same directory as input .m file // and report location handleBestVersion(fileName,path,tmpPath,bestVersion); break; } case hybrid_orthogonal: { std::cout << "entering hybrid orthogonal search " << endl; int bestVersion = smart_hybrid_search(g, *baseGraph, cDetails, bDetails); // One way or another we have selected a version we are calling the best // or we failed if (bestVersion < 0) { std::cout << "All versions failed to generate or compile\n"; return; } else { std::cout << "\n----------------------------------\n"; std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n"; } // copy best version to same directory as input .m file // and report location handleBestVersion(fileName,path,tmpPath,bestVersion); break; } case debug: { std::cout << "entering debug search " << endl; int bestVersion = debug_search(g, *baseGraph, partitionForest, cDetails, bDetails); // One way or another we have selected a version we are calling the best // or we failed if (bestVersion < 0) { std::cout << "All versions failed to generate or compile\n"; return; } else { std::cout << "\n----------------------------------\n"; std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n"; } // copy best version to same directory as input .m file // and report location handleBestVersion(fileName,path,tmpPath,bestVersion); break; } case ga: { std::cout << "entering genetic algorithm search " << endl; bool gamaxfuse = true; if (vm.count("ga_nomaxfuse")) { gamaxfuse = false; } int seconds = vm["ga_timelimit"].as<int>(); int popsize = vm["ga_popsize"].as<int>(); int bestVersion = -1; if (vm.count("ga_noglobalthread")) { bestVersion = genetic_algorithm_search(g, *baseGraph, partitionForest, seconds, popsize, gamaxfuse, cDetails, bDetails).best_version; } else if (vm.count("ga_exthread")) { bestVersion = ga_exthread(g, *baseGraph, partitionForest, seconds, gamaxfuse, popsize, cDetails, bDetails); } else { // global thread bestVersion = ga_thread(g, *baseGraph, partitionForest, seconds, gamaxfuse, popsize, cDetails, bDetails); } // One way or another we have selected // a version we are calling the best // or we failed if (bestVersion < 0) { std::cout << "All versions failed to generate or compile\n"; return; } else { std::cout << "\n----------------------------------\n"; std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n"; } // copy best version to same directory as input .m file // and report location handleBestVersion(fileName,path,tmpPath,bestVersion); break; } case thread: { int thread_search(graph &g, graph &baseGraph, vector<partitionTree_t*> part_forest, compile_details_t &cDet, build_details_t &bDet); std::cout << "entering thread search " << endl; thread_search(g, *baseGraph, partitionForest, cDetails, bDetails); break; } } // }}} deleteForest(partitionForest); }
void OnlineFusionObject::draw(){ pi::ScopedMutex lock(_mutex); if(!_currentMeshInterleaved) return; glColor3f(1,1,1); if(_currentMeshInterleaved->faces.size()<1) return; if(_currentMeshInterleaved->vertices.size() != _currentNV || _currentMeshInterleaved->faces.size() != _currentNF){ eprintf("\nReassigning Buffers for interleaved Mesh"); if(!_vertexBuffer){ generateBuffers(); } _currentNV = _currentMeshInterleaved->vertices.size(); _currentNF = _currentMeshInterleaved->faces.size(); glBindBuffer(GL_ARRAY_BUFFER,_vertexBuffer); glBufferData(GL_ARRAY_BUFFER,_currentMeshInterleaved->vertices.size()*3*sizeof(float),_currentMeshInterleaved->vertices.data(), GL_STATIC_DRAW); if(_currentMeshInterleaved->colors.size()){ glBindBuffer(GL_ARRAY_BUFFER,_colorBuffer); glBufferData(GL_ARRAY_BUFFER,_currentMeshInterleaved->colors.size()*3,_currentMeshInterleaved->colors.data(), GL_STATIC_DRAW); } if(_currentMeshInterleaved->faces.size()){ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,_faceBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, _currentMeshInterleaved->faces.size()*sizeof(unsigned int), _currentMeshInterleaved->faces.data(), GL_STATIC_DRAW); } eprintf("\nChecking Mesh..."); std::vector<bool> checks(_currentMeshInterleaved->vertices.size(),false); for(size_t i=0;i<_currentMeshInterleaved->faces.size();i++) checks[_currentMeshInterleaved->faces[i]] = true; bool loneVertex = false; for(size_t i=0;i<checks.size();i++) loneVertex |= !checks[i]; if(loneVertex){ fprintf(stderr,"\nThere were lone Vertices!"); } eprintf("\nMesh Check done"); } glBindBuffer(GL_ARRAY_BUFFER,_vertexBuffer); glVertexPointer(3, GL_FLOAT, 0, 0); if(_currentMeshInterleaved->colors.size()){ glBindBuffer(GL_ARRAY_BUFFER,_colorBuffer); glColorPointer(3, GL_UNSIGNED_BYTE, 0, 0); } else{ glColor3f(0.5f,0.5f,0.5f); } glEnableClientState(GL_VERTEX_ARRAY); if(_colorEnabled) { glEnableClientState(GL_COLOR_ARRAY); } else{ glColor3f(0.5f,0.5f,0.5f); } if(_displayMode==1){ glPolygonMode(GL_FRONT, GL_LINE); glPolygonMode(GL_BACK, GL_LINE); glLineWidth(0.5f); } else{ glPolygonMode(GL_FRONT, GL_FILL); glPolygonMode(GL_BACK, GL_FILL); } if(_displayMode==2){ glPointSize(2.0); glBindBuffer(GL_ARRAY_BUFFER,_vertexBuffer); glDrawArrays(GL_POINTS,0,_currentMeshInterleaved->vertices.size()); } else{ glDrawElements(GL_TRIANGLES, _currentMeshInterleaved->faces.size(), GL_UNSIGNED_INT,0); } if(_colorEnabled) glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); }
bool CollisionModel3DImpl::collision(CollisionModel3D* other, int AccuracyDepth, int MaxProcessingTime, float* other_transform) { m_ColType=Models; CollisionModel3DImpl* o=static_cast<CollisionModel3DImpl*>(other); if (!m_Final) throw Inconsistency(); if (!o->m_Final) throw Inconsistency(); Matrix3D t=( other_transform==NULL ? o->m_Transform : *((Matrix3D*)other_transform) ); if (m_Static) t *= m_InvTransform; else t *= m_Transform.Inverse(); RotationState rs(t); if (AccuracyDepth<0) AccuracyDepth=0xFFFFFF; if (MaxProcessingTime==0) MaxProcessingTime=0xFFFFFF; DWORD EndTime,BeginTime = GetTickCount(); int num=Max(m_Triangles.size(),o->m_Triangles.size()); int Allocated=Max(64,(num>>4)); std::vector<Check> checks(Allocated); int queue_idx=1; Check& c=checks[0]; c.m_first=&m_Root; c.depth=0; c.m_second=&o->m_Root; while (queue_idx>0) { if (queue_idx>(Allocated/2)) // enlarge the queue. { Check c; checks.insert(checks.end(),Allocated,c); Allocated*=2; } EndTime=GetTickCount(); if (EndTime >= (BeginTime+MaxProcessingTime)) throw TimeoutExpired(); // @@@ add depth check //Check c=checks.back(); Check& c=checks[--queue_idx]; BoxTreeNode* first=c.m_first; BoxTreeNode* second=c.m_second; assert(first!=NULL); assert(second!=NULL); if (first->intersect(*second,rs)) { int tnum1=first->getTrianglesNumber(); int tnum2=second->getTrianglesNumber(); if (tnum1>0 && tnum2>0) { { for(int i=0;i<tnum2;i++) { BoxedTriangle* bt2=second->getTriangle(i); Triangle tt(Transform(bt2->v1,rs.t),Transform(bt2->v2,rs.t),Transform(bt2->v3,rs.t)); for(int j=0;j<tnum1;j++) { BoxedTriangle* bt1=first->getTriangle(j); if (tt.intersect(*bt1)) { m_ColTri1=*bt1; m_iColTri1=getTriangleIndex(bt1); m_ColTri2=tt; m_iColTri2=o->getTriangleIndex(bt2); return true; } } } } } else if (first->getSonsNumber()==0) { BoxTreeNode* s1=second->getSon(0); BoxTreeNode* s2=second->getSon(1); assert(s1!=NULL); assert(s2!=NULL); Check& c1=checks[queue_idx++]; c1.m_first=first; c1.m_second=s1; Check& c2=checks[queue_idx++]; c2.m_first=first; c2.m_second=s2; } else if (second->getSonsNumber()==0) { BoxTreeNode* f1=first->getSon(0); BoxTreeNode* f2=first->getSon(1); assert(f1!=NULL); assert(f2!=NULL); Check& c1=checks[queue_idx++]; c1.m_first=f1; c1.m_second=second; Check& c2=checks[queue_idx++]; c2.m_first=f2; c2.m_second=second; } else { float v1=first->getVolume(); float v2=second->getVolume(); if (v1>v2) { BoxTreeNode* f1=first->getSon(0); BoxTreeNode* f2=first->getSon(1); assert(f1!=NULL); assert(f2!=NULL); Check& c1=checks[queue_idx++]; c1.m_first=f1; c1.m_second=second; Check& c2=checks[queue_idx++]; c2.m_first=f2; c2.m_second=second; } else { BoxTreeNode* s1=second->getSon(0); BoxTreeNode* s2=second->getSon(1); assert(s1!=NULL); assert(s2!=NULL); Check& c1=checks[queue_idx++]; c1.m_first=first; c1.m_second=s1; Check& c2=checks[queue_idx++]; c2.m_first=first; c2.m_second=s2; } } } } return false; }
void strategytdexp4::update( const board& oldBoard, const board& newBoard ) { // get the values from the old board vector<double> oldInputs = getInputValues( oldBoard, oldBoard.perspective() ); vector<double> oldMiddles = getMiddleValues( oldInputs ); double oldProbOutput = getOutputProbValue( oldMiddles ); double oldGammonWinOutput = getOutputGammonWinValue( oldMiddles, oldBoard ); double oldGammonLossOutput = getOutputGammonLossValue( oldMiddles, oldBoard ); double oldBgWinOutput = getOutputBackgammonWinValue( oldMiddles, oldBoard ); double oldBgLossOutput = getOutputBackgammonLossValue( oldMiddles, oldBoard ); // calculate all the partial derivatives we'll need (of output node values // to the various weights) int i, j; // then do derivs of the prob nodes to each of the middle->input weights (that's a 2d array), and the derivs of each of // the middle nodes to its weights->inputs. double mid, input, v1, v2, v3, v4, v5; for( i=0; i<nMiddle; i++ ) { mid = oldMiddles.at(i); v1 = outputProbWeights.at(i); v2 = outputGammonWinWeights.at(i); v3 = outputGammonLossWeights.at(i); v4 = outputBackgammonWinWeights.at(i); v5 = outputBackgammonLossWeights.at(i); probDerivs.at(i) = mid * oldProbOutput * ( 1 - oldProbOutput ); gamWinDerivs.at(i) = mid * oldGammonWinOutput * ( 1 - oldGammonWinOutput ); gamLossDerivs.at(i) = mid * oldGammonLossOutput * ( 1 - oldGammonLossOutput ); bgWinDerivs.at(i) = mid * oldBgWinOutput * ( 1 - oldBgWinOutput ); bgLossDerivs.at(i) = mid * oldBgLossOutput * ( 1 - oldBgLossOutput ); for( j=0; j<198; j++ ) { input = oldInputs.at(j); probInputDerivs.at(i).at(j) = v1 * input * oldProbOutput * ( 1 - oldProbOutput ) * mid * ( 1 - mid ); gamWinInputDerivs.at(i).at(j) = v2 * input * oldGammonWinOutput * ( 1 - oldGammonWinOutput ) * mid * ( 1 - mid ); gamLossInputDerivs.at(i).at(j) = v3 * input * oldGammonLossOutput * ( 1 - oldGammonLossOutput ) * mid * ( 1 - mid ); bgWinInputDerivs.at(i).at(j) = v4 * input * oldBgWinOutput * ( 1 - oldBgWinOutput ) * mid * ( 1 - mid ); bgLossInputDerivs.at(i).at(j) = v5 * input * oldBgLossOutput * ( 1 - oldBgLossOutput ) * mid * ( 1 - mid ); } probInputDerivs.at(i).at(198) = v1 * oldProbOutput * ( 1 - oldProbOutput ) * mid * ( 1 - mid ); gamWinInputDerivs.at(i).at(198) = v2 * oldGammonWinOutput * ( 1 - oldGammonWinOutput ) * mid * ( 1 - mid ); gamLossInputDerivs.at(i).at(198) = v3 * oldGammonLossOutput * ( 1 - oldGammonLossOutput ) * mid * ( 1 - mid ); bgWinInputDerivs.at(i).at(198) = v4 * oldBgWinOutput * ( 1 - oldBgWinOutput ) * mid * ( 1 - mid ); bgLossInputDerivs.at(i).at(198) = v5 * oldBgLossOutput * ( 1 - oldBgLossOutput ) * mid * ( 1 - mid ); } probDerivs.at(nMiddle) = oldProbOutput * ( 1 - oldProbOutput ); gamWinDerivs.at(nMiddle) = oldGammonWinOutput * ( 1 - oldGammonWinOutput ); gamLossDerivs.at(nMiddle) = oldGammonLossOutput * ( 1 - oldGammonLossOutput ); bgWinDerivs.at(nMiddle) = oldBgWinOutput * ( 1 - oldBgWinOutput ); bgLossDerivs.at(nMiddle) = oldBgLossOutput * ( 1 - oldBgLossOutput ); // now calculate the next estimate of the outputs. That's known if the game is over; otherwise we use the network's // estimate on the new board as a proxy. Note that the update fn is only ever called by the game when the player wins, not when // the player loses, just because the winner is the last one to play. But we need to train on prob of losing a gammon too, // so we flip board perspective and train again based on that. bool trainGammonLoss = true; bool trainGammonWin = true; bool trainBgLoss = true; bool trainBgWin = true; double newProbOutput, newGammonWinOutput, newGammonLossOutput, newBgWinOutput, newBgLossOutput; if( newBoard.bornIn0Raw() == 15 ) { trainGammonLoss = false; // can't train the conditional prob of a gammon loss if there isn't a loss trainBgLoss = false; // ditto for backgammon loss newProbOutput = 1.; if( newBoard.bornIn1Raw() == 0 ) // gammon or backgammon { newGammonWinOutput = 1.; vector<int> checks( newBoard.checkers1Raw() ); bool foundOne = newBoard.hit1Raw() > 0; if( !foundOne ) { for( int i=0; i<6; i++ ) if( checks.at(i) > 0 ) { foundOne = true; break; } } newBgWinOutput = foundOne ? 1 : 0; } else { newGammonWinOutput = 0.; trainBgWin = false; // no gammon win so can't train conditional bg win prob } } else if( newBoard.bornIn1Raw() == 15 ) { trainGammonWin = false; trainBgWin = false; newProbOutput = 0.; if( newBoard.bornIn0Raw() == 0 ) // gammon loss or backgammon loss { newGammonLossOutput = 1; vector<int> checks( newBoard.checkers0Raw() ); bool foundOne = newBoard.hit0Raw() > 0; if( !foundOne ) { for( int i=18; i<24; i++ ) if( checks.at(i) > 0 ) { foundOne = true; break; } } newBgLossOutput = foundOne ? 1 : 0; } else { newGammonLossOutput = 0; trainBgLoss = false; } } else { // estimate from the new board's outputs, remembering that after the move is done, // the other player gets the dice. vector<double> midVals( getMiddleValues( getInputValues( newBoard, !newBoard.perspective() ) ) ); newProbOutput = getOutputProbValue( midVals ); newGammonWinOutput = getOutputGammonWinValue( midVals, newBoard ); newGammonLossOutput = getOutputGammonLossValue( midVals, newBoard ); newBgWinOutput = getOutputBackgammonWinValue( midVals, newBoard ); newBgLossOutput = getOutputBackgammonLossValue( midVals, newBoard ); } // train the nodes as appropriate for( i=0; i<nMiddle; i++ ) { outputProbWeights.at(i) += alpha * ( newProbOutput - oldProbOutput ) * probDerivs.at(i); if( trainGammonWin ) outputGammonWinWeights.at(i) += alpha * ( newGammonWinOutput - oldGammonWinOutput ) * gamWinDerivs.at(i); if( trainGammonLoss ) outputGammonLossWeights.at(i) += alpha * ( newGammonLossOutput - oldGammonLossOutput ) * gamLossDerivs.at(i); if( trainBgWin ) outputBackgammonWinWeights.at(i) += alpha * ( newBgWinOutput - oldBgWinOutput ) * bgWinDerivs.at(i); if( trainBgLoss ) outputBackgammonLossWeights.at(i) += alpha * ( newBgLossOutput - oldBgLossOutput ) * bgLossDerivs.at(i); for( j=0; j<199; j++ ) { middleWeights.at(i).at(j) += beta * ( newProbOutput - oldProbOutput ) * probInputDerivs.at(i).at(j); if( trainGammonWin ) middleWeights.at(i).at(j) += beta * ( newGammonWinOutput - oldGammonWinOutput ) * gamWinInputDerivs.at(i).at(j); if( trainGammonLoss ) middleWeights.at(i).at(j) += beta * ( newGammonLossOutput - oldGammonLossOutput ) * gamLossInputDerivs.at(i).at(j); if( trainBgWin ) middleWeights.at(i).at(j) += beta * ( newBgWinOutput - oldBgWinOutput ) * bgWinInputDerivs.at(i).at(j); if( trainBgLoss ) middleWeights.at(i).at(j) += beta * ( newBgLossOutput - oldBgLossOutput ) * bgLossInputDerivs.at(i).at(j); } } outputProbWeights.at(nMiddle) += alpha * ( newProbOutput - oldProbOutput ) * probDerivs.at(nMiddle); if( trainGammonWin ) outputGammonWinWeights.at(nMiddle) += alpha * ( newGammonWinOutput - oldGammonWinOutput ) * gamWinDerivs.at(nMiddle); if( trainGammonLoss ) outputGammonLossWeights.at(nMiddle) += alpha * ( newGammonLossOutput - oldGammonLossOutput ) * gamLossDerivs.at(nMiddle); if( trainBgWin ) outputBackgammonWinWeights.at(nMiddle) += alpha * ( newBgWinOutput - oldBgWinOutput ) * bgWinDerivs.at(nMiddle); if( trainBgLoss ) outputBackgammonLossWeights.at(nMiddle) += alpha * ( newBgLossOutput - oldBgLossOutput ) * bgLossDerivs.at(nMiddle); }
// read a file, has to be out of order because it is called by the others struct site* read_file( struct head_data *HEAD_DATA , const char *config_in ) { // some additional information #ifdef CONDOR_MODE fprintf( stdout , "[PAR] CONDOR_MODE selected .... \n" ) ; #else fprintf( stdout , "[PAR] NOT_CONDOR_MODE selected .... " "(same-architecture caching used) \n" ) ; #endif /// here we include the usual stuff look at header for global stuff // open our configuration FILE *infile = fopen( config_in , "r" ) ; if( infile == NULL ) { // need to check what we are doing if( Latt.head == UNIT_GAUGE || Latt.head == RANDOM_CONFIG || Latt.head == INSTANTON ) { fprintf( stdout , "[IO] %s is empty but that is ok \n" , config_in ) ; } else { fprintf( stderr , "[IO] error opening file :: %s\n" , config_in ) ; return NULL ; } } fprintf( stdout , "[IO] reading file %s\n" , config_in ) ; // initialise the configuration number to zero struct head_data tmp ; if( read_header( infile , &tmp , GLU_TRUE ) == GLU_FAILURE ) { fprintf( stderr , "[IO] Header reading failure\n" ) ; fclose( infile ) ; return NULL ; } // initialise geometry so that we can use LVOLUME and stuff init_latt( ) ; // check for having enough memory for the gauge field if( have_memory_gauge( ) == GLU_FAILURE ) { fclose( infile ) ; return NULL ; } // malloc our gauge field and initialise our lattice geometry struct site *lat = NULL ; if( ( lat = allocate_lat( ) ) == NULL ) { fprintf( stderr , "[IO] Gauge field allocation failure\n" ) ; return NULL ; } #ifdef SINGLE_PREC fprintf( stdout , "[PREC] Single-precision storage for the gauge fields\n" ) ; #endif const int check = get_config_SUNC( infile , lat , tmp ) ; // read in the configuration ... if( check == GLU_FAILURE ) { fprintf( stderr , "[IO] File read error ... Leaving \n" ) ; fclose( infile ) ; free( lat ) ; return NULL ; } // look at scidac header again to get the checksums // this is taken from the bottom of the file if( Latt.head == SCIDAC_HEADER || Latt.head == ILDG_SCIDAC_HEADER || Latt.head == ILDG_BQCD_HEADER ) { get_header_data_SCIDAC( infile , &tmp ) ; } // have a look at some available checks if( checks( lat , check , tmp ) == GLU_FAILURE ) { fclose( infile ) ; free( lat ) ; return NULL ; } // set the header info *HEAD_DATA = tmp ; // free it if it was opened if( infile != NULL ) { fclose( infile ) ; } // and finally set the header data into a constant struct return lat ; }
bool CollisionModel3D::modelCollision(ModelCollisionTest *test, int maxProcessingTime) const { const CollisionModel3D* other = test->otherModel(); test->m_collides = false; test->m_iColTri = -1; test->m_iOtherColTri = -1; test->m_colPointIsDirty = true; test->m_maxProcessingTimedOut = false; if (!d->m_isFinalized) throw Inconsistency(); if (!other->d->m_isFinalized) throw Inconsistency(); Matrix3D t = test->otherModelTransform() == NULL ? other->d->m_transform : Private::toMatrix3D(test->otherModelTransform()); if (d->m_isStatic) t *= d->m_invTransform; else t *= d->m_transform.Inverse(); RotationState rs(t); int accuracyDepth = test->accuracyDepth(); if (accuracyDepth < 0) accuracyDepth = 0xFFFFFF; if (maxProcessingTime == 0) maxProcessingTime = 0xFFFFFF; const DWORD beginTime = GetTickCount(); DWORD endTime = 0; const std::size_t num = std::max(d->m_triangles.size(), other->d->m_triangles.size()); std::size_t allocated = std::max(std::size_t(64), (num>>4)); std::vector<Check> checks(allocated); int queue_idx = 1; { // Initialize first Check object checks.front().m_first = &d->m_root; checks.front().m_depth = 0; checks.front().m_second = &other->d->m_root; } while (queue_idx > 0) { if (queue_idx > (allocated / 2)) { // Enlarge the queue Check c; checks.insert(checks.end(), allocated, c); allocated *= 2; } endTime = GetTickCount(); if (endTime >= (beginTime + maxProcessingTime)) { test->m_maxProcessingTimedOut = true; return false; } // @@@ add depth check //Check c=checks.back(); Check& c = checks[--queue_idx]; const BoxTreeNode* first = c.m_first; const BoxTreeNode* second = c.m_second; assert(first != NULL); assert(second != NULL); if (first->intersect(*second, rs)) { std::size_t tnum1 = first->getTrianglesNumber(); std::size_t tnum2 = second->getTrianglesNumber(); if (tnum1 > 0 && tnum2 > 0) { for (int i = 0; i < tnum2; i++) { const BoxedTriangle* bt2 = second->getTriangle(i); const Triangle tt(Transform(bt2->v1, rs.t), Transform(bt2->v2, rs.t), Transform(bt2->v3, rs.t)); for (int j = 0; j < tnum1; j++) { const BoxedTriangle* bt1 = first->getTriangle(j); if (tt.intersect(*bt1)) { bt1->copyCoords(test->m_colTri); test->m_iColTri = d->getTriangleIndex(bt1); tt.copyCoords(test->m_otherColTri); test->m_iOtherColTri = other->d->getTriangleIndex(bt2); test->m_collides = true; return true; } } } } else if (first->getSonsNumber() == 0) { const BoxTreeNode* s1 = second->getSon(0); const BoxTreeNode* s2 = second->getSon(1); assert(s1 != NULL); assert(s2 != NULL); Check& c1 = checks[queue_idx++]; c1.m_first = first; c1.m_second = s1; Check& c2 = checks[queue_idx++]; c2.m_first = first; c2.m_second = s2; } else if (second->getSonsNumber() == 0) { const BoxTreeNode* f1 = first->getSon(0); const BoxTreeNode* f2 = first->getSon(1); assert(f1 != NULL); assert(f2 != NULL); Check& c1 = checks[queue_idx++]; c1.m_first = f1; c1.m_second = second; Check& c2 = checks[queue_idx++]; c2.m_first = f2; c2.m_second = second; } else { float v1 = first->getVolume(); float v2 = second->getVolume(); if (v1 > v2) { const BoxTreeNode* f1=first->getSon(0); const BoxTreeNode* f2=first->getSon(1); assert(f1 != NULL); assert(f2 != NULL); Check& c1 = checks[queue_idx++]; c1.m_first = f1; c1.m_second = second; Check& c2 = checks[queue_idx++]; c2.m_first = f2; c2.m_second = second; } else { const BoxTreeNode* s1 = second->getSon(0); const BoxTreeNode* s2 = second->getSon(1); assert(s1 != NULL); assert(s2 != NULL); Check& c1 = checks[queue_idx++]; c1.m_first = first; c1.m_second = s1; Check& c2 = checks[queue_idx++]; c2.m_first = first; c2.m_second = s2; } } } } return false; }