Beispiel #1
0
int
main ()
{
    random_t* random1Ptr;
    random_t* random2Ptr;
    random_t* random3Ptr;
    long i;

    puts("Starting...");

    random1Ptr = random_alloc();
    random2Ptr = random_alloc();
    random3Ptr = random_alloc();

    random_seed(random2Ptr, (RANDOM_DEFAULT_SEED + 1));
    random_seed(random3Ptr, (RANDOM_DEFAULT_SEED + 1));

    for (i = 0; i < NUM_ITERATIONS; i++) {
        unsigned long rand1 = random_generate(random1Ptr);
        unsigned long rand2 = random_generate(random2Ptr);
        unsigned long rand3 = random_generate(random3Ptr);
        printf("i = %2li, rand1 = %12lu, rand2 = %12lu, rand2 = %12lu\n",
                i, rand1, rand2, rand3);
        assert(rand1 != rand2);
        assert(rand2 == rand3);
    }

    random_free(random1Ptr);
    random_free(random2Ptr);

    puts("Done.");

    return 0;
}
Beispiel #2
0
/* =============================================================================
 * queue_shuffle
 * =============================================================================
 */
void
queue_shuffle (queue_t* queuePtr, random_t* randomPtr)
{
    long pop      = queuePtr->pop;
    long push     = queuePtr->push;
    long capacity = queuePtr->capacity;

    long numElement;
    if (pop < push) {
        numElement = push - (pop + 1);
    } else {
        numElement = capacity - (pop - push + 1);
    }

    void** elements = queuePtr->elements;
    long i;
    long base = pop + 1;
    for (i = 0; i < numElement; i++) {
        long r1 = random_generate(randomPtr) % numElement;
        long r2 = random_generate(randomPtr) % numElement;
        long i1 = (base + r1) % capacity;
        long i2 = (base + r2) % capacity;
        void* tmp = elements[i1];
        elements[i1] = elements[i2];
        elements[i2] = tmp;
    }
}
Beispiel #3
0
/* =============================================================================
 * initializeManager
 * =============================================================================
 */
static manager_t*
initializeManager ()
{
    manager_t* managerPtr;
    long i;
    long numRelation;
    random_t* randomPtr;
    long* ids;
    bool_t (*manager_add[])(manager_t*, long, long, long) = {
        &manager_addCar_seq,
        &manager_addFlight_seq,
        &manager_addRoom_seq,
        &addCustomer
    };
    long t;
    long numTable = sizeof(manager_add) / sizeof(manager_add[0]);

    printf("Initializing manager... ");
    fflush(stdout);

    randomPtr = random_alloc();

    managerPtr = manager_alloc();

    numRelation = (long)global_params[PARAM_RELATIONS];
    ids = (long*)malloc(numRelation * sizeof(long));
    for (i = 0; i < numRelation; i++) {
        ids[i] = i + 1;
    }

    for (t = 0; t < numTable; t++) {

        /* Shuffle ids */
        for (i = 0; i < numRelation; i++) {
            long x = random_generate(randomPtr) % numRelation;
            long y = random_generate(randomPtr) % numRelation;
            long tmp = ids[x];
            ids[x] = ids[y];
            ids[y] = tmp;
        }

        /* Populate table */
        for (i = 0; i < numRelation; i++) {
            bool_t status;
            long id = ids[i];
            long num = ((random_generate(randomPtr) % 5) + 1) * 100;
            long price = ((random_generate(randomPtr) % 5) * 10) + 50;
            status = manager_add[t](managerPtr, id, num, price);
        }

    } /* for t */

    puts("done.");
    fflush(stdout);

    random_free(randomPtr);
    free(ids);

    return managerPtr;
}
Beispiel #4
0
void			random_seed(void)
{
  s_clock		clock;
  t_uint64		rounds;
  t_uint64		round;

  assert(clock_current(&clock) == STATUS_OK);

  _library_random_seed = CLOCK_UNIQUE(&clock);

  rounds = random_generate() % 32;

  for (round = 0; round < rounds; round++)
    random_generate();
}
Beispiel #5
0
int fork_func(){
        int     fd[2], nbytes;
        pid_t   childpid;
        int    readbuffer[80];

        pipe(fd);

        if((childpid = fork()) == -1) {
                perror("fork");
                exit(1);
        }

        if(childpid == 0) {
                /* Child process closes up input side of pipe */
                close(fd[0]);
                int result = random_generate((int)time(0));
                /* Send "string" through the output side of pipe */
                write(fd[1], &result, sizeof(result));
                exit(0);
        }
        else {
                /* Parent process closes up output side of pipe */
                close(fd[1]);
                /* Read in a string from the pipe */
                nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
                printf("Received number: %d \n", readbuffer);
                return readbuffer;
        }
}
Beispiel #6
0
/**@brief Generate an appropriate, random Access Address following rules in
 * Link Layer specification Section 2.1.2, Core 4.1 pages 2503-2504
 */
static uint32_t generate_access_address(void)
{
	uint32_t aa = 0;
	do {
		for (int i = 0; i < 4; i++)
			aa |= (random_generate() << (8*i));
	} while (aa == LL_ACCESS_ADDRESS_ADV);
	/* TODO: check for the various other requirements in the spec */

	return aa;
}
Beispiel #7
0
int get_rand_level() {
	int i, level = 1;
	for (i = 0; i < levelmax - 1; i++) {
		if ((random_generate(randomPtr) % 100) < 50)
			level++;
		else
			break;
	}
	/* 1 <= level <= levelmax */
	return level;
}
Beispiel #8
0
int get_random_integer( int min,  int max)
 {/* Init get_random_integer */
 double y;
 int ret;
 
 y = random_generate();
 ret = floor(((y * (max-min+1))));
 return(min+ret);
#ifdef WRONG
  int up = tabc[cl].card - 1;
  return(GET_RANDOM_INTEGER(0,up));
#endif
 }/* End get_random_integer */
Beispiel #9
0
/* =============================================================================
 * net_generateRandomEdges
 * =============================================================================
 */
void
net_generateRandomEdges (net_t* netPtr,
                         long maxNumParent,
                         long percentParent,
                         random_t* randomPtr)
{
    vector_t* nodeVectorPtr = netPtr->nodeVectorPtr;

    long numNode = vector_getSize(nodeVectorPtr);
    bitmap_t* visitedBitmapPtr = bitmap_alloc(numNode);
    assert(visitedBitmapPtr);
    queue_t* workQueuePtr = queue_alloc(-1);

    long n;

    for (n = 0; n < numNode; n++) {
        long p;
        for (p = 0; p < maxNumParent; p++) {
            long value = random_generate(randomPtr) % 100;
            if (value < percentParent) {
                long parent = random_generate(randomPtr) % numNode;
                if ((parent != n) &&
                    !net_hasEdge(netPtr, parent, n) &&
                    !net_isPath(netPtr, n, parent, visitedBitmapPtr, workQueuePtr))
                {
#ifdef TEST_NET
                    printf("node=%li parent=%li\n", n, parent);
#endif
                    insertEdge(netPtr, parent, n);
                }
            }
        }
    }

    assert(!net_isCycle(netPtr));

    bitmap_free(visitedBitmapPtr);
    queue_free(workQueuePtr);
}
Beispiel #10
0
int get_random_object( int cl )
 {/* Init get_random_object */
  double y;
  int ret;
 
  y = random_generate();
  ret = floor(((y * (tabc[cl].card))));
  return(ret);
#ifdef WRONG
  int up = tabc[cl].card - 1;
  return(GET_RANDOM_INTEGER(0,up));
#endif
 }/* End get_random_object */
Beispiel #11
0
int mutation(int n)
{
	int site = random_generate(MAX);
	int i,j;
	int array[MAX];
	
	for(i=0; i<MAX;i++)
	{
		array[i] = n%2;
		n = n/2;
	}
	Flip(array,site);
	return decimal_convert(array);
	cout<<endl;
}
Beispiel #12
0
/* =============================================================================
 * splitIntoPackets
 * -- Packets will be equal-size chunks except for last one, which will have
 *    all extra bytes
 * =============================================================================
 */
