示例#1
0
void generateRandomeAdjacency(int n,const char *filename){
	FILE *f = fopen(filename,"w");
	int adj[n][n];
	for(int i=0;i<n;i++){
		loadBar(i,n,50,50);
		for(int j=0;j<i;j++){
			int con = rand()%4;
			if(con == 0){
				adj[i][j] = 0;
				adj[j][i] = 0;
			}else{
				adj[i][j] = 1;
				adj[j][i] = 1;
			}
		}
		adj[i][i] = 0;
	}
	for(int i=0;i<n;i++){
		for(int j=0;j<n;j++){
			fprintf(f," %d ",adj[i][j]);
		}
		fprintf(f,"\n");
	}
	fclose(f);
	return;
}
示例#2
0
size_t rewire_bipartite(unsigned short *matrix,size_t ncol, size_t nrow,size_t max_iter,size_t verbose,unsigned int seed)
{


	set_rand(seed);
	size_t i,j,kk,n,e=0,rand1,rand2;
	size_t *from;
	size_t a,b,c,d;
	size_t *to;

	for(i=0;i<nrow;++i)
		for(j=0;j<ncol;++j)
            e+=matrix[i*ncol+j];

	do	from=(size_t*)calloc(e,sizeof(size_t));	while(from==NULL);

	do	to=(size_t*)calloc(e,sizeof(size_t));	while(to==NULL);
	kk=0;
	for(i=0;i<nrow;++i)
		for(j=0;j<ncol;++j)
			if(matrix[i*ncol+j]==1)
				{
					from[kk]=i;
					to[kk]=j;
					kk++;
				}
	//GetRNGstate();
	time_t  tin,tfin;
	tin = time (NULL);
	for(n=0;n<max_iter;n++)
	{
		//random rewiring
		if(verbose==1)
    	loadBar( n,  max_iter, 100,  50);
		rand1=(size_t) (unif_rand()*e);
		do  rand2=(size_t) (unif_rand()*e);while (rand1==rand2);
		a=from[rand1];
		c=from[rand2];
		b=to[rand1];
		d=to[rand2];
		if(a!=c && d!=b && matrix[a*ncol+d]==0 && matrix[c*ncol+b]==0)
			{
				to[rand1]=d;
				to[rand2]=b;
				matrix[a*ncol+d]=matrix[c*ncol+b]=1;
				matrix[a*ncol+b]=matrix[c*ncol+d]=0;

			}

	}
	//PutRNGstate();
	tfin = time (NULL);
	if(verbose==1)
    printf("DONE in %d seconds \n",-(tin-tfin));


return 0;

}
示例#3
0
size_t rewire_sparse_bipartite(size_t *from,size_t *to,size_t nc,size_t nr,size_t max_iter,size_t e,size_t verbose,unsigned int seed)
{


	set_rand(seed);
	size_t i,j,kk,n,rand1,rand2;
 	size_t a,b,c,d;
	size_t *index;
	size_t *pos;
	do	index = (size_t*)calloc( (nr+1),sizeof(size_t ));	while(index==NULL);
	do	pos = (size_t*)calloc(e,sizeof(size_t ));	 while(pos==NULL);
	index[0]=0;
  pos[0]=0;
	kk=1;
  j=0;
	for( i=1;i<e;i++)
    {
			if(from[i]!=from[i-1])
        {
					index[kk++]=i;
          j++;
        }
        pos[i]=j;
    }
    index[nr]=e;
	//GetRNGstate();
	time_t  tin,tfin;
	tin = time (NULL);

	for(n=0;n<max_iter;n++)
	{

		//random rewiring
  	if(verbose==1)
			loadBar( n,  max_iter, 100,  50);
		rand1=(size_t) (unif_rand()*e);
		do rand2=(size_t) (unif_rand()*e); while (rand1==rand2);
		a=from[rand1];
		c=from[rand2];
		b=to[rand1];
		d=to[rand2];
		if(a!=c && d!=b &&  check(pos,to,index,rand1,b,rand2,d,e,nr)==1 )
        {
						to[rand1]=d;
            to[rand2]=b;

            //printf("Rewire ok!\n");
        }

	}
	tfin = time (NULL);
	//PutRNGstate();
	if(verbose==1)
		printf("DONE in %d seconds \n",-(tin-tfin));
	return 0;


}
示例#4
0
GThreadFunc barra_de_progreso(){
	FILE *pcap = NULL;
	while(running && nids_params.pcap_desc != NULL){
		pcap = pcap_file(nids_params.pcap_desc);
		if(pcap == 0) break;
		pcap_position = ftell(pcap);
		if(pcap_position == -1L) break;
		loadBar(pcap_position, pcap_size, pcap_size, 40);
		usleep(500000);
	}
	
	return NULL;
}
示例#5
0
void loadsounds()
{
	//printf("loadsound\n");
        sfzreg* r=regions;
	printf("\n");
	int x=0;
        while(r!=NULL)
        {
		//TODO evita i duplicati
                if(r->sample!=NULL) r->sound=addsound(trimwhitespace(r->sample));
                r=(sfzreg*)r->next;
		loadBar(x,nregions,BARRESOLUTION,BARWIDTH);
		x++;
        }
	printf("\n");
}
示例#6
0
void generateQueryFile(int n,int k,const char *filename){
	std::vector<int> nodeList;
	nodeList.resize(n);
	for(int i=0;i<n;i++){
		nodeList[i] = i;
	}
	std::vector<int> Query = selectKItems(nodeList,n,k);

	FILE *f = fopen(filename,"w");
	for(int i=0;i<Query.size();i++){
		loadBar(i,n,50,50);
		fprintf(f, "%d ",Query[i]);
	}
	fprintf(f, "-1");
	fclose(f);
	return;
}
示例#7
0
void scan_folder(char *dir)
{
	DIR *dp;
	struct dirent *ep;
	char *binaryfile;
	char *sha1;
	char path[PATH_MAX +1];
	char fullpath[PATH_MAX +1];
	char msgError[PATH_MAX +1];
	
	dp = opendir(dir);
	if (dp != NULL) {
		while (ep = readdir (dp)) {
			
			if (ep->d_type != DT_DIR) {
				if (ep->d_type == DT_REG) {
					filesProcessed++;
					loadBar(filesProcessed,totalFiles,50,50);
					/* printf("%ld-%ld\n", filesProcessed, totalFiles); */
				
					sprintf(fullpath,"%s/%s", dir, ep->d_name);
					/* write_uri_file(fullpath); */
					binaryfile = get_binary_of_file(fullpath);
					sha1 = get_sha1(binaryfile);
					/* printf("%s - %s\n", fullpath, sha1); */
				}	
			}
			
			if (ep->d_type == DT_DIR) {
				if ((strcmp(ep->d_name, ".") != 0) && (strcmp(ep->d_name, "..") != 0)) {
					strcpy(path, "");
					strcat(path, dir);
					strcat(path, "/");
					strcat(path, ep->d_name);
					scan_folder(path);
				}
			}
		}
		(void) closedir (dp);
	}
	else {
		sprintf(msgError,"Could't open the directory - %s", dir);
		perror(msgError);
	}	
}
示例#8
0
void generateFeatureFile(int n,int fSize,const char *filename){
	int feature[n][fSize];
	for(int i=0;i<n;i++){
		loadBar(i,n,50,50);
		for(int j=0;j<fSize;j++){
			feature[i][j] = rand()%10;
		}
	}
	FILE *f = fopen(filename,"w");

	for(int j=0;j<fSize;j++){
		for(int i=0;i<n;i++){
			fprintf(f, " %d ", feature[i][j]);
		}
		fprintf(f, "\n");
	}

	fclose(f);
	return;
}
unsigned char* receiveFile(size_t* fileSize, char** fileName) {
	size_t fileSizeReceived;
	size_t fileSizeDone;
	size_t fileSizeLeft;
	unsigned int expectedSequence = 0;
	unsigned int fileIndexToCopyTo = 0;
	unsigned char* file;

	unsigned char* startPacket = malloc(applicationLayerConf.maxPacketSize);
	if(startPacket == NULL) {
		printf("Failed to allocate memory for startPacket, terminating\n");
		return NULL;
	}

	int receptionRes = receiveData(startPacket, applicationLayerConf.maxPacketSize);

	if(receptionRes == -2) {
		//We received a disconnect, end reception
		printf("Received disconnect order, terminating reception\n");
		free(startPacket);
		return NULL;
	}
	else if(receptionRes != -1) {
		if(startPacket[CONTROL_INDEX] == CONTROL_START) {

			unsigned char fileSizeSize = startPacket[FILESIZE_SIZE_INDEX];
			unsigned char fileNameSize = startPacket[FILENAME_SIZE_INDEX(fileSizeSize)];

			memcpy(&fileSizeReceived, &startPacket[FILESIZE_INDEX], fileSizeSize);

			char fileNameReceived[fileNameSize+1];
			memcpy(fileNameReceived, &startPacket[FILENAME_INDEX(fileSizeSize)], fileNameSize);
			fileNameReceived[fileNameSize] = '\0';

            *fileName = malloc(FILENAME_LEN);

			memcpy(*fileName, fileNameReceived, fileNameSize+1);

			*fileSize = fileSizeReceived;
			fileSizeLeft = fileSizeReceived;
			fileSizeDone = 0;
			file = malloc(fileSizeReceived);
			if(file == NULL) {
				printf("Failed to allocate memory for the file buffer, terminating\n");
				free(startPacket);
				return NULL;
			}
		}
	}
	else {
		printf("Failed to receive start packet data\n");
		free(startPacket);
		return NULL;
	}

	unsigned char* packet = malloc(applicationLayerConf.maxPacketSize);
	if(packet == NULL) {
		printf("Failed to allocate memory for packet, terminating\n");
		free(startPacket);
		return NULL;
	}
	unsigned int transmissionOver = 0;
	unsigned int barIndex = 0;

	//Calculate the number of packets we will need based on the defined maximum packet size
	unsigned long numberOfPackets = fileSizeReceived / applicationLayerConf.maxDataFieldSize;
	//Checks the remainder of previous division to check if we need an extra packet or not
	if((fileSizeReceived % applicationLayerConf.maxDataFieldSize) > 0)
		numberOfPackets++;

	loadBar(barIndex, (int)numberOfPackets, (int)numberOfPackets, 50, fileSizeDone, fileSizeReceived);
	barIndex++;

	while(!transmissionOver) {
		receptionRes = receiveData(packet, applicationLayerConf.maxPacketSize);
		if(receptionRes == -2) {
			//We received a disconnect, end reception
			printf("Received disconnect order, terminating reception\n");
			free(startPacket);
			free(file);
			free(packet);
			return NULL;
		}
		else if(receptionRes != -1) {
			if(packet[CONTROL_INDEX] == CONTROL_END) {
				transmissionOver = 1;
				printf("\n\n");
			}
			else if(packet[CONTROL_INDEX] == CONTROL_DATA && packet[SEQUENCE_INDEX] == expectedSequence) {
				unsigned char l1 = packet[L1_INDEX];
				unsigned char l2 = packet[L2_INDEX];

				size_t dataSize = 256 * l2 + l1;

				memcpy(&file[fileIndexToCopyTo], &packet[DATA_INDEX], dataSize);
				fileIndexToCopyTo += dataSize;
				fileSizeDone += dataSize;
				fileSizeLeft -= dataSize;
				loadBar(barIndex, (int)numberOfPackets, (int)numberOfPackets, 50, fileSizeDone, fileSizeReceived);
				barIndex++;
				expectedSequence++;
				if(expectedSequence > 255)
					expectedSequence = 0;
			}
		}
		else {
			printf("Failed to receive packet data\n");
			free(startPacket);
			free(file);
			free(packet);
			return NULL;
		}
	}
	if(fileSizeLeft == 0 && compareControlPackets(startPacket, packet) == 0) {
		free(startPacket);
		free(packet);
		return file;
	}
	else {
		if(fileSizeLeft != 0)
			printf("Didn't receive the expected byte number\n");
		if(compareControlPackets(startPacket, packet) != 0)
			printf("Start and end packets are different\n");

		free(startPacket);
		free(file);
		free(packet);

		return NULL;
	}
}
示例#10
0
size_t analysis(unsigned short *incidence,size_t ncol,size_t nrow,double *scores,size_t step,size_t max_iter,size_t verbose,unsigned int seed)
{


	set_rand(seed);
	size_t i,j,kk,n,rand1,rand2;
	size_t dim=max_iter+1;
	size_t *from;
  	size_t *to;
  	unsigned short *matrix;

	size_t a,b,c,d,e=0;
	size_t index=1;
  do matrix=(unsigned short *)calloc(nrow*ncol,sizeof(unsigned short)); while(matrix==NULL);
	for(i=0;i<nrow;++i)
	{
		
    for(j=0;j<ncol;++j)
			{
				matrix[i*ncol+j]=incidence[i*ncol+j];
				e+=incidence[i*ncol+j];
			}
  }
	//initialization of score vector overwriting the original
	//do	scores=(double*)calloc(dim,sizeof(double));	while(scores==NULL);
	for(i=0;i<dim;scores[i++]=0.0);
	scores[0]=1.0;
 	do	from=(size_t*)calloc(e,sizeof(size_t));	while(from==NULL);
	do	to=(size_t*)calloc(e,sizeof(size_t));	  while(to==NULL);
 	kk=0;
	for(i=0;i<nrow;++i)
		for(j=0;j<ncol;++j)
			if(matrix[i*ncol+j]==1)
				{
					from[kk]=i;
					to[kk]=j;
					kk++;
				}
	time_t  tin,tfin;
	tin = time (NULL);
	//GetRNGstate();
	for(n=0;n<max_iter;n++)
	{
		//random rewiring
    if(verbose==1)
  		loadBar( n,  max_iter, 100,  50);
		rand1=(size_t) (unif_rand()*e);
		do	rand2=(size_t) (unif_rand()*e);	while (rand1==rand2);
		a=from[rand1];
		c=from[rand2];
		b=to[rand1];
		d=to[rand2];
		//printf("%d %d %d %d %d %d %d %d %d\n",e,a,b,c,d,rand1,rand2,t,n);
		if(a!=c && d!=b && incidence[a*ncol+d]==0 && incidence[c*ncol+b]==0)
			{
				to[rand1]=d;
				to[rand2]=b;
				incidence[a*ncol+d]=incidence[c*ncol+b]=1;
				incidence[a*ncol+b]=incidence[c*ncol+d]=0;

			}

			if(n%step==0)
			(scores)[index++]=similarity(incidence,matrix, ncol,nrow, e);
	}
	tfin = time (NULL);
	//PutRNGstate();
	if(verbose==1)
    printf("DONE in %d seconds \n",-(tin-tfin));

	return (index-1);
}
示例#11
0
size_t rewire_ex(unsigned short *incidence,size_t ncol, size_t nrow,size_t max_iter,size_t verbose,size_t MAXITER,unsigned int seed)
{


	set_rand(seed);

 	size_t i,j,kk,n,rand1,rand2,t=0;
	size_t e=0;
    //copy of the original incidence matrix
	size_t *from;
	size_t *to;
	size_t a,b,c,d;


	for(i=0;i<nrow;i++)
		for(j=0;j<ncol;j++)
			e+=incidence[i*ncol+j];


	e/=2;
	//initialization of score vector overwriting the original TO CHECK
	do from=(size_t*)calloc(e,sizeof(size_t)); while(from==NULL);
	do to=(size_t*)calloc(e,sizeof(size_t));   while(to==NULL);
	kk=0;
	for(i=0;i<nrow;++i)
		for(j=0;j<i;++j)
			if(incidence[i*ncol+j]==1)
				{
					from[kk]=i;
					to[kk]=j;
          kk++;
        }
	time_t  tin,tfin;
  tin = time (NULL);

 	//GetRNGstate();
	for(n=0;n<max_iter;t++)
		{
			if(verbose==1)
				loadBar( n,  max_iter, 100,  50);
		//random rewiring
		  rand1=(size_t) (unif_rand()*e);
      do rand2=(size_t) (unif_rand()*e); while (rand1==rand2);
      a=from[rand1];
      c=from[rand2];
      b=to[rand1];
      d=to[rand2];
	if(t>MAXITER)
			{
				tfin = time (NULL);
 				if(verbose==1)
    		printf("DONE in %d seconds \n",-(tin-tfin));
				//PutRNGstate();
				return (-1);

			}
		//  printf("%d %d %d %d %d %d %d %d %d %d\n ",rand1,rand2,a+1,b+1,c+1,d+1,incidence[a*ncol+d],incidence[c*ncol+b],incidence[a*ncol+c],incidence[d*ncol+b]);
     if(a!=c && b!=d&&  a!=d && c!=b &&
           (	(incidence[a*ncol+d]==0 && incidence[c*ncol+b]==0  ) ||
            (incidence[a*ncol+c]==0 && incidence[d*ncol+b]==0  ) ))
        {
            if(incidence[a*ncol+d]==0 && incidence[c*ncol+b]==0 && incidence[a*ncol+c]==0 && incidence[d*ncol+b]==0 )
            {
                if(unif_rand()>=0)
                {
                    incidence[a*ncol+d]=1;incidence[d*ncol+a]=1;
                    incidence[c*ncol+b]=1;incidence[b*ncol+c]=1;
                    incidence[a*ncol+b]=0;incidence[b*ncol+a]=0;
                    incidence[c*ncol+d]=0;incidence[d*ncol+c]=0;
                    to[rand1]=d;
                    to[rand2]=b;
                    n++;

                }
                else
                {
                    incidence[a*ncol+c]=1;incidence[c*ncol+a]=1;
                    incidence[d*ncol+b]=1;incidence[b*ncol+d]=1;
                    incidence[a*ncol+b]=0;incidence[b*ncol+a]=0;
                    incidence[c*ncol+d]=0;incidence[d*ncol+c]=0;
                    //	from[rand1]=d;
                    to[rand1]=c;
                    from[rand2]=b;
                    to[rand2]=d;

                    n++;

                }
            }
            else
                if(incidence[a*ncol+d]==0 && incidence[c*ncol+b]==0)
                {
                    incidence[a*ncol+d]=1;incidence[d*ncol+a]=1;
                    incidence[c*ncol+b]=1;incidence[b*ncol+c]=1;
                    incidence[a*ncol+b]=0;incidence[b*ncol+a]=0;
                    incidence[c*ncol+d]=0;incidence[d*ncol+c]=0;
                    to[rand1]=d;
                    to[rand2]=b;
                    n++;
                }
                else
                {
                    incidence[a*ncol+c]=1;incidence[c*ncol+a]=1;
                    incidence[d*ncol+b]=1;incidence[b*ncol+d]=1;
                    incidence[a*ncol+b]=0;incidence[b*ncol+a]=0;
                    incidence[c*ncol+d]=0;incidence[d*ncol+c]=0;
                    to[rand1]=c;
                    from[rand2]=b;
                    to[rand2]=d;
                    n++;
                }
        }
    }
	tfin = time (NULL);
 	if(verbose==1)
    printf("DONE in %d seconds \n",-(tin-tfin));
	//PutRNGstate();

	return 0;


}
示例#12
0
size_t analysis_undirected_ex(unsigned short *incidence,size_t ncol, size_t nrow,double *scores,size_t step,size_t max_iter,size_t verbose,size_t MAXITER,unsigned int seed)
{


	set_rand(seed);


	size_t i,j,kk,n,index,rand1,rand2,t=0;
	size_t dim=(size_t)round((double)max_iter/step)+2;
	size_t e=0;
    //copy of the original incidence matrix
    unsigned short *matrix;
	size_t *from;
	size_t *to;
	size_t a,b,c,d;

	do	matrix=(unsigned short *)calloc(nrow*ncol,sizeof(unsigned short));	while(matrix==NULL);
	for(i=0;i<nrow;i++)
		{
			for(j=0;j<ncol;j++)
        {
            matrix[i*ncol+j]=incidence[i*ncol+j];
            e+=incidence[i*ncol+j];
        }
	}
	e/=2;
	//initialization of score vector overwriting the original TO CHECK
	do	from=(size_t*)calloc(e,sizeof(size_t));	while(from==NULL);
	do 	to=(size_t*)calloc(e,sizeof(size_t));    while(to==NULL);
	kk=0;
	for(i=0;i<nrow;++i)
		for(j=0;j<i;++j)
			if(matrix[i*ncol+j]==1)
				{
                from[kk]=i;
                to[kk]=j;
                kk++;
				}
	for(i=0;i<dim;scores[i++]=0.0);
	scores[0]=1.0;
	//RANDOM GENERATOR (MILLISECONDS)
	//GetRNGstate();
	index=1;
	time_t  tin,tfin;
	tin = time (NULL);
	for(n=0;n<max_iter;t++)
	{
		if(verbose==1)
			loadBar( n,  max_iter, 100,  50);
		//random rewiring

		rand1=(size_t) (unif_rand()*e);
		do	rand2=(size_t) (unif_rand()*e);	while (rand1==rand2);
		a=from[rand1];
		c=from[rand2];
		b=to[rand1];
		d=to[rand2];
		if(t>MAXITER)
		{
			tfin = time (NULL);
			//PutRNGstate();
			if(verbose==1)
  	  printf("DONE in %d seconds \n",-(tin-tfin));

			printf("Reached the maximum number admissible of iterations!\n");
			return (index-1);
		}
		//printf("a=%d b=%d c=%d d=%d\n ",a+1,b+1,c+1,d+1);
		if( a!=d && c!=b &&
           (	(incidence[a*ncol+d]==0 && incidence[c*ncol+b]==0  ) ||
            (incidence[a*ncol+c]==0 && incidence[d*ncol+b]==0  ) ))
        {
            if(incidence[a*ncol+d]==0 && incidence[c*ncol+b]==0 && incidence[a*ncol+c]==0 && incidence[d*ncol+b]==0 )
            {
                if(unif_rand()>=0.5)
                {
                    incidence[a*ncol+d]=1;incidence[d*ncol+a]=1;
                    incidence[c*ncol+b]=1;incidence[b*ncol+c]=1;
                    incidence[a*ncol+b]=0;incidence[b*ncol+a]=0;
                    incidence[c*ncol+d]=0;incidence[d*ncol+c]=0;
                    to[rand1]=d;
                    to[rand2]=b;
										n++	; if(n%step==0)
            {
								(scores)[index++]=similarity_undirected(matrix,incidence,ncol,nrow,e);
										//printf("%lf \n",(*scores)[index-1]);
						}
                }
                else
                {
                    incidence[a*ncol+c]=1;incidence[c*ncol+a]=1;
                    incidence[d*ncol+b]=1;incidence[b*ncol+d]=1;
                    incidence[a*ncol+b]=0;incidence[b*ncol+a]=0;
                    incidence[c*ncol+d]=0;incidence[d*ncol+c]=0;
                    //	from[rand1]=d;
                    to[rand1]=c;
                    from[rand2]=b;
                    to[rand2]=d;
                    n++	; if(n%step==0)
            {
								(scores)[index++]=similarity_undirected(matrix,incidence,ncol,nrow,e);
										//printf("%lf \n",(*scores)[index-1]);
						}

                }
            }
            else
                if(incidence[a*ncol+d]==0 && incidence[c*ncol+b]==0)
                {
                    incidence[a*ncol+d]=1;incidence[d*ncol+a]=1;
                    incidence[c*ncol+b]=1;incidence[b*ncol+c]=1;
                    incidence[a*ncol+b]=0;incidence[b*ncol+a]=0;
                    incidence[c*ncol+d]=0;incidence[d*ncol+c]=0;
                    to[rand1]=d;
                    to[rand2]=b;
                    n++	; if(n%step==0)
            {
								(scores)[index++]=similarity_undirected(matrix,incidence,ncol,nrow,e);
										//printf("%lf \n",(*scores)[index-1]);
						}
                }
                else
                {
                    incidence[a*ncol+c]=1;incidence[c*ncol+a]=1;
                    incidence[d*ncol+b]=1;incidence[b*ncol+d]=1;
                    incidence[a*ncol+b]=0;incidence[b*ncol+a]=0;
                    incidence[c*ncol+d]=0;incidence[d*ncol+c]=0;
                    to[rand1]=c;
                    from[rand2]=b;
                    to[rand2]=d;
                   n++	;
						if(n%step==0)
            {
								(scores)[index++]=similarity_undirected(matrix,incidence,ncol,nrow,e);
										//printf("%lf \n",(*scores)[index-1]);
						}
                }
        }



	}

	tfin = time (NULL);
	if(verbose==1)
    printf("DONE in %d seconds \n",-(tin-tfin));

  //PutRNGstate();
	return (index-1);
}
示例#13
0
void Renderer::render()
{
  std::vector<ngl::Colour> colourStack;
  for(int y = 0; y < m_film->m_height; y++)
  {
    for(int x = 0; x < m_film->m_width; x++)
    {
      int current_pixel = y*m_film->m_height + x;
      int total_number_of_pixels = m_film->m_height * m_film->m_width;
      int r = 90;
      int w = 45;

      loadBar(current_pixel, total_number_of_pixels, r, w);

      ngl::Colour finalColour;
      if(m_anti_aliasing)
      {
        for(int aay = 0; aay < m_anti_aliasing; aay++)
        {
          for(int aax = 0; aax < m_anti_aliasing; aax++)
          {
            // calculate the primary ray
            float x_amount = ( (float)x + ((float)aax / (float)m_anti_aliasing) + 0.5f * ((float)aax / (float)m_anti_aliasing) ) / (float)m_film->m_width;
            float y_amount = ( (float)y + ((float)aay / (float)m_anti_aliasing) + 0.5f * ((float)aay / (float)m_anti_aliasing) ) / (float)m_film->m_width;

            ngl::Vec3 cam_ray_dir = m_camera->m_dir + (m_camera->m_right * (x_amount - 0.5) + (m_camera->m_down * (y_amount - 0.5)));
            cam_ray_dir.normalize();

            // fire the ray and store its colour into a variable
            ngl::Colour col = trace(m_camera->m_pos, cam_ray_dir, 0);

            colourStack.push_back(col);
          }
        }

        // AVERAGE COLOURS
        float cRed   = 0.0f;
        float cGreen = 0.0f;
        float cBlue  = 0.0f;

        for(int i = 0; i < m_anti_aliasing; i++)
        {
          cRed    += colourStack.at(i).m_r;
          cGreen  += colourStack.at(i).m_g;
          cBlue   += colourStack.at(i).m_b;
        }

        cRed   /= (float)m_anti_aliasing;
        cGreen /= (float)m_anti_aliasing;
        cBlue  /= (float)m_anti_aliasing;

        finalColour = ngl::Colour(cRed, cGreen, cBlue, 1);

        // FLUSH VECTOR
        colourStack.clear();
      }

      else // there is anti-aliasing
      {
        float x_amount = (x+0.5)/(float)m_film->m_width;
        float y_amount = ((y) + 0.5)/(float)m_film->m_height;

        ngl::Vec3 cam_ray_dir = m_camera->m_dir + (m_camera->m_right * (x_amount - 0.5) + (m_camera->m_down * (y_amount - 0.5)));
        cam_ray_dir.normalize();

        // fire the ray and store its colour into a variable
        finalColour = trace(m_camera->m_pos, cam_ray_dir, 0);
      }

      // write pixel into the Film object associated to the Render object
      m_film->writePixel(finalColour);
    }
  }


  // write the file into disk afterwards and display it
  std::string imageFileName = m_image_name + ".ppm";
  m_film->writeFile(imageFileName.c_str());

}
示例#14
0
size_t rewire_sparse_ex(size_t *from, size_t *to,size_t *degree,size_t ncol, size_t nrow,size_t max_iter, size_t e,size_t verbose,size_t MAXITER,unsigned int seed)
{


	set_rand(seed);

 	size_t i,n,rand1,rand2,t=0;
    //copy of the original incidence matrix
	size_t a,b,c,d;
	size_t ad,cb,ac,bd;
	unsigned short *adj;
	size_t *cumdeg;
	do	cumdeg=(size_t *)calloc(nrow,sizeof(size_t)); while(cumdeg==NULL);
    cumdeg[0]=0;
	for(i=1;i<nrow;i++)
		{
			cumdeg[i]=cumdeg[i-1]+degree[i-1]+1;
		}
	adj=(unsigned short *)calloc(cumdeg[nrow-1]+degree[nrow-1]+1,sizeof(unsigned short)); while(adj==NULL);
	for(i=0;i<nrow;i++)
    	adj[cumdeg[i]+degree[i]]= degree[i];
    
	for(i=0;i<e;i++)
		{

			a=from[i];
			b=to[i];
			adj[cumdeg[a]+degree[a]-adj[cumdeg[a]+degree[a]]]=b;
			adj[cumdeg[a]+degree[a]]--;
			adj[cumdeg[b]+degree[b]-adj[cumdeg[b]+degree[b]]]=a;
			adj[cumdeg[b]+degree[b]]--;
    }

  //GetRNGstate();

  time_t  tin,tfin;
	tin = time (NULL);
	for(n=0;n<max_iter;t++)
	{
		if(verbose==1)
			loadBar( n,  max_iter, 100,  50);
		//random rewiring
		   rand1=(size_t) (unif_rand()*e);
        do   rand2=(size_t) (unif_rand()*e); while (rand1==rand2);
        a=from[rand1];
        c=from[rand2];
        b=to[rand1];
        d=to[rand2];

        ad=is_not(a,d,degree,adj,cumdeg);
        cb=is_not(c,b,degree,adj,cumdeg);
        ac=is_not(c,a,degree,adj,cumdeg);
        bd=is_not(b,d,degree,adj,cumdeg);
			if(t>MAXITER)
		{

			tfin = time (NULL);
			if(verbose==1)
		    printf("DONE in %d seconds \n",-(tin-tfin));
		   //PutRNGstate();
			return (-1);




			}
		  // printf("%d %d %d %d %d %d %d %d %d %d \n ",rand1, rand2,a+1,b+1,c+1,d+1,ad,cb,ac,bd);

        if( a!=c && b!=d & a!=d && c!=b && (( ad==1 && cb==1 )|| (ac==1 && bd==1) ))
        {
            if(ad==1 && cb==1 && ac==1 && bd==1 )
            {
                if(unif_rand()>=0.5)
                {

                    to[rand1]=d;
                    to[rand2]=b;
                    sub(a,b,c,d,degree,adj,cumdeg);

                    n++;
                }
                else
                {
                    sub2(a,b,c,d,degree,adj,cumdeg);

                    //	from[rand1]=d;
                    to[rand1]=c;
                    from[rand2]=b;
                    to[rand2]=d;
                               n++;

                }
            }
            else
                if(ad==1 && cb==1 )
                {

                    to[rand1]=d;
                    to[rand2]=b;
                    sub(a,b,c,d,degree,adj,cumdeg);


                    n++;
                }
                else
                {
                    sub2(a,b,c,d,degree,adj,cumdeg);


                    to[rand1]=c;
                    from[rand2]=b;
                    to[rand2]=d;
                    n++;
                }
        }


    }
  tfin = time (NULL);
  if(verbose==1)
 	 printf("DONE in %d seconds \n",-(tin-tfin));
  //PutRNGstate();
	return 0;
}
int sendFile(unsigned char* file, size_t fileSize, char* fileName) {
	if(fileSize > MAX_FILESIZE_ALLOWED) {
		printf("This file is too large to be sent!\n");
		return -1;
	}

	if(strlen(fileName) > (applicationLayerConf.maxPacketSize - (BASE_DATA_PACKET_SIZE + sizeof(size_t)) ) || strlen(fileName) > 255) {
		printf("The filename is too large!\n");
		return -1;
	}
	size_t startPacketSize;
	unsigned char* startPacket = createControlPacket(&startPacketSize, CONTROL_START, fileSize, fileName);
	size_t endPacketSize;
	unsigned char* endPacket = createControlPacket(&endPacketSize, CONTROL_END, fileSize, fileName);

	unsigned int sizeDone = 0;

	//Calculate the number of packets we will need based on the defined maximum packet size
	unsigned long numberOfPackets = fileSize / applicationLayerConf.maxDataFieldSize;
	//Checks the remainder of previous division to check if we need an extra packet or not
	if((fileSize % applicationLayerConf.maxDataFieldSize) > 0)
		numberOfPackets++;

	if(sendData(startPacket, startPacketSize) == -1) {
		free(startPacket);
		return -1;
	}
	free(startPacket);
	unsigned long currentPacket = 0;
	unsigned long currentSequence = 0;
	loadBar(currentPacket, numberOfPackets, numberOfPackets, 50, sizeDone, fileSize);
	for(; currentPacket < numberOfPackets; currentPacket++) {
		unsigned long dataFieldSize;
		if(currentPacket == numberOfPackets - 1) {
            //We do this to ensure we don't copy more than the needed bytes in the last packet
			dataFieldSize = fileSize - currentPacket * applicationLayerConf.maxDataFieldSize;
		}
		else
			dataFieldSize = applicationLayerConf.maxDataFieldSize;

		sizeDone += dataFieldSize;

		unsigned char dataField[applicationLayerConf.maxDataFieldSize];
		memcpy(dataField, &file[currentPacket * applicationLayerConf.maxDataFieldSize], dataFieldSize);
		unsigned char* dataPacket = createDataPacket(currentPacket, dataFieldSize, dataField);
		if(sendData(dataPacket, dataFieldSize + BASE_DATA_PACKET_SIZE) == -1) {
			free(dataPacket);
			return -1;
		}
		free(dataPacket);

		if(currentSequence > 255)
			currentSequence = 0;
		else
			currentSequence++;

		loadBar(currentPacket+1, numberOfPackets, numberOfPackets, 50, sizeDone, fileSize);
	}
	if(sendData(endPacket, endPacketSize) == -1) {
		free(endPacket);
		return -1;
	}
	printf("\n\n");
	free(endPacket);

	return 0;
}
示例#16
0
int main(void) {
char buf[80];
system("clear");
printf("\n\n\n ### GPU ENABLED CODE\n");
printf("\n ### Host creating two input vectors and one output vector\n");
    unsigned i,  LIST_SIZE;
    FILE *fp0;

    fp0 = fopen("data.txt", "r");
    if (!fp0) {
        fprintf(stderr, "Failed to load data.txt.\n");
        exit(1);
    }
    fgets(buf, sizeof(buf),  fp0);
    sscanf(buf,"%d", &LIST_SIZE);
    printf(" ### Vector_size:%d elements, Elem_size:%lu byte\n", LIST_SIZE, sizeof(int));
    fclose(fp0);

    int *A = (int*)malloc(sizeof(int)*LIST_SIZE);
    if (A == NULL) {
    fprintf(stderr, "failed to allocate memory.\n");
    return -1;
    }

    int *B = (int*)malloc(sizeof(int)*LIST_SIZE);
    if (B == NULL) {
    fprintf(stderr, "failed to allocate memory.\n");
    return -1;
    }

    int *C = (int*)malloc(sizeof(int)*LIST_SIZE);
    if (C == NULL) {
    fprintf(stderr, "failed to allocate memory.\n");
    return -1;
    }

printf("\n Host initialising input vector values\n");
    for(i = 0; i < LIST_SIZE; i++) {
        A[i] = /*randomInit()*/ i; 
        B[i] = /*randomInit()*/ LIST_SIZE-i;
        loadBar(i, LIST_SIZE, 100, 2);
    }

printf("\n Setting up GPU\n");    
    // Load the kernel source code into the array source_str
    FILE *fp;
    char *source_str;
    size_t source_size;

    fp = fopen("vec.cl", "r");
    if (!fp) {
        fprintf(stderr, "Failed to load kernel.\n");
        exit(1);
    }
    source_str = (char*)malloc(MAX_SOURCE_SIZE);
    source_size = fread( source_str, 1, MAX_SOURCE_SIZE, fp);
    fclose( fp );

    // Get platform and device information
    cl_platform_id platform_id = NULL;
    cl_device_id device_id = NULL;   
    cl_uint ret_num_devices;
    cl_uint ret_num_platforms;
    cl_int ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms);
    printf("Check platform id %s\n", getErrorString(ret));
    ret = clGetDeviceIDs( platform_id, CL_DEVICE_TYPE_CPU, 1, 
            &device_id, &ret_num_devices);
