int spec_random_load (int fd) {
    /* Now fill up the first chunk with random data, if this data is truly
       random then we will not get much of a boost out of it */
#define RANDOM_CHUNK_SIZE (128*1024)
#define RANDOM_CHUNKS     (32)
    /* First get some "chunks" of random data, because the gzip
	algorithms do not look past 32K */
    int i, j;
    char random_text[RANDOM_CHUNKS][RANDOM_CHUNK_SIZE];

    debug(4,"Creating Chunks\n");
    for (i = 0; i < RANDOM_CHUNKS; i++) {
	debug1(5,"Creating Chunk %d\n", i);
	for (j = 0; j < RANDOM_CHUNK_SIZE; j++) {
	    random_text[i][j] = (int)(ran()*256);
	}
    }

    debug(4,"Filling input file\n");
    /* Now populate the input "file" with random chunks */
    for (i = 0 ; i < spec_fd[fd].limit; i+= RANDOM_CHUNK_SIZE) {
	memcpy(spec_fd[fd].buf + i, random_text[(int)(ran()*RANDOM_CHUNKS)],
		RANDOM_CHUNK_SIZE);
    }
    /* TODO-REMOVE: Pretend we only did 1M */
    spec_fd[fd].len = 1024*1024;
    return 0;
}
Esempio n. 2
0
TEST(LazardEvaluation, Test)
{
	using Poly = carl::MultivariatePolynomial<Rational>;
	carl::Variable x = carl::freshRealVariable("x");
	carl::Variable y = carl::freshRealVariable("y");
	carl::Variable z = carl::freshRealVariable("z");
	
	Poly p = (Poly(x)-Poly(y))*z;
	
	carl::LazardEvaluation<Rational,Poly> le(p);
	
	{
		carl::UnivariatePolynomial<Rational> p(x, std::initializer_list<Rational>{-2, 0, 1});
		carl::Interval<Rational> i(Rational(1), carl::BoundType::STRICT, Rational(2), carl::BoundType::STRICT);
		carl::RealAlgebraicNumber<Rational> ran(p, i);
		
		le.substitute(x, ran);
	}
	
	{
		carl::UnivariatePolynomial<Rational> p(y, std::initializer_list<Rational>{-2, 0, 1});
		carl::Interval<Rational> i(Rational(1), carl::BoundType::STRICT, Rational(2), carl::BoundType::STRICT);
		carl::RealAlgebraicNumber<Rational> ran(p, i);
		
		le.substitute(y, ran);
	}
	
	EXPECT_EQ(-Poly(z), le.getLiftingPoly());
}
Esempio n. 3
0
void computerPlay(Plateau& plat,Pion& pion) {
	PNoeud pn;
	pn.plat=plat;
	pn.computer=pion;
	pn.max=true;
	vector<PNoeud> l;
	pn.generateAll(l);
	vector< pair<float,vector<PNoeud>::iterator> > results;
	
	for(vector<PNoeud>::iterator it=l.begin();it!=l.end();it++) {
		float val=minmax::minimax(*it,DIFFICULTY);
		pair<float,vector<PNoeud>::iterator> tmpPair(val,it);
		if(results.empty()) {
			results.push_back(tmpPair);
			continue;
		}
		if(val==results[0].first)
			results.push_back(tmpPair);
		else if(val>results[0].first) {
			results.clear();
			results.push_back(tmpPair);
		}
	}
	boost::minstd_rand ran(clock());
	size_t choice=ran()%results.size();
	plat = results[choice].second->plat;
}
Esempio n. 4
0
 // C++ standard for generating random doubless
 static double random(double min, double max)
 {
     std::mt19937 rng;
     rng.seed(std::random_device()());
     std::uniform_real_distribution<double> ran(min, max);
     return ran(rng);
 }
Color Raytracer::CalnReflection( Collider* collider , Vector3 ray_V , int dep , bool refracted , int* hash, int rc, Color weight) {
	Primitive* pri = collider->GetPrimitive();
	ray_V = ray_V.Reflect( collider->N );

	if ( pri->GetMaterial()->drefl < EPS || dep > MAX_DREFL_DEP ) {
		Color alpha = pri->GetMaterial()->color * pri->GetMaterial()->refl;
		return RayTracing( collider->C , ray_V , dep + 1 , refracted , hash, rc, weight * alpha) * alpha;
	}

	Vector3 Dx = ray_V.GetAnVerticalVector();
	Vector3 Dy = ray_V.Cross(Dx);
	Dx = Dx.GetUnitVector() * pri->GetMaterial()->drefl;
	Dy = Dy.GetUnitVector() * pri->GetMaterial()->drefl;
	
	int totalSample = camera->GetDreflQuality();
	Color rcol, alpha = pri->GetMaterial()->color * pri->GetMaterial()->refl / totalSample;
	for ( int k = 0 ; k < totalSample ; k++ ) {
		double x , y;
		do {
			x = ran() * 2 - 1;
			y = ran() * 2 - 1;
		} while ( x * x + y * y > 1 );
		x *= pri->GetMaterial()->drefl;
		y *= pri->GetMaterial()->drefl;

		rcol += RayTracing( collider->C , ray_V + Dx * x + Dy * y , dep + MAX_DREFL_DEP , refracted , NULL, rc, weight * alpha);
	}
	return rcol * alpha;
}
Esempio n. 6
0
 // C++ standard for generating random integers
 static int random(int min, int max)
 {
     std::mt19937 rng;
     rng.seed(std::random_device()());
     std::uniform_int_distribution<std::mt19937::result_type> ran(min, max);
     return ran(rng);
 }
Esempio n. 7
0
void fill_matrix(double *A, int n, int seed) {
    int i;
    double x;
    x=ran(seed); /* This is only for setting the seed */
    for (i=0; i<n*n; i++) A[i]=ran(0);
    return;
}
void Neuron::randomize(){
	for(int i=0;i<inputCount;++i){
		weight[i] = ran().NormalRandom(0.0,0.1,0.0,1.0);
		//printf("%lf ",weight[i]);
	}
	//printf("\n");
}
Esempio n. 9
0
/* This function creates the double gaussian distruted x-values for the dopand atoms
* width1 i the distance between the 2 peaks
* width 2 is the width of a single peak.
*/
double xDistrFun2(double xcenter,double width1,double width2) {
	static long idum = 0;
	static long seed = 0;
	static int count = 0;
	static double x2=0,xavg=0;
	double x,dx;

	if (idum == 0) idum  = -(long)(time(NULL)); 
	if (seed == 0) seed  = -(long)(time(NULL)); 

	if (width2 >0) {
		count ++;
		dx = width2*gasdev(&idum);
		x = xcenter+width1*((ran(&seed) > 0.5)-0.5)+dx;
		xavg += x;
		x2 += SQR(dx);
		return x;
	}
	else {
		printf("Statistics (%d): xavg=%g, x2dev=%g\n",count,xavg/(double)count,sqrt(x2/(double)count));
		xavg = 0;
		x2 = 0;
		return 0;
	}
}
Esempio n. 10
0
void addDiagonal(double mu, int* i, int* j, double* v, int nz_generated, int newsize, bool* diags_done) {

    int c;
    int pos = nz_generated;
    for(c=0; c<N; c++) {
        if(!diags_done[c]){

            i[pos] = c;
            j[pos] = c;
            v[pos] = ran()*2.0-1.0;

            pos++;


        }

    }
    // now add mu to each diagonal value.

    for(c=0;c<newsize; c++) {

        if(i[c]==j[c]) {
            v[c] += mu;

        }

    }


}
Esempio n. 11
0
void random(vector *a)
{
    for (long i = 0; i < a->d; i++) {
        a->component[i] = ran() - 0.5;
    }
    
    normalize(a);
}
Esempio n. 12
0
int main() {
    int r;
    int ret = max(-1,-2,&r);
    if(ret == -1) printf("参数相等\n");
    else printf("max=%d\n",r);
    r = ran();
    if(r == -1) printf("随机数错误\n");
    else printf("ran=%d\n",r);
}
Vector3d ran3(){
  double x, y, r2;
  do{
    x = 2 * ran() - 1;
    y = 2 * ran() - 1;
    r2 = x * x + y * y;
  } while(r2 >= 1 || r2 == 0);
  double fac = sqrt(-2*log(r2)/r2);
  Vector3d out(x*fac,y*fac,0);
  do{
    x = 2 * ran() - 1;
    y = 2 * ran() - 1;
    r2 = x * x + y * y;
  } while(r2 >= 1 || r2 == 0);
  fac = sqrt(-2*log(r2)/r2);
  out[2]=x*fac;
  return out;
}
Esempio n. 14
0
	int roll(int many, int sides) {
		int i,q=0;
		if(many>10000)
			many=10000;
		if(sides>1000000)
			sides=1000000;
		for (i=0;i<many;i++) {
			q += ran(sides);
		}
		return ( q );
	}