static void
splitIntoPackets (char* str,
                  long flowId,
                  random_t* randomPtr,
                  vector_t* allocVectorPtr,
                  queue_t* packetQueuePtr)
{
 
    long numByte = strlen(str);
    long numPacket = random_generate(randomPtr) % numByte + 1;

    long numDataByte = numByte / numPacket;

    long p;
    for (p = 0; p < (numPacket - 1); p++) {
        bool_t status;
        char* bytes = (char*)SEQ_MALLOC(PACKET_HEADER_LENGTH + numDataByte);
        assert(bytes);
        status = vector_pushBack(allocVectorPtr, (void*)bytes);
        assert(status);
        packet_t* packetPtr = (packet_t*)bytes;
        packetPtr->flowId      = flowId;
        packetPtr->fragmentId  = p;
        packetPtr->numFragment = numPacket;
        packetPtr->length      = numDataByte;
        memcpy(packetPtr->data, (str + p * numDataByte), numDataByte);
        status = queue_push(packetQueuePtr, (void*)packetPtr);
        assert(status);
    }

    bool_t status;
    long lastNumDataByte = numDataByte + numByte % numPacket;
    char* bytes = (char*)SEQ_MALLOC(PACKET_HEADER_LENGTH + lastNumDataByte);
    assert(bytes);
    status = vector_pushBack(allocVectorPtr, (void*)bytes);
    assert(status);
    packet_t* packetPtr = (packet_t*)bytes;
    packetPtr->flowId      = flowId;
    packetPtr->fragmentId  = p;
    packetPtr->numFragment = numPacket;
    packetPtr->length      = lastNumDataByte;
    memcpy(packetPtr->data, (str + p * numDataByte), lastNumDataByte);
    status = queue_push(packetQueuePtr, (void*)packetPtr);
    assert(status);
}
Beispiel #13
0
int do_random_gen(cmd_tbl_t * cmdtp, int flag, int argc, char *argv[])
{
	unsigned int seed,len,addr;
	const char *cmd;
	if (argc < 3)
		goto usage;
	cmd = argv[1];
	if((strcmp(cmd,"gen")) && (strcmp(cmd,"read"))){
		goto usage;
	}
	if(!strcmp(cmd,"gen")){
		seed = simple_strtoul(argv[2], NULL, 16);
		len = simple_strtoul(argv[3], NULL, 16);
		if(argc >=5){
			addr = simple_strtoul(argv[4], NULL, 16);
		}
		else{
			addr = 0x82000000;
		}
		//seed += get_ticks();
		if(len == 0){
			len = 1;
		}
		if(random_generate(seed,(unsigned char *)addr,len) < 0){
			printf("%s:%d,random generate fail\n",__func__,__LINE__);
			return 1;
		}
	}
	if(!strcmp(cmd,"read")){
		printf("not support \n");
	}
	return 0;
usage:
	cmd_usage(cmdtp);
	return 1;
}
Beispiel #14
0
/* =============================================================================
 * gene_create
 * -- Populate contents with random gene
 * =============================================================================
 */