printf("device_id:%u, device_count:%u\n", (int) device_id, ret_num_devices);
     printf("Check device id %s\n", getErrorString(ret));

    // Create an OpenCL context
    cl_context context = clCreateContext( NULL, 1, &device_id, NULL, NULL, &ret);
     printf("Check context %s\n", getErrorString(ret));

    // Create a command queue
    cl_command_queue command_queue = clCreateCommandQueue(context, device_id, 0, &ret);
     printf("Check command queue %s\n", getErrorString(ret));

    // Create memory buffers on the device for each vector 
    cl_mem a_mem_obj = clCreateBuffer(context, CL_MEM_READ_ONLY, 
            LIST_SIZE * sizeof(int), NULL, &ret);
     printf("Check a_mem_obj %s\n", getErrorString(ret));
    cl_mem b_mem_obj = clCreateBuffer(context, CL_MEM_READ_ONLY,
            LIST_SIZE * sizeof(int), NULL, &ret);
     printf("Check b_mem_obj %s\n", getErrorString(ret));
    cl_mem c_mem_obj = clCreateBuffer(context, CL_MEM_WRITE_ONLY, 
            LIST_SIZE * sizeof(int), NULL, &ret);
     printf("Check c_mem_obj %s\n", getErrorString(ret));

// <-
    // Create a program from the kernel source
    cl_program program = clCreateProgramWithSource(context, 1, 
            (const char **)&source_str, (const size_t *)&source_size, &ret);
     printf("Check program %s\n", getErrorString(ret));

    // Build the program
    ret = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL);
