float ZBrain::MakePathFindingUpdateTime( char nIntelligence) { MQuestNPCGlobalAIValue* pGlobalAIValue = ZGetQuest()->GetNPCCatalogue()->GetGlobalAIValue(); float fShakingRatio = pGlobalAIValue->m_fPathFinding_ShakingRatio; float fTime = pGlobalAIValue->m_fPathFindingUpdateTime[ nIntelligence - 1]; float fExtraValue = fTime * fShakingRatio; float fMinTime = fTime - fExtraValue; if ( fMinTime < 0.0f) fMinTime = 0.0f; float fMaxTime = fTime + fExtraValue; return RandomNumber( fMinTime, fMaxTime); }
void ParticleSystem::InitParticle(Particle &particle, bool random) { if (random) { //random life particle.life = RandomNumber(0.0f, m_maxLife); } else { //full life particle.life = m_maxLife; } //random fade between min and max fade particle.fade = RandomNumber(m_minFade, m_maxFade); //zero position PointZero(particle.position); //perturb initial velocity by spread factor float s = FastSin(m_spread); particle.vX = m_vX + s * RandomNumber(-1.0f, 1.0f); particle.vY = m_vY + s * RandomNumber(-1.0f, 1.0f); particle.vZ = m_vZ + s * RandomNumber(-1.0f, 1.0f); }
float ZBrain::MakeDefaultAttackCoolTime() { if ( !m_pBody->GetNPCInfo()) return 0.0f; float fShakingRatio = 0.3f; float fCoolTime = m_pBody->GetNPCInfo()->fAttackCoolTime; float fExtraValue = fCoolTime * fShakingRatio; float fMinCoolTime = max( (fCoolTime - fExtraValue), 0.01f); float fMaxCoolTime = fCoolTime + fExtraValue; return RandomNumber( fMinCoolTime, fMaxCoolTime); }
void NpcLanzaUnSpell(int NpcIndex, int UserIndex) { /* '************************************************************** */ /* 'Author: Unknown */ /* 'Last Modify by: - */ /* 'Last Modify Date: - */ /* '************************************************************** */ if (UserList[UserIndex].flags.invisible == 1 || UserList[UserIndex].flags.Oculto == 1) { return; } int k; k = RandomNumber(1, Npclist[NpcIndex].flags.LanzaSpells); NpcLanzaSpellSobreUser(NpcIndex, UserIndex, Npclist[NpcIndex].Spells[k]); }
void CParticleManager::CalculateSize(int cont) { unsigned int l_iSizeSize = m_vInfo[cont].vSize.size(); for (unsigned int j=0; j<l_iSizeSize; j++) { //Time SSIZE l_size = m_vInfo[cont].vSize[j]; float l_timeSize = l_size.time; m_vTimeSize.push_back(l_timeSize); //Size float l_sizMin = l_size.sizeMin; float l_sizMax = l_size.sizeMax; float fRand = RandomNumber(l_sizMin, l_sizMax); m_vSize.push_back(fRand); } }
/* ********************************************************************* */ void Init (double *v, double x1, double x2, double x3) /* * *********************************************************************** */ { double x=x1, y=x2, z=x3; double rnd, Bc, g; g = g_inputParam[GRAV]; if (y < 0.0) v[RHO] = 1.0; else v[RHO] = g_inputParam[ETA]; v[PRS] = 1.0/g_gamma + v[RHO]*g*y; /* Hydrostatic balance */ v[VX1] = v[VX2] = v[VX3] = 0.0; /* ----------------------------------- Add perturbation ----------------------------------- */ #if USE_RANDOM_PERTURBATION == YES rnd = RandomNumber(); v[VX2] = 1.e-2*rnd*exp(-y*y*200.0); #else #if DIMENSIONS == 2 v[VX2] = -1.e-2*(1.0 + cos(2.0*CONST_PI*x))*exp(-y*y*200.0); #elif DIMENSIONS == 3 rnd = sqrt(x*x + z*z); v[VX2] = -1.e-2*exp(-rnd*rnd/(0.2*0.2))/cosh(y*y/(0.1*0.1)); #endif #endif /* ----------------------------------- Set magnetic field in units of Bc ----------------------------------- */ #if PHYSICS == MHD Bc = sqrt((g_inputParam[ETA] - 1.0)*fabs(g)); /* Critical field */ v[BX1] = g_inputParam[CHI]*Bc/sqrt(4.0*CONST_PI); v[BX2] = 0.0; v[BX3] = 0.0; v[AX1] = v[AX2] = 0.0; v[AX3] = y*v[BX1]; #endif }
MQUEST_NPC MQuestNPCSpawnTrigger::GetRandomNPC() { float fRandNum = RandomNumber(0.001f, m_fRateSum); float f = 0.0f; for (vector<SpawnTriggerNPCInfoNode>::iterator itor = m_NPCInfo.begin(); itor != m_NPCInfo.end(); ++itor) { f += (*itor).fRate; if (fRandNum <= f) return (*itor).nNPCID; } MQUEST_NPC nDefaultNPC = NPC_GOBLIN; if (!m_NPCInfo.empty()) nDefaultNPC = (*m_NPCInfo.begin()).nNPCID; return nDefaultNPC; }
/* * permute the list of customer ids for the order table */ void InitPermutation (void) { int *cur; int i,j; perm_count = 0; /* initialize with consecutive values [1..ORD_PER_DIST] */ for (i = 0, cur = nums; i < ORD_PER_DIST; i++, cur++) { *cur = i + 1; } /* now, shuffle */ for (i = 0; i < ORD_PER_DIST-1; i++) { j = (int)RandomNumber(i+1, ORD_PER_DIST-1); swap_int(nums[i], nums[j]); } }
/*This functions returns a randomly chose chronic virus infection !!!!!!*/ Virus& Host :: GetChronicInfection(Virus &dummy) { vector<Virus> randomChronicInfections; list<Infection>:: iterator it; int inf_type = 0; for(it = infections.begin(); it!= infections.end(); it++) { inf_type = it->GetInfectionType(); //cout << inf_type << "infection type! "<<endl; if(inf_type!=2) //if it's not chronic continue; else randomChronicInfections.push_back(it->pathogen); } int random = RandomNumber(0,randomChronicInfections.size()-1); dummy.Copy(randomChronicInfections.at(random)); return dummy; }
quaternion RandomQuaternionRange(double dqmax) { quaternion q; double alpha,sina; vector rotaxis; alpha = dqmax*RandomNumber(); rotaxis = RandomUnitVector(); sina = sin(alpha/2.0); q.q0 = cos(alpha/2.0); q.q1 = sina*rotaxis.x; q.q2 = sina*rotaxis.y; q.q3 = sina*rotaxis.z; return q; }
void AiNpcObjeto(int NpcIndex) { /* '*************************************************** */ /* 'Autor: ZaMa */ /* 'Last Modification: 14/09/2009 (ZaMa) */ /* '14/09/2009: ZaMa - Now npcs don't follow protected users. */ /* '*************************************************** */ int UserIndex; int i; bool UserProtected; for (i = (1); i <= (ConnGroups[Npclist[NpcIndex].Pos.Map].CountEntrys); i++) { UserIndex = ConnGroups[Npclist[NpcIndex].Pos.Map].UserEntrys[i]; /* 'Is it in it's range of vision?? */ if (vb6::Abs(UserList[UserIndex].Pos.X - Npclist[NpcIndex].Pos.X) <= RANGO_VISION_X) { if (vb6::Abs(UserList[UserIndex].Pos.Y - Npclist[NpcIndex].Pos.Y) <= RANGO_VISION_Y) { UserProtected = !IntervaloPermiteSerAtacado(UserIndex) && UserList[UserIndex].flags.NoPuedeSerAtacado; if (UserList[UserIndex].flags.Muerto == 0 && UserList[UserIndex].flags.invisible == 0 && UserList[UserIndex].flags.Oculto == 0 && UserList[UserIndex].flags.AdminPerseguible && !UserProtected) { /* ' No quiero que ataque siempre al primero */ if (RandomNumber(1, 3) < 3) { if (Npclist[NpcIndex].flags.LanzaSpells > 0) { NpcLanzaUnSpell(NpcIndex, UserIndex); } return; } } } } } }
/*This functions returns the Virus of the acute infection*/ Virus& Host :: GetAcuteInfection(Virus& dummy) { list<Infection>:: iterator it; vector<Virus> randomAcuteInfections; int inf_type = 0; for(it = infections.begin(); it!= infections.end(); it++) { inf_type = it->GetInfectionType(); if(inf_type != 1) //if it's not an acute infection continue; else //if it is, return the acute virus randomAcuteInfections.push_back(it->pathogen); } int random = RandomNumber(0,randomAcuteInfections.size()-1); //randomAcuteInfections.at(random).PrintParametersVirus(); cout<<"getAcute()"<<endl; dummy.Copy(randomAcuteInfections.at(random)); return dummy; // in case the list is empty, return an empty virus... shoudln't happen anyway! if the list is empty, this function should not be called! }
uint16_t DropRandomItem(struct DropItem* items, uint16_t* item_buffer, struct Solid* solids, uint16_t blocks_destroyed, uint16_t solidIndex) { int i; if (blocks_destroyed == 5) //Random drop timer { blocks_destroyed = RandomNumber() % 6; if (blocks_destroyed == 0) { blocks_destroyed = SPRITE_ITEMBULLET; } else if (blocks_destroyed == 1) { blocks_destroyed = SPRITE_ITEMFLAMEBALL; } else if (blocks_destroyed == 2) { blocks_destroyed = SPRITE_ITEMSHORTPADDLE; } else if (blocks_destroyed == 3) { blocks_destroyed = SPRITE_ITEMLONGPADDLE; } else if (blocks_destroyed == 4) { blocks_destroyed = SPRITE_ITEMFASTBALL; } else { blocks_destroyed = SPRITE_ITEMSLOWBALL; } for (i = 0; i < 10; i++) { if (items[i].sprite.status == 0) { drop_item(&items[i], item_buffer, blocks_destroyed, solids[solidIndex].y_pos, solids[solidIndex].x_pos); break; } } blocks_destroyed = 0; } return blocks_destroyed; }
void NpcEnvenenarUser(int UserIndex) { /* '*************************************************** */ /* 'Author: Unknown */ /* 'Last Modification: 10/07/2010 */ /* '10/07/2010: ZaMa - Now npcs can't poison dead users. */ /* '*************************************************** */ int N; if (UserList[UserIndex].flags.Muerto == 1) { return; } N = RandomNumber(1, 100); if (N < 30) { UserList[UserIndex].flags.Envenenado = 1; WriteConsoleMsg(UserIndex, "¡¡La criatura te ha envenenado!!", FontTypeNames_FONTTYPE_FIGHT); } }
Star::Star(GameData* gamedata , UINT index) { data_ = gamedata; computer_info_ = &data_->COMPUTER_PLANET(index); index_ = index; recycled_metal_ = computer_info_->ruin_metal; recycled_crystal_ = computer_info_->ruin_crystal; is_fleet_out = false; is_npc_player = computer_info_->is_npc_target != 0; name_ = ""; double_res_hero = computer_info_->num_double_res_hero; rank_ = computer_info_->score; is_salve_planet = computer_info_->is_slave_planet != 0; type_ = computer_info_->owner_type; //star position position_ = Index2Pos(index_); bitmap_index_ = RandomNumber(10); //generate enemy if(computer_info_->owner_type == STAR_T_ENEMY) { char buf[32]; if(is_npc_player && data_->NPC_NAME().IsEmpty() == FALSE) { name_.Format("%s[%s]" , data_->NPC_NAME() , position_.ToCString(buf)); } else { name_.Format("%s" , position_.ToCString(buf)); } generate(); } if(computer_info_->owner_type == STAR_T_SELF) { name_ = data_->GetLoginedAccountName(); rank_ = data_->GetLoginedAccountRank(); double_res_hero = data_->GET_STAR_DOUBLE_RES_HERO(); } }
void CloudsVisualSystemRandomDigits2::initRandomNumbers() { // init the numbers cout<<"initRandomNumbers"<<endl; numbers.clear(); int id=0; int zStart = -(zCount*zSpacing/2); int zEnd = zCount*zSpacing/2; int yStart = -(yCount*ySpacing/2); int yEnd = yCount*ySpacing/2; int xStart = -(xCount*xSpacing/2); int xEnd = xCount*xSpacing/2; for (int z=zStart; z<zEnd; z+=zSpacing) { for (int y=yStart; y<yEnd; y+=ySpacing) { for (int x=xStart; x<xEnd; x+=xSpacing) { int row = (int)ofRandom(102); numbers.push_back(RandomNumber(id++, x+ofRandom(xNoise), y+ofRandom(yNoise), z+ofRandom(zNoise), row, 0)); } } } // create the geometry VBO vector<ofVec3f> verts; vector<ofIndexType> indices; for (int i=0; i<numbers.size(); i++) { numbers[i].fillVertices(verts); numbers[i].fillIndices(indices); } vbo.setVertexData(&verts[0], verts.size(), GL_STATIC_DRAW); vbo.setIndexData(&indices[0], indices.size(), GL_STATIC_DRAW); }
void InitializeRandomNumberGenerator(double seed) { unsigned long myint; int kk; double dummy; myint=(unsigned long)((seed)*429496729); myint=myint+1000; if(myint%2==0) myint=myint+1; else myint=myint+2; mt[0]=myint&0xffffffff; for(mti=1;mti<N;mti++) mt[mti]=(69069*mt[mti-1])&0xffffffff; for(kk=1;kk<10000;kk++) dummy=RandomNumber(); return; }
// The min and max values is not the absolute min/max values // The outcome from this function might give a highter prime than the max value. unsigned int RandomPrime( unsigned int min, unsigned int max ) { unsigned int diff = 0; unsigned int number = RandomNumber( min, max ); // Make sure the number is odd if( number % 2 == 0 ) { number++; } // Swap min and max if min is larger than max if( min > max) { unsigned int temp_min = min; min = max; max = temp_min; } // Calculate the diff diff = max - min; // Find a prime by using the randomly generated number as a start number. for( unsigned int i = 0; i < diff; i++ ) { if( IsPrime( number ) ) { return number; } number += 2; } // We did not find any prime. return 0; }
int main() { system("COLOR 1A"); Queue *snake = Queue_Init(); COORD screenResolution = {WIDTH, HEIGHT}; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), screenResolution); SetConsoleTitle("TU-Snake"); COORD directions[4] = { {0, -1}, {0, 1}, {1, 0}, {-1, 0}, }; Direction direction = LEFT; unsigned int keyboardInput = 0; double snakeSpeed = SnakeSpeed; COORD food = {RandomNumber(0, WIDTH), RandomNumber(0, HEIGHT)}; int centerX = WIDTH / 2; int centerY = HEIGHT / 2; //InitSnake for (int i = 0; i < SnakeInitializeSize; i++) { COORD position = { centerX - i , centerY}; Queue_Push(snake, position); } PrintSnake(snake); while (1) { if (_kbhit() == 1) { keyboardInput = _getch(); switch (keyboardInput) { case 119 : //up if (direction != DOWN) direction = UP; break; case 115 : //down if (direction != UP) direction = DOWN; break; case 97 : //left if (direction != RIGHT) direction = LEFT; break; case 100 : //right if (direction != LEFT) direction = RIGHT; break; default: break; } } COORD snakeHead = Queue_Back(snake); COORD nextDirection = directions[direction]; COORD snakeNewHead = {snakeHead.X + nextDirection.X, snakeHead.Y + nextDirection.Y}; //check for collisions if (snakeNewHead.X < 0 || snakeNewHead.Y < 0 || snakeNewHead.X > WIDTH || snakeNewHead.Y > HEIGHT || Queue_Contains (snake, snakeNewHead)) { char text[] = "!!!Game is over!!!"; COORD startPoint = {centerX - strlen(text)/2, centerY}; GoToPosition(startPoint); system("COLOR CF"); printf("%s", text); PlaySong(); break; } //add new head to snake Queue_Push(snake, snakeNewHead); //check for grow if (snakeNewHead.X == food.X && snakeNewHead.Y == food.Y) { food.X = RandomNumber(0, WIDTH); food.Y = RandomNumber(0, HEIGHT); if (snakeSpeed - 1 > 1) snakeSpeed--; } else { Queue_Pop(snake); } PrintSnake(snake); GoToPosition(food); printf("%c", SnakeFood); if (snakeSpeed - 0.1 > 1) snakeSpeed -= 0.1; Sleep((int)snakeSpeed); ClearScreen; } system("pause > ''"); return 0; }
//------------------------------------------------------------------------------------------ long Radio::playMessage (RadioMessageType msgType) { long i, roll, callsign, fragmentNum, dropOut = 0; if (!useSound) return(NO_PLAY); if (!enabled) return(NO_PLAY); if (!owner) return(NO_PLAY); if (!soundSystem->checkMessage(owner, messageInfo[msgType].priority, msgType)) return(NO_PLAY); if ((msgType == RADIO_AMMO_OUT) && ammoOutPlayed) return(NO_PLAY); if (messageInfo[msgType].styleCount > 1) { roll = RandomNumber(100); // choose which style of message to play for (i=0; i<messageInfo[msgType].styleCount; i++) { dropOut += messageInfo[msgType].styleChance[i]; if (roll < dropOut) break; } if (i != 0 && i == messageInfo[msgType].styleCount) return NO_PLAY; if (messageInfo[msgType].messageMapping + i == owner->getLastMessage()) i++; if (i >= messageInfo[msgType].styleCount) i = 0; } else i = 0; //RadioData *msgData = (RadioData *)radioHeap->Malloc(sizeof(RadioData)); RadioData *msgData = new RadioData; //magic 02102011 if (!msgData) { return(NO_PLAY); } memset(msgData,0,sizeof(RadioData)); msgData->noiseId = SHORT_STATIC; msgData->msgType = msgType; msgData->msgId = messageInfo[msgType].messageMapping + i; msgData->movieCode = messageInfo[msgType].movieCode; msgData->msgHeap = NULL ; //radioHeap; //magic 02102011 msgData->turnQueued = turn; msgData->priority = messageInfo[msgType].priority; msgData->pilot = owner; msgData->expirationDate = scenarioTime + messageInfo[msgType].shelfLife; //----------------------------------------------------------------------- // Load the pieces need for playback. callsign = 0; fragmentNum = 0; if (messageInfo[msgType].pilotIdentifiesSelf) { if (messageInfo[RADIO_CALLSIGN].styleCount > 1) { roll = RandomNumber(100); // choose which style of message to play for (i=0; i<messageInfo[RADIO_CALLSIGN].styleCount; i++) { dropOut += messageInfo[RADIO_CALLSIGN].styleChance[i]; if (roll < dropOut) break; } if (i != 0 && i == messageInfo[RADIO_CALLSIGN].styleCount) callsign = 0; if (i >= messageInfo[RADIO_CALLSIGN].styleCount) callsign = 0; } else callsign = 0; callsign += messageInfo[RADIO_CALLSIGN].messageMapping; } if (callsign) { if (messagesFile[radioID]->seekPacket(callsign) == NO_ERR) { unsigned long messageSize = messagesFile[radioID]->getPacketSize(); //msgData->data[fragmentNum] = (MemoryPtr)radioHeap->Malloc(messageSize); msgData->data[fragmentNum] = (MemoryPtr)gos_Malloc(messageSize); //magic 02102011 if (!msgData->data[fragmentNum]) { //radioHeap->Free(msgData); delete msgData; //magic 02102011 return(NO_PLAY); } messagesFile[radioID]->readPacket(callsign,msgData->data[fragmentNum]); msgData->dataSize[fragmentNum] = messageSize; fragmentNum++; } } if (messagesFile[radioID]->seekPacket(msgData->msgId) == NO_ERR) { unsigned long messageSize = messagesFile[radioID]->getPacketSize(); //magic 31032011 begin if (messageSize > 0) { //magic 31032011 end //msgData->data[fragmentNum] = (MemoryPtr)radioHeap->Malloc(messageSize); msgData->data[fragmentNum] = (MemoryPtr)gos_Malloc(messageSize); //magic 02102011 if (!msgData->data[fragmentNum]) { while (fragmentNum >= 0) { //radioHeap->Free(msgData->data[fragmentNum]); gos_Free(msgData->data[fragmentNum]); //magic 02102011 fragmentNum--; } //radioHeap->Free(msgData); delete msgData; //magic 02102011 return(NO_PLAY); } messagesFile[radioID]->readPacket(msgData->msgId,msgData->data[fragmentNum]); msgData->dataSize[fragmentNum] = messageSize; //magic 31032011 begin } //magic 31032011 end if (noiseFile->seekPacket(msgData->noiseId) == NO_ERR) { unsigned long messageSize = noiseFile->getPacketSize(); //msgData->noise[0] = (MemoryPtr)radioHeap->Malloc(messageSize); msgData->noise[0] = (MemoryPtr)gos_Malloc(messageSize); //magic 02102011 if (!msgData->noise[0]) { //radioHeap->Free(msgData); delete msgData; //magic 02102011 if (fragmentNum > 0) //radioHeap->Free(msgData->data[0]); gos_Free(msgData->data[0]); //magic 02102011 return(NO_PLAY); } noiseFile->readPacket(msgData->noiseId,msgData->noise[0]); msgData->noiseSize[fragmentNum] = messageSize; } } //------------------------------------------------------ // Big ol bug here. We weren't checking to see if the // queue was full. If it was, memory would leak from // the smacker window. It wouldn't leak from the RadioHeap // because we clear the radio heap every mission!! if (soundSystem->queueRadioMessage(msgData) != NO_ERR) { if (msgData) { for (long j=0;j<MAX_FRAGMENTS;j++) { //radioHeap->Free(msgData->data[j]); gos_Free(msgData->data[j]); //magic 02102011 msgData->data[j] = NULL; //radioHeap->Free(msgData->noise[j]); gos_Free(msgData->noise[j]); //magic 02102011 msgData->noise[j] = NULL; } //radioHeap->Free(msgData); delete msgData; msgData = NULL; } return (NO_PLAY); } if (msgType == RADIO_AMMO_OUT) ammoOutPlayed = true; return(msgData->msgId); }
// divide N particles among p compartments int main(void) // takes in no parameters { int i,j,k,l,index; int P,N,Ncycle; double Distribution[MAX_COMPARTMENTS][MAX_PARTICLES]; //2D Array: what are the brackets doing here? Okay most likely they are to define the dimensionality of the array. int NumInComp[MAX_COMPARTMENTS]; //1D Array: declaring number of particles in compartment FILE *FilePtr; //created sufficient memory for FilePtr // initialize the random number generator with the system time InitializeRandomNumberGenerator(time(0l)); //most likely a function located in ran_uniform.h; I think time(01) is supposed to be the seed value for the generator // read the input parameters printf("Number of Particles N? "); fscanf(stdin,"%d",&N); //I REALLY DON'T Understand what fscanf is doing in this situation printf("Number of Compartments p? "); fscanf(stdin,"%d",&P); printf("Number of Cycles (x %d)? ",CycleMultiplication); fscanf(stdin,"%d",&Ncycle); if(P<2||P>MAX_COMPARTMENTS||N<2||N>MAX_PARTICLES) { printf("Error in input parameters\n"); exit(1); //what does exit do here (and what is the 1 for?) } // initialize: So you have to make sure every entry is zero? What is the default setting? for(i=0;i<N;i++) { for(j=0;j<P;j++) { Distribution[j][i]=0.0; NumInComp[j]=0; } } // loop over all cycles for(i=0;i<Ncycle;i++) for(k=0;k<CycleMultiplication;k++) { // Distribute particles over the compartments: // Loop over all particles, pick a random compartment, and add // a particle to it. // A random number in the interval [0,1> can be generated using // RandomNumber(). // NumInComp[index] = number of particles in compartment 'index'. // start modification for(l=0;l<N;l++) { index = round(RandomNumber()*(P)); NumInComp[index] += 1; } // end modification // make a histogram for(j=0;j<P;j++) { Distribution[j][NumInComp[j]]+=1.0; NumInComp[j]=0; } } // Write Results FilePtr=fopen("results.dat","w"); for(j=0;j<P;j++) { for(i=0;i<N;i++) { if(Distribution[j][i]>0.0) Distribution[j][i]/=(double)Ncycle*CycleMultiplication; fprintf(FilePtr,"%d %f\n",i,Distribution[j][i]); } fprintf(FilePtr,"\n"); } fclose(FilePtr); // write analytical distribution FilePtr=fopen("analytical.dat","w"); for(j=0;j<N;j++) { fprintf(FilePtr,"%d %f\n",j,exp(LnFactorial(N)-LnFactorial(j)- LnFactorial(N-j)-j*log(P)-(N-j)*log(P/((double)(P-1))))); } fclose(FilePtr); return 0; }
//***************************************************************************** // // This task manages the scurrying about of a spider. // //***************************************************************************** static void SpiderTask(void *pvParameters) { uint32_t ui32Dir, ui32Image, ui32Temp; int32_t i32X, i32Y, i32Spider; // // Get the spider number from the parameter. // i32Spider = (long)pvParameters; // // Add the current tick count to the random entropy pool. // RandomAddEntropy(xTaskGetTickCount()); // // Reseed the random number generator. // RandomSeed(); // // Indicate that this spider is alive. // HWREGBITW(&g_ui32SpiderAlive, i32Spider) = 1; // // Indicate that this spider is not dead yet. // HWREGBITW(&g_ui32SpiderDead, i32Spider) = 0; // // Get a local copy of the spider's starting position. // i32X = g_pi32SpiderX[i32Spider]; i32Y = g_pi32SpiderY[i32Spider]; // // Choose a random starting direction for the spider. // ui32Dir = RandomNumber() >> 29; // // Start by displaying the first of the two spider animation images. // ui32Image = 0; // // Loop forever. // while(1) { // // See if this spider has been killed. // if(HWREGBITW(&g_ui32SpiderDead, i32Spider) == 1) { // // Wait for 2 seconds. // vTaskDelay((1000 / portTICK_RATE_MS) * 2); // // Clear the spider from the display. // DisplayImage(i32X - (SPIDER_WIDTH / 2), i32Y - (SPIDER_HEIGHT / 2), g_pui8SpiderBlankImage); // // Indicate that this spider is not alive. // HWREGBITW(&g_ui32SpiderAlive, i32Spider) = 0; // // Delete the current task. This should never return. // vTaskDelete(NULL); // // In case it does return, loop forever. // while(1) { } } // // Enter a critical section while the next move for the spider is // determined. Having more than one spider trying to move at a time // (via preemption) would make the collision detection check fail. // taskENTER_CRITICAL(); // // Move the spider. // i32X += g_pi32SpiderStepX[ui32Dir]; i32Y += g_pi32SpiderStepY[ui32Dir]; // // See if the spider has cross the boundary of its area, if it has // collided with another spider, or if random chance says that the // spider should turn despite not having collided with anything. // if((i32X < SPIDER_MIN_X) || (i32X > SPIDER_MAX_X) || (i32Y < SPIDER_MIN_Y) || (i32Y > SPIDER_MAX_Y) || (SpiderCollide(i32Spider, i32X, i32Y) != -1) || (RandomNumber() < 0x08000000)) { // // Undo the previous movement of the spider. // i32X -= g_pi32SpiderStepX[ui32Dir]; i32Y -= g_pi32SpiderStepY[ui32Dir]; // // Get a random number to determine the turn to be made. // ui32Temp = RandomNumber(); // // Determine how to turn the spider based on the random number. // Half the time the spider turns to the left and half the time it // turns to the right. Of each half, it turns a quarter of a turn // 12.5% of the time and an eighth of a turn 87.5% of the time. // if(ui32Temp < 0x10000000) { ui32Dir = (ui32Dir + 2) & 7; } else if(ui32Temp < 0x80000000) { ui32Dir = (ui32Dir + 1) & 7; } else if(ui32Temp < 0xf0000000) { ui32Dir = (ui32Dir - 1) & 7; } else { ui32Dir = (ui32Dir - 2) & 7; } } // // Update the position of the spider. // g_pi32SpiderX[i32Spider] = i32X; g_pi32SpiderY[i32Spider] = i32Y; // // Exit the critical section now that the spider has been moved. // taskEXIT_CRITICAL(); // // Have the display task draw the spider at the new position. Since // there is a one pixel empty border around all the images, and the // position of the spider is incremented by only one pixel, this also // erases any traces of the spider in its previous position. // DisplayImage(i32X - (SPIDER_WIDTH / 2), i32Y - (SPIDER_HEIGHT / 2), g_ppui8SpiderImage[(ui32Dir * 2) + ui32Image]); // // Toggle the spider animation index. // ui32Image ^= 1; // // Delay this task for an amount of time based on the direction the // spider is moving. // vTaskDelay(g_pui32SpiderDelay[ui32Dir & 1]); // // Add the new tick count to the random entropy pool. // RandomAddEntropy(xTaskGetTickCount()); // // Reseed the random number generator. // RandomSeed(); } }
void MinimalizationSimulation(void) { int j,k; REAL Drift,ReferenceEnergy,ran; int NumberOfSystemMoves,NumberOfParticleMoves,NumberOfSteps; int ran_int; Drift=0.0; ReferenceEnergy=0.0; CurrentSystem=0; fprintf(stderr, "Starting minimization\n"); OpenOutputFile(); //InitializeNoseHooverAllSystems(); InitializesEnergiesAllSystems(); InitializesEnergyAveragesAllSystems(); InitializeSmallMCStatisticsAllSystems(); InitializeMCMovesStatisticsAllSystems(); CalculateTotalEnergyAllSystems(); PrintPreSimulationStatus(); for(CurrentSystem=0;CurrentSystem<NumberOfSystems;CurrentSystem++) { for(k=0;k<NumberOfCycles;k++) { InitializesEnergiesAllSystems(); InitializesEnergyAveragesAllSystems(); CalculateTotalEnergyAllSystems(); for(CurrentCycle=0;CurrentCycle<NumberOfInitializationCycles;CurrentCycle++) { if((CurrentCycle%PrintEvery)==0) PrintIntervalStatusInit(CurrentCycle,NumberOfInitializationCycles,OutputFilePtr[CurrentSystem]); NumberOfSystemMoves=12; NumberOfParticleMoves=MAX2(MinimumInnerCycles,NumberOfAdsorbateMolecules[CurrentSystem]+NumberOfCationMolecules[CurrentSystem]); NumberOfSteps=(NumberOfSystemMoves+NumberOfParticleMoves)*NumberOfComponents; for(j=0;j<NumberOfSteps;j++) { ran_int=(int)(RandomNumber()*NumberOfSteps); switch(ran_int) { case 0: if(RandomNumber()<ProbabilityParallelTemperingMove) ParallelTemperingMove(); break; case 1: if(RandomNumber()<ProbabilityHyperParallelTemperingMove) HyperParallelTemperingMove(); break; case 2: if(RandomNumber()<ProbabilityParallelMolFractionMove) ParallelMolFractionMove(); break; case 3: if(RandomNumber()<ProbabilityChiralInversionMove) ChiralInversionMove(); break; case 4: if(RandomNumber()<ProbabilityHybridNVEMove) HybridNVEMove(); break; case 5: if(RandomNumber()<ProbabilityHybridNPHMove) HybridNPHMove(); break; case 6: if(RandomNumber()<ProbabilityHybridNPHPRMove) HybridNPHPRMove(); break; case 7: if(RandomNumber()<ProbabilityVolumeChangeMove) VolumeMove(); break; case 8: if(RandomNumber()<ProbabilityBoxShapeChangeMove) BoxShapeChangeMove(); break; case 9: if(RandomNumber()<ProbabilityGibbsVolumeChangeMove) GibbsVolumeMove(); break; case 10: if(RandomNumber()<ProbabilityFrameworkChangeMove) FrameworkChangeMove(); break; case 11: if(RandomNumber()<ProbabilityFrameworkShiftMove) FrameworkShiftMove(); break; default: // choose component at random CurrentComponent=(int)(RandomNumber()*(REAL)NumberOfComponents); // choose the Monte Carlo move at random ran=RandomNumber(); if(ran<Components[CurrentComponent].ProbabilityTranslationMove) TranslationMove(); else if(ran<Components[CurrentComponent].ProbabilityRandomTranslationMove) RandomTranslationMove(); else if(ran<Components[CurrentComponent].ProbabilityRotationMove) RotationMove(); else if(ran<Components[CurrentComponent].ProbabilityPartialReinsertionMove) PartialReinsertionMove(); else if(ran<Components[CurrentComponent].ProbabilityReinsertionMove) ReinsertionMove(); else if(ran<Components[CurrentComponent].ProbabilityReinsertionInPlaceMove) ReinsertionInPlaceMove(); else if(ran<Components[CurrentComponent].ProbabilityReinsertionInPlaneMove) ReinsertionInPlaneMove(); else if(ran<Components[CurrentComponent].ProbabilityIdentityChangeMove) IdentityChangeMove(); else if(ran<Components[CurrentComponent].ProbabilitySwapMove) { if(RandomNumber()<0.5) SwapAddMove(); else SwapRemoveMove(); } else if(ran<Components[CurrentComponent].ProbabilityWidomMove) ; else if(ran<Components[CurrentComponent].ProbabilitySurfaceAreaMove) ; else if(ran<Components[CurrentComponent].ProbabilityGibbsChangeMove) GibbsParticleTransferMove(); else if(ran<Components[CurrentComponent].ProbabilityGibbsIdentityChangeMove) GibbsIdentityChangeMove(); } } if(CurrentCycle%1000==0) OptimizeTranslationAcceptence(); } // do the minimization Minimization(k); InitializesEnergiesCurrentSystem(); CalculateEnergy(); PrintEnergyStatus(OutputFilePtr[CurrentSystem],"minimization full energy"); } PrintRestartFile(); } PrintPostSimulationStatus(); CloseOutputFile(); }
/* * prepare data and execute order status transaction */ static int do_ordstat (int t_num) { int c_num; int byname,i,ret; clock_t clk1,clk2; double rt; struct timespec tbuf1; struct timespec tbuf2; int w_id, d_id, c_id; char c_last[16]; if(num_node==0){ w_id = RandomNumber(1, num_ware); }else{ c_num = ((num_node * t_num)/num_conn); /* drop moduls */ w_id = RandomNumber(1 + (num_ware * c_num)/num_node, (num_ware * (c_num + 1))/num_node); } d_id = RandomNumber(1, DIST_PER_WARE); c_id = NURand(1023, 1, CUST_PER_DIST); Lastname(NURand(255,0,999), c_last); if (RandomNumber(1, 100) <= 60) { byname = 1; /* select by last name */ }else{ byname = 0; /* select by customer id */ } clk1 = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tbuf1 ); for (i = 0; i < MAX_RETRY; i++) { ret = ordstat(t_num, w_id, d_id, byname, c_id, c_last); clk2 = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tbuf2 ); if(ret){ rt = (double)(tbuf2.tv_sec * 1000.0 + tbuf2.tv_nsec/1000000.0-tbuf1.tv_sec * 1000.0 - tbuf1.tv_nsec/1000000.0); if(rt > max_rt[2]) max_rt[2]=rt; hist_inc(2, rt); if(counting_on){ if( rt < RTIME_ORDSTAT ){ success[2]++; success2[2][t_num]++; }else{ late[2]++; late2[2][t_num]++; } } return (1); /* end */ }else{ if(counting_on){ retry[2]++; retry2[2][t_num]++; } } } if(counting_on){ retry[2]--; retry2[2][t_num]--; failure[2]++; failure2[2][t_num]++; } return (0); }
/* * prepare data and execute the new order transaction for one order * officially, this is supposed to be simulated terminal I/O */ static int do_neword (int t_num) { int c_num; int i,ret; clock_t clk1,clk2; double rt; struct timespec tbuf1; struct timespec tbuf2; int w_id, d_id, c_id, ol_cnt; int all_local = 1; int notfound = MAXITEMS+1; /* valid item ids are numbered consecutively [1..MAXITEMS] */ int rbk; int itemid[MAX_NUM_ITEMS]; int supware[MAX_NUM_ITEMS]; int qty[MAX_NUM_ITEMS]; if(num_node==0){ w_id = RandomNumber(1, num_ware); }else{ c_num = ((num_node * t_num)/num_conn); /* drop moduls */ w_id = RandomNumber(1 + (num_ware * c_num)/num_node, (num_ware * (c_num + 1))/num_node); } d_id = RandomNumber(1, DIST_PER_WARE); c_id = NURand(1023, 1, CUST_PER_DIST); ol_cnt = RandomNumber(5, 15); rbk = RandomNumber(1, 100); for (i = 0; i < ol_cnt; i++) { itemid[i] = NURand(8191, 1, MAXITEMS); if ((i == ol_cnt - 1) && (rbk == 1)) { itemid[i] = notfound; } if (RandomNumber(1, 100) != 1) { supware[i] = w_id; } else { supware[i] = other_ware(w_id); all_local = 0; } qty[i] = RandomNumber(1, 10); } clk1 = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tbuf1 ); for (i = 0; i < MAX_RETRY; i++) { ret = neword(t_num, w_id, d_id, c_id, ol_cnt, all_local, itemid, supware, qty); clk2 = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tbuf2 ); if(ret){ rt = (double)(tbuf2.tv_sec * 1000.0 + tbuf2.tv_nsec/1000000.0-tbuf1.tv_sec * 1000.0 - tbuf1.tv_nsec/1000000.0); //printf("NOT : %.3f\n", rt); if (freport_file != NULL) { fprintf(freport_file,"%d %.3f\n", time_count, rt); } if(rt > max_rt[0]) max_rt[0]=rt; hist_inc(0, rt); if(counting_on){ if( rt < RTIME_NEWORD ){ success[0]++; success2[0][t_num]++; }else{ late[0]++; late2[0][t_num]++; } } return (1); /* end */ }else{ if(counting_on){ retry[0]++; retry2[0][t_num]++; } } } if(counting_on){ retry[0]--; retry2[0][t_num]--; failure[0]++; failure2[0][t_num]++; } return (0); }
void Mcloop(void) { int i,j,k; int NumberAccepted,NumberTrials; double RosenbluthFactor,RosenbluthFactorOld,r; double BondedEnergyOld,BondedEnergyNew,NonBondedEnergyNew,NonBondedEnergyOld; double BondedEnergySum,NonBondedEnergySum,EnergyNormalize,BondedEnergy,NonBondedEnergy; FILE *FilePtr; FilePtr=fopen("movie.pdb","w"); InitializePdb(FilePtr); // NumberTrials: number of attempts to create a chain // NumberAccepted: number of accepted chains // BondedEnergySum: average bonded energy // NonBondedEnergySum: average non bonded energy // EnergyNormalize: number of configurations used to compute averages // BondedEnergyOld, BondedEnergyNew: bonded energy of the old and trial chains // NonBondedEnergyOld, NonBondedEnergyNew: non bonded energy of the old and trial chains // RosenbluthFactorOld, RosenbluthFactor: statistical weight of the old and trial chains. If random chains are generated, both values are 1. // r: end-to-end distance // BondedEnergy,NonBondedEnergy: Bonded and non bonded energy of the chain // initiallize variables RosenbluthFactor=1.0; BondedEnergyNew=0.0; NonBondedEnergyNew=0.0; RosenbluthFactorOld=1.0; BondedEnergyOld=0.0; NonBondedEnergyOld=0.0; NumberTrials=0.0; NumberAccepted=0.0; BondedEnergySum=0.0; NonBondedEnergySum=0.0; EnergyNormalize=0.0; // generate a first chain Grow(FALSE,&RosenbluthFactorOld,&BondedEnergyOld,&NonBondedEnergyOld); for(j=0;j<ChainLength;j++) { Positions[j].x=TrialPositions[j].x; Positions[j].y=TrialPositions[j].y; Positions[j].z=TrialPositions[j].z; } BondedEnergy=BondedEnergyOld; NonBondedEnergy=NonBondedEnergyOld; // Initialize the subroutine "Sample" (the subroutine that will sample the average end-to-end distance) Sample(INITIALIZE,1.0,1.0); // Generate the Markov chain of states for(i=0;i<NumberOfSteps;i++) { if(fmod(i,20) == 0) { printf("cycle: %d \n", i); } for(k=0;k<1000;k++) { NumberTrials++; // retrace old chain Grow(TRUE,&RosenbluthFactorOld,&BondedEnergyOld,&NonBondedEnergyOld); // create a new chain Grow(FALSE,&RosenbluthFactor,&BondedEnergyNew,&NonBondedEnergyNew); // If the new chain is accepted, then copy coordinates if(RandomNumber()<(RosenbluthFactor/RosenbluthFactorOld)) { NumberAccepted++; NonBondedEnergy=NonBondedEnergyNew; BondedEnergy=BondedEnergyNew; for(j=0;j<ChainLength;j++) { Positions[j].x=TrialPositions[j].x; Positions[j].y=TrialPositions[j].y; Positions[j].z=TrialPositions[j].z; } } RosenbluthFactor=1.0; // If the simulation is beyond the set number of equilibration steps, // sample End-To-End Distance And Average Energies if(i>=NumberOfInitializationSteps) { r=sqrt(SQR(Positions[ChainLength-1].x-Positions[0].x)+ SQR(Positions[ChainLength-1].y-Positions[0].y)+ SQR(Positions[ChainLength-1].z-Positions[0].z)); Sample(SAMPLE,r,RosenbluthFactor); BondedEnergySum+=BondedEnergy; NonBondedEnergySum+=NonBondedEnergy; // update number of configurations sampled EnergyNormalize+=1.0; // Periodically write a pdb file containing the particle coordinates if(k==0&&(i%5)==0) WritePdb(FilePtr); } } } // Call subroutine "Sample" to output the histogram of the end-to-end distance Sample(WRITE_RESULTS,1.0,1.0); // Output average energies and fraction of accepted chains printf("Fraction Accepted : %f\n", (double)NumberAccepted/(double)NumberTrials ); printf("Average bonded energy : %f\n",BondedEnergySum/EnergyNormalize); printf("Average nonbonded energy : %f\n",NonBondedEnergySum/EnergyNormalize); fclose(FilePtr); }
void GlobalMinimumSimulation(void) { int i,j,k,l; int success; REAL ran,GlobalMinimumEnergy,UInitial,UAfterMC; success=0; GlobalMinimumEnergy=EnergyOverlapCriteria; OpenOutputFile(); PrintPreSimulationStatus(); for(k=0;k<NumberOfCycles;k++) { do { CurrentSystem=0; for(i=0;i<NumberOfAdsorbateMolecules[0];i++) RemoveAdsorbateMolecule(); for(i=0;i<NumberOfCationMolecules[0];i++) RemoveCationMolecule(); for(j=0;j<NumberOfComponents;j++) { if(Components[j].CreateNumberOfMolecules[0]>0) { CurrentSystem=0; if(Components[j].ExtraFrameworkMolecule) MakeInitialCations(Components[j].CreateNumberOfMolecules[0],j); else MakeInitialAdsorbates(Components[j].CreateNumberOfMolecules[0],j); } } CalculateForce(); UInitial=UTotal[0]; for(l=0;l<NumberOfInitializationCycles;l++) { for(j=0;j<MAX2(MinimumInnerCycles,NumberOfAdsorbateMolecules[CurrentSystem]+NumberOfCationMolecules[CurrentSystem]);j++) { // choose component at random CurrentComponent=(int)(RandomNumber()*(REAL)NumberOfComponents); // choose the Monte Carlo move at random ran=RandomNumber(); if(Components[CurrentComponent].ExtraFrameworkMolecule) { if(ran<Components[CurrentComponent].ProbabilityTranslationMove) TranslationMoveCation(); if(ran<Components[CurrentComponent].ProbabilityRotationMove) RotationMoveCation(); else if(ran<Components[CurrentComponent].ProbabilityReinsertionMove) ReinsertionCationMove(); } else { if(ran<Components[CurrentComponent].ProbabilityTranslationMove) TranslationMoveAdsorbate(); if(ran<Components[CurrentComponent].ProbabilityRotationMove) RotationMoveAdsorbate(); else if(ran<Components[CurrentComponent].ProbabilityReinsertionMove) ReinsertionAdsorbateMove(); } } } CalculateForce(); UAfterMC=UTotal[0]; // do the minimization as //success=BakerMinimizationNoOutput(); if(success==0) fprintf(OutputFilePtr[0],"Minimization failed to convergence within %d steps\n",MaximumNumberOfMinimizationSteps); } while(success==0); // recompute energy CalculateForce(); CurrentSystem=0; fprintf(OutputFilePtr[0],"iteration: %d Energy before Monte-Carlo: %18.10f [K] Energy after Monte-Carlo: %18.10f [K]\n", k,UInitial*ENERGY_TO_KELVIN,UAfterMC*ENERGY_TO_KELVIN); fflush(OutputFilePtr[0]); if(UTotal[0]<GlobalMinimumEnergy) { fprintf(OutputFilePtr[0],"found lower new minimum, positions saved to restart-file\n"); GlobalMinimumEnergy=UTotal[0]; PrintRestartFile(); } fprintf(OutputFilePtr[0],"\t\tMinimization steps: %d Minimized energy: %18.10f [K] (%18.10f [kJ/mol]) Global minimum: %18.10f (%18.10f [kJ/mol])\n", success,UTotal[0]*ENERGY_TO_KELVIN,UTotal[0]*ENERGY_TO_KJ_PER_MOL,GlobalMinimumEnergy*ENERGY_TO_KELVIN,GlobalMinimumEnergy*ENERGY_TO_KJ_PER_MOL); fflush(OutputFilePtr[0]); } PrintPostSimulationStatus(); CloseOutputFile(); }
/* * execute delivery transaction */ static int do_delivery (int t_num) { int c_num; int i,ret; clock_t clk1,clk2; double rt; struct timespec tbuf1; struct timespec tbuf2; int w_id, o_carrier_id; if(num_node==0){ w_id = RandomNumber(1, num_ware); }else{ c_num = ((num_node * t_num)/num_conn); /* drop moduls */ w_id = RandomNumber(1 + (num_ware * c_num)/num_node, (num_ware * (c_num + 1))/num_node); } o_carrier_id = RandomNumber(1, 10); clk1 = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tbuf1 ); for (i = 0; i < MAX_RETRY; i++) { ret = delivery(t_num, w_id, o_carrier_id); clk2 = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tbuf2 ); if(ret){ rt = (double)(tbuf2.tv_sec * 1000.0 + tbuf2.tv_nsec/1000000.0-tbuf1.tv_sec * 1000.0 - tbuf1.tv_nsec/1000000.0); if(rt > max_rt[3]) max_rt[3]=rt; hist_inc(3, rt ); if(counting_on){ if( rt < RTIME_DELIVERY ){ success[3]++; success2[3][t_num]++; }else{ late[3]++; late2[3][t_num]++; } } return (1); /* end */ }else{ if(counting_on){ retry[3]++; retry2[3][t_num]++; } } } if(counting_on){ retry[3]--; retry2[3][t_num]--; failure[3]++; failure2[3][t_num]++; } return (0); }
float Common::ResetTimer(float maxAmount, float minAmount) //Fix this. { return mClock.getElapsedTime().asSeconds() + RandomNumber(minAmount, maxAmount); }
/* * prepare data and execute the stock level transaction */ static int do_slev (int t_num) { int c_num; int i,ret; clock_t clk1,clk2; double rt; struct timespec tbuf1; struct timespec tbuf2; int w_id, d_id, level; if(num_node==0){ w_id = RandomNumber(1, num_ware); }else{ c_num = ((num_node * t_num)/num_conn); /* drop moduls */ w_id = RandomNumber(1 + (num_ware * c_num)/num_node, (num_ware * (c_num + 1))/num_node); } d_id = RandomNumber(1, DIST_PER_WARE); level = RandomNumber(10, 20); clk1 = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tbuf1 ); for (i = 0; i < MAX_RETRY; i++) { ret = slev(t_num, w_id, d_id, level); clk2 = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &tbuf2 ); if(ret){ rt = (double)(tbuf2.tv_sec * 1000.0 + tbuf2.tv_nsec/1000000.0-tbuf1.tv_sec * 1000.0 - tbuf1.tv_nsec/1000000.0); if(rt > max_rt[4]) max_rt[4]=rt; hist_inc(4, rt ); if(counting_on){ if( rt < RTIME_SLEV ){ success[4]++; success2[4][t_num]++; }else{ late[4]++; late2[4][t_num]++; } } return (1); /* end */ }else{ if(counting_on){ retry[4]++; retry2[4][t_num]++; } } } if(counting_on){ retry[4]--; retry2[4][t_num]--; failure[4]++; failure2[4][t_num]++; } return (0); }