void
gene_create (gene_t* genePtr, random_t* randomPtr)
{
    long length;
    char* contents;
    long i;
    const char nucleotides[] = {
        NUCLEOTIDE_ADENINE,
        NUCLEOTIDE_CYTOSINE,
        NUCLEOTIDE_GUANINE,
        NUCLEOTIDE_THYMINE,
    };

    assert(genePtr != NULL);
    assert(randomPtr != NULL);

    length = genePtr->length;
    contents = genePtr->contents;

    for (i = 0; i < length; i++) {
        contents[i] =
            nucleotides[(random_generate(randomPtr)% NUCLEOTIDE_NUM_TYPE)];
    }
}
Beispiel #15
0
int main(int argc, char *argv[]){
  
  //Déclaration des variables
  
  int taille=0; //Taille des chaînes (change à chaque paramètre)
  double min; //Temps minimum observé
  double max; //Temps maximum observé
  double sum; //Temps total depuis le début de l'execution (par paramètre)
  double time;//Temps d'une execution
  int cpt;    //Compteur de génération
  char* S=NULL; //Chaîne à comparer
  char* T=NULL; //Idem
  int (*pfonction)(char*,char*,const int &); //Pointeur de fonction (algo1,2,3)
  std::ifstream fichier;	//Pointeur du fichier en cour de lecture (paramètre)
  int ligne_courante=0;		//Second curseur (virtuel) dans le fichier
  bool sortie;			//Condition de sortie de boucle en lecture de fichier
  int cpt_argument=2;		//Compteur de l'argument en cours de lecture
  int facteur;       		//On répète facteur fois le même test entre le début et la fin du chronomètre, pour obtenir un temps >1ms
  
  //Attribution de l'algorithme en fonction du premier paramètre (1,2,3)
  switch (atoi(argv[1])){
    case 1 : pfonction=&algo1;break;
    case 2 : pfonction=&algo2;break;
    case 3 : pfonction=&algo3;break;
    default : std::cout<<"Algorithm "<<atoi(argv[1])<<" does not exist !\n"; return 0;break;
  }

  //On parcourt chaque argument (demande de jeux de tests)
  while(cpt_argument<argc)
	{
	  
	  //INITIALISATION DES VARIABLES
	  cpt=0;
	  min=200000000; //min doit être plus grand que 3minutes (en ms)
	  max=-1;	//Valeur impossible (min=0)
	  time=0;
	  sum=0;
	  sortie=false;
	  //Si la taille est passée en paramètre (génération aléatoire)
	  if(atoi(argv[cpt_argument])!=0)
	  {
	    taille=atoi(argv[cpt_argument]);
		
	    //Génération aléatoire
	    S=random_generate(taille,cpt);
	    T=random_generate(taille,cpt+1);
	    facteur=1;
	    
	    /*
	     * Boucle déterminant le facteur minimum à appliquer pour obtenir des chronométrages >1ms
	     */
	    do{	
		    //Lancement du chronomètre
		    crono_start();
		    for(int i=0;i<facteur;i++)
		    {
		      //On effectue facteur fois la résolution
		      (*pfonction)(S,T,taille);
		    }
		    crono_stop();
		    //Si le temps de résolution est inférieur à 5ms, on multiplie par 10 le facteur
		    if(crono_ms()<5)
		    {
			facteur*=10;
		    }
	    }
	    while(crono_ms()<5);
	    /*
	     * Fin de la boucle de recherche de facteur
	     */
	    
	    
	    
	    //On génère des chaînes aléatoires jusqu'à 3 minutes de temps total de résolution
	      while(sum<180*1000)
	      {
		//Génération aléatoire
		S=random_generate(taille,cpt);
		T=random_generate(taille,cpt+1);

		//Lancement du chronomètre
		crono_start();
		for(int i=0;i<facteur;i++)
		{
		 (*pfonction)(S,T,taille);
		}
		crono_stop();

	
		//Mise à jour des statistiques
		time=crono_ms();
		sum+=time;
		if(time>max)
		{
		  max=time;
		}
		if(time<min)
		{
		  min=time;
		}
		cpt+=2; //Voir fonction random_generate pour plus de détails
	
		//Libération de S et T (cf random_generate)
		free(S);
		free(T);
	  	}
	}//boucle d'argument===taille
	
	
	  //Sinon, si un fichier est passé en paramètre
	  else
	  {
	    //Ouverture du fichier
	    fichier.open(argv[cpt_argument]);
	    //Contrôle de l'ouverture
	    if(fichier)
	    {
	      //Récupération de la taille des chaînes en première ligne
	      fichier>>taille;
	      
	      
	      S=(char*)malloc(taille*sizeof(char));
	      S[0]=' ';
	      T=(char*)malloc(taille*sizeof(char));
	      T[0]=' ';
	      
	      //Récupération de la première chaine
	      fichier>>&S[1];
	      
	      //Sauvegarde de la position (curseur virtuel)
	      ligne_courante=fichier.tellg();
	      
	      //Recopie de S dans T pour la première comparaison
	      strcpy(T,S);
		
	      
	      /*
	       * Détermination du facteur minimum
	       */
		facteur=1;
		do{	
			crono_start();
			for(int i=0;i<facteur;i++)
			{
			 (*pfonction)(S,T,taille);
			}
			crono_stop();
			//std::cout<<"facteur="<<facteur<<" crono="<<crono_ms()<<"\n";//@DEBUG
			if(crono_ms()<5)
			{
			    facteur*=10;
			}
		}
		while(crono_ms()<5);
		
		
		//Tant que toutes les chaînes n'ont pas été parcourues
		while(!sortie)
		{
		    //On résoud toutes les paires possibles du fichier
		    //Si le pointeur de "T" arrive à la fin du fichier
		    if(fichier.eof())
		    {
		      //On avance S d'une ligne
		      fichier.clear();
		      fichier.seekg(ligne_courante);
		      fichier>>&S[1];
		      strcpy(T,S);
		      //Condition d'arrêt du programme : les pointeurs S et T sont à la fin du fichier
		      if(fichier.eof())
		      {
			sortie=true;break;
		      }
		      //On repart à partir de la ligne suivante
		      ligne_courante=fichier.tellg();
		    }
			
		      //Résolution
		      crono_start();
			for(int i=0;i<facteur;i++)
			{
		          (*pfonction)(S,T,taille);
			}
		      crono_stop();
		      
		      
		      //Mise à jour des statistiques
		      time=crono_ms();
		      sum+=time;
		      if(time>max)
		      {
			max=time;
		      }
		      if(time<min)
		      {
			min=time;
		      }
		      cpt+=2;
		      fichier>>&T[1];
		}
		
		//On libère S et T uniquement à la fin
		free(S);
		free(T);
		fichier.close();
	    } 
	    else //ERREUR D'OUVERTURE DE FICHIER
	    {
	       std::cout<<"Wrong file input !\n";
	       return 0;
	    }    
	  }//boucle d'argument===fichier
Beispiel #16
0
double negexp( double mean)
 {/* Init negexp */
  return(((double)(-log(random_generate())*((double)(mean)))));
 }/* End negexp */
Beispiel #17
0
void client_run (void* argPtr) {
    TM_THREAD_ENTER();

    /*long id = thread_getId();

    volatile long* ptr1 = &(global_array[0].value);
    volatile long* ptr2 = &(global_array[100].value);
    long tt = 0;
    if (id == 0) {
        while (1) {
            long v1 = 0;
            long v2 = 0;
            acquire_write(&(local_th_data[phys_id]), &the_lock);
            *ptr1 = (*ptr1) + 1;

            int f = 1;
            int ii;
            for(ii = 1; ii <= 100000000; ii++)
            {
                f *= ii;
            }
            tt += f;

            *ptr2 = (*ptr2) + 1;
            v1 = global_array[0].value;
            v2 = global_array[100].value;
            release_write(cluster_id, &(local_th_data[phys_id]), &the_lock); \
                if (v1 != v2) {
                    printf("different2! %ld %ld\n", v1, v2);
                    exit(1);
                }

        }
    } else {
        while (1) {
            int i = 0;
            long sum = 0;
            for (; i < 100000; i++) {
                int status = _xbegin();
                if (status == _XBEGIN_STARTED) {
                    sum += *ptr1;
                    sum += *ptr2;
                    _xend();
                }
            }
            while(1) {
                long v1 = 0;
                long v2 = 0;
                int status = _xbegin();
                if (status == _XBEGIN_STARTED) {
                    v1 = *ptr1;
                    v2 = *ptr2;
                    _xend();
                if (v1 != v2) {
                    printf("different! %ld %ld\n", v1, v2);
                    exit(1);
                }

                }
            }
        }
    }
    printf("%ld", tt);*/


    random_t* randomPtr = random_alloc();
    random_seed(randomPtr, time(0));

    // unsigned long myId = thread_getId();
    // long numThread = *((long*)argPtr);
    long operations = (long)global_params[PARAM_OPERATIONS] / (long)global_params[PARAM_THREADS];
    long interval = (long)global_params[PARAM_INTERVAL];
    printf("operations: %ld \tinterval: %ld\n", operations, interval);

    long total = 0;
    long total2 = 0;

    long i = 0;
    for (; i < operations; i++) {
        long random_number = ((long) random_generate(randomPtr)) % ((long)global_params[PARAM_SIZE]);
        long random_number2 = ((long) random_generate(randomPtr)) % ((long)global_params[PARAM_SIZE]);
        if (random_number == random_number2) {
            random_number2 = (random_number2 + 1) % ((long)global_params[PARAM_SIZE]);
        }
        TM_BEGIN();
        long r1 = (long)TM_SHARED_READ_L(global_array[random_number].value);
        long r2 = (long)TM_SHARED_READ_L(global_array[random_number2].value);

        int repeat = 0;
        for (; repeat < (long) global_params[PARAM_CONTENTION]; repeat++) {
        	total2 += (long) TM_SHARED_READ_L(global_array[((long) random_generate(randomPtr)) % ((long)global_params[PARAM_SIZE])].value);
        }
        r1 = r1 + 1;
        r2 = r2 - 1;

        int f = 1;
        int ii;
        for(ii = 1; ii <= ((unsigned int) global_params[PARAM_WORK]); ii++)
        {
            f *= ii;
        }
        total += f / 1000000;

        TM_SHARED_WRITE_L(global_array[random_number].value, r1);
        TM_SHARED_WRITE_L(global_array[random_number2].value, r2);
        TM_END();

        long k = 0;
        for (;k < (long)global_params[PARAM_INTERVAL]; k++) {
            long ru = ((long) random_generate(randomPtr)) % 2;
            total += ru;
        }

    }

    TM_THREAD_EXIT();
    printf("ru ignore %ld - %ld\n", total, total2);
}
Beispiel #18
0
void client_run (void* argPtr) {
    TM_THREAD_ENTER();

    random_t* randomPtr = random_alloc();
    random_seed(randomPtr, time(0));

    // unsigned long myId = thread_getId();
    // long numThread = *((long*)argPtr);
    long operations = (long)global_params[PARAM_OPERATIONS] / (long)global_params[PARAM_THREADS];
    long interval = (long)global_params[PARAM_INTERVAL];
    printf("operations: %ld \tinterval: %ld\n", operations, interval);

    long total = 0;
    long total2 = 0;

    long i = 0;
    unsigned int cont_size = (unsigned int) global_params[PARAM_CONTENTION];
    unsigned int* sorted_locks = (unsigned int*) malloc((2 + cont_size) * sizeof(int));
    unsigned int* read_idxs = (unsigned int*) malloc(cont_size * sizeof(int));

    for (; i < operations; i++) {
        long random_number = ((long) random_generate(randomPtr)) % ((long)global_params[PARAM_SIZE]);
        long random_number2 = ((long) random_generate(randomPtr)) % ((long)global_params[PARAM_SIZE]);
        if (random_number == random_number2) {
            random_number2 = (random_number2 + 1) % ((long)global_params[PARAM_SIZE]);
        }

        int repeat = 0;
        for (; repeat < cont_size; repeat++) {
        	read_idxs[repeat] = ((unsigned int) random_generate(randomPtr)) % ((unsigned int)global_params[PARAM_SIZE]);
        	LI_HASH(&global_array[read_idxs[repeat]], &sorted_locks[repeat + 2]);
        }

        // TM_BEGIN();
        LI_HASH(&global_array[random_number], &sorted_locks[0]);
        LI_HASH(&global_array[random_number2], &sorted_locks[1]);
        TM_BEGIN_ARGS(sorted_locks, cont_size + 2);

        long r1 = (long)TM_SHARED_READ(global_array[random_number].value);
        long r2 = (long)TM_SHARED_READ(global_array[random_number2].value);

        for (repeat--; repeat >= 0; repeat--) {
        	total2 += (long) TM_SHARED_READ(global_array[read_idxs[repeat]].value);
        }
        r1 = r1 + 1;
        r2 = r2 - 1;

        int f = 1;
        int ii;
        for(ii = 1; ii <= ((unsigned int) global_params[PARAM_WORK]); ii++)
        {
            f *= ii;
        }
        total += f / 1000000;

        TM_SHARED_WRITE(global_array[random_number].value, r1);
        TM_SHARED_WRITE(global_array[random_number2].value, r2);
        TM_END_ARGS(sorted_locks, cont_size + 2);

        long k = 0;
        for (;k < (long)global_params[PARAM_INTERVAL]; k++) {
            long ru = ((long) random_generate(randomPtr)) % 2;
            total += ru;
        }

    }

    TM_THREAD_EXIT();
    printf("ru ignore %ld - %ld\n", total, total2);
}
Beispiel #19
0
/* =============================================================================
 * genScalData_seq
 * =============================================================================
 */
void
genScalData_seq (graphSDG* SDGdataPtr)
{
    /*
     * STEP 0: Create the permutations required to randomize the vertices
     */

    random_t* stream = random_alloc();
    assert(stream);
    random_seed(stream, 0);

    ULONGINT_T* permV; /* the vars associated with the graph tuple */
    permV = (ULONGINT_T*)malloc(TOT_VERTICES * sizeof(ULONGINT_T));
    assert(permV);

    long i;

    /* Initialize the array */
    for (i = 0; i < TOT_VERTICES; i++) {
        permV[i] = i;
    }

    for (i = 0; i < TOT_VERTICES; i++) {
        long t1 = random_generate(stream);
        long t = i + t1 % (TOT_VERTICES - i);
        if (t != i) {
            ULONGINT_T t2 = permV[t];
            permV[t] = permV[i];
            permV[i] = t2;
        }
    }

    /*
     * STEP 1: Create Cliques
     */

    long* cliqueSizes;

    long estTotCliques = ceil(1.5 * TOT_VERTICES / ((1+MAX_CLIQUE_SIZE)/2));

    /*
     * Allocate mem for Clique array
     * Estimate number of clique required and pad by 50%
     */
    cliqueSizes = (long*)malloc(estTotCliques * sizeof(long));
    assert(cliqueSizes);


    /* Generate random clique sizes. */
    for (i = 0; i < estTotCliques; i++) {
        cliqueSizes[i] = 1 + (random_generate(stream) % MAX_CLIQUE_SIZE);
    }

    long totCliques = 0;

    /*
     * Allocate memory for cliqueList
     */

    ULONGINT_T* lastVsInCliques;
    ULONGINT_T* firstVsInCliques;

    lastVsInCliques = (ULONGINT_T*)malloc(estTotCliques * sizeof(ULONGINT_T));
    assert(lastVsInCliques);
    firstVsInCliques = (ULONGINT_T*)malloc(estTotCliques * sizeof(ULONGINT_T));
    assert(firstVsInCliques);

    /*
     * Sum up vertices in each clique to determine the lastVsInCliques array
     */

    lastVsInCliques[0] = cliqueSizes[0] - 1;
    for (i = 1; i < estTotCliques; i++) {
        lastVsInCliques[i] = cliqueSizes[i] + lastVsInCliques[i-1];
        if (lastVsInCliques[i] >= TOT_VERTICES-1) {
            break;
        }
    }
    totCliques = i + 1;

    /*
     * Fix the size of the last clique
     */
    cliqueSizes[totCliques-1] =
        TOT_VERTICES - lastVsInCliques[totCliques-2] - 1;
    lastVsInCliques[totCliques-1] = TOT_VERTICES - 1;

    firstVsInCliques[0] = 0;


    /*
     * Compute start Vertices in cliques.
     */
    for (i = 1; i < totCliques; i++) {
        firstVsInCliques[i] = lastVsInCliques[i-1] + 1;
    }

#ifdef WRITE_RESULT_FILES
    /* Write the generated cliques to file for comparison with Kernel 4 */
    FILE* outfp = fopen("cliques.txt", "w");
    fprintf(outfp, "No. of cliques - %lu\n", totCliques);
    for (i = 0; i < totCliques; i++) {
        fprintf(outfp, "Clq %lu - ", i);
        long j;
        for (j = firstVsInCliques[i]; j <= lastVsInCliques[i]; j++) {
            fprintf(outfp, "%lu ", permV[j]);
        }
        fprintf(outfp, "\n");
    }
    fclose(outfp);
#endif

    /*
     * STEP 2: Create the edges within the cliques
     */

    /*
     * Estimate number of edges - using an empirical measure
     */
    long estTotEdges;
    if (SCALE >= 12) {
        estTotEdges = ceil(((MAX_CLIQUE_SIZE-1) * TOT_VERTICES));
    } else {
        estTotEdges = ceil(1.2 * (((MAX_CLIQUE_SIZE-1)*TOT_VERTICES)
                                  * ((1 + MAX_PARAL_EDGES)/2) + TOT_VERTICES*2));
    }

    /*
     * Initialize edge counter
     */
    long i_edgePtr = 0;
    float p = PROB_UNIDIRECTIONAL;

    /*
     * Partial edgeLists
     */

    ULONGINT_T* startV;
    ULONGINT_T* endV;
    long numByte = (estTotEdges) * sizeof(ULONGINT_T);
    startV = (ULONGINT_T*)malloc(numByte);
    endV = (ULONGINT_T*)malloc(numByte);
    assert(startV);
    assert(endV);

    /*
     * Tmp array to keep track of the no. of parallel edges in each direction
     */
    ULONGINT_T** tmpEdgeCounter =
        (ULONGINT_T**)malloc(MAX_CLIQUE_SIZE * sizeof(ULONGINT_T *));
    assert(tmpEdgeCounter);
    for (i = 0; i < MAX_CLIQUE_SIZE; i++) {
        tmpEdgeCounter[i] =
            (ULONGINT_T*)malloc(MAX_CLIQUE_SIZE * sizeof(ULONGINT_T));
        assert(tmpEdgeCounter[i]);
    }

    /*
     * Create edges
     */
     long i_clique;

     for (i_clique = 0; i_clique < totCliques; i_clique++) {

        /*
         * Get current clique parameters
         */

        long i_cliqueSize = cliqueSizes[i_clique];
        long i_firstVsInClique = firstVsInCliques[i_clique];

        /*
         * First create at least one edge between two vetices in a clique
         */

        for (i = 0; i < i_cliqueSize; i++) {

            long j;
            for (j = 0; j < i; j++) {

                float r = (float)(random_generate(stream) % 1000) / (float)1000;
                if (r >= p) {

                    startV[i_edgePtr] = i + i_firstVsInClique;
                    endV[i_edgePtr] = j + i_firstVsInClique;
                    i_edgePtr++;
                    tmpEdgeCounter[i][j] = 1;

                    startV[i_edgePtr] = j + i_firstVsInClique;
                    endV[i_edgePtr] = i + i_firstVsInClique;
                    i_edgePtr++;
                    tmpEdgeCounter[j][i] = 1;

                } else  if (r >= 0.5) {

                    startV[i_edgePtr] = i + i_firstVsInClique;
                    endV[i_edgePtr] = j + i_firstVsInClique;
                    i_edgePtr++;
                    tmpEdgeCounter[i][j] = 1;
                    tmpEdgeCounter[j][i] = 0;

                } else {

                    startV[i_edgePtr] = j + i_firstVsInClique;
                    endV[i_edgePtr] = i + i_firstVsInClique;
                    i_edgePtr++;
                    tmpEdgeCounter[j][i] = 1;
                    tmpEdgeCounter[i][j] = 0;

                }

            } /* for j */
        } /* for i */

        if (i_cliqueSize != 1) {
            long randNumEdges = (long)(random_generate(stream)
                                       % (2*i_cliqueSize*MAX_PARAL_EDGES));
            long i_paralEdge;
            for (i_paralEdge = 0; i_paralEdge < randNumEdges; i_paralEdge++) {
                i = (random_generate(stream) % i_cliqueSize);
                long j = (random_generate(stream) % i_cliqueSize);
                if ((i != j) && (tmpEdgeCounter[i][j] < MAX_PARAL_EDGES)) {
                    float r = (float)(random_generate(stream) % 1000) / (float)1000;
                    if (r >= p) {
                        /* Copy to edge structure. */
                        startV[i_edgePtr] = i + i_firstVsInClique;
                        endV[i_edgePtr] = j + i_firstVsInClique;
                        i_edgePtr++;
                        tmpEdgeCounter[i][j]++;
                    }
                }
            }
        }

    } /* for i_clique */

    for (i = 0; i < MAX_CLIQUE_SIZE; i++) {
        free(tmpEdgeCounter[i]);
    }

    free(tmpEdgeCounter);


    /*
     * Merge partial edge lists
     */

    ULONGINT_T i_edgeStartCounter = 0;
    ULONGINT_T i_edgeEndCounter = i_edgePtr;
    long edgeNum = i_edgePtr;

    /*
     * Initialize edge list arrays
     */

    ULONGINT_T* startVertex;
    ULONGINT_T* endVertex;

    if (SCALE < 10) {
        long numByte = 2 * edgeNum * sizeof(ULONGINT_T);
        startVertex = (ULONGINT_T*)malloc(numByte);
        endVertex = (ULONGINT_T*)malloc(numByte);
    } else {
        long numByte = (edgeNum + MAX_PARAL_EDGES * TOT_VERTICES)
                       * sizeof(ULONGINT_T);
        startVertex = (ULONGINT_T*)malloc(numByte);
        endVertex = (ULONGINT_T*)malloc(numByte);
    }
    assert(startVertex);
    assert(endVertex);

    for (i = i_edgeStartCounter; i < i_edgeEndCounter; i++) {
        startVertex[i] = startV[i-i_edgeStartCounter];
        endVertex[i] = endV[i-i_edgeStartCounter];
    }

    ULONGINT_T numEdgesPlacedInCliques = edgeNum;

    /*
     * STEP 3: Connect the cliques
     */

    i_edgePtr = 0;
    p = PROB_INTERCL_EDGES;

    /*
     * Generating inter-clique edges as given in the specs
     */

    for (i = 0; i < TOT_VERTICES; i++) {

        ULONGINT_T tempVertex1 = i;
        long h = totCliques;
        long l = 0;
        long t = -1;
        while (h - l > 1) {
            long m = (h + l) / 2;
            if (tempVertex1 >= firstVsInCliques[m]) {
                l = m;
            } else {
                if ((tempVertex1 < firstVsInCliques[m]) && (m > 0)) {
                    if (tempVertex1 >= firstVsInCliques[m-1]) {
                        t = m - 1;
                        break;
                    } else {
                        h = m;
                    }
                }
            }
        }

        if (t == -1) {
            long m;
            for (m = (l + 1); m < h; m++) {
                if (tempVertex1<firstVsInCliques[m]) {
                    break;
                }
            }
            t = m-1;
        }

        long t1 = firstVsInCliques[t];

        ULONGINT_T d;
        for (d = 1, p = PROB_INTERCL_EDGES; d < TOT_VERTICES; d *= 2, p /= 2) {

            float r = (float)(random_generate(stream) % 1000) / (float)1000;

            if (r <= p) {

                ULONGINT_T tempVertex2 = (i+d) % TOT_VERTICES;

                h = totCliques;
                l = 0;
                t = -1;
                while (h - l > 1) {
                    long m = (h + l) / 2;
                    if (tempVertex2 >= firstVsInCliques[m]) {
                        l = m;
                    } else {
                        if ((tempVertex2 < firstVsInCliques[m]) && (m > 0)) {
                            if (firstVsInCliques[m-1] <= tempVertex2) {
                                t = m - 1;
                                break;
                            } else {
                                h = m;
                            }
                        }
                    }
                }

                if (t == -1) {
                    long m;
                    for (m = (l + 1); m < h; m++) {
                        if (tempVertex2 < firstVsInCliques[m]) {
                            break;
                        }
                    }
                    t = m - 1;
                }

                long t2 = firstVsInCliques[t];

                if (t1 != t2) {
                    long randNumEdges =
                        random_generate(stream) % MAX_PARAL_EDGES + 1;
                    long j;
                    for (j = 0; j < randNumEdges; j++) {
                        startV[i_edgePtr] = tempVertex1;
                        endV[i_edgePtr] = tempVertex2;
                        i_edgePtr++;
                    }
                }

            } /* r <= p */

            float r0 = (float)(random_generate(stream) % 1000) / (float)1000;

            if ((r0 <= p) && (i-d>=0)) {

                ULONGINT_T tempVertex2 = (i-d) % TOT_VERTICES;

                h = totCliques;
                l = 0;
                t = -1;
                while (h - l > 1) {
                    long m = (h + l) / 2;
                    if (tempVertex2 >= firstVsInCliques[m]) {
                        l = m;
                    } else {
                        if ((tempVertex2 < firstVsInCliques[m]) && (m > 0)) {
                            if (firstVsInCliques[m-1] <= tempVertex2) {
                                t = m - 1;
                                break;
                            } else {
                                h = m;
                            }
                        }
                    }
                }

                if (t == -1) {
                    long m;
                    for (m = (l + 1); m < h; m++) {
                        if (tempVertex2 < firstVsInCliques[m]) {
                            break;
                        }
                    }
                    t = m - 1;
                }

                long t2 = firstVsInCliques[t];

                if (t1 != t2) {
                    long randNumEdges =
                        random_generate(stream) % MAX_PARAL_EDGES + 1;
                    long j;
                    for (j = 0; j < randNumEdges; j++) {
                        startV[i_edgePtr] = tempVertex1;
                        endV[i_edgePtr] = tempVertex2;
                        i_edgePtr++;
                    }
                }

            } /* r0 <= p && (i-d) > 0 */

        } /* for d, p */

    } /* for i */


    i_edgeEndCounter = i_edgePtr;
    i_edgeStartCounter = 0;

    edgeNum = i_edgePtr;
    ULONGINT_T numEdgesPlacedOutside = edgeNum;

    for (i = i_edgeStartCounter; i < i_edgeEndCounter; i++) {
        startVertex[i+numEdgesPlacedInCliques] = startV[i-i_edgeStartCounter];
        endVertex[i+numEdgesPlacedInCliques] = endV[i-i_edgeStartCounter];
    }

    ULONGINT_T  numEdgesPlaced = numEdgesPlacedInCliques + numEdgesPlacedOutside;

    SDGdataPtr->numEdgesPlaced = numEdgesPlaced;

    printf("Finished generating edges\n");
    printf("No. of intra-clique edges - %lu\n", numEdgesPlacedInCliques);
    printf("No. of inter-clique edges - %lu\n", numEdgesPlacedOutside);
    printf("Total no. of edges        - %lu\n", numEdgesPlaced);

    free(cliqueSizes);
    free(firstVsInCliques);
    free(lastVsInCliques);

    free(startV);
    free(endV);

    /*
     * STEP 4: Generate edge weights
     */

    SDGdataPtr->intWeight =
        (LONGINT_T*)malloc(numEdgesPlaced * sizeof(LONGINT_T));
    assert(SDGdataPtr->intWeight);

    p = PERC_INT_WEIGHTS;
    ULONGINT_T numStrWtEdges  = 0;

    for (i = 0; i < numEdgesPlaced; i++) {
        float r = (float)(random_generate(stream) % 1000) / (float)1000;
        if (r <= p) {
            SDGdataPtr->intWeight[i] =
                1 + (random_generate(stream) % (MAX_INT_WEIGHT-1));
        } else {
            SDGdataPtr->intWeight[i] = -1;
            numStrWtEdges++;
        }
    }

    long t = 0;
    for (i = 0; i < numEdgesPlaced; i++) {
        if (SDGdataPtr->intWeight[i] < 0) {
            SDGdataPtr->intWeight[i] = -t;
            t++;
        }
    }

    SDGdataPtr->strWeight =
        (char*)malloc(numStrWtEdges * MAX_STRLEN * sizeof(char));
    assert(SDGdataPtr->strWeight);

    for (i = 0; i < numEdgesPlaced; i++) {
        if (SDGdataPtr->intWeight[i] <= 0) {
            long j;
            for (j = 0; j < MAX_STRLEN; j++) {
                SDGdataPtr->strWeight[(-SDGdataPtr->intWeight[i])*MAX_STRLEN+j] =
                    (char) (1 + random_generate(stream) % 127);
            }
        }
    }

    /*
     * Choose SOUGHT STRING randomly if not assigned
     */

    if (strlen(SOUGHT_STRING) != MAX_STRLEN) {
        SOUGHT_STRING = (char*)malloc(MAX_STRLEN * sizeof(char));
        assert(SOUGHT_STRING);
    }

    t = random_generate(stream) % numStrWtEdges;
    long j;
    for (j = 0; j < MAX_STRLEN; j++) {
        SOUGHT_STRING[j] =
            (char) ((long) SDGdataPtr->strWeight[t*MAX_STRLEN+j]);
    }

    /*
     * STEP 5: Permute Vertices
     */

    for (i = 0; i < numEdgesPlaced; i++) {
        startVertex[i] = permV[(startVertex[i])];
        endVertex[i] = permV[(endVertex[i])];
    }

    /*
     * STEP 6: Sort Vertices
     */

    /*
     * Radix sort with StartVertex as primary key
     */

    numByte = numEdgesPlaced * sizeof(ULONGINT_T);
    SDGdataPtr->startVertex = (ULONGINT_T*)malloc(numByte);
    assert(SDGdataPtr->startVertex);
    SDGdataPtr->endVertex = (ULONGINT_T*)malloc(numByte);
    assert(SDGdataPtr->endVertex);

    all_radixsort_node_aux_s3_seq(numEdgesPlaced,
                                  startVertex,
                                  SDGdataPtr->startVertex,
                                  endVertex,
                                  SDGdataPtr->endVertex);

    free(startVertex);
    free(endVertex);

    if (SCALE < 12) {

        /*
         * Sort with endVertex as secondary key
         */

        long i0 = 0;
        long i1 = 0;
        i = 0;

        while (i < numEdgesPlaced) {

            for (i = i0; i < numEdgesPlaced; i++) {
                if (SDGdataPtr->startVertex[i] !=
                    SDGdataPtr->startVertex[i1])
                {
                    i1 = i;
                    break;
                }
            }

            long j;
            for (j = i0; j < i1; j++) {
                long k;
                for (k = j+1; k < i1; k++) {
                    if (SDGdataPtr->endVertex[k] <
                        SDGdataPtr->endVertex[j])
                    {
                        long t = SDGdataPtr->endVertex[j];
                        SDGdataPtr->endVertex[j] = SDGdataPtr->endVertex[k];
                        SDGdataPtr->endVertex[k] = t;
                    }
                }
            }

            if (SDGdataPtr->startVertex[i0] != TOT_VERTICES-1) {
                i0 = i1;
            } else {
                long j;
                for (j=i0; j<numEdgesPlaced; j++) {
                    long k;
                    for (k=j+1; k<numEdgesPlaced; k++) {
                        if (SDGdataPtr->endVertex[k] <
                            SDGdataPtr->endVertex[j])
                        {
                            long t = SDGdataPtr->endVertex[j];
                            SDGdataPtr->endVertex[j] = SDGdataPtr->endVertex[k];
                            SDGdataPtr->endVertex[k] = t;
                        }
                    }
                }
            }

        } /* while i < numEdgesPlaced */

    } else {

        ULONGINT_T* tempIndex =
            (ULONGINT_T*)malloc((TOT_VERTICES + 1) * sizeof(ULONGINT_T));

        /*
         * Update degree of each vertex
         */

        tempIndex[0] = 0;
        tempIndex[TOT_VERTICES] = numEdgesPlaced;
        long i0 = 0;

        for (i=0; i < TOT_VERTICES; i++) {
            tempIndex[i+1] = tempIndex[i];
            long j;
            for (j = i0; j < numEdgesPlaced; j++) {
                if (SDGdataPtr->startVertex[j] !=
                    SDGdataPtr->startVertex[i0])
                {
                    if (SDGdataPtr->startVertex[i0] == i) {
                        tempIndex[i+1] = j;
                        i0 = j;
                        break;
                    }
                }
            }
        }

        /*
         * Insertion sort for now, replace with something better later on
         */
        for (i = 0; i < TOT_VERTICES; i++) {
            long j;
            for (j = tempIndex[i]; j < tempIndex[i+1]; j++) {
                long k;
                for (k = (j + 1); k < tempIndex[i+1]; k++) {
                    if (SDGdataPtr->endVertex[k] <
                        SDGdataPtr->endVertex[j])
                    {
                        long t = SDGdataPtr->endVertex[j];
                        SDGdataPtr->endVertex[j] = SDGdataPtr->endVertex[k];
                        SDGdataPtr->endVertex[k] = t;
                    }
                }
            }
        }

       free(tempIndex);

    } /* SCALE >= 12 */

    random_free(stream);
    free(permV);
}
Beispiel #20
0
/* =============================================================================
 * segments_create
 * -- Populates 'contentsPtr'
 * =============================================================================
 */
void
segments_create (segments_t* segmentsPtr, gene_t* genePtr, random_t* randomPtr)
{
    vector_t* segmentsContentsPtr;
    char** strings;
    long segmentLength;
    long minNumSegment;
    char* geneString;
    long geneLength;
    bitmap_t* startBitmapPtr;
    long numStart;
    long i;
    long maxZeroRunLength;

    assert(segmentsPtr != NULL);
    assert(genePtr != NULL);
    assert(randomPtr != NULL);

    segmentsContentsPtr = segmentsPtr->contentsPtr;
    strings = segmentsPtr->strings;
    segmentLength = segmentsPtr->length;
    minNumSegment = segmentsPtr->minNum;

    geneString = genePtr->contents;
    geneLength = genePtr->length;
    startBitmapPtr = genePtr->startBitmapPtr;
    numStart = geneLength - segmentLength + 1;

    /* Pick some random segments to start */
    for (i = 0; i < minNumSegment; i++) {
        long j = (long)(random_generate(randomPtr) % numStart);
        bool_t status = bitmap_set(startBitmapPtr, j);
        assert(status);
        memcpy(strings[i], &(geneString[j]), segmentLength * sizeof(char));
        status = vector_pushBack(segmentsContentsPtr, (void*)strings[i]);
        assert(status);
    }

    /* Make sure segment covers start */
    i = 0;
    if (!bitmap_isSet(startBitmapPtr, i)) {
        char* string = (char*)malloc((segmentLength+1) * sizeof(char));
        string[segmentLength] = '\0';
        memcpy(string, &(geneString[i]), segmentLength * sizeof(char));
        bool_t status = vector_pushBack(segmentsContentsPtr, (void*)string);
        assert(status);
        status = bitmap_set(startBitmapPtr, i);
        assert(status);
    }

    /* Add extra segments to fill holes and ensure overlap */
    maxZeroRunLength = segmentLength - 1;
    for (i = 0; i < numStart; i++) {
        long i_stop = MIN((i+maxZeroRunLength), numStart);
        for ( /* continue */; i < i_stop; i++) {
            if (bitmap_isSet(startBitmapPtr, i)) {
                break;
            }
        }
        if (i == i_stop) {
            /* Found big enough hole */
            char* string = (char*)malloc((segmentLength+1) * sizeof(char));
            string[segmentLength] = '\0';
            i = i - 1;
            memcpy(string, &(geneString[i]), segmentLength * sizeof(char));
            bool_t status = vector_pushBack(segmentsContentsPtr, (void*)string);
            assert(status);
            status = bitmap_set(startBitmapPtr, i);
            assert(status);
        }
    }
}
Beispiel #21
0
/* =============================================================================
 * stream_generate
 * -- Returns number of attacks generated
 * =============================================================================
 */
long
stream_generate (stream_t* streamPtr,
                 dictionary_t* dictionaryPtr,
                 long numFlow,
                 long seed,
                 long maxLength)
{
    long numAttack = 0;

    long      percentAttack  = streamPtr->percentAttack;
    random_t* randomPtr      = streamPtr->randomPtr;
    vector_t* allocVectorPtr = streamPtr->allocVectorPtr;
    queue_t*  packetQueuePtr = streamPtr->packetQueuePtr;
    MAP_T*    attackMapPtr   = streamPtr->attackMapPtr;

    detector_t* detectorPtr = detector_alloc();
    detector_addPreprocessor(detectorPtr, &preprocessor_toLower);

    random_seed(randomPtr, seed);
    queue_clear(packetQueuePtr);

    long range = '~' - ' ' + 1;

    long f;
    for (f = 1; f <= numFlow; f++) {
        char* str;
        if ((random_generate(randomPtr) % 100) < percentAttack) {
            long s = random_generate(randomPtr) % global_numDefaultSignature;
            str = dictionary_get(dictionaryPtr, s);
            bool_t status =
                MAP_INSERT(attackMapPtr, (void*)f, (void*)str);
            numAttack++;
        } else {
            /*
             * Create random string
             */
            long length = (random_generate(randomPtr) % maxLength) + 1;
            str = (char*)malloc((length + 1) * sizeof(char));
            bool_t status = vector_pushBack(allocVectorPtr, (void*)str);
            long l;
            for (l = 0; l < length; l++) {
                str[l] = ' ' + (char)(random_generate(randomPtr) % range);
            }
            str[l] = '\0';
            char* str2 = (char*)malloc((length + 1) * sizeof(char));
            strcpy(str2, str);
            error_t error = detector_process(detectorPtr, str2); /* updates in-place */
            if (error == ERROR_SIGNATURE) {
                bool_t status = MAP_INSERT(attackMapPtr,
                                           (void*)f,
                                           (void*)str);
                numAttack++;
            }
            free(str2);
        }
        splitIntoPackets(str, f, randomPtr, allocVectorPtr, packetQueuePtr);
    }

    queue_shuffle(packetQueuePtr, randomPtr);

    detector_free(detectorPtr);

    return numAttack;
}
Beispiel #22
0
/* =============================================================================
 * data_generate
 * -- Binary variables of random PDFs
 * -- If seed is <0, do not reseed
 * -- Returns random network
 * =============================================================================
 */
net_t*
data_generate (data_t* dataPtr, long seed, long maxNumParent, long percentParent)
{
    random_t* randomPtr = dataPtr->randomPtr;
    if (seed >= 0) {
        random_seed(randomPtr, seed);
    }

    /*
     * Generate random Bayesian network
     */

    long numVar = dataPtr->numVar;
    net_t* netPtr = net_alloc(numVar);
    assert(netPtr);
    net_generateRandomEdges(netPtr, maxNumParent, percentParent, randomPtr);

    /*
     * Create a threshold for each of the possible permutation of variable
     * value instances
     */

    long** thresholdsTable = (long**)SEQ_MALLOC(numVar * sizeof(long*));
    assert(thresholdsTable);
    long v;
    for (v = 0; v < numVar; v++) {
        list_t* parentIdListPtr = net_getParentIdListPtr(netPtr, v);
        long numThreshold = 1 << list_getSize(parentIdListPtr);
        long* thresholds = (long*)SEQ_MALLOC(numThreshold * sizeof(long));
        assert(thresholds);
        long t;
        for (t = 0; t < numThreshold; t++) {
            long threshold = random_generate(randomPtr) % (DATA_PRECISION + 1);
            thresholds[t] = threshold;
        }
        thresholdsTable[v] = thresholds;
    }

    /*
     * Create variable dependency ordering for record generation
     */

    long* order = (long*)SEQ_MALLOC(numVar * sizeof(long));
    assert(order);
    long numOrder = 0;

    queue_t* workQueuePtr = queue_alloc(-1);
    assert(workQueuePtr);

    vector_t* dependencyVectorPtr = vector_alloc(1);
    assert(dependencyVectorPtr);

    bitmap_t* orderedBitmapPtr = bitmap_alloc(numVar);
    assert(orderedBitmapPtr);
    bitmap_clearAll(orderedBitmapPtr);

    bitmap_t* doneBitmapPtr = bitmap_alloc(numVar);
    assert(doneBitmapPtr);
    bitmap_clearAll(doneBitmapPtr);
    v = -1;
    while ((v = bitmap_findClear(doneBitmapPtr, (v + 1))) >= 0) {
        list_t* childIdListPtr = net_getChildIdListPtr(netPtr, v);
        long numChild = list_getSize(childIdListPtr);
        if (numChild == 0) {

            bool status;

            /*
             * Use breadth-first search to find net connected to this leaf
             */

            queue_clear(workQueuePtr);
            status = queue_push(workQueuePtr, (void*)v);
            assert(status);
            while (!queue_isEmpty(workQueuePtr)) {
                long id = (long)queue_pop(workQueuePtr);
                status = bitmap_set(doneBitmapPtr, id);
                assert(status);
                status = vector_pushBack(dependencyVectorPtr, (void*)id);
                assert(status);
                list_t* parentIdListPtr = net_getParentIdListPtr(netPtr, id);
                list_iter_t it;
                list_iter_reset(&it, parentIdListPtr);
                while (list_iter_hasNext(&it, parentIdListPtr)) {
                    long parentId = (long)list_iter_next(&it, parentIdListPtr);
                    status = queue_push(workQueuePtr, (void*)parentId);
                    assert(status);
                }
            }

            /*
             * Create ordering
             */

            long i;
            long n = vector_getSize(dependencyVectorPtr);
            for (i = 0; i < n; i++) {
                long id = (long)vector_popBack(dependencyVectorPtr);
                if (!bitmap_isSet(orderedBitmapPtr, id)) {
                    bitmap_set(orderedBitmapPtr, id);
                    order[numOrder++] = id;
                }
            }

        }
    }
    assert(numOrder == numVar);

    /*
     * Create records
     */

    char* record = dataPtr->records;
    long r;
    long numRecord = dataPtr->numRecord;
    for (r = 0; r < numRecord; r++) {
        long o;
        for (o = 0; o < numOrder; o++) {
            long v = order[o];
            list_t* parentIdListPtr = net_getParentIdListPtr(netPtr, v);
            long index = 0;
            list_iter_t it;
            list_iter_reset(&it, parentIdListPtr);
            while (list_iter_hasNext(&it, parentIdListPtr)) {
                long parentId = (long)list_iter_next(&it, parentIdListPtr);
                long value = record[parentId];
                assert(value != DATA_INIT);
                index = (index << 1) + value;
            }
            long rnd = random_generate(randomPtr) % DATA_PRECISION;
            long threshold = thresholdsTable[v][index];
            record[v] = ((rnd < threshold) ? 1 : 0);
        }
        record += numVar;
        assert(record <= (dataPtr->records + numRecord * numVar));
    }

    /*
     * Clean up
     */

    bitmap_free(doneBitmapPtr);
    bitmap_free(orderedBitmapPtr);
    vector_free(dependencyVectorPtr);
    queue_free(workQueuePtr);
    SEQ_FREE(order);
    for (v = 0; v < numVar; v++) {
        SEQ_FREE(thresholdsTable[v]);
    }
    SEQ_FREE(thresholdsTable);

    return netPtr;
}
Beispiel #23
0
void One_point_mutation(int Population[])
{
	int member = random_generate(POP);
	mutation(Population[member]);
}
Beispiel #24
0
/* =============================================================================
 * client_run
 * -- Execute list operations on the database
 * =============================================================================
 */
void
client_run (void* argPtr)
{
    TM_THREAD_ENTER();

    long myId = thread_getId();
    client_t* clientPtr = ((client_t**)argPtr)[myId];

    manager_t* managerPtr = clientPtr->managerPtr;
    random_t*  randomPtr  = clientPtr->randomPtr;

    long numOperation           = clientPtr->numOperation;
    long numQueryPerTransaction = clientPtr->numQueryPerTransaction;
    long queryRange             = clientPtr->queryRange;
    long percentUser            = clientPtr->percentUser;

    long* types  = (long*)P_MALLOC(numQueryPerTransaction * sizeof(long));
    long* ids    = (long*)P_MALLOC(numQueryPerTransaction * sizeof(long));
    long* ops    = (long*)P_MALLOC(numQueryPerTransaction * sizeof(long));
    long* prices = (long*)P_MALLOC(numQueryPerTransaction * sizeof(long));

    long i;

    for (i = 0; i < numOperation; i++) {

        long r = random_generate(randomPtr) % 100;
        action_t action = selectAction(r, percentUser);

        switch (action) {

            case ACTION_MAKE_RESERVATION: {
                long maxPrices[NUM_RESERVATION_TYPE] = { -1, -1, -1 };
                long maxIds[NUM_RESERVATION_TYPE] = { -1, -1, -1 };
                long n;
                long numQuery = random_generate(randomPtr) % numQueryPerTransaction + 1;
                long customerId = random_generate(randomPtr) % queryRange + 1;
                for (n = 0; n < numQuery; n++) {
                    types[n] = random_generate(randomPtr) % NUM_RESERVATION_TYPE;
                    ids[n] = (random_generate(randomPtr) % queryRange) + 1;
                }
                bool_t isFound = FALSE;
                TM_BEGIN();
                for (n = 0; n < numQuery; n++) {
                    long t = types[n];
                    long id = ids[n];
                    long price = -1;
                    switch (t) {
                        case RESERVATION_CAR:
                            if (MANAGER_QUERY_CAR(managerPtr, id) >= 0) {
                                price = MANAGER_QUERY_CAR_PRICE(managerPtr, id);
                            }
                            break;
                        case RESERVATION_FLIGHT:
                            if (MANAGER_QUERY_FLIGHT(managerPtr, id) >= 0) {
                                price = MANAGER_QUERY_FLIGHT_PRICE(managerPtr, id);
                            }
                            break;
                        case RESERVATION_ROOM:
                            if (MANAGER_QUERY_ROOM(managerPtr, id) >= 0) {
                                price = MANAGER_QUERY_ROOM_PRICE(managerPtr, id);
                            }
                            break;
                        default:
                            assert(0);
                    }
                    if (price > maxPrices[t]) {
                        maxPrices[t] = price;
                        maxIds[t] = id;
                        isFound = TRUE;
                    }
                } /* for n */
                if (isFound) {
                    MANAGER_ADD_CUSTOMER(managerPtr, customerId);
                }
                if (maxIds[RESERVATION_CAR] > 0) {
                    MANAGER_RESERVE_CAR(managerPtr,
                                        customerId, maxIds[RESERVATION_CAR]);
                }
                if (maxIds[RESERVATION_FLIGHT] > 0) {
                    MANAGER_RESERVE_FLIGHT(managerPtr,
                                           customerId, maxIds[RESERVATION_FLIGHT]);
                }
                if (maxIds[RESERVATION_ROOM] > 0) {
                    MANAGER_RESERVE_ROOM(managerPtr,
                                         customerId, maxIds[RESERVATION_ROOM]);
                }
                TM_END();
                break;
            }

            case ACTION_DELETE_CUSTOMER: {
                long customerId = random_generate(randomPtr) % queryRange + 1;
                TM_BEGIN();
                long bill = MANAGER_QUERY_CUSTOMER_BILL(managerPtr, customerId);
                if (bill >= 0) {
                    MANAGER_DELETE_CUSTOMER(managerPtr, customerId);
                }
                TM_END();
                break;
            }

            case ACTION_UPDATE_TABLES: {
                long numUpdate = random_generate(randomPtr) % numQueryPerTransaction + 1;
                long n;
                for (n = 0; n < numUpdate; n++) {
                    types[n] = random_generate(randomPtr) % NUM_RESERVATION_TYPE;
                    ids[n] = (random_generate(randomPtr) % queryRange) + 1;
                    ops[n] = random_generate(randomPtr) % 2;
                    if (ops[n]) {
                        prices[n] = ((random_generate(randomPtr) % 5) * 10) + 50;
                    }
                }
                TM_BEGIN();
                for (n = 0; n < numUpdate; n++) {
                    long t = types[n];
                    long id = ids[n];
                    long doAdd = ops[n];
                    if (doAdd) {
                        long newPrice = prices[n];
                        switch (t) {
                            case RESERVATION_CAR:
                                MANAGER_ADD_CAR(managerPtr, id, 100, newPrice);
                                break;
                            case RESERVATION_FLIGHT:
                                MANAGER_ADD_FLIGHT(managerPtr, id, 100, newPrice);
                                break;
                            case RESERVATION_ROOM:
                                MANAGER_ADD_ROOM(managerPtr, id, 100, newPrice);
                                break;
                            default:
                                assert(0);
                        }
                    } else { /* do delete */
                        switch (t) {
                            case RESERVATION_CAR:
                                MANAGER_DELETE_CAR(managerPtr, id, 100);
                                break;
                            case RESERVATION_FLIGHT:
                                MANAGER_DELETE_FLIGHT(managerPtr, id);
                                break;
                            case RESERVATION_ROOM:
                                MANAGER_DELETE_ROOM(managerPtr, id, 100);
                                break;
                            default:
                                assert(0);
                        }
                    }
                }
                TM_END();
                break;
            }

            default:
                assert(0);

        } /* switch (action) */

    } /* for i */

    TM_THREAD_EXIT();
}
 // returns if it was able to process
bool Player::process_note_and_instrument(int p_track,int p_note,int p_instrument) {

	bool aux_result;
	aux_result=false;
	Sample *aux_sample=0; // current sample
	int dest_sample_index;
	bool new_instrument=false;

	control.channel[p_track].row_has_note=false; // wise man says.. "we dont have a note... until we really know we have a note".
	control.channel[p_track].new_instrument=false;

	if ( (p_note<0) && (p_instrument<0) ) return aux_result; // nothing to do here
	if ( (p_note==255) && (p_instrument==255) ) return aux_result;

	if ( (p_note>=0) && (p_note<120) ) {

		process_new_note(p_track,p_note);

	} else if (p_note==Note::CUT) {
	
		control.channel[p_track].aux_volume=0;
		control.channel[p_track].note_end_flags|=END_NOTE_OFF;
		control.channel[p_track].note_end_flags|=END_NOTE_KILL;
		return aux_result;

	} else if ((p_note==Note::OFF) && (song->has_instruments())) {

		if (control.channel[p_track].instrument_ptr!=NULL) {
			
			control.channel[p_track].note_end_flags|=END_NOTE_OFF;

			if (!control.channel[p_track].instrument_ptr->get_volume_envelope()->is_enabled() || control.channel[p_track].instrument_ptr->get_volume_envelope()->is_loop_enabled()) {

				control.channel[p_track].note_end_flags|=END_NOTE_FADE;
			}
        	}

		return aux_result;
	} else return aux_result; // invalid note!


	if ( (p_instrument>=0) && (p_instrument<Song::MAX_INSTRUMENTS)) {
		new_instrument=process_new_instrument(p_track,p_instrument);
	
		if ( song->has_instruments() ) {
			// If we're in instrument mode...
			if ( control.channel[p_track].instrument_ptr->get_sample_number(control.channel[p_track].real_note) >= Song::MAX_SAMPLES) {
	
				control.channel[p_track].kick=KICK_NOTHING;
				return aux_result;
	
			} else {
				dest_sample_index=control.channel[p_track].instrument_ptr->get_sample_number(control.channel[p_track].real_note);
				control.channel[p_track].note=control.channel[p_track].instrument_ptr->get_note_number(control.channel[p_track].real_note);
			}
	
		} else {
			// If we're in sample mode...
			dest_sample_index=control.channel[p_track].instrument_index;
				control.channel[p_track].note=control.channel[p_track].real_note;
		}
	
		control.channel[p_track].sample_index=dest_sample_index;
		aux_sample=song->get_sample(dest_sample_index);
		
		if (!SampleManager::get_singleton()->check( aux_sample->get_sample_data() )) {
			/* INVALID SAMPLE */
			control.channel[p_track].kick=KICK_NOTHING;
			return aux_result;
			
		}
		
		aux_sample=song->get_sample(dest_sample_index);
	} else {
		
		
		if (!control.channel[p_track].sample_ptr)
			return aux_result;
		
		if (song->has_instruments()) {
			
			if (!control.channel[p_track].instrument_ptr)
				return aux_result;
			
			control.channel[p_track].note=control.channel[p_track].instrument_ptr->get_note_number(control.channel[p_track].real_note);
			
		} else {
						
			control.channel[p_track].note=control.channel[p_track].real_note;
			
		}
		
		aux_sample=control.channel[p_track].sample_ptr;
		
	}

	
	
	if (p_instrument>=Song::MAX_INSTRUMENTS && control.channel[p_track].sample_ptr!=aux_sample) {

		control.channel[p_track].new_instrument=(control.channel[p_track].period>0);
	}

	control.channel[p_track].sample_ptr=aux_sample;

	/* channel or instrument determined panning ? */

	control.channel[p_track].panning=control.channel[p_track].channel_panning;

	/* set filter,if any ? */	
	

	if (aux_sample->is_pan_enabled()) {
				
		control.channel[p_track].panning=(int)aux_sample->get_pan()*255/64;

	} else if ( song->has_instruments() && (control.channel[p_track].instrument_ptr->is_pan_default_enabled()) ) {

		control.channel[p_track].panning=(int)control.channel[p_track].instrument_ptr->get_pan_default_amount()*255/64;
	}


	if (song->has_instruments()) {

		
                /* Pitch-Pan Separation */
		if ((control.channel[p_track].instrument_ptr->get_pan_pitch_separation()!=0) && (control.channel[p_track].channel_panning!=PAN_SURROUND)){

			control.channel[p_track].panning+=((control.channel[p_track].real_note-control.channel[p_track].instrument_ptr->get_pan_pitch_center())*control.channel[p_track].instrument_ptr->get_pan_pitch_separation())/8;

			if (control.channel[p_track].panning<PAN_LEFT) control.channel[p_track].panning=PAN_LEFT;
			if (control.channel[p_track].panning>PAN_RIGHT) control.channel[p_track].panning=PAN_RIGHT;
		}

		/* Random Volume Variation */
		if (control.channel[p_track].instrument_ptr->get_volume_random_variation()>0) {

			control.channel[p_track].random_volume_variation=100-(random_generate(&control.random_seed) % control.channel[p_track].instrument_ptr->get_volume_random_variation());

		} else {

			control.channel[p_track].random_volume_variation=100;
		}


		/* Random Pan Variation */
		if ((control.channel[p_track].instrument_ptr->get_pan_random_variation()>0) && (control.channel[p_track].panning!=PAN_SURROUND)){

			int aux_pan_modifier;

			aux_pan_modifier=(random_generate(&control.random_seed) % (control.channel[p_track].instrument_ptr->get_pan_random_variation() << 2));
			if ((random_generate(&control.random_seed) % 2)==1) aux_pan_modifier=0-aux_pan_modifier; /* it's 5am, let me sleep :) */

			control.channel[p_track].panning+=aux_pan_modifier;

			if (control.channel[p_track].panning<PAN_LEFT) control.channel[p_track].panning=PAN_LEFT;
			if (control.channel[p_track].panning>PAN_RIGHT) control.channel[p_track].panning=PAN_RIGHT;
			

		}

		/*filter*/
		
		if (control.channel[p_track].instrument_ptr->filter_use_default_cutoff()) {
		
			control.channel[p_track].filter.it_cutoff=control.channel[p_track].instrument_ptr->get_filter_default_cutoff()*2;
		
		}
		
		if (control.channel[p_track].instrument_ptr->filter_use_default_resonance()) {
		
			control.channel[p_track].filter.it_reso=control.channel[p_track].instrument_ptr->get_filter_default_resonance()*2;
		
		}
		
		/*envelopes*/
		
		
		control.channel[p_track].volume_envelope_on=control.channel[p_track].instrument_ptr->get_volume_envelope()->is_enabled();
		control.channel[p_track].panning_envelope_on=control.channel[p_track].instrument_ptr->get_pan_envelope()->is_enabled();
		control.channel[p_track].pitch_envelope_on=control.channel[p_track].instrument_ptr->get_pitch_filter_envelope()->is_enabled();
		control.channel[p_track].NNA_type=control.channel[p_track].instrument_ptr->get_NNA_type();
		control.channel[p_track].duplicate_check_type=control.channel[p_track].instrument_ptr->get_DC_type();
		control.channel[p_track].duplicate_check_action=control.channel[p_track].instrument_ptr->get_DC_action();


	} else {

		control.channel[p_track].NNA_type=Instrument::NNA_NOTE_CUT;
		control.channel[p_track].duplicate_check_type=Instrument::DCT_DISABLED;
		control.channel[p_track].duplicate_check_action=Instrument::DCA_NOTE_CUT;
	}


	if (p_instrument<Song::MAX_INSTRUMENTS) { // instrument change
		
		control.channel[p_track].volume=control.channel[p_track].aux_volume=aux_sample->get_default_volume();

	}


	control.channel[p_track].slide_to_period=control.channel[p_track].aux_period=get_period((Uint16)(control.channel[p_track].note)<<1,SampleManager::get_singleton()->get_c5_freq( (aux_sample->get_sample_data())));

	control.channel[p_track].note_end_flags=END_NOTE_NOTHING; /* clears flags */

	return true;
}