//    ret = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
     printf("Check build program %s, device_id:%d \n", getErrorString(ret),(int)device_id);

    // Create the OpenCL kernel
    cl_kernel kernel = clCreateKernel(program, "vector_add", &ret);
     printf("Check kernel create %s\n", getErrorString(ret));

    // Set the arguments of the kernel
    ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&a_mem_obj);
     printf("Check kernel arg 0 %s\n", getErrorString(ret));
    ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&b_mem_obj);
     printf("Check kernel arg 1 %s\n", getErrorString(ret));
    ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&c_mem_obj);
    ret |= clSetKernelArg(kernel, 3, sizeof(unsigned int), &LIST_SIZE);
     printf("Check kernel args 0-3 %s\n", getErrorString(ret));

    // COPY EXECUTE BLOCK //////////////////////////////////////////////
    // ->Copy the lists A and B to their respective memory buffers
    ret = clEnqueueWriteBuffer(command_queue, a_mem_obj, CL_TRUE, 0,
            LIST_SIZE * sizeof(int), A, 0, NULL, NULL);
     printf("Check Read B %s\n", getErrorString(ret));
    ret = clEnqueueWriteBuffer(command_queue, b_mem_obj, CL_TRUE, 0, 
            LIST_SIZE * sizeof(int), B, 0, NULL, NULL);
     printf("Check Read B %s\n", getErrorString(ret));

    // Execute the OpenCL kernel on the list
    printf("\n GPU adding the vectors \n");
    size_t global_item_size = LIST_SIZE; // Process the entire lists
    size_t local_item_size = 1; // Process one item at a time
    ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, 
            &global_item_size, &local_item_size, 0, NULL, NULL);
    printf("Check kernel EnqueueNDRange %s\n", getErrorString(ret));

    // Read the memory buffer c_mem_obj on the device to the local C
    ret = clEnqueueReadBuffer(command_queue, c_mem_obj, CL_TRUE, 0, 
            LIST_SIZE * sizeof(int), C, 0, NULL, NULL);
     printf("Check Read Buffer C %s\n", getErrorString(ret));
    ////////////////////////////////////////////////////////////////////

    // Display the first 10 result to the screen
    for(i = 0; i < 10; i++)
        printf("%d + %d = %d\n", A[i], B[i], C[i]);
    printf("\n");
    // Display the last 10 result to the screen
    for(i = LIST_SIZE-10; i < LIST_SIZE; i++)
        printf("%d + %d = %d\n", A[i], B[i], C[i]);

