Beispiel #1
0
void frameViewer(char* arg) {
	//Take the arguments and save them into respective strings
	std::string infileName;
	std::string inF;
	std::string inPrefix;
	std::string runs, layers;
	std::string runCount;
	std::istringstream stm(arg);

	inPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/rawRoot/";

	while (true) {	
		if (std::getline(stm, layers, ' ')) {

			//load the input root files
			TChain *chain = new TChain("fourChamTree");

			for (int i=0; ; i++) {
				runCount = std::to_string(i);
				inF = "run" + runCount + "_" + layers + "layers.root";
				infileName = inPrefix + inF;
				ifstream fin;
				fin.open(infileName.c_str());
				if (!fin.fail()) {
					fin.close();
					chain->Add(infileName.c_str());
					std::cout << "Got " << inF << std::endl;
				} else break;
			}

			const int width=480;	//width of the raw image
			const int height=640;	//height of the raw image


			int x=-10;	//x from file
			int y=-10;	//y from file
			int intensity=-10;	//pixle intensity from file
			int pNum=0;//a counter of the order in which the frame was processed

			//the 2d array which will store each frame of image data.
			int frame[480][640]={0};

			//variables
			int UNIXtime=0;
			float tdc[2]={-10,-10};


			//TTree *T = new TTree("T","TTree of muplus data");
			//add the 'branches' to the tree we will now read in
			chain->SetBranchAddress("pNum",&pNum);	//branch for the frame number
			chain->SetBranchAddress("frame",&frame);	//branch for frame data

			TH2I *frameHisto = new TH2I("Single 4 Spark Event","",width,0,width,height,0,height);	//histogram for the stacked images

			TH1I *chamber1 = new TH1I("chamber1","Chamber 1",width,0,width);//histogram for chamber 1 (the top one)
			TH1I *chamber2 = new TH1I("chamber2","Chamber 2",width,0,width);//histogram for chamber 2
			TH1I *chamber3 = new TH1I("chamber3","Chamber 3",width,0,width);//histogram for chamber 3
			TH1I *chamber4 = new TH1I("chamber4","Chamber 4",width,0,width);//histogram for chamber 4 (the bottom one)
			
			TH1I *chamber1y = new TH1I("chamber1y","Chamber 1",height,0,height);//histogram for chamber 1 (the top one)
			TH1I *chamber2y = new TH1I("chamber2y","Chamber 2",height,0,height);//histogram for chamber 2
			TH1I *chamber3y = new TH1I("chamber3y","Chamber 3",height,0,height);//histogram for chamber 3
			TH1I *chamber4y = new TH1I("chamber4y","Chamber 4",height,0,height);//histogram for chamber 4 (the bottom one)

			//output the plot of the stacked images
		
			TCanvas *fH2 = new TCanvas("fH2", "Single 4 Spark Event", 0, 0, 800, 800);
			fH2->cd();
			frameHisto->Draw();
			frameHisto->GetXaxis()->SetTitle("X position (px)");
			frameHisto->GetXaxis()->CenterTitle();

			frameHisto->GetYaxis()->SetTitle("Intensity");
			frameHisto->GetYaxis()->SetTitleOffset(1.4);
			frameHisto->GetYaxis()->CenterTitle();

			TCanvas *pc2 = new TCanvas("pc2","Frame",0,0,800,800);
			
			pc2->Divide(2,2);
			
			pc2->cd(1);
			chamber1->Draw();
			chamber1->GetXaxis()->SetTitle("X position (px)");
			chamber1->GetXaxis()->CenterTitle();

			chamber1->GetYaxis()->SetTitle("Intensity");
			chamber1->GetYaxis()->SetTitleOffset(1.4);
			chamber1->GetYaxis()->CenterTitle();

			pc2->cd(2);
			chamber2->Draw();
			chamber2->GetXaxis()->SetTitle("X position (px)");
			chamber2->GetXaxis()->CenterTitle();

			chamber2->GetYaxis()->SetTitle("Intensity");
			chamber2->GetYaxis()->SetTitleOffset(1.4);
			chamber2->GetYaxis()->CenterTitle();

			pc2->cd(3);
			chamber3->Draw();
			chamber3->GetXaxis()->SetTitle("X position (px)");
			chamber3->GetXaxis()->CenterTitle();

			chamber3->GetYaxis()->SetTitle("Intensity");
			chamber3->GetYaxis()->SetTitleOffset(1.4);
			chamber3->GetYaxis()->CenterTitle();

			pc2->cd(4);
			chamber4->Draw();
			chamber4->GetXaxis()->SetTitle("X position (px)");
			chamber4->GetXaxis()->CenterTitle();

			chamber4->GetYaxis()->SetTitle("Intensity");
			chamber4->GetYaxis()->SetTitleOffset(1.4);
			chamber4->GetYaxis()->CenterTitle();

			//TFile myF("trackTree.root","RECREATE");
			

			//loop over all data in chain
			Int_t nevent = chain->GetEntries();	//get the number of entries in the TChain
			for (Int_t i=0;i<nevent;i++) {
				chain->GetEntry(i);

				//put the frame data into the histogram for this event
				for(int x=0;x<width;x++){
					for(int y=0;y<height;y++){
						if(frame[x][y]>0){
							frameHisto->Fill(x,y,frame[x][y]);
							if(y>580 && y<610){
								chamber1->Fill(x,frame[x][y]);
								chamber1y->Fill(y,frame[x][y]);
							}
							else if(y>400 && y<440){
								chamber2->Fill(x,frame[x][y]);
								chamber2y->Fill(y,frame[x][y]);
							}
							else if(y>240 && y<280){
								chamber3->Fill(x,frame[x][y]);
								chamber3y->Fill(y,frame[x][y]);
							}
							else if(y>50 && y<100){
								chamber4->Fill(x,frame[x][y]);
								chamber4y->Fill(y,frame[x][y]);
							}
						}	
					}
				}

				double x12[2];
				double y12[2];
				double x34[2];
				double y34[2];

				x12[0] = chamber1->GetMean();
				y12[0] = chamber1y->GetMean();			//593.3;
				x12[1] = chamber2->GetMean();
				y12[1] = chamber2y->GetMean();			//424.7;
				x34[0] = chamber3->GetMean();
				y34[0] = chamber3y->GetMean();			//262.5;
				x34[1] = chamber4->GetMean();
				y34[1] = chamber4y->GetMean();			//69.33;

				cout << "Chamber1x: " << chamber1->GetMean() << endl;
				cout << "Chamber1y: " << chamber1y->GetMean() << endl;
				cout << "Chamber2x: " << chamber2->GetMean() << endl;
				cout << "Chamber2y: " << chamber2y->GetMean() << endl;
				cout << "Chamber3x: " << chamber3->GetMean() << endl;
				cout << "Chamber3y: " << chamber3y->GetMean() << endl;
				cout << "Chamber4x: " << chamber4->GetMean() << endl;
				cout << "Chamber4y: " << chamber4y->GetMean() << endl;

				pc2->cd(1);
				chamber1->Draw();
				gPad->Update();
				
				pc2->cd(2);
				chamber2->Draw();
				gPad->Update();
				
				pc2->cd(3);
				chamber3->Draw();
				gPad->Update();
				
				pc2->cd(4);
				chamber4->Draw();
				gPad->Update();
				
				fH2->cd();
				frameHisto->Draw();
				gPad->Update();

				//wait for user input to advance to next event
				cout << "Frame Number=" << pNum<<endl;
				cout << "Press enter to advance to the next frame" << endl;
				cin.ignore();
				
				//clear the old frame from the histogram
				frameHisto->Reset();
				chamber1->Reset();
				chamber2->Reset();
				chamber3->Reset();
				chamber4->Reset();
			}
		} else break;
	}
}
Beispiel #2
0
void CsIProj()
{
  TFile *file = new TFile("../root/NZ_55_New.root");
  TFile *gates = new TFile("../gates/zlines.root");
  TFile *gates2 = new TFile("../gates/zlines_new.root");

  ofstream ofile("CsI_55A_New.dat");
  
  TCanvas *mycan = (TCanvas*)gROOT->FindObjectAny("mycan");
  if(!mycan)
    {
      mycan = new TCanvas("mycan","mycan");
      mycan->Divide(1,2);
    }
  
  
  ostringstream outstring;
  string name;
  int p1= 30, p2=50; //+- fit limits up to 2 peaks. May be different.
  int const num_par = 5; //number of peaks times 2(pol1)+3(gaus).
  
  for(int ic =0;ic<56;ic++)
    {
      
      outstring.str("");
      outstring << "dEE/dEE_" << ic;
      name = outstring.str();
      
      mycan->cd(1);
      TH2I *hist = (TH2I*)file->Get(name.c_str());
      hist->Draw("col");  
      hist->GetXaxis()->SetRangeUser(200.,1800.); 
      hist->GetYaxis()->SetRangeUser(5.,50.); 
   
      
      if(ic <16 || ic > 31)
	TCutG *mycut = (TCutG*)gates->Get(Form("Zline_%i_2_4",ic));
      else 
	TCutG *mycut = (TCutG*)gates2->Get(Form("Zline_%i_2_4",ic));
      mycut->Draw();

      file->cd();
      outstring.str("");
      outstring << "CsI/CsIGate/ECsI_" << ic << "_Gate";
      name = outstring.str();
      gPad->SetLogz();

      mycan->cd(2);
      TH1I * proj = (TH1I*)file->Get(name.c_str());
      proj->Draw();
      proj->Rebin(4);
      proj->GetXaxis()->SetRangeUser(700.,1800.);

      mycan->Modified();
      mycan->Update();

      TMarker * mark;
      mark=(TMarker*)mycan->WaitPrimitive("TMarker"); //Get the Background limits
      int bkg_lo = mark->GetX();
      delete mark;  
      mark=(TMarker*)mycan->WaitPrimitive("TMarker");
      int bkg_hi = mark->GetX();
      delete mark;
      mark=(TMarker*)mycan->WaitPrimitive("TMarker"); // Get the 1st peak initial guess
      int peak1 = mark->GetX();
      delete mark;
      
      
      double par[num_par] = {0.};
      double out[num_par] = {0.}; 
      int peak1_lo = peak1 - p1, peak1_hi = peak1 + p1; // Peak center and limits
      
      
      TF1 *l1 = new TF1("l1", "pol1", bkg_lo, bkg_hi);
      TF1 *g1 = new TF1("g1", "gaus", peak1_lo,peak1_hi);
      
      TF1 *total = new TF1("total", "pol1(0)+gaus(2)", bkg_lo,bkg_hi);
      
      proj->Fit(l1,"R");
      proj->Fit(g1,"R+");
      
      l1->GetParameters(&par[0]);
      g1->GetParameters(&par[2]);
      
      total->SetParameters(par);
      proj->Fit(total,"R");
      total->GetParameters(out);
      
      
      ofile << ic << " " << out[3] << endl;
      
      outstring.str("");
      outstring << "55A_" << ic;
      name = outstring.str();
      total->SetName(name.c_str());
      total->Draw("same");
      mycan->Modified();
      mycan->Update();
      
      bool IsGood = 0;

      cout << "Good fit?" << endl;
      cin >> IsGood;
  

      if(IsGood)
	{
      ofile << ic << " " << out[3] << endl;
	}      
      else
	ofile << ic << " " << -1 << endl;      

   

    }
  
  
  return;
}
Beispiel #3
0
int frameStack2_Mall(char* arg){
	//Take the arguments and save them into respective strings
	std::string infileName, outfileName0, outAllfileName0, outfileName1, outAllfileName1;
	std::string inF, outF0, outF1, outAll0, outAll1;
	std::string inPrefix, outPrefix;
	std::string runs, layers;
	std::string runCount;
	std::istringstream stm(arg);

	inPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/rawRoot/";
	outPrefix = "/home/p180f/Do_Jo_Ol_Ma/Analysis/MainProcedure/testMain/images/";

	outAll0 = "sliceXCuts_allLayers.png";
	outAllfileName0 = outPrefix + outAll0;
	std::cout << outAll0 << " created\n";
	outAll1 = "projYCuts_allLayers.png";
	outAllfileName1 = outPrefix + outAll1;
	std::cout << outAll1 << " created\n";

	const int width=480;	//width of the raw image
	const int height=640;	//height of the raw image
	
	TH2I *frameHistoAll = new TH2I("frameHistoAll","Stacked Frames After Edge Cuts",width/4,0,width,height/4,0,height);	//histogram for the stacked images
	TH1I *chamber1All = new TH1I("chamber1All","Chamber 1 After Edge Cuts",width/4,0,width);//histogram for chamber 1 (the top one)
	TH1I *chamber2All = new TH1I("chamber2All","Chamber 2 After Edge Cuts",width/4,0,width);//histogram for chamber 2
	TH1I *chamber3All = new TH1I("chamber3All","Chamber 3 After Edge Cuts",width/4,0,width);//histogram for chamber 3
	TH1I *chamber4All = new TH1I("chamber4All","Chamber 4 After Edge Cuts",width/4,0,width);//histogram for chamber 4 (the bottom one)

	TCanvas *projCAll = new TCanvas("projCAll","",0,0,800,600);
	TCanvas *pc2All = new TCanvas("pc2All", "Stack of 4 Layer Runs", 0, 0, 800, 600);
	
	while (true) {	
		if (std::getline(stm, layers, ' ')) {

			//create the output root file
			outF0 = "sliceXCuts_" + layers + "layers.png";
			outfileName0 = outPrefix + outF0;
			std::cout << outF0 << " created\n";
			outF1 = "projYCuts_" + layers + "layers.png";
			outfileName1 = outPrefix + outF1;
			std::cout << outF1 << " created\n";
			
			//load the input root files
			TChain *chain = new TChain("fourChamTree");

			for (int i=0; ; i++) {
				runCount = std::to_string(i);
				inF = "run" + runCount + "_" + layers + "layers.root";
				infileName = inPrefix + inF;
				ifstream fin;
				fin.open(infileName.c_str());
				if (!fin.fail()) {
					fin.close();
					chain->Add(infileName.c_str());
					std::cout << "Got " << inF << std::endl;
				} else break;
			}


			int x=-10;	//x from file
			int y=-10;	//y from file
			int intensity=-10;	//pixle intensity from file
			int pNum=0;//the order in which the frame was processed

			//the 2d array which will store each frame of image data.
			int frame[480][640]={0};

			//variables
			int UNIXtime=0;
			float tdc[2]={-10,-10};

			//TTree *T = new TTree("T","TTree of muplus data");
			//add the 'branches' to the tree we will now read in
			chain->SetBranchAddress("pNum",&pNum);	//branch for the frame number
			chain->SetBranchAddress("frame",&frame);	//branch for frame data


			TH2I *frameHisto = new TH2I("frameHisto","Stacked Frames After Edge Cuts",width/4,0,width,height/4,0,height);	//histogram for the stacked images
			TH1I *chamber1 = new TH1I("chamber1","Chamber 1 After Edge Cuts",width/4,0,width);//histogram for chamber 1 (the top one)
			TH1I *chamber2 = new TH1I("chamber2","Chamber 2 After Edge Cuts",width/4,0,width);//histogram for chamber 2
			TH1I *chamber3 = new TH1I("chamber3","Chamber 3 After Edge Cuts",width/4,0,width);//histogram for chamber 3
			TH1I *chamber4 = new TH1I("chamber4","Chamber 4 After Edge Cuts",width/4,0,width);//histogram for chamber 4 (the bottom one)

			//loop over all data in chain
			Int_t nevent = chain->GetEntries();	//get the number of entries in the TChain
			for (Int_t i=0;i<nevent;i++) {
				chain->GetEntry(i);
				for(int x=0;x<width;x++){
					for(int y=0;y<height;y++){
						if(frame[x][y]>0){
							frameHisto->Fill(x,y,frame[x][y]);
							frameHistoAll->Fill(x,y,frame[x][y]);
							if(y>580 && y<610){
								chamber1->Fill(x,frame[x][y]);
								chamber1All->Fill(x,frame[x][y]);
							}
							else if(y>400 && y<440){
								chamber2->Fill(x,frame[x][y]);
								chamber2All->Fill(x,frame[x][y]);
							}
							else if(y>240 && y<280){
								chamber3->Fill(x,frame[x][y]);
								chamber3All->Fill(x,frame[x][y]);
							}
							else if(y>50 && y<100){
								chamber4->Fill(x,frame[x][y]);
								chamber4All->Fill(x,frame[x][y]);
							}

						}

					}
				}
				cout << "Stacking frame number " << pNum << "\r";//this overwrites the line every time
			}
			cout << endl;

			//output the plot of the stacked images
			TCanvas *pc2 = new TCanvas("pc2","Stacked Frames",0,0,600,800);
			pc2->cd();
			frameHisto->SetStats(false);
			frameHisto->Draw("colz");
			frameHisto->GetXaxis()->SetTitle("X position (px)");
			//frameHisto->GetXaxis()->SetTitleSize(0.055);
			//frameHisto->GetXaxis()->SetTitleOffset(1.0);
			//frameHisto->GetXaxis()->SetLabelSize(0.055);
			frameHisto->GetXaxis()->CenterTitle();

			frameHisto->GetYaxis()->SetTitle("Y position (px)");
			//frameHisto->GetYaxis()->SetTitleSize(0.055);
			//frameHisto->GetYaxis()->SetTitleOffset(0.9);
			//frameHisto->GetYaxis()->SetLabelSize(0.055);
			frameHisto->GetYaxis()->CenterTitle();
			gPad->Update();
//			pc2->Print("chamberStack.png");//output to a graphics file 

			//plot the projection onto the Y axis (so we can find our cuts in Y to select each chamber)
			TCanvas *projC = new TCanvas("projC","",0,0,800,600);
			projC->cd();
			TH1D *ydist = frameHisto->ProjectionY("ydist");
			ydist->Draw();
			ydist->GetYaxis()->SetTitle("Entries");
			ydist->GetYaxis()->CenterTitle();

			TCanvas *sliceX = new TCanvas("sliceX","",0,0,800,600);

			sliceX->Divide(2,2);
			
			sliceX->cd(1);
			chamber1->Draw();
			chamber1->GetXaxis()->SetTitle("X position (px)");
			chamber1->GetXaxis()->CenterTitle();
			chamber1->GetYaxis()->SetTitle("Y position (px)");
			chamber1->GetYaxis()->CenterTitle();
		//	chamber1->GetYaxis()->SetMaxDigits(2);
			
			sliceX->cd(2);
			chamber2->Draw();
			chamber2->GetXaxis()->SetTitle("X position (px)");
			chamber2->GetXaxis()->CenterTitle();
			chamber2->GetYaxis()->SetTitle("Y position (px)");
			chamber2->GetYaxis()->CenterTitle();
		//	chamber2->GetYaxis()->SetMaxDigits(2);
			
			sliceX->cd(3);
			chamber3->Draw();
			chamber3->GetXaxis()->SetTitle("X position (px)");
			chamber3->GetXaxis()->CenterTitle();
			chamber3->GetYaxis()->SetTitle("Y position (px)");
			chamber3->GetYaxis()->CenterTitle();
		//	chamber3->GetYaxis()->SetMaxDigits(2);
			
			sliceX->cd(4);
			chamber4->Draw();
			chamber4->GetXaxis()->SetTitle("X position (px)");
			chamber4->GetXaxis()->CenterTitle();
			chamber4->GetYaxis()->SetTitle("Y position (px)");
			chamber4->GetYaxis()->CenterTitle();
		//	chamber4->GetYaxis()->SetMaxDigits(2);

			gPad->Update();
			
			projC->Print(outfileName1.c_str());
			sliceX->Print(outfileName0.c_str());

			frameHisto->Reset();	
			chamber1->Reset();
			chamber2->Reset();
			chamber3->Reset();
			chamber4->Reset();
		} else break;
	}
	
	projCAll->cd();
	TH1D *ydistAll = frameHistoAll->ProjectionY("ydist");
	ydistAll->Draw();
	ydistAll->GetYaxis()->SetTitle("Entries");
	ydistAll->GetYaxis()->CenterTitle();
	
	TCanvas *sliceXAll = new TCanvas("sliceXAll","",0,0,800,600);

	sliceXAll->Divide(2,2);
	
	sliceXAll->cd(1);
	chamber1All->Draw();
	chamber1All->GetXaxis()->SetTitle("X position (px)");
	chamber1All->GetXaxis()->CenterTitle();
	chamber1All->GetYaxis()->SetTitle("Y position (px)");
	chamber1All->GetYaxis()->CenterTitle();
//	chamber1->GetYaxis()->SetMaxDigits(2);
	
	sliceXAll->cd(2);
	chamber2All->Draw();
	chamber2All->GetXaxis()->SetTitle("X position (px)");
	chamber2All->GetXaxis()->CenterTitle();
	chamber2All->GetYaxis()->SetTitle("Y position (px)");
	chamber2All->GetYaxis()->CenterTitle();
//	chamber2->GetYaxis()->SetMaxDigits(2);
	
	sliceXAll->cd(3);
	chamber3All->Draw();
	chamber3All->GetXaxis()->SetTitle("X position (px)");
	chamber3All->GetXaxis()->CenterTitle();
	chamber3All->GetYaxis()->SetTitle("Y position (px)");
	chamber3All->GetYaxis()->CenterTitle();
//	chamber3->GetYaxis()->SetMaxDigits(2);
	
	sliceXAll->cd(4);
	chamber4All->Draw();
	chamber4All->GetXaxis()->SetTitle("X position (px)");
	chamber4All->GetXaxis()->CenterTitle();
	chamber4All->GetYaxis()->SetTitle("Y position (px)");
	chamber4All->GetYaxis()->CenterTitle();
//	chamber4->GetYaxis()->SetMaxDigits(2);

	gPad->Update();
	
	projCAll->Print(outAllfileName1.c_str());
	sliceXAll->Print(outAllfileName0.c_str());
	
	pc2All->cd();
	frameHistoAll->SetStats(false);
	frameHistoAll->Draw("colz");
	frameHistoAll->GetXaxis()->SetTitle("X position (px)");
	//frameHisto->GetXaxis()->SetTitleSize(0.055);
	//frameHisto->GetXaxis()->SetTitleOffset(1.0);
	//frameHisto->GetXaxis()->SetLabelSize(0.055);
	frameHistoAll->GetXaxis()->CenterTitle();

	frameHistoAll->GetYaxis()->SetTitle("Y position (px)");
	//frameHisto->GetYaxis()->SetTitleSize(0.055);
	//frameHisto->GetYaxis()->SetTitleOffset(0.9);
	//frameHisto->GetYaxis()->SetLabelSize(0.055);
	frameHistoAll->GetYaxis()->CenterTitle();
	gPad->Update();

	return 0;  
}
Beispiel #4
0
int main (int argc, char** argv)
{

  if (argc < 3) {
    printHelp() ;
    exit (1) ;
  }

  std::string inputfiles, inputdir ;
  std::string outputRootName = "histoTPG.root" ;
  int verbose = 0 ;
  int occupancyCut = 0 ;
  std::string l1algo ; 

  bool ok(false) ;
  for (int i=0 ; i<argc ; i++) {
    if (argv[i] == std::string("-h") ) {
      printHelp() ;
      exit(1);
    }
    if (argv[i] == std::string("-i") && argc>i+1) {
      ok = true ;
      inputfiles = argv[i+1] ;
    }
    if (argv[i] == std::string("-d") && argc>i+1) inputdir = argv[i+1] ;
    if (argv[i] == std::string("-o") && argc>i+1) outputRootName = argv[i+1] ;
    if (argv[i] == std::string("-v") && argc>i+1) verbose = atoi(argv[i+1]) ;
    if (argv[i] == std::string("-l1") && argc>i+1) l1algo =  std::string(argv[i+1]) ;
    if (argv[i] == std::string("--cutTPOccup") && argc>i+1) occupancyCut = atoi(argv[i+1]) ;
  }
  if (!ok) {
    std::cout<<"No input files have been given: nothing to do!"<<std::endl ;
    printHelp() ;
    exit(1);
  }
  
  std::vector<int> algobits ;
  std::vector<std::string> algos = split(l1algo,",") ;
  for (unsigned int i=0 ; i<algos.size() ; i++) algobits.push_back(atoi(algos[i].c_str())) ;


  unsigned int ref = 2 ;



  ///////////////////////
  // book the histograms
  ///////////////////////

  TH2F * occupancyTP = new TH2F("occupancyTP", "Occupancy TP data", 72, 1, 73, 38, -19, 19) ;
  occupancyTP->GetYaxis()->SetTitle("eta index") ;
  occupancyTP->GetXaxis()->SetTitle("phi index") ;
  TH2F * occupancyTPEmul = new TH2F("occupancyTPEmul", "Occupancy TP emulator", 72, 1, 73, 38, -19, 19) ;
  occupancyTPEmul->GetYaxis()->SetTitle("eta index") ;
  occupancyTPEmul->GetXaxis()->SetTitle("phi index") ;

  TH1F * TP = new TH1F("TP", "TP", 256, 0., 256.) ;
  TP->GetXaxis()->SetTitle("TP (ADC)") ;
  TH1F * TPEmul = new TH1F("TPEmul", "TP Emulator", 256, 0., 256.) ;
  TPEmul->GetXaxis()->SetTitle("TP (ADC)") ;
  TH1F * TPEmulMax = new TH1F("TPEmulMax", "TP Emulator max", 256, 0., 256.) ;
  TPEmulMax->GetXaxis()->SetTitle("TP (ADC)") ;
  TH3F * TPspectrumMap3D = new TH3F("TPspectrumMap3D", "TP data spectrum map", 72, 1, 73, 38, -19, 19, 256, 0., 256.) ;
  TPspectrumMap3D->GetYaxis()->SetTitle("eta index") ;
  TPspectrumMap3D->GetXaxis()->SetTitle("phi index") ;

  TH1F * TPMatchEmul = new TH1F("TPMatchEmul", "TP data matching Emulator", 7, -1., 6.) ;
  TH1F * TPEmulMaxIndex = new TH1F("TPEmulMaxIndex", "Index of the max TP from Emulator", 7, -1., 6.) ;
  TH3I * TPMatchEmul3D = new TH3I("TPMatchEmul3D", "TP data matching Emulator", 72, 1, 73, 38, -19, 19, 7, -1, 6) ;
  TPMatchEmul3D->GetYaxis()->SetTitle("eta index") ;
  TPMatchEmul3D->GetXaxis()->SetTitle("phi index") ;

  TH2I * ttfMismatch = new TH2I("ttfMismatch", "TTF mismatch map",  72, 1, 73, 38, -19, 19) ;
  ttfMismatch->GetYaxis()->SetTitle("eta index") ;
  ttfMismatch->GetXaxis()->SetTitle("phi index") ;

  ///////////////////////
  // Chain the trees:
  ///////////////////////

  TChain * chain = new TChain ("EcalTPGAnalysis") ;
  std::vector<std::string> files ;
  if (inputfiles.find(std::string(",")) != std::string::npos) files = split(inputfiles,",") ;
  if (inputfiles.find(std::string(":")) != std::string::npos) {
    std::vector<std::string> filesbase = split(inputfiles,":") ;
    if (filesbase.size() == 4) {
      int first = atoi(filesbase[1].c_str()) ;
      int last = atoi(filesbase[2].c_str()) ;
      for (int i=first ; i<=last ; i++) {
	std::stringstream name ;
	name<<filesbase[0]<<i<<filesbase[3] ;
	files.push_back(name.str()) ;
      }
    }
  }
  for (unsigned int i=0 ; i<files.size() ; i++) {
    files[i] = inputdir+"/"+files[i] ;
    std::cout<<"Input file: "<<files[i]<<std::endl ;
    chain->Add (files[i].c_str()) ;
  }

  EcalTPGVariables treeVars ;
  setBranchAddresses (chain, treeVars) ;

  int nEntries = chain->GetEntries () ;
  std::cout << "Number of entries: " << nEntries <<std::endl ;    



  ///////////////////////
  // Main loop over entries
  ///////////////////////

  for (int entry = 0 ; entry < nEntries ; ++entry) {
    chain->GetEntry (entry) ;
    if (entry%1000==0) std::cout <<"------> "<< entry+1 <<" entries processed" << " <------\n" ; 
    if (verbose>0) std::cout<<"Run="<<treeVars.runNb<<" Evt="<<treeVars.runNb<<std::endl ;

    // trigger selection if any
    bool keep(false) ;
    if (!algobits.size()) keep = true ; // keep all events when no trigger selection
    for (unsigned int algo = 0 ; algo<algobits.size() ; algo++)
      for (unsigned int ntrig = 0 ; ntrig < treeVars.nbOfActiveTriggers ; ntrig++)
	if (algobits[algo] == treeVars.activeTriggers[ntrig]) keep = true ;
    if (!keep) continue ;
    
             
    // loop on towers
    for (unsigned int tower = 0 ; tower < treeVars.nbOfTowers ; tower++) {

      int tp = getEt(treeVars.rawTPData[tower]) ;
      int emul[5] = {getEt(treeVars.rawTPEmul1[tower]),
		     getEt(treeVars.rawTPEmul2[tower]),
		     getEt(treeVars.rawTPEmul3[tower]),
		     getEt(treeVars.rawTPEmul4[tower]),
		     getEt(treeVars.rawTPEmul5[tower])} ;
      int maxOfTPEmul = 0 ;
      int indexOfTPEmulMax = -1 ;
      for (int i=0 ; i<5 ; i++) if (emul[i]>maxOfTPEmul) {
	maxOfTPEmul = emul[i] ; 
	indexOfTPEmulMax = i ;
      }
      int ieta = treeVars.ieta[tower] ;
      int iphi = treeVars.iphi[tower] ;
      int nbXtals = treeVars.nbOfXtals[tower] ;
      int ttf = getTtf(treeVars.rawTPData[tower]) ;


      if (verbose>9 && (tp>0 || maxOfTPEmul>0)) {
	std::cout<<"(phi,eta, Nbxtals)="<<std::dec<<iphi<<" "<<ieta<<" "<<nbXtals<<std::endl ;
	std::cout<<"Data Et, TTF: "<<tp<<" "<<ttf<<std::endl ;
	std::cout<<"Emulator: " ;
	for (int i=0 ; i<5 ; i++) std::cout<<emul[i]<<" " ;
	std::cout<<std::endl ;
      }


      // Fill TP spctrum
      TP->Fill(tp) ;
      TPEmul->Fill(emul[ref]) ;
      TPEmulMax->Fill(maxOfTPEmul) ;
      TPspectrumMap3D->Fill(iphi, ieta, tp) ;


      // Fill TP occupancy
      if (tp>occupancyCut) occupancyTP->Fill(iphi, ieta) ;
      if (emul[ref]>occupancyCut) occupancyTPEmul->Fill(iphi, ieta) ;


      // Fill TP-Emulator matching
      // comparison is meaningful when:
      if (tp>0 && nbXtals == 25) {
	bool match(false) ;
	for (int i=0 ; i<5 ; i++) {
	  if (tp == emul[i]) {
	    TPMatchEmul->Fill(i+1) ;
	    TPMatchEmul3D->Fill(iphi, ieta, i+1) ;
	    match = true ;
	  }
	}
	if (!match) {
	  TPMatchEmul->Fill(-1) ;
	  TPMatchEmul3D->Fill(iphi, ieta, -1) ;
	  if (verbose>5) {
	    std::cout<<"MISMATCH"<<std::endl ;
	    std::cout<<"(phi,eta, Nbxtals)="<<std::dec<<iphi<<" "<<ieta<<" "<<nbXtals<<std::endl ;
	    std::cout<<"Data Et, TTF: "<<tp<<" "<<ttf<<std::endl ;
	    std::cout<<"Emulator: " ;
	    for (int i=0 ; i<5 ; i++) std::cout<<emul[i]<<" " ;
	    std::cout<<std::endl ;
	  }
	}
      }
      if (maxOfTPEmul>0) TPEmulMaxIndex->Fill(indexOfTPEmulMax+1) ;


      // Fill TTF mismatch
      if ((ttf==1 || ttf==3) && nbXtals != 25) ttfMismatch->Fill(iphi, ieta) ;


    } // end loop towers


  } // endloop entries

  

  ///////////////////////
  // Format & write histos
  ///////////////////////


  // 1. TP Spectrum  
  TProfile2D * TPspectrumMap = TPspectrumMap3D->Project3DProfile("yx") ;
  TPspectrumMap->SetName("TPspectrumMap") ;

  // 2. TP Timing
  TH2F * TPMatchEmul2D = new TH2F("TPMatchEmul2D", "TP data matching Emulator", 72, 1, 73, 38, -19, 19) ;
  TH2F * TPMatchFraction2D = new TH2F("TPMatchFraction2D", "TP data: fraction of non-single timing", 72, 1, 73, 38, -19, 19) ;
  TPMatchEmul2D->GetYaxis()->SetTitle("eta index") ; 
  TPMatchEmul2D->GetXaxis()->SetTitle("phi index") ;
  TPMatchEmul2D->GetZaxis()->SetRangeUser(-1,6) ;
  TPMatchFraction2D->GetYaxis()->SetTitle("eta index") ; 
  TPMatchFraction2D->GetXaxis()->SetTitle("phi index") ;
  for (int binx=1 ; binx<=72 ; binx++)    
    for (int biny=1 ; biny<=38 ; biny++) {
      int maxBinz = 5 ;
      double maxCell = TPMatchEmul3D->GetBinContent(binx, biny, maxBinz) ;
      double totalCell(0) ;
      for (int binz=1; binz<=7 ; binz++) {
	double content = TPMatchEmul3D->GetBinContent(binx, biny, binz) ;
	if (content>maxCell) {
	  maxCell = content ;
	  maxBinz = binz ;
	}
	totalCell += content ;
      }
      if (maxCell <=0) maxBinz = 2 ; // empty cell
      TPMatchEmul2D->SetBinContent(binx, biny, float(maxBinz)-2.) ; //z must be in [-1,5] 
      double fraction = 0 ;
      if (totalCell>0) fraction = 1.- maxCell/totalCell ;
      TPMatchFraction2D->SetBinContent(binx, biny, fraction) ;
      if (totalCell > maxCell && verbose>9) {
	std::cout<<"--->"<<std::endl ;	
	for (int binz=1; binz<=7 ; binz++) {	  
	  std::cout<< "(phi,eta, z): (" 
		   << TPMatchEmul3D->GetXaxis()->GetBinLowEdge(binx) 
		   << ", " << TPMatchEmul3D->GetYaxis()->GetBinLowEdge(biny) 
		   << ", " << TPMatchEmul3D->GetZaxis()->GetBinLowEdge(binz)		   
		   << ") Content="<<TPMatchEmul3D->GetBinContent(binx, biny, binz)		   
		   << ", erro="<<TPMatchEmul3D->GetBinContent(binx, biny, binz)	   
		   << std::endl ;	
	}
      }
    }



  TFile saving (outputRootName.c_str (),"recreate") ;
  saving.cd () ;
  
  occupancyTP->Write() ;
  occupancyTPEmul->Write() ;
  
  TP->Write() ;
  TPEmul->Write() ;
  TPEmulMax->Write() ;
  TPspectrumMap->Write() ;

  TPMatchEmul->Write() ; 
  TPMatchEmul3D->Write() ; 
  TPEmulMaxIndex->Write() ;
  TPMatchEmul2D->Write() ; 
  TPMatchFraction2D->Write() ; 

  ttfMismatch->Write() ; 

     
  saving.Close () ;
  delete chain ;

  return 0 ;
}
void plot_pad_size_in_layer(TString digiPar="trd.v13/trd_v13g.digi.par", Int_t nlines=1, Int_t nrows_in_sec=0, Int_t alllayers=1) 
{

  gStyle->SetPalette(1,0);
  gROOT->SetStyle("Plain");
  gStyle->SetPadTickX(1);                        
  gStyle->SetPadTickY(1); 
  gStyle->SetOptStat(kFALSE);
  gStyle->SetOptTitle(kFALSE);

  Bool_t read = false;
  TH2I *fLayerDummy = new TH2I("LayerDummy","",1200,-600,600,1000,-500,500);
  fLayerDummy->SetXTitle("x-coordinate [cm]");
  fLayerDummy->SetYTitle("y-coordinate [cm]");
  fLayerDummy->GetXaxis()->SetLabelSize(0.02);
  fLayerDummy->GetYaxis()->SetLabelSize(0.02);
  fLayerDummy->GetZaxis()->SetLabelSize(0.02);
  fLayerDummy->GetXaxis()->SetTitleSize(0.02);
  fLayerDummy->GetXaxis()->SetTitleOffset(1.5);
  fLayerDummy->GetYaxis()->SetTitleSize(0.02);
  fLayerDummy->GetYaxis()->SetTitleOffset(2);
  fLayerDummy->GetZaxis()->SetTitleSize(0.02);
  fLayerDummy->GetZaxis()->SetTitleOffset(-2);

  TString title;
  TString title1, title2, title3;
  TString buffer;
  TString firstModule = "";
  Int_t blockCounter(0), startCounter(0); // , stopCounter(0);
  Double_t msX(0), msY(0), mpX(0), mpY(0), mpZ(0), psX(0), psY(0);
  Double_t ps1X(0), ps1Y(0), ps2X(0), ps2Y(0), ps3X(0), ps3Y(0);
  Int_t modId(0), layerId(0);
  Double_t sec1(0), sec2(0), sec3(0);
  Double_t row1(0), row2(0), row3(0);
  std::map<float, TCanvas*> layerView;// map key is z-position of modules
  std::map<float, TCanvas*>::iterator it;
  ifstream digipar;

  digipar.open(digiPar.Data(), ifstream::in);
  while (digipar.good()) {
    digipar >> buffer;
    //cout << "(" << blockCounter << ")    " << buffer << endl;
    if (blockCounter == 19)
      firstModule = buffer;
    if (buffer == (firstModule + ":")){
      //cout << buffer << " <===========================================" << endl;
      read = true;
    }
    if (read) {
      startCounter++;
      if (startCounter == 1)   // position of module position in x
      {
	modId = buffer.Atoi();
        layerId = (modId & (15 << 4)) >> 4;  // from CbmTrdAddress.h
      }

      if (startCounter == 5)   // position of module position in x
	mpX = buffer.Atof();
      if (startCounter == 6)   // position of module position in y
	mpY = buffer.Atof();
      if (startCounter == 7)   // position of module position in z
	mpZ = buffer.Atof();
      if (startCounter == 8)   // position of module size in x
	msX = buffer.Atof();
      if (startCounter == 9)   // position of module size in y
	msY = buffer.Atof();

      if (startCounter == 12)   // sector 1 size in y
	sec1 = buffer.Atof();
      if (startCounter == 13)   // position of pad size in x - do not take the backslash (@14)
	ps1X = buffer.Atof();
      if (startCounter == 15)   // position of pad size in y
	ps1Y = buffer.Atof();

      if (startCounter == 17)   // sector 2 size in y
	sec2 = buffer.Atof();
      if (startCounter == 18)   // position of pad size in x
      {
	ps2X = buffer.Atof();
        psX = ps2X;   // for backwards compatibility - sector 2 is default sector
      }
      if (startCounter == 19)   // position of pad size in y
      {
	ps2Y = buffer.Atof();
        psY = ps2Y;   // for backwards compatibility - sector 2 is default sector
      }

      if (startCounter == 21)   // sector 3 size in y
	sec3 = buffer.Atof();
      if (startCounter == 22)   // position of pad size in x
	ps3X = buffer.Atof();
      if (startCounter == 23)   // position of pad size in y
	ps3Y = buffer.Atof();

//      if (startCounter == 23)   // last element
//      {
//        printf("moduleId         : %d, %d\n", modId, layerId);
//        printf("pad size sector 1: (%.2f cm, %.2f cm) pad area: %.2f cm2\n", ps1X, ps1Y, ps1X*ps1Y);
//        printf("pad size sector 2: (%.2f cm, %.2f cm) pad area: %.2f cm2\n", ps2X, ps2Y, ps2X*ps2Y);
//        printf("pad size sector 3: (%.2f cm, %.2f cm) pad area: %.2f cm2\n", ps3X, ps3Y, ps3X*ps3Y);
//        printf("rows per sector  : %.1f %.1f %.1f\n", sec1/ps1Y, sec2/ps2Y, sec3/ps3Y);
//        printf("\n");
//      }

      //printf("module position: (%.1f, %.1f, %.1f) module size: (%.1f, %.1f) pad size: (%.2f, %.2f) pad area: %.2f\n",mpX,mpY,mpZ,2*msX,2*msY,psX,psY,psX*psY);

      if (startCounter == 23) { // if last element is reached
	startCounter = 0; // reset

        if ( alllayers == 0 )   
          if ( !((layerId == 0) || (layerId == 4) || (layerId == 8)) )   // plot only 1 layer per station
            continue;

        row1 = sec1 / ps1Y;
        row2 = sec2 / ps2Y;
        row3 = sec3 / ps3Y;

	it = layerView.find(mpZ);
	if (it == layerView.end()){	
	  //	  title.Form("pad_size_layer_at_z_%.2fm",mpZ);  
	  title.Form("%02d_pad_size_layer%02d", layerId, layerId);  
	  layerView[mpZ] = new TCanvas(title,title,1200,1000);
	  fLayerDummy->DrawCopy("");

        // now print cm2 in the center
	layerView[mpZ]->cd();
	title.Form("cm^{2}");  // print cm2
	TPaveText *text = new TPaveText(0 - 28.5,
					0 - 28.5,
					0 + 28.5,
					0 + 28.5
					);
	text->SetFillStyle(1001);
	text->SetLineColor(1);
        text->SetFillColor(kWhite);
	text->AddText(title);
	text->Draw("same");
	}

        // print pad size in each module
	layerView[mpZ]->cd();
	//	title.Form("%2.0fcm^{2}",psX*psY);  // print pad size
	//	title.Form("%.0f",psX*psY);  // print pad size - 1 digit
	TPaveText *text = new TPaveText(mpX - msX,
					mpY - msY,
					mpX + msX,
					mpY + msY
					);
	text->SetFillStyle(1001);
	text->SetLineColor(1);
	//        text->SetFillColor(kViolet);

	// vary background color
//        if ((int)(psX*psY+.5) == 2)
//        {
//          text->SetFillColor(kOrange + 9);
//        } 
//        else 
        if (psX*psY <= 1.1)
        {
          text->SetFillColor(kOrange + 10);
        }
        else if (psX*psY <= 2.1)
        {
          text->SetFillColor(kOrange -  3);
        }
        else if (psX*psY <= 3.1)
        {
          text->SetFillColor(kOrange -  4);
        }
        else if (psX*psY <= 5)
        {
          text->SetFillColor(kOrange + 10 - ((int)(psX*psY+.5)-1) * 2);
//        printf("%2.1f: %d\n", psX*psY, 10 - ((int)(psX*psY+.5)-1) * 2);
        } 
        else if (psX*psY <= 10)
	{
          text->SetFillColor(kSpring + 10 - ((int)(psX*psY+.5)-4) * 2);
//        printf("%2.1f: %d\n", psX*psY, 10 - ((int)(psX*psY+.5)-4) * 2);
        } 
        else if (psX*psY > 10)
	{
          text->SetFillColor(kGreen);
//        printf("%2.1f: %s\n", psX*psY, "green");
        } 

        if (nrows_in_sec == 1)   // print number of rows in sector
	{
   	  title1.Form("%3.1f - %2.0f", ps1X*ps1Y, row1);  // print pad size and nrows - 2 digits - sector 1
	  title2.Form("%3.1f - %2.0f", ps2X*ps2Y, row2);  // print pad size and nrows - 2 digits - sector 2
	  title3.Form("%3.1f - %2.0f", ps3X*ps3Y, row3);  // print pad size and nrows - 2 digits - sector 3
	}
        else
	{
   	  title1.Form("%3.1f",ps1X*ps1Y);  // print pad size - 2 digits - sector 1
	  title2.Form("%3.1f",ps2X*ps2Y);  // print pad size - 2 digits - sector 2
	  title3.Form("%3.1f",ps3X*ps3Y);  // print pad size - 2 digits - sector 3
	}

        if (nlines==1)   // plot pad size for central sector only
	{
	  text->AddText(title2);
        }
        else   // plot pad size for all 3 sectors
	{
	  text->AddText(title1);
	  text->AddText(title2);
	  text->AddText(title3);
        }
	text->Draw("same");
	//layerView[mpZ]->Update();
      }
    }  
    blockCounter++;
  }