void Player::die(void) { shake(); reset(); lives--; if (lives <= 0) { // game over isDestructable = false; invincibleCount = 20000; ALLEGRO_BITMAP *old_target = al_get_target_bitmap(); al_set_target_bitmap(highscoreBitmap); int w = al_get_bitmap_width(highscoreBitmap); int h = al_get_bitmap_height(highscoreBitmap); ResourceManager& rm = ResourceManager::getInstance(); ALLEGRO_FONT *large_font = (ALLEGRO_FONT *)rm.getData(RES_LARGEFONT); ALLEGRO_FONT *small_font = (ALLEGRO_FONT *)rm.getData(RES_SMALLFONT); al_draw_textf(large_font, al_map_rgb(255, 255, 255), w/2, h/2-16, ALLEGRO_ALIGN_CENTRE, "GAME OVER"); al_draw_textf(small_font, al_map_rgb(255, 255, 255), w/2, h/2+16, ALLEGRO_ALIGN_CENTRE, "%d Points", score); al_set_target_bitmap(old_target); } else { hp = 1; isDestructable = false; invincibleCount = 3000; } }
HitResponse UnstableTile::collision(GameObject& other, const CollisionHit& ) { if(state == STATE_NORMAL) { Player* player = dynamic_cast<Player*> (&other); if(player != NULL && player->get_bbox().get_bottom() < get_bbox().get_top() + SHIFT_DELTA) { shake (); } if (dynamic_cast<Explosion*> (&other)) { shake (); } } return FORCE_MOVE; }
void LoginDialog::onLogin() { try { password = ui->password->text().toStdString(); auto profile_name = ui->profileSelection->currentText().toStdString(); auto profile = bts::application::instance()->load_profile(profile_name,password); if (profile) accept(); } catch (const fc::db_in_use_exception& e) { elog("error ${w}", ("w", e.to_detail_string()) ); QMessageBox::warning(this,tr("Keyhotee login"), tr("Unable to load profile: ") + ui->profileSelection->currentText()); } catch (const fc::exception& e) { elog("error ${w}", ("w", e.to_detail_string()) ); //TODO: We need to display a message to user when profile load fails because // it can't be opened (versus just a bad password specified). One reason // a profile load can fail is because it's already locked (opened by another // Keyhotee process, for example). Unfortunately displaying such a message // requires untangling the exception thrown, so leaving this as-is for now. // QMessageBox::warning(this,tr("Unable to load profile"),e.to_detail_string().c_str()); } ui->password->setText(QString()); shake(); }
void Acquired_Taste(){//dump motor_off(); shake(); ao(); enable_servos(); servo_set(0, 450,4);//half way up motor(MOT_LEFT, -40); motor(MOT_RIGHT, -30);//back up msleep(2000); servo_set (0, 20, 2);//full up ao(); motor(MOT_LEFT, 40); motor(MOT_RIGHT, 30);//unjam if jammed msleep(1000); motor(MOT_LEFT, -40); motor(MOT_RIGHT, -30);//redump msleep(1000); ao(); disable_servos(); msleep(2000); enable_servos(); motor(MOT_LEFT, 60); motor(MOT_RIGHT, 30); servo_set (0, 700, 2);//forward and drop motor(MOT_LEFT, -40); motor(MOT_RIGHT, -30); servo_set (0, 800, 2); disable_servos(); }
void mainView::showDialog2() { dialog1->setSVG("dialog-theme.svg"); dialog1->setTextColor("Yellow"); //Ensure to pass a valid Qt-CSS color name. dialog1->showDialog("<html>Semi transparent Dialog, enabled by <b>transparency</b> in the <i>SVG file</i>. Also you can <b><i>shake it</i></b> to take more attention.</html>", atSlideUp); dialog1->setShakeTTL(9000); QTimer::singleShot(1000,dialog1,SLOT(shake())); }
void Camera::update_scroll_autoscroll(float elapsed_time) { Player* player = sector->player; if(player->is_dying()) return; translation += autoscroll_walker->advance(elapsed_time); keep_in_bounds(translation); shake(); }
void LayerNet::perturb ( LayerNet *cent , LayerNet *perturbed , double temp , int reg ) { int n ; if (nhid1 == 0) { // No hidden layer n = nout * (nin+1) ; shake ( n , cent->out_coefs , perturbed->out_coefs , temp ) ; } else if (nhid2 == 0) { // One hidden layer n = nhid1 * (nin+1) ; shake ( n , cent->hid1_coefs , perturbed->hid1_coefs , temp ) ; if (! reg) { n = nout * (nhid1+1) ; shake ( n , cent->out_coefs , perturbed->out_coefs , temp ) ; } } else { // Two hidden layers n = nhid1 * (nin+1) ; shake ( n , cent->hid1_coefs , perturbed->hid1_coefs , temp ) ; n = nhid2 * (nhid1+1) ; shake ( n , cent->hid2_coefs , perturbed->hid2_coefs , temp ) ; if (! reg) { n = nout * (nhid2+1) ; shake ( n , cent->out_coefs , perturbed->out_coefs , temp ) ; } } }
void ComponentCamera::update() { shake(); // ZOOM/ALTURA de la camara /* if(eventManager->isKeyPressed(KEY::KEY_HOME) || eventManager->isKeyPressed(KEY::KEY_KEY_P)) { relativePosition.y = startYPosition; } if(eventManager->mouseState.wheelUp || eventManager->isKeyPressed(KEY::KEY_PRIOR) || eventManager->isKeyPressed(KEY::KEY_KEY_O)) { speed += ACCELERATION; } else if(eventManager->mouseState.wheelDown || eventManager->isKeyPressed(KEY::KEY_NEXT) || eventManager->isKeyPressed(KEY::KEY_KEY_L)) { speed -= ACCELERATION; } if (speed > MAX_SPEED) { speed = MAX_SPEED; } if (speed < -MAX_SPEED) { speed = -MAX_SPEED; } speed *= FRICTION; if (Math::abs(speed) < Math::abs(0.1)) { speed = 0; } relativePosition.y += speed; if (relativePosition.y > MAX_ZOOM) { relativePosition.y = MAX_ZOOM; } else if (relativePosition.y < MIN_ZOOM) { relativePosition.y = MIN_ZOOM; } */ Vector3d playerPosition(parent->position.x, 0, parent->position.y); node->setPosition(playerPosition + relativePosition + offset); node->setTargetPosition(playerPosition + offset); }
void CCamera::CamShake(float shakeFactor, float shakeX, float shakeY, float shakeZ) { CVector shake(shakeX, shakeY, shakeZ); CVector ds = this->cams[this->activeCam].Source - shake; float force = Clamp(0.0f, sqrt(ds.z * ds.z + ds.Magnitude2DSquared()), 100.0f); v15 = 1.0 - force / 100.0f; v12 = (this->fCameraSpeedSoFar - (CTimer::GetCurrentTimeMs() - this->m_uiCamShakeStart) / 1000.0f) * v15; v13 = v15 * shakeFactor * 0.35; if (v13 > Clamp<float>(0.0f, v12, 2.0f)) { this->fCameraSpeedSoFar = v13; this->m_uiCamShakeStart = CTimer::GetCurrentTimeMs(); } }
void LoginDialog::onLogin() { try { password = ui->password->text().toStdString(); auto profile = bts::application::instance()->load_profile(password); if( profile ) { accept(); } } catch ( const fc::exception& e ) { wlog( "error ${w}", ("w",e.to_detail_string()) ); } ui->password->setText(QString()); shake(); }
void Camera::update(float elapsed_time) { switch(mode) { case NORMAL: update_scroll_normal(elapsed_time); break; case AUTOSCROLL: update_scroll_autoscroll(elapsed_time); break; case SCROLLTO: update_scroll_to(elapsed_time); break; default: break; } shake(); }
void MusicWidget::setupSensors() { QSensorGestureManager manager; QStringList gestureIds = manager.gestureIds(); qDebug() << gestureIds; if(gestureIds.contains("QtSensors.shake2")) { qDebug() << "setup shake 2 sensor"; m_shakeGesture = new QSensorGesture( QStringList() << "QtSensors.shake2" , this); connect(m_shakeGesture, SIGNAL(shakeUp()), m_playlist, SLOT(previous())); connect(m_shakeGesture, SIGNAL(shakeDown()), m_playlist, SLOT(next())); connect(m_shakeGesture, SIGNAL(shakeLeft()), m_playlist, SLOT(previous())); connect(m_shakeGesture, SIGNAL(shakeRight()), m_playlist, SLOT(next())); } else if(gestureIds.contains("QtSensors.shake")) { qDebug() << "setup shake sensor"; m_shakeGesture = new QSensorGesture( QStringList() << "QtSensors.shake" , this); connect(m_shakeGesture, SIGNAL(shake()), m_playlist, SLOT(next())); } if(gestureIds.contains("QtSensors.turnover")) { m_turnoverGesture = new QSensorGesture( QStringList("QtSensors.turnover") ,this ); connect(m_turnoverGesture, SIGNAL(turnover()), this, SLOT(onTurnover())); } }
void Effects::applyEffect(const string& fx) { if(fx == "flip") { flip(true); } else if(fx == "mirror") { mirror(true); } else if(fx == "invert") { invert(true); } else if(fx == "ripple") { ripple(true, 3.5); } else if(fx == "posterize") { posterize(true); } else if(fx == "pixelate") { pixelate(true, pixelate_x, pixelate_y); } else if(fx == "wave") { wave(true, wave_speed, wave_displace, wave_num); } else if(fx == "swirl") { swirl(true, swirl_radius, swirl_angle); } else if(fx == "shake") { shake(true, shake_duration, shake_number, shake_amplitude); } else if(fx == "reflect") { reflect(true); } else if(fx == "crack") { crack(true); } else if(fx == "love") { love(true); } }
void QShakeSensorGestureRecognizer::accelChanged() { qreal x = accel->reading()->x(); qreal y = accel->reading()->y(); qreal z = accel->reading()->z(); currentData.x = x; currentData.y = y; currentData.z = z; if (qAbs(prevData.x - currentData.x) < 1 && qAbs(prevData.y - currentData.y) < 1 && qAbs(prevData.z - currentData.z) < 1) { prevData.x = currentData.x; prevData.y = currentData.y; prevData.z = currentData.z; return; } bool wasShake = checkForShake(prevData, currentData, THRESHOLD); if (!shaking && wasShake && shakeCount >= NUMBER_SHAKES) { shaking = true; shakeCount = 0; Q_EMIT shake(); Q_EMIT detected("shake"); } else if (wasShake) { shakeCount++; if (shakeCount > NUMBER_SHAKES) { timer->start(); } } prevData.x = currentData.x; prevData.y = currentData.y; prevData.z = currentData.z; }
void LayerNet::perturb ( LayerNet *cent , LayerNet *perturbed , double temp , int reg , enum RandomDensity dens ) { int n ; if (nhid1 == 0) { // No hidden layer n = nout * nin_n ; shake ( n , cent->out_coefs , perturbed->out_coefs , temp , dens ) ; limit ( n , perturbed->out_coefs , 20.0 ) ; } else if (nhid2 == 0) { // One hidden layer n = nhid1 * nin_n ; shake ( n , cent->hid1_coefs , perturbed->hid1_coefs , temp , dens ) ; limit ( n , perturbed->hid1_coefs , 20.0 ) ; if (! reg) { n = nout * nhid1_n ; shake ( n , cent->out_coefs , perturbed->out_coefs , temp , dens ) ; limit ( n , perturbed->out_coefs , 20.0 ) ; } } else { // Two hidden layers n = nhid1 * nin_n ; shake ( n , cent->hid1_coefs , perturbed->hid1_coefs , temp , dens ) ; limit ( n , perturbed->hid1_coefs , 20.0 ) ; n = nhid2 * nhid1_n ; shake ( n , cent->hid2_coefs , perturbed->hid2_coefs , temp , dens ) ; limit ( n , perturbed->hid2_coefs , 20.0 ) ; if (! reg) { n = nout * nhid2_n ; shake ( n , cent->out_coefs , perturbed->out_coefs , temp , dens ) ; limit ( n , perturbed->out_coefs , 20.0 ) ; } } }
transform_model* evolve_transform( const language_model* model, const char* text, int (*controller) ( int iteration, transform_model* transform, const char* better_output, unsigned long score)){ const int population_count = POPULATION_SIZE; transform_model* population[population_count]; // Initial population { int i; for (i = 0; i < population_count; i++){ population[i] = random_transform(); } } long iteration; int done = 0; for (iteration = 0;!done;iteration++){ { int i; for (i = 0; i < population_count; i++){ char* out = process(population[i], text, model); free(out); } } qsort(&population, population_count, sizeof(transform_model*), inv_language_score_cmp); { transform_model* winner = population[0]; char* better = process(winner, text, model); int action = controller(iteration, winner, better, winner->score); if ((iteration % SHOW_INTERVAL) == 0) { int limit = strlen(better); // Make the “better” string readable if (limit > 50){ strcpy(&better[40], "\x1b[7m%\x1b[0m"); limit = 40; } int i; for (i = 0; i < limit; i++){ if ((!isalnum(better[i])) && (!ispunct(better[i])) && (better[i] != ' ')){ better[i] = '.'; } } printf("Iteration (%5li) [%5li | %3li]: |\x1b[1m%s\x1b[0m|\n", iteration, winner->score, winner->output_size, better); } free(better); switch(action){ case EVOLVE_SHAKE: shake(population); case EVOLVE_CONTINUE: cross(population, iteration, text); break; case EVOLVE_DONE: done = 1; break; default: printf("Unknown action code: %i\n", action); } } } // Free population { int i; for (i = 1; i < population_count; i++){ free_transform_model(population[i]); } } return population[0]; }
void Camera::update_scroll_normal(float elapsed_time) { assert(sector != 0); Player* player = sector->player; // check that we don't have division by zero later if(elapsed_time < EPSILON) return; /****** Vertical Scrolling part ******/ bool do_y_scrolling = true; if(player->is_dying() || sector->solids->get_height() == 19) do_y_scrolling = false; if(do_y_scrolling) { // target_y is the high we target our scrolling at. This is not always the // high of the player, but if he is jumping upwards we should use the // position where he last touched the ground. (this probably needs // exceptions for trampolines and similar things in the future) float target_y; if(player->fall_mode == Player::JUMPING) target_y = player->last_ground_y + player->get_bbox().get_height(); else target_y = player->get_bbox().p2.y; // delta_y is the distance we'd have to travel to directly reach target_y float delta_y = translation.y - (target_y - SCREEN_HEIGHT*2/3); // speed is the speed the camera would need to reach target_y in this frame float speed_y = delta_y / elapsed_time; // limit the camera speed when jumping upwards if(player->fall_mode != Player::FALLING && player->fall_mode != Player::TRAMPOLINE_JUMP) { if(speed_y > max_speed_y) speed_y = max_speed_y; else if(speed_y < -max_speed_y) speed_y = -max_speed_y; } // finally scroll with calculated speed translation.y -= speed_y * elapsed_time; } /****** Horizontal scrolling part *******/ // our camera is either in leftscrolling, rightscrolling or nonscrollingmode. // when suddenly changing directions while scrolling into the other direction. // abort scrolling, since tux might be going left/right at a relatively small // part of the map (like when jumping upwards) if((player->dir == ::LEFT && scrollchange == RIGHT) || (player->dir == ::RIGHT && scrollchange == LEFT)) scrollchange = NONE; // when in left 1/3rd of screen scroll left if(player->get_bbox().get_middle().x < translation.x + SCREEN_WIDTH/3 - 16 && do_backscrolling) scrollchange = LEFT; // scroll right when in right 1/3rd of screen else if(player->get_bbox().get_middle().x > translation.x + SCREEN_WIDTH/3*2+16) scrollchange = RIGHT; // calculate our scroll target depending on scroll mode float target_x; if(scrollchange == LEFT) target_x = player->get_bbox().get_middle().x - SCREEN_WIDTH/3*2; else if(scrollchange == RIGHT) target_x = player->get_bbox().get_middle().x - SCREEN_WIDTH/3; else target_x = translation.x; // that's the distance we would have to travel to reach target_x float delta_x = translation.x - target_x; // the speed we'd need to travel to reach target_x in this frame float speed_x = delta_x / elapsed_time; // limit our speed float maxv = 130 + (fabsf(player->physic.get_velocity_x() * 1.3)); if(speed_x > maxv) speed_x = maxv; else if(speed_x < -maxv) speed_x = -maxv; // apply scrolling translation.x -= speed_x * elapsed_time; keep_in_bounds(translation); shake(); }
int improve(int ring,clock_t start,int p,int levelMax,int iterMax,int *currBestScore, int *bestScore,elem_sol **currBest,int width,int heigth,pos_t * pos_centers,pos_t *pos_borders,pos_t* pos_corners, int numCenters,int numBorders,int numCorners,int perc_shake_coner,int perc_shake_border,int perc_shake_center,int maxTotal,elem_sol**best, int stepStarts,int maxUguale){ int stepTot=0; int iter,neighborOfcurrBestScore; int prev; clock_t stop; float difference; int uguale; int fine=0,i; elem_sol**neighborOfcurrBest; neighborOfcurrBest=allocaMatrix(width,heigth); int num,binCenter,binCorner,binBorder; binCorner=bin(numCorners); binBorder=bin(numBorders); ring++; //if(ring>2) { // printf("Ring %d",ring); //char c=getchar(); //} fine=0; uguale=0; int cnt=0; while(!fine && cnt < MAX_COUNT){ cnt++; levelMax=heigth/2; p=LEVEL_MIN; while ( p< levelMax && !fine){ iter=0; num=centersOnFrame(p,heigth,numCenters); binCenter=bin(num); computePercShake(binCorner,binBorder,binCenter,&perc_shake_coner,&perc_shake_border,&perc_shake_center); //uguale=0; //printf("p %d\n",p); while(iter < iterMax*p && !fine){ stepTot++; neighborOfcurrBestScore=*currBestScore; storeSolution(neighborOfcurrBest,currBest,width,heigth); for (i=0; i<p; i++){ shake(p,neighborOfcurrBest, width, heigth, pos_centers, pos_borders, pos_corners, numCenters, numBorders, numCorners,perc_shake_coner,perc_shake_border,perc_shake_center); //speedStarting(neighborOfcurrBest, width, heigth, pos_centers, pos_borders, pos_corners, numCenters, numBorders, numCorners); } neighborOfcurrBestScore=CheckMatchingEdgesSol(neighborOfcurrBest,width,heigth); //printf("ring %d p %d iter %d- Before %d \n",ring,p,iter,neighborOfcurrBestScore); if(p>1) improvedLocal(&neighborOfcurrBestScore,neighborOfcurrBest, width,heigth,pos_centers,pos_borders,pos_corners,numCenters,numBorders,numCorners,p); //improve(ring,start,LEVEL_MIN,LEVEL_MIN+1, iterMax,&neighborOfcurrBestScore,*currBestScore,neighborOfcurrBest,width,heigth,pos_centers,pos_borders,pos_corners, //numCenters,numBorders,numCorners,perc_shake_coner,perc_shake_border,perc_shake_center,maxTotal,best,stepStarts,maxUguale/p); //printf("ring %d p %d iter %d- After %d -%d\n",ring,p,iter,neighborOfcurrBestScore,CheckMatchingEdgesSol(neighborOfcurrBest,width,heigth)); if(LOCAL_ROTATE){ localSearch3(pos_centers, numCenters, neighborOfcurrBest, vector, width, heigth); } //speedStarting(neighborOfcurrBest, width, heigth, pos_centers, pos_borders, pos_corners, numCenters, numBorders, numCorners); neighborOfcurrBestScore=CheckMatchingEdgesSol(neighborOfcurrBest,width,heigth); //printf("Dopo local ring %d p %d iter %d- After %d \n",ring,p,iter,neighborOfcurrBestScore); //if(ring==0) printf("Sono tornato!\n"); if (DOLOCAL){ if (FROM_CORNERS_TO_CENTERS) { doLocalSearchHun(CORNER,VALUE_K_CORNER,numCorners,pos_corners,neighborOfcurrBest,heigth,width,&neighborOfcurrBestScore); doLocalSearchHun(BORDER,VALUE_K_BORDER,numBorders,pos_borders,neighborOfcurrBest,heigth,width,&neighborOfcurrBestScore); doLocalSearchHun(CENTER,VALUE_K_CENTER,numCenters,pos_centers,neighborOfcurrBest,heigth,width,&neighborOfcurrBestScore); } else { doLocalSearchHun(CENTER,VALUE_K_CENTER,numCenters,pos_centers,neighborOfcurrBest,heigth,width,&neighborOfcurrBestScore); doLocalSearchHun(BORDER,VALUE_K_BORDER,numBorders,pos_borders,neighborOfcurrBest,heigth,width,&neighborOfcurrBestScore); doLocalSearchHun(CORNER,VALUE_K_CORNER,numCorners,pos_corners,neighborOfcurrBest,heigth,width,&neighborOfcurrBestScore); } } if(DOLOCAL_REPEAT){ do{ do{ doLocalSearchHun(CORNER,VALUE_K_CORNER,numCorners,pos_corners,neighborOfcurrBest,heigth,width,&neighborOfcurrBestScore); prev=neighborOfcurrBestScore; doLocalSearchHun(BORDER,VALUE_K_BORDER,numBorders,pos_borders,neighborOfcurrBest,heigth,width,&neighborOfcurrBestScore); }while (prev !=neighborOfcurrBestScore ); doLocalSearchHun(CENTER,VALUE_K_CENTER,numCenters,pos_centers,neighborOfcurrBest,heigth,width,&neighborOfcurrBestScore); }while (prev != neighborOfcurrBestScore); } stop = clock(); difference = ((float)(stop - globalTime))/CLOCKS_PER_SEC; if( maxTime>0 && difference >= maxTime){ goto end; } if ( (neighborOfcurrBestScore > *currBestScore) || ( /*p==1 &&*/uguale < maxUguale && (neighborOfcurrBestScore == *currBestScore) && different(neighborOfcurrBest,currBest,heigth,width)) ){ if (neighborOfcurrBestScore == *currBestScore) uguale ++; // if(ring >= 3 ){ //printf ("\nRing %d nedges matching = %d \t currBestScore = %d \t bestScore = %d\n", ring,neighborOfcurrBestScore, *currBestScore, bestScore); //printf("\nTime %f - Passaggio %d: Sono all'iter %d e shake è fatta %d volte A %3d B %3d C %3d pt uguale per %d- Sono ripartito %d volte\n", // difference,stepTot, iter, p, perc_shake_coner,perc_shake_border,perc_shake_center,uguale,stepStarts); // } //printGame(heigth, width,neighborOfcurrBest); //printf("p %d\n",p); if (neighborOfcurrBestScore > *currBestScore){ p=LEVEL_MIN; uguale=0; //printGame(heigth, width, currBest); //printf("\a\a\a"); p=LEVEL_MIN;iter=0; num=centersOnFrame(p,heigth,numCenters); binCenter=bin(num); computePercShake(binCorner,binBorder,binCenter,&perc_shake_coner,&perc_shake_border,&perc_shake_center); *currBestScore=neighborOfcurrBestScore; /* stop = clock(); difference = ((float)(stop - start))/CLOCKS_PER_SEC; printf("\nTime %f - Best Score: %d\n",difference,*currBestScore); */ } *currBestScore=neighborOfcurrBestScore; if ( (*currBestScore) > *bestScore ){ storeSolution(best,currBest,width,heigth); *bestScore= (*currBestScore); stop = clock(); difference = ((float)(stop - start))/CLOCKS_PER_SEC; float differenceGlobal = ((float)(stop - globalTime))/CLOCKS_PER_SEC; printf("\nGlobal Time %.2f - Time %.2f for %d instance - Best Score: %d\n",differenceGlobal,difference,stepStarts,*bestScore); } storeSolution(currBest,neighborOfcurrBest,width,heigth); printer(width,heigth,currBest); /* stop = clock(); difference = ((float)(stop - globalTime))/CLOCKS_PER_SEC; printf("\nGlobal Time %.2f\n",difference); */ if (stepTot >= MAXITERTOT || *bestScore == maxTotal || ( maxScore >0 && *bestScore >=maxScore) || ( maxTime>0 && difference>=maxTime) ){ end: printf("\nDone!\n"); storeSolution(best,currBest,width,heigth); printf("\nBest score = best %d in %f seconds\nResult matrix following:\n", *bestScore,difference); printGame2(heigth, width, best); printer(width,heigth,best); fine = 1; } } iter++; } p+=1; } } return fine; }
void ControllerIf::updateState() { // Don't do anything if we're not in a running state if(currentNode != liveNode) { return; } // Each state needs some lead-in delay time for servo movement, etc. current_time = millis(); if(current_time < (state_start_time + STATE_WAIT_TIME)) { return; } // Check weight at a regular interval if(current_time > cur_check_delay) { cur_check_delay += max_check_delay; getWeight(); } switch(cur_state) { case MENU_STATE: set_fill_weight = analogRead(WEIGHT_PIN); cur_fill_weight = 0; cur_shake_angle = FILL_ANGLE; nxt_state = FILL_HYP; Serial.println("Switching to FILL_HYP"); break; case FLUSH_SLN: if(current_time < (state_start_time + 5000 + STATE_WAIT_TIME)) { pump(); } else { nxt_state = FILL_HYP; Serial.println("Switching to FILL_HYP"); } break; case FILL_HYP: if((DEBUG_TIME != 0) && (current_time < (state_start_time + DEBUG_TIME + STATE_WAIT_TIME))) { pump(); } else if(DEBUG_TIME == 0 && (cur_fill_weight < max_fill_weight)) { pump(); } else { if(isFlushCycle) { if(curFlush < max_flush_cycles) { curFlush++; Serial.println("Switching to DRAIN_HYP"); nxt_state = DRAIN_HYP; } else { isFlushCycle = false; curFlush = 0; Serial.println("Switching to SHAKE_HYP"); nxt_state = SHAKE_HYP; } } else { Serial.println("Switching to SHAKE_HYP"); nxt_state = SHAKE_HYP; } } break; case SHAKE_HYP: if(current_time < (state_start_time + (max_shake_time * 1000) + STATE_WAIT_TIME)) { if(cur_shake_angle == SETTLE_ANGLE) { shaker_direction = true; cur_shake_angle = CENTER_ANGLE - max_shaker_angle; shake(); } if(current_time >= cur_state_delay) { cur_state_delay += max_shaker_delay; if(shaker_direction) { cur_shake_angle++; if(cur_shake_angle >= (CENTER_ANGLE + max_shaker_angle)) { shaker_direction = false; } } else { cur_shake_angle--; if(cur_shake_angle <= (CENTER_ANGLE - max_shaker_angle)) { shaker_direction = true; } } shake(); } } else { Serial.println("Switching to SETTLE_HYP"); cur_shake_angle = SETTLE_ANGLE; shake(); nxt_state = SETTLE_HYP; } break; case SETTLE_HYP: if(current_time < (state_start_time + (max_settle_time * 1000) + STATE_WAIT_TIME)) { // No-op } else { Serial.println("Switching to DRAIN_HYP"); nxt_state = DRAIN_HYP; } break; case DRAIN_HYP: if(DEBUG_TIME != 0 && (current_time <= (state_start_time + DEBUG_TIME + STATE_WAIT_TIME)) && (!readDetector())) { /* No-op */ } else if(!readDetector() && (cur_fill_weight > 1) && (DEBUG_TIME == 0) // Set a max drain time && (current_time < (state_start_time + 12000))) { /* No-op */ } else { if(isFlushCycle) { Serial.println("Switching to FILL_HYP"); nxt_state = FILL_HYP; } else { Serial.println("Switching to FILL_NORM"); nxt_state = FILL_NORM; } cur_shake_angle = FILL_ANGLE; shake(); } break; case FILL_NORM: if((DEBUG_TIME != 0) && (current_time < (state_start_time + DEBUG_TIME + STATE_WAIT_TIME))) { pump(); } else if((DEBUG_TIME == 0) && (cur_fill_weight < max_fill_weight)) { /* No-op */ pump(); } else { Serial.println("Switching to SHAKE_NORM"); nxt_state = SHAKE_NORM; } break; case SHAKE_NORM: if(current_time < (state_start_time + (max_shake_time * 1000) + STATE_WAIT_TIME)) { if(cur_shake_angle == SETTLE_ANGLE) { shaker_direction = true; cur_shake_angle = CENTER_ANGLE - max_shaker_angle; shake(); } if(current_time >= cur_state_delay) { cur_state_delay += max_shaker_delay; if(shaker_direction) { cur_shake_angle++; if(cur_shake_angle >= CENTER_ANGLE + max_shaker_angle) { shaker_direction = false; } } else { cur_shake_angle--; if(cur_shake_angle <= CENTER_ANGLE - max_shaker_angle) { shaker_direction = true; } } shake(); } } else { Serial.println("Switching to SETTLE_NORM"); cur_shake_angle = SETTLE_ANGLE; shake(); nxt_state = SETTLE_NORM; } break; case SETTLE_NORM: if(current_time < (state_start_time + (max_settle_time * 1000))) { // No-op } else { Serial.println("Switching to DRAIN_NORM"); nxt_state = DRAIN_NORM; } break; case DRAIN_NORM: if(DEBUG_TIME != 0 && (current_time <= (state_start_time + DEBUG_TIME + STATE_WAIT_TIME)) && (!readDetector())) { /* No-op */ } else if(!readDetector() && (cur_fill_weight > 1) && (DEBUG_TIME == 0) // Set a max drain time && (current_time < (state_start_time + 12000))) { /* No-op */ } else { if(curIters < max_iterations) { isFlushCycle = true; curIters++; Serial.println("Switching to FILL_HYP"); cur_shake_angle = FILL_ANGLE; nxt_state = FILL_HYP; } else { Serial.println("Switching to DONE"); cur_shake_angle = SETTLE_ANGLE; nxt_state = DONE; } shake(); } break; case DONE: // No-op break; } if(cur_state != nxt_state) { cur_state = nxt_state; updateValvePosition(); state_start_time = millis(); cur_check_delay = state_start_time; cur_state_delay = state_start_time; if((cur_state == FILL_HYP) || (cur_state == FILL_NORM) || (cur_state == FLUSH_SLN)) { digitalWrite(PUMP_EN_PIN, HIGH); } else { digitalWrite(PUMP_EN_PIN, LOW); } } }
void *RVNS(void *arg){//Reduced VNS pVNS *vns = arg; int t = 0,k=1,j; int best_aval = 0; int shake_one = 1; bool stop = false; int avalmax_aux=0; int shake_cont =0; int vns_cont = 0; double *x,*x2,*y,*r; double fx,fy; int run=vns->RUN; int p = vns->P; x = malloc (vns->DIM * sizeof(double)); x2 = malloc (vns->DIM * sizeof(double)); y = malloc (vns->DIM * sizeof(double)); //GRAFICOS //INICIO Grafico Convergencia inicializacao #ifdef GRAFICO char *vns_plot_k; /* char *vns_plot_best; */ char file_name[100]; if(GRAFICO == 1){ /* vns_plot_best = (char *) malloc(sizeof(char) * vns->TMAX * 1000); */ sprintf(file_name,"Convergencia/VNS_%d_%d_%d_%d",vns->METHOD,vns->DIM,vns->FUNCTION,vns->RUN); }else if(GRAFICO == 2){ vns_plot_k = (char *) malloc(sizeof(char) * vns->TMAX * 1000); sprintf(file_name,"Convergencia/VNS_K_%d_%d_%d_%d",vns->METHOD,vns->DIM,vns->FUNCTION,vns->RUN); } #endif //FIM Grafico Convergencia inicializacao r = (double*)malloc ( (vns->KMAX+1) *sizeof(double)); if(vns->r == NULL) vns->r = (double*)malloc ( (vns->KMAX+1) *sizeof(double)); //set wich radii value r[0] = 0.0f; for(j=1;j<=vns->KMAX;j++){ r[j] = vns->RADII; vns->r[j] = r[j]; vns->RADII*=vns->Q; } /* memcpy(vns->r,r,sizeof(double)* (vns->KMAX + 1)); */ run = vns->RUN+1; t=0; k=1; vns_cont=0; avalmax_aux=0; shake_cont=0; stop=false; memcpy(x,vns->best,sizeof(double)*vns->DIM); memcpy(x2,x,vns->DIM*sizeof(double));//set as start value, just for initialize memcpy(y,x,vns->DIM*sizeof(double));//set as start value, just for initialize fx = objfunc(x,&vns->FUNCTION,&vns->DIM,&t);//initialize fx avalmax_aux = vns->AVAL_MAX; //GRAFICOS #ifdef GRAFICO if(GRAFICO == 1){ geracao = 0; //melhor fo bestfo_geracoes[execucao][geracao] = fx; if(DEBUG){ printf("\nMelhor[%d] =>%f\n",geracao,bestfo_geracoes[execucao][geracao]); } }else if(GRAFICO == 2){ //calcular a media de K para gerar grafico sprintf(vns_plot_k, "%s %d %lf\n ",vns_plot_k,vns_cont,(double)k); } #endif time (&(vns->solv.stime)); while(t < vns->TMAX && !stop){ k=1; while(k<=vns->KMAX && t< vns->TMAX && !stop){ /* t++; */ vns_cont++; //do shake */ /* shake_one(x, y, r, k,vns->KMAX,vns->DIM,vns->LB,vns->UB,&shake_cont,vns->RADII_T_FLAG,p); */ shake(x, y, r, k,vns->DIM,vns->LB,vns->UB,&shake_cont,vns->RADII_T_FLAG,p,shake_one,0.5f); if( (vns->TMAX - t) < avalmax_aux){ avalmax_aux = vns->TMAX -t; } //change neighborhood, x<= receive the best or the same neighborhoodChange(x,y,&fx,vns->DIM,&k,vns->FUNCTION,&best_aval,&t,&fy,vns->LB,vns->UB); /* if(fx == 0.0f){ */ /* if(vns->FUNCTION == 8){ */ /* if(-418.0 > fx){ */ /* printf("Find the best solution before finis2h!\n"); */ /* stop = true; */ /* }else{ */ /* continue; */ /* } */ /* }else if(fx < (1E-10)){ */ /* printf("Find the best solution before finish!\n"); */ /* stop = true; */ /* } */ //GRAFICOS #ifdef GRAFICO if(GRAFICO == 1 && t%50 ==0){ geracao++; //melhor fo memcpy(&bestfo_geracoes[execucao][geracao],&fx,sizeof(double)); if(DEBUG){ printf("\nMelhor[%d][%d] =>%f\n",execucao,geracao,bestfo_geracoes[execucao][geracao]); } }else if(GRAFICO == 2){ //calcular a media de K para gerar grafico /* sprintf(vns_plot_k, "%s %d %lf\n ",vns_plot_k,vns_cont,(double)k); */ } #endif } } time (&(vns->solv.etime)); vns->solv.t_total = difftime(vns->solv.etime,vns->solv.stime); printf("\n==RUN: %d\n",run); printf("Total number of avaliation: %d\n",t); printf("Best solution found == %.10f\n",fx); printf("Time: == %.0f seconds\n",vns->solv.t_total); vns->solv.c_aval=t; vns->solv.c_aval_best=best_aval; vns->solv.bestfo=fx; free(x); free(y); free(r); return (void*)arg; }
void *BVNS_NM(void *arg){//VNSM com NM pVNS *vns = arg; int t = 0,k=1,i,j; int best_aval = 0; bool stop = false; int shake_cont =0; int vns_cont = 0; double *x,*x2,*y,*r; double fx,fy; int run=vns->RUN; int p=vns->P; int nelmin_cont = 0; double *simplex; int shake_one = 1; int avalmax_aux=0; int num_restart = 0; int ifault = 0; simplex = (double*) malloc ((vns->DIM +1) * sizeof(double)); x = (double*) malloc (vns->DIM * sizeof(double)); x2 = (double*) malloc (vns->DIM * sizeof(double)); y = (double*)malloc (vns->DIM * sizeof(double)); r = (double*)malloc ( (vns->KMAX+1) *sizeof(double)); //set wich radii value r[0] = 0.0f; for(j=vns->KMAX;j>=1;j--){ r[j] = vns->RADII; vns->RADII*=vns->Q; } run = vns->RUN+1; t=0; k=1; vns_cont=0; int vns_geral_cont=0; shake_cont=0; stop=false; for (i=0; i<vns->DIM;i++) //each dimension { x[i] = randon(vns->LB,vns->UB); } memcpy(x2,x,vns->DIM*sizeof(double));//set as start value, just for initialize memcpy(y,x,vns->DIM*sizeof(double));//set as start value, just for initialize fx = objfunc(x,&vns->FUNCTION,&vns->DIM,&t);//initialize fx time (&(vns->solv.stime)); while(t < vns->TMAX && !stop){ k=1; while(k<=vns->KMAX && t< vns->TMAX && !stop){ //do shake */ shake(x, y, r, k,vns->DIM,vns->LB,vns->UB,&shake_cont,vns->RADII_T_FLAG,p,shake_one,1.0f); for(i=0;i<vns->DIM;i++){ simplex[i] = x[i]; //inicializa o simplex com indice igual, menos o final } simplex[vns->DIM] = randon(vns->LB,vns->UB); //o ultimo faz aleatorio if( (vns->TMAX - t) < avalmax_aux){ avalmax_aux = vns->TMAX -t; } nelmin(vns->DIM, x, x, &fx, vns->EPSILON , simplex,avalmax_aux, &nelmin_cont, &num_restart, &ifault, vns->FUNCTION ); avalmax_aux = vns->AVAL_MAX; /* printf("nelmin_cont => %d valor => %.2f\n",nelmin_cont,fx); */ t+=nelmin_cont; nelmin_cont = 0; if(checkisLbUb(x,vns->DIM,vns->LB,vns->UB)){ fx = objfunc(x,&vns->FUNCTION,&vns->DIM,&t); //<= fx vem do nelmin, so atualiza se mudar pelo checkisLBUL } //change neighborhood, x<= receive the best or the same neighborhoodChange(x,x2,&fx,vns->DIM,&k,vns->FUNCTION,&best_aval,&vns_cont,&fy,vns->LB,vns->UB); t+=vns_cont; vns_geral_cont+=vns_cont; vns_cont=0; /* if(vns->FUNCTION == 8){ */ /* if(-418.0 > fx){ */ /* printf("Find the best solution before finis2h!\n"); */ /* stop = true; */ /* }else{ */ /* continue; */ /* } */ /* }else if(fx < (1E-10)){ */ /* printf("Find the best solution before finish!\n"); */ /* stop = true; */ /* } */ /* if(fx == fy){ */ /* printf("Improved with %d avaliation and %.20f value \n",t,fx); */ /* } */ } } t--; time (&(vns->solv.etime)); vns->solv.t_total = difftime(vns->solv.etime,vns->solv.stime); printf("\n==RUN: %d\n",run); /* printf("VNS total number of avaliations : %d\n",vns_geral_cont); */ /* printf("NM total number of avaliations: %d\n",nm_geral_cont); */ printf("Total number of avaliation: %d\n",t); printf("Best solution found == %.10f\n",fx); printf("Time: == %.0f seconds\n",vns->solv.t_total); vns->solv.c_aval=t; vns->solv.c_aval_best=best_aval; vns->solv.bestfo=fx; printf("\n"); free(x); free(x2); free(y); free(r); return (void*)arg; }
double genetic ( double (*func)( int n , double *x ) , // Function to be minimized int ngens , // Number of complete generations int popsize , // Number of individuals in population int climb , // Do we hill climb via elitism? double stddev , // Standard deviation for initial population double pcross , // Probability of crossover (.6-.9 typical) double pmutate , // Probability of mutation (.0001 to .001 typical) double favor_best ,// Factor for favoring best over average (2-3 is good) double fitfac , // Factor for converting fval to raw fitness (-20 good) double fquit , // Quit if function reduced to this amount int nvars , // Number of variables in x double *x , // Set to starting estimate when called; returns best double *best, // Work vector nvars long int *choices , // Work vector popsize long double *fvals , // Work vector popsize long double *fitness , // Work vector popsize long double *pool1, // Work vector nvars * popsize long double *pool2 ) // Work vector nvars * popsize long { int istart, individual, best_individual, generation, n_cross ; int first_child, parent1, parent2, improved, crosspt, nchoices ; double fval, bestfval, *oldpop, *newpop, *popptr, *temppop ; /* Generate initial population pool. We also preserve the best point across all generations, as this is what we will ultimately return to the user. Its objective function value is bestfval. */ bestfval = 1.e30 ; // For saving best (across all individuals) best_individual = 0 ; // Safety only for (individual=0 ; individual<popsize ; individual++) { popptr = pool1 + individual * nvars ; // Build population in pool1 shake ( nvars , x , popptr , stddev ) ; // Randomly perturb about init x fval = (*func) ( nvars , popptr ) ; // Evaluate function there fvals[individual] = fval ; // and keep function value of each if (fval < bestfval) { // Keep track of best bestfval = fval ; // as it will be returned to user best_individual = individual ; // This is its index in pool1 } if (fval <= fquit) break ; } /* The initial population has been built in pool1. Copy its best member to 'best' in case it never gets beat (unlikely but possible!). */ popptr = pool1 + best_individual * nvars ; // Point to best memcpy ( best , popptr , nvars * sizeof(double) ) ; // and save it /* This is the main generation loop. There are two areas for population pool storage: pool1 and pool2. At any given time, oldpop will be set to one of them, and newpop to the other. This avoids a lot of copying. */ oldpop = pool1 ; // This is the initial population newpop = pool2 ; // The next generation is created here for (generation=0 ; generation<ngens ; generation++) { if (fval <= fquit) // We may have satisfied this in initial population break ; // So we test at start of generation loop fval_to_fitness ( popsize , favor_best , fitfac , fvals , fitness ) ; fitness_to_choices ( popsize , fitness , choices ) ; nchoices = popsize ; // Will count down as choices array emptied n_cross = pcross * popsize ; // Number crossing over first_child = 1 ; // Generating first of parent's 2 children? improved = 0 ; // Flags if we beat best if (climb) { // If we are to hill climb memcpy ( newpop , best , nvars * sizeof(double) ) ; // start with best fvals[0] = bestfval ; // Record its error istart = 1 ; // and start children past it } else istart = 0 ; /* Generate the children */ for (individual=istart ; individual<popsize ; individual++) { popptr = newpop + individual * nvars ; // Will put this child here if (first_child) // If this is the first of 2 children, pick parents pick_parents ( &nchoices , choices , &parent1 , &parent2 ) ; if (n_cross-- > 0) // Do crossovers first reproduce ( oldpop + parent1 * nvars , oldpop + parent2 * nvars , first_child , nvars , popptr , &crosspt ) ; else if (first_child) // No more crossovers, so just copy parent memcpy( popptr , oldpop + parent1 * nvars , nvars * sizeof(double)); else memcpy( popptr , oldpop + parent2 * nvars , nvars * sizeof(double)); if (pmutate > 0.0) mutate ( popptr , nvars , stddev , pmutate ) ; fval = (*func) ( nvars , popptr ) ; // Evaluate function for this child fvals[individual] = fval ; // and keep function value of each if (fval < bestfval) { // Keep track of best bestfval = fval ; // It will be returned to user best_individual = individual ; // This is its index in newpop improved = 1 ; // Flag so we copy it later } if (fval <= fquit) break ; first_child = ! first_child ; } // For all genes in population /* We finished generating all children. If we improved (one of these children beat the best so far) then copy that child to the best. Swap oldpop and newpop for the next generation. */ if (improved) { popptr = newpop + best_individual * nvars ; // Point to best memcpy ( best , popptr , nvars * sizeof(double) ) ; // and save it } temppop = oldpop ; // Switch old and new pops for next generation oldpop = newpop ; newpop = temppop ; } /* We are all done. Copy the best to x, as that is how we return it. */ memcpy ( x , best , nvars * sizeof(double) ) ; // Return best return bestfval ; }
int main(int argc, char** argv) { /** * Argument Wrangling * */ boost::program_options::options_description desc( "TestClient" ); boost::program_options::variables_map vm; boost::asio::io_service io_service; std::array<char, MAX_PACKET_BYTES> recvBuffer; boost::asio::ip::udp::endpoint sender_endpoint; size_t bytes_recvd; /** * Note: options inside the configuration file that are NOT listed here * become ignored and are not accessible. */ desc.add_options() ( "help,h", "Display help message" ) ( "server", boost::program_options::value<std::string>()->default_value("localhost"), "MetaServer host. \nDefault:localhost" ) ( "port", boost::program_options::value<int>()->default_value(8453), "MetaServer port. \nDefault:8453" ) ( "attribute", boost::program_options::value<attribute_list>(), "Set client attribute.\nDefault: none" ) ( "filter", boost::program_options::value<attribute_list>(), "Set client filters.\nDefault: none" ) ( "keepalives", boost::program_options::value<int>()->default_value(3), "Number of Keepalives. \nDefault:3" ) ; try { boost::program_options::store( boost::program_options::parse_command_line(argc, argv, desc), vm ); boost::program_options::notify(vm); /** * Special case for help */ if ( vm.count("help") ) { std::cout << desc << std::endl; return 0; } std::cout << "Server : " << vm["server"].as<std::string>() << std::endl; std::cout << "Port : " << vm["port"].as<int>() << std::endl; std::cout << "Keepalives : " << vm["keepalives"].as<int>() << std::endl; std::cout << "---------------" << std::endl; for (boost::program_options::variables_map::iterator it=vm.begin(); it!=vm.end(); ++it ) { if ( it->second.value().type() == typeid(int) ) { std::cout << it->first.c_str() << "=" << it->second.as<int>() << std::endl; } else if (it->second.value().type() == typeid(std::string) ) { std::cout << it->first.c_str() << "=" << it->second.as<std::string>().c_str() << std::endl; } else if (it->second.value().type() == typeid(attribute_list) ) { std::cout << it->first.c_str() << "=Attribute List" << std::endl; } } std::cout << "-------------------------" << std::endl; /** * because boost query is too stupid to take port as an int */ std::stringstream port_str; port_str << vm["port"].as<int>(); boost::asio::ip::udp::socket s(io_service, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 0)); boost::asio::ip::udp::resolver resolver(io_service); boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), vm["server"].as<std::string>(), port_str.str() ); boost::asio::ip::udp::resolver::iterator iterator = resolver.resolve(query); /** * Step 1 : keepalive x3 w/ sleep */ /** * 1.1 - send keepalive */ for ( int i=0 ; i < vm["keepalives"].as<int>() ; ++i ) { MetaServerPacket keep; keep.setPacketType(NMT_CLIENTKEEPALIVE); std::cout << "Sending keepalive ... "; s.send_to(boost::asio::buffer(keep.getBuffer(), keep.getSize()), *iterator ); /** * 1.2 - receive handshake */ bytes_recvd = s.receive_from( boost::asio::buffer(recvBuffer), sender_endpoint ); MetaServerPacket shake( recvBuffer, bytes_recvd ); shake.setAddress(sender_endpoint.address().to_string()); shake.setPort(sender_endpoint.port()); std::cout << "Got handshake ... "; unsigned int shake_key = shake.getIntData(4); /** * 1.3 - send clientshake */ MetaServerPacket clientshake; clientshake.setPacketType(NMT_CLIENTSHAKE); clientshake.addPacketData(shake_key); clientshake.setAddress( shake.getAddress() ); s.send_to(boost::asio::buffer(clientshake.getBuffer(), clientshake.getSize()), *iterator ); std::cout << "Sending registration." << std::endl; //std::cout << "Sleeping between keepalives : 2s" << std::endl; //sleep(2); } /** * Step 2 : register attributes if any */ if ( vm.count("attribute") ) { std::cout << "Registering Client Attributes: " << std::endl; attribute_list v = vm["attribute"].as<attribute_list>(); while(!v.empty()) { std::string ele = v.back(); size_t pos = ele.find_first_of("="); if( pos != std::string::npos ) { std::string n = ele.substr(0,pos); std::string v = ele.substr(pos+1); std::cout << " register: " << n << std::endl; std::cout << " value: " << v << std::endl; MetaServerPacket a; a.setPacketType(NMT_CLIENTATTR); a.addPacketData(n.length()); a.addPacketData(v.length()); a.addPacketData(n); a.addPacketData(v); s.send_to(boost::asio::buffer(a.getBuffer(), a.getSize()), *iterator ); } else { std::cout << " Attribute Ignored : " << ele << std::endl; } v.pop_back(); } } /** * Step 3 : register filters */ if ( vm.count("filter") ) { std::cout << "Registering Client Filters: " << std::endl; attribute_list v = vm["filter"].as<attribute_list>(); while(!v.empty()) { std::string ele = v.back(); size_t pos = ele.find_first_of("="); if( pos != std::string::npos ) { std::string n = ele.substr(0,pos); std::string v = ele.substr(pos+1); std::cout << " register: " << n << std::endl; std::cout << " value: " << v << std::endl; MetaServerPacket a; a.setPacketType(NMT_CLIENTFILTER); a.addPacketData(n.length()); a.addPacketData(v.length()); a.addPacketData(n); a.addPacketData(v); s.send_to(boost::asio::buffer(a.getBuffer(), a.getSize()), *iterator ); } else { std::cout << " Filter Ignored : " << ele << std::endl; } v.pop_back(); } } /** * Step 4 : send listreq */ unsigned int total=1; unsigned int from=0; unsigned int packed=0; unsigned int count=0; while(1) { if ( from > total || total == 0 ) break; std::cout << "List Request: " << std::endl; MetaServerPacket req; req.setPacketType(NMT_LISTREQ); req.addPacketData(from); req.setAddress( sender_endpoint.address().to_string() ); req.setPort( sender_endpoint.port() ); s.send_to(boost::asio::buffer(req.getBuffer(), req.getSize()), *iterator ); bytes_recvd = s.receive_from( boost::asio::buffer(recvBuffer), sender_endpoint ); MetaServerPacket resp( recvBuffer, bytes_recvd ); resp.setAddress(sender_endpoint.address().to_string()); resp.setPort(sender_endpoint.port()); if ( resp.getPacketType() != NMT_LISTRESP || resp.getPacketType() == NMT_PROTO_ERANGE ) break; std::cout << "Received server list packet"; total = resp.getIntData(sizeof(uint32_t)*1); // 4 packed = resp.getIntData(sizeof(uint32_t)*2); // 8 std::cout << " Received " << packed << " / " << total << " servers." << std::endl; for ( count = 1 ; count <= packed; count++ ) { unsigned int offset = (sizeof(uint32_t)*2) + (sizeof(uint32_t)*count); //std::cout << " " << count << " / " << offset << " == "; uint32_t ip = resp.getIntData(offset); //std::cout << ip << std::endl; std::cout << "Server: " << resp.IpNetToAscii(ip) << std::endl; } from += packed; } /** * Step 4: send terminate */ std::cout << "Sending Terminate: " << std::endl; MetaServerPacket term; term.setPacketType(NMT_TERMINATE); term.addPacketData(0); // increase size of term packet to indicate client term.setAddress( sender_endpoint.address().to_string() ); term.setPort( sender_endpoint.port() ); s.send_to(boost::asio::buffer(term.getBuffer(), term.getSize()), *iterator ); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } std::cout << "All Done!" << std::endl; return 0; }
int main(int argc, char** argv){ /* A->0 ; C->1 ; G->2 ; T->3 */ int i, j, nbseq, nb1, nb2, prov, secondes, minutes, heures, jours, muet, nbeval; char nomfinseq[50], nomfintree[50], nomfopt[50], *seq[MAXNSP], *seqname[MAXNSP], *comments[MAXNSP]; char *ctree, *current_best, **evaluated, *ret; double maxl, runtime; FILE *treefile,*in, *optfile, *current_best_file, *evaluated_file; options opt; time_t debut, fin; /* debugf=fopen("shake_debug", "w");*/ init_cas(); srand48(seed); /** input sequences **/ if(argc<2){ muet=0; while(1){ printf("\nSequence file (MASE) ? "); gets(nomfinseq); in=fopen(nomfinseq, "r"); if(in) break; printf("Cannot find file : %s\n", nomfinseq); } } else{ in=fopen(argv[1], "r"); if(!in){ printf("Cannot find sequence file : %s\n", argv[1]); exit(EXIT_FAILURE); } sprintf(nomfinseq, "%s", argv[1]); muet=1; } fclose(in); if(muet) nbseq=readmasemuet(nomfinseq, seq, seqname, comments, MAXDATASET*MAXNSP); else nbseq=readmaseseqs(nomfinseq, seq, seqname, comments, MAXDATASET*MAXNSP); refresh(seq, nbseq, 0); /* debug_nom=seqname; */ /** input tree **/ if(argc<3){ while(1){ printf("\nTree file ? "); gets(nomfintree); treefile=fopen(nomfintree, "r"); if(treefile) break; printf("Cannot find file : %s\n", nomfintree); } } else{ treefile=fopen(argv[2], "r"); if(!treefile){ printf("Cannot find tree file : %s\n", argv[2]); exit(EXIT_FAILURE); } } ctree=readtree(treefile, nbseq); /** input options **/ if(argc<4){ while(1){ printf("\nOption file ? "); gets(nomfopt); optfile=fopen(nomfopt, "r"); if(optfile) break; printf("Cannot find file : %s\n", nomfopt); } } else{ optfile=fopen(argv[3], "r"); if(!optfile){ printf("Cannot find option file : %s\n", argv[3]); exit(EXIT_FAILURE); } } getoptions(&opt, optfile); /** input saved work **/ if(opt->SH_RESTART && argc==5){ evaluated_file=fopen(argv[4], "r"); if(!evaluated_file){ printf("Cannot find evaluated file %s\n", argv[5]); exit(EXIT_FAILURE); } evaluated=check_alloc(MAX_NBLISTMAX, sizeof(char*)); nbeval=0; j=3*MAXLNAME*nbseq; while(1){ evaluated[nbeval]=check_alloc(j, sizeof(char)); ret=fgets(evaluated[nbeval], j, evaluated_file); if(ret==NULL) break; nbeval++; } } else{ evaluated=NULL; nbeval=0; } time(&debut); /** shake **/ maxl=shake(nbseq, seq, seqname, ctree, opt, evaluated, nbeval); /** output **/ if(!opt->print->PRINT1) printf("%f\n", maxl); time(&fin); runtime=difftime(fin, debut); if(opt->print->PRINT1){ jours=(int)(runtime/86400.); heures=(int)((runtime-86400*jours)/3600.); minutes=(int)((runtime-86400*jours-3600*heures)/60.); secondes=(int)(runtime-86400*jours-3600*heures-60*minutes); printf("(running time : "); if(jours) printf("%d days, ", jours); if(jours || heures) printf("%d hours, ", heures); if(jours || heures || minutes) printf("%d minutes, ", minutes); printf("%d seconds)\n\n", secondes); } return 0; }