Esempio n. 15
0
LL get_fac(LL num)
{
    int sz=2 ;
    LL ret=1 ;
	for (LL x0=ran(),x=x0;ret==1;sz*=2,x0=x)
		for (int i=1;i<=sz && ret==1;i++)
    {
     	x=mul(x,x,num)+1 ;
        ret=gcd(x-x0,num) ;
        if(ret<0) ret=-ret ;
	}
    return ret ;
}
Esempio n. 16
0
int aiArilou(pPlayer ai, pObject ObjectsOfConcern, COUNT ConcernCounter)
{
	pObject lpEvalDesc;
	pPlayer opp=(pPlayer)ai->opp;

	 ObjectsOfConcern[ENEMY_SHIP_INDEX].MoveState = ENTICE;
		ship_intelligence (ai, ObjectsOfConcern, ConcernCounter);

		if (ai->special_turn == 0)
		{


			ai->ship_input_state &= ~SPECIAL;

			lpEvalDesc = &ObjectsOfConcern[ENEMY_WEAPON_INDEX];
			if (lpEvalDesc->parent && lpEvalDesc->which_turn <= 6)
			{
				s8 IsTrackingWeapon;



				/*if (((opp->ship_flags	& SEEKING_WEAPON)
						//&& lpEvalDesc->tr->next.image.farray ==
						//EnemyStarShipPtr->RaceDescPtr->ship_data.weapon
						) ||
						((opp->ship_flags & SEEKING_SPECIAL)
						// &&	lpEvalDesc->tr->next.image.farray ==
						//EnemyStarShipPtr->RaceDescPtr->ship_data.special))
						})*/
				if ((opp->ship_flags	& SEEKING_WEAPON)&&(opp->ship_flags & SEEKING_SPECIAL))
					IsTrackingWeapon = 1;
				else
					IsTrackingWeapon = 0;

				if ((//(opp->ship_flags & IMMEDIATE_WEAPON)|| /* means IMMEDIATE WEAPON */
						 (IsTrackingWeapon && (lpEvalDesc->which_turn == 1
						|| (lpEvalDesc->type != CREW))) /* FIGHTERS!!! */
						|| PlotIntercept (ai,lpEvalDesc,  3, 0))
						&& !(ran(0,3)))
				{
					ai->ship_input_state &= ~(LEFT | RIGHT | THRUST | WEAPON);
					ai->ship_input_state |= SPECIAL;
				}
			}
		}
		if (ai->batt <= SPECIAL_ENERGY_COST << 1)
			ai->ship_input_state &= ~WEAPON;
}
Esempio n. 17
0
void shuffle_vector( std::vector<double> &vec )
{
  int len = (int)vec.size();
  int v1, v2;
  double elem;
  CRandomMother ran( rand()%1000 );

  for(int i=0; i<10*len; i++)
  {
    v1 = vec[ran.IRandom(0, len-1)];
    v2 = vec[ran.IRandom(0, len-1)];
    elem = vec[v1];
    vec[v1] = vec[v2];
    vec[v2] = elem;
  }
}
Esempio n. 18
0
/* Set forest cell to Tree or NoTree, depending on whether a randomly
 * generated integer equals or exceeds the density probability.
 */
int plant_forest( char forest[ ][ Side ], float density )
{
    int i, j;
    int val;
    int count = 0;
    for ( i = 0; i < Side; i++ )
        for ( j = 0; j < Side; j++ ) {
            val = ran( 100 );
            if ( val > density )
                forest[ i ][ j ] = NoTree;
            else {
                forest[ i ][ j ] = Tree;
                count++;
            }
        }
    return count;  /* count of trees in forest */
}
Esempio n. 19
0
/* Genera un conjunto de entrenamiento a partir de los datos de y,
 * que contiene 'p' datos de tipo t_sample (ie: pares (input,output))
 *
 * Los inputs de cada t_sample son vectores de 'n' datos tomados de 'y'
 * Si el primer elemento de uno de estos inputs es y[i], entonces el siguiente
 * será y[i+jump] y así sucesivamente.
 * Es decir que los datos son tomados de 'y' mediante saltos de longitud 'jump'
 *
 * El output es el dato "siguiente" al del último valor de input,
 * donde "siguiente" también implica un salto de longitud 'jump'
 *
 * Ej: p = 1, n = 2 , jump = 4 , y = [0,5,10,15,20,25,30,35,40,45]
 *
 *     Entonces la muestra generada será: { ((0,20) , 40) }
 */
static void
sample_gen (t_sample *s, size_t n, size_t p, size_t jump, double *y)
{
	long i = 0, j = 0, k = 0;
	long *loi = NULL;	/* Lista de índices para acceder 
				 * aleatoriamente a los valores de y */
	
	assert (s != NULL);
	
	/* Primero creamos la lista de índices aleatorios */
	loi = (long *) malloc (p * sizeof (long));
	assert (loi != NULL);
	#pragma omp parallel for if(p>200)
	for (k=0 ; k < p ; k++) {
		loi[k] = k;
	}
	k = p-1;
	while (k-- > 0) {
		i = floor (ran()*p);
		loi[k] += loi[i];
		loi[i]  = loi[k] - loi[i];
		loi[k] -= loi[i];
	}
	
	/* Ahora escogemos aleatoriamente las 'p' muestras */
	#pragma omp parallel for default(shared) private(i,j)
	for (k=0 ; k < p ; k++) {
		i = loi[k];
		for (j=0 ; j < n ; j++) {
			/* Presentación secuencial de ejemplos: */
			gsl_vector_set (s[k].in, j, y[k+j*jump]);
			/* Presentación aleatoria de ejemplos: */
/*			gsl_vector_set (s[k].in, j, y[i+j*jump]);
*/		}
		s[i].out = y[i+n*jump];
	}
	
	free (loi);
	loi = NULL;
	
	return;
}
int main(){

  FILE *fp;
  int i,j,k,m,n,g,h,pick,tempm,tempn;
  int a[NODE][EDGE];
  int a1[NODE][EDGE];
  int length[NODE];
  int length1[NODE];
  int Edges[20000][2];
  int node = 200;
  int index;
  int edge;
  int min=10000;
  long totaledge;
  char temp[500];
  
  int flag;
  char * pch;


    srand((unsigned)time(NULL));
    for(i=0;i<NODE;i++){
      for(j=0;j<EDGE;j++){
	a1[i][j] = NODE+1;
      }
      length1[i] = 0;
    }
    do{
    fp = fopen("data","r");
    }while(fp == NULL);
    
    i = 0;
    while(fgets(temp,500,fp)){
      if(temp[0] < '0' || temp[0] > '9') break;
      j = 0;
      index = 0;
      while(temp[index] != '\r'){
	if(temp[index] != '\t'){
	  a1[i][j] = atoi(temp+index);
	  if(a1[i][j] < 10) index++;
	  else if(a1[i][j] < 100) index+=2;
	  else index+=3;
	  j++;
	}
	else
	  {
	    index++;
	  }
      }
      length1[i] = j-1;
      i++;
    }

  
  for(k=0;k<loop;k++){
    i = rand();
    i = I_ran4(i);
    for(i=0;i<NODE;i++){
      for(j=0;j<EDGE;j++){
	a[i][j] = a1[i][j];
      }
      length[i] = length1[i];
    }

/*     for(i=0;i<NODE;i++){ */
/*       for(j=0;j<=length[i];j++){ */
/* 	printf("%d\t",a[i][j]); */
/*       } */
/*       printf("\r\n"); */
/*     } */
    
    for(node=NODE;node>2;node--){
      totaledge = 0;
      for(i=0;i<node;i++){
	for(j=1;j<=length[i];j++){
	  Edges[totaledge][0] = a[i][0];
	  Edges[totaledge][1] = a[i][j];
	  totaledge++;
	}
      }
      pick = (int)(ran()*totaledge);
      tempm = Edges[pick][0];
      tempn = Edges[pick][1];
      for(i=0;i<node;i++){
	if(a[i][0] == tempm) m = i;
	if(a[i][0] == tempn) n = i;
      }
      for(j=1;j<=length[m];j++){
	if(a[m][j] == a[n][0]){
	  a[m][j] = a[m][length[m]];
	  length[m]--;
	  j--;
	}
      }
      for(j=1;j<=length[n];j++){
	if(a[n][j] == a[m][0]){
	  a[n][j] = a[n][length[n]];
	  length[n]--;
	  j--;
	}
      }

      if(m<n)
	{
	  for(g=0;g<node;g++){
	    for(h=1;h<=length[g];h++){
	      if(a[g][h] == a[n][0]) a[g][h] = a[m][0];
	    }
	  }
	  for(j=1;j<=length[n];j++){
	    a[m][length[m]+j] = a[n][j];
	  }
	  length[m] += length[n];
	  for(j=0;j<=length[node-1];j++){
	    a[n][j]=a[node-1][j];
	  }
	  length[n] = length[node-1];	  
	}
      else{
	for(g=0;g<node;g++){
	  for(h=1;h<=length[g];h++){
	    if(a[g][h] == a[m][0]) a[g][h] = a[n][0];
	  }
	}
	for(j=1;j<=length[m];j++){
	  a[n][length[n]+j] = a[m][j];
	}
	length[n] += length[m];
	for(j=0;j<=length[node-1];j++){
	  a[m][j]=a[node-1][j];
	}
	length[m] = length[node-1];
      }
    }
    if(node != 2)
      {
	printf("Error!");
	exit(0);
      }    
    edge = (length[0] + length[1])/2;
    if(edge<min) min=edge;
  }
  printf("The mini cut is: %d\n",min);
}
Esempio n. 21
0
	Node *M(Node *p, Node *q) {
		return (!p||!q)?(p?p:q):(p->k>q->k?M(q,p):((ran()?p->l=M(p->l,q):p->r=M(p->r,q)),p));
	};