//// SECOND TIME ////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
printf("\n Host initialising input vectors randomly \n");
    for(i = 0; i < LIST_SIZE; i++) {
        A[i] = randomInit(); 
        B[i] = randomInit();
        loadBar(i, LIST_SIZE, 100, 2);
    }

    // COPY EXECUTE BLOCK RE-RUN ////////////////////////////////////////
    // ->Copy the lists A and B to their respective memory buffers
    ret = clEnqueueWriteBuffer(command_queue, a_mem_obj, CL_TRUE, 0,
            LIST_SIZE * sizeof(int), A, 0, NULL, NULL);
     printf("Check Read B %s\n", getErrorString(ret));
    ret = clEnqueueWriteBuffer(command_queue, b_mem_obj, CL_TRUE, 0, 
            LIST_SIZE * sizeof(int), B, 0, NULL, NULL);
     printf("Check Read B %s\n", getErrorString(ret));

    // Execute the OpenCL kernel on the list
    ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, 
            &global_item_size, &local_item_size, 0, NULL, NULL);
    printf("Check kernel EnqueueNDRange %s\n", getErrorString(ret));

    // Read the memory buffer c_mem_obj on the device to the local C
    ret = clEnqueueReadBuffer(command_queue, c_mem_obj, CL_TRUE, 0, 
            LIST_SIZE * sizeof(int), C, 0, NULL, NULL);
     printf("Check Read Buffer C %s\n", getErrorString(ret));
    ////////////////////////////////////////////////////////////////////

    // Display the first 10 result to the screen
    for(i = 0; i < 10; i++)
        printf("%d + %d = %d\n", A[i], B[i], C[i]);
    printf("\n");
    // Display the last 10 result to the screen
    for(i = LIST_SIZE-10; i < LIST_SIZE; i++)
        printf("%d + %d = %d\n", A[i], B[i], C[i]);


