bool League::finished() { //calculate games count // int max; if (clubs.count() %2 == 0) { max = ((clubs.count()-1)*2)*(clubs.count() /2); } else { int count = clubs.count() + 1; max = ((count-1)*2)*(count/2); } //смотрим максимальный сыгранный тур QSqlQuery q; q.prepare("SELECT COUNT (*) FROM Matches"); if (!q.exec()) {qDebug() << "SQL Error: " + q.lastError().text() + ", query " + q.executedQuery();} else {qDebug() << "Query done: " + q.executedQuery();} q.first(); if (max <= q.value(0).toInt()) { writeResults(); return true; } else return false; }
void advanced_quit (void) { if (!USE_PRIMENET) { outputLongLine (MANUAL_QUIT); if (askYesNo ('N')) { writeResults ("Quitting GIMPS.\n"); //bug - either delete file, or delete all work_units and write the file. //bug IniDeleteAllLines (WORKTODO_FILE); stop_workers_for_escape (); } } else { int res; outputLongLine (PRIMENET_QUIT); res = askYesNoCancel ('C'); if (res == 0) { OutputBoth (MAIN_THREAD_NUM, "Quitting GIMPS after current work completes.\n"); IniWriteInt (INI_FILE, "NoMoreWork", 1); askOK (); } if (res == 1) { OutputBoth (MAIN_THREAD_NUM, "Quitting GIMPS immediately.\n"); spoolMessage (MSG_QUIT_GIMPS, NULL); askOK (); } } }
int main(int argc, char *argv[]) /* Read snp126. */ /* Write coords of multiple alignments to .tab file. */ /* Write counts to .log file. */ { if (argc != 2) usage(); snpDb = argv[1]; hSetDb(snpDb); outputFileHandle = mustOpen("snpMultiple.tab", "w"); logFileHandle = mustOpen("snpMultiple.log", "w"); readSnps(); writeResults(); // free hashes carefulClose(&outputFileHandle); carefulClose(&logFileHandle); return 0; }
int main(int argc, char *argv[]) { if (argc != 4) usage(); database = argv[1]; hSetDb(database); snpSimpleTable = argv[2]; if (!hTableExistsDb(database, snpSimpleTable)) errAbort("can't get table %s\n", snpSimpleTable); orthoTable = argv[3]; if (!hTableExistsDb(database, orthoTable)) errAbort("can't get table %s\n", orthoTable); outputFileHandle = mustOpen("snpOrthoJoin.tab", "w"); missingFileHandle = mustOpen("snpOrthoJoin.missing", "w"); chimpHash = getOrtho(orthoTable, "panTro2"); macaqueHash = getOrtho(orthoTable, "rheMac2"); writeResults(snpSimpleTable); carefulClose(&outputFileHandle); carefulClose(&missingFileHandle); return 0; }
int main(int argc, char** argv) { uint32_t matchAlgorithm = 0; const char* outputFile = "displacements.result"; const char* imageSequenceFolder = nullptr; const ImageProc::ImageProc* imProc = new ImageProc::ImageProcBase(); Draw::DrawInterface* drawer = new Draw::Draw(); const Displacement::DisplacementInterface* displacement = new Displacement::DisplacementBase(); InputMethod::InputMethodInterface* inputMethod = nullptr; OutputMethod::OutputImageSequence* outputMethod = new OutputMethod::OutputImageSequence(); const Descriptor::DescriptorInterface* descriptor = nullptr; const Match::MatcherInterface* matcher = nullptr; if (argc > 1) { imageSequenceFolder = argv[1]; } else { LOG_ERROR("Image sequence folder not defined"); return -1; } if (argc > 2) { matchAlgorithm = (uint32_t) std::strtoul(argv[2], NULL, 10); } if (argc > 3) { outputFile = argv[3]; } LOG_INFO("Using %s", getMethodPname(matchAlgorithm)); if (getInputMethod(imageSequenceFolder, &inputMethod) != GBL::RESULT_SUCCESS) { LOG_ERROR("Could not deduce a valid input method"); return -1; } if (getExecutors(matchAlgorithm, &descriptor, &matcher) != GBL::RESULT_SUCCESS) { LOG_ERROR("Could not get valid descriptor and matcher. Define a valid algorithm to be used."); return -1; } clock_t tStart = clock(); int64_t startTime = GetTimeMs64(); std::vector<GBL::Displacement_t> displacements = findTheBall(imageSequenceFolder, imProc, *drawer, *descriptor, *matcher, *displacement, *inputMethod, *outputMethod); int64_t endTime = GetTimeMs64(); float_t totalTimeElapsed = (float_t) (clock() - tStart) / CLOCKS_PER_SEC; LOG(stdout, "TIME", "CPU time of processing stage: %f s", totalTimeElapsed); LOG(stdout, "TIME", "Execution time of processing stage: %f s", (float_t ) (endTime - startTime) / 1000.0f); if (writeResults(outputFile, displacements) != GBL::RESULT_SUCCESS) { LOG_WARNING("Could not write results to file %s", outputFile); } delete imProc; delete descriptor; delete matcher; delete displacement; delete drawer; delete inputMethod; return 0; }
void RunExhaustiveDocsimSearch() { const char *topicoutput = Config("RESULTS-PATH"); FILE *fo; if (topicoutput) { fo = fopen(topicoutput, "wb"); if (!fo) { fprintf(stderr, "The results file \"%s\" could not be opened for writing.\n", topicoutput); exit(1); } } else { fo = stdout; } unsigned char *sigFile; SignatureHeader sigCfg = readSigFile(Config("SIGNATURE-PATH"), &sigFile); int threadCount = 1; int searchDocFirst = 0; int searchDocLast = (sigCfg.num_signatures - 1); if (Config("THREADS")) { threadCount = atoi(Config("THREADS")); } if (Config("SEARCH-DOC-FIRST")) searchDocFirst = atoi(Config("SEARCH-DOC-FIRST")); if (Config("SEARCH-DOC-LAST")) searchDocLast = atoi(Config("SEARCH-DOC-LAST")); int totalDocs = searchDocLast - searchDocFirst + 1; void **threads = malloc(sizeof(void *) * threadCount); for (int i = 0; i < threadCount; i++) { WorkerThroughput *threadData = malloc(sizeof(WorkerThroughput)); threadData->sig_cfg = &sigCfg; threadData->sigFile = sigFile; threadData->doc_begin = totalDocs * i / threadCount + searchDocFirst; threadData->doc_end = totalDocs * (i+1) / threadCount + searchDocFirst; threads[i] = threadData; } Timer T = StartTimer(); DivideWork(threads, Throughput_Job, threadCount); for (int i = 0; i < threadCount; i++) { WorkerThroughput *thread_data = threads[i]; int doc_count = thread_data->doc_end - thread_data->doc_begin; for (int j = 0; j < doc_count; j++) { int topicId = thread_data->doc_begin + j; const char *docName = (const char *)(sigFile + (size_t)sigCfg.sig_record_size * topicId); writeResults(fo, topicId, docName, &thread_data->output[j]); } } fprintf(stderr, "search time %.2fms\n", TickTimer(&T)); for (int i = 0; i < threadCount; i++) { free(threads[i]); } free(threads); }
PrintDialog::PrintDialog(QWidget* a_parent) : QDialog(a_parent) { m_ui.setupUi(this); connect(m_ui.m_action_print, SIGNAL(triggered()), this, SLOT(sPrint())); writeResults(); }
int readFromFile (const char *finput, const char *foutput) { if (!finput) { printf("Не сте въвели файл за четене\n"); return 0; } FILE *input; // file read vars char *line = NULL; size_t len = 0; ssize_t charactersRead; // comment vars const char pattern[3] = "/*"; char *token; int inComment = 0; // result vars int ifCount = 0; int elseCount = 0; int linesCount = 0; input = fopen(finput, "r"); while ((charactersRead = getline(&line, &len, input)) != -1) { linesCount += 1; token = strtok(line, pattern); if (token != NULL) { printf("inComment: %d Token: %s\n", inComment, token); printf("Equal: %d\n", strcmp(token, line)); while( token != NULL ) { if (strcmp(token, line) && searchThroughString(line, "/*")) { inComment = 1; break; } else if (strcmp(token, line) && searchThroughString(line, "*/")) { inComment = 0; break; } if (!inComment) { ifCount += searchThroughString(token, "if"); elseCount += searchThroughString(token, "else"); } token = strtok(NULL, pattern); if (token != NULL) inComment = !inComment ; } } } fclose(input); writeResults(foutput, ifCount, elseCount, linesCount); return 0; }
int main(int argc, char *argv[]) /* generate snpOrtho table from snp ortho file */ /* combine with snp table */ { if (argc != 4) usage(); hSetDb(argv[1]); if (!hTableExistsDb(argv[1], argv[2])) errAbort("can't get table %s\n", argv[2]); if (!fileExists(argv[3])) errAbort("can't find %s\n", argv[3]); orthoHash = getOrtho(argv[3]); writeResults(argv[2]); return 0; }
int readFromStdin (const char *foutput) { // input read vars char *line = NULL; size_t len = 0; ssize_t charactersRead; // comment vars const char pattern[3] = "/*"; char *token; int inComment = 0; // result vars int ifCount = 0; int elseCount = 0; int linesCount = 0; while ((charactersRead = getline(&line, &len, stdin)) != -1) { linesCount += 1; token = strtok(line, pattern); if (token != NULL) { while( token != NULL ) { if (strcmp(token, line) && searchThroughString(line, "/*")) { inComment = 1; break; } else if (strcmp(token, line) && searchThroughString(line, "*/")) { inComment = 0; break; } if (!inComment) { ifCount += searchThroughString(token, "if"); elseCount += searchThroughString(token, "else"); } token = strtok(NULL, pattern); if (token != NULL) inComment = !inComment ; } } } writeResults(foutput, ifCount, elseCount, linesCount - 1); return 0; }
int main(int argc, char *argv[]) { if (argc != 4) usage(); database = argv[1]; hSetDb(database); snpTable = argv[2]; if (!hTableExistsDb(database, snpTable)) errAbort("can't get table %s\n", snpTable); orthoTable = argv[3]; if (!hTableExistsDb(database, orthoTable)) errAbort("can't get table %s\n", orthoTable); snpHash = getBaseSnpData(snpTable); outputFileHandle = mustOpen("snpOrthoLookup.tab", "w"); writeResults(orthoTable); carefulClose(&outputFileHandle); return 0; }
int main() { int n, a; Vert vertices; std::vector<int> distances; std::vector<int> toConsider; std::set<std::vector<int>,CompareResults> results; printf("Liczba wierzcholkow wielokata: \n"); scanf("%d", &n); createPolygon(n, vertices); printf("Konfiguracja do zbadania:\n"); for (int i = 0; i < 6; ++i) { scanf("%d", &a); distances.push_back(a); } transformDistancesToVertex(distances, toConsider); checkAllPairs(toConsider, vertices, results); writeResults(results); }
void Game::startGame() { //Demarrer les threads for(int i = 0; i < nbPlayers_; i++) players_[i]->startPlayingAsync(); populateGrid(10); //Condition pour continuer a jouer (genre s'il reste des cases cachees) while(remaining_ > 0) loop(); #ifndef NO_OUT system("cls"); printGrille(*mirroir_); #endif writeResults(); //Liberer les joueurs, leur dire de rentrer au vestiaire prendre une douche for(int i = 0; i < nbPlayers_; i++) { //Dabord laisser une chance au thread de se terminer normalement SetEvent(events_[i]); } Sleep(1000); //Donner un delais max pour que les threads se terminent for(int i = 0; i < nbPlayers_; i++) { DWORD result = WaitForSingleObject( players_[i]->getThread(), 0); // Si le thread est encore actif, le tuer de maniere violente. if (result != WAIT_OBJECT_0) players_[i]->stopPlaying(); } }
int main(int argc, char* argv[]) try { const auto prm = example::initParam(argc, argv); const auto cellID = prm.getDefault("cell", 0); const auto rset = example::identifyResultSet(prm); const auto init = Opm::ECLInitFileData(rset.initFile()); const auto graph = Opm::ECLGraph::load(rset.gridFile(), init); auto pvtCC = Opm::ECLPVT::ECLPvtCurveCollection(graph, init); if (prm.has("unit")) { pvtCC.setOutputUnits(makeUnits(prm.get<std::string>("unit"), init)); } const auto x = CellState{ graph, rset, cellID }; auto props = std::vector<Property>{}; for (const auto& prop : enumerateProperties()) { if (prm.getDefault(prop.first, false)) { props.push_back(Property{ prop.first, (*prop.second)(pvtCC, x) }); } } if (! props.empty()) { std::cout.precision(16); std::cout.setf(std::ios_base::scientific); writeResults(x, props); } } catch (const std::exception& e) { std::cerr << "Caught Exception: " << e.what() << '\n'; return EXIT_FAILURE; }
//Execute par le thread principal (controleur) int main (int argc, char **argv) { if (argc != 6) return EXIT_FAILIURE; signal(SIGALRM, sigHandler); std::string pathGrilleVide = argv[1]; std::string pathGrilleSolution = argv[2]; std::string pathArrivee = argv[3]; int tempsMax = atoi(argv[4]); pathResultat = argv[5]; int grille[9][9]; int solution[9][9]; mainThread = pthread_self(); loadGrid(pathGrilleVide, grille); // printGrid(grille); loadGrid(pathGrilleSolution, solution); // printGrid(solution); for (int i = 0; i < 5; i++) { joueurs[i] == 0; } //creaation des thread joueur par defaut joueurs[0] = new Joueur(); joueurs[1] = new Joueur(); joueurs[2] = new Joueur(); joueurs[0]->thread = new pthread_t(); joueurs[1]->thread = new pthread_t(); joueurs[2]->thread = new pthread_t(); int un=1; int deux=2; int trois=3; pthread_create(joueurs[0]->thread, NULL, jouer, &un); pthread_create(joueurs[1]->thread, NULL, jouer, &deux); pthread_create(joueurs[2]->thread, NULL, jouer, &trois); joueurs[0]->tid = 1; joueurs[1]->tid = 2; joueurs[2]->tid = 3; joueurs[0]->etat = "Inconnu"; joueurs[1]->etat = "Inconnu"; joueurs[2]->etat = "Inconnu"; listeJoueurs.insert(std::pair<int, Joueur*>(joueurs[0]->tid, joueurs[0])); listeJoueurs.insert(std::pair<int, Joueur*>(joueurs[1]->tid, joueurs[1])); listeJoueurs.insert(std::pair<int, Joueur*>(joueurs[2]->tid, joueurs[2])); // Creation des deux autres thread pthread_t accueil_t; pthread_t alarm_t; pthread_create(&accueil_t, NULL, accueil, (void*)pathArrivee.c_str()); pthread_create(&alarm_t, NULL, minuterie, (void*)&tempsMax); sem_init(&file1_sem, 0, 0); int* empty = findEmpty(grille); int col = 0, ln = 0; do { //============================================================ // BOUCLE POUR TROUVER LES ZERO ET LES ENVOYER DANS LA FILE 1 if (empty == 0) break; if (pthread_mutex_trylock(&file1_lock) == 0) { // std::cout<<"je prend le mutex pour le broadcast"<<std::endl; if (file1.size() < 4) { MessageCJ* msg = new MessageCJ(); msg->colonne = empty[0]; msg->ligne = empty[1]; bool duplicate = false; std::queue<MessageCJ*> temp; while(!file1.empty()) { temp.push(new MessageCJ((*file1.front()))); file1.pop(); } while(!temp.empty()) { MessageCJ* tmpMsg = new MessageCJ((*temp.front())); file1.push(tmpMsg); temp.pop(); if (tmpMsg->colonne == msg->colonne && tmpMsg->ligne == msg->ligne) duplicate = true; } if (!duplicate) { std::list<int> opts = getOptions(grille, msg->colonne, msg->ligne); msg->choiceList = opts; file1.push(msg); pthread_cond_broadcast(&nonEmpty); // std::cout<<"je broadcast "<<file1.size()<<std::endl; // sem_post(&file1_sem); } delete empty; col = msg->colonne; ln = msg->ligne; } pthread_mutex_unlock( &file1_lock ); // std::cout<<"je rend le mutex pour le broadcast "<<file2.size()<<std::endl; } //========================== //BOUCLE POUR LIRE LA FILE 2 if(pthread_mutex_trylock(&file2_lock) == 0) { if (file2.size() > 0) { _MessageJC* msg = new _MessageJC((*file2.front())); file2.pop(); if (listeJoueurs.find(msg->tid)->second->etat != "Elimine") { // std::cout<<"ANS = "<<msg->choice<<" ? "<<solution[msg->colonne][msg->ligne]<<std::endl; // if (msg->choice == 0) // std::cout<<"LE CIEL NOUS TOMBE SUR LA TETE PAR TOUTATIS!!!"<<std::endl; //pthread_cond_broadcast(&nonFullFile2); if (solution[msg->colonne][msg->ligne] == msg->choice) { //If win! grille[msg->colonne][msg->ligne] = msg->choice; Joueur* vainqueur = listeJoueurs.find(msg->tid)->second; vainqueur->score++; } else { //if noob! Joueur* looser = listeJoueurs.find(msg->tid)->second; looser->score--; looser->nbErreur++; if (looser->score <= -10) { eliminateLooser(&listeJoueurs, msg->tid, joueurs); std::cout<<"Better luck next time, NOOB! "<<msg->tid<<std::endl; } } } pthread_mutex_unlock(&file2_lock); } else { pthread_mutex_unlock(&file2_lock); sleep(1); } } pthread_mutex_lock(&nouveauJoueurs_lock); if (nouveauxJoueurs.size() > 0) { if (nouveauxJoueurs.front() == 0) pthread_cancel(accueil_t); else if (playerCount < 5 ) { for (int i = 0; i < 5 && playerCount < 5 && nouveauxJoueurs.size() > 0; i++) { if (joueurs[i] == 0) { int id = nouveauxJoueurs.front(); if (id == 0) pthread_cancel(accueil_t); else { nouveauxJoueurs.pop(); joueurs[i] = listeJoueurs.find(id)->second; playerCount++; joueurs[i]->etat = "Inconnu"; pthread_create(joueurs[i]->thread, NULL, jouer, &joueurs[i]->tid); } } } } } pthread_mutex_unlock(&nouveauJoueurs_lock); empty = findEmpty(grille, col, ln); //printGrid(grille); // std::cout<<std::endl; } while (empty != 0 && nbJoueurActifs() > 0); // Si on se rend ici, soit tous les joueurs sont morts, soit on a fini la grille int max = 0; for (std::map<int, Joueur*>::iterator it = listeJoueurs.begin(); it != listeJoueurs.end(); it++) { if (it->second->etat == "Inconnu") { if (it->second->score > max) max = it->second->score; } } for (std::map<int, Joueur*>::iterator it = listeJoueurs.begin(); it != listeJoueurs.end(); it++) { if (it->second->etat == "Inconnu") { if (it->second->score == max) it->second->etat = "Vainqueur"; else it->second->etat = "Perdant"; } } pthread_cancel(accueil_t); pthread_cancel(alarm_t); writeResults(); dispose(); return EXIT_SUCCESS; }
static void master(int nslaves, char* parameterFile) { //VARIABLE DECLARATIONS time_t startTime, computationStartTime, endTime; int rank, i, j, accel, MAX_ITER, *slave_ldAs, total_ldA, rdA, numLambdas, error; ISTAinstance_mpi* instance; float *xvalue, *result, *b, *lambdas, lambdaStart, lambdaFinish, gamma, step, MIN_FUNCDIFF; char regType, xfilename[MAX_FILENAME_SIZE], bfilename[MAX_FILENAME_SIZE], outfilename[MAX_FILENAME_SIZE]; //START TIMER startTime = time(NULL); //GET VALUES FROM PARAMETER FILE getMasterParams(parameterFile, xfilename, bfilename, outfilename, &rdA, &numLambdas, &lambdaStart, &lambdaFinish, &gamma, &step, ®Type, &accel, &MAX_ITER, &MIN_FUNCDIFF); //STORE EACH SLAVE'S INDIVIDUAL LDA AND CALCULATE TOTAL_LDA slave_ldAs = (int*)malloc((nslaves+1)*sizeof(int)); int my_ldA = 0; MPI_Gather(&my_ldA, 1, MPI_INT, slave_ldAs, 1, MPI_INT, 0, MPI_COMM_WORLD); total_ldA = 0; for(i=0; i<=nslaves; i++) total_ldA += slave_ldAs[i]; fprintf(stdout, "TOTAL LDA IS %d\n", total_ldA); //ALLOCATE MEMORY xvalue = calloc(rdA+1,sizeof(float)); result = malloc((total_ldA+rdA)*sizeof(float)); b = malloc((total_ldA)*sizeof(float)); lambdas = malloc(numLambdas*sizeof(float)); if(xvalue==NULL || result==NULL || b==NULL || lambdas==NULL) fprintf(stdout,"Unable to allocate memory!"); //ASSIGN VALUES TO XVALUE AND B error=1; if(strcmp(xfilename, "zeros")==0){ //do nothing - calloc already initialized xvalue to 0 } else error *= getVector(xvalue, rdA, xfilename); error *= getVector(b, total_ldA, bfilename); //CHECK FOR FILEOPEN ERRORS; IF ANY PRESENT END PROGRAM for(i=1; i<=nslaves; i++) if(slave_ldAs[i] == -1) error=0; MPI_Bcast(&error, 1, MPI_INT, 0, MPI_COMM_WORLD); if(error==0) { free(result); free(xvalue); free(b); free(lambdas); return; } //PRINT INPUTS /* fprintf(stdout, "Here's x:\n"); for(i=0; i < rdA; i++) { fprintf(stdout, "%f ", xvalue[i]); } fprintf(stdout, "\n and here's b:\n"); for(i=0; i < total_ldA; i++) { fprintf(stdout, "%f ", b[i]); } */ //CREATE ISTA OBJECT instance = ISTAinstance_mpi_new(slave_ldAs, total_ldA, rdA, b, lambdaStart, gamma, accel, regType, xvalue, step, nslaves, MPI_COMM_WORLD, TAG_AX, TAG_ATX, TAG_ATAX, TAG_DIE); //CENTER FEATURES float* shifts = calloc(rdA, sizeof(float)); MPI_Reduce(shifts, instance->meanShifts, rdA, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD); cblas_sscal(rdA, 1.0 / total_ldA, instance->meanShifts, 1); MPI_Bcast(instance->meanShifts, rdA, MPI_FLOAT, 0, MPI_COMM_WORLD); //SCALE FEATURES float* norms = calloc(rdA, sizeof(float)); MPI_Reduce(norms, instance->scalingFactors, rdA, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD); for(j=0; j<rdA; j++) instance->scalingFactors[j] = pow(instance->scalingFactors[j], 0.5); MPI_Bcast(instance->scalingFactors, rdA, MPI_FLOAT, 0, MPI_COMM_WORLD); //CREATE LAMBDA PATH calcLambdas(lambdas, numLambdas, lambdaStart, lambdaFinish, instance); //DEBUGGING AREA /*float* ones = calloc(rdA+1, sizeof(float)); for(i=0; i< rdA+1; i++) { ones[i] = 1.0; } fprintf(stdout, "meanshifts: "); for(i=0; i<5; i++) { fprintf(stdout, "%f ", instance->meanShifts[i]); } fprintf(stdout, "\nscalingFactors: "); for(i=0; i<5; i++) { fprintf(stdout, "%f ", instance->scalingFactors[i]); } fprintf(stdout, "\nlambdas: "); for(i=0; i<5; i++) { fprintf(stdout, "%f ", lambdas[i]); } fprintf(stdout, "\nA * ones: "); multiply_Ax(ones, result, instance); for(i=0; i<5; i++) { fprintf(stdout, "%f ", result[i]); } fprintf(stdout, "\n"); */ //TIME UPDATE computationStartTime = time(NULL); //RUN ISTA for(j=0; j < numLambdas; j++) { instance->lambda = lambdas[j]; ISTAsolve_lite(instance, MAX_ITER, MIN_FUNCDIFF); fprintf(stdout, "\n"); } //UNDO RESCALING for(i=0; i<(instance->rdA); i++) { if(instance->scalingFactors[i] > 0.0001) instance->xcurrent[i] = instance->xcurrent[i] / instance->scalingFactors[i]; } instance->intercept = -1.0 * cblas_sdot(instance->rdA, instance->xcurrent, 1, instance->meanShifts, 1); //WRITE RESULTS writeResults(instance, outfilename, bfilename, lambdas[numLambdas-1]); //STOP TIME endTime = time(NULL); fprintf(stdout,"Setup took %f seconds and computation took %f seconds\n", difftime(computationStartTime, startTime), difftime(endTime, computationStartTime)); //CLOSE THE SLAVE PROCESSES AND FREE MEMORY fprintf(stdout, "Closing the program\n"); for(rank=1; rank <= nslaves; rank++) { MPI_Send(0, 0, MPI_INT, rank, TAG_DIE, MPI_COMM_WORLD); } free(result); ISTAinstance_mpi_free(instance); free(shifts); free(norms); free(lambdas); return; }
int main() { MSS * myResult; /* initialize random seed: */ srand (time(NULL)); unsigned int sizeOfNum = 512; std::vector<int> num; createVector(num, sizeOfNum); printf("Max Sum Sub-Array Algorithms\n\n"); printf("size = %d\n\n", sizeOfNum); std::clock_t start; printf("\n\nBrute Force Max Sum Sub-Array\n\n"); start = std::clock(); bruteMaxSumSub(num, result, sizeOfNum); std::cout << "Brute Force Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms\n"; printf("Result of bruteMaxSumSub, max sum = %d\nSubArray*************\n", result.sum); for(int i = result.start; i <= result.end; ++i) { printf("%d\t", num[i]); } printf("\n\nImproved Brute Force Max Sum Sub-Array\n\n"); start = std::clock(); betterBruteMaxSum(num, result, sizeOfNum); std::cout << "Better Brute Force Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms\n"; printf("Result of betterBruteMaxSumSub, max sum = %d\nSubArray*************\n", result.sum); for(int i = result.start; i <= result.end; ++i) { printf("%d\t", num[i]); } printf("\n\nDivide and Conquer Max Sum Sub-Array\n\n"); start = std::clock(); myResult = divideAndConquerMaxSub(num, 0, sizeOfNum - 1); std::cout << "Divide and Conquer Max Sum Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms\n"; printf("Result of divideAndConquerMaxSub, max sum = %d\nSubArray*************\n", myResult->sum); for(int i = myResult->start; i <= myResult->end; ++i) { printf("%d\t", num[i]); } //clean up delete myResult; myResult = NULL; printf("\n\nLinear Max Sum Sub-Array\n\n"); start = std::clock(); linearMaxSub(num, sizeOfNum, result); std::cout << "Linear Max Sum Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms\n"; printf("Result of linearMaxSub, max sum = %d\nSubArray*************\n", result.sum); for(int i = result.start; i <= result.end; ++i) { printf("%d\t", num[i]); } std::cout << std::endl << std::endl; /********************************************************************************************************************************* **TESTING FILES **********************************************************************************************************************************/ /* Stream class provided by C++ to read from files Credit: http://www.cplusplus.com/doc/tutorial/files/*/ std::ifstream textfile; /* In order to open a file with a stream object we use its member function open */ textfile.open( "MSS_Problems.txt" ); /* To check if a file stream was successful opening a file, you can do it by calling to member is_open Credit: http://www.cplusplus.com/doc/tutorial/files/*/ if( !textfile.is_open() ) { textfile.close(); std::cout << "Please add MSS_Problems.txt and try again." << std::endl; exit(1); } /* Stream class to write on files Credit: http://www.cplusplus.com/doc/tutorial/files/*/ std::ofstream textfile2; textfile2.open("MSS_Results.txt"); /* vector of vectors to store number set */ std::vector<std::vector<int>> setOfNumbers = getNumbers(textfile); textfile.close(); /* Label the results file */ textfile2 << " Algorithm 1: Enumeration \n"; std::cout << " Algorithm 1: Enumeration \n" << std::endl; /* Run enumeration algorithm on input numbers */ for( unsigned int i = 0; i < setOfNumbers.size(); i++ ) { bruteMaxSumSub(setOfNumbers.at(i), result, setOfNumbers.at(i).size()); int total = result.sum; int start = result.start; int end = result.end; /* Call function to output is to be written to MSS_Results.txt */ std::cout << total << std::endl; writeResults( textfile2, setOfNumbers.at(i), start, end, total ); } /* Label the results file */ textfile2 << " Algorithm 2: Better Enumeration \n"; std::cout << " Algorithm 2: Better Enumeration \n" << std::endl; /* Run better enumeration algorithm on input numbers */ for( unsigned int i = 0; i < setOfNumbers.size(); i++ ) { betterBruteMaxSum(setOfNumbers.at(i), result, setOfNumbers.at(i).size()); int total = result.sum; int start = result.start; int end = result.end; /* Call function to output is to be written to MSS_Results.txt */ std::cout << total << std::endl; writeResults( textfile2, setOfNumbers.at(i), start, end, total ); } /* Label the results file */ textfile2 << " Algorithm 3: Divide and Conquer \n"; std::cout << " Algorithm 3: Divide and Conquer \n" << std::endl; /* Run divide and conquer algorithm on input numbers */ for( unsigned int i = 0; i < setOfNumbers.size(); i++ ) { myResult = divideAndConquerMaxSub(setOfNumbers.at(i), 0, setOfNumbers.at(i).size()-1); int total = myResult->sum; int start = myResult->start; int end = myResult->end; /* Call function to output is to be written to MSS_Results.txt */ std::cout << total << std::endl; writeResults( textfile2, setOfNumbers.at(i), start, end, total ); //clean up delete myResult; myResult = NULL; } /* Label the results file */ textfile2 << " Algorithm 4: Linear-time \n"; std::cout << " Algorithm 4: Linear-time \n" << std::endl; for( unsigned int i = 0; i < setOfNumbers.size(); i++ ) { linearMaxSub(setOfNumbers.at(i), setOfNumbers.at(i).size(), result); int total = result.sum; int start = result.start; int end = result.end; /* Call function to output is to be written to MSS_Results.txt */ std::cout << total << std::endl; writeResults( textfile2, setOfNumbers.at(i), start, end, total ); } textfile2.close(); //clean up delete myResult; myResult = NULL; return 0; }
// Point d'entree dans le programme int main(int argc,char** argv) { FILE* transaction_file = fopen(S_LEC,"a+"); fclose(transaction_file); transaction_file = fopen(S_LEC,"r"); if (transaction_file == NULL) { fprintf(stderr,"Impossible d'ouvrir le fichier %s\n",S_LEC); return -1; } char line_buffer[256], message[256]; int i, flags; Connection* connection; PRIM_PACKET p; // Recuperation des references au tuyaux // (respectivement l'ecriture et l'ecoute) transToNet_pipe = atoi(argv[1]); netToTrans_pipe = atoi(argv[2]); // On s'assure que les file descriptors sont en mode 0_NONBLOCK flags = fcntl(transToNet_pipe,F_GETFL,0); fcntl(transToNet_pipe,F_SETFL, flags | O_NONBLOCK); flags = fcntl(netToTrans_pipe,F_GETFL,0); fcntl(netToTrans_pipe,F_SETFL, flags | O_NONBLOCK); if (DEBUG) printf("TRANSPORT\nMes fd sont:\n%i,%i\n",netToTrans_pipe,transToNet_pipe); //ALGO //-------- //TANT QUE FICHIER_NON_VIDE //LIRE S_LEC //REGARDER_TABLE_DE_CONNEXIONS //SI CONNEXION_EXISTE_PAS //ENVOYER_CONNECTION_REQ //ECOUTER_REPONSE //SI REPONSE_POSITIVE //CHANGER_ETAT_CONNEXION_TABLE_CONNEXION //ENVOYER_DATA_REQ //SINON //SUPPRIMER_CONNEXION //FIN SI //SINON //ENVOYER_DATA_REQ //FIN SI //FIN TANT QUE //POUR TOUS LES CONNEXION //SUPPRIMMER_CONNEXION // Lecture du fichier S_LEC, envoie des requetes et ecoute // de la reponse. while(fgets(line_buffer, 256, transaction_file)) { connection = (Connection*) findConnection(line_buffer[0]); // La connexion n'existe pas if (!connection/*==NULL*/) { // Engager une connexion connection = (Connection*) add_connection(line_buffer[0],NULL,NULL); // Creaction d'un paquet contenant la primitive N_CONNECT_req p.prim = N_CONNECT_req; // Genere un seed pour une valeur pseudo-aleatoire // differente par rand() srand(time(NULL)); p.con_prim_packet.src_addr = (unsigned char) rand(); // Adresses aleatoires pour la source p.con_prim_packet.dest_addr = (unsigned char) rand(); // et la destination.. p.con_prim_packet.con_number = connection->tcon.con_number; // Envoie d'un paquet et ecoute de la reponse de ER writePrimPacketToStdOut(&p,I_AM); if(sendPacketToInterface(&p,transToNet_pipe) == -1) return -1; if (getPacketFromInterface(&p,netToTrans_pipe) == -1) return -1; char result[256]; // Action en consequence switch(p.prim) { // CON_PRIM_PACKET reçu => N_CONNECT_conf case N_CONNECT_conf: // Ecriture des resutlats dans S_ECR sprintf(result,"Reception de la primitive N_CONNECT.conf sur la connection %c\n", connection->tcon.con_number); writeResults(result,S_ECR); // Confirmation de la connexion connection->tcon.state = 0x01; // Construction du paquet de DATA p.prim = N_DATA_req; getMessageFromBuffer(line_buffer,message); strcpy(p.data_prim_packet.transaction,message); p.data_prim_packet.con_number = connection->tcon.con_number; // Envoie du paquet a l'ER writePrimPacketToStdOut(&p,I_AM); if(sendPacketToInterface(&p,transToNet_pipe) == -1) return -1; break; // REL_PRIM_PACKET reçu => N_DISCONNECT_ind case N_DISCONNECT_ind: // Ecriture des resultats dans S_ECR sprintf(result,"Reception de la primitive N_DISCONNECT.ind pour la connexion %c\n",connection->tcon.con_number); writeResults(result,S_ECR); // Retrait de la connexion de la table de connexions remove_connection(connection->tcon.con_number); break; } } else { // Construction du paquet de DATA p.prim = N_DATA_req; getMessageFromBuffer(line_buffer,message); strcpy(p.data_prim_packet.transaction,message); p.data_prim_packet.con_number = connection->tcon.con_number; // Envoyer N_DATA.req writePrimPacketToStdOut(&p,I_AM); if(sendPacketToInterface(&p,transToNet_pipe) == -1) return -1; } } // Construction d'un paquet REL_PRIM_PACKET // et vidage de la table de connexions p.prim = N_DISCONNECT_req; connection = first_con_node; while (connection) { p.rel_prim_packet.con_number = connection->tcon.con_number; writePrimPacketToStdOut(&p,I_AM); if(sendPacketToInterface(&p,transToNet_pipe) == -1) return -1; connection = connection->tcon.next; } deleteAllConnections(); // Fermeture du fichier S_LEC fclose(transaction_file); return 0; }
/************************************************************** * * This main function creates a vector of randomly generated integers * * for use in testing the implementations of Algorithms 1-4. The first part measures * * the running time in ms for each Algorithm for display. The second part tests * * input output by reading input from a specified text file, running each Algorithm * * on this input, and writing the results to another specified text file. * ***************************************************************/ int main(int argc, char* argv[]){ std::string filename; std::string outputfilename; /* The first argument (argc) is the number of elements in the array so we should have two elements the program name and file name Credit: http://www.site.uottawa.ca/~lucia/courses/2131-05/labs/Lab3/CommandLineArguments.html */ if(argc != 2) { std::cout << "Please enter an input filename." << std::endl << std::endl; exit(1); } /* which is the second argument (argv). The second argument is always an array of char*, */ else { filename = std::string(argv[1]); std::string tempoutputfilename = std::string(argv[1]); //http://www.cplusplus.com/reference/string/string/length/ int strsize = tempoutputfilename.length() - 4; /* http://www.cplusplus.com/reference/string/string/operator+/ http://www.cplusplus.com/reference/string/string/substr/ */ outputfilename = (tempoutputfilename.substr(0, strsize)) + "change.txt"; std::cout << outputfilename << std::endl; } //cout << filename << endl; /* Stream class provided by C++ to read from files Credit: http://www.cplusplus.com/doc/tutorial/files/*/ std::ifstream textfile; /* In order to open a file with a stream object we use its member function open */ textfile.open(filename); /* To check if a file stream was successful opening a file, you can do it by calling to member is_open Credit: http://www.cplusplus.com/doc/tutorial/files/*/ if(!textfile.is_open()) { std::cout << "The file could not be opened." << std::endl; textfile.close(); exit(1); } /* Call function to put first alternating lines as the coin set input and the second alternating lines as total change V */ std::vector<std::vector<int>> coinsetinput; std::vector<int> changevalueV; getinput( textfile, coinsetinput, changevalueV ); textfile.close(); /* Stream class to write on files Credit: http://www.cplusplus.com/doc/tutorial/files/*/ std::ofstream textfile2; textfile2.open(outputfilename); if(!textfile2.is_open()) { std::cout << "Cannot open for writing. Check the permissions of the directory." << std::endl; textfile2.close(); exit(1); } /* Display a babel for brute force algorithm time trial */ std::cout << "Testing changeslow...." << std::endl; for( unsigned int i = 0; i < coinsetinput.size(); i++ ) { /* Run brute force algorithm on input numbers from first to last element */ std::vector<int> coinCount; runtimetrial( changeslow, coinsetinput.at(i), changevalueV.at(i), coinCount ); } /* Display a babel for greedy algorithm time trial */ std::cout << "Testing changegreedy...." << std::endl; for( unsigned int i = 0; i < coinsetinput.size(); i++ ) { /* Run greedy algorithm on input numbers from first to last element */ std::vector<int> coinCount; runtimetrial( changegreedy, coinsetinput.at(i), changevalueV.at(i), coinCount); } /* Display a babel for dynamic programming algorithm time trial */ std::cout << "Testing changedp...." << std::endl; /*for( unsigned int i = 0; i < coinsetinput.size(); i++ ) { Run greedy algorithm on input numbers from first to last element }*/ /* Call function to output is to be written to text file */ textfile2 << "Brute Force \n\n"; /* Run changeslow algorithm on input numbers */ for( unsigned int i = 0; i < coinsetinput.size(); i++ ) { std::vector<int> coinCount; int minCoins = changeslow( coinsetinput.at(i), changevalueV.at(i), coinCount ); writeResults( textfile2, coinCount, minCoins ); } /* Call function to output is to be written to text file */ textfile2 << "Greedy\n\n"; for( unsigned int i = 0; i < coinsetinput.size(); i++ ) { std::vector<int> coinCount; int minCoins = changegreedy(coinsetinput.at(i), changevalueV.at(i), coinCount); writeResults( textfile2, coinCount, minCoins ); } /* Call function to output is to be written to text file */ textfile2 << "Dynamic Programming\n\n"; //for( unsigned int i = 0; i < coinsetinput.size(); i++ ) // { // std::vector<int> coinCount; // int minCoins = changedp(); //writeResults( textfile2, coinCount, minCoins ); //} textfile2.close(); }
void Game::writeResults() { #ifndef NO_OUT writeResults(std::cout); #endif }
// Create a grayscale face image that has a standard size and contrast & brightness. // "srcImg" should be a copy of the whole color camera frame, so that it can draw the eye positions onto. // If 'doLeftAndRightSeparately' is true, it will process left & right sides seperately, // so that if there is a strong light on one side but not the other, it will still look OK. // Performs Face Preprocessing as a combination of: // - geometrical scaling, rotation and translation using Eye Detection, // - smoothing away image noise using a Bilateral Filter, // - standardize the brightness on both left and right sides of the face independently using separated Histogram Equalization, // - removal of background and hair using an Elliptical Mask. // Returns either a preprocessed face square image or NULL (ie: couldn't detect the face and 2 eyes). // If a face is found, it can store the rect coordinates into 'storeFaceRect' and 'storeLeftEye' & 'storeRightEye' if given, // and eye search regions into 'searchedLeftEye' & 'searchedRightEye' if given. cv::Mat preprocessFace::getPreprocessedFace(cv::Mat &srcImg, int desiredFaceWidth, cv::CascadeClassifier &faceCascade, cv::CascadeClassifier &eyeCascade1, cv::CascadeClassifier &eyeCascade2, bool doLeftAndRightSeparately, cv::Rect *storeFaceRect, cv::Point *storeLeftEye, cv::Point *storeRightEye, cv::Rect *searchedLeftEye, cv::Rect *searchedRightEye) { // Use square faces. int desiredFaceHeight = desiredFaceWidth; // Mark the detected face region and eye search regions as invalid, in case they aren't detected. if (storeFaceRect) storeFaceRect->width = -1; if (storeLeftEye) storeLeftEye->x = -1; if (storeRightEye) storeRightEye->x = -1; if (searchedLeftEye) searchedLeftEye->width = -1; if (searchedRightEye) searchedRightEye->width = -1; // Find the largest face. cv::Rect faceRect; detector.detectLargestObject(srcImg, faceCascade, faceRect); // Check if a face was detected. if (faceRect.width > 0) { // Give the face rect to the caller if desired. if (storeFaceRect) *storeFaceRect = faceRect; cv::Mat faceImg = srcImg(faceRect); // Get the detected face image. // If the input image is not grayscale, then convert the BGR or BGRA color image to grayscale. cv::Mat gray; if (faceImg.channels() == 3) { cvtColor(faceImg, gray, CV_BGR2GRAY); } else if (faceImg.channels() == 4) { cvtColor(faceImg, gray, CV_BGRA2GRAY); } else { // Access the input image directly, since it is already grayscale. gray = faceImg; } // Search for the 2 eyes at the full resolution, since eye detection needs max resolution possible! cv::Point leftEye, rightEye; detectBothEyes(gray, eyeCascade1, eyeCascade2, leftEye, rightEye, searchedLeftEye, searchedRightEye); // Give the eye results to the caller if desired. if (storeLeftEye) *storeLeftEye = leftEye; if (storeRightEye) *storeRightEye = rightEye; // Check if both eyes were detected. if (leftEye.x >= 0 && rightEye.x >= 0) { inputFaceCount++; // Make the face image the same size as the training images. // Since we found both eyes, lets rotate & scale & translate the face so that the 2 eyes // line up perfectly with ideal eye positions. This makes sure that eyes will be horizontal, // and not too far left or right of the face, etc. // Get the center between the 2 eyes. cv::Point2f eyesCenter = cv::Point2f((leftEye.x + rightEye.x) * 0.5f, (leftEye.y + rightEye.y) * 0.5f); // Get the angle between the 2 eyes. double dy = (rightEye.y - leftEye.y); double dx = (rightEye.x - leftEye.x); double len = sqrt(dx*dx + dy*dy); double angle = atan2(dy, dx) * 180.0 / CV_PI; // Convert from radians to degrees. // Hand measurements shown that the left eye center should ideally be at roughly (0.19, 0.14) of a scaled face image. const double DESIRED_RIGHT_EYE_X = (1.0f - DESIRED_LEFT_EYE_X); // Get the amount we need to scale the image to be the desired fixed size we want. double desiredLen = (DESIRED_RIGHT_EYE_X - DESIRED_LEFT_EYE_X) * desiredFaceWidth; double scale = desiredLen / len; // Get the transformation matrix for rotating and scaling the face to the desired angle & size. cv::Mat rot_mat = getRotationMatrix2D(eyesCenter, angle, scale); // Shift the center of the eyes to be the desired center between the eyes. rot_mat.at<double>(0, 2) += desiredFaceWidth * 0.5f - eyesCenter.x; rot_mat.at<double>(1, 2) += desiredFaceHeight * DESIRED_LEFT_EYE_Y - eyesCenter.y; // Rotate and scale and translate the image to the desired angle & size & position! // Note that we use 'w' for the height instead of 'h', because the input face has 1:1 aspect ratio. cv::Mat warped = cv::Mat(desiredFaceHeight, desiredFaceWidth, CV_8U, cv::Scalar(128)); // Clear the output image to a default grey. warpAffine(gray, warped, rot_mat, warped.size()); //imshow("warped", warped); // Give the image a standard brightness and contrast, in case it was too dark or had low contrast. if (!doLeftAndRightSeparately) { // Do it on the whole face. equalizeHist(warped, warped); } else { // Do it seperately for the left and right sides of the face. equalizeLeftAndRightHalves(warped); } //imshow("equalized", warped); // Use the "Bilateral Filter" to reduce pixel noise by smoothing the image, but keeping the sharp edges in the face. cv::Mat filtered = cv::Mat(warped.size(), CV_8U); bilateralFilter(warped, filtered, 0, 20.0, 2.0); //imshow("filtered", filtered); // Filter out the corners of the face, since we mainly just care about the middle parts. // Draw a filled ellipse in the middle of the face-sized image. cv::Mat mask = cv::Mat(warped.size(), CV_8U, cv::Scalar(0)); // Start with an empty mask. cv::Point faceCenter = cv::Point(desiredFaceWidth / 2, cvRound(desiredFaceHeight * FACE_ELLIPSE_CY)); cv::Size size = cv::Size(cvRound(desiredFaceWidth * FACE_ELLIPSE_W), cvRound(desiredFaceHeight * FACE_ELLIPSE_H)); ellipse(mask, faceCenter, size, 0, 0, 360, cv::Scalar(255), CV_FILLED); //imshow("mask", mask); // Use the mask, to remove outside pixels. cv::Mat dstImg = cv::Mat(warped.size(), CV_8U, cv::Scalar(128)); // Clear the output image to a default gray. /* namedWindow("filtered"); imshow("filtered", filtered); namedWindow("dstImg"); imshow("dstImg", dstImg); namedWindow("mask"); imshow("mask", mask); */ // Apply the elliptical mask on the face. filtered.copyTo(dstImg, mask); // Copies non-masked pixels from filtered to dstImg. //imshow("dstImg", dstImg); /*if (leftEye.x >= 0 && rightEye.x >= 0) { eyeRegion.x = 0; eyeRegion.y = searchedLeftEye.y; eyeRegion.width = preprocessedFace.rows; eyeRegion.height = 30; cv::rectangle(frame, eyeRegion, CV_RGB(255, 255, 0), 3); }*/ if (needResults) { writeResults(srcImg, gray, dstImg); } return dstImg; } /* else { // Since no eyes were found, just do a generic image resize. resize(gray, tmpImg, Size(w,h)); } */ } return cv::Mat(); }
int main(){ fp = fopen("partitionResult.txt", "w"); int i=0; scanf("%d", &number_of_vertex); //3 scanf("%d", &number_of_edge); //2 // construct Graph and allocate spaces for each edge graph= malloc(sizeof(struct Graph)); graph->V = number_of_vertex; graph->list = malloc(sizeof(AdjList)*graph->V); //graph->edgeList = malloc(sizeof(EdgeList)*number_of_edge); // allocate space for FreeList freeList = malloc(sizeof(FreeList)*number_of_vertex); // hold the free nodes newFreeList = malloc(sizeof(FreeList)*number_of_vertex); // to hold the new freeList for (i=0; i<graph->V; i++) { graph->list[i].head = NULL; } for (i=0; i<graph->V; i++) { // allocate spaces and give initial values freeList[i].gainList = malloc(sizeof(struct GainList*)); newFreeList[i].gainList = malloc(sizeof(struct GainList*)); freeList[i].gainList->cell_id = i; } Nodes *nodes = malloc(sizeof(Nodes)*number_of_edge); // take source, destinaton and weight from user and hold them into Nodes list for(i=0; i<number_of_edge; i++){ Nodes node = malloc(sizeof(Nodes)); scanf("%d", &node->src); scanf("%d", &node->dest); scanf("%d", &node->weight); nodes[i] = node; } // add edges, make connection between nodes and hold them all in graph->list for(i=0; i<number_of_edge;i++){ NodeList *node = malloc(sizeof*node); node->random = rand()%2; node->dest = nodes[i]->dest; node->next = graph->list[nodes[i]->src].head; graph->list[nodes[i]->src].head = node; // because of undirect NodeList *node2 = malloc(sizeof*node2); node2->random = rand()%2; node2->dest = nodes[i]->src; node2->next = graph->list[nodes[i]->dest].head; graph->list[nodes[i]->dest].head = node2; } // initialize GainList maxDegree = findTheMaxDegree(); headL = malloc(sizeof(struct GainList*)*2*maxDegree+1); headR = malloc(sizeof(struct GainList*)*2*maxDegree+1); lastL = malloc(sizeof(struct GainList*)*2*maxDegree+1); lastR = malloc(sizeof(struct GainList*)*2*maxDegree+1); initializeGainList(); // fill FreeList fillFreeList(); int cut; int minCut; cut = computeCut(); minCut = INT_MAX; printf("Initial Number of Cut %d\n", cut); gainCell(); // display(); // gain cell int j; do{ for(i=0; i<graph->V;i++){ // base cell int baseCellId = findBaseCell(); moveBaseCell(baseCellId); cut = computeCut(); if(cut < minCut){ minCut = cut; for (j=0; j<graph->V; j++) { newFreeList[j].gain = freeList[j].gain; newFreeList[j].partition = freeList[j].partition; newFreeList[j].locked = 0;//freeList[j].locked; } } gainCell(); } for (j=0; j<graph->V; j++) { freeList[j].gain = newFreeList[j].gain; freeList[j].partition = newFreeList[j].partition; freeList[j].locked =0;// newFreeList[j].locked; } gainCell(); }while(cut != minCut); printf("Size of Left %d and Size of Right %d\n", sizeL, sizeR); printf("Min Cut is %d\n", minCut); writeResults(); // write final partition to file fclose(fp); return 0; }
//Gestionnaire de signal void sigHandler(int arg) { writeResults(); dispose(); exit(EXIT_SUCCESS); }
int main (int argc, const char * argv[]){ struct timeval start, end; gettimeofday(&start, NULL); // general parameters size_t maxSeqLen = 50000; int seqType = Sequence::AMINO_ACIDS; // parameter for the prefiltering int kmerSize = 6; int alphabetSize = 21; size_t maxResListLen = 100; int split = 0; int skip = 0; bool aaBiasCorrection = true; float zscoreThr = 50.0f; float sensitivity = 4.0; // parameters for the alignment double evalThr = 0.001; double covThr = 0.8; int maxAlnNum = 10; std::string lastSeqDB = ""; std::string currentSeqDB = ""; std::string cluDB = ""; std::string outDB = ""; std::string tmpDir = ""; // get the path of the scoring matrix char* mmdir = getenv ("MMDIR"); if (mmdir == 0){ std::cerr << "Please set the environment variable $MMDIR to your MMSEQS installation directory.\n"; exit(1); } std::string scoringMatrixFile(mmdir); scoringMatrixFile = scoringMatrixFile + "/data/blosum62.out"; parseArgs(argc, argv, &lastSeqDB, ¤tSeqDB, &cluDB, &outDB, &tmpDir, &scoringMatrixFile, &maxSeqLen); std::string lastSeqDBIndex = lastSeqDB + ".index"; std::string currentSeqDBIndex = currentSeqDB + ".index"; std::string cluDBIndex = cluDB + ".index"; std::string outDBIndex = outDB + ".index"; std::list<std::string>* tmpFiles = new std::list<std::string>(); std::string AIndex = tmpDir + "/A.index"; std::string BIndex = tmpDir + "/B.index"; tmpFiles->push_back(AIndex); tmpFiles->push_back(BIndex); std::string Brest_indexFile = tmpDir + "/Brest.index"; tmpFiles->push_back(Brest_indexFile); std::string BB_clu = tmpDir + "/BB_clu"; std::string BB_clu_index = BB_clu + ".index"; tmpFiles->push_back(BB_clu); tmpFiles->push_back(BB_clu_index); std::cout << "////////////////////////////////////////////////////////////////////////\n"; std::cout << "/////// Init /////////////\n"; std::cout << "////////////////////////////////////////////////////////////////////////\n"; // extract three indexes: // - A: last database version without deleted sequences // - B: sequences which are new in the database writeIndexes(AIndex, BIndex, lastSeqDBIndex, currentSeqDBIndex); std::cout << "////////////////////////////////////////////////////////////////////////\n"; std::cout << "/////// Calculating B->A scores /////////////\n"; std::cout << "////////////////////////////////////////////////////////////////////////\n"; // calculate score for the updating // B->A scores std::string BA_base = runScoresCalculation(currentSeqDB, BIndex, currentSeqDB, AIndex, tmpDir, scoringMatrixFile, maxSeqLen, seqType, kmerSize, alphabetSize, maxResListLen, split, skip, aaBiasCorrection, zscoreThr, sensitivity, evalThr, covThr, maxAlnNum, "BA", tmpFiles); std::cout << "////////////////////////////////////////////////////////////////////////\n"; std::cout << "/////// Adding sequences to existing clusters /////////////\n"; std::cout << "////////////////////////////////////////////////////////////////////////\n"; // update the clustering DBReader* currSeqDbr = new DBReader(currentSeqDB.c_str(), currentSeqDBIndex.c_str()); currSeqDbr->open(DBReader::NOSORT); // data structures for the clustering int seqDBSize = currSeqDbr->getSize(); unsigned int* id2rep = new unsigned int[seqDBSize]; char** rep2cluName = new char*[seqDBSize]; for (int i = 0; i < seqDBSize; i++) rep2cluName[i] = new char[FFINDEX_MAX_ENTRY_NAME_LENTH]; cluster_t* clusters = new cluster_t[seqDBSize]; for (int i = 0; i < seqDBSize; i++){ clusters[i].clu_size = 0; clusters[i].first = 0; clusters[i].last = 0; } std::cout << "Read the existing clustering...\n"; // Read the existing clustering readClustering(currSeqDbr, cluDB, id2rep, rep2cluName, clusters); std::cout << "Append new sequences to the existing clustering...\n"; // append sequences from the new database to the existing clustering based on the B->A alignment scores // write sequences without a match to a separate index (they will be clustered separately) appendToClustering(currSeqDbr, BIndex, BA_base, id2rep, clusters, Brest_indexFile); if (seqsWithoutMatches > 0){ std::cout << "////////////////////////////////////////////////////////////////////////\n"; std::cout << "/////// Calculating B->B scores /////////////\n"; std::cout << "////////////////////////////////////////////////////////////////////////\n"; // B->B scores std::string BB_base = runScoresCalculation(currentSeqDB, Brest_indexFile, currentSeqDB, Brest_indexFile, tmpDir, scoringMatrixFile, maxSeqLen, seqType, kmerSize, alphabetSize, maxResListLen, split, skip, aaBiasCorrection, zscoreThr, sensitivity, evalThr, covThr, maxAlnNum, "BB", tmpFiles); std::cout << "////////////////////////////////////////////////////////////////////////\n"; std::cout << "/////// Appending new clusters /////////////\n"; std::cout << "////////////////////////////////////////////////////////////////////////\n"; std::cout << "Cluster new sequences without a match to the existing clusters...\n"; // cluster sequences without a match to the existing clusters separately // use the index generated in the previous step Clustering* clu = new Clustering(currentSeqDB, currentSeqDBIndex, BB_base, BB_base + ".index", BB_clu, BB_clu_index, 0.0, 0, maxResListLen); clu->run(Clustering::SET_COVER); std::cout << "Append generated clusters to the complete clustering...\n"; // append B->B clusters to the clustering newClus = readClustering(currSeqDbr, BB_clu, id2rep, rep2cluName, clusters); } // write new clustering std::cout << "Write clustering results...\n"; writeResults(clusters, rep2cluName, currSeqDbr, seqDBSize, outDB); std::cout << "done.\n"; currSeqDbr->close(); std::cout << "////////////////////////////////////////////////////////////////////////\n"; std::cout << "/////// Statistics ////////\n"; std::cout << "////////////////////////////////////////////////////////////////////////\n"; std::cout << "\nPrevios database version: " << oldDBSize << " entries.\n"; std::cout << "New database vesion : " << newDBSize << " entries.\n"; std::cout << deletedSeqs << " entries were deleted,\n"; std::cout << newSeqs << " entries are new,\n"; std::cout << sharedSeqs << " entries are shared.\n\n"; std::cout << seqsWithMatches << " new sequences had matches to the previous database version.\n"; std::cout << "Remaining " << seqsWithoutMatches << " were grouped into " << newClus << " new clusters.\n"; gettimeofday(&end, NULL); int sec = end.tv_sec - start.tv_sec; std::cout << "\nTime for updating: " << (sec / 3600) << " h " << (sec % 3600 / 60) << " m " << (sec % 60) << "s\n\n"; deleteTmpFiles(tmpFiles); delete tmpFiles; }