Esempio n. 22
0
int main()
{
	int idx, idx2;
	int cnt[10] = {100, 100, 100, 100, 100, 100, 100, 100, 100, 100};

	srandom(time(NULL));

	/* reset counter */

	TotalAlloc		= 0;
	TotalFree		= 0;
	NullAlloc			= 0;
	NullFree			= 0;
	TotalAllocSize	= 0;

	TITLE(Test Start);

	for (idx = 0 ; idx < DESTROY_COUNT ; idx ++)
	{
		int i;

		/* Init mm spool */
		for (i = 0 ; i < 10 ; i ++)
			cnt [i] = (random() % 100);

		/* Init */
		upnp_mm_init(cnt);

		SUBSUBTITLE(Start Round......);

		/* Dump */
		upnp_mm_dump();


		for (idx2 = 0 ; idx2 < REINIT_COUNT ; idx2 ++)
		{
			int i;

			SUBSUBTITLE(Reinit mm system......);
			
			bzero(my_alloc, (sizeof(void *) * MAX_ALLOC));

			for (i = 0 ; i < MAX_TEST_COUNT ; i ++)
			{
				allo();
				callo();
				reallo();
				sdup();
				hybrid();
				ran();
			}
			/* Reinit */
			upnp_mm_reinit();
		}

		SUBSUBTITLE(One Round Complete......);

		/* Dump */
		upnp_mm_dump();

		/* Destroy */
		upnp_mm_destroy();
	}

	/* Dump counter */
	TITLE(Test Complete);
	printf("\tTotalAlloc\t(Total Allocation Count)\t:\t%u\n", TotalAlloc);
	printf("\tTotalFree\t(Total Free Count)\t\t:\t%u\n", TotalFree);

	printf("\tNullAlloc\t(Total Count of out-of-memory)\t:\t%u", NullAlloc);
	if (NullAlloc)
		printf("\t(This COULD cause daemon stop!)\n");
	else
		printf("\n");
	
	printf("\tNullFree\t(Free with the NULL pointer)\t:\t%u\n", NullFree);
	printf("\tTotalAllocSize\t(Total Allocated memory size)\t:\t%u\n", TotalAllocSize);
	printf("\n");
	return 0;
}
Esempio n. 23
0
void calculateNext(hashset *hash, vector*  keys, int k, char* f, int size) {
  int currK, i, elems = 0, seedNumber;
  char *nxt, *cnt, *key2, *storage = (char*)malloc(sizeof(char) * k);
  FILE *fileR;
  vectorv keyNext;
  keysv *rs, key;
  k+=1;
  fileR = fopen(f, "r");
  assert(fileR != NULL && "Cannot open the file");
  VectorNew(keys, sizeof(char*) * k, NULL, 10);
  while (fgets(storage, k, fileR) != NULL) {
    currK = strlen(storage);
    if (currK < k && storage[currK - 1] == '\n') {
      fgets(&storage[currK], k - currK, fileR);
    }
    VectorAppend(keys, storage);
  }
  storage = (char*)VectorNth(keys, keys->currentPosition - 1);
  fclose(fileR);
  HashSetNew(hash, sizeof(keysv), keys->currentPosition * 3, hashVector, cmpVector, NULL);
  for (i = 0; i < (keys->currentPosition - 1); i++) {
    rs = (keysv*)malloc(sizeof(keysv));
    vector nexts;
    cnt = VectorNth(keys, i);
    nxt = VectorNth(keys, i + 1);
    rs->string = strdup(cnt);
    rs = (keysv*)HashSetLookup(hash, rs);
    keyNext.string = nxt;
    key.string = cnt;
    if (rs == NULL) {
      keyNext.frecuency = 1;
      VectorNew(&nexts, sizeof(vectorv), NULL, 1);
      VectorAppend(&nexts, &keyNext);
      key.frecuency = 1;
      key.vectorv = nexts;
      key.amount = 1;
      HashSetEnter(hash, &key);
    } else {
      rs->frecuency++;
      rs->amount++;
      vectorv* rSucessor;
      int idx = VectorSearch(&rs->vectorv, &keyNext, cmpvct, 0, false);
      if (idx >= 0) {
        rSucessor = VectorNth(&rs->vectorv, idx);
        rSucessor->frecuency++;
      } else {
        keyNext.frecuency = 1;
        VectorAppend(&rs->vectorv, &keyNext);
      }
    }
  }
  key.string = VectorNth(keys, keys->currentPosition - 1);
  key.frecuency = 1;
  key.amount = 0;
  HashSetEnter(hash, &key);
  if (k == 0) {
    elems = keys->currentPosition;
  } else {
    HashSetMap(hash, mapFn, &elems);
  }
  seedNumber = rand() % elems;
  key2 = (char*)VectorNth(keys, seedNumber);
  printf("Generated text:\n");
  printf("%s", key2);
  if (k > 0) {
    for (i = 0; i < size;) {
      key2 = ran(hash, keys, key2);
      printf("%s", key2);
      if (strstr(key2, " ") != NULL || strstr(key2, "\n") != NULL) {
        i++;
      }
    }
  }
  else {
    for (i = 0; i < size;) {
      seedNumber = rand() % elems;
      key2 = (char*)VectorNth(keys, seedNumber);
      printf("%s", key2);
      if (strstr(key2, " ") != NULL || strstr(key2, "\n") != NULL) {
        i++;
      }
    }
  }
  printf("\n");
}
Esempio n. 24
0

void add_noise_at_node(node *n)
BEGIN
	float r;