////// SECOND TIME ENDS/////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
printf("\n Cleaning up GPU queues\n");
    // Clean up
    ret = clFlush(command_queue);
    ret = clFinish(command_queue);
    ret = clReleaseKernel(kernel);
    ret = clReleaseProgram(program);
    ret = clReleaseMemObject(a_mem_obj);
    ret = clReleaseMemObject(b_mem_obj);
    ret = clReleaseMemObject(c_mem_obj);
    ret = clReleaseCommandQueue(command_queue);
    ret = clReleaseContext(context);

printf("\n Host freeing up the vectors\n");
    free(A);
    free(B);
    free(C);
    return 0;
}
示例#17
0
CvPoint*
cvDRLSE(const CvArr * image,
        const CvArr * mask,
	int *length,
        double lambda,
        double alfa,
        double epsilon,
        int timestep,
        int ITER_ext,
        int ITER_int,
        int flag)
{
    IplImage sstub1, sstub2, *msk, *img, *marker, *levelset;
    CvMat *ones, *Ix, *Iy, *phi, *f, *g;
    CvSize size;
    int comp_count =0, iStep;
    float* fPtr;
    CvMemStorage* storage = cvCreateMemStorage(0);
    CvSeq* contours = 0;
    CvPoint pt= cvPoint(0,0), *point=NULL;
    double mu = 0.2f/double(timestep);
    char c;

    CV_FUNCNAME( "cvDRLSE" );
    
    __BEGIN__;
    
    CV_CALL( msk = cvGetImage(mask,    &sstub1 ));
    CV_CALL( img = cvGetImage(image,   &sstub2 ));    
    cvSmooth(img, img, CV_GAUSSIAN, 5, 5, 1.5f);
    size = cvGetSize(img);
    levelset = cvCreateImage(size, IPL_DEPTH_8U, 1);
    ones = cvCreateMat(size.height, size.width, CV_32FC1);
    Ix = cvCreateMat(size.height, size.width, CV_32FC1);
    Iy = cvCreateMat(size.height, size.width, CV_32FC1);
    phi = cvCreateMat(size.height, size.width, CV_32FC1);
    f = cvCreateMat(size.height, size.width, CV_32FC1);
    g = cvCreateMat(size.height, size.width, CV_32FC1);
    marker = cvCreateImage(size, IPL_DEPTH_32S, 1);
    cvSet(ones, cvScalar(1.0f));
    
    cvSobel(img, Ix, 1, 0, 1);
    cvSobel(img, Iy, 0, 1, 1);
    cvMul(Ix, Ix, Ix, 0.25f*0.25f);
    cvMul(Iy, Iy, Iy, 0.25f*0.25f);
    cvAdd(Ix, Iy, f);
    cvAdd(f, ones, f);
    cvDiv(NULL, f, g, 1.0f);
    
    cvFindContours( msk, storage, &contours, sizeof(CvContour),CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE );
    cvZero(marker);
    for( ; contours != 0; contours = contours->h_next, comp_count++ )
    {
        cvDrawContours( marker, contours, cvScalarAll(255),cvScalarAll(255), -1, -1, 8);
    }
   
    iStep = phi->step/sizeof(fPtr[0]);
    fPtr = phi->data.fl;
    
    for (int j=0; j<size.height; j++)
        for (int i=0; i<size.width; i++) {
            int idx = CV_IMAGE_ELEM( marker, int, j, i );
            if (idx >0 )
                if (flag == CV_LSE_SHR)
                    fPtr[i+iStep*j]=-2.0f;
                else
                    fPtr[i+iStep*j]=2.0f;
            else
                if (flag == CV_LSE_SHR)
                    fPtr[i+iStep*j]=2.0f;
                else
                    fPtr[i+iStep*j]=-2.0f;
        }
    
    for (int i=0; i<ITER_ext; i++) {
        cvDrlse_edge(phi, g, phi, lambda, mu, alfa, epsilon, timestep, ITER_int);
	loadBar(i+1, ITER_ext, 50);
    }
    cvDrlse_edge(phi, g, phi, lambda, mu, 0.0f, epsilon, timestep, ITER_int);
    cvZero(msk);
    if (flag == CV_LSE_SHR)
        cvThreshold(phi, msk, 0.0f, 255, CV_THRESH_BINARY_INV);
    else
        cvThreshold(phi, msk, 0.0f, 255, CV_THRESH_BINARY);

    cvFindContours(msk, storage, &contours, sizeof(CvContour), CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);

    if(!contours) return 0;
    *length = contours->total;
    //if(*length<10) return 0;
    point = new CvPoint[*length];
    CvSeqReader reader;
    
    cvStartReadSeq(contours, &reader);
    for (int i = 0; i < *length; i++){
        CV_READ_SEQ_ELEM(pt, reader);
        point[i]=pt;
    }
  
    //clean up
    cvReleaseMemStorage(&storage);
    cvReleaseImage(&marker);
    cvReleaseMat(&Ix);
    cvReleaseMat(&Iy);
    cvReleaseMat(&f);
    cvReleaseMat(&g);
    cvReleaseMat(&phi);
    cvReleaseMat(&ones);
    
    return point;
    __END__;
}
示例#18
0
void MuonPlots(TString HLTname = "IsoMu20")
{
	TTimeStamp ts_start;
	cout << "[Start Time(local time): " << ts_start.AsString("l") << "]" << endl;

	TStopwatch totaltime;
	totaltime.Start();

	TString HLT;
	Double_t LeadPtCut = 9999;
	Double_t SubPtCut = 9999;
	Double_t LeadEtaCut = 9999;
	Double_t SubEtaCut = 9999;
	AssignAccThreshold(HLTname, &HLT, &LeadPtCut, &SubPtCut, &LeadEtaCut, &SubEtaCut);
	cout << "===========================================================" << endl;
	cout << "Trigger: " << HLT << endl;
	cout << "leading lepton pT Cut: " << LeadPtCut << endl;
	cout << "Sub-leading lepton pT Cut: " << SubPtCut << endl;
	cout << "leading lepton Eta Cut: " << LeadEtaCut << endl;
	cout << "sub-leading lepton Eta Cut: " << SubEtaCut << endl;
	cout << "===========================================================" << endl;

	Double_t Factor = 569.0171*2008.4*3/4.5275/10;

	//TFile *f = new TFile("ROOTFile_Histogram_InvMass_"+HLTname+"_Data.root", "RECREATE");
	//TFile *f = new TFile("ROOTFile_Histogram_InvMass_60to120_Data.root", "RECREATE");
	TFile *fcut = new TFile("MuonCut.root", "RECREATE");
	//TFile *fisPF = new TFile("MuonCutIsPF.root", "RECREATE");
	//TFile *fisChi2dof = new TFile("MuonCutChi2dof.root", "RECREATE");
	//TFile *f = new TFile("MuonCutMuonHits.root", "RECREATE");
	//TFile *f = new TFile("MuonCutNMatches.root", "RECREATE");
	//TFile *f = new TFile("MuonCutDxyVTX.root", "RECREATE");
	//TFile *f = new TFile("MuonCutDzVTX.root", "RECREATE");
	//TFile *f = new TFile("MuonCutPixelHits.root", "RECREATE");
	//TFile *f = new TFile("MuonCutTrackerLayers.root", "RECREATE");

	TString BaseLocation = "/data4/Users/kplee/DYntuple";
	//Each ntuple directory & corresponding Tags
	vector< TString > ntupleDirectory; vector< TString > Tag;
	//MC
	// ntupleDirectory.push_back( "Spring15DR/25ns/DYLL_M10to50_v2_AddTauInfo" ); Tag.push_back( "DYMuMu_M20to50" );
	ntupleDirectory.push_back( "Spring15DR/25ns/DYLL_M50_v1" ); Tag.push_back( "DYMuMu" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/DYLL_M10to50_v2_AddTauInfo" ); Tag.push_back( "DYTauTau_M20to50" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/DYLL_M50_v1" ); Tag.push_back( "DYTauTau" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/ttbar_v1" );  Tag.push_back( "ttbar" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/WJets_v1" );  Tag.push_back( "WJets" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/WW_v1" );  Tag.push_back( "WW" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/WZ_v1" );  Tag.push_back( "WZ" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/ZZ_v1" );  Tag.push_back( "ZZ" );

	//Data
	ntupleDirectory.push_back( "Run2015C/GoldenJSON/SingleMuon_v3_Run246908to256869" ); Tag.push_back( "Data" ); // -- Run2015C -- //


	//Loop for all samples
	const Int_t Ntup = ntupleDirectory.size();
	for(Int_t i_tup = 0; i_tup<Ntup; i_tup++)
	{
		TStopwatch looptime;
		looptime.Start();

		cout << "\t<" << Tag[i_tup] << ">" << endl;

		ControlPlots *Plots = new ControlPlots( Tag[i_tup] );
		//Histograms for cuts
		TH1D *h_isGLB_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_isGLB_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_isGLB_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_isPF_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_isPF_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_isPF_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_chi2dof_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_chi2dof_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_chi2dof_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_muonHits_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_muonHits_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_muonHits_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_nMatches_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_nMatches_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_nMatches_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_dxyVTX_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_dxyVTX_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_dxyVTX_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_dzVTX_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_dzVTX_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_dzVTX_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_pixelHits_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_pixelHits_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_pixelHits_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_trackerLayers_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_trackerLayers_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_trackerLayers_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);

		TChain *chain = new TChain("recoTree/DYTree");
		chain->Add(BaseLocation+"/"+ntupleDirectory[i_tup]+"/ntuple_*.root");
		if( Tag[i_tup] == "Data" )
		{
			// -- Run2015D -- // 
			chain->Add("/data4/Users/kplee/DYntuple/Run2015D/GoldenJSON/v20151016_v3JSON_Run2015D_SingleMuon_Run246908to256869/*.root");
			chain->Add("/data4/Users/kplee/DYntuple/Run2015D/GoldenJSON/v20151010_v2JSON_SingleMuon_Run256870to257599/*.root");
			chain->Add("/data4/Users/kplee/DYntuple/Run2015D/GoldenJSON/v20151009_SingleMuon_Run257600toRun258159/*.root");
		}
		
		NtupleHandle *ntuple = new NtupleHandle( chain );

		Bool_t isNLO = 0;
		if( Tag[i_tup] == "DYMuMu" || Tag[i_tup] == "DYTauTau" || Tag[i_tup] == "WJets" || Tag[i_tup] == "DYMuMu_M20to50" || Tag[i_tup] == "DYTauTau_M20to50" )
		{
			isNLO = 1;
			cout << "\t" << Tag[i_tup] << ": generated with NLO mode - Weights are applied" << endl;
		}

		Int_t count_Zpeak = 0;
		Double_t SumWeight = 0;
		Double_t SumWeight_DYMuMu_M20to50 = 0;
		Double_t SumWeight_DYTauTau_M20to50 = 0;

		Int_t NEvents = chain->GetEntries();
		cout << "\t[Total Events: " << NEvents << "]" << endl;
		for(Int_t i=0; i<NEvents; i++)
		{
			loadBar(i+1, NEvents, 100, 100);
			
			ntuple->GetEvent(i);

			//Bring weights for NLO MC events
			Double_t GenWeight;
			if( isNLO == 1 )
				GenWeight = ntuple->GENEvt_weight;
			else
				GenWeight = 1;
			// cout << "Weight of " << i << "th Event: " << GenWeight << endl;
			SumWeight += GenWeight;

			Int_t GenMassFlag = -1;
			//Take the events within 20<M<50 in gen-level
/*
 *            if( Tag[i_tup] == "DYMuMu_M20to50" )
 *            {
 *                GenMassFlag = 0;
 *                vector<GenLepton> GenLeptonCollection;
 *                Int_t NGenLeptons = ntuple->gnpair;
 *                for(Int_t i_gen=0; i_gen<NGenLeptons; i_gen++)
 *                {
 *                    GenLepton genlep;
 *                    genlep.FillFromNtuple(ntuple, i_gen);
 *                    if( genlep.isMuon() && genlep.fromHardProcessFinalState )
 *                        GenLeptonCollection.push_back( genlep );
 *                }
 *
 *                if( GenLeptonCollection.size() == 2 )
 *                {
 *                    GenLepton genlep1 = GenLeptonCollection[0];
 *                    GenLepton genlep2 = GenLeptonCollection[1];
 *
 *                    TLorentzVector gen_v1 = genlep1.Momentum;
 *                    TLorentzVector gen_v2 = genlep2.Momentum;
 *                    TLorentzVector gen_vtot = gen_v1 + gen_v2;
 *                    Double_t gen_M = gen_vtot.M();
 *
 *                    if( gen_M > 20 && gen_M < 50 ) //Take the events within 20<M<50 in gen-level
 *                    {
 *                        GenMassFlag = 1;
 *                        SumWeight_DYMuMu_M20to50 += GenWeight;
 *                    }		
 *                }
 *            }
 *            else if( Tag[i_tup] == "DYTauTau_M20to50" )
 *            {
 *                GenMassFlag = 0;
 *                vector<GenLepton> GenLeptonCollection;
 *                Int_t NGenLeptons = ntuple->gnpair;
 *                for(Int_t i_gen=0; i_gen<NGenLeptons; i_gen++)
 *                {
 *                    GenLepton genlep;
 *                    genlep.FillFromNtuple(ntuple, i_gen);
 *                    if( abs(genlep.ID) == 15 && genlep.fromHardProcessDecayed )
 *                        GenLeptonCollection.push_back( genlep );
 *                }
 *
 *                if( GenLeptonCollection.size() == 2 )
 *                {
 *                    GenLepton genlep1 = GenLeptonCollection[0];
 *                    GenLepton genlep2 = GenLeptonCollection[1];
 *
 *                    TLorentzVector gen_v1 = genlep1.Momentum;
 *                    TLorentzVector gen_v2 = genlep2.Momentum;
 *                    TLorentzVector gen_vtot = gen_v1 + gen_v2;
 *                    Double_t gen_M = gen_vtot.M();
 *
 *                    if( gen_M > 20 && gen_M < 50 ) //Take the events within 20<M<50 in gen-level
 *                    {
 *                        GenMassFlag = 1;
 *                        SumWeight_DYTauTau_M20to50 += GenWeight;
 *                    }	
 *                }
 *            }
 *            else
 */
				GenMassFlag = 1; // -- other cases: pass


			
			if( ntuple->isTriggered( HLT ) && GenMassFlag)
			{
				//Collect Reconstruction level information
				vector< Muon > MuonCollection;
				Int_t NLeptons = ntuple->nMuon;
				for(Int_t i_reco=0; i_reco<NLeptons; i_reco++)
				{
					Muon mu;
					mu.FillFromNtuple(ntuple, i_reco);
						MuonCollection.push_back( mu );
				}

				//Select muons directly from Z/gamma by matching with gen-level final state muons from hard process
				if( Tag[i_tup] == "DYMuMu" )
					GenMatching(HLTname, "fromHardProcess", ntuple, &MuonCollection);
/*
 *                //Select muons directly from tau by matching with gen-level final state muons from prompt tau
 *                else if( Tag[i_tup] == "DYTauTau" )
 *                    GenMatching(HLTname, "fromTau", ntuple, &MuonCollection);
 *
 */

				//Collect qualified muons among muons
				vector< Muon > QMuonCollection;
				for(Int_t j=0; j<(int)MuonCollection.size(); j++)
				{
					if( MuonCollection[j]->isGLB == 1)
					{
						h_isGLB_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_isGLB_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_isGLB_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->isPF == 1)
					{
						h_isPF_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_isPF_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_isPF_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->chi2dof < 10)
					{
						h_ischi2dof_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_ischi2dof_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_ischi2dof_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->muonHits > 0)
					{
						h_is_muonHits_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_is_muonHits_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_is_muonHits_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->nMatches > 1)
					{
						h_nMatches_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_nMatches_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_nMatches_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( fabs(MuonCollection[j]->dxyVTX) < 0.2)
					{
						h_dxyVTX_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_dxyVTX_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_dxyVTX_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( fabs(MuonCollection[j]->dzVTX) < 0.5 )
					{
						h_dzVTX_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_dzVTX_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_dzVTX_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->pixelHits > 0 )
					{
						h_pixelHits_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_pixelHits_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_pixelHits_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->trackerLayers > 5)
					{
						h_trackerLayers_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_trackerLayers_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_trackerLayers_phi->Fill( MuonCollection[j].phi, GenWeight);
					}

					//if( MuonCollection[j].isTightMuon() && MuonCollection[j].trkiso < 0.10)
						//QMuonCollection.push_back( MuonCollection[j] );
				}

/*
 *                //Give Acceptance cuts
 *                if( QMuonCollection.size() >= 2)
 *                {
 *                    Muon leadMu, subMu;
 *                    CompareMuon(&QMuonCollection[0], &QMuonCollection[1], &leadMu, &subMu);
 *                    if( !(leadMu.Pt > LeadPtCut && subMu.Pt > SubPtCut && abs(leadMu.eta) < LeadEtaCut && abs(subMu.eta) < SubEtaCut) )
 *                        QMuonCollection.clear();
 *                }
 *
 *                if( QMuonCollection.size() == 2)
 *                {
 *                    Muon recolep1 = QMuonCollection[0];
 *                    Muon recolep2 = QMuonCollection[1];
 *                    TLorentzVector reco_v1 = recolep1.Momentum;
 *                    TLorentzVector reco_v2 = recolep2.Momentum;
 *                    Double_t reco_M = (reco_v1 + reco_v2).M();
 *
 *                    if( reco_M > 60 && reco_M < 120 && isPassDimuonVertexCut(ntuple, recolep1.cktpT, recolep2.cktpT) )
 *                    {
 *                        Plots->FillHistograms(ntuple, HLT, recolep1, recolep2, GenWeight);
 *
 *                        //Count # events in the Z-peak region for each sample
 *                        //if( reco_M > 60 && reco_M < 120 )
 *                            count_Zpeak++;
 *                    }
 *                }
 *
 */
			} //End of if( isTriggered )

		} //End of event iteration

		/*
		 *cout << "\tcount_Zpeak(" << Tag[i_tup] << "): " << count_Zpeak << endl;
		 */

		// if( Tag[i_tup] == "DYTauTau_M20to50" )
		// {
		// 	for(Int_t i_hist=0; i_hist < (Int_t)Plots->Histo.size(); i_hist++)
		// 		Plots->Histo[i_hist]->Scale( 2.49997e+10 / 4.48119e+11 );
		// }




		//Plots->WriteHistograms( fisGLB );
		fisGLB->cd();
		h_isGLB_Pt->Write();
		h_isGLB_eta->Write();
		h_isGLB_phi->Write();
		h_isPF_Pt->Write();
		h_isPF_eta->Write();
		h_isPF_phi->Write();
		h_chi2dof_Pt->Write();
		h_chi2dof_eta->Write();
		h_chi2dof_phi->Write();
		h_muonHits_Pt->Write();
		h_muonHits_eta->Write();
		h_muonHits_phi->Write();
		h_nMatches_Pt->Write();
		h_nMatches_eta->Write();
		h_nMatches_phi->Write();
		h_dxyVTX_Pt->Write();
		h_dxyVTX_eta->Write();
		h_dxyVTX_phi->Write();
		h_dzVTX_Pt->Write();
		h_dzVTX_eta->Write();
		h_dzVTX_phi->Write();
		h_pixelHits_Pt->Write();
		h_pixelHits_eta->Write();
		h_pixelHits_phi->Write();
		h_trackerLayers_Pt->Write();
		h_trackerLayers_eta->Write();
		h_trackerLayers_phi->Write();
		



		if(isNLO == 1)
			cout << "\tTotal sum of weights: " << SumWeight << endl;

		if( Tag[i_tup] == "DYMuMu_M20to50" )
			cout << "\tSum of weights in 20<M<50 for DYMuMu events: " << SumWeight_DYMuMu_M20to50 << endl;

		if( Tag[i_tup] == "DYTauTau_M20to50" )
			cout << "\tSum of weights in 20<M<50 for DYTauTau events: " << SumWeight_DYTauTau_M20to50 << endl;

		Double_t LoopRunTime = looptime.CpuTime();
		cout << "\tLoop RunTime(" << Tag[i_tup] << "): " << LoopRunTime << " seconds\n" << endl;
	} //end of i_tup iteration

	Double_t TotalRunTime = totaltime.CpuTime();
	cout << "Total RunTime: " << TotalRunTime << " seconds" << endl;

	TTimeStamp ts_end;
	cout << "[End Time(local time): " << ts_end.AsString("l") << "]" << endl;
}