/* should be giving the same noise as I had in 2D Micrasterias programs:
    uniform deviations up to 1 Poisson s.d. No larger magnitude noise
    allowed. */


	IF ((n->X < 0.15) || (n->Y < 0.15)) THEN
		return;
		FI

	r = ran();
	r = 1.0 - 2.0*r;
	r /= sqrt(10000*n->X);

	n->X += r;
        if(n->X < 0.0 || n->X > 100)
        {
      /*                printf("addnoise,X is %f, id is %d\n",n->X,n->id);*/
	        user_stops_exe = TRUE;
                exestopmsg = "X negative or too large";
		return;
		/*                n->Y = 0.0; */
	}

        if((n->X <= Xth) && (iterations > growth_onset)) n->conc_fixed = TRUE; 
 
Esempio n. 25
0
void makeSpecial(int distPlotFlag) {
	int p,g,iatom,atomCount = 0,amorphAtoms;
	double d,r,x,y,z,dist,volume;
	int i,j,Znum,count;
	long seed;
	float pos[3],center[3],grainBound[6];
	int trials = 0,type;
	char *ptr;

	seed = -(long)(time(NULL));  // initialize random number generator.

	for (g=0;g<nGrains;g++) {
		/********************************************************
		* if this grain is a special one ... 
		*/
		if (grains[g].amorphFlag == SPECIAL_GRAIN) {
			//  type = atoi(grains[g].name);
			ptr = grains[g].name;
			while (*ptr != ' ') ptr++;
			type = atoi(ptr+1);
			*ptr = 0;
			// printf("Distribution type: %d \n",type);
			printf("%s: distribution type: %d (%s)\n",grains[g].name,type,
				(type == 2) ? "double gaussian" : (type == 1 ? "single gaussian" : "random"));
			/**************************************************************
			* We would like to calculate the Volume of this grain.  
			* We do this by brute force, by simply checking, if randomly
			* distributed points are within the grain, or not.
			*************************************************************/
			grainBound[0] = superCell.ax;  grainBound[1] = 0;
			grainBound[2] = superCell.by;  grainBound[3] = 0;
			grainBound[4] = superCell.cz;  grainBound[5] = 0;
			for (count=0, i=0; i<TRIAL_COUNT;i++) {
				// remember that we have to create a vector with
				// z,y,x, because that is the way the atom struct is 
				pos[2] = superCell.ax*ran(&seed);
				pos[1] = superCell.by*ran(&seed);
				pos[0] = superCell.cz*ran(&seed);
				for (p=0;p<grains[g].nplanes;p++) {
					d = findLambda(grains[g].planes+p,pos,-1);
					if (d < 0) break;
				}
				// if all the previous tests have been successful, this atom is IN 
				if (p == grains[g].nplanes) {
					count++;
					// center of this grain
					center[0] += pos[2]; center[1] += pos[1]; center[2] += pos[0]; 
					// boundaries in X-direction of this grain
					if (grainBound[0] > pos[2]) grainBound[0] = pos[2]; // xmin
					if (grainBound[1] < pos[2]) grainBound[1] = pos[2]; // xmax
					if (grainBound[2] > pos[1]) grainBound[2] = pos[1]; // ymin
					if (grainBound[3] < pos[1]) grainBound[3] = pos[1]; // ymax
					if (grainBound[4] > pos[0]) grainBound[4] = pos[0]; // zmin
					if (grainBound[5] < pos[0]) grainBound[5] = pos[0]; // zmax
				}
			}
			center[0] /= (double)count;
			center[1] /= (double)count;
			center[2] /= (double)count;
			volume = superCell.ax*superCell.by*superCell.cz*(double)count/(double)TRIAL_COUNT;
			printf("Volume: %gA^3, %g %%\n",volume,(double)(100*count)/(double)TRIAL_COUNT);
			printf("boundaries: x: %g..%g, y: %g..%g, z: %g..%g\n",
				grainBound[0],grainBound[1],grainBound[2], 
				grainBound[3],grainBound[4],grainBound[5]); 

			// First we need to find out how much memory we need to reserve for this grain
			amorphAtoms = 0;
			for (iatom=0;iatom<grains[g].natoms;iatom++) {
				if (grains[g].unitCell[iatom].y < 1.0) {  // if this is a concentration, and no count
					grains[g].unitCell[iatom].y *= volume;  // then convert it to number of atoms
				}
				amorphAtoms += (int)(grains[g].unitCell[iatom].y);
			}

			superCell.atoms = (atom *)realloc(superCell.atoms,(amorphAtoms+superCell.natoms+1)*
				sizeof(atom));
			if (superCell.atoms == NULL) {
				printf("makeAmorphous: Could not allocate memory for additional atoms!\n");
				exit(0);
			}
			atomCount = superCell.natoms;  // start adding amorphous atoms, where we left off.

			// Now we can loop through and add these atoms randomly to the grain
			for (iatom=0;iatom<grains[g].natoms;iatom++) {
				r = grains[g].unitCell[iatom].z;             // radius of this atom
				count = (int)(grains[g].unitCell[iatom].y);  // number of atoms of this kind
				Znum = grains[g].unitCell[iatom].Znum;
				covRad[Znum-1] = r;                          // set radius of other atoms also
				for (j=0;j<count;j++) {
					do { // make it lie within the grain bounding planes
						do { // make the atoms not touch eachother
							// z = superCell.cz*ran(&seed);
							// y = superCell.by*ran(&seed);
							z = grainBound[4]+ran(&seed)*(grainBound[5]-grainBound[4]);	    
							y = grainBound[2]+ran(&seed)*(grainBound[3]-grainBound[2]);	    
							if (fabs(superCell.cz-z) < 2e-5) z = 0.0;
							if (fabs(superCell.by-y) < 2e-5) y = 0.0;
							if (iatom > 0) {
								x = grainBound[0]+ran(&seed)*(grainBound[1]-grainBound[0]);	    
							}
							else {
								switch (type) {
		case 0:
			x = grainBound[0]+ran(&seed)*(grainBound[1]-grainBound[0]);	    
			break;
		case 1:
			x = xDistrFun1(center[0],0.08*(grainBound[1]-grainBound[0]));	    
			break;
		case 2:
			x = xDistrFun2(center[0],0.80*(grainBound[1]-grainBound[0]),
				0.08*(grainBound[1]-grainBound[0]));
			break;
		default:
			x = grainBound[0]+ran(&seed)*(grainBound[1]-grainBound[0]);	    
								}
							}
							if (fabs(superCell.ax-x) < 2e-5) x = 0.0;
							// Now we must check, whether atoms overlap
							for (i=0;i<atomCount;i++) {
								for (p=-1;p<=1;p++) {
									dist = sqrt(SQR(x-superCell.atoms[i].x)+
										SQR(y-superCell.atoms[i].y+p*superCell.by)+
										SQR(z-superCell.atoms[i].z));		  
									if (dist < r+covRad[superCell.atoms[i].Znum-1]) break;		
								}	    
								if (p < 2) break;
							}
							trials++;
							if (trials % amorphAtoms == 0)
								printf("Average trials per atom: %d times, success: %g %%\n",
								trials/amorphAtoms,100.0*(atomCount-superCell.natoms)/
								(double)amorphAtoms);
						} while (i < atomCount);  
						// try until we find one that does not touch any other

						// superCell.atoms[atomCount].dw = 0.0;
						superCell.atoms[atomCount].dw = 0.45*28.0/(double)(2.0*Znum);

						superCell.atoms[atomCount].occ  = 1.0;
						superCell.atoms[atomCount].q    = 0;
						superCell.atoms[atomCount].Znum = Znum;
						superCell.atoms[atomCount].x    = x;
						superCell.atoms[atomCount].y    = y;
						superCell.atoms[atomCount].z    = z;

						for (p=0;p<grains[g].nplanes;p++) {
							d = findLambda(grains[g].planes+p,&(superCell.atoms[atomCount].z),-1);
							if (d < 0) break;
						}
						// if all the previous tests have been successful, this atom is IN 
					} while(p < grains[g].nplanes);
					atomCount++;
				} // for j=0..count
				printf("%d (%d): %d \n",iatom,Znum,count);
			} // for iatom = 0..natoms
			printf("\n%d amorphous atoms, volume: %gA^3 (%g%%), center: %g, width: %g\n",
				atomCount-superCell.natoms,
				volume,100.0*volume/(superCell.ax*superCell.by*superCell.cz),center[0],
				grainBound[1]-grainBound[0]);
			switch (type) {
	  case 2:
		  xDistrFun2(0.0,0.0,0.0);
		  break;
	  case 1:
		  xDistrFun1(0.0,0.0);
		  break;
			}
			superCell.natoms = atomCount;
		} // if special_grain 
	} // g=0..nGrains ..
	/*******************************************************************
	* Now we must produce distribution plots of the different atom kinds
	*/
	if (distPlotFlag) makeDistrPlot(superCell.atoms,superCell.natoms,superCell.ax);
}
Esempio n. 26
0
bool fitSimAnneal::fit() {
    int error=0;
    bool finished=false;
    //double newChi2;
    double T=T0*pow(10.0,floor(log10(chi2(param, fitParamCount))));
    int* dirVariations=(int*)calloc(fitParamCount, sizeof(int));
    double* fast=(double*)calloc(Nepsilon, sizeof(double));
    for (int i=0; i<Nepsilon; i++) {
        fast[i]=currentChi2;
    }
    int k=0;

    std::cout<<"  initial temperature: "<<T<<std::endl;
    do {
        for (unsigned int tempSteps=0; tempSteps<NT; tempSteps++) {
            // clear variations counter
            /*for (unsigned int i=0; i<fitParamCount; i++) {
                dirVariations[i]=0;
            }*/

            for (register unsigned int stepVariations=0; stepVariations<NS; stepVariations++) {
                iterations++;
                for (register unsigned int h=0; h<fitParamCount; h++) {
                    //std::cout<<h<<" ";

                    // x' = x + r*v[h] * eh
                    //     where eh is the unit vector in direction h
                    // for this ensure that a_h <= x'_h <= b_h
                    register double new_xh=0;
                    register double old_xh=x0[h];
                    do {
                        // r=random number from flat distribution between -1..1
                        new_xh=x0[h]+(ran(2.0)-1.0)*v[h];
                    } while (new_xh<lowerBounds[h] || new_xh>upperBounds[h]);
                    x0[h]=new_xh;
                    register double testChi2=chi2(x0, fitParamCount);
                    if (testChi2<currentChi2) {
                        // accept trial step
                        currentChi2=testChi2;
                        dirVariations[h]++;
                        //std::cout<<"      downhill trial accepted: "<<doublevectortostr(x0, fitParamCount)<<" <"<<currentChi2<<">";

                        // save best fits
                        if (currentChi2<bestChi2) {
                            //std::cout<<"   as optimal";
                            memcpy(param, x0, fitParamCount*sizeof(double));
                            bestChi2=testChi2;
                        }
                        //std::cout<<std::endl;
                    } else {
                        // Metropolis-Monte-Carlo step
                        if (ran()<exp((currentChi2-testChi2)/T)) {
                            // accept trial step
                            //memcpy(param, x0, fitParamCount*sizeof(double));
                            currentChi2=testChi2;
                            dirVariations[h]++;
                            //std::cout<<"      metropolis trial accepted: "<<doublevectortostr(x0, fitParamCount)<<" <"<<currentChi2<<">\n";
                        } else {
                            // reset to former value (old_xh)
                            x0[h]=old_xh;
                        }
                    }
                }
            }

            // update the step vector
            //std::cout<<"    NS = "<<NS<<"    dirVariations = (";
            for (register unsigned int h=0; h<fitParamCount; h++) {
                //if (h>0) std::cout<<", ";
                //std::cout<<dirVariations[h];
                if (dirVariations[h]>0.6*(double)NS) {
                    v[h]=v[h]*(1.0+c*(dirVariations[h]/(double)NS-0.6)/0.4);
                    if (v[h]>fabs(upperBounds[h]-lowerBounds[h])/2.0) v[h]=fabs(upperBounds[h]-lowerBounds[h])/2.0;
                } else if (dirVariations[h]<0.4*(double)NS) {
                    v[h]=v[h]/(1.0+c*(0.4-dirVariations[h]/(double)NS)/0.4);
                    if (v[h]>fabs(upperBounds[h]-lowerBounds[h])/2.0) v[h]=fabs(upperBounds[h]-lowerBounds[h])/2.0;
                }
                dirVariations[h]=0;

            }
            //std::cout<<")\n";
            //std::cout<<"    new step vector("<<tempSteps<<"/"<<NT<<"): "<<doublevectortostr(v, fitParamCount)<<std::endl;
        }
        // temperature update
        T=T*rT;
        std::cout<<"  new temperature: "<<T;//<<std::endl;

        // stop criterion
        fast[k]=currentChi2;
        finished=true;
        //std::cout<<"  fmax="<<fmax<<"     ";
        for (unsigned int u=0; (u<Nepsilon) && (finished); u++) {
            finished=finished && (fabs(currentChi2-fast[u])<=fmax);
            //std::cout<<"   |"<<currentChi2<<" - "<<fast[u]<<"|="<<fabs(currentChi2-fast[u]);
        }
        //std::cout<<std::endl;
        /*if (finished) {
            finished=(fast[k]-bestChi2)<=fmax;
        }*/
        k++; if (k>=Nepsilon) k=0;

        memcpy(x0, param, fitParamCount*sizeof(double));
        currentChi2=bestChi2;

        //std::cout<<"  current f*="<<doublevectortostr(fast, Nepsilon)<<std::endl;
        std::cout<<"  bestChi2="<<bestChi2<<"   bestParam="<<doublevectortostr(param, fitParamCount)<<"   iterations="<<iterations<<std::endl;

    } while (!finished && error==0 && iterations<iterationsMax);

    free(dirVariations);
    std::cout<<"best fit: ( ";
    for (int i=0; i<fitParamCount; i++) {
        if (i>0) std::cout<<", ";
        std::cout<<param[i];
    }
    std::cout<<" )\n";

    if (iterations>=iterationsMax) std::cout<<" stopped by maximum iterations.\n";
    if (finished) std::cout<<" stopped by abortion criterion f<sub>max</sub>.\n";

    if (error==-1) std::cout<<"ERROR: Not a Number (NaN) occured during chi2() function evaluation\n";
    if (error==-2) std::cout<<"ERROR: Infinity occured (Inf) during chi2() function evaluation\n";


    return (error==0);
}
Esempio n. 27
0
double perfectMRF2(int *delta,int Q,int G,
		   const vector<vector<int> > &neighbour,
		   const vector<double> &potOn,
		   const vector<double> &potOff,
		   double alpha,double beta,
		   double betag,unsigned int *seed,int draw) {
  unsigned int finalStart = *seed;

  if (draw == 1) {
    vector<int> start(1,-1);
    vector<unsigned int> seeds(1,finalStart);

    unsigned int nextSeed;
    int finished = 0;
    while (finished == 0) {
      vector<int> valueLower(Q * G,0);
      vector<int> valueUpper(Q * G,1);

      int b;
      for (b = start.size() - 1; b >= 0; b--) {
	int first = start[b];
	int last;
	if (b > 0)
	  last = start[b-1];
	else
	  last = 0;

	Random ran(seeds[b]);
	int k;
	for (k = first; k < last; k++) {
	  int q,g;
	  for (q = 0; q < Q; q++)
	    for (g = 0; g < G; g++)
	      updateMRF2perfect(q,g,Q,G,valueLower,valueUpper,potOn,potOff,
				neighbour,alpha,beta,betag,ran);
	}

	unsigned int dummy = 1;
	if (b == start.size() - 1) nextSeed = ran.ChangeSeed(dummy);
      }

      int nUndef = 0;
      int q,g;
      for (q = 0; q < Q; q++)
	for (g = 0; g < G; g++) {
	  int kqg = qg2index(q,g,Q,G);
	  nUndef += (valueLower[kqg] != valueUpper[kqg]);
	}
      //      cout << "nUndef: " << nUndef << endl;

      if (nUndef == 0) {
	finished = 1;
	finalStart = nextSeed;
      }
      else {
	finished = 0;
	seeds.push_back(nextSeed);
	start.push_back(2*start[start.size() - 1]);
      }

      if (finished == 1) {
	for (q = 0; q < Q; q++)
	  for (g = 0; g < G; g++) {
	    int kqg = qg2index(q,g,Q,G);
	    delta[kqg] = valueLower[kqg];
	  }
      }
    }

    *seed = nextSeed;
  }

  double pot = 0.0;
  int q,g;
  for (q = 0; q < Q; q++)
    for (g = 0; g < G; g++) {
      int kqg = qg2index(q,g,Q,G);
      if (delta[kqg] == 1)
	pot += - alpha + potOn[kqg];
      else
	pot += potOff[kqg];

      int k;
      for (k = 0; k < neighbour[g].size(); k++) {
	int gg = neighbour[g][k];
	int kqgg = qg2index(q,gg,Q,G);
	if (delta[kqg] == delta[kqgg]) {
	  int ng = neighbour[g].size();
	  int ngg = neighbour[gg].size();
	  //	  double w = 0.5 * exp(- kappa * log((double) (ng * ngg)));
	  double w = 1.0 / ((double) ng);

	  pot += - beta * w;
	}
      }
    }

  int qq;
  for (q = 0; q < Q; q++)
    for (qq = q + 1; qq < Q; qq++)
      for (g = 0; g < G; g++) {
	int kqg = qg2index(q,g,Q,G);
	int kqqg = qg2index(qq,g,Q,G);
	if (delta[kqg] == delta[kqqg])
	  pot += - betag / ((double) (Q - 1));
      }

  return pot;
}
Esempio n. 28
0
double perfectMRF1_onedelta(int *delta,int G,
			    const vector<vector<int> > &neighbour,
			    const vector<double> &potOn,
			    const vector<double> &potOff,
			    double eta0,double omega0,double kappa,
			    unsigned int *seed,int draw) {
  unsigned int finalStart = *seed;

  if (draw == 1) {
    vector<int> start(1,-1);
    vector<unsigned int> seeds(1,finalStart);

    unsigned int nextSeed;
    int finished = 0;
    while (finished == 0) {
      vector<int> valueLower(G,0);
      vector<int> valueUpper(G,1);

      int b;
      for (b = start.size() - 1; b >= 0; b--) {
	int first = start[b];
	int last;
	if (b > 0)
	  last = start[b-1];
	else
	  last = 0;

	Random ran(seeds[b]);
	int k;
	for (k = first; k < last; k++) {
	  int g;
	  for (g = 0; g < G; g++)
	    updateMRF1perfect_onedelta(g,valueLower,valueUpper,potOn,
				       potOff,neighbour,
				       eta0,omega0,kappa,ran);
	}

	unsigned int dummy = 1;
	if (b == start.size() - 1) nextSeed = ran.ChangeSeed(dummy);
      }

      int nUndef = 0;
      int g;
      for (g = 0; g < G; g++)
	nUndef += (valueLower[g] != valueUpper[g]);
      //      cout << "nUndef: " << nUndef << endl;

      if (nUndef == 0) {
	finished = 1;
	finalStart = nextSeed;
      }
      else {
	finished = 0;
	seeds.push_back(nextSeed);
	start.push_back(2*start[start.size() - 1]);
      }

      if (finished == 1) {
	for (g = 0; g < G; g++)
	  delta[g] = valueLower[g];
      }
    }

    *seed = nextSeed;
  }

  double pot = 0.0;
  int g;
  for (g = 0; g < G; g++) {
    if (delta[g] == 1)
      pot += potOn[g];
    else
      pot += potOff[g];

    int n = neighbour[g].size();
    double omega;
    if (n > 0)
      omega = omega0 * ((double) n) / (kappa + ((double) n));
    else
      omega = 0.0;
    int nOn = 0;
    int gg;
    for (gg = 0; gg < neighbour[g].size(); gg++)
      nOn += delta[neighbour[g][gg]];
    double fraction = ((double) nOn) / ((double) neighbour[g].size());
    double eta;
    if (omega > 0)
      eta = (1.0 - omega) * eta0 + omega * fraction;
    else
      eta = eta0;

    if (delta[g] == 1)
      pot += - log(eta);
    else
      pot += - log(1.0 - eta);
  }

  return pot;
}
Esempio n. 29
0
int set() {
	int ingresando=1, temp_int, carga_ocupada=0;
	double current=0, termino, toneladas=0,temp_tiempo,temp_double,media_pala,media_camion, media_repcamion;
	long idum = -275920;
	pcamion listainicio=NULL,listacargado=NULL,listadescarga=NULL,listamotor=NULL,listainterferencia=NULL,listatrayecto=NULL, listacarga=NULL, listapala=NULL, temp=NULL, listatermino=NULL, aux=NULL;
	var_grales parametros=crea_var();		//crea e inicializa parametros para utilizacion en generacion de reporte

	printf("Simulador de camiones autonomos!\n");
	printf("Ingrese semilla distinta de 0 para el generador de numeros aleatorios:\n");
	scanf("%d",&idum);
	parametros->idum = idum;
	printf("Ingrese media de tiempo entre fallas de los camiones [Default: 1472[min]]\n");
	scanf("%lf",&media_camion);
	parametros->media_camion = (double)media_camion;
	printf("Ingrese media de tiempo de reparacion de camion [Default: 360[min]]\n");
	scanf("%lf",&media_repcamion);
	parametros->media_repcamion = (double)media_repcamion;
	printf("Ingrese media de tiempo de reparacion de palas [Default: 105[min]]\n");
	scanf("%lf",&media_pala);	
	parametros->media_pala =  (double)media_pala;
	printf("Ingrese tiempo de simulacion [Minutos]\n");
	scanf("%lf",&termino);
	parametros->termino = (double)termino;
	listatermino=insertarenorden(listatermino,creacamion(314159,termino,0,NULL,0));
	
	while(ingresando==1){
		printf("\nIngrese id del camion a insertar\n");
		scanf("%d",&temp_int);
		printf("\nIngrese tiempo de partida del camion\n");
		scanf("%lf",&temp_tiempo);
		listainicio=insertarenorden(listainicio,creacamion(temp_int,temp_tiempo,termino,&idum,media_repcamion));
		parametros->cam += 1;
		printf("\nInsertar otro camion? (1=si, 2=no)\n");
		scanf("%d",&ingresando);
		}
	

	while(current<termino){
		if(carga_ocupada)temp=seleccionarminimo(listainicio,listacargado,listadescarga,listatrayecto,listamotor,listainterferencia,NULL,listapala,listatermino);
		else temp=seleccionarminimo(listainicio,listacargado,listadescarga,listatrayecto,listamotor,listainterferencia,listacarga,NULL,listatermino);
		current+=(temp->tiempo-current);

		if(temp==listainicio){  temp->direccion=1;
					temp->senal=1;
					temp->motor=1;          //Variables de estado
					temp->velocidad=1;
					temp->carga=0;			
					printf("Camion %d parte hacia faena en t=%e\n",temp->id,temp->tiempo);
					
					while(current>temp->falla->tiempo)temp->falla=temp->falla->next;
					
					if(temp->tiempo+10>temp->falla->tiempo){
							temp->tiempo+=((temp->falla->tiempo)-current);
							temp->tiempo_funcionamiento+=((temp->falla->tiempo)-current);
							temp->tiempo_trayecto=((temp->falla->tiempo)-current);            

							printf("Camion %d sufre falla motor en t=%e\n",temp->id,temp->tiempo);
							listainicio=eliminarcamion(listainicio);
							temp->next=NULL;
							temp->motor=0;
							temp->velocidad=0;
							listamotor=insertarenorden(listamotor,temp);
							continue;
							}
									  
					/*if(temp_int<40){
							printf("Camion  %d sufre interferencia en t=%e\n",temp->id,temp->tiempo);
							temp->tiempo+=5;
							listainicio=eliminarcamion(listainicio);
							temp->next=NULL;
							temp->senal=0;
							temp->velocidad=0;
							listainterferencia=insertarenorden(listainterferencia,temp);
							continue;
							}*/
				  
					temp->tiempo+=10;
					temp->tiempo_funcionamiento+=10;
					printf("Llega camion %d a cola de carga en t=%e\n",temp->id,temp->tiempo);
					listainicio=eliminarcamion(listainicio);
					temp->next=NULL;
					temp->velocidad=0;
					listacarga=insertarenorden(listacarga,temp);
					continue;
					}
		

		if(temp==listamotor){
					temp->tiempo+=(-media_repcamion*log(ran(&idum)));//tiempo de reparacion (variable)
					temp->tiempo_funcionamiento += (temp->tiempo - temp->tiempo_funcionamiento);
					printf("Camion %d es reparado en t=%e\n",temp->id,temp->tiempo);
					listamotor=eliminarcamion(listamotor);
					temp->next=NULL;
					temp->motor=1;
					temp->velocidad=1;
					listatrayecto=insertarenorden(listatrayecto,temp);
					continue;
					}

		if(temp==listainterferencia){
					printf("Camion %d deja de sufrir interferencia en t=%e\n",temp->id,temp->tiempo);
					temp->tiempo+=5;
					temp->tiempo_funcionamiento+=5;
					listainterferencia=eliminarcamion(listainterferencia);
					temp->next=NULL;
					temp->senal=1;
					temp->velocidad=1;
					listatrayecto=insertarenorden(listatrayecto,temp);
					continue;
					}

		if(temp==listatrayecto){ 
					while(current>temp->falla->tiempo)temp->falla=temp->falla->next;
			
					if(temp->tiempo+(10-temp->tiempo_trayecto)>temp->falla->tiempo){
							temp->tiempo_trayecto+=((temp->falla->tiempo)-current); 
							temp->tiempo+=((temp->falla->tiempo)-current);
							temp->tiempo_funcionamiento+=((temp->falla->tiempo)-current);

							printf("Camion  %d sufre falla motor en t=%e\n",temp->id,temp->tiempo);
							listatrayecto=eliminarcamion(listatrayecto);
							temp->next=NULL;
							temp->motor=0;
							temp->velocidad=0;
							listamotor=insertarenorden(listamotor,temp);
							continue;
							}
					/*  
					if(temp_int<40){
							printf("Camion  %d sufre interferencia en t=%e\n",temp->id,temp->tiempo);
							temp->tiempo+=5;
							listatrayecto=eliminarcamion(listatrayecto);
							temp->next=NULL;
							temp->senal=0;
							temp->velocidad=0;
							listainterferencia=insertarenorden(listainterferencia,temp);
							continue;
							}	*/			  
					if(temp->direccion==1){	
							temp->tiempo+=(10-temp->tiempo_trayecto);
							temp->tiempo_funcionamiento+=(10-temp->tiempo_trayecto);
							printf("Llega camion %d a cola de carga en t=%e\n",temp->id,temp->tiempo);
							listatrayecto=eliminarcamion(listatrayecto);
							temp->next=NULL;
							temp->velocidad=0;
							listacarga=insertarenorden(listacarga,temp);
							continue;
							}
					if(temp->direccion==0){
							temp->tiempo+=(10-temp->tiempo_trayecto);
							temp->tiempo_funcionamiento+=(10-temp->tiempo_trayecto);
							printf("Llega camion %d a descarga en t=%e\n",temp->id,temp->tiempo);
							listatrayecto=eliminarcamion(listatrayecto);
							temp->next=NULL;
							temp->velocidad=0;
							listadescarga=insertarenorden(listadescarga,temp);
							continue;
							}
					}

		if(temp==listacarga){	
					temp_double=ran(&idum);
					carga_ocupada=1;
					temp->carga=2;
					temp->tiempo_trayecto=0;			//resetea valor de tiempo de trayecto
				    	
					printf("Camion %d se empieza a cargar en t=%e\n",temp->id,temp->tiempo);

					if(temp_double<0.40625){ 
							printf("Falla de pala mientras se carga camion  %d\n",temp->id);

							temp->tiempo+=(-media_pala* log(ran(&idum)));
							temp->tiempo_funcionamiento += (temp->tiempo - temp->tiempo_funcionamiento);
							listacarga=eliminarcamion(listacarga);
							temp->next=NULL;
							listapala=insertarenorden(listapala,temp);
							continue;
							}
						
					else  {	
						printf("Camion %d se esta cargando sin problemas en t=%e\n",temp->id,temp->tiempo);
						temp->tiempo+=10;
						temp->tiempo_funcionamiento+=10;
						listacarga=eliminarcamion(listacarga);
						temp->next=NULL;
						listacargado=insertarenorden(listacargado,temp);
						continue;
						}
				}

		if(temp==listapala){ 
					printf("Pala es arreglada en t= %e\n",temp->tiempo);
					temp->tiempo+=0.5;
					temp->tiempo_funcionamiento += 0.5;
					listapala=eliminarcamion(listapala);
					temp->next=NULL;
					listacarga=insertaralinicio(listacarga,temp);
					carga_ocupada=0;
			}

		if(temp==listacargado){ 
					temp->direccion=0;
					temp->carga=1;
					temp->velocidad=1;
					temp_double=ran(&idum);
					carga_ocupada=0;			
					if(listacarga!=NULL){	listacarga->tiempo=temp->tiempo+0.5;
								listacarga->tiempo_funcionamiento+=0.5;
								}
					printf("Camion  %d se ha terminado de cargar, vuelve a planta en t=%e\n",temp->id,temp->tiempo);
							
			
					while(current>temp->falla->tiempo)temp->falla=temp->falla->next;
					
					if(temp->tiempo+10>temp->falla->tiempo){
							temp->tiempo_trayecto=((temp->falla->tiempo)-current);
							temp->tiempo+=((temp->falla->tiempo)-current);
							temp->tiempo_funcionamiento+=((temp->falla->tiempo)-current);

							printf("Camion  %d sufre falla motor en t=%e\n",temp->id,temp->tiempo);
							//temp->tiempo+=5;
							listacargado=eliminarcamion(listacargado);
							temp->next=NULL;
							temp->motor=0;
							temp->velocidad=0;
							temp->tiempo_trayecto=0;
							listamotor=insertarenorden(listamotor,temp);
							continue;
							}
					/*				  
					if(temp_int<40){
							printf("Camion  %d sufre interferencia en t=%e\n",temp->id,temp->tiempo);
							temp->tiempo+=5;
							listacargado=eliminarcamion(listacargado);
					
					temp->next=NULL;
							temp->senal=0;
							temp->velocidad=0;
							listainterferencia=insertarenorden(listainterferencia,temp);
							continue;
							}*/
				  
					temp->tiempo+=10;
					temp->tiempo_funcionamiento+=10;
					listacargado=eliminarcamion(listacargado);
					temp->next=NULL;
					listadescarga=insertarenorden(listadescarga,temp);
					continue;
					}
			
		if(temp==listadescarga){
					printf("Camion %d descarga en t=%e\n",temp->id,temp->tiempo);
					temp->tiempo+=10;
					temp->tiempo_funcionamiento+=10;
					temp->toneladas_camion+=5;
					listadescarga=eliminarcamion(listadescarga);
					temp->next=NULL;
					temp->carga=3; 
					listainicio=insertarenorden(listainicio,temp);
					toneladas+=5;
					continue;
					}
		
		if(temp==listatermino){
					printf("Tiempo limite de simulacion alcanzado.(t=%e)\n",temp->tiempo);
					if(listainicio!=NULL) aux = insertarenorden(aux,listainicio);
					if(listacargado!=NULL) aux = insertarenorden(aux,listacargado);
					if(listadescarga!=NULL)  aux = insertarenorden(aux,listadescarga);
					if(listatrayecto!=NULL)  aux = insertarenorden(aux,listatrayecto);
					if(listamotor!=NULL)  aux = insertarenorden(aux,listamotor);
					if(listainterferencia!=NULL) aux = insertarenorden(aux,listainterferencia);
					if(listacarga!=NULL) aux = insertarenorden(aux,listacarga);
					if(listapala!=NULL) aux = insertarenorden(aux,listapala);
					if(listatermino!=NULL) aux = insertarenorden(aux,listatermino);
					
					continue;
					}
		}
	printf("Se extrajeron %e toneladas en %e minutos\n",toneladas, termino);
	printf("El rendimiento final es: %e [Ton/Hora]\n",toneladas/(current/60));
	parametros->toneladas = toneladas;
	parametros->current = current;

	reporte_gral(parametros);
	printf("\nReporte generado (Informe.txt).\nSimulacion finalizada\n");
	estadisticas_camion(aux);

	return 0;
}
Esempio n. 30
0
int main (int argc, char** argv) {

    // aim for a nonzero density given by sparsity:
    sparsity = 0.2; // nz = sparsity*100% of the size of the matrix

    /*
     * we say 'aim' here, since of course initially exactly
     *    nz = sparsity * N^2
     * nonzeroes will be generated at random spots, but because
     * the matrix must be symmetric and diagonally positive, the
     * actual number of nonzeroes will probably not be exactly
     * the projected number.
     */

    // read the desired size of the matrix from command line
    if (argc < 2) {
        printf("Usage: %s N [mu] [sparsity]\n", argv[0]);
        exit(-1);
    }

    if(sscanf(argv[1], "%d", &N) != 1) {
        printf("couldn't read command-line argument for N. must be an integer.\n");
        exit(-2);
    }
    double mu;
    mu = 2.5; //default scalar for making matrix diagonal-dominant

    // maybe the user supplied a different mu
    if(argc > 2 && sscanf(argv[2], "%lf", &mu) != 1) {
        exit(-2);
    }
    // maybe the user supplied a different sparsity
    if(argc > 3 && sscanf(argv[3], "%lf", &sparsity) != 1) {
        exit(-2);
    }

    int nz = sparsity*N*N;
    int* xs;
    int* ys;
    double* vals;

    fprintf(stderr,"Generating matrix. N=%d, density=%lf, target nz=%d, ",
            N, sparsity, nz);
    fprintf(stderr, "mu = %lf\n", mu);

    // seed the random generator.
    srandom((unsigned)time(NULL));

    xs = vecalloci(nz);
    ys = vecalloci(nz);
    vals = vecallocd(nz);

    bool* diag_done;
    diag_done = malloc(N*sizeof(bool));

    int i;
    for(i = 0; i<N; i++) {
        diag_done[i] = false;
    }

    int nz_generated;

    int x,y;
    nz_generated = 0;
    double fake_transpose;
    x=0;y=0;
    while(x<N && y<N) { //don't escape matrix bounds.

        if (nz_generated % 1000000 == 0) {
            fprintf(stderr,"progress: %f%%\r", (double)nz_generated/(double)(nz/2.0)*100.0);
        }
        if(x==y) {
            //diagonal, so always generate.

            xs[nz_generated]=x;
            ys[nz_generated]=y;
            vals[nz_generated]=ran()*2.0-1.0;
            diag_done[x] = true;

#ifdef DEBUG
            fprintf(stderr,"generated A[//][%d]=%lf\n"
                                                      , ys[nz_generated]
                                                      , vals[nz_generated]);
#endif

            nz_generated++;

        } else {
            // not a diagonal. only add if in
            // lower triangular half
            if(x<y) {

                if(nz_generated > nz) {
                    // this should NEVER happen, although all that's
                    // stopping it from happening is our ran() being
                    // well-behaved...........
                    printf("EEK! something went wrong!!\n");
                    exit(666);
                }

                xs[nz_generated]= x;
                ys[nz_generated]= y;
                // simulate the distribution of values which
                // would occur if we do A+A^T afterwards.
                if (ran() < sparsity) {
                    fake_transpose    = ran()*2.0-1.0;
                    vals[nz_generated]= ran()*2.0-1.0 + fake_transpose;
                } else {
                    vals[nz_generated]= ran()*2.0-1.0;
                }
#ifdef DEBUG
            fprintf(stderr,"generated A[%d][%d]=%lf\n", xs[nz_generated]
                                                      , ys[nz_generated]
                                                      , vals[nz_generated]);
#endif
                nz_generated++;


            }
        }
        x += 1/sparsity * (ran() + 0.5);
        if( x >= N ) {
            y += x/N;
            x  = x%N;
        }

    }

    fprintf(stderr, "generated initial randoms\n");

    int diagonals_present = 0;
    for(i=0; i<nz_generated; i++) {
        if(xs[i]==ys[i])
            diagonals_present++;
    }

    fprintf(stderr,"generated %d nzeros, array was %d big.\n", nz_generated, nz);


#ifdef DEBUG
    fprintf(stderr, "found %d diagonal(s), still need %d more.\n", diagonals_present, (N-diagonals_present));
#endif

    // add the missing diagonals, and add mu to each diagonal.
    int newsize = nz_generated + (N - diagonals_present);
    fprintf(stderr,"reallocating values array to %lluM \n", (unsigned long long)(SZDBL+2*SZINT)*newsize/1048576);
    int* diag_i;
    int* diag_j;
    double* diag_val;

    diag_i   = realloc(xs  ,SZINT*newsize);
    diag_j   = realloc(ys  ,SZINT*newsize);
    diag_val = realloc(vals,SZDBL*newsize);

    if(diag_i == NULL ||
            diag_j == NULL ||
            diag_val == NULL)
    {
        printf("out of memory!");
        exit(44);
    }

    addDiagonal(mu, diag_i, diag_j, diag_val, nz_generated, newsize, diag_done);
    nz_generated=newsize;
#ifdef DEBUG
    for(i=0;i<newsize;i++) {
        fprintf(stderr,"after addDiagonal A[%d][%d]=%lf\n", diag_i[i],diag_j[i], diag_val[i]);
    }

    fprintf(stderr, "Going to make symmetric now... (nz_generated = %d)\n", nz_generated);
#endif

    // now we explicitly fill the array with the
    // upper triangle values

    // things must be symmetric, but they aren't, yet
    // ... here's a good place to do the transposing thing.

    newsize = nz_generated * 2 - N; //number of real nonzeros, don't
                                    // count diagonals twice.
    int *new_i;
    int *new_j;
    double *new_v;

    new_i = realloc(diag_i  ,SZINT*newsize);
    new_j = realloc(diag_j  ,SZINT*newsize);
    new_v = realloc(diag_val,SZDBL*newsize);

    if(new_i == NULL ||
            new_i == NULL ||
            new_v == NULL)
    {
        printf("out of memory (2)!");
        exit(44);
    }
    diag_i = new_i;
    diag_j = new_j;
    diag_val = new_v;
    addTranspose(newsize,diag_i,diag_j,diag_val,
                              nz_generated);

#ifdef DEBUG
    for(i=0;i<newsize;i++)
        // to make diags stand out.
        if(diag_i[i]==diag_j[i])
            fprintf(stderr,"after transpose A[%d][%d]=%lf \\\\\n", diag_i[i],diag_j[i], diag_val[i]);
        else
            fprintf(stderr,"after transpose A[%d][%d]=%lf\n", diag_i[i],diag_j[i], diag_val[i]);
#endif

    checkStrictDiagonallyDominant(diag_i,diag_j,diag_val, newsize);

    // now quickly generate a test-vector to solve against:

    double *vec = vecallocd(N);
    for(i=0;i<N;i++)
        vec[i]=ran();

    fprintf(stderr,"Left with %d nonzeroes; nonzero density = %lf (desired=%lf)\n", newsize, newsize/((double)N*N), sparsity);
    fprintf(stderr,"========== OUTPUTTING ... ==========\n");

    outputMondriaanMatrix(newsize, diag_i, diag_j, diag_val, vec);
    outputMathematicaMatrix(newsize, diag_i, diag_j, diag_val, vec);

    free(diag_done);
    free(vec);
    free(diag_i);
    free(diag_j);
    free(diag_val);

    return 0;
}