Example #1
0
void processmarriage(const char* ifname="marry.txt",const char* ofname="marry.root"){

  vector<int> mage;
  vector<float> mpercent;

  vector<int> fage;
  vector<float> fpercent;

  mage.push_back(0);
  mpercent.push_back(0.0);
  fage.push_back(0);
  fpercent.push_back(0.0);

  ifstream marry(ifname);
  while(1){
    int gender,year;
    float percent;
    marry >> gender >> year >> percent;
    if(!marry.good())break;
    if(gender == 1){
      mage.push_back(year);
      mpercent.push_back(percent);
    }
    if(gender == 0){
      fage.push_back(year);
      fpercent.push_back(percent);
    }
  }

  TFile* outfile = new TFile(ofname,"RECREATE");

  TGraph* man = new TGraph(mage.size());
  TGraph* woman = new TGraph(fage.size());

  for(int i = 0; i < (int)mage.size(); i++){
    man->SetPoint(i,mage[i],mpercent[i]);
  }
  for(int i = 0; i < (int)fage.size(); i++){
    woman->SetPoint(i,fage[i],fpercent[i]);
  }

  man->SetName("man");
  woman->SetName("woman");
  man->Write();
  woman->Write();
  outfile->Write();
  outfile->Close();

}
Example #2
0
void createInputs(int n = 2) 
{
   for(UInt_t i = 0; i < (UInt_t)n; ++i ) {
      TFile *file = TFile::Open(TString::Format("input%d.root",i),"RECREATE");
      TH1F * h = new TH1F("h1","",10,0,100);
      h->Fill(10.5); h->Fill(20.5);
 
      Int_t nbins[5];
      Double_t xmin[5];
      Double_t xmax[5];
      for(UInt_t j = 0; j < 5; ++j) {
         nbins[j] = 10; xmin[j] = 0; xmax[j] = 10;
      }
      THnSparseF *sparse = new THnSparseF("sparse", "sparse", 5, nbins, xmin, xmax);
      Double_t coord[5] = {0.5, 1.5, 2.5, 3.5, 4.5};
      sparse->Fill(coord);
      sparse->Write();
      
      THStack *stack = new THStack("stack","");
      h = new TH1F("hs_1","",10,0,100);
      h->Fill(10.5); h->Fill(20.5);
      h->SetDirectory(0);
      stack->Add(h);
      h = new TH1F("hs_2","",10,0,100);
      h->Fill(30.5); h->Fill(40.5);
      h->SetDirectory(0);
      stack->Add(h);
      stack->Write();

      TGraph *gr = new TGraph(3);
      gr->SetName("exgraph");
      gr->SetPoint(0,1,1);
      gr->SetPoint(1,2,2);
      gr->SetPoint(2,3,3);
      
      gr->Write();
      
      TTree *tree = new TTree("tree","simplistic tree");
      Int_t data = 0;
      tree->Branch("data",&data);
      for(Int_t l = 0; l < 2; ++l) {
         data = l;
         tree->Fill();
      }
      
      file->Write();
      delete file;
   }
}
void builtVetoMult2reader(string Input = ""){

	int card1 = 13;
	int card2 = 18;
	Bool_t useThresh = true; // if true, also enables fitting LED peaks
	
	
	//led (low) qdc threshold values from findThresh.C
		Int_t ledthresh[numPanels] = {136, 129, 115, 108, 172, 129, 129, 122, 129, 108, 122, 115, 108, 115, 108, 186, 65, 165, 100, 136, 93, 100, 143, 79, 136, 115, 93, 122, 158, 172, 129, 93};
	
		//muon (high) qdc threshold values
		Int_t muonthresh[numPanels] = {0};

		for (Int_t k=0; k<numPanels; k++){
			muonthresh[k] = 500;
		}

	
	// Input a list of run numbers
	if (Input == "") Char_t InputName[200] = "builtVeto_DebugList";
	else Char_t InputName[200] = Input.c_str();
	Char_t InputFile[200];
	sprintf(InputFile,"%s.txt",InputName);
	ifstream InputList;
	InputList.open(InputFile);
	Char_t TheFile[200];
	
	// Set up output file(s)
	Char_t OutputFile[200];
	sprintf(OutputFile,"%s.root",InputName);
	TFile *RootFile = new TFile(OutputFile, "RECREATE");	
  	TH1::AddDirectory(kFALSE); // Global flag: "When a (root) file is closed, all histograms in memory associated with this file are automatically deleted."
	
	ofstream lowdt;
	lowdt.open ("zerodeltat.txt");

	//=== Global counters / variables / plots ===

		Int_t run = 0;
		Float_t duration = 0;

		const Int_t nqdc_bins=1400;  // this gives 3 qdc / bin
		const Float_t ll_qdc=0.;
		const Float_t ul_qdc=4300.;

		Float_t Tnew = 0;
		Float_t Told = 0;
		Float_t deltaT = 0;

		Float_t totdur = 0;
		Int_t badtimecount = 0;
		Int_t baddurcount = 0;

		Float_t ledcount[numFiles] = {0};
		Float_t ledcountmax[numFiles] = {0};
		Float_t ledtimemax[numFiles] = {0}; 
		Float_t totledcount = 0;

		Float_t muoncount[numFiles] = {0};
		Float_t totmuoncount = 0;
		Int_t omitteddur[numFiles] = {0};


		Float_t ledQDCcount[numFiles][numPanels] = {0};
		Float_t totledQDC[numFiles][numPanels] = {0};
		Float_t quadtotledQDC[numFiles][numPanels] = {0};
		Float_t AvgledQDC[numFiles][numPanels] = {0};
		Float_t rmsledQDC[numFiles][numPanels] = {0};
		Float_t AvgFileLEDQDC[numFiles] = {0};
		Float_t totFileLEDQDC[numFiles] = {0};
		Float_t totFileledQDCcount[numFiles] = {0};
		Float_t slope[numFiles] = {0}; //slope of # leds vs duration
		Int_t runnum[numFiles] = {0}; //array of run numbers
		
		// get number of files in dataset for the TGraph
		Int_t filesToScan = 0;
		Int_t filesScanned = 0;
	  	while(true) { 
			InputList >> run; 
			if (InputList.eof()) 		break;
			filesToScan++; 
		}
	  	cout << "Scanning " << numFiles << " files." << endl;	  	
	  	InputList.close();
	  	InputList.open(InputFile);
	  	run=0;
	 	TGraph *SCorruption = new TGraph(filesToScan);
	 	Int_t BadTSTotal = 0;
		if (filesToScan != numFiles){
			cout << " Error: number of files in builtVetoMult.C does not equal number of files in builtVeto_DebugList.txt" << endl;
			break;
		}

	 	TH1D *TotalCorruptionInTime = new TH1D("TotalCorruptionInTime","corrupted entries during run (entry method)",(Int_t)3600/5,0,3600);
	 	TotalCorruptionInTime->GetXaxis()->SetTitle("time (5 sec / bin)");
	 	Bool_t PlotCorruptedEntries = true; // flag for plotting corrupted entries in time for EACH RUN

	 	TH1D *TotalMultiplicity = new TH1D("TotalMultiplicity","Events over threshold",32,0,32);
	 	TotalMultiplicity->GetXaxis()->SetTitle("number of panels hit");
	 	Bool_t PlotMultiplicity = true;	// flag to plot multiplicity for EACH RUN

		Int_t ledcut = 20;
		TH1D *hLEDCutMult = new TH1D("hLEDCutMult","LED Events over threshold (ledcut = 20) ",32,0,32);
	 	hLEDCutMult->GetXaxis()->SetTitle("number of panels hit");

		TH1D *hLEDCutMulttest = new TH1D("hLEDCutMult","LED Events over threshold (ledcut = 2) ",32,0,32);
	 	hLEDCutMulttest->GetXaxis()->SetTitle("number of panels hit");		

		TH1D *hLEDCutDT = new TH1D("hLEDCutDT","Delta T between LED Events over threshold (ledcut = 20) ",20000,0,20);
	 	hLEDCutDT->GetXaxis()->SetTitle("time (seconds)");
		
		TH1D *hLEDCutDTFocus = new TH1D("hLEDCutDTFocus","Delta T between LED Events over threshold (ledcut = 20)",100000,7,8); //graph DT peak with high resolution
		hLEDCutDTFocus->GetXaxis()->SetTitle("time (seconds)");

		TH1D *hLEDpertime = new TH1D("hLEDpertime","LED events vs run duration (ledcut = 10) ",3600,0,3600);
	 	hLEDpertime->GetXaxis()->SetTitle("run duration");
		hLEDpertime->GetYaxis()->SetTitle("# of LED events");

		TH1D *hAvgMuonQDC = new TH1D("hAvgMuonQDC","Muon Multiplicity vs Muon Avg QDC value",1000,0,5000);
	 	hAvgMuonQDC->GetXaxis()->SetTitle("Muon Avg QDC value");
		hAvgMuonQDC->GetYaxis()->SetTitle("Multiplicity");

	
		Char_t hname[50];
/*		
		for (Int_t j=0; j<numFiles; j++){
			
			for (Int_t i=0; i<numPanels; i++){
				sprintf(hname,"File%dhRawQDC%d",j,i);
				hRawQDC[j][i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);
				sprintf(hname,"File%dhLEDCutQDC%d",j,i);
				hLEDCutQDC[j][i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);
				sprintf(hname,"File%dhMuonCutQDC%d",j,i);
				hMuonCutQDC[j][i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);
			}
		}
*/
		for (Int_t i=0; i<numFiles; i++){
			sprintf(hname,"ledTime_run%d",i);
			ledTime[i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);

		}

		for (Int_t i=0; i<numPanels; i++){
			sprintf(hname,"MuonMultiplicityGT%d",i);
			hMuonMult[i] = new TH1F(hname,hname,32,0,32);
			sprintf(hname,"MuonManyTrigQDCPanel%d",i);
			hMuonManyQDC[i] = new TH1F(hname,hname,3600,0,3600);
			sprintf(hname,"hLEDAvgQDCPanel%d",i);
			hLEDAvgQDCPanel[i] = new TH1F(hname,hname,runspace,runmin,runmax);
			sprintf(hname,"hLEDrmsQDCPanel%d",i);
			hLEDrmsQDCPanel[i] = new TH1F(hname,hname,runspace,runmin,runmax);
		}

	//=== End ===


	// Loop over files
	while(true){

		// initialize 
		InputList >> run;
		if (InputList.eof()) 		break;
		sprintf(TheFile,"/global/project/projectdirs/majorana/data/mjd/surfmjd/data/built/P3JDY/OR_run%u.root",run); 	
		TChain *VetoTree = new TChain("VetoTree");
		VetoTree->AddFile(TheFile);
		Long64_t nentries = VetoTree->GetEntries();
		
		MJTRun *VetoRun = new MJTRun();
		MGTBasicEvent *vetoEvent = new MGTBasicEvent();
		UInt_t mVeto = 0;
		
		//set branch addresses
		VetoTree->SetBranchAddress("run",&VetoRun);
		VetoTree->SetBranchAddress("mVeto",&mVeto);
		VetoTree->SetBranchAddress("vetoEvent",&vetoEvent);
	
	

		// Unsigned int from MGTypes.hh -- kData=0, kTest=1, kCalibration=2, kMC=3, kUndefined=4																	  
		printf("Run Type: %u\n",VetoRun->GetRunType());  
		
//-------------

    	//=== Single-file counters / variables / plots

			Bool_t IsEmpty = false;

			Int_t BadTSInFile = 0;
			Float_t corruption = 0;
			if (PlotCorruptedEntries) {
				TH1D *CorruptionInTime = new TH1D("CorruptionInTime","corrupted entries during run (entry method)",(Int_t)duration/5,0,(Int_t)duration);
				CorruptionInTime->GetXaxis()->SetTitle("time (5 sec / bin)");
			}
			
			Int_t lednumPanelsHit = 0;
			Int_t muonnumPanelsHit = 0;
			runnum[filesScanned] = run;
			
			Float_t MuonQDCtot = 0;
			Float_t AvgMuonQDCvalue = 0;
			
			sprintf(hname,"ledtimestamp_run%d",run);
			ledtimestamp[filesScanned] = new TGraph(nentries);
			ledtimestamp[filesScanned]->SetName(hname);
			
			//check if runmin and runmax are correct
			if (filesScanned == 0 && runmin != run){
				cout << "Runmin is not set correctly (should be first run number in debug list" << endl;
				break;
			}	
			
			if (filesScanned == numFiles -1 && runmax != run){
				cout << "Runmax is not set correctly (should be last run number in debug list" << endl;
				break;
			}
			
			if (PlotMultiplicity) {
				TH1D *OneRunMultiplicity = new TH1D("multiplicity","multiplicity of veto entries",32,0,32);
  				OneRunMultiplicity->GetXaxis()->SetTitle("number of panels hit");
  			}
			
			TGraph *AvgFileLEDQDCgraph = new TGraph(numFiles);
			AvgFileLEDQDCgraph->SetTitle("Average LED QDC value per file");
			AvgFileLEDQDCgraph->GetXaxis()->SetTitle("File Number");
			AvgFileLEDQDCgraph->GetYaxis()->SetTitle("Avg QDC value");

			TGraph *ledFiletime = new TGraph(numFiles);
			ledFiletime->SetTitle("# of LEDs vs run number");
			ledFiletime->GetXaxis()->SetTitle("Run number");
			ledFiletime->GetYaxis()->SetTitle("Total # of LEDs");
			
			TGraph *ledfitslope = new TGraph(numFiles);
			ledfitslope->SetTitle("(# of led vs run duration) linear fit slope vs run number");
			ledfitslope->GetXaxis()->SetTitle("Run number");
			ledfitslope->GetYaxis()->SetTitle("slope (corresponds to frequency)");

		//=== End ===

		// Loop over VetoTree entries
		printf("Now scanning run %i: %lli entries, %.2f sec.  \n",run,nentries,duration);
		if (nentries == 0) IsEmpty = true;
		for (int z = 0; z < nentries; z++) {
				VetoTree->GetEntry(z);
				
				//Access run duration
				duration = VetoRun->GetStopTime() - VetoRun->GetStartTime();
				
				// Access the MJTVetoData objects "vd"
				MJTVetoData *vd[numPanels];
				for (int i=0; i<numPanels; i++) { vd[i] = dynamic_cast<MJTVetoData*>(vetoEvent->GetDetectorData()->At(i)); }
				
				if (vd[0]->GetEventCount() != vd[0]->GetScalerCount()) 
				printf("Warning!  EventCount and ScalerCount don't match!\n");
		
				Bool_t isBadTS = vd[0]->IsBadTS();
				double TimeStamp = vd[0]->GetTimeStamp()/1E8; //scaler timestamp in seconds
					
				//sort data into arrays
				// Sort raw data into arrays and then display.
				// This may not be totally necessary, but makes hit pattern analysis easier
				//   to match to the physical veto panel locations, and Yuri's wiring diagrams.
				// Most things are cast to int's.  
				// Original types can be found in MJTVetoData.hh and MGDetectorData.hh if necessary.
				const int card1 = 13;
				const int card2 = 18;
				int Card[numPanels] = {0};
				int QDC[numPanels] = {0};
				int IsUnderThreshold[numPanels] = {0};
				int IsOverflow[numPanels] = {0};
				int ID[numPanels] = {0};
				long Index[numPanels] = {0};
				int k = 0;
				for (int j = 0; j<numPanels; j++)	{
					if (vd[j]){
						k = vd[j]->GetChannel();	// goes from 0 to 15
						if (vd[j]->GetCard() == card1) {
							Card[k] = vd[j]->GetCard();
							QDC[k] = (int)vd[j]->GetAmplitude();
							IsUnderThreshold[k] = (int)vd[j]->IsUnderThreshold();
							IsOverflow[k] = (int)vd[j]->IsOverflow();
							ID[k] = vd[j]->GetID();
							Index[k] = (Long_t)vd[j]->GetIndex();
						}
						else if (vd[j]->GetCard() == card2) {
							Card[16+k] = vd[j]->GetCard();
							QDC[16+k] = (int)vd[j]->GetAmplitude();
							IsUnderThreshold[16+k] = (int)vd[j]->IsUnderThreshold();
							IsOverflow[16+k] = (int)vd[j]->IsOverflow();	
							ID[16+k] = vd[j]->GetID();
							Index[16+k] = (Long_t)vd[j]->GetIndex();
						}
					}
				}
				
		

				//=====================BEGIN ACTUAL GODDAMMED ANALYSIS=================
				//change Bool_t isLED to isIdentified? (0=unidentified, 1 = LED, 2 = muon)?


				Bool_t isLED = false; 		//if true, event is LED (first assume event is not an LED)
		
				if (isBadTS) { 
					BadTSInFile++;
					TotalCorruptionInTime->Fill(TimeStamp);
					if (PlotCorruptedEntries) CorruptionInTime->Fill(TimeStamp);
				}

				// multiplicity of panels above threshold
		       		for (int k=0; k<numPanels; k++) { 
				//	hRawQDC[filesScanned][k]->Fill(QDC[k]);
				
				

				// count lednumPanelsHit and muonnumPanelsHit
				if (useThresh) { 
					if (QDC[k]>ledthresh[k]) lednumPanelsHit++; 
					if (QDC[k]>muonthresh[k]) muonnumPanelsHit++;
				}
				else { if (!IsUnderThreshold[k]) lednumPanelsHit++; }
				
				}
		      		TotalMultiplicity->Fill(lednumPanelsHit);			
		       		if (PlotMultiplicity) OneRunMultiplicity->Fill(lednumPanelsHit);

				if (lednumPanelsHit >= 2){
					hLEDCutMulttest->Fill(lednumPanelsHit);
				}

				//include LED cut
				if (lednumPanelsHit >= ledcut){
					isLED = true; // if true, marks the signal as an LED
					hLEDCutMult->Fill(lednumPanelsHit);
					ledcount[filesScanned] +=1;
/*					if(filesScanned == 0) {
						cout << "led count for file 0 is: " << ledcount[filesScanned] << endl;
					}
*/
					//fill ledtimestamp
					ledtimestamp[filesScanned]->SetPoint(ledcount[filesScanned], TimeStamp, ledcount[filesScanned]);
	
					hLEDpertime->Fill(TimeStamp,ledcount[filesScanned]);
					ledTime[filesScanned]->Fill(TimeStamp,ledcount[filesScanned]);
					
					if (ledcountmax[filesScanned] < ledcount[filesScanned]) ledcountmax[filesScanned] = ledcount[filesScanned];

					if (ledtimemax[filesScanned] < TimeStamp) ledtimemax[filesScanned] = TimeStamp;
					
					for (int k=0; k<numPanels; ++k) {
						if (useThresh) { 
							if (QDC[k]>ledthresh[k]){
							//	hLEDCutQDC[filesScanned][k]->Fill(QDC[k]);
								ledQDCcount[filesScanned][k] += 1;
								totledQDC[filesScanned][k] += QDC[k];
								quadtotledQDC[filesScanned][k] += QDC[k]*QDC[k];
								
							}
						}
						else {
						//	if (!IsUnderThreshold[k]) hLEDCutQDC[filesScanned][k]->Fill(QDC[k]); 
						}	
						
					}
					//find deltat
					Tnew = TimeStamp;
					//see if 0 in deltat is from the first event
					if (ledcount[filesScanned] == 1 | ledcount[filesScanned] == 2){
//						cout << "led count = " << ledcount[filesScanned] << " | Timestamp = " << Tnew << endl;
					}					
					deltaT = Tnew - Told;
					if (deltaT < 0.01 || deltaT > 10000){
					lowdt << "delta T = " << deltaT << " | led #'s = " << ledcount[filesScanned]-1 << " and " << ledcount[filesScanned] << "run # = " << run << endl;

					}
					Told = Tnew;
					hLEDCutDT->Fill(deltaT);
					hLEDCutDTFocus->Fill(deltaT);
					if (TimeStamp > 10000){
						badtimecount++;
					}
	
				}
			
				//count multiplicity for muon cut
				if (!isLED && muonnumPanelsHit > 2 && muonnumPanelsHit < ledcut){
					muoncount[filesScanned] += 1;
										
					for (Int_t k=0; k<numPanels; k++){
						if (muonnumPanelsHit > k) hMuonMult[k]->Fill(muonnumPanelsHit);
						if(QDC[k]>muonthresh[k]){
							//hMuonCutQDC[filesScanned][k]->Fill(QDC[k]);
							hMuonManyQDC[k]->Fill(QDC[k]);
							MuonQDCtot += QDC[k];
						}
					}			
					AvgMuonQDCvalue = MuonQDCtot/((double) muonnumPanelsHit);
					hAvgMuonQDC->Fill(AvgMuonQDCvalue);
					MuonQDCtot = 0;
					
				}
				
				//=====================END ACTUAL GODDAMMED ANALYSIS===================
			
			lednumPanelsHit=0;
			muonnumPanelsHit=0;

		}	// End loop over VetoTree entries.

		// === END OF FILE Output & Plotting ===
		if (filesScanned == 0){
			TDirectory *runmultiplicity = RootFile->mkdir("RunMultiplicity");	
			TDirectory *corruptionintime = RootFile->mkdir("CorruptionInTime");
		}
		
		corruption = ((Float_t)BadTSInFile/nentries)*100;
		printf(" Corrupted scaler entries: %i of %lli, %.3f %%.\n",BadTSInFile,nentries,corruption);
		if(run>45000000) SCorruption->SetPoint(filesScanned,run-45000000,corruption);
		else SCorruption->SetPoint(filesScanned,run,corruption);

		if (PlotCorruptedEntries) {
			RootFile->cd("CorruptionInTime");
			char outfile1[200];	
			sprintf(outfile1,"CorruptionInTime_Run%i",run);
			CorruptionInTime->Write(outfile1,TObject::kOverwrite);
			RootFile->cd();
		}
		if (PlotMultiplicity) {
			RootFile->cd("RunMultiplicity");
			char outfile2[200];
			sprintf(outfile2,"Multiplicity_Run%i",run);
			OneRunMultiplicity->Write(outfile2,TObject::kOverwrite);
			RootFile->cd();
		}

		if (!IsEmpty && ledcount[filesScanned] > 2){
			ledTime[filesScanned]->Fit("pol1");
			slope[filesScanned] = ledTime[filesScanned]->GetFunction("pol1")->GetParameter(1);
		}
		
		for (int j=0; j<numFiles; ++j){
			ledFiletime->SetPoint(j, runnum[j], ledcount[j]);
		}

		// ==========================

		delete VetoTree;
		cout << "files Scanned: " << filesScanned << endl;
		if (duration >= 0){
			totdur += duration;
		}
		if (duration < 0){
			omitteddur[baddurcount]=run;
			baddurcount +=1;
		}
		cout << "totdur = " << totdur << " | duration = " << duration << endl;
		filesScanned++;
	} // End loop over files.

	//calculate/fill qdc mean and rms
	for (int k=0; k<numPanels; ++k){
		for (int j=0; j<numFiles; ++j){
			if(k == 15){
				AvgledQDC[j][k] = 0;
				rmsledQDC[j][k] = 0;
			}
			else{
				AvgledQDC[j][k] = totledQDC[j][k]/ledQDCcount[j][k];
				rmsledQDC[j][k] = sqrt(quadtotledQDC[j][k]/ledQDCcount[j][k]);
			}
			hLEDAvgQDCPanel[k]->Fill(runnum[j],AvgledQDC[j][k]);
			hLEDrmsQDCPanel[k]->Fill(runnum[j],rmsledQDC[j][k]);
//		cout << "panel number: " << k << " | mean value " << AvgQDC[k] << " | rms value " << rmsQDC[k] << endl;
		}
	} 

	//calculate qdc mean for each file
	for (int j=0; j<numFiles; ++j){		
		for (int k=0; k<numPanels; ++k){
			totFileLEDQDC[j] += totledQDC[j][k];
			totFileledQDCcount[j] += ledQDCcount[j][k];
		}
		AvgFileLEDQDC[j] = totFileLEDQDC[j]/totFileledQDCcount[j];
		AvgFileLEDQDCgraph->SetPoint(j, runnum[j], AvgFileLEDQDC[j]);
		if (!IsEmpty){
			ledfitslope->SetPoint(j,runnum[j],slope[j]);
		}
	}
	
	for (int i=0; i<numFiles; ++i){
		printf("led count for file %i: %i. \n", i,ledcount[i]);	
		totledcount += ledcount[i];

		printf("muon count for file %i: %i. \n", i,muoncount[i]);	
		totmuoncount += muoncount[i];
	}

	// === END OF SCAN Output & Plotting ===
	printf("Finished loop over files.\n");
	printf("Total # of Files: %i. \n",numFiles);
	printf("Total Duration: %f seconds. \n",totdur);
	printf("Total LED Count: %f. \n", totledcount);
	printf("Total Muon Count: %f. \n", totmuoncount);	
	printf("Number of Bad Durations: %f. \n", baddurcount);
	

//	TCanvas *c1 = new TCanvas("c1", "Bob Ross's Canvas",600,600);
//	c1->SetGrid();
	SCorruption->SetMarkerColor(4);
	SCorruption->SetMarkerStyle(21);
	SCorruption->SetMarkerSize(0.5);
	SCorruption->SetTitle("Corruption in scaler card");
	SCorruption->GetXaxis()->SetTitle("Run");
	SCorruption->GetYaxis()->SetTitle("% corrupted events");
//	SCorruption->Draw("ALP");	
	
	SCorruption->Write("ScalerCorruption",TObject::kOverwrite);

	TotalCorruptionInTime->Write("TotalCorruptionInTime",TObject::kOverwrite);

	TotalMultiplicity->Write("TotalMultiplicity",TObject::kOverwrite);


//	TCanvas *c2 = new TCanvas("c2", "LEDCutMult",600,600);
//	c2->SetGrid();
//	c2->SetLogy();
//	hLEDCutMult->Draw();
	hLEDCutMult->Write();

//	TCanvas *c3 = new TCanvas("c3", "LEDCutMulttest",600,600);
//	c3->SetGrid();
//	c3->SetLogy();
//	hLEDCutMulttest->Draw();
	hLEDCutMulttest->Write();

//	TCanvas *c4 = new TCanvas("c4", "LEDCutDT",600,600);
//	c4->SetGrid();
//	hLEDCutDT->Draw();
	hLEDCutDT->Write();

//	TCanvas *c5 = new TCanvas("c5", "AvgFileLEDQDCgraph",600,600);
//	c5->SetGrid();
	AvgFileLEDQDCgraph->SetMarkerColor(4);
	AvgFileLEDQDCgraph->SetMarkerStyle(21);
	AvgFileLEDQDCgraph->SetMarkerSize(0.5);
//	AvgFileLEDQDCgraph->Draw("AP");	
	AvgFileLEDQDCgraph->Write("AvgFileLEDQDCgraph",TObject::kOverwrite);


//	TCanvas *c6 = new TCanvas("c6", "ledFiletime",600,600);
//	c6->SetGrid();
	ledFiletime->SetMarkerColor(4);
	ledFiletime->SetMarkerStyle(21);
	ledFiletime->SetMarkerSize(0.5);
//	ledFiletime->Draw("ALP");	
	ledFiletime->Write("LEDFileTime",TObject::kOverwrite);


//	TCanvas *c7 = new TCanvas("c7", "LEDpertime",600,600);
//	c7->SetGrid();
//	hLEDpertime->Draw();
//	hLEDpertime->Write();

//	TCanvas *c9 = new TCanvas("c9", "slope vs file number", 600,600);
//	c9->SetGrid();
	ledfitslope->SetMarkerColor(4);
	ledfitslope->SetMarkerStyle(21);
	ledfitslope->SetMarkerSize(0.5);
//	ledfitslope->Draw("ALP");	
	ledfitslope->Write("LEDFitSlope",TObject::kOverwrite);
	
//	TCanvas *c10 = new TCanvas("c10", "avg muon qdc value", 600,600);
//	c10->SetGrid();
//	hAvgMuonQDC->Draw();
	hAvgMuonQDC->Write();
	
//	TCanvas *c11 = new TCanvas("c11", "LEDCutDTFocus",600,600);
//	c11->SetGrid();
//	hLEDCutDTFocus->Draw();
	hLEDCutDTFocus->Write();
	
//	TCanvas *vcan0 = new TCanvas("vcan0","raw veto QDC, panels 1-32",0,0,1600,900);
//	vcan0->Divide(8,4,0,0);
	
//	TCanvas *vcan1 = new TCanvas("vcan1","LED Cut veto QDC (ledcut = 20), panels 1-32",0,0,1600,900);
//	vcan1->Divide(8,4,0,0);

//	TCanvas *vcan2 = new TCanvas("vcan2","Muon Cut veto QDC (all qdc over muon thresh), panels 1-32",0,0,1600,900);
//	vcan2->Divide(8,4,0,0);

//	TCanvas *vcan9 = new TCanvas("vcan9","Muon Cut Multiplicity (muon cut = 0-31)", 0,0,1600,900);
//	vcan9->Divide(8,4,0,0);	
//	TCanvas *vcan10 = new TCanvas("vcan10","LED event vs time (ledcut = 20), files 1-2",0,0,800,600);
//	vcan10->Divide(2);
	
//	TCanvas *vcan11 = new TCanvas("vcan11","Muon QDC numPanelsHit > 2 && < 20", 0,0,1600,900);
//	vcan11->Divide(8,4,0,0);

//	TCanvas *vcan12 = new TCanvas("vcan12","Avg LED QDC", 0,0, 1600,900);
//	vcan12->Divide(8,4,0,0);

//	TCanvas *vcan13 = new TCanvas("vcan13","rms LED QDC", 0,0,1600,900);
//	vcan13->Divide(8,4,0,0);

//	TCanvas *vcan14 = new TCanvas("vcan14","ledtimestamps",0,0,1600,900);
	
	
	Char_t buffer[2000];
	printf("\n Calibration Table:\n  Panel / Mean,error / Sigma,error / Chi-square/NDF (~1?) / LED Peak Pos.\n");

	
	RootFile->Write();

	TDirectory *ledtime = RootFile->mkdir("LEDTime");
	for (Int_t i=0; i<filesToScan; i++){

		RootFile->cd("LEDTime");
//		vcan10->cd(i+1);
//		TVirtualPad *vpad10 = vcan10->cd(i+1);
//		ledTime[i]->Draw();
		ledTime[i]->Write();

	}
	
	TDirectory *rawqdc = RootFile->mkdir("RawQDC");
	TDirectory *ledcutqdc = RootFile->mkdir("LEDCutQDC");
	TDirectory *muoncutqdc = RootFile->mkdir("MuonCutQDC");
	TDirectory *muonmult = RootFile->mkdir("MuonMult");
	TDirectory *muonmanyqdc = RootFile->mkdir("MuonManyQDC");
	TDirectory *avgledqdc = RootFile->mkdir("AvgLEDQDC");
	TDirectory *rmsledqdc = RootFile->mkdir("rmsLEDQDC");
	TDirectory *ledtimestamps = RootFile->mkdir("LEDTimestamps");

	
	for (Int_t j=0; j<numFiles; j++){


		for (Int_t i=0; i<numPanels; i++){
		
			RootFile->cd("RawQDC");
//			vcan0->cd(i+1);
//			TVirtualPad *vpad0 = vcan0->cd(i+1); vpad0->SetLogy();
//			hRawQDC[j][i]->Draw();
//			hRawQDC[j][i]->Write();		// write the raw QDC without fitting

			
			RootFile->cd("LEDCutQDC");
//			vcan1->cd(i+1);
//			TVirtualPad *vpad1 = vcan1->cd(i+1); vpad1->SetLogy();
//			hLEDCutQDC[j][i]->Draw();
//			hLEDCutQDC[j][i]->Write();		
		
			RootFile->cd("MuonCutQDC");
//			vcan2->cd(i+1);
//			TVirtualPad *vpad2 = vcan2->cd(i+1); vpad2->SetLogy();
//			hMuonCutQDC[j][i]->Draw();
//			hMuonCutQDC[j][i]->Write();	

		}
		RootFile->cd("LEDTimestamps");
//		vcan14->cd(1);
//		vcan14->SetLogy();
		ledtimestamp[j]->SetMarkerColor(4);
		ledtimestamp[j]->SetMarkerStyle(21);
		ledtimestamp[j]->SetMarkerSize(0.5);
		ledtimestamp[j]->SetTitle("ledcount vs timestamp");
		ledtimestamp[j]->GetXaxis()->SetTitle("timestamp");
		ledtimestamp[j]->GetYaxis()->SetTitle("ledcount");
//		ledtimestamp[j]->Draw("ALP");	
		ledtimestamp[j]->Write();
		
	}
	
	RootFile->cd("MuonManyQDC");
	for (Int_t i=0; i<numPanels; i++){
//		vcan11->cd(i+1);
//		TVirtualPad *vpad11 = vcan11->cd(i+1); vpad11->SetLogy();
		hMuonManyQDC[i]->GetYaxis()->SetTitle("Multiplicity");
		hMuonManyQDC[i]->GetXaxis()->SetTitle("QDC Values");
//		hMuonManyQDC[i]->Draw();
		hMuonManyQDC[i]->Write();
	
	}
	RootFile->cd("MuonMult");
	for (Int_t i=0; i<numPanels; i++){
//		vcan9->cd(i+1);
//		TVirtualPad *vpad9 = vcan9->cd(i+1); vpad9->SetLogy();
		hMuonMult[i]->GetYaxis()->SetTitle("Multiplicity");
		hMuonMult[i]->GetXaxis()->SetTitle("# of panels hit");
//		hMuonMult[i]->Draw();
		hMuonMult[i]->Write();
	}

	RootFile->cd("AvgLEDQDC");
	for (Int_t i=0; i<numPanels; i++){
//		vcan12->cd(i+1);
//		TVirtualPad *vpad12 = vcan12->cd(i+1); vpad12->SetLogy();
		hLEDAvgQDCPanel[i]->GetYaxis()->SetTitle("Avg QDC value");
		hLEDAvgQDCPanel[i]->GetXaxis()->SetTitle("Run Number");
//		hLEDAvgQDCPanel[i]->Draw();
		hLEDAvgQDCPanel[i]->Write();
	}

	RootFile->cd("rmsLEDQDC");
	for (Int_t i=0; i<numPanels; i++){
//		vcan13->cd(i+1);
//		TVirtualPad *vpad13 = vcan13->cd(i+1); vpad13->SetLogy();
		hLEDAvgQDCPanel[i]->GetYaxis()->SetTitle("rms QDC value");
		hLEDAvgQDCPanel[i]->GetXaxis()->SetTitle("Run Number");
//		hLEDrmsQDCPanel[i]->Draw();
		hLEDrmsQDCPanel[i]->Write();
	}

	RootFile->cd();

	// ==========================

	RootFile->Close();

	cout << "badtimecount = " << badtimecount << endl;
	cout << "Wrote ROOT file." << endl;
	
	lowdt.close();

}
void ratioPlots_Zxx()
{

  // llbb_Mass_reco mfJetEta_450_600 mfJetEta_250_300 lljjMass_reco mjj_HighMass_reco drll_HighMass_reco

   TString Variable = "Zxx_Mass_reco";
//   TString Variable2 = "Zbb_Mass_reco";
   TString x_title = "M_{llxx}";
   Int_t N_Rebin = 10;

   Double_t yTopLimit = 3;

   TFile *f1 = TFile::Open("/home/fynu/amertens/storage/test/MG_PY6_/output/MG_PY6_/MG_PY6v9.root");
   TH1D *h1 = (TH1D*)f1->Get(Variable);
   h1->Sumw2();
//   h1->Add((TH1D*)f1->Get(Variable2));
   h1->SetDirectory(0);
   f1->Close();

   TFile *f2 = TFile::Open("/home/fynu/amertens/storage/test/aMCNLO_PY8_/output/aMCNLO_PY8_/aMCNLO_PY8v9.root");
   TH1D *h2 = (TH1D*)f2->Get(Variable);
   h2->Sumw2();
//   h2->Add((TH1D*)f2->Get(Variable2));
   h2->SetDirectory(0);
   f2->Close();

/*
   TFile *f3 = TFile::Open("/home/fynu/amertens/storage/test/MG_PY8_/output/MG_PY8_/MG_PY8.root");
   TH1D *h3 = (TH1D*)f3->Get(Variable);
   h3->SetDirectory(0);
   f3->Close();
*/
//   h1->Sumw2();
//   h2->Sumw2();
//   h3->Sumw2();

   cout << "MG_PY6      : " << h1->Integral() << endl;
   cout << "aMC@NLO_PY8 : " << h2->Integral() << endl;


   //h1->Scale(1.0/151456.0);
   //h2->Scale(1.0/1.45192e+09);
   //h2->Scale(1./12132.9);
   h1->Scale(1.0/h1->Integral());
   h2->Scale(1.0/h2->Integral());

   h1->Sumw2();
   h2->Sumw2();



//   h3->Scale(1.0/h3->Integral());

   h1->Rebin(N_Rebin);
   h2->Rebin(N_Rebin);
//   h3->Rebin(N_Rebin);

   TH1D *h1c = h1->Clone();
   h1c->Sumw2();
   TH1D *h2c = h2->Clone();
   h2c->Sumw2();

   TH1D *h1c2 = h1->Clone();
   h1c2->Sumw2();

   h2c->Add(h1c,-1);
   h2c->Divide(h1c);


   h1->SetTitle("");
   h2->SetTitle("");
//   h3->SetTitle("");


   h1->SetLineColor(kRed);
//   h3->SetLineColor(kGreen);

   TCanvas *c1 = new TCanvas("c1","example",600,700);
   TPad *pad1 = new TPad("pad1","pad1",0,0.5,1,1);
   pad1->SetBottomMargin(0);
   gStyle->SetOptStat(0);
   pad1->Draw();
   pad1->cd();
   h2->DrawCopy();
//   h3->DrawCopy("same");
   h1->GetYaxis()->SetLabelSize(0.1);
   h1->GetYaxis()->SetRangeUser(0, 0.2);// ,yTopLimit);
   h1->GetYaxis()->SetTitleSize(0.06);
   h1->GetYaxis()->SetTitleOffset(0.7);



   h1->Draw("same");

   TLegend *leg = new TLegend(0.6,0.7,0.89,0.89);
   leg->SetLineColor(0);
   leg->SetFillColor(0);
   //leg->AddEntry(h1,"t#bar{t} uncertainty","f");
   leg->AddEntry(h1,"MG5 + PY6","l");
   leg->AddEntry(h2,"aMC@NLO + PY8","l");
//   leg->AddEntry(h3,"MG5 + PY8","l");
   leg->Draw();

   
   c1->cd();

   TPad *pad2 = new TPad("pad2","pad2",0,0,1,0.5);
   pad2->SetTopMargin(0);
   pad2->SetBottomMargin(0.4);
   pad2->Draw();
   pad2->cd();
   pad2->SetGrid();
   h2->SetStats(0);
   h2->Divide(h1);
   //h2->SetMarkerStyle(21);
   h2->Draw("ep");
   h2->GetYaxis()->SetLabelSize(0.1);
   h2->GetYaxis()->SetRangeUser(-0.5, 2.5);// ,yTopLimit);
   h2->GetYaxis()->SetTitle("aMC@NLO+PY8 / MG5+PY6");
   h2->GetYaxis()->SetTitleSize(0.06);
   h2->GetYaxis()->SetTitleOffset(0.7);
   h2->GetXaxis()->SetLabelSize(0.1);
   h2->GetXaxis()->SetTitle(x_title);
   h2->GetXaxis()->SetTitleSize(0.16);
   h2->GetXaxis()->SetTitleOffset(0.9);
 //  Double_t matrix[4][4];
   h2->Fit("pol3","","",50.0,1200.0);
   TF1 *ratio = h2->GetFunction("pol3");
   TVirtualFitter *fitter = TVirtualFitter::GetFitter();
   TMatrixD matrix(4,4,fitter->GetCovarianceMatrix());
   Double_t errorPar00 = fitter->GetCovarianceMatrixElement(0,0);
   Double_t errorPar11 = fitter->GetCovarianceMatrixElement(1,1);
   Double_t errorPar22 = fitter->GetCovarianceMatrixElement(2,2);
   Double_t errorPar33 = fitter->GetCovarianceMatrixElement(3,3);
//   c1->cd();

   matrix.Print();

   //const TMatrixDSym m = matrix;
   const TMatrixDEigen eigen(matrix);
   const TMatrixD eigenVal = eigen.GetEigenValues();
   const TMatrixD V = eigen.GetEigenVectors(); 

   cout << "V" << endl;

   V.Print();

   cout << "eigenVal" << endl;

   eigenVal.Print();



   cout << "Recomputed diag" << endl;

   //const TMatrixD Vt(TMatrixD::kTransposed,V);
   //const TMatrixD Vinv = V.Invert();
   const TMatrixD Vt(TMatrixD::kTransposed,V);
   //cout << "V-1" << endl;
   //Vinv.Print();
   cout << "Vt" << endl;
   Vt.Print();

   const TMatrixD VAVt = Vt*matrix*V;
   VAVt.Print();


   const TVectorD FittedParam(4);
   FittedParam(0) = fitter->GetParameter(0);
   FittedParam(1) = fitter->GetParameter(1);
   FittedParam(2) = fitter->GetParameter(2);
   FittedParam(3) = fitter->GetParameter(3);
   FittedParam.Print();


   //const TVectorD FittedParamNB(4);
   const TVectorD PNb = V*FittedParam;
   cout << "Pnb" << endl;
   PNb.Print();
  

   cout << " Generating other parameters values " << endl;

   cout <<" V " << V(0,0) << endl;

   TRandom3 r;
   const TVectorD NewP(4);

   TH1D *hist100 = new TH1D("h100","h100",200,-5,5);
   TH1D *hist200 = new TH1D("h200","h200",200,-5,5);
   TH1D *hist400 = new TH1D("h400","h400",200,-5,5);
   TH1D *hist600 = new TH1D("h600","h600",100,-5,5);
   TH1D *hist800 = new TH1D("h800","h800",100,-5,5);
   TH1D *hist1000 = new TH1D("h1000","h1000",100,-5,5);

   TH1D *histp0 = new TH1D("p0","p0",100,-0.2,0.3);
   TH1D *histp1 = new TH1D("p1","p1",100,0.0,0.01);
   TH1D *histp2 = new TH1D("p2","p2",100,-0.00001,0);
   TH1D *histp3 = new TH1D("p3","p3",100,0,0.000000002);



   for (Int_t i = 0; i< 500; i++){
     NewP(0) = r.Gaus(PNb(0),sqrt(eigenVal(0,0)));
     NewP(1) = r.Gaus(PNb(1),sqrt(eigenVal(1,1)));
     NewP(2) = r.Gaus(PNb(2),sqrt(eigenVal(2,2)));
     NewP(3) = r.Gaus(PNb(3),sqrt(eigenVal(3,3)));
     //NewP.Print();

     //FittedParam.Print();

     const TVectorD NewP2 = Vt*NewP;
     //NewP2.Print();

     histp0->Fill(NewP2(0));
     histp1->Fill(NewP2(1));
     histp2->Fill(NewP2(2));
     histp3->Fill(NewP2(3));



     TF1 *newFit=new TF1("test","[0]+x*[1]+[2]*pow(x,2)+[3]*pow(x,3)",0,1400);
     newFit->SetParameters(NewP2(0),NewP2(1),NewP2(2),NewP2(3));
     newFit->SetLineColor(kBlue);

     Double_t area=0;
     for(Int_t it=1; it < 16; it++){
       //cout << "bin : " << it << " " << h1c2->GetBinContent(it) << endl;
       area += h1c2->GetBinContent(it)*newFit->Eval(100*it+50);
       }
   
     //newFit->Draw("same");
     //cout <<"val: " << newFit->Eval(200) << endl;
     hist100->Fill(newFit->Eval(100)/area);
     hist200->Fill(newFit->Eval(200)/area);
     hist400->Fill(newFit->Eval(400)/area);
     hist600->Fill(newFit->Eval(600)/area);
     hist800->Fill(newFit->Eval(800)/area);
     hist1000->Fill(newFit->Eval(1000)/area);
     }

   c1->cd();
   TCanvas *c2 = new TCanvas("c2","c2",1000,1000);
   c2->cd();
   c2->Divide(3,2);
   c2->cd(1);
   hist100->Draw();
   c2->cd(2);
   hist200->Draw();
   c2->cd(3);
   hist400->Draw();
   c2->cd(4);
   hist600->Draw();
   c2->cd(5);
   hist800->Draw();
   c2->cd(6);
   hist1000->Draw();



Double_t m_100,m_200,m_400,m_600,m_800,m_1000;
Double_t s_100,s_200,s_400,s_600,s_800,s_1000;

hist100->Fit("gaus","","",0.3,1.2);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_100 = fitter->GetParameter(1);
s_100 = fitter->GetParameter(2);

hist200->Fit("gaus","","",0.5,1.2);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_200 = fitter->GetParameter(1);
s_200 = fitter->GetParameter(2);

hist400->Fit("gaus","","",0.8,1.2);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_400 = fitter->GetParameter(1);
s_400 = fitter->GetParameter(2);

hist600->Fit("gaus","","",0.8,1.3);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_600 = fitter->GetParameter(1);
s_600 = fitter->GetParameter(2);

hist800->Fit("gaus","","",0.5,2);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_800 = fitter->GetParameter(1);
s_800 = fitter->GetParameter(2);

hist1000->Fit("gaus","","",0.5,2.5);
TVirtualFitter *fitter = TVirtualFitter::GetFitter();
m_1000 = fitter->GetParameter(1);
s_1000 = fitter->GetParameter(2);


Double_t x[6],y[6],ym[6],yup[6],ydown[6];
x[0]=100; x[1]=200; x[2]=400;x[3]=600; x[4]=800; x[5]=1000;
yup[0]=ratio->Eval(100)+s_100;
yup[1]=ratio->Eval(200)+s_200;
yup[2]=ratio->Eval(400)+s_400;
yup[3]=ratio->Eval(600)+s_600;
yup[4]=ratio->Eval(800)+s_800;
yup[5]=ratio->Eval(1000)+s_1000;
ydown[0]=ratio->Eval(100)-s_100;
ydown[1]=ratio->Eval(200)-s_200;
ydown[2]=ratio->Eval(400)-s_400;
ydown[3]=ratio->Eval(600)-s_600;
ydown[4]=ratio->Eval(800)-s_800;
ydown[5]=ratio->Eval(1000)-s_1000;

y[0]=1+s_100/ratio->Eval(100);
y[1]=1+s_200/ratio->Eval(200);
y[2]=1+s_400/ratio->Eval(400);
y[3]=1+s_600/ratio->Eval(600);
y[4]=1+s_800/ratio->Eval(800);
y[5]=1+s_1000/ratio->Eval(1000);

ym[0]=-s_100/m_100;
ym[1]=-s_200/m_200;
ym[2]=-s_400/m_400;
ym[3]=-s_600/m_600;
ym[4]=-s_800/m_800;
ym[5]=-s_1000/m_1000;


TGraph* g = new TGraph(6,x,y);
TGraph* gm = new TGraph(6,x,ym);
TGraph* gup = new TGraph(6,x,yup);
TGraph* gdown = new TGraph(6,x,ydown);


TCanvas *c3 = new TCanvas("c3","c3",1000,1000);
c3->cd();

//gup->Draw("AC*");
//gdown->Draw("C*");
g->Draw("AC*");

gPad->SetBottomMargin(0.2);
gPad->SetLeftMargin(0.2);
gStyle->SetOptStat(0);

g->GetXaxis()->SetTitle("M_{Zbb}");
g->GetXaxis()->SetRangeUser(50,1100);
g->GetYaxis()->SetLabelSize(0.06);
g->GetYaxis()->SetTitle("Uncertainty");
g->GetYaxis()->SetTitleSize(0.06);
g->GetYaxis()->SetTitleOffset(1.4);
g->GetXaxis()->SetLabelSize(0.06);
g->GetXaxis()->SetTitleSize(0.06);
g->GetXaxis()->SetTitleOffset(1);
g->GetYaxis()->SetNdivisions(5);

TFile f("syst_zxx.root","recreate");
g->Write();
f.Close();


//gm->Draw("C*");
//g->SetMaximum(1);
//g->SetMinimum(-1);
//h2c->Draw("same");


TH1D *h22=h2->Clone();

TCanvas *c5 =  new TCanvas("c5","c5",1000,1000);

gPad->SetBottomMargin(0.2);
gPad->SetLeftMargin(0.2);
gStyle->SetOptStat(0);

h22->Draw();
h22->GetXaxis()->SetRangeUser(50,1100);
h22->GetYaxis()->SetLabelSize(0.06);
h22->GetYaxis()->SetTitleSize(0.06);
h22->GetYaxis()->SetTitleOffset(1.4);
h22->GetXaxis()->SetLabelSize(0.06);
h22->GetXaxis()->SetTitleSize(0.06);
h22->GetXaxis()->SetTitleOffset(1);

ratio->SetLineColor(kRed);
ratio->Draw("same");

gup->Draw("C");
gdown->Draw("C");


TLegend *leg = new TLegend(0.6,0.7,0.89,0.89);
leg->SetLineColor(0);
leg->SetFillColor(0);
leg->AddEntry(h22,"aMC@NLO / MG5","lep");
leg->AddEntry(ratio,"best fit","l");
leg->AddEntry(gup,"Syst Error (#pm 1 #sigma)","l");
leg->Draw();



TCanvas *c4 = new TCanvas("c4","c4",1000,1000);
c4->Divide(2,2);
c4->cd(1);
histp0->Draw();
c4->cd(2);
histp1->Draw();
c4->cd(3);
histp2->Draw();
c4->cd(4);
histp3->Draw();


}
void rebinmacro() {
  for (int filecounter = 0; filecounter < 5; filecounter++) { //FILE LOOP
    if (filecounter == 0) {
      TFile *MyFile = new TFile("balanceout1234.root", "Read"); // 40 TO 60 PT AVERAGE
      if (MyFile->IsOpen()) printf("File Opened Successfully.\n");
      gFile = MyFile;
      MyFile->ls();
      TH1F *balance = (TH1F *)MyFile->Get("balance");
      TH1F *outereta = (TH1F *)MyFile->Get("outereta");
      TH1F *innereta = (TH1F *)MyFile->Get("innereta");
      TFile *rebinfile = new TFile("rebinout1234.root", "Recreate"); // 40 TO 60 PT AVERAGE
    }
    if (filecounter == 1) {
      TFile *MyFile = new TFile("balanceout123.root", "Read"); // 60 TO 80 PT AVERAGE
      if (MyFile->IsOpen()) printf("File Opened Successfully.\n");
      gFile = MyFile;
      MyFile->ls();
      TH1F *balance = (TH1F *)MyFile->Get("balance");
      TH1F *outereta = (TH1F *)MyFile->Get("outereta");
      TH1F *innereta = (TH1F *)MyFile->Get("innereta");
      TFile *rebinfile = new TFile("rebinout123.root", "Recreate"); // 60 TO 80 PT AVERAGE
    }
    if (filecounter == 2) {
      TFile *MyFile = new TFile("balanceout1.root", "Read"); // 80 TO 100 PT AVERAGE
      if (MyFile->IsOpen()) printf("File Opened Successfully.\n");
      gFile = MyFile;
      MyFile->ls();
      TH1F *balance = (TH1F *)MyFile->Get("balance");
      TH1F *outereta = (TH1F *)MyFile->Get("outereta");
      TH1F *innereta = (TH1F *)MyFile->Get("innereta");
      TFile *rebinfile = new TFile("rebinout1.root", "Recreate"); // 80 TO 100 PT AVERAGE
    }
    if (filecounter == 3) {
      TFile *MyFile = new TFile("balanceout.root", "Read"); // 100 TO 140 PT AVERAGE
      if (MyFile->IsOpen()) printf("File Opened Successfully.\n");
      gFile = MyFile;
      MyFile->ls();
      TH1F *balance = (TH1F *)MyFile->Get("balance");
      TH1F *outereta = (TH1F *)MyFile->Get("outereta");
      TH1F *innereta = (TH1F *)MyFile->Get("innereta");
      TFile *rebinfile = new TFile("rebinout.root", "Recreate"); // 100 TO 140 PT AVERAGE
    }
    if (filecounter == 4) {
      TFile *MyFile = new TFile("balanceout12.root", "Read"); // 140 TO 200 PT AVERAGE
      if (MyFile->IsOpen()) printf("File Opened Successfully.\n");
      gFile = MyFile;
      MyFile->ls();
      TH1F *balance = (TH1F *)MyFile->Get("balance");
      TH1F *outereta = (TH1F *)MyFile->Get("outereta");
      TH1F *innereta = (TH1F *)MyFile->Get("innereta");
      TFile *rebinfile = new TFile("rebinout12.root", "Recreate"); // 140 TO 200 PT AVERAGE
    }
 
  Float_t  cms_hcal_edge_pseudorapidity[83] = {-5.191, -4.889, -4.716, -4.538, -4.363, -4.191, -4.013, -3.839, -3.664, -3.489, -3.314, -3.139, -2.964, -2.853, -2.650, -2.500, -2.322, -2.172, -2.043, -1.930, -1.830, -1.740, -1.653, -1.566, -1.479, -1.392, -1.305, -1.218, -1.131, -1.044, -0.957, -0.879, -0.783, -0.696, -0.609, -0.522, -0.435, -0.348, -0.261, -0.174, -0.087, 0.000, 0.087,  0.174,  0.261,  0.348,  0.435,  0.522,  0.609, 0.696,  0.783,  0.879,  0.957,  1.044,  1.131,  1.218, 1.305,  1.392,  1.479,  1.566,  1.653,  1.740,  1.830, 1.930,  2.043,  2.172,  2.322,  2.500,  2.650,  2.853, 2.964,  3.139,  3.314,  3.489,  3.664,  3.839,  4.013, 4.191,  4.363,  4.538,  4.716,  4.889,  5.191};
  Float_t xcoordinate[82];
  Float_t intbalance[82];
  Float_t intinnereta[82];
  Float_t intoutereta[82];
 

  for (int count = 0; count < 82; count++) {
    Float_t lowerbound = cms_hcal_edge_pseudorapidity[count];
    Float_t upperbound = cms_hcal_edge_pseudorapidity[count + 1]; 
    Int_t lowerbin = balance->FindBin(lowerbound);
    Int_t upperbin = balance->FindBin(upperbound);
    Float_t integral = balance->Integral(lowerbin, upperbin);
    Float_t integral1 = innereta->Integral(lowerbin, upperbin);
    Float_t integral2 = outereta->Integral(lowerbin, upperbin);
    xcoordinate[count] = (lowerbound + upperbound)/2; 
    intbalance[count] = integral;
    //cout << "My x-coordinate is " << xcoordinate[count] << " and my integral is " << intbalance[count] << endl;
    intinnereta[count] = integral1;
    intoutereta[count] = integral2;
    //balancerebin->Fill(integral);
    //inneretarebin->Fill(integral1);
    //outeretarebin->Fill(integral2);
  }
TGraph *balancerebin = new TGraph(82, xcoordinate, intbalance);
TGraph *inneretarebin = new TGraph(82, xcoordinate, intinnereta);
TGraph *outeretarebin = new TGraph(82, xcoordinate, intoutereta);

balancerebin->SetTitle("Rebin Full Eta Range");
balancerebin->GetXaxis()->SetTitle("Dijet Balance");
balancerebin->GetYaxis()->SetTitle("Event Fraction");
balancerebin->SetMarkerStyle(8);
balancerebin->SetLineColor(0);
inneretarebin->SetTitle("Rebin Inner Eta Range");
inneretarebin->GetXaxis()->SetTitle("Dijet Balance");
inneretarebin->GetYaxis()->SetTitle("Event Fraction");
inneretarebin->SetMarkerStyle(8);
inneretarebin->SetLineColor(0);
outeretarebin->SetTitle("Rebin Outer Eta Range");
outeretarebin->GetXaxis()->SetTitle("Dijet Balance");
outeretarebin->GetYaxis()->SetTitle("Event Fraction");
outeretarebin->SetMarkerStyle(8);
outeretarebin->SetLineColor(0);

//balancerebin->Draw("ACP");
//inneretarebin->Draw("ACP");
//outeretarebin->Draw("ACP");
  
TCanvas *brebin = new TCanvas(1);
brebin->cd();
balancerebin->Draw("ACP");

TCanvas *binnerrebin = new TCanvas(2);
binnerrebin->cd();
inneretarebin->Draw("ACP");

TCanvas *bouterrebin = new TCanvas(3);
bouterrebin->cd();
outeretarebin->Draw("ACP");
  //Double_t scalerebin = 1/balancerebin->Integral();
  //Double_t scaleinnerrebin = 1/inneretarebin->Integral();
  //Double_t scaleouterrebin = 1/outeretarebin->Integral();

  //balancerebin->Scale(scalerebin);
  //inneretarebin->Scale(scaleinnerrebin);
  //outeretarebin->Scale(scaleouterrebin);
  
  rebinfile->cd();
  balancerebin->Write();
  inneretarebin->Write();
  outeretarebin->Write();
  rebinfile->Close();
  MyFile->Close();

}
} //END FILE LOOP
Example #6
0
void combinePlots(char* sample = "T2tt" , int x = 1, bool print = false){

  bool  shift       = true;
  bool  smooth      = false;
  char* filename    = "";
  char* outfilename = "";
  char* label       = "";
  float xaxismin    = 0;
  float yaxismax    = 250.0;

  if( TString(sample).Contains("T2tt") ){
    label       = "pp #rightarrow #tilde{t} #tilde{t}, #tilde{t} #rightarrow t #chi_{1}^{0}";
    outfilename = "combinePlots_T2tt.root";
    xaxismin    = 200.0;
    yaxismax    = 250.0;
    filename    = "T2tt_histos_trigweight.root";
  }

  else if( TString(sample).Contains("T2bw") ){

    label       = "pp #rightarrow #tilde{t} #tilde{t}, #tilde{t} #rightarrow b #chi_{1}^{#pm} #rightarrow b W #chi_{1}^{0}";

    if( x==25 ){
      xaxismin = 360.0;
      outfilename = "combinePlots_T2bw_x25.root";
      filename    = "T2bw_x25_histos.root";
    }
    if( x==50 ){
      xaxismin = 180.0;
      outfilename = "combinePlots_T2bw_x75.root";
      filename    = "T2bw_x50_histos.root";
    }
    if( x==75 ){
      xaxismin = 120.0;
      outfilename = "combinePlots_T2bw_x75.root";
      filename    = "T2bw_x75_histos.root";
      smooth      = true;
    }
  }

  else{
    cout << "ERROR! unrecognized sample " << sample << endl;
    exit(0);
  }

  cout << "--------------------------------------" << endl;
  cout << "Opening    " << filename << endl;
  cout << "Writing to " << outfilename << endl;
  cout << "Label      " << label << endl;
  cout << "--------------------------------------" << endl;

  TFile *file = TFile::Open(filename);

  const unsigned int ncuts = 7;

  TH2F* hxsec[ncuts];
  TH2F* hxsec_exp[ncuts];
  TH2F* hxsec_expp1[ncuts];
  TH2F* hxsec_expm1[ncuts];
  TH2F* hxsec_best;
  TH2F* hbest;
  TH2F* hxsec_best_exp;
  TH2F* hxsec_best_expp1;
  TH2F* hxsec_best_expm1;

  for( unsigned int i = 0 ; i < ncuts ; ++i ){
    hxsec[i]       = (TH2F*) file->Get(Form("hxsec_%i",i));
    hxsec_exp[i]   = (TH2F*) file->Get(Form("hxsec_exp_%i",i));
    hxsec_expp1[i] = (TH2F*) file->Get(Form("hxsec_expp1_%i",i));
    hxsec_expm1[i] = (TH2F*) file->Get(Form("hxsec_expm1_%i",i));

    if( i == 0 ){
      hxsec_best = (TH2F*) hxsec[i]->Clone("hxsec_best");
      hxsec_best->Reset();
      hbest = (TH2F*) hxsec[i]->Clone("hbest");
      hbest->Reset();
      hxsec_best_exp = (TH2F*) hxsec[i]->Clone("hxsec_best_exp");
      hxsec_best_exp->Reset();
      hxsec_best_expp1 = (TH2F*) hxsec[i]->Clone("hxsec_best_expp1");
      hxsec_best_expp1->Reset();
      hxsec_best_expm1 = (TH2F*) hxsec[i]->Clone("hxsec_best_expm1");
      hxsec_best_expm1->Reset();
    }


  }

  for( int xbin = 1 ; xbin <= hxsec_best->GetXaxis()->GetNbins() ; ++xbin ){
    for( int ybin = 1 ; ybin <= hxsec_best->GetYaxis()->GetNbins() ; ++ybin ){

      cout << "xbin ybin " << xbin << " " << ybin << endl;
     
      if( hxsec_exp[0]->GetBinContent(xbin,ybin) < 1e-10 ) continue;
      
      int   best_ul    = 0;
      float min_exp_ul = hxsec_exp[0]->GetBinContent(xbin,ybin);

      cout << "exp0 " << hxsec_exp[0]->GetBinContent(xbin,ybin) << endl;

      for( unsigned int i = 1 ; i < ncuts ; ++i ){

	if( hxsec_exp[i]->GetBinContent(xbin,ybin) < 1e-10 ) continue;

	cout << "exp" << i << " " << hxsec_exp[i]->GetBinContent(xbin,ybin) << endl;

	if( hxsec_exp[i]->GetBinContent(xbin,ybin) < min_exp_ul ){
	  min_exp_ul = hxsec_exp[i]->GetBinContent(xbin,ybin);
	  best_ul    = i;
	}

      }

      hxsec_best->SetBinContent(xbin,ybin,hxsec[best_ul]->GetBinContent(xbin,ybin));
      hxsec_best_exp->SetBinContent(xbin,ybin,hxsec_exp[best_ul]->GetBinContent(xbin,ybin));
      hxsec_best_expp1->SetBinContent(xbin,ybin,hxsec_expp1[best_ul]->GetBinContent(xbin,ybin));
      hxsec_best_expm1->SetBinContent(xbin,ybin,hxsec_expm1[best_ul]->GetBinContent(xbin,ybin));
      hbest->SetBinContent(xbin,ybin,best_ul+1);

      cout << "best ul " << best_ul << " " << min_exp_ul << endl;
      cout << "obs limit " << hxsec[best_ul]->GetBinContent(xbin,ybin) << endl << endl << endl;
      
 
    }
  }

  TCanvas *can1 = new TCanvas("can1","",800,600);
  can1->cd();

  TLatex *t = new TLatex();
  t->SetNDC();

  //-------------------------------
  // cross section limit
  //-------------------------------

  if( smooth ){
    smoothHist( hxsec_best );
    smoothHist( hbest );
  }

  blankHist( hxsec_best , 200 );
  TH2F* hxsec_best_shifted = shiftHist( hxsec_best );
  TH2F* hdummy = (TH2F*) hxsec_best->Clone("hdummy");
  hdummy->Reset();

  //hxsec_best->Reset();
  // if( shift ){
  //   hxsec_best = shiftHist( hxsec_best );
  //}

  // cout << endl << "observed" << endl;
  // plot1D( hxsec_best );
  // cout << endl << "observed (+1)" << endl;
  // plot1D( hxsec_best_obsp1 );
  // cout << endl << "observed (-1)" << endl;
  // plot1D( hxsec_best_obsm1 );
  // cout << endl << "expected" << endl;
  // plot1D( hxsec_best_exp );
  // cout << endl << "expected (+1)" << endl;
  // plot1D( hxsec_best_expp1 );
  // cout << endl << "expected (-1)" << endl;
  // plot1D( hxsec_best_expm1 );

  gPad->SetTopMargin(0.1);
  gPad->SetRightMargin(0.2);
  gPad->SetLogz();
  hdummy->GetXaxis()->SetLabelSize(0.035);
  hdummy->GetYaxis()->SetLabelSize(0.035);
  hdummy->GetZaxis()->SetLabelSize(0.035);
  hdummy->GetYaxis()->SetTitle("m_{#chi^{0}_{1}} [GeV]");
  hdummy->GetYaxis()->SetTitleOffset(0.9);
  hdummy->GetXaxis()->SetTitle("m_{ #tilde{t}} [GeV]");
  hdummy->GetZaxis()->SetTitle("95% CL UL on #sigma#timesBF [pb]");
  hdummy->GetZaxis()->SetTitleOffset(0.8);
  hdummy->GetXaxis()->SetRangeUser(xaxismin,590);
  hdummy->GetYaxis()->SetRangeUser(0,yaxismax);
  //hdummy->Draw("colz");
  hdummy->SetMinimum(0.01);
  hdummy->SetMaximum(10);
  hxsec_best_shifted->SetMinimum(0.01);
  hxsec_best_shifted->SetMaximum(10);
  hdummy->SetMaximum(10);
  hdummy->Draw();
  hxsec_best_shifted->Draw("samecolz");
  hdummy->Draw("axissame");
  
  // TGraph* gr        = getRefXsecGraph(hxsec_best       , "T2tt", 1.0);
  // TGraph* gr_exp    = getRefXsecGraph(hxsec_best_exp   , "T2tt", 1.0);
  // TGraph* gr_expp1  = getRefXsecGraph(hxsec_best_expp1 , "T2tt", 1.0);
  // TGraph* gr_expm1  = getRefXsecGraph(hxsec_best_expm1 , "T2tt", 1.0);
  // TGraph* gr_obsp1  = getRefXsecGraph(hxsec_best       , "T2tt", 1.15);
  // TGraph* gr_obsm1  = getRefXsecGraph(hxsec_best       , "T2tt", 0.85);


  TGraph* gr       = new TGraph();
  TGraph* gr_exp   = new TGraph();
  TGraph* gr_expp1 = new TGraph();
  TGraph* gr_expm1 = new TGraph();
  TGraph* gr_obsp1 = new TGraph();
  TGraph* gr_obsm1 = new TGraph();

  if( TString(sample).Contains("T2tt") ){
    gr       = T2tt_observed();
    gr_exp   = T2tt_expected();
    gr_expp1 = T2tt_expectedP1();
    gr_expm1 = T2tt_expectedM1();
    gr_obsp1 = T2tt_observedP1();
    gr_obsm1 = T2tt_observedM1();
  }
  else if( TString(sample).Contains("T2bw") && x==75 ){
    gr       = T2bw_x75_observed();
    gr_exp   = T2bw_x75_expected();
    gr_expp1 = T2bw_x75_expectedP1();
    gr_expm1 = T2bw_x75_expectedM1();
    gr_obsp1 = T2bw_x75_observedP1();
    gr_obsm1 = T2bw_x75_observedM1();
  }
  else if( TString(sample).Contains("T2bw") && x==50 ){
    gr       = T2bw_x50_observed();
    gr_exp   = T2bw_x50_expected();
    gr_expp1 = T2bw_x50_expectedP1();
    gr_expm1 = T2bw_x50_expectedM1();
    gr_obsp1 = T2bw_x50_observedP1();
    gr_obsm1 = T2bw_x50_observedM1();
  }

  gr->SetLineWidth(6);

  gr_exp->SetLineWidth(4);
  gr_exp->SetLineStyle(7);

  gr_expp1->SetLineWidth(3);
  gr_expp1->SetLineStyle(3);
  gr_expm1->SetLineWidth(3);
  gr_expm1->SetLineStyle(3);

  gr_exp->SetLineColor(4);
  gr_expp1->SetLineColor(4);
  gr_expm1->SetLineColor(4);

  gr_obsp1->SetLineStyle(2);
  gr_obsm1->SetLineStyle(2);
  gr_obsp1->SetLineWidth(3);
  gr_obsm1->SetLineWidth(3);

  gr_exp->Draw();
  gr_expp1->Draw();
  gr_expm1->Draw();
  gr_obsp1->Draw();
  gr_obsm1->Draw();
  gr->Draw();

  // cout << endl << "observed" << endl;
  // printGraph(gr);
  // cout << endl << "observed (+1)" << endl;
  // printGraph(gr_obsp1);
  // cout << endl << "observed (-1)" << endl;
  // printGraph(gr_obsm1);
  // cout << endl << "expected" << endl;
  // printGraph(gr_exp);
  // cout << endl << "expected (+1)" << endl;
  // printGraph(gr_expp1);
  // cout << endl << "expected (-1)" << endl;
  // printGraph(gr_expm1);

  // TLegend *leg = new TLegend(0.2,0.6,0.65,0.8);
  // leg->AddEntry(gr,       "observed","l");
  // leg->AddEntry(gr_exp,   "median expected (#pm1#sigma)","l");
  // //leg->AddEntry(gr_expp1, "expected (#pm1#sigma)","l");
  // leg->SetFillColor(0);
  // leg->SetBorderSize(0);
  // leg->Draw();

  /*
  t->SetTextSize(0.04);
  t->DrawLatex(0.20,0.72  ,"NLO-NLL exclusions");
  t->DrawLatex(0.27,0.67,"Observed #pm1#sigma^{theory}");
  t->DrawLatex(0.27,0.62,"Expected #pm1#sigma");

  t->DrawLatex(0.19,0.84,label);
  t->DrawLatex(0.19,0.79,"unpolarized top quarks");
  */
  t->SetTextSize(0.035);
  t->DrawLatex(0.18,0.79,"50 / 50 t_{L} / t_{R} mixture");
  t->DrawLatex(0.18,0.84,label);
  t->SetTextSize(0.04);
  t->DrawLatex(0.50,0.85  ,"NLO-NLL exclusions");
  t->DrawLatex(0.55,0.80,"Observed #pm1#sigma^{theory}");
  t->DrawLatex(0.55,0.75,"Expected #pm1#sigma");


  t->SetTextSize(0.045);
  if( TString(sample).Contains("T2bw") && x==25 ) t->DrawLatex(0.15,0.04,"m_{#chi_{1}^{#pm}} = 0.25 m_{ #tilde{t}} + 0.75 m_{#chi_{1}^{0}}");
  if( TString(sample).Contains("T2bw") && x==50 ) t->DrawLatex(0.15,0.04,"m_{#chi_{1}^{#pm}} = 0.5 m_{ #tilde{t}} + 0.5 m_{#chi_{1}^{0}}");
  if( TString(sample).Contains("T2bw") && x==75 ) t->DrawLatex(0.15,0.04,"m_{#chi_{1}^{#pm}} = 0.75 m_{ #tilde{t}} + 0.25 m_{#chi_{1}^{0}}");

  //float offset = 40.0;
  float xoffset = 405.0;
  float yoffset = 213.0;
  float length  =  30.0;
  float yspace1 =     5;
  float yspace2 =    17;

  if( TString(sample).Contains("T2bw") && x==75 ) xoffset -= 30.0;
  
  // median expected
  //TLine *line22 = new TLine(xaxismin+xoffset+25, 310-yoffset, xaxismin+xoffset+65, 310-yoffset);
  TLine *line22 = new TLine(xoffset,yoffset,xoffset+length,yoffset);
  line22->SetLineWidth(4);
  line22->SetLineColor(4);
  line22->SetLineStyle(7);
  line22->Draw();
 
  // expected +/-1sigma
  //TLine *line23 = new TLine(xaxismin+xoffset+25, 317-yoffset, xaxismin+xoffset+65, 317-yoffset);
  TLine *line23 = new TLine(xoffset,yoffset+yspace1,xoffset+length,yoffset+yspace1);
  line23->SetLineWidth(3);
  line23->SetLineColor(4);
  line23->SetLineStyle(3);
  line23->Draw();

  // expected +/-1sigma  
  //TLine *line24 = new TLine(xaxismin+xoffset+25, 303-yoffset, xaxismin+xoffset+65, 303-yoffset);
  TLine *line24 = new TLine(xoffset,yoffset-yspace1,xoffset+length,yoffset-yspace1);
  line24->SetLineWidth(3);
  line24->SetLineColor(4);
  line24->SetLineStyle(3);
  line24->Draw();

  // median observed
  //TLine *line25 = new TLine(xaxismin+xoffset+25, 335-yoffset, xaxismin+xoffset+65, 335-yoffset);
  TLine *line25 = new TLine(xoffset,yoffset+yspace2,xoffset+length,yoffset+yspace2);
  line25->SetLineWidth(6);
  line25->SetLineColor(1);
  line25->SetLineStyle(1);
  line25->Draw();
 
  //TLine *line26 = new TLine(xaxismin+xoffset+25, 342-yoffset, xaxismin+xoffset+65, 342-yoffset);
  TLine *line26 = new TLine(xoffset,yoffset+yspace1+yspace2,xoffset+length,yoffset+yspace1+yspace2);
  line26->SetLineWidth(2);
  line26->SetLineColor(1);
  line26->SetLineStyle(2);
  line26->Draw();
  
  //TLine *line27 = new TLine(xaxismin+xoffset+25, 328-yoffset, xaxismin+xoffset+65, 328-yoffset);
  TLine *line27 = new TLine(xoffset,yoffset-yspace1+yspace2,xoffset+length,yoffset-yspace1+yspace2);
  line27->SetLineWidth(2);
  line27->SetLineColor(1);
  line27->SetLineStyle(2);
  line27->Draw();



  t->SetTextSize(0.04);
  t->DrawLatex(0.18,0.94,"CMS Preliminary                 #sqrt{s} = 8 TeV, #scale[0.6]{#int}Ldt = 9.7 fb^{-1}");
  
  /*
  //-------------------------------
  // best signal region
  //-------------------------------

  TCanvas *can2 = new TCanvas("can2","",600,600);
  can2->cd();
  
  hbest->Draw("colz");
  hbest->Draw("sametext");
  gPad->SetTopMargin(0.1);
  gPad->SetRightMargin(0.2);
  hbest->SetMaximum(7);
  hbest->GetXaxis()->SetLabelSize(0.035);
  hbest->GetYaxis()->SetLabelSize(0.035);
  hbest->GetZaxis()->SetLabelSize(0.035);
  hbest->GetYaxis()->SetTitle("m_{#chi^{0}_{1}} [GeV]");
  hbest->GetXaxis()->SetTitle("m_{ #tilde{t}} [GeV]");
  hbest->GetXaxis()->SetRangeUser(xaxismin,590);
  hbest->GetYaxis()->SetRangeUser(0,400);
  hbest->GetZaxis()->SetTitle("best signal region");

  t->SetTextSize(0.035);
  t->DrawLatex(0.18,0.92,"CMS Preliminary   #sqrt{s} = 8 TeV, #scale[0.6]{#int}Ldt = 9.7 fb^{-1}");
  
  t->SetTextSize(0.04);
  t->DrawLatex(0.19,0.83,label);

  t->DrawLatex(0.2,0.75,"1 = SRA");
  t->DrawLatex(0.2,0.70,"2 = SRB");
  t->DrawLatex(0.2,0.65,"3 = SRC");
  t->DrawLatex(0.2,0.60,"4 = SRD");
  t->DrawLatex(0.2,0.55,"5 = SRE");
  t->DrawLatex(0.2,0.50,"6 = SRF");
  t->DrawLatex(0.2,0.45,"7 = SRG");

  if( TString(sample).Contains("T2bw") && x==25 ) t->DrawLatex(0.15,0.03,"m_{#chi_{1}^{#pm}} = 0.25 m_{ #tilde{t}} + 0.75 m_{#chi_{1}^{0}}");
  if( TString(sample).Contains("T2bw") && x==50 ) t->DrawLatex(0.15,0.03,"m_{#chi_{1}^{#pm}} = 0.5 m_{ #tilde{t}} + 0.5 m_{#chi_{1}^{0}}");
  if( TString(sample).Contains("T2bw") && x==75 ) t->DrawLatex(0.15,0.03,"m_{#chi_{1}^{#pm}} = 0.75 m_{ #tilde{t}} + 0.25 m_{#chi_{1}^{0}}");




  //-------------------------------
  // excluded regions
  //-------------------------------

  int   nbinsx  =   120;
  float xmin    =    -5;
  float xmax    =  1195;
  int   nbinsy  =   120;
  float ymin    =    -5;
  float ymax    =  1195;

  TFile* f = TFile::Open("stop_xsec.root");
  TH1F* refxsec = (TH1F*) f->Get("h_stop_xsec");

  TH2F* hexcl       = new TH2F("hexcl"         , "hexcl"        , nbinsx , xmin , xmax , nbinsy , ymin , ymax );
  TH2F* hexcl_obsp1 = new TH2F("hexcl_obsp1"   , "hexcl_obsp1"  , nbinsx , xmin , xmax , nbinsy , ymin , ymax );
  TH2F* hexcl_obsm1 = new TH2F("hexcl_obsm1"   , "hexcl_obsm1"  , nbinsx , xmin , xmax , nbinsy , ymin , ymax );
  TH2F* hexcl_exp   = new TH2F("hexcl_exp"     , "hexcl_exp"    , nbinsx , xmin , xmax , nbinsy , ymin , ymax );
  TH2F* hexcl_expp1 = new TH2F("hexcl_expp1"   , "hexcl_expp1"  , nbinsx , xmin , xmax , nbinsy , ymin , ymax );
  TH2F* hexcl_expm1 = new TH2F("hexcl_expm1"   , "hexcl_expm1"  , nbinsx , xmin , xmax , nbinsy , ymin , ymax );

  
  for( unsigned int ibin = 1 ; ibin <= nbinsx ; ibin++ ){
    for( unsigned int jbin = 1 ; jbin <= nbinsy ; jbin++ ){

      //float mg      = hxsec_best->GetXaxis()->GetBinCenter(ibin);
      float mg      = hexcl->GetXaxis()->GetBinCenter(ibin);
      int   bin     = refxsec->FindBin(mg);
      float xsec    = refxsec->GetBinContent(bin);

      float xsec_up = refxsec->GetBinContent(bin) + refxsec->GetBinError(bin);
      float xsec_dn = refxsec->GetBinContent(bin) - refxsec->GetBinError(bin);
      
      float xsecul       = hxsec_best->GetBinContent(ibin,jbin);
      float xsecul_exp   = hxsec_best_exp->GetBinContent(ibin,jbin);
      float xsecul_expp1 = hxsec_best_expp1->GetBinContent(ibin,jbin);
      float xsecul_expm1 = hxsec_best_expm1->GetBinContent(ibin,jbin);

      // cout << endl;
      // cout << "mg xsec " << mg << " " << xsec << endl;
      // cout << "xsec: obs exp expp1 expm1 " << xsecul << " " << xsecul_exp << " " << xsecul_expp1 << " " << xsecul_expm1 << endl;

      if( xsecul < 1.e-10 ) continue;

      hexcl->SetBinContent(ibin,jbin,0);
      if( xsec > xsecul )   hexcl->SetBinContent(ibin,jbin,1);

      hexcl_exp->SetBinContent(ibin,jbin,0);
      if( xsec > xsecul_exp )   hexcl_exp->SetBinContent(ibin,jbin,1);
      
      hexcl_expp1->SetBinContent(ibin,jbin,0);
      if( xsec > xsecul_expp1 )   hexcl_expp1->SetBinContent(ibin,jbin,1);
      
      hexcl_expm1->SetBinContent(ibin,jbin,0);
      if( xsec > xsecul_expm1 )   hexcl_expm1->SetBinContent(ibin,jbin,1);
      
      hexcl_obsp1->SetBinContent(ibin,jbin,0);
      if( xsec_up > xsecul )   hexcl_obsp1->SetBinContent(ibin,jbin,1);
      
      hexcl_obsm1->SetBinContent(ibin,jbin,0);
      if( xsec_dn > xsecul )   hexcl_obsm1->SetBinContent(ibin,jbin,1);
    }
  }

  TCanvas *can3 = new TCanvas("can3","can3",1200,800);
  can3->Divide(3,2);

  t->SetTextSize(0.07);

  gr->SetMarkerColor(6);
  gr_obsp1->SetMarkerColor(6);
  gr_obsm1->SetMarkerColor(6);
  gr_exp->SetMarkerColor(6);
  gr_expp1->SetMarkerColor(6);
  gr_expm1->SetMarkerColor(6);

  can3->cd(1);
  gPad->SetGridx();
  gPad->SetGridy();
  hexcl->GetXaxis()->SetTitle("stop mass [GeV]");
  hexcl->GetYaxis()->SetTitle("#chi_{1}^{0} mass [GeV]");
  hexcl->GetXaxis()->SetRangeUser(xaxismin,600);
  hexcl->GetYaxis()->SetRangeUser(0,200);
  hexcl->Draw("colz");
  gr->Draw("lp");
  t->DrawLatex(0.3,0.8,"observed");

  can3->cd(2);
  gPad->SetGridx();
  gPad->SetGridy();
  hexcl_obsp1->GetXaxis()->SetTitle("stop mass [GeV]");
  hexcl_obsp1->GetYaxis()->SetTitle("#chi_{1}^{0} mass [GeV]");
  hexcl_obsp1->GetXaxis()->SetRangeUser(xaxismin,600);
  hexcl_obsp1->GetYaxis()->SetRangeUser(0,200);
  hexcl_obsp1->Draw("colz");
  gr_obsp1->Draw("lp");
  t->DrawLatex(0.3,0.8,"observed (+1#sigma)");

  can3->cd(3);
  gPad->SetGridx();
  gPad->SetGridy();
  hexcl_obsm1->GetXaxis()->SetTitle("stop mass [GeV]");
  hexcl_obsm1->GetYaxis()->SetTitle("#chi_{1}^{0} mass [GeV]");
  hexcl_obsm1->GetXaxis()->SetRangeUser(xaxismin,600);
  hexcl_obsm1->GetYaxis()->SetRangeUser(0,200);
  hexcl_obsm1->Draw("colz");
  gr_obsm1->Draw("lp");
  t->DrawLatex(0.3,0.8,"observed (-1#sigma)");

  can3->cd(4);
  gPad->SetGridx();
  gPad->SetGridy();
  hexcl_exp->GetXaxis()->SetTitle("stop mass [GeV]");
  hexcl_exp->GetYaxis()->SetTitle("#chi_{1}^{0} mass [GeV]");
  hexcl_exp->GetXaxis()->SetRangeUser(xaxismin,600);
  hexcl_exp->GetYaxis()->SetRangeUser(0,200);
  hexcl_exp->Draw("colz");
  gr_exp->Draw("lp");
  t->DrawLatex(0.3,0.8,"expected");

  can3->cd(5);
  gPad->SetGridx();
  gPad->SetGridy();
  hexcl_expp1->GetXaxis()->SetTitle("stop mass [GeV]");
  hexcl_expp1->GetYaxis()->SetTitle("#chi_{1}^{0} mass [GeV]");
  hexcl_expp1->GetXaxis()->SetRangeUser(xaxismin,600);
  hexcl_expp1->GetYaxis()->SetRangeUser(0,200);
  hexcl_expp1->Draw("colz");
  gr_expp1->Draw("lp");
  t->DrawLatex(0.3,0.8,"expected (+1#sigma)");

  can3->cd(6);
  gPad->SetGridx();
  gPad->SetGridy();
  hexcl_expm1->GetXaxis()->SetTitle("stop mass [GeV]");
  hexcl_expm1->GetYaxis()->SetTitle("#chi_{1}^{0} mass [GeV]");
  hexcl_expm1->GetXaxis()->SetRangeUser(xaxismin,600);
  hexcl_expm1->GetYaxis()->SetRangeUser(0,200);
  hexcl_expm1->Draw("colz");
  gr_expm1->Draw("lp");
  t->DrawLatex(0.3,0.8,"expected (-1#sigma)");
*/

  if( print ){
    if     ( TString(sample).Contains("T2tt") ){
      can1->Print("../../plots/combinePlots_T2tt.pdf");
      //can2->Print("../../plots/combinePlots_T2tt_bestSignalRegion.pdf");
      //can3->Print("../../plots/combinePlots_T2tt_excludedPoints.pdf");
    }
    else if( TString(sample).Contains("T2bw") ){
      can1->Print(Form("../../plots/combinePlots_T2bw_x%i.pdf",x));
      //can2->Print(Form("../../plots/combinePlots_T2bw_x%i_bestSignalRegion.pdf",x));
      //can3->Print(Form("../../plots/combinePlots_T2bw_x%i_excludedPoints.pdf",x));
    }
  }

  TFile* fout = TFile::Open(Form("%s_x%icombinePlots.root",sample,x),"RECREATE");
  fout->cd();
  hxsec_best->Write();
  hxsec_best_exp->Write();
  gr->Write();
  fout->Close();

}
Example #7
0
//______________________________________________________________________________
void CheckTime(const Char_t* loc)
{
    // Check time.

    Char_t t[256];

    // number of runs
    Int_t nRuns = gFiles->GetSize();

    // create arrays
    const Int_t nCh = 352;
    Double_t** pedPos = new Double_t*[nCh];
    Double_t* runNumbersD = new Double_t[nRuns];
    for (Int_t i = 0; i < nCh; i++) pedPos[i] = new Double_t[nRuns];

    // open the output files
    TFile* fROOTout = new TFile("/tmp/tagger_time.root", "RECREATE");

    // create directories
    for (Int_t i = 0; i < nCh; i++)
    {
        sprintf(t, "%03d", i);
        fROOTout->mkdir(t);
    }
    
    TF1* func = new TF1("func", "gaus(0)+pol1(3)", -1000 , 1000);

    // loop over runs
    for (Int_t i = 0; i < nRuns; i++)
    {   
        // get the file
        TFile* f = (TFile*) gFiles->At(i);

        // extract run number
        Int_t runNumber;
        sprintf(t, "%s/ARHistograms_CB_%%d.root", loc);
        sscanf(f->GetName(), t, &runNumber);
        runNumbersD[i] = (Double_t)runNumber;

        printf("Processing run %d (%d/%d)\n", runNumber, i+1, nRuns);

        fROOTout->cd();
        
        TH2* h2 = (TH2*) f->Get("CaLib_Tagger_Time");

        // loop over channels
        for (Int_t j = 0; j < nCh; j++)
        {
            // load histogram
            sprintf(t, "%03d", j);
            fROOTout->cd(t);
            sprintf(t, "%d_%d", i, j);
            TH1* h = h2->ProjectionX(t, j+1, j+1);
            h->Rebin(2);
            
            sprintf(t, "Run_%d", runNumber);
            TCanvas* c = new TCanvas(t, t);
            TLine* tline = 0;
            
            // check entries
            if (h->GetEntries())
            {
                // fit gaussian to peak
                Double_t maxPos = h->GetXaxis()->GetBinCenter(h->GetMaximumBin());
                func->SetParameters(1, maxPos, 0.5, 1, 0.1);
                func->SetRange(maxPos - 2, maxPos + 2);
                func->SetParLimits(0, 0, 1000);
                for (Int_t k = 0; k < 10; k++)
                    if (!h->Fit(func, "RBQ")) break;

                // save position in file and memory
                maxPos = func->GetParameter(1);
                pedPos[j][i] = maxPos;

                h->GetXaxis()->SetRangeUser(maxPos - 10, maxPos + 10);
                h->Draw();
                
                tline = new TLine(maxPos, 0, maxPos, 10000);
                tline->SetLineColor(kRed);
                tline->SetLineWidth(2);
                tline->Draw();
            }
            else
            {
                h->Draw();
            }

            c->Write(c->GetName(), TObject::kOverwrite);
    
            delete h;
            delete c;
            if (tline) delete tline;
        }
        
        delete h2;
    }
    
    // create pedestal evolution graphs
    fROOTout->cd();
    
    // loop over channels
    for (Int_t j = 0; j < nCh; j++)
    {
        printf("Creating time graph for channel %d\n", j);
        
        TGraph* g = new TGraph(nRuns, runNumbersD, pedPos[j]);
        sprintf(t, "Overview_%03d", j);
        g->SetName(t);
        g->SetTitle(t);
        //g->GetYaxis()->SetRangeUser(1200, 1300);
        g->Write(g->GetName(), TObject::kOverwrite);
        
        delete g;
    }

    printf("Saving output file\n");
    
    delete fROOTout;

    // cleanup
    for (Int_t i = 0; i < nCh; i++) delete [] pedPos[i];
    delete [] pedPos;
    delete [] runNumbersD;
}
Example #8
0
void Analyze7p2_Lin(bool force_recompile=true)
{
    FNameManager fnm("fnameconfig.dat");
    TString results_dir = fnm.GetResultsDir(true);
    TString target_id  = TString::Format("%s_%.1f_%s",target.Data(), eg, pol.Data());
    TString combined_hist_run = (results_dir + "/");
    combined_hist_run += (fnm.GetHistFileBase(false) + target_id.Data() + ".root");

    TString int_file = (fnm.GetResultsDir() + "/IntOutput/" + target_id.Data());
    TString int_subbed_file = (fnm.GetResultsDir() + "/IntOutput/" + target_id.Data() + "_bgsubbed");
    TString int_sanormed_file = (fnm.GetResultsDir() + "/IntOutput/" + target_id.Data() + "_sanormed");
    TString int_subbed_sanormed_file = (fnm.GetResultsDir() + "/IntOutput/" + target_id.Data() + "_bgsubbed_sanormed");

    TString angle_file = "angle_data/angles";
    TString sa_corr_file = "angle_data/sa_corrections";
    TString correction_id = TString::Format("%s_%.1f_%s", target.Data(), eg, pol.Data());
    TString circ_corr_file = TString::Format("corrections%s.root",correction_id.Data());

    TString angdist_dir = (results_dir + "/ang_dists");
    TString angdist_text_file = (angdist_dir + "/angdists_" + target_id + ".dat");
    TString angdist_subbed_text_file = (angdist_dir + "/angdists_" + target_id + "_bgsubbed.dat");

    TString angdist_sanormed_text_file = (angdist_dir + "/angdists_" + target_id + "_sanormed" + ".dat");
    TString angdist_subbed_sanormed_text_file = (angdist_dir + "/angdists_" + target_id + "_sanormed_bgsubbed.dat");

    TString angdist_root_file = (angdist_dir + "/angdists_" + target_id + ".root");
    TString angdist_subbed_root_file = (angdist_dir + "/angdists_" + target_id + "_bgsubbed.root");
    TString angdist_sanormed_root_file = (angdist_dir + "/angdists_" + target_id + "_sanormed" + ".root");
    TString angdist_subbed_sanormed_root_file = (angdist_dir + "/angdists_" + target_id + "_sanormed_bgsubbed.root");


    TString overnight_hist_run = (results_dir + "/" + fnm.GetHistFileBase(false).data() + bgnd_id + "_0.0_--.root");


    if (force_recompile==true)
    {
        gROOT->ProcessLine(".L analysis_soft/Scripts/GenerateTGraphInputFiles.cpp++");
        gROOT->ProcessLine(".L analysis_soft/Scripts/CreatePlotOverlay.C++");
        gROOT->ProcessLine(".L analysis_soft/Scripts/CleanupCombinedCanvasesDirectory.cpp++");
        gROOT->ProcessLine(".L analysis_soft/Scripts/CreateOverlayCanvases.cpp++");
        gROOT->ProcessLine(".L analysis_soft/Scripts/GenerateRatioAndAsymmetry.cpp++");
        gROOT->ProcessLine(".L GenerateSubtractionUncertainties.cpp++");
        gROOT->ProcessLine(".L NormalizeByLiveTimeFractionForRuns.cpp++");
        gROOT->ProcessLine(".L NormalizeAllHists.C++");
        gROOT->ProcessLine(".L ShiftHistsFromFile.cpp++");
        gROOT->ProcessLine(".L SubtractBgnd.cpp++");
        gROOT->ProcessLine(".L UnnormalizeAllHists.C++");
        gROOT->ProcessLine(".L NormalizeAlphaCountsByReference.cpp++");
        gROOT->ProcessLine(".L CalibrateHIsts.cpp++");
        gROOT->ProcessLine(".L CreateSysCorrRatios.cpp++");
        gROOT->ProcessLine(".L CreateRatioFromAlphaInts.cpp++");

    }
    else
    {
        gROOT->ProcessLine(".L analysis_soft/Scripts/GenerateTGraphInputFiles.cpp+");
        gROOT->ProcessLine(".L analysis_soft/Scripts/CreatePlotOverlay.C+");
        gROOT->ProcessLine(".L analysis_soft/Scripts/CleanupCombinedCanvasesDirectory.cpp+");
        gROOT->ProcessLine(".L analysis_soft/Scripts/CreateOverlayCanvases.cpp+");
        gROOT->ProcessLine(".L analysis_soft/Scripts/GenerateRatioAndAsymmetry.cpp+");
        gROOT->ProcessLine(".L GenerateSubtractionUncertainties.cpp+");
        gROOT->ProcessLine(".L NormalizeByLiveTimeFractionForRuns.cpp+");
        gROOT->ProcessLine(".L NormalizeAllHists.C+");
        gROOT->ProcessLine(".L ShiftHistsFromFile.cpp+");
        gROOT->ProcessLine(".L SubtractBgnd.cpp+");
        gROOT->ProcessLine(".L UnnormalizeAllHists.C+");
        gROOT->ProcessLine(".L NormalizeAlphaCountsByReference.cpp+");
        gROOT->ProcessLine(".L CalibrateHIsts.cpp+");
        gROOT->ProcessLine(".L CreateSysCorrRatios.cpp+");
        gROOT->ProcessLine(".L CreateRatioFromAlphaInts.cpp+");
    }
    cout << "BEGIN ANALYSIS" << endl;
    cout << "begin processing runs" << endl;

    TString message = TString::Format("Form LTF corrected histograms");
    if (OkToContinue(message))
    {
        FormAlphaLTFCorrection(target.Data(), eg, pol.Data(), 678);
    }


    message = TString::Format("combine %s, Eg=%.1f, %s", target.Data(), eg, pol.Data());
    if (OkToContinue(message))
    {
        CombineAllRunsForTargetWithEnergyAndPol(target.Data(),eg,pol.Data(),true);
        f = new TFile(combined_hist_run,"UPDATE");
        CleanupCombinedCanvasesDirectory(f);
        f->Close();
        f = TFile::Open(combined_hist_run,"UPDATE");
        CreateOverlayCanvases(f);
        f->Close();
    }

    message = TString::Format("calibrate %s, Eg=%.1f, %s", target.Data(), eg, pol.Data());
    if (OkToContinue(message))
    {
        f = new TFile(combined_hist_run.Data(),"UPDATE");
        TDirectory* dir = f->GetDirectory("adc");
        if (dir==0)
        {
            std::cout << "\tfailed to find adc folder in " << f->GetName() << std::endl;
        }
        else
        {
            std::cout << "\tCalibrating adc with " << calib_file
                    << std::endl;
            CalibrateHists(dir, calib_file.Data());
        }
        f->Close();
        dir = 0;

        f = new TFile(combined_hist_run.Data(),"UPDATE");
        dir = f->GetDirectory("ltf_corr_adc");
        if (dir==0)
        {
            std::cout << "\tfailed to find ltf_corr_adc folder in " << f->GetName() << std::endl;
        }
        else
        {
            std::cout << "\tCalibrating ltf_corr_adc with " << calib_file
                    << std::endl;
            CalibrateHists(dir, calib_file.Data());
        }

        dir = 0;

        dir = f->GetDirectory("ltf_corr_adc_gt_thresh");
        if (dir==0)
        {
            std::cout << "\tfailed to find ltf_corr_adc_gt_thresh folder in " << f->GetName() << std::endl;
        }
        else
        {
            std::cout << "\tCalibrating ltf_corr_adc_gt_thresh with " << calib_file
                    << std::endl;
            CalibrateHists(dir, calib_file.Data());
        }

        f->Close();
    }
//    TFile *f, *fcorr;
//    message = TString::Format("normalize %s, Eg=%.1f, %s data by 10HzClock",
//                              target.Data(), eg, pol.Data());
//    if (OkToContinue(message))
//    {
//        f = new TFile(combined_hist_run.Data(),"UPDATE");
//
//        std::cout << "\tNormalizing hists in ltf_corr_adc directory" << std::endl;
//        TDirectory *dir = f->GetDirectory("ltf_corr_adc_cut_tofcut");
//        if (dir==0)  std::cout << "cannot find ltf_corr_adc histograms" << std::endl;
//        else         NormalizeAllHists(dir,1/16042.0);
//
//        std::cout << "\tNormalizing hists in ltf_corr_adc_gt_thresh directory" << std::endl;
//        dir = f->GetDirectory("ltf_corr_adc_gt_thresh_tofcut");
//        if (dir==0)  std::cout << "cannot find ltf_corr_adc_gt_thresh histograms" << std::endl;
//        else         NormalizeAllHists(dir,1/16042.0);
//
//        f->Close();
//    }

    cout << "\n\nBegin processing runs overnight background runs\n" << endl;
     cout << "Do you want to skip the overnight bgnd subtraction? (y/n) " << endl;
     Char_t myans;
     cin >> myans;
     if (myans=='n')
     {
         message = TString::Format("Form LTF corrected histograms");
         if (OkToContinue(message))
         {
             FormAlphaLTFCorrection(bgnd_id.Data(), 0, "--", 678);
         }

         message = TString::Format("combine runs and set errors on %s", bgnd_id.Data());
         if (OkToContinue(message))
         {
             CombineAllRunsForTargetWithEnergyAndPol(bgnd_id.Data(),0,"--");
         }

         message = TString::Format("normalize %s by Veto10HzClock", bgnd_id.Data());
         if (OkToContinue(message))
         {
             f = new TFile(overnight_hist_run.Data(),"UPDATE");

             std::cout << "\tNormalizing hists in ltf_corr_adc directory" << std::endl;
             TDirectory *dir = f->GetDirectory("ltf_corr_adc");
             if (dir==0) std::cout << "Cannot find ltf_corr_adc folder" << std::endl;
             else        NormalizeAllHists(dir,normalization);

             std::cout << "\tNormalizing hists in ltf_corr_adc_gt_thresh directory" << std::endl;
             dir = f->GetDirectory("ltf_corr_adc_gt_thresh");
             if (dir==0) std::cout << "Cannot find ltf_corr_adc_gt_thresh folder" << std::endl;
             else        NormalizeAllHists(dir,normalization);

             std::cout << "\tNormalizing hists in ltf_corr_adc_gt_thresh_tofcut directory" << std::endl;
             dir = f->GetDirectory("ltf_corr_adc_gt_thresh_tofcut");
             if (dir==0) std::cout << "Cannot find ltf_corr_adc_gt_thresh_tofcut folder" << std::endl;
             else        NormalizeAllHists(dir,normalization);
             f->Close();
         }

         message = TString::Format("calibrate %s", bgnd_id.Data());
         if (OkToContinue(message))
         {
             f = new TFile(overnight_hist_run,"UPDATE");
             TDirectory* dir = f->GetDirectory("adc");
             if (dir==0)
             {
                 std::cout << "\tfailed to find adc folder in " << f->GetName() << std::endl;
             }
             else
             {
                 std::cout << "\tCalibrating adc with " << bgnd_calib_file
                         << std::endl;
                 CalibrateHists(dir, bgnd_calib_file.Data());
             }

             f = new TFile(overnight_hist_run,"UPDATE");
             dir = f->GetDirectory("normed_ltf_corr_adc");
             if (dir==0)
             {
                 std::cout << "\tfailed to find normed_ltf_corr_adc folder in " << f->GetName() << std::endl;
             }
             else
             {
                 std::cout << "\tCalibrating normed_ltf_corr_adc with " << bgnd_calib_file
                         << std::endl;
                 CalibrateHists(dir, bgnd_calib_file.Data());
             }

             dir = f->GetDirectory("normed_ltf_corr_adc_gt_thresh");
             if (dir==0)
             {
                 std::cout << "\tfailed to find normed_ltf_corr_adc_gt_thresh folder in " << f->GetName() << std::endl;
             }
             else
             {
                 std::cout << "\tCalibrating normed_ltf_corr_adc_gt_thresh with " << bgnd_calib_file
                         << std::endl;
                 CalibrateHists(dir, bgnd_calib_file.Data());
             }

//             dir = f->GetDirectory("normed_ltf_corr_adc_gt_thresh_sanormed");
//             if (dir==0)
//             {
//                 std::cout << "\tfailed to find normed_ltf_corr_adc_gt_thresh_sanormed folder in " << f->GetName() << std::endl;
//             }
//             else
//             {
//                 std::cout << "\tCalibrating normed_ltf_corr_adc_gt_thresh_sanormed with " << bgnd_calib_file
//                         << std::endl;
//                 CalibrateHists(dir, bgnd_calib_file.Data());
//             }

             f->Close();
         }

         message = TString::Format("align %s, Eg=%.1f, %s hists to %s",
                                   target.Data(), eg, pol.Data(), bgnd_id.Data());
         if (OkToContinue(message))
         {
             f = new TFile(combined_hist_run.Data(),"UPDATE");

             std::cout << "\tShifting ltf_corr_adc hists" << std::endl;
             TDirectory *dir = f->GetDirectory("ltf_corr_adc");
             if (dir==0)  std::cout << "cannot find ltf_corr_adc directory" << std::endl;
             else         ShiftHistsFromFile(dir, shift_data.Data());

             std::cout << "\tShifting ltf_corr_adc_gt_thresh hists" << std::endl;
             dir = f->GetDirectory("ltf_corr_adc_gt_thresh");
             if (dir==0)  std::cout << "cannot find ltf_corr_adc_gt_thresh directory" << std::endl;
             else         ShiftHistsFromFile(dir, shift_data.Data());

             std::cout << "\tShifting ltf_corr_adc_gt_thresh_tofcut hists" << std::endl;
             dir = f->GetDirectory("ltf_corr_adc_gt_thresh_tofcut");
             if (dir==0)  std::cout << "cannot find ltf_corr_adc_gt_thresh_tofcut directory" << std::endl;
             else         ShiftHistsFromFile(dir, shift_data.Data());
             f->Close();
         }

         cout << "Subtraction..." << endl;
         message = TString::Format("subtract %s from %s, Eg=%.1f, %s data",
                                   bgnd_id.Data(), target.Data(), eg, pol.Data());
         if (OkToContinue(message))
         {
             f = new TFile(combined_hist_run.Data(),"UPDATE");

             std::cout << "\tSubtracting shifted_ltf_corr_adc hists" << std::endl;
             TDirectory *dir = f->GetDirectory("shifted_ltf_corr_adc");
             if (dir==0)
             {
                 std::cout << "cannot find shifted shifted_ltf_corr_adc histograms" << std::endl;
             }
             else
             {
                 fbg = new TFile(overnight_hist_run.Data(),"UPDATE");
                 TDirectory *dirbg = fbg->GetDirectory("normed_ltf_corr_adc");
                 if (dirbg==0)   std::cout << "cannot find normed histograms in " << fbg->GetName() << std::endl;
                 else     	      SubtractBgndRuns(dirbg,dir);
                 fbg->Close();
             }

             std::cout << "\tSubtracting shifted_ltf_corr_adc_gt_thresh hists" << std::endl;
             dir = f->GetDirectory("shifted_ltf_corr_adc_gt_thresh");
             if (dir==0)
             {
                 std::cout << "cannot find shifted_ltf_corr_adc_gt_thresh histograms" << std::endl;
             }
             else
             {
                 fbg = new TFile(overnight_hist_run.Data(),"UPDATE");
                 TDirectory *dirbg = fbg->GetDirectory("normed_ltf_corr_adc_gt_thresh");
                 if (dirbg==0) std::cout << "cannot find normed histograms in " << fbg->GetName() << std::endl;
                 else          SubtractBgndRuns(dirbg,dir);
                 fbg->Close();
             }

             std::cout << "\tSubtracting shifted_ltf_corr_adc_gt_thresh_tofcut hists" << std::endl;
             dir = f->GetDirectory("shifted_ltf_corr_adc_gt_thresh_tofcut");
             if (dir==0)
             {
                 std::cout << "cannot find shifted_ltf_corr_adc_gt_thresh_tofcut histograms" << std::endl;
             }
             else
             {
                 fbg = new TFile(overnight_hist_run.Data(),"UPDATE");
                 TDirectory *dirbg = fbg->GetDirectory("normed_ltf_corr_adc_gt_thresh_tofcut");
                 if (dirbg==0) std::cout << "cannot find normed histograms in " << fbg->GetName() << std::endl;
                 else          SubtractBgndRuns(dirbg,dir);
                 fbg->Close();
             }


             f->Close();
         }

//         message = TString::Format("unnormalize run bgsubbed %s", pol.Data());
//          if (OkToContinue(message))
//          {
//              f = new TFile(combined_hist_run.Data(),"UPDATE");
//
//              std::cout << "\tUnnormalizing adc hists" << std::endl;
//              TDirectory* dir = f->GetDirectory("bgsubbed_shifted_ltf_corr_adc");
//              if (dir==0)  std::cout << "Cannot find folder containing hists" << std::endl;
//              else         UnnormalizeAllHists(dir,16042.0);
//
//              std::cout << "\tUnnormalizing adc_gt_thresh hists" << std::endl;
//              dir = f->GetDirectory("bgsubbed_shifted_ltf_corr_adc_gt_thresh");
//              if (dir==0)  std::cout << "Cannot find folder containing hists" << std::endl;
//              else         UnnormalizeAllHists(dir,16042.0);
//
//              f->Close();
//          }
     }

     if (OkToContinue("compute systematic unc. from overnight bgnd histograms"))
     {
         TString uncorr_dir = "ltf_corr_adc_gt_thresh";
         TString corr_dir = "bgsubbed_shifted_ltf_corr_adc_gt_thresh";
         f = new TFile(combined_hist_run.Data(),"update");
         TDirectory* du = f->GetDirectory(uncorr_dir.Data());
         TDirectory* ds = f->GetDirectory(corr_dir.Data());

         if (du==0)      std::cout << "Cannot find " << uncorr_dir << std::endl;
         else if (ds==0) std::cout << "Cannot find " << corr_dir << std::endl;
         else
         {
             TGraph* gr = GenerateSubtractionUncertainties(du, ds);
             f->cd();
             gr->Write("", TObject::kOverwrite);
         }

         f->Close();
     }

//     if (OkToContinue("Form alpha normalized spectra"))
//     {
//         f = new TFile(combined_hist_run.Data(),"update");
//
//         TString uncorr_dir = "ltf_corr_adc_gt_thresh";
//         TString corr_dir = "bgsubbed_shifted_ltf_corr_adc_gt_thresh";
//         TDirectory* du = f->GetDirectory(uncorr_dir.Data());
//
//
//         if (du==0)      std::cout << "Cannot find " << uncorr_dir << std::endl;
//         else
//         {
//            CreateAlphaNormedHists(du, "g4_sa_corr_232Th.dat");
//         }
//
//         TDirectory* dc = f->GetDirectory(corr_dir);
//
//         if (dc==0)      std::cout << "Cannot find " << corr_dir << std::endl;
//         else
//         {
//            CreateAlphaNormedHists(dc, "g4_sa_corr_232Th.dat");
//         }
//
//         f->Close();
//     }

    if (OkToContinue("integrate all \"adc_gt_thresh_tofcut\" histograms"))
    {
        PAnalysis::IntegrateSiStrips(combined_hist_run,
                                     TString("ltf_corr_adc_gt_thresh"),
                                     TString(""));

        PAnalysis::IntegrateSiStrips(combined_hist_run,
                                     "normed_bgsubbed_ltf_corr_adc_gt_thresh",
                                     "",
                                     int_subbed_file,
                                     "bgsubbed_shifted_ltf_corr_adc_gt_thresh");

//        PAnalysis::IntegrateSiStrips(combined_hist_run,
//                                     "ltf_corr_adc_gt_thresh",
//                                     "_sanormed",
//                                     int_sanormed_file,
//                                     "ltf_corr_adc_gt_thresh_sanormed");
//
//        PAnalysis::IntegrateSiStrips(combined_hist_run,
//                                     "ltf_corr_normed_bgsubbed_ltf_corr_adc_gt_thresh",
//                                     "_sanormed",
//                                     int_subbed_sanormed_file,
//                                     "bgsubbed_shifted_ltf_corr_adc_gt_thresh_sanormed");
//
    }

    if (OkToContinue("generate angular distribution"))
    {
        GenerateTGraphInputFiles(int_file.Data(),
                                 angle_file.Data(),
                                 angdist_text_file.Data());

        GenerateTGraphInputFiles(int_subbed_file.Data(),
                                 angle_file.Data(),
                                 angdist_subbed_text_file.Data());

//        GenerateTGraphInputFiles(int_sanormed_file.Data(),
//                                 angle_file.Data(),
//                                 angdist_sanormed_text_file.Data());
//
//        GenerateTGraphInputFiles(int_subbed_sanormed_file.Data(),
//                                 angle_file.Data(),
//                                 angdist_subbed_sanormed_text_file.Data());
//
    }

    if (OkToContinue("generate ratio and asymmetry plots"))
    {
        f = new TFile(angdist_root_file.Data(),"UPDATE");
        GenerateRatioAndAsymmetry(f);
        f->Close();

        f = new TFile(angdist_subbed_root_file.Data(),"UPDATE");
        GenerateRatioAndAsymmetry(f);
        f->Close();

//        f = new TFile(angdist_sanormed_root_file.Data(),"UPDATE");
//        GenerateRatioAndAsymmetry(f);
//        f->Close();
//
//        f = new TFile(angdist_subbed_sanormed_root_file.Data(),"UPDATE");
//        GenerateRatioAndAsymmetry(f);
//        f->Close();
//
    }

    if (OkToContinue("create overlaid angular distributions"))
    {
        gROOT->SetBatch(true);
        f = new TFile(angdist_root_file.Data(),"UPDATE");
        CreatePlotOverlay(f, Form("%s E_{#gamma}=%.1f MeV %s Yields", target.Data(), eg, pol.Data()));
        f->Close();

        f = new TFile(angdist_subbed_root_file.Data(),"UPDATE");
        CreatePlotOverlay(f, Form("%s E_{#gamma}=%.1f MeV %s Yields (subbed)", target.Data(), eg, pol.Data()));
        f->Close();

//        f = new TFile(angdist_sanormed_root_file.Data(),"UPDATE");
//        CreatePlotOverlay(f, Form("%s E_{#gamma}=%.1f MeV %s Yields SA Normed", target.Data(), eg, pol.Data()));
//        f->Close();
//
//        f = new TFile(angdist_subbed_sanormed_root_file.Data(),"UPDATE");
//        CreatePlotOverlay(f, Form("%s E_{#gamma}=%.1f MeV %s Yields SA Normed (subbed)", target.Data(), eg, pol.Data()));
//        f->Close();
//
        gROOT->SetBatch(false);
    }

//    if (OkToContinue("generate 2D angular dist"))
//    {
//        GenerateTGraph2D(angdist_corr_text_file.Data(), angdist_root_file.Data());
//        f = new TFile(angdist_root_file.Data(),"UPDATE");
////        GenerateTH2D(f);
//        f->Close();
//
//        GenerateTGraph2D(angdist_corr_text_file.Data(), angdist_root_file.Data());
//        f = new TFile(angdist_root_file.Data(),"UPDATE");
////        GenerateTH2D(f);
//        f->Close();
//
//
//    }

    if (OkToContinue("form alpha_ratio graph"))
    {
        f = new TFile(combined_hist_run.Data(),"UPDATE");

        StripDb sdb(angle_file.Data());
        TH1* halpha_ints;
        f->GetObject("alpha_ints",halpha_ints);
        TGraphErrors* gr_alpha_ratio = CreateRatioFromStripHist(halpha_ints,sdb);
		gr_alpha_ratio->Sort();
        gr_alpha_ratio->Write("alpha_ratio", TObject::kOverwrite);
        f->Close();
    }



    if (OkToContinue("incorporate systematic uncertainty into the ratio"))
    {
        f = new TFile(combined_hist_run.Data(),"UPDATE");
//        if (gr_==0)
//        {
//            std::cout << "Failed to find the ratio graph" << std::endl;
//        }
//        else
//        {
            TFile* fsim = new TFile("alpha_source_r3_r5_x1_y0_z0_80M_analyzed.root");
            // the next will look for the alpha_ratio graphs in specified directories
            CreateSysCorrRatios(f, fsim, angdist_subbed_root_file.Data());
            fsim->Close();
  //      }
        f->Close();

        f = new TFile(angdist_subbed_root_file.Data(),"UPDATE");
        TDirectory* d = f->GetDirectory("uncorrected");
        TGraphErrors* gr_ = 0;
        d->GetObject("ratio",gr_);
        if (gr_==0)
        {
            std::cout << "Failed to find the ratio graph" << std::endl;
        }
        else
        {
            TGraphErrors* grsys = 0;
            f->GetObject("systematic_alpha_diffs",grsys);
            if (grsys!=0)
            {
                CreateCorrectedRatios(gr_, grsys, f);
            }
            else
            {
                std::cout << "Couldn't find systematic_alpha_diffs graph" << std::endl;
            }
            fsim->Close();
        }

        f->Close();

    }

    cout << "ANALYSIS COMPLETE" << endl;
}
Example #9
0
int main(int argc, char** argv){
 
 ///=======================================================================================
 ///==== Calculate Scale from Data (minimization Chi2 and more)
 ///==== then perform toy MC to see the error on THAT scale with THAT statistics available
 ///======================================================================================= 

 if(argc != 2)
 {
  std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
  return 1;
 }
 
 // Parse the config file                                                                                                                                                          
 
 std::string fileName (argv[1]) ;
 boost::shared_ptr<edm::ProcessDesc> processDesc = edm::readConfigFile(fileName) ;
 boost::shared_ptr<edm::ParameterSet> parameterSet = processDesc->getProcessPSet () ;

 edm::ParameterSet subPSetInput = parameterSet->getParameter<edm::ParameterSet> ("inputTree") ;
 std::string treeNameDATA  = subPSetInput.getParameter<std::string> ("treeNameDATA") ;
 std::string inputFileDATA = subPSetInput.getParameter<std::string> ("inputFileDATA") ;
 treeNameMC = subPSetInput.getParameter<std::string> ("treeNameMC") ;
 std::string inputFileMC = subPSetInput.getParameter<std::string> ("inputFileMC") ;
  
 std::cout << ">>>>> InputDATA::treeName  " << treeNameDATA  << std::endl;  
 std::cout << ">>>>> InputDATA::inputFile  " << inputFileDATA  << std::endl;  
 std::cout << ">>>>> InputMC::treeName  " << treeNameMC  << std::endl;  
 std::cout << ">>>>> InputMC::inputFile  " << inputFileMC  << std::endl;  


 edm::ParameterSet subPSetOutput = parameterSet->getParameter<edm::ParameterSet> ("outputTree") ;
 std::string outputFile = subPSetOutput.getParameter<std::string> ("outputFile") ;

 std::cout << ">>>>> Output::outputFile  " << outputFile  << std::endl;  


 edm::ParameterSet subPSetOptions = parameterSet->getParameter<edm::ParameterSet> ("options") ;
 MinScan  = subPSetOptions.getParameter<double> ("MinScan") ;
 MaxScan  = subPSetOptions.getParameter<double> ("MaxScan") ;
 iNoSteps = subPSetOptions.getParameter<int>    ("iNoSteps") ;
  
 std::cout << ">>>>> Options::MinScan  " << MinScan  << std::endl;  
 std::cout << ">>>>> Options::MaxScan  " << MaxScan  << std::endl;  
 std::cout << ">>>>> Options::iNoSteps " << iNoSteps << std::endl;  

 MinScanRange  = subPSetOptions.getParameter<double> ("MinScanRange") ;
 MaxScanRange  = subPSetOptions.getParameter<double> ("MaxScanRange") ;
 
 std::cout << ">>>>> Options::MinScanRange  " << MinScanRange  << std::endl;  
 std::cout << ">>>>> Options::MaxScanRange  " << MaxScanRange  << std::endl;  

 minBINS = subPSetOptions.getParameter<double> ("minBINS") ;
 maxBINS = subPSetOptions.getParameter<double> ("maxBINS") ;
 numBINS = subPSetOptions.getParameter<int>    ("numBINS") ;

 std::cout << ">>>>> Options::numBINS   " << numBINS  << std::endl;  
 std::cout << ">>>>> Options::minBINS   " << minBINS  << std::endl;
 std::cout << ">>>>> Options::maxBINS   " << maxBINS  << std::endl;


 NBINTemplate = 10 * numBINS;
 MinTemplate = minBINS;
 MaxTemplate = maxBINS;
 Delta = (MaxTemplate - MinTemplate) / NBINTemplate;



 variableName = subPSetOptions.getParameter<std::string> ("variableName") ;
 std::cout << ">>>>> Options::variableName " << variableName.c_str() << std::endl;
 
 double minET = subPSetOptions.getParameter<double> ("minET") ;
 std::cout << ">>>>> Options::minET " << minET << std::endl;
 
 
 std::string temp_cut = subPSetOptions.getParameter<std::string> ("cut") ;
 std::cout << ">>>>> Options::cut " << temp_cut.c_str() << std::endl;
 AdditionalCut = Form("%s",temp_cut.c_str());
 std::cout << ">>>>> Options::AdditionalCut " << AdditionalCut.Data() << std::endl;
 
 
 EEEB = subPSetOptions.getParameter<int> ("EEorEB");
 std::cout << ">>>>> Options::EEEB " << EEEB << std::endl;
///==== 0 = EE+EB
///==== 1 = EE
///==== 2 = EB
///==== 3 = EE+
///==== 4 = EE-

 if (EEEB == 1) { ///==== EE
  AdditionalCut = Form("%s && (eta > 1.5 || eta < -1.5)",AdditionalCut.Data());
 }

 if (EEEB == 2) { ///==== EB
  AdditionalCut = Form("%s && (eta < 1.5 && eta > -1.5)",AdditionalCut.Data());
 }
 if (EEEB == 3) { ///==== EE+
  AdditionalCut = Form("%s && (eta > 1.5)",AdditionalCut.Data());
 }
 if (EEEB == 4) { ///==== EE-
  AdditionalCut = Form("%s && (eta < -1.5)",AdditionalCut.Data());
 }
 if (EEEB == 5) { ///==== EB mod 1
  AdditionalCut = Form("%s && (abs(eta) < 0.435)",AdditionalCut.Data());
 }
 if (EEEB == 6) { ///==== EB mod 2
  AdditionalCut = Form("%s && (abs(eta) < 0.783 && abs(eta) > 0.435)",AdditionalCut.Data());
 }
 if (EEEB == 7) { ///==== EB mod 3
  AdditionalCut = Form("%s && (abs(eta) < 1.131 && abs(eta) > 0.783)",AdditionalCut.Data());
 }
 if (EEEB == 8) { ///==== EB mod 4
  AdditionalCut = Form("%s && (abs(eta) < 1.479 && abs(eta) > 1.131)",AdditionalCut.Data());
 }
 if (EEEB == 9) { ///==== EE No ES
  AdditionalCut = Form("%s && (abs(eta) > 2.5)",AdditionalCut.Data());
 }
 if (EEEB == 10) { ///==== EE + ES
 AdditionalCut = Form("%s && (abs(eta) < 2.5 && abs(eta) > 1.5)",AdditionalCut.Data());
 }
 if (EEEB == 11) { ///==== EE- + ES
  AdditionalCut = Form("%s && (eta > -2.5 && eta < -1.5)",AdditionalCut.Data());
 }
 if (EEEB == 12) { ///==== EE+ + ES
  AdditionalCut = Form("%s && (eta < 2.5 && eta > 1.5)",AdditionalCut.Data());
 }
 
 std::cout << ">>>>>        :: " << AdditionalCut.Data() << std::endl;

 maxIter = subPSetOptions.getParameter<int> ("numToyMC") ;
 std::cout << ">>>>> Options::numToyMC  " << maxIter  << std::endl;  

 ///==== DATA ====
 fileInDATA = new TFile(inputFileDATA.c_str(),"READ");
 
 ///==== W ====
 fileInMC = new TFile(inputFileMC.c_str(),"READ");

 ///==== output ====
 outFile = new TFile(outputFile.c_str(),"RECREATE");
 outFile->cd();
 

 double ScaleTrue_Chi2;
 double ScaleTrue_Chi2_Fit;
 double ScaleTrue_LL;
 double ScaleTrue_LL_Fit;
 double ScaleTrue_NewChi2;
 double ScaleTrue_NewChi2_Fit;


 ///==== Prepare output trees ====

 myTreeChi2 = new TTree("myTreeChi2","myTreeChi2");
 myTreeChi2->Branch("Data_or_MC",&Data_or_MC,"Data_or_MC/I");
 myTreeChi2->Branch("Alpha",&Alpha,"Alpha/D");
 myTreeChi2->Branch("Chi2",&Chi2,"Chi2/D");
 myTreeChi2->Branch("NewChi2",&NewChi2,"NewChi2/D");
 myTreeChi2->Branch("LL",&LL,"LL/D");
 myTreeChi2->Branch("ScaleTrue",&ScaleTrue,"ScaleTrue/D");

 myTreeChi2_Result = new TTree("myTreeChi2_Result","myTreeChi2_Result");

 myTreeChi2_Result->Branch("Data_or_MC",&Data_or_MC,"Data_or_MC/I");
 myTreeChi2_Result->Branch("AlphaMean",&AlphaMean,"AlphaMean/D");
 myTreeChi2_Result->Branch("AlphaMinus",&AlphaMinus,"AlphaMinus/D");
 myTreeChi2_Result->Branch("AlphaPlus",&AlphaPlus,"AlphaPlus/D");
 myTreeChi2_Result->Branch("AlphaMean_Fit",&AlphaMean_Fit,"AlphaMean_Fit/D");
 myTreeChi2_Result->Branch("AlphaMinus_Fit",&AlphaMinus_Fit,"AlphaMinus_Fit/D");
 myTreeChi2_Result->Branch("AlphaPlus_Fit",&AlphaPlus_Fit,"AlphaPlus_Fit/D");
 myTreeChi2_Result->Branch("ScaleTrue",&ScaleTrue,"ScaleTrue/D");

 myTreeLL_Result = new TTree("myTreeLL_Result","myTreeLL_Result");
 myTreeLL_Result->Branch("Data_or_MC",&Data_or_MC,"Data_or_MC/I");
 myTreeLL_Result->Branch("AlphaMean",&AlphaMean,"AlphaMean/D");
 myTreeLL_Result->Branch("AlphaMinus",&AlphaMinus,"AlphaMinus/D");
 myTreeLL_Result->Branch("AlphaPlus",&AlphaPlus,"AlphaPlus/D");
 myTreeLL_Result->Branch("AlphaMean_Fit",&AlphaMean_Fit,"AlphaMean_Fit/D");
 myTreeLL_Result->Branch("AlphaMinus_Fit",&AlphaMinus_Fit,"AlphaMinus_Fit/D");
 myTreeLL_Result->Branch("AlphaPlus_Fit",&AlphaPlus_Fit,"AlphaPlus_Fit/D");
 myTreeLL_Result->Branch("ScaleTrue",&ScaleTrue,"ScaleTrue/D");

 myTreeNewChi2_Result = new TTree("myTreeNewChi2_Result","myTreeNewChi2_Result");
 myTreeNewChi2_Result->Branch("Data_or_MC",&Data_or_MC,"Data_or_MC/I");
 myTreeNewChi2_Result->Branch("AlphaMean",&AlphaMean,"AlphaMean/D");
 myTreeNewChi2_Result->Branch("AlphaMinus",&AlphaMinus,"AlphaMinus/D");
 myTreeNewChi2_Result->Branch("AlphaPlus",&AlphaPlus,"AlphaPlus/D");
 myTreeNewChi2_Result->Branch("AlphaMean_Fit",&AlphaMean_Fit,"AlphaMean_Fit/D");
 myTreeNewChi2_Result->Branch("AlphaMinus_Fit",&AlphaMinus_Fit,"AlphaMinus_Fit/D");
 myTreeNewChi2_Result->Branch("AlphaPlus_Fit",&AlphaPlus_Fit,"AlphaPlus_Fit/D");
 myTreeNewChi2_Result->Branch("ScaleTrue",&ScaleTrue,"ScaleTrue/D");


 ///==== Prepare input trees ====
 TTree* MyTreeDATA = (TTree*) fileInDATA->Get(treeNameDATA.c_str());

 MyTreeDATA->SetBranchAddress("pT",&pT);
 MyTreeDATA->SetBranchAddress("ET",&ET);
 MyTreeDATA->SetBranchAddress("MT",&MT);
 MyTreeDATA->SetBranchAddress("EoP",&EoP);
 MyTreeDATA->SetBranchAddress("eta",&eta);

 MyTreeDATA->SetBranchAddress("E5x5",&E5x5);
 MyTreeDATA->SetBranchAddress("p",&p);
 MyTreeDATA->SetBranchAddress("eleES",&eleES);
 MyTreeDATA->SetBranchAddress("eleFBrem",&eleFBrem);
 
 TTree* MyTreeMC = (TTree*) fileInMC->Get(treeNameMC.c_str());
 MyTreeMC->SetBranchAddress("pT",&pT);
 MyTreeMC->SetBranchAddress("ET",&ET);
 MyTreeMC->SetBranchAddress("MT",&MT);
 MyTreeMC->SetBranchAddress("EoP",&EoP);
 MyTreeMC->SetBranchAddress("eta",&eta);
 
 MyTreeMC->SetBranchAddress("E5x5",&E5x5);
 MyTreeMC->SetBranchAddress("p",&p);
 MyTreeMC->SetBranchAddress("eleES",&eleES);
 MyTreeMC->SetBranchAddress("eleFBrem",&eleFBrem);
 
 numEntriesMC = MyTreeMC->GetEntries();
 
 ///==== prepare minuit ====

 fitMin->SetRange(MinScanRange,MaxScanRange); 
 
 double step[1] = {0.001};
 double variable[1] = {0.0};
 minuit->SetLimitedVariable(0,"Scale" , variable[0]  , step[0] , MinScan  , MaxScan );
 

///===========================
///==== DATA Scale search ====
 ScaleTrue = -1000; ///==== default
 Data_or_MC = 1; ///=== 1 = Data;  0 = MC;
 numEvents = MyTreeDATA->GetEntries(); //==== number of events in Data sample
 outFile->cd();
 vET_data.clear();
 nIter = 1000000000; ///==== less than 1000000000 iterations at the end !!!
 TString nameDATA = Form("hDATA_%d_%d_%.5f",Data_or_MC,nIter,ScaleTrue);
 TH1F hDATA(nameDATA,nameDATA,numBINS,minBINS,maxBINS);
 
 MyTreeDATA->Draw(">> myList",(AdditionalCut + Form(" && ET > %f",minET)).Data(),"entrylist");
 TEntryList *mylist = (TEntryList*)gDirectory->Get("myList");
 MyTreeDATA->SetEntryList(mylist);
 
 MyTreeDATA->Draw(Form("%s >> %s",variableName.c_str(),nameDATA.Data()));
 ConvertStdVectDouble(vET_data,MyTreeDATA->GetV1(),mylist->GetN());
 
 hDATA.Write();
  
 std::cerr << "... I'm minimizing ... DATA analysis" << std::endl;
 std::cerr << ">>>>>>> numEvents = " << numEvents << " => " << vET_data.size() << " selected (=" << mylist->GetN() << ")" << std::endl;
 numSelectedData = vET_data.size();
 
 
 ///===== Chi2 ====
 std::cerr << " === Chi2 === " << std::endl;
 minuit->SetFunction(functorChi2);

 TGraph * grChi2 = new TGraph(iNoSteps);
 minuit->Scan(iPar_NoBG,iNoSteps,grChi2->GetX(),grChi2->GetY(),MinScan,MaxScan);

// TGraph * grChi2 = new TGraph();
// for (int iStep = 0; iStep < iNoSteps; iStep++){
//  double x = MinScan + (MaxScan - MinScan) / iNoSteps * (iStep+0.5);
//  double y = Chi2F(&x);
//  grChi2->SetPoint(iStep+1,x,y);
// }
 grChi2->Draw("AL");
 outFile->cd();
 minuit->PrintResults();
 outFile->cd();
 grChi2->SetTitle("grChi2");
 grChi2->Write();
 const double *outParametersTemp = minuit->X();
 const double *errParametersTemp = minuit->Errors();
  
 double *outParameters = new double;
 double *errParameters = new double;
 outParameters[0] = outParametersTemp[0];
 errParameters[0] = errParametersTemp[0];
   
 double minChi2 = grChi2->Eval(outParameters[0]);
 std::cerr << " numEvents = " << numEvents << " Scale = " << outParameters[0] << " +/- " << errParameters[0] << std::endl;
 ///===== end Chi2 ====
  
 ///==== likelihood ====
 std::cerr << " === LL === " << std::endl;
 minuit->SetFunction(functorLL);

 TGraph * grLL_temp = new TGraph(iNoSteps);
 minuit->Scan(iPar_NoBG,iNoSteps,grLL_temp->GetX(),grLL_temp->GetY(),MinScan,MaxScan);
 TGraph * grLL = new TGraph();
 grLL->SetName("grLL");
 int nPointLL = 0;
 for (unsigned int iStep = 0; iStep < iNoSteps; iStep++){
  double x = MinScan + (MaxScan - MinScan) / iNoSteps * (iStep+0.5);
  double y = LLFunc(&x);
//  std::cerr << " y = " << y << std::endl;
  if (y != numberDATA * numEvents) {
   std::cerr << " Ok y = " << y << std::endl;
   grLL->SetPoint(nPointLL,x,y);
   nPointLL++;
  }
 }
 
 
 std::cerr << " finito " << std::endl;
 
 grLL->Draw("AL");
 outFile->cd();
 minuit->PrintResults();
 outFile->cd();
 grLL->SetTitle("grLL");
 grLL->Write();
 
 std::cerr << " done " << std::endl;

 const double *outParametersTemp2 = minuit->X();
 const double *errParametersTemp2 = minuit->Errors();

 std::cerr << " done 2 " << std::endl;
  
 double *outParametersLL = new double;
 double *errParametersLL = new double;
 outParametersLL[0] = outParametersTemp2[0];
 errParametersLL[0] = errParametersTemp2[0];
 
 double minLL = grLL->Eval(outParametersLL[0]);
 std::cerr << " numEvents = " << numEvents << " Scale = " << outParametersLL[0] << " +/- " << errParametersLL[0] << std::endl;
 ///==== end likelihood ====
 
 
 ///==== newChi2 ====
 std::cerr << " === newChi2 === " << std::endl;
 minuit->SetFunction(functorNewChi2);
 TGraph * grNewChi2 = new TGraph(iNoSteps);
 minuit->Scan(iPar_NoBG,iNoSteps,grNewChi2->GetX(),grNewChi2->GetY(),MinScan,MaxScan);
 grNewChi2->Draw("AL");
 outFile->cd();
 minuit->PrintResults();
 outFile->cd();
 grNewChi2->SetTitle("grNewChi2");
 grNewChi2->Write();
 const double *outParametersNewChi2 = minuit->X();
 const double *errParametersNewChi2 = minuit->Errors();
 double minNewChi2 = grNewChi2->Eval(outParametersNewChi2[0]);
 std::cerr << " numEvents = " << numEvents << " Scale = " << outParametersNewChi2[0] << " +/- " << errParametersNewChi2[0] << std::endl;
 ///==== end newChi2 ====
  
 
 
 std::cerr << "... Minimized with all methods ..." << std::endl;

 ///==== Save the whole shape of LL/Chi2 ====
 for (unsigned int ii=0; ii < iNoSteps; ii++){
  double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan;
  
  Alpha   = X_ii;
  Chi2    = grChi2->Eval(X_ii);
  LL      = grLL->Eval(X_ii);
  NewChi2 = grNewChi2->Eval(X_ii);
  myTreeChi2->Fill();
 }
  
 ///===== Look for minima =====
  
 ///===== Chi2 ====
 std::cerr << " === Chi2 === " << std::endl;
 std::cerr << "==== min Scan = " << minChi2 << std::endl;
 double errX_low = -9999;
 double errX_up = 9999;
 int err_low = 0;
 int err_up = 0;
 for (unsigned int ii=0; ii < iNoSteps; ii++){
  double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan;
  double here = grChi2->Eval(X_ii);
  if (err_low == 0){
   if (here < (minChi2 + DELTA_CHI2)){
    errX_low = X_ii;
    err_low = 1;
   }
  }
  else if (err_up == 0 && here > (minChi2 + DELTA_CHI2) && X_ii > outParameters[0]){
   errX_up = X_ii; 
   err_up = 1;
  }
 }
 
 AlphaMean = outParameters[0];
 AlphaMinus = errX_low;
 AlphaPlus = errX_up;

 grChi2->Fit("fitMin","RMQ");
 c = fitMin->GetParameter(0);
 b = fitMin->GetParameter(1);
 a = fitMin->GetParameter(2);
 AlphaMean_Fit  = -b / (2*a);
 AlphaMinus_Fit = (-b + 2 * sqrt(a)) / (2*a);  ///==== delta Chi2 = 1 
 AlphaPlus_Fit  = (-b - 2 * sqrt(a)) / (2*a);  ///==== delta Chi2 = 1   
 myTreeChi2_Result->Fill();
  
 ScaleTrue_Chi2 = AlphaMean;
 ScaleTrue_Chi2_Fit = AlphaMean_Fit;

 ///===== LogLikelihood ====
 std::cerr << " === LL === " << std::endl;
 std::cerr << "==== min Scan = " << minLL << std::endl;
 errX_low = -9999;
 errX_up = 9999;
 err_low = 0;
 err_up = 0;
 for (unsigned int ii=0; ii < iNoSteps; ii++){
  double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan;
  double here = grLL->Eval(X_ii);
  if (err_low == 0){
   if (here < (minLL + DELTA_LL)){
    errX_low = X_ii;
    err_low = 1;
   }
  }
  else if (err_up == 0 && here > (minLL + DELTA_LL) && X_ii > outParametersLL[0]){
   errX_up = X_ii; 
   err_up = 1;
  }
 }
 
 AlphaMean = outParametersLL[0];
 AlphaMinus = errX_low;
 AlphaPlus = errX_up;

 grLL->Fit("fitMin","RMQ");
 c = fitMin->GetParameter(0);
 b = fitMin->GetParameter(1);
 a = fitMin->GetParameter(2);
 AlphaMean_Fit  = -b / (2*a);
 AlphaMinus_Fit = (-b + sqrt(2*a)) / (2*a);  ///==== delta LL = 0.5
 AlphaPlus_Fit  = (-b - sqrt(2*a)) / (2*a);  ///==== delta LL = 0.5   
 
 myTreeLL_Result->Fill();
 
 ScaleTrue_LL = AlphaMean;
 ScaleTrue_LL_Fit = AlphaMean_Fit;

 
 ///===== NewChi2 ====
 std::cerr << " === NewChi2 === " << std::endl;
 std::cerr << "==== min Scan = " << minNewChi2 << std::endl;
 errX_low = -9999;
 errX_up = 9999;
 err_low = 0;
 err_up = 0;
 for (unsigned int ii=0; ii < iNoSteps; ii++){
  double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan;
  double here = grNewChi2->Eval(X_ii);
  if (err_low == 0){
   if (here < (minNewChi2 + DELTA_CHI2)){
    errX_low = X_ii;
    err_low = 1;
   }
  }
  else if (err_up == 0 && here > (minNewChi2 + DELTA_CHI2) && X_ii > outParametersNewChi2[0]){
   errX_up = X_ii; 
   err_up = 1;
  }
 }
  
 AlphaMean = outParametersNewChi2[0];
 AlphaMinus = errX_low;
 AlphaPlus = errX_up;
 
 
 grNewChi2->Fit("fitMin","RMQ");
 c = fitMin->GetParameter(0);
 b = fitMin->GetParameter(1);
 a = fitMin->GetParameter(2);
 AlphaMean_Fit  = -b / (2*a);
 AlphaMinus_Fit = (-b + 2 * sqrt(a)) / (2*a);  ///==== delta Chi2 = 1 
 AlphaPlus_Fit  = (-b - 2 * sqrt(a)) / (2*a);  ///==== delta Chi2 = 1   
 
 myTreeNewChi2_Result->Fill();
  
 ScaleTrue_NewChi2 = AlphaMean;
 ScaleTrue_NewChi2_Fit = AlphaMean_Fit;

 std::cerr << " ================ End DATA Scale search ================ " << std::endl;


///==== MC analysis ==== Scale search ====
 Data_or_MC = 0; ///=== 1 = Data;  0 = MC; -1 = MC Fit
 std::cerr << " ==== MC Scale search ==== " << std::endl; 
 ///==== cycle on number of Toy MC experiments ====
 ///=== Chi2 ===
 std::cerr << "======================= Chi2 " << ScaleTrue_Chi2 << " =====================" << std::endl;
//  ScaleTrue = ScaleTrue_Chi2;
//  doMC_Chi2();

///=== LogLikelihood ===
 std::cerr << "======================= LL " << ScaleTrue_LL << " =====================" << std::endl;
//  ScaleTrue = ScaleTrue_LL;
//  doMC_LL();

///=== NewChi2 ===
 std::cerr << "======================= NewChi2 " << ScaleTrue_NewChi2 << " =====================" << std::endl;
//  ScaleTrue = ScaleTrue_NewChi2;
//  doMC_NewChi2();


 Data_or_MC = -1; ///=== 1 = Data;  0 = MC; -1 = MC Fit
 std::cerr << " ==== MC Scale search ==== " << std::endl; 
 ///==== cycle on number of Toy MC experiments ====
 ///=== Chi2 ===
 std::cerr << "======================= Chi2 FIT " << ScaleTrue_Chi2_Fit << " =====================" << std::endl;
//  ScaleTrue = ScaleTrue_Chi2_Fit;
//  doMC_Chi2();

///=== LogLikelihood ===
 std::cerr << "======================= LL FIT " << ScaleTrue_LL_Fit << " =====================" << std::endl;
 ScaleTrue = ScaleTrue_LL_Fit;
 doMC_LL();

///=== NewChi2 ===
 std::cerr << "======================= NewChi2 FIT " << ScaleTrue_NewChi2_Fit << " =====================" << std::endl;
//  ScaleTrue = ScaleTrue_NewChi2_Fit;
//  doMC_NewChi2();

 
  ///----------------------
  ///---- Plot results ----
  ///----------------------
  outFile->cd();
  myTreeChi2->Write();
  myTreeLL_Result->Write();
  myTreeChi2_Result->Write();
  myTreeNewChi2_Result->Write();
  delete fitMin;
  
}
Example #10
0
///**** LL ****
void doMC_LL(){
 TTree* MyTreeMC = (TTree*) fileInMC->Get(treeNameMC.c_str());

 for (nIter = 0; nIter<maxIter; nIter++){
  if (!(nIter%1)) std::cerr << ">>> nIter = " << nIter << " : " << maxIter << std::endl;
  vET_data.clear();
  outFile->cd();
  TString nameDATA = Form("hDATA_%d_%d_%.5f",Data_or_MC,nIter,ScaleTrue);
  TH1F hDATA(nameDATA,nameDATA,numBINS,minBINS,maxBINS);
  
  MyTreeMC->Draw(">> myListMC",(AdditionalCut+Form("&& (ET * (1+(%f)))>%f",ScaleTrue,minET)).Data(),"entrylist");
  TEntryList *myListMC = (TEntryList*)gDirectory->Get("myListMC");
  
  MyTreeMC->SetEntryList(0); 
  TEntryList *listMCHere = new TEntryList("listMCHere","listMCHere");    
  for (int iEvt = 0; iEvt < numSelectedData; iEvt ++){
   listMCHere->Enter(myListMC->GetEntry(gRandom->Uniform(0,myListMC->GetN())));
  }
  
  MyTreeMC->SetEntryList(listMCHere);
  MyTreeMC->Draw(Form("(1+%f) * %s >> %s",ScaleTrue,variableName.c_str(),nameDATA.Data()));
  
  ConvertStdVectDouble(vET_data,MyTreeMC->GetV1(),numSelectedData);
  
  ///==== likelihood ====
 std::cerr << " === LL === " << std::endl;
 std::cerr << " === pseudo vET_data.size() = " << vET_data.size() << std::endl;
 
 
  minuit->SetFunction(functorLL); 
  TGraph * grLL_temp = new TGraph(iNoSteps);
  minuit->Scan(iPar_NoBG,iNoSteps,grLL_temp->GetX(),grLL_temp->GetY(),MinScan,MaxScan);
  TGraph * grLL = new TGraph();
  int nPointLL = 0;
 for (unsigned int iStep = 0; iStep < iNoSteps; iStep++){
   double x = MinScan + (MaxScan - MinScan) / iNoSteps * (iStep+0.5);
   double y = LLFunc(&x);
   if (y != numberDATA * numEvents) {
    grLL->SetPoint(nPointLL,x,y);
    nPointLL++;
   }
  }
  grLL->Draw("AL");
  outFile->cd();
  minuit->PrintResults();
  const double *outParametersTemp2 = minuit->X();
  const double *errParametersTemp2 = minuit->Errors();
  
  double *outParametersLL = new double;
  double *errParametersLL = new double;
  outParametersLL[0] = outParametersTemp2[0];
  errParametersLL[0] = errParametersTemp2[0];
  
  std::cerr << " nPointLL = " << nPointLL << std::endl;
  
  double minLL = grLL->Eval(outParametersLL[0]);
  ///==== end likelihood ====
  
    ///==== Save the whole shape of LL/Chi2 ====
  for (unsigned int ii=0; ii < iNoSteps; ii++){
   double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan;
   
   Alpha   = X_ii;
   Chi2    = 0;
   LL      = grLL->Eval(X_ii);
   NewChi2 = 0;
   
   myTreeChi2->Fill();
  }

  ///===== Look for minima =====
  double a;
  double b;
  double c;
  
  
  double errX_low = -9999;
  double errX_up = 9999;
  int err_low = 0;
  int err_up = 0;
  for (unsigned int ii=0; ii < iNoSteps; ii++){
   double X_ii = (MaxScan - MinScan) / iNoSteps * ii + MinScan;
   double here = grLL->Eval(X_ii);
   if (err_low == 0){
    if (here < (minLL + DELTA_LL)){
     errX_low = X_ii;
     err_low = 1;
    }
   }
   else if (err_up == 0 && here > (minLL + DELTA_LL) && X_ii > outParametersLL[0]){
    errX_up = X_ii; 
    err_up = 1;
   }
  }
  
  AlphaMean = outParametersLL[0];
  AlphaMinus = errX_low;
  AlphaPlus = errX_up;
 
  grLL->Fit("fitMin","RMQ");
  c = fitMin->GetParameter(0);
  b = fitMin->GetParameter(1);
  a = fitMin->GetParameter(2);
  AlphaMean_Fit  = -b / (2*a);
  AlphaMinus_Fit = (-b + sqrt(2*a)) / (2*a);  ///==== delta LL = 0.5
  AlphaPlus_Fit  = (-b - sqrt(2*a)) / (2*a);  ///==== delta LL = 0.5   
  
  myTreeLL_Result->Fill();
 
  grLL->Write();
  
  //delete listMCHere;
  
 }
}
Example #11
0
void DoEvolutions( const TString &sim, Int_t time, Int_t Nbins=1, const TString &options="") { 
  
#ifdef __CINT__  
  gSystem->Load("libptools.so");
#endif

  PGlobals::Initialize();
    
  // Palettes!
  gROOT->Macro("PPalettes.C");

  TString opt = options;
  // cout << "options = " << opt << endl;

  // Load PData
  PData *pData = PData::Get(sim.Data());
  pData->LoadFileNames(time);
  if(!pData->IsInit()) return;

  Bool_t CYL = kFALSE;
  if(sim.Contains("cyl")) { CYL = kTRUE; opt += "cyl"; } 
    
  Bool_t ThreeD = kFALSE;
  if(sim.Contains("3D")) ThreeD = kTRUE; 
  
  // Some plasma constants
  Double_t n0 = pData->GetPlasmaDensity();
  Double_t kp = pData->GetPlasmaK();
  Double_t skindepth = 1.0;
  if(kp!=0.0) skindepth = 1/kp;
  Double_t E0 = pData->GetPlasmaE0();

  // Some initial beam properties:
  Float_t Ebeam = pData->GetBeamEnergy() * PUnits::MeV;
  Float_t gamma = pData->GetBeamGamma();
  Float_t vbeam = pData->GetBeamVelocity();
  
  Double_t rms0 = pData->GetBeamRmsY() * kp;
  if(CYL)  rms0 = pData->GetBeamRmsR() * kp;
  
  // Time in OU
  Float_t Time = pData->GetRealTime();
  // z start of the plasma in normalized units.
  Float_t zStartPlasma = pData->GetPlasmaStart() * kp;
  // z start of the beam in normalized units.
  Float_t zStartBeam = pData->GetBeamStart() * kp;
  
  if(opt.Contains("center")) {
    Time -= zStartPlasma;
    if(opt.Contains("comov"))      // Centers on the head of the beam.
      Time += zStartBeam;
  }

  // Beam charge 2D and 1D histogram (on-axis)
  // ------------------------------------------------------------------
  TH2F *hDen2D = NULL;
  if(pData->GetChargeFileName(1)) {
    char hName[24];
    sprintf(hName,"hDen2D");
    hDen2D = (TH2F*) gROOT->FindObject(hName);
    if(hDen2D) { delete hDen2D; hDen2D = NULL; }

    if(!ThreeD)
      hDen2D = pData->GetCharge(1,opt);
    else
      hDen2D = pData->GetCharge2DSliceZY(1,-1,1,opt+"avg");

    hDen2D->SetName(hName);
    hDen2D->GetXaxis()->CenterTitle();
    hDen2D->GetYaxis()->CenterTitle();
    hDen2D->GetZaxis()->CenterTitle();
    
    if(opt.Contains("comov"))
      hDen2D->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      hDen2D->GetXaxis()->SetTitle("k_{p}z");
    
    if(CYL) 
      hDen2D->GetYaxis()->SetTitle("k_{p}r");
    else
      hDen2D->GetYaxis()->SetTitle("k_{p}y");

    hDen2D->GetZaxis()->SetTitle("n_{b}/n_{0}");

 
  }
  
  // Define ranges from the charge 2D histogram:
  // Binning for 2D histograms:
  // We get this values from the 2D density histogram.
  Int_t   x1Nbin    = hDen2D->GetNbinsX();
  Float_t x1Range   = (hDen2D->GetXaxis()->GetXmax() - hDen2D->GetXaxis()->GetXmin());
  Float_t x1Mid     = (hDen2D->GetXaxis()->GetXmax() + hDen2D->GetXaxis()->GetXmin())/2.;
  Float_t x1Min     = hDen2D->GetXaxis()->GetXmin();
  Float_t x1Max     = hDen2D->GetXaxis()->GetXmax();
  
  Int_t   x2Nbin    = hDen2D->GetNbinsY();      
  Float_t x2Range   = (hDen2D->GetYaxis()->GetXmax() - hDen2D->GetYaxis()->GetXmin());
  Float_t x2Mid     = (hDen2D->GetYaxis()->GetXmax() + hDen2D->GetYaxis()->GetXmin())/2.;
  Float_t x2Min     = x2Mid - x2Range/2;
  Float_t x2Max     = x2Mid + x2Range/2;
  
  if(Nbins==0) {
    Nbins = TMath::Nint(rms0 / hDen2D->GetYaxis()->GetBinWidth(1)) ;
    // cout << Form(" Rms0 = %6.2f  Dx = %6.2f  Nbins = %4i .", 
    // 	   rms0, hDen2D->GetYaxis()->GetBinWidth(1), Nbins) << endl;
  }
  
  // Slice width limits.
  Int_t FirstyBin = 0;
  Int_t LastyBin  = 0;
  if(!CYL) {
    FirstyBin = hDen2D->GetNbinsY()/2 + 1 - Nbins;
    LastyBin =  hDen2D->GetNbinsY()/2 + Nbins;
  } else {
    FirstyBin = 1; 
    LastyBin  = Nbins;
  }  


  // OUTPUT ROOT FILE WITH THE PLOTS:
  TString filename = Form("./%s/Plots/Evolutions/Evolutions-%s.root",sim.Data(),sim.Data());
  TFile * ifile = (TFile*) gROOT->GetListOfFiles()->FindObject(filename);
  // if doesn't exist the directory should be created
  if (!ifile) {
    TString f = filename;
    TString dir2 = f.Remove( f.Last( '/' ), f.Length() - f.Last( '/' ) );
    TString dir1 = f.Remove( f.Last( '/' ), f.Length() - f.Last( '/' ) );
    gSystem->mkdir( dir1 );
    gSystem->mkdir( dir2 );
    ifile = new TFile(filename,"UPDATE");
  }  

  
  // Charge 1D histogram on axis
  TH1F *hDen1D = NULL;
  if(pData->GetChargeFileName(1)) {
    TString opth1 = opt;
    opth1 += "avg";
    
    char hName[24];
    sprintf(hName,"hDen1D");
    hDen1D = (TH1F*) gROOT->FindObject(hName);
    if(hDen1D) delete hDen1D;
    
    if(ThreeD) {
      hDen1D = pData->GetH1SliceZ3D(pData->GetChargeFileName(1)->c_str(),"charge",-1,Nbins,-1,Nbins,opth1.Data());
    } else if(CYL) { // Cylindrical: The first bin with r>0 is actually the number 1 (not the 0).
      hDen1D = pData->GetH1SliceZ(pData->GetChargeFileName(1)->c_str(),"charge",1,Nbins,opth1.Data());
    } else { // 2D cartesian
      hDen1D = pData->GetH1SliceZ(pData->GetChargeFileName(1)->c_str(),"charge",-1,Nbins,opth1.Data());
    }
    hDen1D->SetName(hName); 
    
    if(opt.Contains("comov"))
      hDen1D->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      hDen1D->GetXaxis()->SetTitle("k_{p}z");
  
    hDen1D->GetYaxis()->SetTitle("n_{b}/n_{0}");
  }

  // On-axis beam density vs \zeta vs time! _________________________________
  TH2F *hDen1DvsTime = NULL; 
  if(hDen1D) {
    char hName[24];
    sprintf(hName,"hDen1DvsTime");
    TH2F *hDen1DvsTimeOld = (TH2F*) ifile->Get(hName);

    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hDen1DvsTimeOld!=NULL) {
      nBins = hDen1DvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hDen1DvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hDen1DvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hDen1DvsTime = new TH2F("temp","",nBins,edge0,edge1,
		       	hDen1D->GetNbinsX(),
			hDen1D->GetBinLowEdge(1),
			hDen1D->GetBinLowEdge(hDen1D->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hDen1DvsTime->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hDen1DvsTime->GetNbinsY();iy++) {
	hDen1DvsTime->SetBinContent(ix,iy,hDen1DvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hDen1DvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hDen1D->GetNbinsX();iy++) {
      hDen1DvsTime->SetBinContent(nBins,iy,hDen1D->GetBinContent(iy));
    }   

    hDen1DvsTime->GetZaxis()->SetTitle("n_{b}/n_{0}");
    hDen1DvsTime->GetYaxis()->SetTitle("k_{p}#zeta");
    hDen1DvsTime->GetXaxis()->SetTitle("k_{p}z");
    hDen1DvsTime->GetZaxis()->CenterTitle();
    hDen1DvsTime->GetYaxis()->CenterTitle();
    hDen1DvsTime->GetXaxis()->CenterTitle();
    hDen1DvsTime->SetName(hName);

    // Change the range of z axis 
    Float_t Denmax = hDen1DvsTime->GetMaximum();
    hDen1DvsTime->GetZaxis()->SetRangeUser(0,Denmax); 
    hDen1DvsTime->Write(hName,TObject::kOverwrite);

  }

  // RMS (vs z) of the beam's charge distribution: 
  TProfile *hDen2Dprof = NULL;
  TH1F *hRms = NULL;
  Double_t axisPos = x2Mid;
  if(hDen2D) {
    TString pname = hDen2D->GetName();
    pname += "_pfx";
    
    hDen2Dprof =  (TProfile*) gROOT->FindObject(pname.Data());
    if(hDen2Dprof) { delete hDen2Dprof; hDen2Dprof = NULL; }
    hDen2Dprof = hDen2D->ProfileX("_pfx",1,-1,"s");
    
    hRms = (TH1F*) gROOT->FindObject("hRms");
    if(hRms) delete hRms;
    
    hRms = new TH1F("hRms","",x1Nbin,x1Min,x1Max);
    
    if(CYL) axisPos = 0.0;
    
    for(Int_t j=0;j<hRms->GetNbinsX();j++) {
      Double_t rms = 0;
      Double_t total = 0;
      for(Int_t k=1;k<=x2Nbin;k++) {
	Double_t value  = hDen2D->GetBinContent(j,k);
	Double_t radius = hDen2D->GetYaxis()->GetBinCenter(k) - axisPos;
	if(CYL) {
	  rms += radius*radius*radius*value;
	  total += radius*value;
	} else {
	  rms += radius*radius*value;
	  total += value;
	}
	// cout << Form(" (%i,%i) -> radius = %7.4f ,  density = %7.4f",j,k,radius,value) << endl;
      }
      
      rms /= total;
      rms = sqrt(rms);
      
      hRms->SetBinContent(j,rms); 
      
    }
    
    hRms->GetXaxis()->SetTitle("k_{p}z");
    if(opt.Contains("comov"))
      hRms->GetXaxis()->SetTitle("k_{p}#zeta");
    
    hRms->GetYaxis()->SetTitle("k_{p}#LTr#GT_{rms}");
  }
  
  // Transverse charge RMS vs \zeta vs time! _________________________________
  TH2F *hRmsvsTime = NULL; 
  if(hRms) {
    char hName[24];
    sprintf(hName,"hRmsvsTime");
    TH2F *hRmsvsTimeOld = (TH2F*) ifile->Get(hName);

    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hRmsvsTimeOld!=NULL) {
      nBins = hRmsvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hRmsvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hRmsvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hRmsvsTime = new TH2F("temp","",nBins,edge0,edge1,
		       	hRms->GetNbinsX(),
			hRms->GetBinLowEdge(1),
			hRms->GetBinLowEdge(hRms->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hRmsvsTime->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hRmsvsTime->GetNbinsY();iy++) {
	hRmsvsTime->SetBinContent(ix,iy,hRmsvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hRmsvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hRms->GetNbinsX();iy++) {
      hRmsvsTime->SetBinContent(nBins,iy,hRms->GetBinContent(iy));
    }   

    hRmsvsTime->GetZaxis()->SetTitle("#LTr#GT_{rms}");
    hRmsvsTime->GetYaxis()->SetTitle("k_{p}#zeta");
    hRmsvsTime->GetXaxis()->SetTitle("k_{p}z");
    hRmsvsTime->GetZaxis()->CenterTitle();
    hRmsvsTime->GetYaxis()->CenterTitle();
    hRmsvsTime->GetXaxis()->CenterTitle();
    hRmsvsTime->SetName(hName);

    // Change the range of z axis
    Float_t Rmsmax = hRmsvsTime->GetMaximum();
    hRmsvsTime->GetZaxis()->SetRangeUser(0,Rmsmax); 
    hRmsvsTime->Write(hName,TObject::kOverwrite);

  }

  // INTEGRATED Beam's Charge:
  // Total charge vs time :
  TGraph *gQvsTime = NULL;
  if(hDen2D) {
    Double_t Q = 0;
    for(Int_t i=1;i<=x1Nbin;i++) {
      for(Int_t j=1;j<=x2Nbin;j++) {
	Double_t value  = hDen2D->GetBinContent(i,j);
	if(CYL) {
	  Double_t radius = hDen2D->GetYaxis()->GetBinCenter(j);
	  Q += radius * value;
	  // cout << Form(" (%i,%i) -> radius = %7.4f , value = %7.4f",i,j,radius,value) << endl;
	} else {
	  Q += value;
	}
      }    
    }
    Double_t xbinsize = hDen2D->GetXaxis()->GetBinWidth(1);
    Double_t ybinsize = hDen2D->GetYaxis()->GetBinWidth(1); 
    Q *= xbinsize * ybinsize;
    
    if(!CYL && !ThreeD) {
      Q *= TMath::Sqrt(2*TMath::Pi()) * rms0; 
    } else if(CYL) {
      Q *= 2*TMath::Pi();
    }
    
    if(opt.Contains("units")) {
      Double_t dV = skindepth * skindepth * skindepth;
      Q *= n0 * dV;
      Q *= (PConst::ElectronCharge/PUnits::picocoulomb); 
      cout << Form(" Integrated charge     = %8i pC", TMath::Nint(Q)) << endl;
    } else {
      cout << Form(" Integrated charge     = %8.4f n0 * kp^-3",Q) << endl;
    }
    
    Int_t nPoints = 0;
    char gName[32];
    sprintf(gName,"gQvsTime");     
    gQvsTime = (TGraph*) ifile->Get(gName);
    if(gQvsTime==NULL) {
      gQvsTime = new TGraph();
      gQvsTime->SetName(gName);
      nPoints = 0;
      // Some cosmetics at creation time:
      gQvsTime->SetLineWidth(3);
      gQvsTime->SetLineColor(PGlobals::fieldLine);
      gQvsTime->SetMarkerStyle(20);
      gQvsTime->SetMarkerSize(0.4);
      gQvsTime->SetMarkerColor(PGlobals::fieldLine);	
      gQvsTime->GetYaxis()->SetTitle("charge [n_{0}/k_{p}^{3}]");
      gQvsTime->GetXaxis()->SetTitle("k_{p}z");
    } else {
      nPoints = gQvsTime->GetN(); 
    }  
    
    gQvsTime->Set(nPoints+1);
    gQvsTime->SetPoint(nPoints,Time,Q);
    gQvsTime->Write(gName,TObject::kOverwrite);
  }
  
  // ------------------------------------------------------------------------------------
  

  // Longitudinal phasespace 
  Int_t  gNbin = 100;
  // Float_t gMin = 80;
  // Float_t gMax = 120;
  Float_t gMin = 43.07 - 1.2;
  Float_t gMax = 43.07 + 1.2;
  TH2F *hGvsZ = NULL;
  if(pData->GetRawFileName(1)) {
    char hName[24];
    sprintf(hName,"hGvsZ");
    hGvsZ = (TH2F*) gROOT->FindObject(hName);
    if(hGvsZ) { delete hGvsZ; hGvsZ = NULL; }
    hGvsZ = new TH2F(hName,"",x1Nbin,x1Min,x1Max,gNbin,gMin,gMax);
    pData->GetH2Raw(pData->GetRawFileName(1)->c_str(),"x1","gamma",hGvsZ,opt);
    
    hGvsZ->GetXaxis()->CenterTitle();
    hGvsZ->GetYaxis()->CenterTitle();
    hGvsZ->GetZaxis()->CenterTitle();
    hGvsZ->GetYaxis()->SetTitle("#gamma");
    if(opt.Contains("comov")) {
      hGvsZ->GetXaxis()->SetTitle("k_{p}#zeta");
      hGvsZ->GetZaxis()->SetTitle("dN/d#zetad#gamma [a.u.]");
    }  else {
      hGvsZ->GetXaxis()->SetTitle("k_{p}z");
      hGvsZ->GetZaxis()->SetTitle("dN/dzd#gamma [a.u.]");
    }    
  } else {
    cout << Form("--> No RAW data file is present for species 1") << endl;
  }

  TH2F *hGvsTime = NULL; 
  TProfile *hGvsZprof = NULL;
  TGraphErrors *gGvsZ = NULL;
  if(hGvsZ) {
    TString pname = hGvsZ->GetName();
    pname += "_pfx";
    hGvsZprof =  (TProfile*) gROOT->FindObject(pname.Data());
    if(hGvsZprof) delete hGvsZprof;

    hGvsZprof = hGvsZ->ProfileX("_pfx",1,-1,"s");

    gGvsZ = (TGraphErrors*) gROOT->FindObject("gGvsZ");
    if(gGvsZ) delete gGvsZ;

    Int_t Npoints = hGvsZprof->GetNbinsX();
    Double_t *x = new Double_t[Npoints];
    Double_t *y = new Double_t[Npoints];
    Double_t *ex = new Double_t[Npoints];
    Double_t *ey = new Double_t[Npoints];
    
    for(Int_t j=0;j<Npoints;j++) {
      x[j] = hGvsZprof->GetBinCenter(j);
      y[j] = hGvsZprof->GetBinContent(j);
      ex[j] = 0;
      ey[j] = hGvsZprof->GetBinError(j);   
    }
    
    gGvsZ = new TGraphErrors(Npoints,x,y,ex,ey);
    gGvsZ->SetName("gGvsZ");
        
    // PGlobals::SetH1Style((TH1*)gGvsZ,1);
    PGlobals::SetGraphStyle(gGvsZ,1);

   
    if(opt.Contains("comov")) 
      gGvsZ->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      gGvsZ->GetXaxis()->SetTitle("k_{p}z");
    
    gGvsZ->GetYaxis()->SetTitle("#LT#gamma#GT [MeV]");

    char hName[24];
    sprintf(hName,"hGvsTime");
    TH2F *hGvsTimeOld = (TH2F*) ifile->Get(hName);

    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hGvsTimeOld!=NULL) {
      nBins = hGvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hGvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hGvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hGvsTime = new TH2F("temp","",nBins,edge0,edge1,
		       	hGvsZprof->GetNbinsX(),
			hGvsZprof->GetBinLowEdge(1),
			hGvsZprof->GetBinLowEdge(hGvsZprof->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hGvsTime->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hGvsTime->GetNbinsY();iy++) {
	hGvsTime->SetBinContent(ix,iy,hGvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hGvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hGvsZprof->GetNbinsX();iy++) {
      hGvsTime->SetBinContent(nBins,iy,hGvsZprof->GetBinContent(iy));
    }   

    hGvsTime->GetZaxis()->SetTitle("#LT#gamma#GT");
    hGvsTime->GetYaxis()->SetTitle("k_{p}#zeta");
    hGvsTime->GetXaxis()->SetTitle("k_{p}z");
    hGvsTime->GetZaxis()->CenterTitle();
    hGvsTime->GetYaxis()->CenterTitle();
    hGvsTime->GetXaxis()->CenterTitle();
    hGvsTime->SetName(hName);

    // Change the range of z axis
    Float_t Gmax = hGvsTime->GetMaximum();
    Float_t Gmin = hGvsTime->GetMinimum();    
    hGvsTime->GetZaxis()->SetRangeUser(Gmin,Gmax); 
    hGvsTime->Write(hName,TObject::kOverwrite);
    
  }

  // ---------------------------------------------------------------------------------


  // EM fields on - axis :

  TString opth1 = opt;
  opth1 += "avg";
  // Get electric fields
  const Int_t Nfields = 2;
  TH1F **hE1D = new TH1F*[Nfields];
  for(Int_t i=0;i<Nfields;i++) {
    hE1D[i] = NULL;
    if(!pData->GetEfieldFileName(i))
      continue;
    
    char nam[3]; sprintf(nam,"e%i",i+1);
    if(ThreeD) {
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,-1,Nbins,opth1.Data());
      else  
	hE1D[i] = pData->GetH1SliceZ3D(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,-Nbins,Nbins,opth1.Data());
    } else if(CYL) { // Cylindrical: The first bin with r>0 is actually the number 1 (not the 0).
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,1,Nbins,opth1.Data());
      else
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,1,Nbins,opth1.Data());
    } else { // 2D cartesian
      if(i==0) 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-1,Nbins,opth1.Data());
      else 
	hE1D[i] = pData->GetH1SliceZ(pData->GetEfieldFileName(i)->c_str(),nam,-Nbins,Nbins,opth1.Data());
    }
    
    char hName[24];
    sprintf(hName,"hE_%i_%i",i,time);
    hE1D[i]->SetName(hName);
    if(opt.Contains("comov"))
      hE1D[i]->GetXaxis()->SetTitle("k_{p}#zeta");
    else
      hE1D[i]->GetXaxis()->SetTitle("k_{p}z");
   
    if(i==0)
      hE1D[i]->GetYaxis()->SetTitle("E_{z}/E_{0}");
    else if(i==1)
      hE1D[i]->GetYaxis()->SetTitle("E_{y}/E_{0}");
    else if(i==2)
      hE1D[i]->GetYaxis()->SetTitle("E_{x}/E_{0}");
    
    hE1D[i]->GetYaxis()->CenterTitle();
    hE1D[i]->GetXaxis()->CenterTitle();
    
  }  
  
  // Calculate wave positions:
  // ----------------------------------------------------------------
    
  // Calculate the crossings and the extremes of the Electric fields
  Float_t Ecross[Nfields][100] = {{0.0}};
  Float_t Eextr[Nfields][100] = {{0.0}};
  Int_t Ncross[Nfields] = {0};

  for(Int_t i=0;i<Nfields;i++) {
    Ncross[i] = 0;
    
    if(!hE1D[i]) continue;
    
    // Only smooths the focusing if flag activated..
    if(i>0 && opt.Contains("smooth")) {
      // cout << " Smoothing fields on axis..." << endl;
      hE1D[i]->Smooth(10);
    } 

    Float_t maxZeta = zStartBeam;
    if(opt.Contains("center")) 
      maxZeta -= zStartBeam;
          
    for(Int_t ip=hE1D[i]->GetNbinsX();ip>1;ip--) {

      Float_t Z2 = hE1D[i]->GetBinCenter(ip-1);
      if(Z2 > maxZeta) continue;
      Float_t E1 = hE1D[i]->GetBinContent(ip);
      Float_t E2 = hE1D[i]->GetBinContent(ip-1);
      Float_t Z1 = hE1D[i]->GetBinCenter(ip);
      
      // cout << Form("Z1 = %6.4f  Z2 = %6.4f   E1 = %6.4f   E2 = %6.4f", Z1, Z2, E1, E2) << endl; 

      if(E1*E2 >= 0) { // No change of sign means we are in a side of the zero axis.
	if(fabs(E2)>fabs(Eextr[i][Ncross[i]])) {
	  Eextr[i][Ncross[i]] = E2;
	} 
      }
      
      if(E1*E2 < 0) { // change of sign means a crossing!
	
	// The next crossing has to be far enough from the previous one:
	Float_t zcross =  -E1 * ( (Z2-Z1)/(E2-E1) ) + Z1;
        if(Ncross[i]>0 && fabs(Ecross[i][Ncross[i]-1]-zcross)<TMath::PiOver2() ) continue;	
	// cout << " CROSS! " << endl;

	// add the point
	Ecross[i][Ncross[i]] = zcross;
	Ncross[i]++;
      }
    }
    
    cout << "  -> Number of crossings for field " << i << " : " << Ncross[i] << endl;
    for(Int_t ic=0;ic<Ncross[i];ic++) {
      //  cout << Form(" %2i:  zeta = %6.4f  E = %6.4f", ic, Ecross[i][ic], Eextr[i][ic]) << endl; 
    }  
    
    
    hE1D[i]->SetLineColor(kRed);
    hE1D[i]->Write(hE1D[i]->GetName(),TObject::kOverwrite);

  }
  
  // Get the Graphs and histos from file
  Int_t nPoints = 0;
  TGraph ***gEcross = new TGraph**[Nfields]; 
  TGraph ***gEextr  = new TGraph**[Nfields]; 
  TH2F **hEvsTime = new TH2F*[Nfields]; 
  for(Int_t i=0;i<Nfields;i++) {
    char hName[24];
    sprintf(hName,"hEvsTime_%i",i);
    TH2F *hEvsTimeOld = (TH2F*) ifile->Get(hName);
    Int_t nBins   = 1;
    Float_t edge0 = Time-0.5;
    Float_t edge1 = Time+0.5;
    if(hEvsTimeOld!=NULL) {
      nBins = hEvsTimeOld->GetNbinsX()+1;
      Float_t binwidth =  (Time - hEvsTimeOld->GetXaxis()->GetBinCenter(1))/(nBins-1);
      edge0 = hEvsTimeOld->GetXaxis()->GetBinCenter(1) - binwidth/2.;
      edge1 = Time + binwidth/2.;
    }
    hEvsTime[i] = new TH2F("temp","",nBins,edge0,edge1,
			hE1D[i]->GetNbinsX(),
			hE1D[i]->GetBinLowEdge(1),
			hE1D[i]->GetBinLowEdge(hE1D[i]->GetNbinsX()+1));
    
    for(Int_t ix=1;ix<hEvsTime[i]->GetNbinsX();ix++) {
      for(Int_t iy=1;iy<hEvsTime[i]->GetNbinsY();iy++) {
	hEvsTime[i]->SetBinContent(ix,iy,hEvsTimeOld->GetBinContent(ix,iy));
      }
    }  
    delete hEvsTimeOld;
  
    // Fill last bin with the newest values.
    for(Int_t iy=1;iy<=hE1D[i]->GetNbinsX();iy++) {
      hEvsTime[i]->SetBinContent(nBins,iy,hE1D[i]->GetBinContent(iy));
    }   

    if(i==0) 
      hEvsTime[i]->GetZaxis()->SetTitle("E_{z}/E_{0}");
    else if(i==1)
      hEvsTime[i]->GetZaxis()->SetTitle("E_{y}/E_{0}");
    else if(i==2)
      hEvsTime[i]->GetZaxis()->SetTitle("E_{x}/E_{0}");
  
    hEvsTime[i]->GetYaxis()->SetTitle("k_{p}#zeta");
    hEvsTime[i]->GetXaxis()->SetTitle("k_{p}z");
    hEvsTime[i]->GetZaxis()->CenterTitle();
    hEvsTime[i]->GetYaxis()->CenterTitle();
    hEvsTime[i]->GetXaxis()->CenterTitle();
    hEvsTime[i]->SetName(hName);

    // Change the range of z axis for the fields to be symmetric.
    Float_t Emax = hEvsTime[i]->GetMaximum();
    Float_t Emin = hEvsTime[i]->GetMinimum();
    if(Emax > TMath::Abs(Emin))
      Emin = -Emax;
    else
      Emax = -Emin;
    hEvsTime[i]->GetZaxis()->SetRangeUser(Emin,Emax); 
    
    hEvsTime[i]->Write(hName,TObject::kOverwrite);

    // ---

    gEcross[i] = new TGraph*[Ncross[i]];
    gEextr[i] = new TGraph*[Ncross[i]];
    char gName[24];
    Int_t ifail = 0;
    for(Int_t ic=0;ic<Ncross[i];ic++) {
      sprintf(gName,"gEcross_%i_%i",i,ic);     
      gEcross[i][ic] = (TGraph*) ifile->Get(gName);
      if(gEcross[i][ic]==NULL) {
	gEcross[i][ic] = new TGraph();
	gEcross[i][ic]->SetName(gName);
	nPoints = 0;
	// Some cosmetics at creation time:
	if(i==1) gEcross[i][ic]->SetLineStyle(2);
	else gEcross[i][ic]->SetLineStyle(1);
	gEcross[i][ic]->SetLineWidth(1);
	gEcross[i][ic]->SetLineColor(kGray+1);
	gEcross[i][ic]->SetMarkerStyle(20);
	gEcross[i][ic]->SetMarkerSize(0.4);
	gEcross[i][ic]->SetMarkerColor(kGray+1);	
	gEcross[i][ic]->GetYaxis()->SetTitle("k_{p}#zeta]");
	gEcross[i][ic]->GetXaxis()->SetTitle("k_{p}z");
      } else {
	nPoints = gEcross[i][ic]->GetN(); 
      }  
      
      // Check the new crossings respect the previous ones:
      // Double_t t,zeta;
      // if(nPoints>0) {
      // 	gEcross[i][ic]->GetPoint(nPoints-1,t,zeta);
      // 	if(fabs(zeta-Ecross[i][ic+ifail])>TMath::Pi()) {
      // 	  ic--;
      // 	  ifail++;
      // 	  continue;
      // 	}
      // }
      
      gEcross[i][ic]->Set(nPoints+1);
      gEcross[i][ic]->SetPoint(nPoints,Time,Ecross[i][ic+ifail]);
      gEcross[i][ic]->Write(gName,TObject::kOverwrite);
      
      // if(ic==Ncross[i]-1) continue;
      
      sprintf(gName,"gEextr_%i_%i",i,ic);     
      gEextr[i][ic] = (TGraph*) ifile->Get(gName);
      if(gEextr[i][ic]==NULL) {
	gEextr[i][ic] = new TGraph();
	gEextr[i][ic]->SetName(gName);
	nPoints = 0;
	// Some cosmetics at creation time:
	if(i==0) {
	  gEextr[i][ic]->SetLineWidth(3);
	  gEextr[i][ic]->SetLineColor(PGlobals::fieldLine);
	  gEextr[i][ic]->SetMarkerStyle(20);
	  gEextr[i][ic]->SetMarkerSize(0.4);
	  gEextr[i][ic]->SetMarkerColor(PGlobals::fieldLine);	
	  gEextr[i][ic]->GetYaxis()->SetTitle("E_{z}/E_{0}");
	  gEextr[i][ic]->GetXaxis()->SetTitle("k_{p}z");
	} else if(i==1) {
	  gEextr[i][ic]->SetLineWidth(1);
	  gEextr[i][ic]->SetLineColor(kGray+2);
	  gEextr[i][ic]->SetMarkerStyle(20);
	  gEextr[i][ic]->SetMarkerSize(0.4);
	  gEextr[i][ic]->SetMarkerColor(kGray+2);	
	  gEextr[i][ic]->GetYaxis()->SetTitle("E_{y}/E_{0}");
	  gEextr[i][ic]->GetXaxis()->SetTitle("k_{p}z");	  
	}
      } else {
	nPoints = gEextr[i][ic]->GetN(); 
      }  
      
      gEextr[i][ic]->Set(nPoints+1);
      gEextr[i][ic]->SetPoint(nPoints,Time,Eextr[i][ic]);
      gEextr[i][ic]->Write(gName,TObject::kOverwrite);
    }
  }

  
  ifile->Close();
  
}
int main (int argc, char** argv)
{
  

  TChain *chain = new TChain ("myanalysis/EcalAnalysisTree") ;
 
  // input files
  chain->Add("/tmp/malberti/SpikesCommissioning10_GOODCOLLV8.root");
  chain->Add("/tmp/malberti/SpikesCommissioning10_Apr1Skim_GOODCOLL-v1.root");
  int nEntries = chain->GetEntries () ;
  std::cout << "FOUND " << nEntries << " ENTRIES\n" ;    

  //ecalVariables variables
  unsigned int BX;
  unsigned int lumiId;
  unsigned int runId;
  unsigned int eventId;
  unsigned int eventNaiveId;

  int nEcalRecHits;
  float ecalRecHitType[1000];
  float ecalRecHitEnergy[1000];
  float ecalRecHitOutOfTimeEnergy[1000];
  float ecalRecHitIEta[1000];
  float ecalRecHitIPhi[1000];
  float ecalRecHitTime[1000];
  float ecalRecHitChi2[1000];
  float ecalRecHitOutOfTimeChi2[1000];
  int ecalRecHitRawId[1000];
  float ecalRecHitCoeff[1000];
  int ecalRecHitRecoFlag[1000];
  float ecalRecHitR9[1000];
  float ecalRecHitS4oS1[1000];
  float ecalRecHitIso03[1000][2];
  float ecalRecHitIso04[1000][2];
  int ecalDigis[1000][10];
  int ecalGainId[1000][10];
  float ecalRecHitMatrix[1000][5][5];
  float ecalRecHitMatrixFlag[1000][5][5];

  // L1 trigger variables
  int techL1Bit[64];
  int algoL1Bit[128];
  
  chain -> SetBranchAddress("BX",            &BX);
  chain -> SetBranchAddress("lumiId",        &lumiId);
  chain -> SetBranchAddress("runId",         &runId);
  chain -> SetBranchAddress("eventId",       &eventId);
  chain -> SetBranchAddress("eventNaiveId",  &eventNaiveId);

  chain -> SetBranchAddress("nEcalRecHits",             &nEcalRecHits);
  chain -> SetBranchAddress("ecalRecHitType",            ecalRecHitType);
  chain -> SetBranchAddress("ecalRecHitEnergy",          ecalRecHitEnergy);
  chain -> SetBranchAddress("ecalRecHitOutOfTimeEnergy", ecalRecHitOutOfTimeEnergy);
  chain -> SetBranchAddress("ecalRecHitIEta",            ecalRecHitIEta);
  chain -> SetBranchAddress("ecalRecHitIPhi",            ecalRecHitIPhi);
  chain -> SetBranchAddress("ecalRecHitTime",            ecalRecHitTime);
  chain -> SetBranchAddress("ecalRecHitChi2",            ecalRecHitChi2);
  chain -> SetBranchAddress("ecalRecHitOutOfTimeChi2",   ecalRecHitOutOfTimeChi2);
  chain -> SetBranchAddress("ecalRecHitRawId",           ecalRecHitRawId);
  chain -> SetBranchAddress("ecalRecHitCoeff",           ecalRecHitCoeff);
  chain -> SetBranchAddress("ecalRecHitRecoFlag",        ecalRecHitRecoFlag);
  chain -> SetBranchAddress("ecalRecHitR9",              ecalRecHitR9);
  chain -> SetBranchAddress("ecalRecHitS4oS1",           ecalRecHitS4oS1);
  chain -> SetBranchAddress("ecalRecHitIso03",           ecalRecHitIso03);
  chain -> SetBranchAddress("ecalRecHitIso04",           ecalRecHitIso04);
  chain -> SetBranchAddress("ecalDigis",                 ecalDigis);
  chain -> SetBranchAddress("ecalGainId",                ecalGainId);
  chain -> SetBranchAddress("ecalRecHitMatrix",          ecalRecHitMatrix);
  chain -> SetBranchAddress("ecalRecHitMatrixFlag",      ecalRecHitMatrixFlag);
  
  chain -> SetBranchAddress("techL1Bit",     techL1Bit);
  chain -> SetBranchAddress("algoL1Bit",     algoL1Bit);
 
  // output file
  std::string outputRootName = "spikeEfficiency_3GeV.root" ;
  
  // output histos

  TH1F *hRun = new TH1F("hRun","hRun",300,132400,132700);

  TH1F *hS1oS9  = new TH1F("hS1oS9","S1oS9 all Rec Hits",120,0,1.2); 
  hS1oS9 -> GetXaxis()-> SetTitle("S1/S9");

  TH1F *hTime[2];
  hTime[0] = new TH1F("hTimeSpike","hTimeSpike",800,-100,100);
  hTime[0]->SetLineColor(2);
  hTime[0]-> GetXaxis()-> SetTitle("t(ns)");
  hTime[1] = new TH1F("hTimeNormal","hTimeNormal",800,-100,100);
  hTime[1]->SetLineColor(3);
  hTime[1]-> GetXaxis()-> SetTitle("t(ns)");

  TH1F *hChi2[2];
  hChi2[0] = new TH1F("hChi2Spike","hChi2Spike",100,0,100);
  hChi2[0] -> SetLineColor(2);
  hChi2[0] -> GetXaxis()-> SetTitle("chi^{2}");
  hChi2[1] = new TH1F("hChi2Normal","hChi2Normal",100,0,100);
  hChi2[1] ->SetLineColor(3);
  hChi2[1] -> GetXaxis()-> SetTitle("chi^{2}");

  TH1F *hOutOfTimeChi2[2];
  hOutOfTimeChi2[0] = new TH1F("hOutOfTimeChi2Spike","hOutOfTimeChi2Spike",100,0,100);
  hOutOfTimeChi2[0] -> SetLineColor(2);
  hOutOfTimeChi2[0] -> GetXaxis()-> SetTitle("OutOfTime chi^{2}");
  hOutOfTimeChi2[1] = new TH1F("hOutOfTimeChi2Normal","hOutOfTimeChi2Normal",100,0,100);
  hOutOfTimeChi2[1] ->SetLineColor(3);
  hOutOfTimeChi2[1] -> GetXaxis()-> SetTitle("OutOfTime chi^{2}");

  int nSpikeTot  = 0 ;
  int nNormalTot = 0 ;
 
  int nSpikeTotEB[2]  = {0} ;
  int nNormalTotEB[2] = {0} ;
 
  int n = 1000;

  int nSpikeChi2[1000] = {0.};
  int nNormalChi2[1000]= {0};

  int nSpikeChi2OutOfTime[1000] = {0};
  int nNormalChi2OutOfTime[1000]= {0};

  int nSpikeTime[1000] = {0};
  int nNormalTime[1000]= {0};


  int nSpikeChi2EB[1000][2] ;
  int nNormalChi2EB[1000][2];

  int nSpikeChi2OutOfTimeEB[1000][2] ;
  int nNormalChi2OutOfTimeEB[1000][2];

  int nSpikeTimeEB[1000][2] ;
  int nNormalTimeEB[1000][2];

  for (int i = 0; i < n ; i++){
    for (int j = 0; j < 2; j++){
      nSpikeChi2EB[i][j] = 0;
      nSpikeChi2OutOfTimeEB[i][j] = 0;
      nSpikeTimeEB[i][j] = 0;
      nNormalChi2EB[i][j] = 0;
      nNormalChi2OutOfTimeEB[i][j] = 0;
      nNormalTimeEB[i][j] = 0;
    }
  }

  //for time resolution parametrization
  float N = 31.;
  float ADCtoGeV = 0.03865 ;
  float rmsNoise = 1.1;
  float cterm = 0.7;

  // loop over entries
  for (int entry = 0; entry < nEntries; ++entry)
    {
      chain->GetEntry (entry) ;
      if(entry%500000 == 0) std::cout << "event n. " << entry << std::endl;
      

      if ((techL1Bit[40]+techL1Bit[41])==0) continue; // c'e' gia'
             
      
      // select the good collisions runs + good lumi sections (no ecal time scans, etc...)
      bool goodrun = false;
      
      if (runId==132440 && lumiId >=86  && lumiId <= 138) goodrun = true;
      if (runId==132440 && lumiId >=141 && lumiId <= 401) goodrun = true;
   
      if (runId==132473 && lumiId >=1   && lumiId <= 29 ) goodrun = true;
      
      if (runId==132476 && lumiId >=23  && lumiId <= 28 ) goodrun = true;
      if (runId==132476 && lumiId >=54  && lumiId <= 57 ) goodrun = true;

      if (runId==132477 && lumiId >=34  && lumiId <= 35 ) goodrun = true;
      if (runId==132477 && lumiId >=63  && lumiId <= 64 ) goodrun = true;
      if (runId==132477 && lumiId >=90  && lumiId <= 93 ) goodrun = true;
      if (runId==132477 && lumiId >=118 && lumiId <= 121) goodrun = true;
      if (runId==132477 && lumiId >=148 && lumiId <= 149) goodrun = true;
      if (runId==132477 && lumiId >=176 && lumiId <= 179) goodrun = true;
      if (runId==132477 && lumiId >=225 && lumiId <= 236) goodrun = true;
      if (runId==132477 && lumiId >=368 && lumiId <= 384) goodrun = true;
      if (runId==132477 && lumiId >=517 && lumiId <= 520) goodrun = true;

      if (runId==132569 && lumiId >=222 && lumiId <= 224) goodrun = true;
      if (runId==132569 && lumiId >=310 && lumiId <= 310) goodrun = true;
      if (runId==132569 && lumiId >=411 && lumiId <= 419) goodrun = true;
      if (runId==132569 && lumiId >=529 && lumiId <= 582) goodrun = true;

      if (runId==132596 && lumiId >=383 && lumiId <= 383) goodrun = true;
      if (runId==132596 && lumiId >=447 && lumiId <= 453) goodrun = true;

      if (runId==132598 && lumiId >=80  && lumiId <= 82 ) goodrun = true;
      if (runId==132598 && lumiId >=174 && lumiId <= 188) goodrun = true;

      if (runId==132599 && lumiId >=1   && lumiId <= 74 ) goodrun = true;

      if (runId==132601 && lumiId >=261 && lumiId <= 1131)goodrun = true;

      if (runId==132602 && lumiId >=1   && lumiId <= 83)  goodrun = true;

      if (runId==132605 && lumiId >=446 && lumiId <= 622) goodrun = true;
      if (runId==132605 && lumiId >=624 && lumiId <= 829) goodrun = true;
      if (runId==132605 && lumiId >=831 && lumiId <= 968) goodrun = true;

      if (runId==132606 && lumiId >=1   && lumiId <= 37 ) goodrun = true;
      
      if (!goodrun) continue;      



      for (int ihit =0 ; ihit < nEcalRecHits; ihit++){
	  
      if (ecalRecHitEnergy[ihit] < 3) continue;
      
      // check gain switch
      bool gainSwitch = false;
      for (int isample = 0; isample < 10 ; isample++){
        if ( (isample > 0 && ecalGainId[ihit][isample]!= ecalGainId[ihit][isample-1]) ||
             ecalGainId[ihit][isample] !=1 ) {
          gainSwitch = true;
          break;
        }
      }

      if (gainSwitch) continue;

      hRun->Fill(runId);


      // c'e' un canale con problemi?
      if ( ecalRecHitIEta[ihit]==58 && ecalRecHitIPhi[ihit]==97 && runId==132569) continue; 


      if (ecalRecHitR9[ihit] > 0.95 ) {
	nSpikeTot++;
	if (ecalRecHitIEta[ihit] < 0)  nSpikeTotEB[0]++;
	if (ecalRecHitIEta[ihit] > 0)  nSpikeTotEB[1]++;
	hTime[0]->Fill(ecalRecHitTime[ihit]);
      }

      if (ecalRecHitR9[ihit] < 0.80 ) {
	nNormalTot++;
	if (ecalRecHitIEta[ihit] < 0)  nNormalTotEB[0]++;
	if (ecalRecHitIEta[ihit] > 0)  nNormalTotEB[1]++;
	hTime[1]->Fill(ecalRecHitTime[ihit]);
	//if (ecalRecHitTime[ihit]> 8) std::cout << ecalRecHitIEta[ihit] << "  " << ecalRecHitIPhi[ihit] << "  " << runId<< std::endl;
	
      }


      for (int i = 0 ; i < n ; i++){

	float chi2cut = (i+1) * 65./n ;

	// for the time cut , use parametrization by Giovanni et al.
	float A = ecalRecHitEnergy[ihit]/ADCtoGeV; 
	float sigmat = sqrt(pow(N/(A/rmsNoise),2) + cterm*cterm );
	float timecut = (i+1)*20./n;

	if ( ecalRecHitR9[ihit] > 0.95 ){

	  if (ecalRecHitChi2[ihit] < chi2cut) nSpikeChi2[i]++;
	  if (ecalRecHitChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] < 0) nSpikeChi2EB[i][0]++;
	  if (ecalRecHitChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] > 0) nSpikeChi2EB[i][1]++;
	
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut) nSpikeChi2OutOfTime[i]++;
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] < 0) nSpikeChi2OutOfTimeEB[i][0]++;
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] > 0) nSpikeChi2OutOfTimeEB[i][1]++;
	  
	  if (fabs(ecalRecHitTime[ihit]/sigmat) < timecut) nSpikeTime[i]++;
	  if (fabs(ecalRecHitTime[ihit]/sigmat ) < timecut && ecalRecHitIEta[ihit] < 0) nSpikeTimeEB[i][0]++;
	  if (fabs(ecalRecHitTime[ihit]/sigmat ) < timecut && ecalRecHitIEta[ihit] > 0) nSpikeTimeEB[i][1]++;

	}

	if ( ecalRecHitR9[ihit] < 0.80 ){
	  


	  if (ecalRecHitChi2[ihit] < chi2cut) nNormalChi2[i]++;
	  if (ecalRecHitChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] < 0) nNormalChi2EB[i][0]++;
	  if (ecalRecHitChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] > 0) nNormalChi2EB[i][1]++;
	
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut) nNormalChi2OutOfTime[i]++;
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] < 0) nNormalChi2OutOfTimeEB[i][0]++;
	  if (ecalRecHitOutOfTimeChi2[ihit] < chi2cut  && ecalRecHitIEta[ihit] > 0) nNormalChi2OutOfTimeEB[i][1]++;
	  
	  if (fabs(ecalRecHitTime[ihit]/sigmat ) < timecut) nNormalTime[i]++;
	  if (fabs(ecalRecHitTime[ihit]/sigmat ) < timecut && ecalRecHitIEta[ihit] < 0) nNormalTimeEB[i][0]++;
	  if (fabs(ecalRecHitTime[ihit]/sigmat ) < timecut && ecalRecHitIEta[ihit] > 0) nNormalTimeEB[i][1]++;


	  
	}
      }


      }
    } // loop over entries

  TGraph *gTime = new TGraph();
  gTime->SetMarkerStyle(21);
  gTime->SetMarkerSize(0.6);
  gTime->SetMarkerColor(2);

  TGraph *gChi2 = new TGraph();
  gChi2->SetMarkerStyle(21);
  gChi2->SetMarkerSize(0.6);
  gChi2->SetMarkerColor(3);

  TGraph *gOutOfTimeChi2 = new TGraph();
  gOutOfTimeChi2->SetMarkerStyle(21);
  gOutOfTimeChi2->SetMarkerSize(0.6);
  gOutOfTimeChi2->SetMarkerColor(4);


  TGraph *gTimeEBP = new TGraph();
  gTimeEBP->SetMarkerStyle(20);
  gTimeEBP->SetMarkerSize(0.7);
  gTimeEBP->SetMarkerColor(2);

  TGraph *gChi2EBP = new TGraph();
  gChi2EBP->SetMarkerStyle(20);
  gChi2EBP->SetMarkerSize(0.7);
  gChi2EBP->SetMarkerColor(3);

  TGraph *gOutOfTimeChi2EBP = new TGraph();
  gOutOfTimeChi2EBP->SetMarkerStyle(20);
  gOutOfTimeChi2EBP->SetMarkerSize(0.7);
  gOutOfTimeChi2EBP->SetMarkerColor(4);
 
  TGraph *gTimeEBM = new TGraph();
  gTimeEBM->SetMarkerStyle(24);
  gTimeEBM->SetMarkerSize(0.7);
  gTimeEBM->SetMarkerColor(2);

  TGraph *gChi2EBM = new TGraph();
  gChi2EBM->SetMarkerStyle(24);
  gChi2EBM->SetMarkerSize(0.7);
  gChi2EBM->SetMarkerColor(3);

  TGraph *gOutOfTimeChi2EBM = new TGraph();
  gOutOfTimeChi2EBM->SetMarkerStyle(24);
  gOutOfTimeChi2EBM->SetMarkerSize(0.7);
  gOutOfTimeChi2EBM->SetMarkerColor(4);


  float effS, effN;

  for (int i = 0; i < n ; i++){

    effN = (float)nNormalTime[i]/(float)nNormalTot;
    effS = (float)nSpikeTime[i]/(float)nSpikeTot;
    gTime->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2[i]/(float)nNormalTot;
    effS = (float)nSpikeChi2[i]/(float)nSpikeTot;
    gChi2->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2OutOfTime[i]/(float)nNormalTot;
    effS = (float)nSpikeChi2OutOfTime[i]/(float)nSpikeTot;
    gOutOfTimeChi2->SetPoint(i,effS,effN);

    //EB-
    effN = (float)nNormalTimeEB[i][0]/(float)nNormalTotEB[0];
    effS = (float)nSpikeTimeEB[i][0]/(float)nSpikeTotEB[0];
    gTimeEBM->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2EB[i][0]/(float)nNormalTotEB[0];
    effS = (float)nSpikeChi2EB[i][0]/(float)nSpikeTotEB[0];
    gChi2EBM->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2OutOfTimeEB[i][0]/(float)nNormalTotEB[0];
    effS = (float)nSpikeChi2OutOfTimeEB[i][0]/(float)nSpikeTotEB[0];
    gOutOfTimeChi2EBM->SetPoint(i,effS,effN);

    //EB+
    effN = (float)nNormalTimeEB[i][1]/(float)nNormalTotEB[1];
    effS = (float)nSpikeTimeEB[i][1]/(float)nSpikeTotEB[1];
    gTimeEBP->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2EB[i][1]/(float)nNormalTotEB[1];
    effS = (float)nSpikeChi2EB[i][1]/(float)nSpikeTotEB[1];
    gChi2EBP->SetPoint(i,effS,effN);

    effN = (float)nNormalChi2OutOfTimeEB[i][1]/(float)nNormalTotEB[1];
    effS = (float)nSpikeChi2OutOfTimeEB[i][1]/(float)nSpikeTotEB[1];
    gOutOfTimeChi2EBP->SetPoint(i,effS,effN);

  }




  TFile saving (outputRootName.c_str (),"recreate") ;
  saving.cd () ;  
  
  // saving distributions
  hRun->Write();

  gTime->Write("g_Time");
  gChi2->Write("g_Chi2");
  gOutOfTimeChi2->Write("g_OutOfTimeChi2");

  gTimeEBP->Write("g_Time_EBP");
  gChi2EBP->Write("g_Chi2_EBP");
  gOutOfTimeChi2EBP->Write("g_OutOfTimeChi2_EBP");

  gTimeEBM->Write("g_Time_EBM");
  gChi2EBM->Write("g_Chi2_EBM");
  gOutOfTimeChi2EBM->Write("g_OutOfTimeChi2_EBM");


  hTime[0]->Write();
  hTime[1]->Write();

  saving.Close () ;
 
  return 0 ;
}
Example #13
0
int main(int argc, char **argv) {
    char *ttbarFileName = NULL;
    char *wp3jetsFileName = NULL;
    char *wp4jetsFileName = NULL;
    char *smwwFileName = NULL;
    char *opsFileName[10];
    int nOpsFile = 0;
    char *outputFileName = NULL;
    int c;
    while(1) {
        int option_index = 0;
        static struct option long_options[] = {
            {"ttbar", required_argument, 0, 'a'},
            {"wp3jets", required_argument, 0, 'b'},
            {"wp4jets", required_argument, 0, 'c'},
            {"smww", required_argument, 0, 'd'},
            {"opsww", required_argument, 0, 'e'},
            {"output", required_argument, 0, 'f'}
        };
        c = getopt_long(argc, argv, "abcdef:", long_options, &option_index);
        if (c==-1)
            break;
        switch(c) {
            case 'a':
                ttbarFileName = optarg;
                break;
            case 'b':
                wp3jetsFileName = optarg; 
                break;
            case 'c':
                wp4jetsFileName = optarg;
                break;
            case 'd':
                smwwFileName = optarg;
                break;
            case 'e':
                opsFileName[nOpsFile] = optarg;
                nOpsFile++;
                break;
            case 'f':
                outputFileName = optarg;
                break;
        }
    }
    /*
    double cww[4] = {4*pow(10, -6), 4.6*pow(10, -6), 5.33*pow(10, -6), 6.25*pow(10, -6)};
    double lambda[4];
    for (int i = 0; i < 4; i++) {
        lambda[i] = 1.0/sqrt(cww[i]);
    }
    */
    double lambda[4] = {500, 466, 433, 400};

    TFile *outputFile = new TFile(outputFileName, "RECREATE");
    outputFile->Close();
    double significance[10];
    for (int i = 0; i < nOpsFile; i++) {
        std::cerr << "using signal file " << opsFileName[i] << "\n";
        significance[i] = RunHypoTest(smwwFileName, ttbarFileName, wp3jetsFileName, wp4jetsFileName, opsFileName[i], outputFileName, lambda[i]);
        std::cerr << "Significance = " << significance[i] << "\n";
    }
    TGraph *graph = new TGraph(nOpsFile, lambda, significance);
    graph->SetFillColor(kRed);
    graph->SetTitle("");
    graph->GetYaxis()->SetTitle("Significance (#sigma)");
    graph->GetYaxis()->CenterTitle();
    graph->GetXaxis()->SetTitle("#Lambda (GeV)");
    graph->GetXaxis()->CenterTitle();
    TFile *outputFile2 = new TFile(outputFileName, "UPDATE");
    TCanvas *canvas = new TCanvas();
    graph->Draw("A*");
    canvas->Write();
    graph->Write();
    std::cerr << "---------------------------------------------------\n";
    for (int i = 0; i < nOpsFile; i++) {
        std::cerr << "Significance = " << significance[i] << "\n";
    }
    std::cerr << "n files: " << nOpsFile << "\n";
    outputFile2->Close();
}
int main(int argc, char *argv[])
{
  setenv("TZ","UTC",1);
  tzset();
  gROOT->SetStyle("Plain");

  static struct RecEvent RecEvent30;
  static struct RecEvent RecEvent17;
  static struct channel_profiles channel_profiles30;
  static struct channel_profiles channel_profiles17;
  static struct h3 h330;
  static struct h3 h317;

  //get pointer to data
  TChain *TRecEvent30 = new TChain ("TRecEvent");
  CreateTRecEventChain30(TRecEvent30);
  cout << "TRecEvent entries = " << TRecEvent30->GetEntries() << endl;
  CreateTRecEvent(TRecEvent30, &RecEvent30);
  CreateTGrande(TRecEvent30, &h330, false);
  
  TChain *TRecEvent17 = new TChain ("TRecEvent");
  CreateTRecEventChain17(TRecEvent17);
  cout << "TRecEvent entries = " << TRecEvent17->GetEntries() << endl;
  CreateTRecEvent(TRecEvent17, &RecEvent17);
  CreateTGrande(TRecEvent17, &h317, false);

  char cut[2048];
  sprintf(cut, "Eg>0");
  sprintf(cut, "Eg>8.5 && abs(Zenith1Third)+2*Zenith1Third_err>Zeg && abs(Zenith1Third)-2*Zenith1Third_err<Zeg && LDFSlope<0");
//  sprintf(cut, "Eg>6 && abs(Zenith1Third)+2*Zenith1Third_err>Zeg && abs(Zenith1Third)-2*Zenith1Third_err<Zeg && event_id!=2768428"); //slope!!
  cout << "cut = " << cut << endl;
  
  
  TRecEvent30->Draw(">>ListRecEvent30",cut);
  TEventList *EventList30 = (TEventList*) gDirectory->Get("ListRecEvent30");
  if(EventList30==NULL) cerr << "error - EventList30 has null entries" << endl;
  TRecEvent30->SetEventList(EventList30);
  cout << "30: events to analyse = " <<  EventList30->GetN() << endl;
  
  TRecEvent17->Draw(">>ListRecEvent17",cut);
  TEventList *EventList17 = (TEventList*) gDirectory->Get("ListRecEvent17");
  if(EventList17==NULL) cerr << "error - EventList17 has null entries" << endl;
  TRecEvent17->SetEventList(EventList17);
  cout << "17: events to analyse = " <<  EventList17->GetN() << endl;
  
  TChain *Tchannel_profile30 = new TChain("Tchannel_profile");
  int NoChannels30;
  Tchannel_profile30->AddFile("~/analysis/AnaFlag/AF_D30_run21-49_v28.root");
  CreateTchannel_profiles(Tchannel_profile30, &channel_profiles30);
  NoChannels30 = Tchannel_profile30->GetEntries();
  cout << "Tchannel_profile30 entries = " << NoChannels30 << endl;

  TChain *Tchannel_profile17 = new TChain("Tchannel_profile");
  int NoChannels17;
  Tchannel_profile17->AddFile("~/analysis/AnaFlag/AF_D17_run12-60_v28.root");
  CreateTchannel_profiles(Tchannel_profile17, &channel_profiles17);
  NoChannels17 = Tchannel_profile17->GetEntries();
  cout << "Tchannel_profile17 entries = " << NoChannels17 << endl;
  
  
  gEntries = 0;
  float errScale = 1;
  float errScale2 = 0.14; //0.0737; //0.048*1;
  
  bool bNS = false, bEW = false;
  //fill data pointers
  for(int i=0; i<EventList30->GetN(); i++){
    TRecEvent30->GetEntry(EventList30->GetEntry(i));
    bNS = false;
    bEW = false;
    for(int k=0; k<RecEvent30.DetCh; k++){
      for(int j=0; j<NoChannels30; j++){
        Tchannel_profile30->GetEntry(j);
	if((int)channel_profiles30.ch_id == RecEvent30.channel_id[k]){
	  if( strncmp(channel_profiles30.polarisation,"East",4) == 0 ){
	    bEW = true;
	    gFieldStrengthEW[gEntries]    = RecEvent30.FieldStrengthChannel[k];
	    gFieldStrengthEWErr[gEntries] = RecEvent30.ChannelErrBackground[k]*errScale + RecEvent30.FieldStrengthChannel[k]*errScale2;
	    gFieldStrengthAnt[gEntries]   = RecEvent30.FieldStrengthAntenna[k];
	    gDistanceShowerAxis[gEntries] = RecEvent30.DistanceShowerAxis[k];
	  }
	  else{
	    bNS = true;
	    gFieldStrengthNS[gEntries]    = RecEvent30.FieldStrengthChannel[k];
	    gFieldStrengthNSErr[gEntries] = RecEvent30.ChannelErrBackground[k]*errScale + RecEvent30.FieldStrengthChannel[k]*errScale2;
	    gFieldStrengthAnt[gEntries]   = RecEvent30.FieldStrengthAntenna[k];
	    gDistanceShowerAxis[gEntries] = RecEvent30.DistanceShowerAxis[k];
	  }
	  if(bNS && bEW){
	    gAzimuth[gEntries] = h330.Azg;
            while(gAzimuth[gEntries]>360) gAzimuth[gEntries] -= 360;
	    gBAngle[gEntries] = RecEvent30.BAngle;
            while(gBAngle[gEntries]>360) gBAngle[gEntries] -= 360;
	    gZenith[gEntries] = h330.Zeg;	    
	    gEg[gEntries] = h330.Eg;
	    
	   if(0){
              cout << gAzimuth[gEntries] << " -- " << gBAngle[gEntries] << endl;
              cout << channel_profiles30.polarisation << endl;
              cout << gFieldStrengthNS[gEntries] << " -- " << gFieldStrengthEW[gEntries] <<  " ----- " << gFieldStrengthNS[gEntries]/gFieldStrengthEW[gEntries] << endl;
	      cout << gFieldStrengthAnt[gEntries] << endl;
              cout << h330.Zeg << " -- " << RecEvent30.Zenith1Third << " -- " << RecEvent30.Zenith1Third_err << endl;
	      cout << RecEvent30.event_id << endl;
              cout << endl;
            }

	    gEntries++;
	    bNS = false;
	    bEW = false;
	  }
	  break;
	}
      }
    }
   }

  if(true)
  for(int i=0; i<EventList17->GetN(); i++){
    TRecEvent17->GetEntry(EventList17->GetEntry(i));
    bNS = false;
    bEW = false;
    for(int k=0; k<RecEvent17.DetCh; k++){
      for(int j=0; j<NoChannels17; j++){
        Tchannel_profile17->GetEntry(j);
	if((int)channel_profiles17.ch_id == RecEvent17.channel_id[k]){
	  if( strncmp(channel_profiles17.polarisation,"East",4) == 0 ){
	    bEW = true;
	    gFieldStrengthEW[gEntries]    = RecEvent17.FieldStrengthChannel[k];
	    gFieldStrengthEWErr[gEntries] = RecEvent17.ChannelErrBackground[k]*errScale + RecEvent17.FieldStrengthChannel[k]*errScale2;
	    gFieldStrengthAnt[gEntries]   = RecEvent17.FieldStrengthAntenna[k];
	    gDistanceShowerAxis[gEntries] = RecEvent17.DistanceShowerAxis[k];
	  }
	  else{
	    bNS = true;
	    gFieldStrengthNS[gEntries]    = RecEvent17.FieldStrengthChannel[k];
	    gFieldStrengthNSErr[gEntries] = RecEvent17.ChannelErrBackground[k]*errScale + RecEvent17.FieldStrengthChannel[k]*errScale2;
	    gFieldStrengthAnt[gEntries]   = RecEvent17.FieldStrengthAntenna[k];
	    gDistanceShowerAxis[gEntries] = RecEvent17.DistanceShowerAxis[k];
	  }
	  if(bNS && bEW){
	    gAzimuth[gEntries] = h317.Azg;
            while(gAzimuth[gEntries]>360) gAzimuth[gEntries] -= 360;
	    gBAngle[gEntries] = RecEvent17.BAngle;
            while(gBAngle[gEntries]>360) gBAngle[gEntries] -= 360;
    	    gZenith[gEntries] = h317.Zeg;
	    gEg[gEntries] = h317.Eg;

	    
	    
	   if(0){
	      cout << "index = " << i << endl;
              cout << gAzimuth[gEntries] << " -- " << gBAngle[gEntries] << endl;
              cout << channel_profiles17.polarisation << endl;
              cout << gFieldStrengthNS[gEntries] << " -- " << gFieldStrengthEW[gEntries] <<  " ----- " << gFieldStrengthNS[gEntries]/gFieldStrengthEW[gEntries] << endl;
	      cout << gFieldStrengthAnt[gEntries] << endl;
              cout << h317.Zeg << " -- " << RecEvent17.Zenith1Third << " -- " << RecEvent17.Zenith1Third_err << endl;
              cout << endl;
            }

	    gEntries++;
	    bNS = false;
	    bEW = false;
	  }
	  break;
	}
      }
    }
   }

   cout << gEntries << endl;
   if(NoChannels30+NoChannels17 > gMaxCh || gEntries > gMaxEvents) {
     cout << "constants limit reached" << endl;
     exit(1);
   }
 
   TMinuit *gMinuit = new TMinuit(10);
   gMinuit->SetPrintLevel(-1);
   Double_t arglist[10];
   Int_t ierflg = 0;
   int NoPar = 6;
   
   bool AntFit = false;
   
   if(AntFit){
   // Antenna Fit Settings
   //++++++++++++++++++++++
   cout << "Antenna Fit" << endl;
   cout << "+++++++++++" << endl;
   
   gMinuit->SetFCN(FcnParFS);
   
// no effect
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);

  arglist[0] = 1;
  gMinuit->mnexcm("SET STRATEGY", arglist, 1, ierflg);
  

   gMinuit->mnparm(0, "scale",  1., 0.01, 0, 0, ierflg);
   gMinuit->mnparm(1, "r0",    400., 1, 0, 0, ierflg);
   gMinuit->mnparm(2, "Epower",  1., 0.01, 0.8, 1.2, ierflg);
//   gMinuit->mnparm(2, "Epower",  1., 0.1, 0, 0, ierflg);
   gMinuit->mnparm(3, "Zphase",  0., 0.1, -TMath::Pi()*2, TMath::Pi()*2, ierflg);
   gMinuit->mnparm(4, "Bphase",  0., 0.1, -TMath::Pi()*2, TMath::Pi()*2, ierflg);
   gMinuit->mnparm(5, "offset",  2., 0.1, 0, 0, ierflg);
//   gMinuit->FixParameter(0);
//   gMinuit->FixParameter(2);

   gMinuit->FixParameter(3);
   gMinuit->FixParameter(4);
   gMinuit->FixParameter(5);
   }
   else{
   // Channel Fit Settings
   //+++++++++++++++++++++
   cout << "Channel Fit" << endl;
   cout << "+++++++++++" << endl;

   gMinuit->SetFCN(FcnParFSChannel);
   
// no effect
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);

  arglist[0] = 1;
  gMinuit->mnexcm("SET STRATEGY", arglist, 1, ierflg);
  
   gMinuit->mnparm(0, "scale",  1., 0.01, 0.1, 100, ierflg);
   gMinuit->mnparm(1, "r0",    400., 1, 100, 1000, ierflg);
   gMinuit->mnparm(2, "Epower",  1., 0.01, 0.8, 1.2, ierflg);
//   gMinuit->mnparm(2, "Epower",  1., 0.01, 0, 0, ierflg);
   gMinuit->mnparm(3, "Zphase",  0., 0.1, -TMath::Pi()*2, TMath::Pi()*2, ierflg);
   gMinuit->mnparm(4, "Bphase",  0., 0.1, -TMath::Pi()*2, TMath::Pi()*2, ierflg);
   gMinuit->mnparm(5, "offset",  2., 0.1, 0, 0, ierflg);
//   gMinuit->FixParameter(0);
//   gMinuit->FixParameter(2);

   gMinuit->FixParameter(3);
   gMinuit->FixParameter(4);
   gMinuit->FixParameter(5);
   }

   
   //scan par space
   for(int i=0; i<1; i++){
     gMinuit->mnexcm("SCA", arglist, 0, ierflg);
   }
   
// Now ready for minimization step
   arglist[0] = 50000; // steps of iteration
   arglist[1] = 1.; // tolerance
   gMinuit->mnexcm("MIGRAD", arglist ,2,ierflg); //MIGRAD
   cout << " MINIMIZE flag is " << ierflg << endl;
   if(ierflg!=0){
     cout << "+++++++++++++++++++++" << endl;
     cout << "+ ups.. check again +" << endl;
     cout << "+++++++++++++++++++++" << endl;
   }

   // MIGRAD: error optimiser
   if(ierflg==0 && 0){
     arglist[0] = 500000;
     gMinuit->mnexcm("MIGRAD", arglist ,1,ierflg);
     cout << " MIGRAD flag is " << ierflg << endl;
     if(ierflg!=0){
       cout << "+++++++++++++++++++++" << endl;
       cout << "+ ups.. check again +" << endl;
       cout << "+++++++++++++++++++++" << endl;
     }
   }

   // Minos: error optimiser
   if(ierflg==0 && 0){
     arglist[0] = 500000;
     gMinuit->mnexcm("MINOS", arglist ,1,ierflg);
     cout << " MINOS flag is " << ierflg << endl;
     if(ierflg!=0){
       cout << "+++++++++++++++++++++" << endl;
       cout << "+ ups.. check again +" << endl;
       cout << "+++++++++++++++++++++" << endl;
     }
   }

// Print results
   Double_t amin,edm,errdef;
   Int_t nvpar,nparx,icstat;
   gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
   gMinuit->mnprin(3,amin);
 
   cout << "prob = " << TMath::Prob(amin,gEntriesUsed-gMinuit->GetNumFreePars())*100 << " %" << endl;
   cout << "ndf = " << gEntriesUsed-gMinuit->GetNumFreePars() << endl;

   
   cout << "output" << endl;
//   gMinuit->mnexcm("SHO COV", arglist ,0,ierflg);
//   gMinuit->mnexcm("SHO COR", arglist ,0,ierflg);
//   gMinuit->mnexcm("SHO EIG", arglist ,0,ierflg);
   
   //get fit parameters
   double par[15], epar;
   for(int i=0; i<NoPar; i++){
     gMinuit->GetParameter(i,par[i],epar);
   }

   
   TFile *output = new TFile("FitParFieldStrength_out.root","RECREATE");

   int tcount = 0;
   float tmpBAngle, tmpZenith;
   float r0x[gMaxEvents], r0y[gMaxEvents];
   float bx[gMaxEvents], by[gMaxEvents];
   
   for(int i=0; i<gEntries; i++){
     if(gFieldStrengthAnt[i]>0 && gFieldStrengthNS[i]>0 && gFieldStrengthEW[i]>0){
       tmpBAngle = gBAngle[i] * TMath::Pi() / 180.;
       tmpZenith = gZenith[i] * TMath::Pi() / 180.;
       
       r0x[tcount] = -gDistanceShowerAxis[i];
       r0y[tcount] = (log( (gFieldStrengthAnt[i]/gEffBand) / ( par[0]*cos(tmpZenith+par[3])*(par[5]+sin(tmpBAngle+par[4]))*powf(10,par[2]*(gEg[i]-8))))  );
       //if(r0y[tcount] < -4 && r0x[tcount] > 50) cout << "E = " << gEg[i] << " --  i = " << i << endl;
       
       bx[tcount] = tmpBAngle;
       by[tcount] = gFieldStrengthAnt[i]/gEffBand / (par[0]*cos(tmpZenith+par[3])*exp(-gDistanceShowerAxis[i]/par[1])*powf(10,par[2]*(gEg[i]-8))) - par[5];
//       if(by[tcount]>1.5) cout << " E = " << gEg[i] << " -- i = " << i << endl;

       tcount++;
     }
   }
   TCanvas *can1 = new TCanvas("can1");
   can1->Divide(2,2);

   TGraph *gr0 = new TGraph(tcount,r0x, r0y);
   gr0->SetName("gr0");
   gr0->SetMarkerStyle(20);
   gr0->SetTitle("lateral distribution");

   TGraph *gb = new TGraph(tcount,bx, by);
   gb->SetName("gb");
   gb->SetMarkerStyle(20);
   gb->SetTitle("geomagnetic angle");
 
   can1->cd(1);
   gr0->Draw("ap");
   
   can1->cd(2);
   gb->Draw("ap");
 
 
   gr0->Write();
   gb->Write();
   can1->Write();
   output->Close();
   
   
   

}
int main(){
  
  system("mkdir -p plots");
  RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
  TFile *bkgFile = TFile::Open("comb_svn/hgg.inputbkgdata_8TeV_MVA.root");
  TFile *sigFile = TFile::Open("comb_svn/hgg.inputsig_8TeV_nosplitVH_MVA.root");
  RooWorkspace *bkgWS = (RooWorkspace*)bkgFile->Get("cms_hgg_workspace");
  RooWorkspace *sigWS = (RooWorkspace*)sigFile->Get("wsig_8TeV");

  RooRealVar *mass = (RooRealVar*)bkgWS->var("CMS_hgg_mass");
  RooRealVar *mu = new RooRealVar("mu","mu",-5.,5.);

  mass->setBins(320);
  cout << mass->getBins() << endl;
  RooDataSet *dataAll;
  
  int firstCat=1;
  int lastCat=1;
  float mu_low=-1.;
  float mu_high=3.;
  float mu_step=0.01;

  vector<pair<double,TGraph*> > minNlltrack;

  for (int cat=firstCat; cat<=lastCat; cat++){
    RooDataSet *data = (RooDataSet*)bkgWS->data(Form("data_mass_cat%d",cat));
    if (cat==firstCat) dataAll = (RooDataSet*)data->Clone("data_mass_all");
    else dataAll->append(*data);
    RooDataHist *dataBinned = new RooDataHist(Form("roohist_data_mass_cat%d",cat),Form("roohist_data_mass_cat%d",cat),RooArgSet(*mass),*data);
    RooDataSet *sigMC = (RooDataSet*)sigWS->data(Form("sig_mass_m125_cat%d",cat));

    if (!dataBinned || !sigMC){
      cerr << "ERROR -- one of data or signal is NULL" << endl;
      exit(1);
    }
    
    // Construct PDFs for this category using PdfModelBuilder
    PdfModelBuilder modelBuilder;
    modelBuilder.setObsVar(mass);
    modelBuilder.setSignalModifier(mu);
    // For Standard Analysis
    //if (cat>=0 && cat<=3) modelBuilder.addBkgPdf("Bernstein",5,Form("pol5_cat%d",cat));
    //if (cat>=4 && cat<=5) modelBuilder.addBkgPdf("Bernstein",4,Form("pol4_cat%d",cat));
    //if (cat>=6 && cat<=8) modelBuilder.addBkgPdf("Bernstein",3,Form("pol3_cat%d",cat));
    // To Profile Multiple PDFs
    if (cat==0 || cat==1 || cat==2 || cat==3){
      modelBuilder.addBkgPdf("Bernstein",4,Form("pol4_cat%d",cat));
      modelBuilder.addBkgPdf("Bernstein",5,Form("pol5_cat%d",cat));
      modelBuilder.addBkgPdf("Bernstein",6,Form("pol6_cat%d",cat));
      /*
      modelBuilder.addBkgPdf("PowerLaw",1,Form("pow1_cat%d",cat));
      modelBuilder.addBkgPdf("PowerLaw",3,Form("pow3_cat%d",cat));
      modelBuilder.addBkgPdf("PowerLaw",5,Form("pow5_cat%d",cat));
      modelBuilder.addBkgPdf("Exponential",1,Form("exp1_cat%d",cat));
      modelBuilder.addBkgPdf("Exponential",3,Form("exp3_cat%d",cat));
      modelBuilder.addBkgPdf("Exponential",5,Form("exp5_cat%d",cat));
      modelBuilder.addBkgPdf("Laurent",1,Form("lau1_cat%d",cat));
      modelBuilder.addBkgPdf("Laurent",3,Form("lau3_cat%d",cat));
      modelBuilder.addBkgPdf("Laurent",5,Form("lau5_cat%d",cat));
      */
    }
    if (cat==4 || cat==5 || cat==6 || cat==7 || cat==8) {
      modelBuilder.addBkgPdf("Bernstein",3,Form("pol3_cat%d",cat));
      modelBuilder.addBkgPdf("Bernstein",4,Form("pol4_cat%d",cat));
      /*
      modelBuilder.addBkgPdf("PowerLaw",1,Form("pow1_cat%d",cat));
      modelBuilder.addBkgPdf("PowerLaw",3,Form("pow3_cat%d",cat));
      modelBuilder.addBkgPdf("Exponential",1,Form("exp1_cat%d",cat));
      modelBuilder.addBkgPdf("Exponential",3,Form("exp3_cat%d",cat));
      modelBuilder.addBkgPdf("Laurent",1,Form("lau1_cat%d",cat));
      modelBuilder.addBkgPdf("Laurent",3,Form("lau3_cat%d",cat));
      */
    }
    map<string,RooAbsPdf*> bkgPdfs = modelBuilder.getBkgPdfs();
    modelBuilder.setSignalPdfFromMC(sigMC);
    modelBuilder.makeSBPdfs();
    map<string,RooAbsPdf*> sbPdfs = modelBuilder.getSBPdfs();

    modelBuilder.fitToData(dataBinned,true,true);
    modelBuilder.fitToData(dataBinned,false,true);

    modelBuilder.throwToy(Form("cat%d_toy0",cat),dataBinned->sumEntries(),true,true);

    // Profile this category using ProfileMultiplePdfs
    ProfileMultiplePdfs profiler;
    for (map<string,RooAbsPdf*>::iterator pdf=sbPdfs.begin(); pdf!=sbPdfs.end(); pdf++) {
      string bkgOnlyName = pdf->first.substr(pdf->first.find("sb_")+3,string::npos);
      if (bkgPdfs.find(bkgOnlyName)==bkgPdfs.end()){
        cerr << "ERROR -- couldn't find bkg only pdf " << bkgOnlyName << " for SB pdf " << pdf->first << endl;
        pdf->second->fitTo(*dataBinned);
        exit(1);
      }
      int nParams = bkgPdfs[bkgOnlyName]->getVariables()->getSize()-1;
      profiler.addPdf(pdf->second,2*nParams);
      //profiler.addPdf(pdf->second);
      cout << pdf->second->GetName() << " nParams=" << pdf->second->getVariables()->getSize() << " nBkgParams=" << nParams << endl;
    }
    profiler.printPdfs();
    //cout << "Continue?" << endl;
    //string bus; cin >> bus;
    profiler.plotNominalFits(dataBinned,mass,80,Form("cat%d",cat));
    pair<double,map<string,TGraph*> > minNlls = profiler.profileLikelihood(dataBinned,mass,mu,mu_low,mu_high,mu_step);
    pair<double,map<string,TGraph*> > correctedNlls = profiler.computeEnvelope(minNlls,Form("cat%d",cat),2.);
    minNlltrack.push_back(make_pair(correctedNlls.first,correctedNlls.second["envelope"]));
    //minNlls.second.insert(pair<string,TGraph*>("envelope",envelopeNll.second));
    //map<string,TGraph*> minNLLs = profiler.profileLikelihoodEnvelope(dataBinned,mu,mu_low,mu_high,mu_step);
    profiler.plot(correctedNlls.second,Form("cat%d_nlls",cat));
    //profiler.print(minNLLs,mu_low,mu_high,mu_step);
    /*
    if (minNLLs.find("envelope")==minNLLs.end()){
      cerr << "ERROR -- envelope TGraph not found in minNLLs" << endl;
      exit(1);
    }
    */
    //minNlltrack.push_back(make_pair(profiler.getGlobalMinNLL(),minNLLs["envelope"]));
  }
  //exit(1);
  TGraph *comb = new TGraph();
  for (vector<pair<double,TGraph*> >::iterator it=minNlltrack.begin(); it!=minNlltrack.end(); it++){
    if (it->second->GetN()!=minNlltrack.begin()->second->GetN()){
      cerr << "ERROR -- unequal number of points for TGraphs " << it->second->GetName() << " and " << minNlltrack.begin()->second->GetName() << endl;
      exit(1);
    }
  }
  for (int p=0; p<minNlltrack.begin()->second->GetN(); p++){
    double x,y,sumy=0;
    for (vector<pair<double,TGraph*> >::iterator it=minNlltrack.begin(); it!=minNlltrack.end(); it++){
      it->second->GetPoint(p,x,y);
      sumy += (y+it->first);
    }
    comb->SetPoint(p,x,sumy);
  }
  pair<double,double> globalMin = getGraphMin(comb);
  for (int p=0; p<comb->GetN(); p++){
    double x,y;
    comb->GetPoint(p,x,y);
    comb->SetPoint(p,x,y-globalMin.second);
  }
  vector<double> fitVal = getValsFromLikelihood(comb);

  cout << "Best fit.." << endl;
  cout << "\t mu = " << Form("%4.3f",fitVal[0]) << " +/- (1sig) = " << fitVal[2]-fitVal[0] << " / " << fitVal[0]-fitVal[1] << endl;
  cout << "\t      " << "    " << " +/- (2sig) = " << fitVal[4]-fitVal[0] << " / " << fitVal[0]-fitVal[3] << endl;

  cout << comb->Eval(fitVal[0]) << " " << comb->Eval(fitVal[1]) << " " << comb->Eval(fitVal[2]) << " " << comb->Eval(fitVal[3]) << " " << comb->Eval(fitVal[4]) << endl;

  double quadInterpVal = ProfileMultiplePdfs::quadInterpMinimum(comb);
  cout << "quadInterp: mu = " << quadInterpVal << endl;
  cout << "\t " << comb->Eval(quadInterpVal) << " " << comb->Eval(quadInterpVal-0.005) << " " << comb->Eval(quadInterpVal-0.01) << " " << comb->Eval(quadInterpVal+0.005) << " " << comb->Eval(quadInterpVal+0.01) << endl;
  
  comb->SetLineWidth(2);
  TCanvas *canv = new TCanvas();
  comb->Draw("ALP");
  canv->Print("plots/comb.pdf");
  TFile *tempOut = new TFile("tempOut.root","RECREATE");
  tempOut->cd();
  comb->SetName("comb");
  comb->Write();
  tempOut->Close();
  return 0;
}
void builtVetoCal(string Input = ""){

	int mode = 1;		// switch: 0 for local files, 1 for pdsf files
	UInt_t card1 = 13;	// 11: prototype, 13: module 1
	UInt_t card2 = 18;
	Bool_t useThresh = true; // if true, also enables fitting LED peaks

	// "low" qdc threshold values
	//Int_t thresh[numPanels] = {123,115,95,93,152,115,105,103,119,91,108,103,94,107,95,167,
	//	53,150,89,120,65,85,132,62,130,101,80,108,145,164,119,82};

	// "high" qdc threshold values
	Int_t thresh[numPanels] = {124,117,96,93,155,115,112,105,120,91,109,108,95,112,96,168,
		63,157,100,127,72,100,140,65,145,125,82,112,151,168,122,94};

	// Input a list of run numbers
	Char_t InputName[200];
	string def = "builtVeto_DebugList"; // default
	if (Input == "") strcpy(InputName,def.c_str());
	else strcpy(InputName,Input.c_str());
	Char_t InputFile[200];
	sprintf(InputFile,"%s.txt",InputName);
	ifstream InputList;
	InputList.open(InputFile);
	Char_t TheFile[200];

	// Set up output file(s)
	Char_t OutputFile[200];
	sprintf(OutputFile,"./output/%s.root",InputName);
	TFile *RootFile = new TFile(OutputFile, "RECREATE");	
  	TH1::AddDirectory(kFALSE); // Global flag: "When a (root) file is closed, all histograms in memory associated with this file are automatically deleted."

	ofstream calib;
	Char_t CalibFile[200];
	sprintf(CalibFile,"./output/%s_CalibrationTable.txt",InputName);
	calib.open(CalibFile);


	//=== Global counters / variables / plots ===

		Int_t run = 0;
		Float_t duration = 0;
		Float_t durationTotal = 0;
		
		// get number of files in dataset for the TGraph
		Int_t filesToScan = 0;
		Int_t filesScanned = 0;
	  	while(!InputList.eof()) { InputList >> run; filesToScan++; }
	  	cout << "Scanning " << filesToScan << " files." << endl;	  	
	  	InputList.close();
	  	InputList.open(InputFile);
	  	run=0;
	 	TGraph *SCorruption = new TGraph(filesToScan);
	 	Int_t BadTSTotal = 0;

	 	TH1D *TotalCorruptionInTime = new TH1D("TotalCorruptionInTime","corrupted entries during run (entry method)",(Int_t)3600/5,0,3600);
	 	TotalCorruptionInTime->GetXaxis()->SetTitle("time (5 sec / bin)");
	 	Bool_t PlotCorruptedEntries = false; // flag for plotting corrupted entries in time for EACH RUN

	 	TH1D *TotalMultiplicity = new TH1D("TotalMultiplicity","Events over threshold",32,0,32);
	 	TotalMultiplicity->GetXaxis()->SetTitle("number of panels hit");
	 	Bool_t PlotMultiplicity = false;	// flag to plot multiplicity for EACH RUN

	 	const Int_t nqdc_bins=1400;  // this gives 3 qdc / bin
		const Float_t ll_qdc=0.;
		const Float_t ul_qdc=4200.;
		Char_t hname[50];
		for (Int_t i=0; i<numPanels; i++){
			sprintf(hname,"hRawQDC%d",i);
			hRawQDC[i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);
			sprintf(hname,"hCutQDC%d",i);
			hCutQDC[i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);
			sprintf(hname,"hThreshQDC%d",i);
			hThreshQDC[i] = new TH1F(hname,hname,500,ll_qdc,500);
			sprintf(hname,"hLEDCutQDC%d",i);
			hLEDCutQDC[i] = new TH1F(hname,hname,500,ll_qdc,500);
		}

		Long64_t CountsBelowThresh[numPanels] = {0};
		Long64_t TotalCounts[numPanels] = {0};		

		
	//=== End ===



	// Loop over files
	while(!InputList.eof()){

		// initialize 
		InputList >> run;
		if (mode==0) sprintf(TheFile,"~/dev/datasets/muFinder/OR_run%i.root",run);
		else if (mode==1) sprintf(TheFile,"/global/project/projectdirs/majorana/data/mjd/surfmjd/data/built/P3JDY/OR_run%u.root",run); 
		TChain *VetoTree = new TChain("VetoTree");
		VetoTree->AddFile(TheFile);
		TChain *MGTree = new TChain("MGTree");
		MGTree->AddFile(TheFile);
		MJTRun *MyRun = new MJTRun();
		MGTree->SetBranchAddress("run",&MyRun);
		Long64_t nentries = VetoTree->GetEntries();
		MGTBasicEvent *b = new MGTBasicEvent; 
		//MGTBasicEvent b;
		VetoTree->SetBranchAddress("vetoEvent",&b);
		const int vd_size = 16;	
		MJTVetoData *vd[vd_size];
		VetoTree->GetEntry(0);
		for (int i=0; i<vd_size; i++) { vd[i] = dynamic_cast<MJTVetoData*>(b->GetDetectorData()->At(i)); }
        MGTree->GetEntry(0);
        duration = MyRun->GetStopTime() - MyRun->GetStartTime();
        if (duration < 0) {
        	printf("\nRun %i has duration %.0f, skipping file!\n\n",run,duration);
        	continue;
        }
        durationTotal += duration;

    	//=== Single-file counters / variables / plots

			QEvent qdc;
			QEvent prevqdc;
				prevqdc.EventCount=-1;
			VEvent veto;
			Bool_t EventMatch = false;

			Int_t BadTSInFile = 0;
			Float_t corruption = 0;
			Int_t numPanelsHit = 0;

			// only write these if their bools are set = true
			TH1D *CorruptionInTime = new TH1D("CorruptionInTime","corrupted entries during run (entry method)",(Int_t)duration/5,0,(Int_t)duration);
			CorruptionInTime->GetXaxis()->SetTitle("time (5 sec / bin)");
			TH1D *OneRunMultiplicity = new TH1D("multiplicity","multiplicity of veto entries",32,0,32);
			OneRunMultiplicity->GetXaxis()->SetTitle("number of panels hit");
		
		//=== End ===

		// Loop over VetoTree entries
		printf("Now scanning run %i: %lli entries, %.2f sec.  \n",run,nentries,duration);
		for (int i = 0; i < nentries; i++) {
			VetoTree->GetEntry(i);

			// move data into QEvent structure
			qdc.runNumber=run;
			qdc.crate=vd[0]->GetCrate();
			qdc.card=vd[0]->GetCard();
			qdc.EventCount=vd[0]->GetEventCount();
			int k = 0;
			for (int j = 0; j<16; j++)	{
				k = vd[j]->GetChannel();
				qdc.QDC[k]=vd[j]->GetAmplitude();
				qdc.IsUnderThreshold[k]=vd[j]->IsUnderThreshold();
				qdc.IsOverflow[k]=vd[j]->IsOverflow();
			}
			
			// check qdc data after moving into QEvent structure
			//printf("QDC -- run: %i  Entry: %i  crate: %i  card: %i  EventCount: %i \n",qdc.runNumber,i,qdc.crate,qdc.card,qdc.EventCount);
			//cout << "QDC: "; for (int k = 0; k<16; ++k) { cout << qdc.QDC[k] << "  "; } cout << endl;
			//cout << "UTh: "; for (int k = 0; k<16; ++k) { cout << qdc.IsUnderThreshold[k] << "  "; } cout << endl;
			//cout << "Ovr: "; for (int k = 0; k<16; ++k) { cout << qdc.IsOverflow[k] << "  "; } cout << endl;	
			
			// check entry numbers
			//printf("Entry: %i  card: %i  EventCount: %i",i,qdc.card,qdc.EventCount);
			//printf("  ||  ScalerCount: %i  TimeStamp: %.5f  IsBadTs: %i \n",
			//	vd[0]->GetScalerCount(),vd[0]->GetTimeStamp()/1E8,vd[0]->IsBadTS());
			
			// set flag if current qdc entry has same EventCount as previous one.
			EventMatch = false;
			if (qdc.EventCount == prevqdc.EventCount) { 
				EventMatch = true; 
				//printf("EventMatch true.  qdc.EventCount:%i  prevqdc.EventCount:%i \n",qdc.EventCount,prevqdc.EventCount);
			}
			else if (abs(qdc.EventCount - prevqdc.EventCount) > 1 && i > 2) {
				printf(" EventCount mismatch! Run:%i current:%i previous:%i card:%i prev.card:%i  Breaking at %.0f%% through file.\n",run,i,qdc.card,prevqdc.card,((Float_t)i/nentries)*100);
				break;
			}

			
			
			if (EventMatch) {
				
				// move matching events into VEvent structure and incorporate scaler info.
				veto.run = qdc.runNumber;
				veto.vEnt = qdc.EventCount;
				veto.sEnt = vd[0]->GetScalerCount();
				veto.sTime = vd[0]->GetTimeStamp()/1E8;
				veto.sTimeBad = vd[0]->IsBadTS();
				veto.eTime = ((Float_t)i/nentries)*duration;	
				// case 1
				if (prevqdc.card==card1 && qdc.card==card2) {
					veto.card[0]=vd[0]->GetScalerID();
					veto.card[1]=prevqdc.card;
					veto.card[2]=qdc.card;
					for (int k = 0; k<16; k++) {
						veto.QDC[k]=prevqdc.QDC[k];
						veto.QDC[16+k]=qdc.QDC[k];
						veto.IsUnderThreshold[k]=prevqdc.IsUnderThreshold[k];
						veto.IsUnderThreshold[16+k]=qdc.IsUnderThreshold[k];
						veto.IsOverflow[k]=prevqdc.IsOverflow[k];
						veto.IsOverflow[16+k]=qdc.IsOverflow[k];
					}
				}
				// case 2
				else if (prevqdc.card==card2 && qdc.card==card1) {
					veto.card[0]=vd[0]->GetScalerID();
					veto.card[1]=qdc.card;
					veto.card[2]=prevqdc.card;
					for (int k = 0; k<16; k++) {
						veto.QDC[k]=qdc.QDC[k];
						veto.QDC[16+k]=prevqdc.QDC[k];
						veto.IsUnderThreshold[k]=qdc.IsUnderThreshold[k];
						veto.IsUnderThreshold[16+k]=prevqdc.IsUnderThreshold[k];
						veto.IsOverflow[k]=qdc.IsOverflow[k];
						veto.IsOverflow[16+k]=prevqdc.IsOverflow[k];
					}
				}
				else if ((int)prevqdc.card==-1) { cout << "Previous Card was 0, EventMatch: " << EventMatch << endl;  continue; }
				else { printf("Failed to match!  Run: %i  VetoTree entry: %i  Card:%i  Prev.Card:%i  Breaking at %.0f%% through file.\n",run,i,qdc.card,prevqdc.card,((Float_t)i/nentries)*100); break; }

				// check VEvent data
				//printf("run:%i  vEnt:%i  sEnt:%i  card0:%i  card1:%i  card2:%i  sTime:%.5f  sTimeBad:%i\n",
				//	veto.run,veto.vEnt,veto.sEnt,veto.card[0],veto.card[1],veto.card[2],veto.sTime,veto.sTimeBad);
				//cout << "QDC: "; for (int k = 0; k<numPanels; ++k) { cout << veto.QDC[k] << "  "; } cout << endl;
				//cout << "UTh: "; for (int k = 0; k<numPanels; ++k) { cout << veto.IsUnderThreshold[k] << "  "; } cout << endl;
				//cout << "Ovr: "; for (int k = 0; k<numPanels; ++k) { cout << veto.IsOverflow[k] << "  "; } cout << endl;

				//=====================BEGIN ACTUAL GODDAMMED ANALYSIS=================

				// scaler corruption
				if (veto.sTimeBad) { 
					BadTSInFile++;
					TotalCorruptionInTime->Fill(veto.eTime);
					if (PlotCorruptedEntries) CorruptionInTime->Fill(veto.eTime);
				}

				// loop over panels
				for (int k=0; k<numPanels; k++) {
					
					// test lowered panel-by-panel thresholds
					if (veto.QDC[k]<thresh[k]) CountsBelowThresh[k]++;
					TotalCounts[k]++;

					// plot qdc entries above threshold
					hRawQDC[k]->Fill(veto.QDC[k]);
					if (veto.QDC[k]<500) hThreshQDC[k]->Fill(veto.QDC[k]);
					if (useThresh && veto.QDC[k]>thresh[k]) hCutQDC[k]->Fill(veto.QDC[k]);

					// count multiplicity
					if (useThresh) { if (veto.QDC[k]>thresh[k]) numPanelsHit++; }
					else { if (!veto.IsUnderThreshold[k]) numPanelsHit++; }
				}
		        TotalMultiplicity->Fill(numPanelsHit);			
		        if (PlotMultiplicity) OneRunMultiplicity->Fill(numPanelsHit);


				//=====================END ACTUAL GODDAMMED ANALYSIS===================

			} // end EventMatch condition

			// Save qdc into prevqdc before getting next VetoTree entry.
			prevqdc = qdc;
			EventMatch = false;
			numPanelsHit=0;

		}	// End loop over VetoTree entries.

		// === END OF FILE Output & Plotting ===
		
		corruption = ((Float_t)BadTSInFile/nentries)*100;
		printf(" Corrupted scaler entries: %i of %lli, %.3f %%.\n",BadTSInFile,nentries,corruption);
		if(run>45000000) SCorruption->SetPoint(filesScanned,run-45000000,corruption);
		else SCorruption->SetPoint(filesScanned,run,corruption);

		if (PlotCorruptedEntries) {
			char outfile1[200];	
			sprintf(outfile1,"CorruptionInTime_Run%i",run);
			CorruptionInTime->Write(outfile1,TObject::kOverwrite);
		}
		if (PlotMultiplicity) {
			char outfile2[200];
			sprintf(outfile2,"Multiplicity_Run%i",run);
			OneRunMultiplicity->Write(outfile2,TObject::kOverwrite);
		}

		// ==========================

		delete VetoTree;
		delete MGTree;
		filesScanned++;
	} // End loop over files.

	

	// === END OF SCAN Output & Plotting ===
	printf("Finished loop over files.\n");

	// estimate reduction in data
	if (useThresh) {
		Long64_t total=0, below=0;
		double reduction;
		for (int i=0; i<numPanels; i++) {
			below += CountsBelowThresh[i];
			total += TotalCounts[i];
		}
		reduction = ((double)below/total)*100;
		double rateBefore = (double)total/durationTotal; 
		double rateAfter = (double)(total-below)/durationTotal;
		printf("Counts below thresh make up %.2f%% of total entries scanned, over %.2f seconds.\n",reduction,durationTotal);
		printf("This is %lli of %lli events.  Rate reduction would be from %.2f Hz to %.2f Hz.\n",below,total,rateBefore,rateAfter);
	}

	TCanvas *c1 = new TCanvas("c1", "Bob Ross's Canvas",600,600);
	c1->SetGrid();
	SCorruption->SetMarkerColor(4);
	SCorruption->SetMarkerStyle(21);
	SCorruption->SetMarkerSize(0.5);
	SCorruption->SetTitle("Corruption in scaler card");
	SCorruption->GetXaxis()->SetTitle("Run");
	SCorruption->GetYaxis()->SetTitle("% corrupted events");
	SCorruption->Draw("ALP");	
	SCorruption->Write("ScalerCorruption",TObject::kOverwrite);

	TotalCorruptionInTime->Write("TotalCorruptionInTime",TObject::kOverwrite);

	TotalMultiplicity->Write("TotalMultiplicity",TObject::kOverwrite);

	// QDC Plots & Calibration Table:
	// gaus: A gaussian with 3 parameters: f(x) = p0*exp(-0.5*((x-p1)/p2)^2)).
	TF1 *fits[numPanels];
	TCanvas *vcan0 = new TCanvas("vcan0","cut & fitted veto QDC, panels 1-32",0,0,800,600);
	vcan0->Divide(8,4,0,0);
	TCanvas *vcan1 = new TCanvas("vcan1","veto QDC thresholds, panels 1-32",0,0,800,600);
	vcan1->Divide(8,4,0,0);	
	Char_t buffer[2000];
	printf("\n Calibration Table:\n  Panel / Mean,error / Sigma,error / Chi-square/NDF (~1?) / LED Peak Pos.\n");
	for (Int_t i=0; i<numPanels; i++){
		
		vcan0->cd(i+1);
		TVirtualPad *vpad0 = vcan0->cd(i+1); vpad0->SetLogy();
		hThreshQDC[i]->Write(); // write the low-QDC part of the spectrum separately
		if (useThresh) {
			hCutQDC[i]->Write();    // write the cut QDC
			hCutQDC[i]->Fit("gaus","q");
			hCutQDC[i]->Draw();
			fits[i] = hCutQDC[i]->GetFunction("gaus");
			if (hCutQDC[i]->GetEntries() > 0) {
				Float_t NDF = (Float_t)fits[i]->GetNDF();
				if (fits[i]->GetNDF() == 0) NDF = 0.0000001;
				sprintf(buffer,"%i  %.1f  %.1f  %.1f  %.1f  %.1f",i,
					fits[i]->GetParameter(1),fits[i]->GetParError(1),		// mean (LED center)
					fits[i]->GetParameter(2),fits[i]->GetParError(2),		// sigma
					fits[i]->GetChisquare()/NDF); // X^2/NDF (closer to 1, better fit.)
				cout << "  " << buffer << endl;
				calib << buffer << endl;
			}
		}
		else {
			hRawQDC[i]->Write();		// write the raw QDC without fitting
		}	
    	
   	// plot low-QDC range separately
  		vcan1->cd(i+1);
  		TVirtualPad *vpad1 = vcan1->cd(i+1); vpad1->SetLogy();
  		hThreshQDC[i]->Draw();
	}

	// Output canvasses of interest.
	Char_t OutputName[200];
	
	sprintf(OutputName,"./output/%s_VetoQDC.C",InputName);
	vcan0->Print(OutputName);

	sprintf(OutputName,"./output/%s_ThreshVetoQDC.C",InputName);
	vcan1->Print(OutputName);
	
	// ==========================

	calib.close();
	RootFile->Close();
	cout << "Wrote ROOT file." << endl;
}
Example #17
0
//______________________________________________________________________________
void MUONStatusMapEvolution(const char* runlist, const char* outfile)
{
  // Compute the number of bad pads (because of bad ped, bad hv, bad lv,
  // or missing in configuration)
  //
  // output a root file with the different graphs.
  //
  // output can be then plotted using the DrawEvolution function
  //
  // Note that the output of different runlists can then be merged simply using
  // the hadd program, and so then the DrawEvolution can be used over
  // a huge period, e.g. a full year, while this method is better restricted
  // to a period or even less (depending on your success of accessing the OCDB)
  //

  std::vector<int> runs;

  ReadIntegers(runlist,runs);

  if ( runs.empty() )
  {
    cout << "No runs to process..." << endl;
    return;
  }

  int year(2016);

  if ( runs[0] <= 139699 ) year=2010;

  if ( runs[0] <= 176000 ) year=2011;

  if ( runs[0] <= 195344 ) year = 2012;

  if ( runs[0] <= 198000 ) year = 2013;

  if ( runs[0] <= 246994 ) year = 2015;

  TString defaultOCDB;

  defaultOCDB.Form("local:///cvmfs/alice-ocdb.cern.ch/calibration/data/%d/OCDB",year);

//  defaultOCDB.Form("alien://folder=/alice/data/%d/OCDB?cacheFold=/local/cdb",year);

  AliCDBManager::Instance()->SetDefaultStorage(defaultOCDB.Data());
  AliCDBManager::Instance()->SetRun(0);

  TList glist;

  glist.SetOwner(kTRUE);

  TGraph* gnbad = new TGraph(runs.size());
  gnbad->SetName("nbad");
  glist.Add(gnbad);

  TGraph* gnbadped = new TGraph(runs.size());
  gnbadped->SetName("nbadped");
  glist.Add(gnbadped);

  TGraph* gnbadocc = new TGraph(runs.size());
  gnbadocc->SetName("nbadocc");
  glist.Add(gnbadocc);

  TGraph* gnbadhv = new TGraph(runs.size());
  gnbadhv->SetName("nbadhv");
  glist.Add(gnbadhv);

  TGraph* gnmissing = new TGraph(runs.size());
  gnmissing->SetName("nmissing");
  glist.Add(gnmissing);

  TGraph* gnreco = new TGraph(runs.size());
  gnreco->SetName("nreco");
  glist.Add(gnreco);

  TGraph* gnbadlv = new TGraph(runs.size());
  gnbadlv->SetName("nbadlv");
  glist.Add(gnbadlv);

  for ( std::vector<int>::size_type i = 0; i < runs.size(); ++i )
  {
    Int_t runNumber = runs[i];
    Int_t nbadped;
    Int_t nbadhv;
    Int_t nbadlv;
    Int_t nbadocc;
    Int_t nmissing;
    Int_t nreco;

    Int_t nbad = GetBadChannels(runNumber,nbadped,nbadhv,nbadlv,nbadocc,nmissing,nreco);

    gnbad->SetPoint(i,runNumber,nbad);
    gnbadped->SetPoint(i,runNumber,nbadped);
    gnbadhv->SetPoint(i,runNumber,nbadhv);
    gnbadlv->SetPoint(i,runNumber,nbadlv);
    gnbadocc->SetPoint(i,runNumber,nbadocc);
    gnmissing->SetPoint(i,runNumber,nmissing);
    gnreco->SetPoint(i,runNumber,nreco);
  }

  TIter next(&glist);
  TGraph* g;
  Int_t index(0);

  TFile f(outfile,"recreate");
  Int_t  color[] = {  1 ,  2 ,  3 ,  4,  6,  8,  7 };
  Int_t marker[] = { 28 , 24 , 23 , 26, 30,  5, 32 };

  while ( ( g = static_cast<TGraph*>(next() ) ) )
  {
    g->GetXaxis()->SetNdivisions(505);
    g->GetXaxis()->SetNoExponent();
    g->SetMinimum(0);
    g->GetYaxis()->SetNoExponent();
    g->SetLineColor(color[index]);
    g->SetMarkerStyle(marker[index]);
    g->SetMarkerColor(color[index]);
    g->SetMarkerSize(1.0);
    ++index;
    g->Write();
  }

  f.Close();


}
int doHistAnalysis () {
    
    // plot options
    gStyle->SetOptFit(111111111);
    gStyle->SetOptStat(11111111);
    
    // paths to files
    string Bfile_path = "rootfiles/DataScouting_V00-01-06_Run2012B_runrange_193752-197044_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string Cfile_path = "rootfiles/DataScouting_V00-01-06_Run2012C_runrange_197885-203755_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string Dfile_path = "rootfiles/DataScouting_V00-01-06_Run2012D_runrange_203773-208686_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string BCDfile_path = "rootfiles/DataScouting_V00-01-06_Run2012B_Run2012C_Run2012D_runrange_193752-208686_dijet_alfaT_razor_dijetpairs_trijetpairs.root";
    string histPath = "DQMData/Run 999999/DataScouting/Run summary/DiJet";
    string mjj_histName = "h1_MjjWide_finalSel_varbin;1"; // use VARIABLE BINS
    //string mjj_histName = "h1_MjjWide_finalSel;1"; // use 1 GEV BINS
    
    // luminosities, as given on the twiki
    double BLum_fb = 4.445, CLum_fb = 6.806, DLum_fb = 7.384; // in inverse fb
    double BCDLum_fb = BLum_fb + CLum_fb + DLum_fb;
    double BLum_pb = BLum_fb * 1e3;
    double CLum_pb = CLum_fb * 1e3;
    double DLum_pb = DLum_fb * 1e3;
    double BCDLum_pb = BCDLum_fb * 1e3; // converts to inverse pb
    
    // read in the files and get histograms
    TFile * Bfile = new TFile (Bfile_path.c_str());
    TDirectory * BHistDir = Bfile->GetDirectory(histPath.c_str());
    TH1D * BmjjHist = (TH1D*)BHistDir->Get(mjj_histName.c_str());
    BmjjHist->SetName("RunB dijet mass");
    BmjjHist->SetTitle("RunB dijet mass");
    
    TFile * Cfile = new TFile (Cfile_path.c_str());
    TDirectory * CHistDir = Cfile->GetDirectory(histPath.c_str());
    TH1D * CmjjHist = (TH1D*)CHistDir->Get(mjj_histName.c_str());
    CmjjHist->SetName("RunC dijet mass");
    CmjjHist->SetTitle("RunC dijet mass");
    
    TFile * Dfile = new TFile (Dfile_path.c_str());
    TDirectory * DHistDir = Dfile->GetDirectory(histPath.c_str());
    TH1D * DmjjHist = (TH1D*)DHistDir->Get(mjj_histName.c_str());
    DmjjHist->SetName("RunD dijet mass");
    DmjjHist->SetTitle("RunD dijet mass");
    
    TFile * BCDfile = new TFile (BCDfile_path.c_str());
    TDirectory * BCDHistDir = BCDfile->GetDirectory(histPath.c_str());
    TH1D * BCDmjjHist = (TH1D*)BCDHistDir->Get(mjj_histName.c_str());
    BCDmjjHist->SetName("RunsBCD dijet mass");
    BCDmjjHist->SetTitle("RunsBCD dijet mass");
    
    // read out into memory and close the files
    TFile * writefile = new TFile("fTestHists.root","recreate");
    BmjjHist->SetDirectory(writefile);
    CmjjHist->SetDirectory(writefile);
    DmjjHist->SetDirectory(writefile);
    BCDmjjHist->SetDirectory(writefile);
    Bfile->Close();
    Cfile->Close();
    Dfile->Close();
    BCDfile->Close();
    
    // normalise histograms
    NormaliseByLuminosity(BmjjHist, BLum_pb);
    NormaliseByBinWidth(BmjjHist);
    NormaliseByLuminosity(CmjjHist, CLum_pb);
    NormaliseByBinWidth(CmjjHist);
    NormaliseByLuminosity(DmjjHist, DLum_pb);
    NormaliseByBinWidth(DmjjHist);
    NormaliseByLuminosity(BCDmjjHist, BCDLum_pb);
    NormaliseByBinWidth(BCDmjjHist);
    
    // make ratio histograms
    TH1D * BCratio = (TH1D*)BmjjHist->Clone();
    BCratio->Divide(CmjjHist);
    BCratio->SetName("B/C ratio");
    BCratio->SetTitle("B/C ratio");
    
    TH1D * BDratio = (TH1D*)BmjjHist->Clone();
    BDratio->Divide(DmjjHist);
    BDratio->SetName("B/D ratio");
    BDratio->SetTitle("B/D ratio");
    
    TH1D * CDratio = (TH1D*)CmjjHist->Clone();
    CDratio->Divide(DmjjHist);
    CDratio->SetName("C/D ratio");
    CDratio->SetTitle("C/D ratio");
    
    // choose the range to do the fit in
    Float_t fitRangeLow = 270.;
    Float_t fitRangeHigh = 3000.;
    
    // set plot ranges
    BmjjHist->SetAxisRange(500, 3000, "X");
    CmjjHist->SetAxisRange(500, 3000, "X");
    DmjjHist->SetAxisRange(500, 3000, "X");
    BCDmjjHist->SetAxisRange(fitRangeLow, fitRangeHigh, "X");
    
    // write these histograms to file
    writefile->Write();
    
    // F-test loop
    // repeat until the F-test is satisfied
    int nBasePars = 4;
    int nExtraPars = 0;
    float RSSold = 0;
    float RSS = 0;
    int stopTest = 0;
    while (stopTest == 0) {
        // get number of fit parameters
        // (one of the parameters holds the number of parameters... tricky!)
        int nTotalPars = 1 + nBasePars + nExtraPars;

        // set the name of the fit/histogram
        std::ostringstream s;
        s << "FTest" << nExtraPars;
        string fitNameStr = s.str();
        
        // make a canvas to put fit and residual on
        TCanvas* canvas = new TCanvas((fitNameStr + "-canv").c_str(), (fitNameStr + "-canv").c_str(), 800, 600);
        canvas->cd();
        
        //create 3 pads in the canvas
        TPad* fPads1 = NULL;
        TPad* fPads2 = NULL;

        fPads1 = new TPad("pad1", "", 0.00, 0.20, 0.99, 0.99);
        fPads2 = new TPad("pad3", "", 0.00, 0.00, 0.99, 0.20);
        fPads1->SetFillColor(0);
        fPads1->SetLineColor(0);
        fPads2->SetFillColor(0);
        fPads2->SetLineColor(0);
        fPads1->Draw();
        fPads2->Draw();
        
        // make a new histogram to do the fit on
        fPads1->cd();
        TH1D * fitHist = new TH1D;
        fitHist = BCDmjjHist;
        fitHist->SetName(fitNameStr.c_str());

        // set up the background fit
        TF1 *bkfit = new TF1(fitNameStr.c_str(),BackgroundShape, fitRangeLow, fitRangeHigh, nTotalPars);
        bkfit->SetParName(0,"nPar");
        for (int i=1;i<nTotalPars;++i) {
            std::ostringstream p;
            p << "P" << i-1;
            string parNameStr = p.str();
            bkfit->SetParName(i,parNameStr.c_str());
        }
        
        // set the initial parameter values
        bkfit->FixParameter(0,nTotalPars*1.); // number of parameters does not change!
        bkfit->SetParameter(0+1,2.6e-06); // P0
        bkfit->SetParameter(1+1,5.8); // P1
        bkfit->SetParameter(2+1,6.7); // P2
        bkfit->SetParameter(3+1,0.3); // P3
        for (int i=nBasePars+1;i<nTotalPars;++i) {
            // all others to zero
            bkfit->SetParameter(i+1,0.0);
        }
        
        // Fit and get parameters
        fitHist->Fit(bkfit,"IM"); // MRQ (M=improve, R=use fn range, Q=quiet, I=integral, L=likelihood)
        Double_t * params = bkfit->GetParameters();
        fitHist->Write();
        fitHist->SetDirectory(0);
        
        // Make new TGraph for the residual plot
        fPads2->cd();
        TVectorD nsigma_x(fitHist->GetNbinsX()); 
        TVectorD nsigma_y(fitHist->GetNbinsX()); 
      
        for(int i = 1; i <= fitHist->GetNbinsX(); ++i) {
            double binLow = fitHist->GetXaxis()->GetBinLowEdge(i);
            double binHigh = fitHist->GetXaxis()->GetBinUpEdge(i);
            double exp = fitHist->GetBinContent(i);
            double obs = bkfit->Integral(binLow, binHigh, params) / (binHigh - binLow);
            double error = fitHist->GetBinError(i);
            double x = fitHist->GetBinCenter(i);
            
            double diff = obs - exp;
            double sigma = sqrt(error*error);
        
            if (sigma != 0.0 && obs != 0.0 ) {
                nsigma_x[i] = x;
                nsigma_y[i] = diff / sigma;
            } else {
                nsigma_x[i] = +999999;
                nsigma_y[i] = 0;
            }       
        }
        
        // plot the graph of residuals 
        if (nsigma_x.GetNoElements() != 0 ) {
            TGraph *nsigmaGraph = new TGraph(nsigma_x,nsigma_y);
            nsigmaGraph->SetName((fitNameStr+"-resid").c_str());
            nsigmaGraph->SetTitle("");
            nsigmaGraph->GetYaxis()->SetRangeUser(-5,5);
            nsigmaGraph->GetYaxis()->SetTitle("(Data-Fit)/#sigma");
            nsigmaGraph->GetYaxis()->SetTitleOffset(0.1);
            nsigmaGraph->GetYaxis()->SetTitleSize(0.15);
            nsigmaGraph->GetYaxis()->SetLabelSize(0.07);
            nsigmaGraph->GetXaxis()->SetTitle("");
            nsigmaGraph->GetXaxis()->SetLimits(fitRangeLow, fitRangeHigh);
            nsigmaGraph->GetXaxis()->SetRangeUser(fitRangeLow, fitRangeHigh);
            nsigmaGraph->GetXaxis()->SetTitleOffset(0.01);
            nsigmaGraph->GetXaxis()->SetLabelSize(0.09);
            nsigmaGraph->SetMarkerStyle(8);
            nsigmaGraph->SetMarkerSize(0.8);
            nsigmaGraph->Draw("AP");
            nsigmaGraph->Write();
        }
        
        canvas->Write();
        
        // Get degrees of freedom
        int dof = GetNBinsInRange(fitHist, fitRangeLow, fitRangeHigh) - nTotalPars + 1;
        cout << dof << endl;
        
        // Get the RSS value between fit and histogram
        RSSold = RSS;
        RSS = GetResidualSumSquares(BCDmjjHist, bkfit, params, fitRangeLow, fitRangeHigh);
        cout << nExtraPars << endl;
        cout << RSSold << endl;
        cout << RSS << endl;
        
        if (RSSold==0) {
            // we must do it again with an extra parameter before we can do the f-test
            nExtraPars += 1;
            continue;
        }
        
        // otherwise, do a F-test
        const double alphaFTest=0.05;
        cout << "Starting F-Test evaluation with alpha = " << alphaFTest << endl;
        double fTestVal = (RSSold-RSS) * dof / RSS;
        if (fTestVal < 0) {
            // the fit got WORSE - try again!
            
            // TODO: probably look at this, as at present it will add an extra parameter
            // any time the fit worsens from the last time, even slightly.
            // Really we should only do this if the fit is significantly worse. 
            
            cout << "Fit worsened; automatically trying extra parameter\n";
            nExtraPars += 1;
            continue;
        }
        cout  << "F-test value = " << fTestVal << endl;
        double goodCL =  1.-TMath::FDistI(fTestVal,1,dof);
        cout  << "F-test CL = " << goodCL << endl;
        
        if (goodCL > alphaFTest) {
            // the fit got better but not by much - stop here
            cout << "Requires " << nExtraPars-1 << " extra parameters.\n";
            stopTest = 1;
        } else if (nExtraPars == 10) {
            // 10 extra parameters is enough for anyone
            cout << "Reached 10 extra parameters without success - aborting\n";
            stopTest = 1;
        } else {
            // it got significantly better - try still more parameters
            cout << "F-test failed; trying more parameters\n";
            nExtraPars += 1;
        }
    }
    
    // finish up
    writefile->Close();
    
    return 1;
}
   void ws_constrained_profile3D( const char* wsfile = "rootfiles/ws-data-unblind.root",
                                   const char* new_poi_name = "n_M234_H4_3b",
                                   int npoiPoints = 20,
                                   double poiMinVal = 0.,
                                   double poiMaxVal = 20.,
                                   double constraintWidth = 1.5,
                                   double ymax = 10.,
                                   int verbLevel=0 ) {


     gStyle->SetOptStat(0) ;

     //--- make output directory.

     char command[10000] ;
     sprintf( command, "basename %s", wsfile ) ;
     TString wsfilenopath = gSystem->GetFromPipe( command ) ;
     wsfilenopath.ReplaceAll(".root","") ;
     char outputdirstr[1000] ;
     sprintf( outputdirstr, "outputfiles/scans-%s", wsfilenopath.Data() ) ;
     TString outputdir( outputdirstr ) ;


     printf("\n\n Creating output directory: %s\n\n", outputdir.Data() ) ;
     sprintf(command, "mkdir -p %s", outputdir.Data() ) ;
     gSystem->Exec( command ) ;


     //--- Tell RooFit to shut up about anything less important than an ERROR.
      RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ;



       if ( verbLevel > 0 ) { printf("\n\n Verbose level : %d\n\n", verbLevel) ; }


       TFile* wstf = new TFile( wsfile ) ;

       RooWorkspace* ws = dynamic_cast<RooWorkspace*>( wstf->Get("ws") );

       if ( verbLevel > 0 ) { ws->Print() ; }






       RooDataSet* rds = (RooDataSet*) ws->obj( "ra2b_observed_rds" ) ;

       if ( verbLevel > 0 ) {
          printf("\n\n\n  ===== RooDataSet ====================\n\n") ;
          rds->Print() ;
          rds->printMultiline(cout, 1, kTRUE, "") ;
       }





       ModelConfig* modelConfig = (ModelConfig*) ws->obj( "SbModel" ) ;
       RooAbsPdf* likelihood = modelConfig->GetPdf() ;

       RooRealVar* rrv_mu_susy_all0lep = ws->var("mu_susy_all0lep") ;
       if ( rrv_mu_susy_all0lep == 0x0 ) {
          printf("\n\n\n *** can't find mu_susy_all0lep in workspace.  Quitting.\n\n\n") ;
          return ;
       }





       //-- do BG only.
       rrv_mu_susy_all0lep->setVal(0.) ;
       rrv_mu_susy_all0lep->setConstant( kTRUE ) ;










       //-- do a prefit.

       printf("\n\n\n ====== Pre fit with unmodified nll var.\n\n") ;

       RooFitResult* dataFitResultSusyFixed = likelihood->fitTo(*rds, Save(true),Hesse(false),Minos(false),Strategy(1),PrintLevel(verbLevel));
       int dataSusyFixedFitCovQual = dataFitResultSusyFixed->covQual() ;
       if ( dataSusyFixedFitCovQual < 2 ) { printf("\n\n\n *** Failed fit!  Cov qual %d.  Quitting.\n\n", dataSusyFixedFitCovQual ) ; return ; }
       double dataFitSusyFixedNll = dataFitResultSusyFixed->minNll() ;

       if ( verbLevel > 0 ) {
          dataFitResultSusyFixed->Print("v") ;
       }

       printf("\n\n Nll value, from fit result : %.3f\n\n", dataFitSusyFixedNll ) ;

       delete dataFitResultSusyFixed ;






       //-- Construct the new POI parameter.
       RooAbsReal* new_poi_rar(0x0) ;

       new_poi_rar = ws->var( new_poi_name ) ;
       if ( new_poi_rar == 0x0 ) {
          printf("\n\n New POI %s is not a variable.  Trying function.\n\n", new_poi_name ) ;
          new_poi_rar = ws->function( new_poi_name ) ;
          if ( new_poi_rar == 0x0 ) {
             printf("\n\n New POI %s is not a function.  I quit.\n\n", new_poi_name ) ;
             return ;
          }
       } else {
          printf("\n\n     New POI %s is a variable with current value %.1f.\n\n", new_poi_name, new_poi_rar->getVal() ) ;
       }








       if ( npoiPoints <=0 ) {
          printf("\n\n Quitting now.\n\n" ) ;
          return ;
       }


       double startPoiVal = new_poi_rar->getVal() ;



      //--- The RooNLLVar is NOT equivalent to what minuit uses.
  //   RooNLLVar* nll = new RooNLLVar("nll","nll", *likelihood, *rds ) ;
  //   printf("\n\n Nll value, from construction : %.3f\n\n", nll->getVal() ) ;

      //--- output of createNLL IS what minuit uses, so use that.
       RooAbsReal* nll = likelihood -> createNLL( *rds, Verbose(true) ) ;

       RooRealVar* rrv_poiValue = new RooRealVar( "poiValue", "poiValue", 0., -10000., 10000. ) ;
   /// rrv_poiValue->setVal( poiMinVal ) ;
   /// rrv_poiValue->setConstant(kTRUE) ;

       RooRealVar* rrv_constraintWidth = new RooRealVar("constraintWidth","constraintWidth", 0.1, 0.1, 1000. ) ;
       rrv_constraintWidth -> setVal( constraintWidth ) ;
       rrv_constraintWidth -> setConstant(kTRUE) ;




       if ( verbLevel > 0 ) {
          printf("\n\n ======= debug likelihood print\n\n") ;
          likelihood->Print("v") ;
          printf("\n\n ======= debug nll print\n\n") ;
          nll->Print("v") ;
       }






    //----------------------------------------------------------------------------------------------

       RooMinuit* rminuit( 0x0 ) ;


       RooMinuit* rminuit_uc = new RooMinuit( *nll  ) ;

       rminuit_uc->setPrintLevel(verbLevel-1) ;
       rminuit_uc->setNoWarn() ;

       rminuit_uc->migrad() ;
       rminuit_uc->hesse() ;

       RooFitResult* rfr_uc = rminuit_uc->fit("mr") ;

       double floatParInitVal[10000] ;
       char   floatParName[10000][100] ;
       int nFloatParInitVal(0) ;
       RooArgList ral_floats = rfr_uc->floatParsFinal() ;
       TIterator* floatParIter = ral_floats.createIterator() ;
       {
          RooRealVar* par ;
          while ( (par = (RooRealVar*) floatParIter->Next()) ) {
             sprintf( floatParName[nFloatParInitVal], "%s", par->GetName() ) ;
             floatParInitVal[nFloatParInitVal] = par->getVal() ;
             nFloatParInitVal++ ;
          }
       }



     //-------

       printf("\n\n Unbiased best value for new POI %s is : %7.1f\n\n", new_poi_rar->GetName(), new_poi_rar->getVal() ) ;
       double best_poi_val = new_poi_rar->getVal() ;

       char minuit_formula[10000] ;
       sprintf( minuit_formula, "%s+%s*(%s-%s)*(%s-%s)",
         nll->GetName(),
         rrv_constraintWidth->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName()
          ) ;

       printf("\n\n Creating new minuit variable with formula: %s\n\n", minuit_formula ) ;
       RooFormulaVar* new_minuit_var = new RooFormulaVar("new_minuit_var", minuit_formula,
           RooArgList( *nll,
                       *rrv_constraintWidth,
                       *new_poi_rar, *rrv_poiValue,
                       *new_poi_rar, *rrv_poiValue
                       ) ) ;

       printf("\n\n Current value is %.2f\n\n",
            new_minuit_var->getVal() ) ;

       rminuit = new RooMinuit( *new_minuit_var ) ;


       RooAbsReal* plot_var = nll ;

       printf("\n\n Current value is %.2f\n\n",
            plot_var->getVal() ) ;




       rminuit->setPrintLevel(verbLevel-1) ;
       if ( verbLevel <=0 ) { rminuit->setNoWarn() ; }

    //----------------------------------------------------------------------------------------------

       //-- If POI range is -1 to -1, automatically determine the range using the set value.

       if ( poiMinVal < 0. && poiMaxVal < 0. ) {

          printf("\n\n Automatic determination of scan range.\n\n") ;

          if ( startPoiVal <= 0. ) {
             printf("\n\n *** POI starting value zero or negative %g.  Quit.\n\n\n", startPoiVal ) ;
             return ;
          }

          poiMinVal = startPoiVal - 3.5 * sqrt(startPoiVal) ;
          poiMaxVal = startPoiVal + 6.0 * sqrt(startPoiVal) ;

          if ( poiMinVal < 0. ) { poiMinVal = 0. ; }

          printf("    Start val = %g.   Scan range:   %g  to  %g\n\n", startPoiVal, poiMinVal, poiMaxVal ) ;


       }



    //----------------------------------------------------------------------------------------------


       double poiVals_scanDown[1000] ;
       double nllVals_scanDown[1000] ;

       //-- Do scan down from best value.

       printf("\n\n +++++ Starting scan down from best value.\n\n") ;

       double minNllVal(1.e9) ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          ////double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*(npoiPoints-1)) ;
          double poiValue = best_poi_val - poivi*(best_poi_val-poiMinVal)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;



          poiVals_scanDown[poivi] = new_poi_rar->getVal() ;
          nllVals_scanDown[poivi] = plot_var->getVal() ;

          if ( nllVals_scanDown[poivi] < minNllVal ) { minNllVal = nllVals_scanDown[poivi] ; }

          delete rfr ;


       } // poivi


       printf("\n\n +++++ Resetting floats to best fit values.\n\n") ;

       for ( int pi=0; pi<nFloatParInitVal; pi++ ) {
          RooRealVar* par = ws->var( floatParName[pi] ) ;
          par->setVal( floatParInitVal[pi] ) ;
       } // pi.

       printf("\n\n +++++ Starting scan up from best value.\n\n") ;

      //-- Now do scan up.

       double poiVals_scanUp[1000] ;
       double nllVals_scanUp[1000] ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          double poiValue = best_poi_val + poivi*(poiMaxVal-best_poi_val)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;

          poiVals_scanUp[poivi] = new_poi_rar->getVal() ;
          nllVals_scanUp[poivi] = plot_var->getVal() ;

          if ( nllVals_scanUp[poivi] < minNllVal ) { minNllVal = nllVals_scanUp[poivi] ; }

          delete rfr ;


       } // poivi





       double poiVals[1000] ;
       double nllVals[1000] ;

       int pointCount(0) ;
       for ( int pi=0; pi<npoiPoints/2; pi++ ) {
          poiVals[pi] = poiVals_scanDown[(npoiPoints/2-1)-pi] ;
          nllVals[pi] = nllVals_scanDown[(npoiPoints/2-1)-pi] ;
          pointCount++ ;
       }
       for ( int pi=1; pi<npoiPoints/2; pi++ ) {
          poiVals[pointCount] = poiVals_scanUp[pi] ;
          nllVals[pointCount] = nllVals_scanUp[pi] ;
          pointCount++ ;
       }
       npoiPoints = pointCount ;

       printf("\n\n --- TGraph arrays:\n") ;
       for ( int i=0; i<npoiPoints; i++ ) {
          printf("  %2d : poi = %6.1f, nll = %g\n", i, poiVals[i], nllVals[i] ) ;
       }
       printf("\n\n") ;

       double nllDiffVals[1000] ;

       double poiAtMinlnL(-1.) ;
       double poiAtMinusDelta2(-1.) ;
       double poiAtPlusDelta2(-1.) ;
       for ( int poivi=0; poivi < npoiPoints ; poivi++ ) {
          nllDiffVals[poivi] = 2.*(nllVals[poivi] - minNllVal) ;
          double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*npoiPoints) ;
          if ( nllDiffVals[poivi] < 0.01 ) { poiAtMinlnL = poiValue ; }
          if ( poiAtMinusDelta2 < 0. && nllDiffVals[poivi] < 2.5 ) { poiAtMinusDelta2 = poiValue ; }
          if ( poiAtMinlnL > 0. && poiAtPlusDelta2 < 0. && nllDiffVals[poivi] > 2.0 ) { poiAtPlusDelta2 = poiValue ; }
       } // poivi

       printf("\n\n Estimates for poi at delta ln L = -2, 0, +2:  %g ,   %g ,   %g\n\n", poiAtMinusDelta2, poiAtMinlnL, poiAtPlusDelta2 ) ;




      //--- Main canvas

       TCanvas* cscan = (TCanvas*) gDirectory->FindObject("cscan") ;
       if ( cscan == 0x0 ) {
          printf("\n Creating canvas.\n\n") ;
          cscan = new TCanvas("cscan","Delta nll") ;
       }


       char gname[1000] ;

       TGraph* graph = new TGraph( npoiPoints, poiVals, nllDiffVals ) ;
       sprintf( gname, "scan_%s", new_poi_name ) ;
       graph->SetName( gname ) ;

       double poiBest(-1.) ;
       double poiMinus1stdv(-1.) ;
       double poiPlus1stdv(-1.) ;
       double poiMinus2stdv(-1.) ;
       double poiPlus2stdv(-1.) ;
       double twoDeltalnLMin(1e9) ;

       int nscan(1000) ;
       for ( int xi=0; xi<nscan; xi++ ) {

          double x = poiVals[0] + xi*(poiVals[npoiPoints-1]-poiVals[0])/(nscan-1) ;

          double twoDeltalnL = graph -> Eval( x, 0, "S" ) ;

          if ( poiMinus1stdv < 0. && twoDeltalnL < 1.0 ) { poiMinus1stdv = x ; printf(" set m1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( poiMinus2stdv < 0. && twoDeltalnL < 4.0 ) { poiMinus2stdv = x ; printf(" set m2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnL < twoDeltalnLMin ) { poiBest = x ; twoDeltalnLMin = twoDeltalnL ; }
          if ( twoDeltalnLMin < 0.3 && poiPlus1stdv < 0. && twoDeltalnL > 1.0 ) { poiPlus1stdv = x ; printf(" set p1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnLMin < 0.3 && poiPlus2stdv < 0. && twoDeltalnL > 4.0 ) { poiPlus2stdv = x ; printf(" set p2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}

          if ( xi%100 == 0 ) { printf( " %4d : poi=%6.2f,  2DeltalnL = %6.2f\n", xi, x, twoDeltalnL ) ; }

       }
       printf("\n\n POI estimate :  %g  +%g  -%g    [%g,%g],   two sigma errors: +%g  -%g   [%g,%g]\n\n",
               poiBest,
               (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), poiMinus1stdv, poiPlus1stdv,
               (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv), poiMinus2stdv, poiPlus2stdv
               ) ;

       printf(" %s val,pm1sig,pm2sig: %7.2f  %7.2f  %7.2f  %7.2f  %7.2f\n",
          new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv) ) ;

       char htitle[1000] ;
       sprintf(htitle, "%s profile likelihood scan: -2ln(L/Lm)", new_poi_name ) ;
       TH1F* hscan = new TH1F("hscan", htitle, 10, poiMinVal, poiMaxVal ) ;
       hscan->SetMinimum(0.) ;
       hscan->SetMaximum(ymax) ;


       hscan->DrawCopy() ;
       graph->SetLineColor(4) ;
       graph->SetLineWidth(3) ;
       graph->Draw("CP") ;
       gPad->SetGridx(1) ;
       gPad->SetGridy(1) ;
       cscan->Update() ;

       TLine* line = new TLine() ;
       line->SetLineColor(2) ;
       line->DrawLine(poiMinVal, 1., poiPlus1stdv, 1.) ;
       line->DrawLine(poiMinus1stdv,0., poiMinus1stdv, 1.) ;
       line->DrawLine(poiPlus1stdv ,0., poiPlus1stdv , 1.) ;

       TText* text = new TText() ;
       text->SetTextSize(0.04) ;
       char tstring[1000] ;

       sprintf( tstring, "%s = %.1f +%.1f -%.1f", new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv) ) ;
       text -> DrawTextNDC( 0.15, 0.85, tstring ) ;

       sprintf( tstring, "68%% interval [%.1f,  %.1f]", poiMinus1stdv, poiPlus1stdv ) ;
       text -> DrawTextNDC( 0.15, 0.78, tstring ) ;


       char hname[1000] ;
       sprintf( hname, "hscanout_%s", new_poi_name ) ;
       TH1F* hsout = new TH1F( hname,"scan results",4,0.,4.) ;
       double obsVal(-1.) ;
       hsout->SetBinContent(1, obsVal ) ;
       hsout->SetBinContent(2, poiPlus1stdv ) ;
       hsout->SetBinContent(3, poiBest ) ;
       hsout->SetBinContent(4, poiMinus1stdv ) ;
       TAxis* xaxis = hsout->GetXaxis() ;
       xaxis->SetBinLabel(1,"Observed val.") ;
       xaxis->SetBinLabel(2,"Model+1sd") ;
       xaxis->SetBinLabel(3,"Model") ;
       xaxis->SetBinLabel(4,"Model-1sd") ;

       char outrootfile[10000] ;
       sprintf( outrootfile, "%s/scan-ff-%s.root", outputdir.Data(), new_poi_name ) ;

       char outpdffile[10000] ;
       sprintf( outpdffile, "%s/scan-ff-%s.pdf", outputdir.Data(), new_poi_name ) ;

       cscan->Update() ; cscan->Draw() ;

       printf("\n Saving %s\n", outpdffile ) ;
       cscan->SaveAs( outpdffile ) ;



     //--- save in root file

       printf("\n Saving %s\n", outrootfile ) ;
       TFile fout(outrootfile,"recreate") ;
       graph->Write() ;
       hsout->Write() ;
       fout.Close() ;

       delete ws ;
       wstf->Close() ;

   }
Example #20
0
int main(int argc, char* argv[]){
	std::stringstream buff;
	//=======================================
	//*************About Models**********
	double pFermi_1 = 0.24;
	double pFermi_2 = 0.8;
	double vFermi_1 = 2e-2;
	double vFermi_2 = 4.5e-4;

	//=======================================
	//*************read parameter**********
	//if (argc==1) {
	//	print_usage(argv[0]);
	//	return -1;
	//}
	init_args();
	int result;
	while((result=getopt(argc,argv,"hv:m:"))!=-1){
		switch(result){
			/* INPUTS */
			case 'm':
				strcpy(m_workMode,optarg);
				printf("work mode: %s\n",m_workMode);
				break;
			case 'v':
				verbose = atoi(optarg);
				printf("verbose level: %d\n",verbose);
				break;
			case '?':
				printf("Wrong option! optopt=%c, optarg=%s\n", optopt, optarg);
				break;
			case 'h':
			default:
				print_usage(argv[0]);
				return 1;
		}
	}

	//for (;optind<argc;optind++){
	//	m_input_files.push_back(argv[optind]);
	//}

	//=======================================
	//************Verbose Control***********
	int Verbose_SectorInfo = 5; //大概的流程情况
	std::string prefix_SectorInfo = "### ";
	int Verbose_HistInfo = 10; //有哪些hist,什么时候输出了,参数如何
	std::string prefix_HistInfo= "  [Histograms] ";
	int Verbose_Statistics = 10; //跟统计相关的(效率,分辨,粒子鉴别的情况)
	std::string prefix_Statistics="  [Statistics] ";
	int Verbose_FileInfo = 10; //有哪些FileList,都有多少file
	std::string prefix_FileInfo="  [FileInfo] ";
	int Verbose_EffInfo = 15; //Efficiency info
	std::string prefix_EffInfo="  [EffInfo] ";
	int Verbose_EventInfo = 20; //每个event的基本流程
	std::string prefix_EventInfoStart="    =>[EventInfo] ";
	std::string prefix_EventInfo="      [EventInfo] ";
	int Verbose_ParticleInfo=25; //每个particle的基本信息
	std::string prefix_ParticleInfoStart="    ->[ParticleInfo]";
	std::string prefix_ParticleInfo="      [ParticleInfo]";

	//=======================================================================================================
	//************PRESET********************
	if (verbose >= Verbose_SectorInfo ) std::cout<<prefix_SectorInfo<<"In PRESET###"<<std::endl;

	//=> About Histogram
	std::string histList = "histList";
	int index_temp;

	//=>About Constant
	double PI = 3.141592653589793238;
	double FSC = 1/137.03599911; //fine structure constant
	double M_MUON = 105.6584; //mass of muon in MeV
	double M_ELE = 0.510999; //mass of electron in MeV
	double M_U = 931.494061; //atomic mass unit in MeV

	//=>About output
	std::string OutputDir = "result/";

	//=======================================================================================================
	//************SET HISTOGRAMS********************
	if (verbose >= Verbose_SectorInfo ) std::cout<<prefix_SectorInfo<<"In SET HISTOGRAMS###"<<std::endl;
 
	//=>Read histList
	std::ifstream fin_card(histList.c_str());
	if(!fin_card){
		std::cout<<"Cannot find "<<histList<<std::endl;
	}
	std::string s_card;
	std::string histtype, histname, histtitle, dirname, runname, histdrawOpt, histxName, histyName;
	double histleft1, histright1, histleft2, histright2;
	int histbin1, histbin2, histcolor, histcompare, histlogx, histlogy, nCPU, njob, histmarker;
	std::vector<std::string> DirNames; 
	std::vector<std::string> RunNames; 
	std::vector<int> NCPU;
	std::vector<int> NJob;
	// read histList
	while(getline(fin_card,s_card)){
		if ( ISEMPTY(s_card) ) continue;
		std::vector<std::string> segments;
		seperate_string(s_card,segments,'|');
		int iterator = 1;
		if ( segments[0] == "TH1D" ){
			if(iterator<segments.size()) nameForH1D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) titleForH1D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) xNameForH1D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) yNameForH1D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) bin1ForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) left1ForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) right1ForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) minxForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) minyForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) colorForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) compareForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) xlogForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) ylogForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) markerForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) drawOptForH1D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
		}
		else if ( segments[0] == "TH2D" ){
			if(iterator<segments.size()) nameForH2D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) titleForH2D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) xNameForH2D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) yNameForH2D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) bin1ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) left1ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) right1ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) bin2ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) left2ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) right2ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
		}
		else if ( segments[0] == "FILE" ){
			if(iterator<segments.size()) DirNames.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			std::string runname;
			if(iterator<segments.size()) runname = "_"+segments[iterator++]; else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if (runname=="_"){
				RunNames.push_back("");
			}
			else{
				RunNames.push_back(runname);
			}
			if(iterator<segments.size()) NCPU.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) NJob.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
		}
		else if ( segments[0] == "TGraph" ){
			if(iterator<segments.size()) nameForGraph.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) titleForGraph.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) xNameForGraph.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) yNameForGraph.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			std::vector<double> avec;
			xForGraph.push_back(avec);
			std::vector<double> bvec;
			yForGraph.push_back(bvec);
			if(iterator<segments.size()) colorForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) compareForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) minxForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) maxxForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) minyForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) xlogForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) ylogForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) markerForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) drawOptForGraph.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			int i = nameForGraph.size() - 1;
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"Input vecGraph["<<i<<"]: "<<nameForGraph[i]<<", "<<titleForGraph[i]<<", "<<xNameForGraph[i]<<", "<<yNameForGraph[i]<<", Color="<<colorForGraph[i]<<", xlogSyle="<<xlogForGraph[i]<<", ylogSyle="<<ylogForGraph[i]<<", nCompare="<<compareForGraph[i]<<", markerStyle="<<markerForGraph[i]<<", drawOpt=\""<<drawOptForGraph[i]<<"\""<<std::endl;
		}
		else{
			std::cout<<"Cannot recogonize this line: "<<s_card<<std::endl;
			continue;
		}
	}

	//=> Get histograms in
	for ( int i = 0; i < nameForH2D.size(); i++ ){
		vecH2D.push_back(new TH2D(nameForH2D[i],titleForH2D[i],bin1ForH2D[i],left1ForH2D[i],right1ForH2D[i],bin2ForH2D[i],left2ForH2D[i],right2ForH2D[i]) );
	}
	for ( int i = 0; i < nameForH1D.size(); i++ ){
		vecH1D.push_back(new TH1D(nameForH1D[i],titleForH1D[i],bin1ForH1D[i],left1ForH1D[i],right1ForH1D[i]) );
	}

	//=======================================================================================================
	//************SET Statistics********************
	if (verbose >= Verbose_SectorInfo ) std::cout<<prefix_SectorInfo<<"In SET Statistics###"<<std::endl;

	//=>About Statistical
	int N0 = 0;
	int N1 = 0;
	int N2 = 0;
	int N3 = 0;

	//=======================================================================================================
	//************DO THE DIRTY WORK*******************
	if (verbose >= Verbose_SectorInfo) std::cout<<prefix_SectorInfo<<"In DO THE DIRTY WORK ###"<<std::endl;

	//loop in events
	int nbin = 120;
	if ( (index_temp = get_TH1D("h")) != -1 ){
		nbin = bin1ForH1D[index_temp];
	}
	for( int ibin = 1; ibin <= nbin; ibin++ ){
		if (verbose >= Verbose_EventInfo ) std::cout<<prefix_EventInfoStart<<"In Event "<<ibin<<std::endl;
		N0++;
		// Generate a nucleon
		double pFermi_left = 0;
		double pFermi_right = pFermi_2;
		if ( (index_temp = get_TH1D("h")) != -1 ){
			pFermi_left = left1ForH1D[index_temp];
			pFermi_right = right1ForH1D[index_temp];
		}
		double pFermi = pFermi_left + (pFermi_right-pFermi_left)*(ibin-1)/((double)nbin);
		double weight = 0;
		if ( pFermi < pFermi_1 ) weight = 1;
		else {
			weight = vFermi_1 * pow(vFermi_2/vFermi_1,(pFermi-pFermi_1)/(pFermi_2-pFermi_1));
		}
		if ( (index_temp = get_TH1D("h")) != -1 ){
			vecH1D[index_temp]->SetBinContent(ibin,weight);
		}
		if ( (index_temp = get_TH1D("h_log")) != -1 ){
			vecH1D[index_temp]->SetBinContent(ibin,weight);
		}

		if (verbose >= Verbose_EventInfo ) std::cout<<prefix_EventInfo<<"Finished!"<<std::endl;
	}/* end of loop in events*/

	//=======================================================================================================

	//=======================================================================================================
	//************WRITE AND OUTPUT********************
	if (verbose >= Verbose_SectorInfo) std::cout<<prefix_SectorInfo<<"In WRITE AND OUTPUT ###"<<std::endl;
	std::string outputFileName = OutputDir + "output.root";
	TFile *file = new TFile(outputFileName.c_str(),"RECREATE");
	std::cout<<"N0 = "<<N0<<std::endl;
	std::cout<<"N1 = "<<N1<<std::endl;
	std::cout<<"N2 = "<<N2<<std::endl;
	std::cout<<"N3 = "<<N3<<std::endl;

	gStyle->SetPalette(1);
	gStyle->SetOptStat(0);
	gStyle->SetPadTickX(1);
	gStyle->SetPadTickY(1);
	//  gStyle->SetTitleW(0.99);
	//  gStyle->SetTitleH(0.08);
	//Output these histograms
	for ( int i = 0; i < vecH1D.size(); i++ ){
		if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"Output vecH1D["<<i<<"]: "<<nameForH1D[i]<<", "<<titleForH1D[i]<<", "<<xNameForH1D[i]<<", "<<yNameForH1D[i]<<", "<<bin1ForH1D[i]<<", "<<left1ForH1D[i]<<", "<<right1ForH1D[i]<<", Color="<<colorForH1D[i]<<", xlogSyle="<<xlogForH1D[i]<<", ylogSyle="<<ylogForH1D[i]<<", nCompare="<<compareForH1D[i]<<", markerStyle="<<markerForH1D[i]<<", drawOpt=\""<<drawOptForH1D[i]<<"\""<<std::endl;
		vecH1D[i]->SetLineColor(colorForH1D[i]);
		TString name = vecH1D[i]->GetName();
		TCanvas* c = new TCanvas(name);
		int nCompare = compareForH1D[i];
		if ( nCompare ) if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<nCompare<<" histograms to be compared"<<std::endl;
		double currentMaximum = vecH1D[i]->GetMaximum();
		for ( int j = 1; j <= nCompare; j++ ){
			double maximum = vecH1D[i+j]->GetMaximum();
			if ( maximum > currentMaximum ){
				currentMaximum = maximum;
			}
		}
		if ( nCompare ) if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"  maximum y value is ("<<currentMaximum<<")"<<std::endl;
		if ( xlogForH1D[i] ) gPad->SetLogx(1);
		else gPad->SetLogx(0);
		if ( ylogForH1D[i] ) gPad->SetLogy(1);
		else gPad->SetLogy(0);
		if ( xlogForH1D[i] ) vecH1D[i]->GetXaxis()->SetRangeUser(minxForH1D[i],right1ForH1D[i]);
		else vecH1D[i]->GetXaxis()->SetRangeUser(left1ForH1D[i],right1ForH1D[i]);
		if ( ylogForH1D[i] ) vecH1D[i]->GetYaxis()->SetRangeUser(minyForH1D[i],2*currentMaximum);
		else vecH1D[i]->GetYaxis()->SetRangeUser(left1ForH1D[i],1.05*currentMaximum);
		vecH1D[i]->SetMarkerStyle(markerForH1D[i]);
		vecH1D[i]->SetMarkerColor(colorForH1D[i]);
		vecH1D[i]->SetLineColor(colorForH1D[i]);
		vecH1D[i]->GetXaxis()->SetTitle(xNameForH1D[i]);
		vecH1D[i]->GetYaxis()->SetTitle(yNameForH1D[i]);
		vecH1D[i]->Draw(drawOptForH1D[i]);
		vecH1D[i]->Write();
		for ( int j = 0; j < nCompare; j++ ){
			i++;
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<" ->"<<j<<", vecH1D["<<i<<"]: "<<nameForH1D[i]<<", "<<titleForH1D[i]<<", "<<xNameForH1D[i]<<", "<<yNameForH1D[i]<<", "<<bin1ForH1D[i]<<", "<<left1ForH1D[i]<<", "<<right1ForH1D[i]<<", Color="<<colorForH1D[i]<<", xlogSyle="<<xlogForH1D[i]<<", ylogSyle="<<ylogForH1D[i]<<", nCompare="<<compareForH1D[i]<<", markerStyle="<<markerForH1D[i]<<", drawOpt=\""<<drawOptForH1D[i]<<"\""<<std::endl;
			vecH1D[i]->SetLineColor(colorForH1D[i]);
			vecH1D[i]->SetMarkerStyle(markerForH1D[i]);
			vecH1D[i]->SetMarkerColor(colorForH1D[i]);
			vecH1D[i]->SetLineColor(colorForH1D[i]);
			TString drawOpt = drawOptForH1D[i]+"SAME";
			vecH1D[i]->Draw(drawOpt);
		}
		TString fileName = OutputDir + name + ".pdf";
		c->Print(fileName);
	}
	gStyle->SetOptStat(0);
	for ( int i = 0; i < vecH2D.size(); i++ ){
		if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"Output vecH2D["<<i<<"]: "<<nameForH2D[i]<<", "<<titleForH2D[i]<<", "<<xNameForH2D[i]<<", "<<yNameForH2D[i]<<", "<<bin1ForH2D[i]<<", "<<left1ForH2D[i]<<", "<<right1ForH2D[i]<<", "<<bin2ForH2D[i]<<", "<<left2ForH2D[i]<<", "<<right2ForH2D[i]<<std::endl;
		TString name = vecH2D[i]->GetName();
		TCanvas* c = new TCanvas(name);
		vecH2D[i]->GetXaxis()->SetTitle(xNameForH2D[i]);
		vecH2D[i]->GetYaxis()->SetTitle(yNameForH2D[i]);
		vecH2D[i]->Draw("COLZ");
		vecH2D[i]->Write();
		TString fileName = OutputDir + name + ".pdf";
		c->Print(fileName);
	}
	for ( int i = 0; i < nameForGraph.size(); i++ ){
		int sizeOfThisGraph = xForGraph[i].size();
		if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"Output vecGraph["<<i<<"]: "<<nameForGraph[i]<<", "<<titleForGraph[i]<<", "<<xNameForGraph[i]<<", "<<yNameForGraph[i]<<", Color="<<colorForGraph[i]<<", xlogSyle="<<xlogForGraph[i]<<", ylogSyle="<<ylogForGraph[i]<<", nCompare="<<compareForGraph[i]<<", markerStyle="<<markerForGraph[i]<<", drawOpt=\""<<drawOptForGraph[i]<<"\", size = "<<sizeOfThisGraph<<std::endl;
		if ( sizeOfThisGraph <= 0 ) continue;
		if (verbose >= Verbose_HistInfo){
			for ( int j = 0; j < sizeOfThisGraph; j++ ){
				std::cout<<prefix_HistInfo<<"  ["<<j<<"]: ("<<xForGraph[i][j]<<","<<yForGraph[i][j]<<")"<<std::endl;
			}
		}
		TString name = nameForGraph[i];
		TCanvas* c = new TCanvas(nameForGraph[i]);
		TGraph *aTGraph = new TGraph(sizeOfThisGraph,&xForGraph[i][0],&yForGraph[i][0]);
		aTGraph->SetTitle(titleForGraph[i]);
		int nCompare = compareForGraph[i];
		if ( nCompare ) if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<nCompare<<" graphs to be compared"<<std::endl;
		std::vector<double> yforgraph = yForGraph[i];
		std::vector<double> xforgraph = xForGraph[i];
		double currentMaximum = *std::max_element(yforgraph.begin(),yforgraph.end());
		for ( int j = 1; j <= nCompare; j++ ){
			double maximum = *std::max_element(yForGraph[i+j].begin(),yForGraph[i+j].end());
			if ( maximum > currentMaximum ){
				currentMaximum = maximum;
			}
		}
		if ( nCompare ) if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"  maximum y value is ("<<currentMaximum<<")"<<std::endl;
		if ( xlogForGraph[i] ) gPad->SetLogx(1);
		else gPad->SetLogx(0);
		if ( ylogForGraph[i] ) gPad->SetLogy(1);
		else gPad->SetLogy(0);
		if ( xlogForGraph[i] ) aTGraph->GetXaxis()->SetRangeUser(minxForGraph[i],2*maxxForGraph[i]);
		else aTGraph->GetXaxis()->SetRangeUser(minxForGraph[i],1.05*maxxForGraph[i]);
		if ( ylogForGraph[i] ) aTGraph->GetYaxis()->SetRangeUser(minyForGraph[i],2*currentMaximum);
		else aTGraph->GetYaxis()->SetRangeUser(minyForGraph[i],1.05*currentMaximum);
		aTGraph->GetXaxis()->SetTitle(xNameForGraph[i]);
		aTGraph->GetYaxis()->SetTitle(yNameForGraph[i]);
		aTGraph->SetMarkerStyle(markerForGraph[i]);
		aTGraph->SetMarkerColor(colorForGraph[i]);
		aTGraph->SetLineColor(colorForGraph[i]);
		TString drawOpt = "A"+drawOptForGraph[i];
		aTGraph->Draw(drawOpt);
		aTGraph->Write();
		for ( int j = 0; j < nCompare; j++ ){
			i++;
			int sizeOfThisGraph = xForGraph[i].size();
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<" ->"<<j<<", vecGraph["<<i<<"]: "<<nameForGraph[i]<<", "<<titleForGraph[i]<<", "<<xNameForGraph[i]<<", "<<yNameForGraph[i]<<", Color="<<colorForGraph[i]<<", xlogSyle="<<xlogForGraph[i]<<", ylogSyle="<<ylogForGraph[i]<<", nCompare="<<compareForGraph[i]<<", markerStyle="<<markerForGraph[i]<<", drawOpt=\""<<drawOptForGraph[i]<<"\", size = "<<sizeOfThisGraph<<std::endl;
			if ( sizeOfThisGraph <= 0 ) continue;
			if (verbose >= Verbose_HistInfo){
				for ( int k = 0; k < sizeOfThisGraph; k++ ){
					std::cout<<prefix_HistInfo<<"  ["<<k<<"]: ("<<xForGraph[i][k]<<","<<yForGraph[i][k]<<")"<<std::endl;
				}
			}
			TGraph *bTGraph = new TGraph(sizeOfThisGraph,&xForGraph[i][0],&yForGraph[i][0]);
			bTGraph->SetTitle(titleForGraph[i]);
			bTGraph->GetXaxis()->SetTitle(xNameForGraph[i]);
			bTGraph->GetYaxis()->SetTitle(yNameForGraph[i]);
			bTGraph->SetLineColor(colorForGraph[i]);
			bTGraph->SetMarkerStyle(markerForGraph[i]);
			bTGraph->SetMarkerColor(colorForGraph[i]);
			bTGraph->SetLineColor(colorForGraph[i]);
			bTGraph->Draw(drawOptForGraph[i]);
			bTGraph->Write();
		}
		TString fileName = OutputDir + name + ".pdf";
		c->Print(fileName);
	}

	//TTree *m_TTree = m_TChain->CloneTree();
	//m_TTree->Write();
	//file->Write();
	file->Close();

	delete file;
	return 0;
}
Example #21
0
void make_SMS_exclusion(TH2F *rawlimits,TH2F *xsec,int scantype,std::string& scanx, bool isobserved) {
  TH2F *limits = prep_histo(rawlimits,scantype); // this is to be independent of the style used at creation time
  //here we get some limits and the cross section; we want to make an exclusion plot!
  TH2F *rellimits = (TH2F*)limits->Clone("rellimits");
  TH2F *rellimitsd3 = (TH2F*)limits->Clone("rellimitsd3"); // one third the cross section ("divided by 3" -> d3)
  TH2F *rellimitst3 = (TH2F*)limits->Clone("rellimitst3"); // three times the cross section ("times 3" -> t3)
  
  if(!xsec ) {
    cout << "Watch out, cross section map is invalid!" << endl;
    delete limits;
    return;
  }
  
  rellimits->Divide(xsec);
  
  
  for(int i=1;i<=rellimits->GetNbinsX();i++) {
    for(int j=1;j<=rellimits->GetNbinsY();j++) {
      rellimitst3->SetBinContent(i,j,(rellimits->GetBinContent(i,j))/3.0);
      rellimitsd3->SetBinContent(i,j,(rellimits->GetBinContent(i,j))*3.0);
    }
  }
  

//  TH2F *exclusionshape = make_exclusion_shape(rellimits,1);
//  TH2F *exclusionshapet3 = make_exclusion_shape(rellimitst3,2);
//  TH2F *exclusionshaped3 = make_exclusion_shape(rellimitsd3,3);
  
  //Now let's produce the plots!
  
  set_range(xsec,scantype,false);
  set_range(limits,scantype,false);
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  
  bool drawdoubleline=false; //draw nice thin line on top of thick outer line
  TGraph *exclline = MarcosExclusionLine(rellimits, scantype);
  TGraph *thinexcline = thin_line(exclline);
  
  TGraph *excllinet3 = MarcosExclusionLine(rellimitst3, scantype);
  excllinet3->SetLineStyle(2);
  TGraph *thinexclinet3 = thin_line(excllinet3);

  TGraph *excllined3 = MarcosExclusionLine(rellimitsd3, scantype);
  excllined3->SetLineStyle(3);
  TGraph *thinexclined3 = thin_line(excllined3);

//  produce_extensive_plots(xsec,limits,rellimits, rellimitst3, rellimitsd3,scantype);
  
  TCanvas *finalcanvas = new TCanvas("finalcanvas","finalcanvas");
  finalcanvas->SetLogz(1);
  finalcanvas->cd();
  limits->SetZTitle("95% CL upper limit on #sigma [pb]");
  limits->Draw("COLZ");

  TLine *desertline;
  if(drawefficiencydesertline) {
	desertline = new TLine(375,50,1200,875);
	desertline->SetLineWidth(3);
	//desertline->SetLineWidth(4); // paper style
	desertline->SetLineColor(kBlack);
	desertline->Draw("same");
  }


//  fill_with_text(exclline,excllined3,excllinet3,finalcanvas,scantype,scanx);
  stringstream real;
  real << "Limits/";
  if(!isobserved) real << "expected/expected_";
  real << "final_exclusion__" << limits->GetName();
  
  if(Contains(limits->GetName(),"bestlimits")) {
    cout << "----------> " << limits->GetName() << endl;
    TFile *f = new TFile("limits.root","RECREATE");
    thinexcline->SetName("ExclusionLine");
    limits->SetName("UpperLimits");
    limits->Write();
    thinexcline->Write();
    f->Close();
  }
  
  
  exclline->Draw("l");
  if(drawdoubleline) thinexcline->Draw("");
  excllinet3->Draw("");
  if(drawdoubleline) thinexclinet3->Draw("");
  excllined3->Draw("");
  if(drawdoubleline) thinexclined3->Draw("");
  
  CompleteSave(finalcanvas,real.str());

  
  
  //-------------------------------------- extensive plots 
  
  TCanvas *ca = new TCanvas("ca","ca",2400,1200);
  ca->Divide(4,2);
  ca->cd(1);
  ca->cd(1)->SetLogz(1);
  xsec->GetZaxis()->SetRangeUser(0.001,1000);
  xsec->Draw("COLZ");
  TText *title0 = write_title("Reference Cross Section");
  title0->Draw("same");
  ca->cd(2);
  ca->cd(2)->SetLogz(1);
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  limits->Draw("COLZ");
  TText *title = write_title("Cross Section Upper Limit");
  title->Draw("same");
  ca->cd(3);
  ca->cd(3)->SetLogz(1);
  TH2F *limit_ref = (TH2F*)limits->Clone("limit_ref");
  limit_ref->Divide(xsec);
  limit_ref->GetZaxis()->SetRangeUser(limits_ratio_lower_bound,limits_ratio_upper_bound);
  limit_ref->Draw("COLZ");
  TText *title2 = write_title("Cross Section UL / XS");
  title2->Draw("same");
  ca->cd(4);
  ca->cd(4)->SetLogz(1);
  limits->SetTitle("");
  limits->GetZaxis()->SetRangeUser(limits_lower_bound,limits_upper_bound);
  limits->SetZTitle("95% CL upper limit on #sigma [pb]");

  limits->Draw("COLZ");


  ca->cd(4);
  exclline->Draw();
  thinexcline->Draw();
  excllinet3->Draw();
  thinexclinet3->Draw();
  excllined3->Draw();
  thinexclined3->Draw();
  stringstream partial;
  partial << "Limits/";
  if(!isobserved) real << "expected/expected_";
  partial << "exclusion__" << limits->GetName();
  fill_with_text(exclline,excllined3,excllinet3,ca->cd(4),scantype);
//  CompleteSave(ca,partial.str());

  ca->cd(5);
  (hardlimit(rellimitsd3))->Draw("COL");
  TText *c = write_title("Exclusion shape for #sigma_{ref}/3");
  c->Draw();
  excllined3->Draw("same");
  
  ca->cd(6);
  (hardlimit(rellimits))->Draw("COL");
  exclline->Draw("same");
  TText *b = write_title("Exclusion shape for #sigma_{ref}");
  b->Draw();
  
  ca->cd(7);
  (hardlimit(rellimitst3))->Draw("COL");
  excllinet3->Draw("same");
  TText *a = write_title("Exclusion shape for 3x#sigma_{ref}");
  a->Draw();
  
  CompleteSave(ca,partial.str()+"__PlusInfo");
  delete ca;
  delete limits;
  
  //---------------------------------------</extensive plots>
  delete finalcanvas;
}
Example #22
0
   void constrained_scan( const char* wsfile = "outputfiles/ws.root",
                          const char* new_poi_name="mu_bg_4b_msig_met1",
                          double constraintWidth=1.5,
                          int npoiPoints = 20,
                          double poiMinVal = 0.,
                          double poiMaxVal = 10.0,
                          double ymax = 9.,
                          int verbLevel=1  ) {

      TString outputdir("outputfiles") ;

      gStyle->SetOptStat(0) ;

      TFile* wstf = new TFile( wsfile ) ;
      RooWorkspace* ws = dynamic_cast<RooWorkspace*>( wstf->Get("ws") );
      ws->Print() ;

      RooDataSet* rds = (RooDataSet*) ws->obj( "hbb_observed_rds" ) ;
      cout << "\n\n\n  ===== RooDataSet ====================\n\n" << endl ;
      rds->Print() ;
      rds->printMultiline(cout, 1, kTRUE, "") ;

      RooRealVar* rv_sig_strength = ws->var("sig_strength") ;
      if ( rv_sig_strength == 0x0 ) { printf("\n\n *** can't find sig_strength in workspace.\n\n" ) ; return ; }

      RooAbsPdf* likelihood = ws->pdf("likelihood") ;
      if ( likelihood == 0x0 ) { printf("\n\n *** can't find likelihood in workspace.\n\n" ) ; return ; }
      printf("\n\n Likelihood:\n") ;
      likelihood -> Print() ;



      /////rv_sig_strength -> setConstant( kFALSE ) ;
      rv_sig_strength -> setVal(0.) ;
      rv_sig_strength -> setConstant( kTRUE ) ;

      likelihood->fitTo( *rds, Save(false), PrintLevel(0), Hesse(true), Strategy(1) ) ;
      //RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0), Hesse(true), Strategy(1) ) ;
      //double minNllSusyFloat = fitResult->minNll() ;
      //double susy_ss_atMinNll = rv_sig_strength -> getVal() ;

      RooMsgService::instance().getStream(1).removeTopic(Minimization) ;
      RooMsgService::instance().getStream(1).removeTopic(Fitting) ;



     //-- Construct the new POI parameter.
      RooAbsReal* new_poi_rar(0x0) ;

      new_poi_rar = ws->var( new_poi_name ) ;
      if ( new_poi_rar == 0x0 ) {
         printf("\n\n New POI %s is not a variable.  Trying function.\n\n", new_poi_name ) ;
         new_poi_rar = ws->function( new_poi_name ) ;
         if ( new_poi_rar == 0x0 ) {
            printf("\n\n New POI %s is not a function.  I quit.\n\n", new_poi_name ) ;
            return ;
         } else {
            printf("\n Found it.\n\n") ;
         }
      } else {
         printf("\n\n     New POI %s is a variable with current value %.1f.\n\n", new_poi_name, new_poi_rar->getVal() ) ;
      }

       double startPoiVal = new_poi_rar->getVal() ;


       RooAbsReal* nll = likelihood -> createNLL( *rds, Verbose(true) ) ;

       RooRealVar* rrv_poiValue = new RooRealVar( "poiValue", "poiValue", 0., -10000., 10000. ) ;

       RooRealVar* rrv_constraintWidth = new RooRealVar("constraintWidth","constraintWidth", 0.1, 0.1, 1000. ) ;
       rrv_constraintWidth -> setVal( constraintWidth ) ;
       rrv_constraintWidth -> setConstant(kTRUE) ;


       RooMinuit* rminuit( 0x0 ) ;


       RooMinuit* rminuit_uc = new RooMinuit( *nll  ) ;

       rminuit_uc->setPrintLevel(verbLevel-1) ;
       rminuit_uc->setNoWarn() ;

       rminuit_uc->migrad() ;
       rminuit_uc->hesse() ;

       RooFitResult* rfr_uc = rminuit_uc->fit("mr") ;

       double floatParInitVal[10000] ;
       char   floatParName[10000][100] ;
       int nFloatParInitVal(0) ;
       RooArgList ral_floats = rfr_uc->floatParsFinal() ;
       TIterator* floatParIter = ral_floats.createIterator() ;
       {
          RooRealVar* par ;
          while ( (par = (RooRealVar*) floatParIter->Next()) ) {
             sprintf( floatParName[nFloatParInitVal], "%s", par->GetName() ) ;
             floatParInitVal[nFloatParInitVal] = par->getVal() ;
             nFloatParInitVal++ ;
          }
       }


       printf("\n\n Unbiased best value for new POI %s is : %7.1f\n\n", new_poi_rar->GetName(), new_poi_rar->getVal() ) ;
       double best_poi_val = new_poi_rar->getVal() ;

       char minuit_formula[10000] ;
       sprintf( minuit_formula, "%s+%s*(%s-%s)*(%s-%s)",
         nll->GetName(),
         rrv_constraintWidth->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName()
          ) ;

       printf("\n\n Creating new minuit variable with formula: %s\n\n", minuit_formula ) ;
       RooFormulaVar* new_minuit_var = new RooFormulaVar("new_minuit_var", minuit_formula,
           RooArgList( *nll,
                       *rrv_constraintWidth,
                       *new_poi_rar, *rrv_poiValue,
                       *new_poi_rar, *rrv_poiValue
                       ) ) ;

       printf("\n\n Current value is %.2f\n\n",
            new_minuit_var->getVal() ) ;

       rminuit = new RooMinuit( *new_minuit_var ) ;


       RooAbsReal* plot_var = nll ;

       printf("\n\n Current value is %.2f\n\n",
            plot_var->getVal() ) ;


       rminuit->setPrintLevel(verbLevel-1) ;
       if ( verbLevel <=0 ) { rminuit->setNoWarn() ; }


       if ( poiMinVal < 0. && poiMaxVal < 0. ) {

          printf("\n\n Automatic determination of scan range.\n\n") ;

          if ( startPoiVal <= 0. ) {
             printf("\n\n *** POI starting value zero or negative %g.  Quit.\n\n\n", startPoiVal ) ;
             return ;
          }

          poiMinVal = startPoiVal - 3.5 * sqrt(startPoiVal) ;
          poiMaxVal = startPoiVal + 6.0 * sqrt(startPoiVal) ;

          if ( poiMinVal < 0. ) { poiMinVal = 0. ; }

          printf("    Start val = %g.   Scan range:   %g  to  %g\n\n", startPoiVal, poiMinVal, poiMaxVal ) ;


       }



    //----------------------------------------------------------------------------------------------


       double poiVals_scanDown[1000] ;
       double nllVals_scanDown[1000] ;

       //-- Do scan down from best value.

       printf("\n\n +++++ Starting scan down from best value.\n\n") ;

       double minNllVal(1.e9) ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          ////double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*(npoiPoints-1)) ;
          double poiValue = best_poi_val - poivi*(best_poi_val-poiMinVal)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;



          poiVals_scanDown[poivi] = new_poi_rar->getVal() ;
          nllVals_scanDown[poivi] = plot_var->getVal() ;

          if ( nllVals_scanDown[poivi] < minNllVal ) { minNllVal = nllVals_scanDown[poivi] ; }

          delete rfr ;


       } // poivi


       printf("\n\n +++++ Resetting floats to best fit values.\n\n") ;

       for ( int pi=0; pi<nFloatParInitVal; pi++ ) {
          RooRealVar* par = ws->var( floatParName[pi] ) ;
          par->setVal( floatParInitVal[pi] ) ;
       } // pi.

       printf("\n\n +++++ Starting scan up from best value.\n\n") ;

      //-- Now do scan up.

       double poiVals_scanUp[1000] ;
       double nllVals_scanUp[1000] ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          double poiValue = best_poi_val + poivi*(poiMaxVal-best_poi_val)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;

          poiVals_scanUp[poivi] = new_poi_rar->getVal() ;
          nllVals_scanUp[poivi] = plot_var->getVal() ;

          if ( nllVals_scanUp[poivi] < minNllVal ) { minNllVal = nllVals_scanUp[poivi] ; }

          delete rfr ;


       } // poivi





       double poiVals[1000] ;
       double nllVals[1000] ;

       int pointCount(0) ;
       for ( int pi=0; pi<npoiPoints/2; pi++ ) {
          poiVals[pi] = poiVals_scanDown[(npoiPoints/2-1)-pi] ;
          nllVals[pi] = nllVals_scanDown[(npoiPoints/2-1)-pi] ;
          pointCount++ ;
       }
       for ( int pi=1; pi<npoiPoints/2; pi++ ) {
          poiVals[pointCount] = poiVals_scanUp[pi] ;
          nllVals[pointCount] = nllVals_scanUp[pi] ;
          pointCount++ ;
       }
       npoiPoints = pointCount ;

       printf("\n\n --- TGraph arrays:\n") ;
       for ( int i=0; i<npoiPoints; i++ ) {
          printf("  %2d : poi = %6.1f, nll = %g\n", i, poiVals[i], nllVals[i] ) ;
       }
       printf("\n\n") ;

       double nllDiffVals[1000] ;

       double poiAtMinlnL(-1.) ;
       double poiAtMinusDelta2(-1.) ;
       double poiAtPlusDelta2(-1.) ;
       for ( int poivi=0; poivi < npoiPoints ; poivi++ ) {
          nllDiffVals[poivi] = 2.*(nllVals[poivi] - minNllVal) ;
          double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*npoiPoints) ;
          if ( nllDiffVals[poivi] < 0.01 ) { poiAtMinlnL = poiValue ; }
          if ( poiAtMinusDelta2 < 0. && nllDiffVals[poivi] < 2.5 ) { poiAtMinusDelta2 = poiValue ; }
          if ( poiAtMinlnL > 0. && poiAtPlusDelta2 < 0. && nllDiffVals[poivi] > 2.0 ) { poiAtPlusDelta2 = poiValue ; }
       } // poivi

       printf("\n\n Estimates for poi at delta ln L = -2, 0, +2:  %g ,   %g ,   %g\n\n", poiAtMinusDelta2, poiAtMinlnL, poiAtPlusDelta2 ) ;




      //--- Main canvas

       TCanvas* cscan = (TCanvas*) gDirectory->FindObject("cscan") ;
       if ( cscan == 0x0 ) {
          printf("\n Creating canvas.\n\n") ;
          cscan = new TCanvas("cscan","Delta nll") ;
       }


       char gname[1000] ;

       TGraph* graph = new TGraph( npoiPoints, poiVals, nllDiffVals ) ;
       sprintf( gname, "scan_%s", new_poi_name ) ;
       graph->SetName( gname ) ;

       double poiBest(-1.) ;
       double poiMinus1stdv(-1.) ;
       double poiPlus1stdv(-1.) ;
       double poiMinus2stdv(-1.) ;
       double poiPlus2stdv(-1.) ;
       double twoDeltalnLMin(1e9) ;

       int nscan(1000) ;
       for ( int xi=0; xi<nscan; xi++ ) {

          double x = poiVals[0] + xi*(poiVals[npoiPoints-1]-poiVals[0])/(nscan-1) ;

          double twoDeltalnL = graph -> Eval( x, 0, "S" ) ;

          if ( poiMinus1stdv < 0. && twoDeltalnL < 1.0 ) { poiMinus1stdv = x ; printf(" set m1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( poiMinus2stdv < 0. && twoDeltalnL < 4.0 ) { poiMinus2stdv = x ; printf(" set m2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnL < twoDeltalnLMin ) { poiBest = x ; twoDeltalnLMin = twoDeltalnL ; }
          if ( twoDeltalnLMin < 0.3 && poiPlus1stdv < 0. && twoDeltalnL > 1.0 ) { poiPlus1stdv = x ; printf(" set p1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnLMin < 0.3 && poiPlus2stdv < 0. && twoDeltalnL > 4.0 ) { poiPlus2stdv = x ; printf(" set p2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}

          if ( xi%100 == 0 ) { printf( " %4d : poi=%6.2f,  2DeltalnL = %6.2f\n", xi, x, twoDeltalnL ) ; }

       }
       printf("\n\n POI estimate :  %g  +%g  -%g    [%g,%g],   two sigma errors: +%g  -%g   [%g,%g]\n\n",
               poiBest,
               (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), poiMinus1stdv, poiPlus1stdv,
               (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv), poiMinus2stdv, poiPlus2stdv
               ) ;

       printf(" %s val,pm1sig,pm2sig: %7.2f  %7.2f  %7.2f  %7.2f  %7.2f\n",
          new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv) ) ;

       char htitle[1000] ;
       sprintf(htitle, "%s profile likelihood scan: -2ln(L/Lm)", new_poi_name ) ;
       TH1F* hscan = new TH1F("hscan", htitle, 10, poiMinVal, poiMaxVal ) ;
       hscan->SetMinimum(0.) ;
       hscan->SetMaximum(ymax) ;


       hscan->DrawCopy() ;
       graph->SetLineColor(4) ;
       graph->SetLineWidth(3) ;
       graph->Draw("CP") ;
       gPad->SetGridx(1) ;
       gPad->SetGridy(1) ;
       cscan->Update() ;

       TLine* line = new TLine() ;
       line->SetLineColor(2) ;
       line->DrawLine(poiMinVal, 1., poiPlus1stdv, 1.) ;
       line->DrawLine(poiMinus1stdv,0., poiMinus1stdv, 1.) ;
       line->DrawLine(poiPlus1stdv ,0., poiPlus1stdv , 1.) ;

       TText* text = new TText() ;
       text->SetTextSize(0.04) ;
       char tstring[1000] ;

       sprintf( tstring, "%s = %.1f +%.1f -%.1f", new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv) ) ;
       text -> DrawTextNDC( 0.15, 0.85, tstring ) ;

       sprintf( tstring, "68%% interval [%.1f,  %.1f]", poiMinus1stdv, poiPlus1stdv ) ;
       text -> DrawTextNDC( 0.15, 0.78, tstring ) ;


       char hname[1000] ;
       sprintf( hname, "hscanout_%s", new_poi_name ) ;
       TH1F* hsout = new TH1F( hname,"scan results",4,0.,4.) ;
       double obsVal(-1.) ;
       hsout->SetBinContent(1, obsVal ) ;
       hsout->SetBinContent(2, poiPlus1stdv ) ;
       hsout->SetBinContent(3, poiBest ) ;
       hsout->SetBinContent(4, poiMinus1stdv ) ;
       TAxis* xaxis = hsout->GetXaxis() ;
       xaxis->SetBinLabel(1,"Observed val.") ;
       xaxis->SetBinLabel(2,"Model+1sd") ;
       xaxis->SetBinLabel(3,"Model") ;
       xaxis->SetBinLabel(4,"Model-1sd") ;

       char outrootfile[10000] ;
       sprintf( outrootfile, "%s/scan-ff-%s.root", outputdir.Data(), new_poi_name ) ;

       char outpdffile[10000] ;
       sprintf( outpdffile, "%s/scan-ff-%s.pdf", outputdir.Data(), new_poi_name ) ;

       cscan->Update() ; cscan->Draw() ;

       printf("\n Saving %s\n", outpdffile ) ;
       cscan->SaveAs( outpdffile ) ;



     //--- save in root file

       printf("\n Saving %s\n", outrootfile ) ;
       TFile fout(outrootfile,"recreate") ;
       graph->Write() ;
       hsout->Write() ;
       fout.Close() ;

       delete ws ;
       wstf->Close() ;




   } // constrained_scan.
Example #23
0
//______________________________________________________________________________
void CheckPulsers(const Char_t* loc)
{
    // Some old pedestal checking method.

    Char_t t[256];

    // number of runs
    Int_t nRuns = gFiles->GetSize();

    // number of channels
    Int_t nCh = gReadAR->GetNelements();

    // create arrays
    Double_t** pedPos = new Double_t*[nCh];
    Double_t* runNumbersD = new Double_t[nRuns];
    for (Int_t i = 0; i < nCh; i++) pedPos[i] = new Double_t[nRuns];

    // open the output files
    TFile* fROOTout = new TFile("/tmp/pulser.root", "RECREATE");

    // create directories
    for (Int_t i = 0; i < nCh; i++)
    {
        sprintf(t, "%03d_%s", i, gReadAR->GetElement(i)->GetTDC());
        fROOTout->mkdir(t);
    }
    
    TF1* func = new TF1("gausfunc", "gaus", 0 , 200);

    // loop over runs
    for (Int_t i = 0; i < nRuns; i++)
    {   
        // get the file
        TFile* f = (TFile*) gFiles->At(i);

        // extract run number
        Int_t runNumber;
        sprintf(t, "%s/ARHistograms_CB_%%d.root", loc);
        sscanf(f->GetName(), t, &runNumber);
        runNumbersD[i] = (Double_t)runNumber;

        printf("Processing run %d (%d/%d)\n", runNumber, i+1, nRuns);

        fROOTout->cd();

        // loop over TDCs
        for (Int_t j = 0; j < nCh; j++)
        {
            // load histogram
            sprintf(t, "%03d_%s", j, gReadAR->GetElement(j)->GetTDC());
            fROOTout->cd(t);
            sprintf(t, "ADC%s", gReadAR->GetElement(j)->GetTDC());
            TH1D* h = (TH1D*) f->Get(t);
            
            // fit gaussian to pulser
            Double_t maxPos = h->GetXaxis()->GetBinCenter(h->GetMaximumBin());
            func->SetParameters(1, maxPos, 0.1);
            func->SetRange(maxPos - 2, maxPos + 2);
            h->Fit(func, "RBQ");
            maxPos = func->GetParameter(1);
            
            // save position in file and memory
            pedPos[j][i] = maxPos;

            sprintf(t, "Run_%d", runNumber);
            TCanvas* c = new TCanvas(t, t);
            h->Draw();
            
            TLine* tline = new TLine(maxPos, 0, maxPos, 10000);
            tline->SetLineColor(kRed);
            tline->SetLineWidth(2);
            tline->Draw();
            
            c->Write(c->GetName(), TObject::kOverwrite);
    
            delete h;
            delete c;
            delete tline;
        }
    }
    
    // create pedestal evolution graphs
    fROOTout->cd();
    
    // loop over channels
    for (Int_t j = 0; j < nCh; j++)
    {
        printf("Creating pedestal graph for channel %d\n", j);
        
        TGraph* g = new TGraph(nRuns, runNumbersD, pedPos[j]);
        sprintf(t, "Overview_%03d_%s", j, gReadAR->GetElement(j)->GetTDC());
        g->SetName(t);
        g->SetTitle(t);
        //g->GetYaxis()->SetRangeUser(1200, 1300);
        g->Write(g->GetName(), TObject::kOverwrite);
        
        delete g;
    }

    printf("Saving output file\n");
    
    delete fROOTout;

    // cleanup
    for (Int_t i = 0; i < nCh; i++) delete [] pedPos[i];
    delete [] pedPos;
    delete [] runNumbersD;
}
Example #24
0
int main(int argc, char* argv[]){
	std::stringstream buff;

	//=======================================
	//*************read parameter**********
	//if (argc==1) {
	//	print_usage(argv[0]);
	//	return -1;
	//}
	init_args();
	int result;
	while((result=getopt(argc,argv,"hbv:n:m:p:"))!=-1){
		switch(result){
			/* INPUTS */
			case 'm':
				strcpy(m_workMode,optarg);
				printf("work mode: %s\n",m_workMode);
				break;
			case 'v':
				verbose = atoi(optarg);
				printf("verbose level: %d\n",verbose);
				break;
			case 'b':
				backup = true;
				printf("restore backup file!\n");
				break;
			case 'n':
				nEvents = atoi(optarg);
				printf("nEvent: %d\n",nEvents);
				break;
			case 'p':
				printModule = atoi(optarg);
				printf("printModule: %d\n",printModule);
				break;
			case '?':
				printf("Wrong option! optopt=%c, optarg=%s\n", optopt, optarg);
				break;
			case 'h':
			default:
				print_usage(argv[0]);
				return 1;
		}
	}

	//for (;optind<argc;optind++){
	//	m_input_files.push_back(argv[optind]);
	//}

	//=======================================
	//************Verbose Control***********
	int Verbose_SectorInfo = 5; //大概的流程情况
	std::string prefix_SectorInfo = "### ";
	int Verbose_HistInfo = 10; //有哪些hist,什么时候输出了,参数如何
	std::string prefix_HistInfo= "  [Histograms] ";
	int Verbose_Statistics = 10; //跟统计相关的(效率,分辨,粒子鉴别的情况)
	std::string prefix_Statistics="  [Statistics] ";
	int Verbose_FileInfo = 10; //有哪些FileList,都有多少file
	std::string prefix_FileInfo="  [FileInfo] ";
	int Verbose_EffInfo = 15; //Efficiency info
	std::string prefix_EffInfo="  [EffInfo] ";
	int Verbose_EventInfo = 20; //每个event的基本流程
	std::string prefix_EventInfoStart="    =>[EventInfo] ";
	std::string prefix_EventInfo="      [EventInfo] ";
	int Verbose_ParticleInfo=25; //每个particle的基本信息
	std::string prefix_ParticleInfoStart="    ->[ParticleInfo]";
	std::string prefix_ParticleInfo="      [ParticleInfo]";

	//=======================================================================================================
	//************PRESET********************
	if (verbose >= Verbose_SectorInfo ) std::cout<<prefix_SectorInfo<<"In PRESET###"<<std::endl;

	//=> About Histogram
	std::string histList = "histList";
	int index_temp;

	//=>About Constant
	double PI = 3.141592653589793238;
	double FSC = 1/137.03599911; //fine structure constant
	double M_MUON = 0.1056584; //mass of muon in GeV
	double M_ELE = 0.510999e-3; //mass of electron in GeV
	double M_U = 0.931494061; //atomic mass unit in GeV
	double M_p = 0.9382723; // proton mass unit in GeV

	//=>About output
	std::string OutputDir = "result/";

	//=======================================================================================================
	//************SET HISTOGRAMS********************
	if (verbose >= Verbose_SectorInfo ) std::cout<<prefix_SectorInfo<<"In SET HISTOGRAMS###"<<std::endl;
 
	//=>Read histList
	std::ifstream fin_card(histList.c_str());
	if(!fin_card){
		std::cout<<"Cannot find "<<histList<<std::endl;
	}
	std::string s_card;
	std::vector<std::string> DirNames; 
	std::vector<std::string> RunNames; 
	std::vector<int> NCPU;
	std::vector<int> NJob;
	double beamPx = 0;
	double beamPy = 0;
	double beamPz = 0;
	// read histList
	while(getline(fin_card,s_card)){
		if ( ISEMPTY(s_card) ) continue;
		std::vector<std::string> segments;
		seperate_string(s_card,segments,'|');
		int iterator = 1;
		if ( segments[0] == "TH1D" ){
			if(iterator<segments.size()) nameForH1D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) titleForH1D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) xNameForH1D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) yNameForH1D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) bin1ForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) left1ForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) right1ForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) minxForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) minyForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) colorForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) compareForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) xlogForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) ylogForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) markerForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) normForH1D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) drawOptForH1D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
		}
		else if ( segments[0] == "TH2D" ){
			if(iterator<segments.size()) nameForH2D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) titleForH2D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) xNameForH2D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) yNameForH2D.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) bin1ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) left1ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) right1ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) bin2ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) left2ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) right2ForH2D.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
		}
		else if ( segments[0] == "FILE" ){
			if(iterator<segments.size()) DirNames.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			std::string runname;
			if(iterator<segments.size()) runname = "_"+segments[iterator++]; else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if (runname=="_"){
				RunNames.push_back("");
			}
			else{
				RunNames.push_back(runname);
			}
			if(iterator<segments.size()) NCPU.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) NJob.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
		}
		else if ( segments[0] == "TGraph" ){
			if(iterator<segments.size()) nameForGraph.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) titleForGraph.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) xNameForGraph.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) yNameForGraph.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			std::vector<double> avec;
			xForGraph.push_back(avec);
			std::vector<double> bvec;
			yForGraph.push_back(bvec);
			if(iterator<segments.size()) colorForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) compareForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) minxForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) maxxForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) minyForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) xlogForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) ylogForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) markerForGraph.push_back(string2double(segments[iterator++])); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) drawOptForGraph.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			int i = nameForGraph.size() - 1;
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"Input vecGraph["<<i<<"]: "<<nameForGraph[i]<<", "<<titleForGraph[i]<<", "<<xNameForGraph[i]<<", "<<yNameForGraph[i]<<", Color="<<colorForGraph[i]<<", xlogSyle="<<xlogForGraph[i]<<", ylogSyle="<<ylogForGraph[i]<<", nCompare="<<compareForGraph[i]<<", markerStyle="<<markerForGraph[i]<<", drawOpt=\""<<drawOptForGraph[i]<<"\""<<std::endl;
		}
		else if (segments[0] == "refTH1D"){
			if(iterator<segments.size()) refFileName.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) refHistName.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
		}
		else if (segments[0] == "oFILE"){
			if(iterator<segments.size()) oFileName.push_back(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
		}
		else if (segments[0] == "BEAM"){
			if(iterator<segments.size()) beamPx = string2double(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) beamPy = string2double(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
			if(iterator<segments.size()) beamPz = string2double(segments[iterator++]); else {std::cout<<"Not enough segments in"<<s_card<<"!!!"<<std::endl; return -1;}
		}
		else{
			std::cout<<"Cannot recogonize this line: "<<s_card<<std::endl;
			continue;
		}
	}

	//=> Get histograms in
	for ( int i = 0; i < nameForH2D.size(); i++ ){
		vecH2D.push_back(new TH2D(nameForH2D[i].c_str(),titleForH2D[i].c_str(),bin1ForH2D[i],left1ForH2D[i],right1ForH2D[i],bin2ForH2D[i],left2ForH2D[i],right2ForH2D[i]) );
	}
	for ( int i = 0; i < nameForH1D.size(); i++ ){
		vecH1D.push_back(new TH1D(nameForH1D[i].c_str(),titleForH1D[i].c_str(),bin1ForH1D[i],left1ForH1D[i],right1ForH1D[i]) );
	}
	for ( int i = 0; i < refFileName.size(); i++ ){
		TFile * fp_ref = new TFile(refFileName[i].c_str());
		if (fp_ref==NULL) {
			std::cout<<"ERROR: Can not find file: "<<refFileName[i]<<"!!!"<<std::endl;
			return -1;
		}
		TH1D* h1_ref = (TH1D*)fp_ref->Get(refHistName[i].c_str());
		if(h1_ref==NULL){
			std::cout<<"ERROR: Can not find histogram \""<<refHistName[i]<<"\"in file : "<<refFileName[i]<<"!!!"<<std::endl;
			return -1;
		}
		if ( (index_temp = get_TH1D(refHistName[i])) != -1 ){
			h1_ref->SetTitle(titleForH1D[index_temp].c_str());
			vecH1D[index_temp]=h1_ref;
		}
		else{
			std::cout<<"ERROR: Can not find histogram \""<<refHistName[i]<<"\"in vecH1D!!!"<<std::endl;
			return -1;
		}
	}

	//=======================================================================================================
	//************SET Statistics********************
	if (verbose >= Verbose_SectorInfo ) std::cout<<prefix_SectorInfo<<"In SET Statistics###"<<std::endl;

	//=>About Statistical
	int N0 = 0;
	int N1 = 0;
	int N2 = 0;
	int N3 = 0;
	int N4 = 0;
	int N5 = 0;
	int N6 = 0;
	int N7 = 0;

	//=======================================================================================================
	//************READ THE FILES********************
	if (verbose >= Verbose_SectorInfo ) std::cout<<prefix_SectorInfo<<"In READ THE FILES###"<<std::endl;
	std::string TreeName = "tree";
	TChain *m_TChain = new TChain(TreeName.c_str());

	int iStart = 0;
	int nBit = 2;
	for ( int iFile = 0; iFile < DirNames.size(); iFile++ ){
		int nCPU = NCPU[iFile];
		int njob = NJob[iFile];
		if ( verbose >= Verbose_FileInfo) std::cout<<prefix_FileInfo<<"FileList \""<<DirNames[iFile]<<"\" with runname = \""<<RunNames[iFile]<<"\" has "<<NJob[iFile]<<" jobs on "<<NCPU[iFile]<<" CPUs"<<std::endl;
		for (int i = iStart; i < iStart + nCPU; i ++){
			for (int j = iStart; j < iStart + njob; j ++){
				buff.str("");
				buff.clear();
				buff<<DirNames[iFile]<<"/"<<i<<"_job"<<j<<RunNames[iFile]<<".raw";
				m_TChain->Add(buff.str().c_str());
			}
		}
	}
	for ( int iFile = 0; iFile < oFileName.size(); iFile++ ){
		m_TChain->Add(oFileName[iFile].c_str());
	}

	//=======================================================================================================
	//************SET Branches********************
	int evt_num = 0;
	int run_num = 0;
	int McTruth_nTracks;
	std::vector<int> *McTruth_pid = 0;
	std::vector<int> *McTruth_tid = 0;
	std::vector<int> *McTruth_ptid = 0;
	std::vector<int> *McTruth_time = 0;
	std::vector<double> *McTruth_px = 0;
	std::vector<double> *McTruth_py = 0;
	std::vector<double> *McTruth_pz = 0;
	std::vector<double> *McTruth_e = 0;
	std::vector<double> *McTruth_x = 0;
	std::vector<double> *McTruth_y = 0;
	std::vector<double> *McTruth_z = 0;
	std::vector<int> *McTruth_charge = 0;
	std::vector<std::string> *McTruth_particleName = 0;
	std::vector<std::string> *McTruth_process = 0;
	std::vector<std::string> *McTruth_volume = 0;

	int Trigger_nHits = 0;
	std::vector<double> *Trigger_x = 0;
	std::vector<double> *Trigger_y = 0;
	std::vector<double> *Trigger_z = 0;
	std::vector<double> *Trigger_t = 0;
	std::vector<double> *Trigger_px = 0;
	std::vector<double> *Trigger_py = 0;
	std::vector<double> *Trigger_pz = 0;
	std::vector<double> *Trigger_e = 0;
	std::vector<double> *Trigger_edep = 0;
	std::vector<double> *Trigger_stepL = 0;
	std::vector<int> *Trigger_volID = 0;
	std::vector<std::string> *Trigger_volName = 0;
	std::vector<int> *Trigger_tid = 0;
	std::vector<int> *Trigger_pid = 0;
	std::vector<int> *Trigger_charge = 0;

	int CdcCell_nHits;
	std::vector<double> *CdcCell_x = 0;
	std::vector<double> *CdcCell_y = 0;
	std::vector<double> *CdcCell_z = 0;
	std::vector<double> *CdcCell_pIx = 0;
	std::vector<double> *CdcCell_pIy = 0;
	std::vector<double> *CdcCell_pIz = 0;
	std::vector<double> *CdcCell_pOx = 0;
	std::vector<double> *CdcCell_pOy = 0;
	std::vector<double> *CdcCell_pOz = 0;
	std::vector<double> *CdcCell_t = 0;
	std::vector<double> *CdcCell_px = 0;
	std::vector<double> *CdcCell_py = 0;
	std::vector<double> *CdcCell_pz = 0;
	std::vector<double> *CdcCell_e = 0;
	std::vector<double> *CdcCell_edep = 0;
	std::vector<double> *CdcCell_driftD_smeared = 0;
	std::vector<double> *CdcCell_driftD = 0;
	std::vector<double> *CdcCell_error = 0;
	std::vector<int> *CdcCell_status = 0;
	std::vector<int> *CdcCell_nTry = 0;
	std::vector<int> *CdcCell_layerID = 0;
	std::vector<int> *CdcCell_cellID = 0;
	std::vector<int> *CdcCell_tid = 0;
	std::vector<int> *CdcCell_pid = 0;

	TBranch *bMcTruth_pid = 0;
	TBranch *bMcTruth_tid = 0;
	TBranch *bMcTruth_ptid = 0;
	TBranch *bMcTruth_time = 0;             
	TBranch *bMcTruth_px = 0;              
	TBranch *bMcTruth_py = 0;              
	TBranch *bMcTruth_pz = 0;              
	TBranch *bMcTruth_e = 0;               
	TBranch *bMcTruth_x = 0;                
	TBranch *bMcTruth_y = 0;                
	TBranch *bMcTruth_z = 0;                
	TBranch *bMcTruth_charge = 0;
	TBranch *bMcTruth_particleName = 0;
	TBranch *bMcTruth_process = 0;
	TBranch *bMcTruth_volume = 0;

	TBranch *bTrigger_x = 0;
	TBranch *bTrigger_y = 0;
	TBranch *bTrigger_z = 0;
	TBranch *bTrigger_t = 0;
	TBranch *bTrigger_px = 0;
	TBranch *bTrigger_py = 0;
	TBranch *bTrigger_pz = 0;
	TBranch *bTrigger_e = 0;
	TBranch *bTrigger_edep = 0;
	TBranch *bTrigger_stepL = 0;
	TBranch *bTrigger_volID = 0;
	TBranch *bTrigger_volName = 0;
	TBranch *bTrigger_tid = 0;
	TBranch *bTrigger_pid = 0;
	TBranch *bTrigger_charge = 0;

	TBranch *bCdcCell_x = 0;
	TBranch *bCdcCell_y = 0;
	TBranch *bCdcCell_z = 0;
	TBranch *bCdcCell_pIx = 0;
	TBranch *bCdcCell_pIy = 0;
	TBranch *bCdcCell_pIz = 0;
	TBranch *bCdcCell_pOx = 0;
	TBranch *bCdcCell_pOy = 0;
	TBranch *bCdcCell_pOz = 0;
	TBranch *bCdcCell_t = 0;
	TBranch *bCdcCell_px = 0;
	TBranch *bCdcCell_py = 0;
	TBranch *bCdcCell_pz = 0;
	TBranch *bCdcCell_e = 0;
	TBranch *bCdcCell_edep = 0;
	TBranch *bCdcCell_driftD_smeared = 0;
	TBranch *bCdcCell_driftD = 0;
	TBranch *bCdcCell_error = 0;
	TBranch *bCdcCell_status = 0;
	TBranch *bCdcCell_nTry = 0;
	TBranch *bCdcCell_layerID = 0;
	TBranch *bCdcCell_cellID = 0;
	TBranch *bCdcCell_tid = 0;
	TBranch *bCdcCell_pid = 0;

	m_TChain->SetBranchAddress("evt_num", &evt_num);
	m_TChain->SetBranchAddress("run_num", &run_num);
	m_TChain->SetBranchAddress("McTruth_nTracks", &McTruth_nTracks);
	m_TChain->SetBranchAddress("McTruth_pid", &McTruth_pid, &bMcTruth_pid);
	m_TChain->SetBranchAddress("McTruth_tid", &McTruth_tid, &bMcTruth_tid);
	m_TChain->SetBranchAddress("McTruth_ptid", &McTruth_ptid, &bMcTruth_ptid);
	m_TChain->SetBranchAddress("McTruth_time", &McTruth_time, &bMcTruth_time);             
	m_TChain->SetBranchAddress("McTruth_px", &McTruth_px, &bMcTruth_px);              
	m_TChain->SetBranchAddress("McTruth_py", &McTruth_py, &bMcTruth_py);              
	m_TChain->SetBranchAddress("McTruth_pz", &McTruth_pz, &bMcTruth_pz);              
	m_TChain->SetBranchAddress("McTruth_e", &McTruth_e, &bMcTruth_e);               
	m_TChain->SetBranchAddress("McTruth_x", &McTruth_x, &bMcTruth_x);                
	m_TChain->SetBranchAddress("McTruth_y", &McTruth_y, &bMcTruth_y);                
	m_TChain->SetBranchAddress("McTruth_z", &McTruth_z, &bMcTruth_z);                
	m_TChain->SetBranchAddress("McTruth_charge", &McTruth_charge, &bMcTruth_charge);
	m_TChain->SetBranchAddress("McTruth_particleName", &McTruth_particleName, &bMcTruth_particleName);
	m_TChain->SetBranchAddress("McTruth_process", &McTruth_process, &bMcTruth_process);
	m_TChain->SetBranchAddress("McTruth_volume", &McTruth_volume, &bMcTruth_volume);

	m_TChain->SetBranchAddress("Trigger_nHits", &Trigger_nHits);
	m_TChain->SetBranchAddress("Trigger_x", &Trigger_x, &bTrigger_x);
	m_TChain->SetBranchAddress("Trigger_y", &Trigger_y, &bTrigger_y);
	m_TChain->SetBranchAddress("Trigger_z", &Trigger_z, &bTrigger_z);
	m_TChain->SetBranchAddress("Trigger_t", &Trigger_t, &bTrigger_t);
	m_TChain->SetBranchAddress("Trigger_px", &Trigger_px, &bTrigger_px);
	m_TChain->SetBranchAddress("Trigger_py", &Trigger_py, &bTrigger_py);
	m_TChain->SetBranchAddress("Trigger_pz", &Trigger_pz, &bTrigger_pz);
	m_TChain->SetBranchAddress("Trigger_e", &Trigger_e, &bTrigger_e);
	m_TChain->SetBranchAddress("Trigger_edep", &Trigger_edep, &bTrigger_edep);
	m_TChain->SetBranchAddress("Trigger_stepL", &Trigger_stepL, &bTrigger_stepL);
	m_TChain->SetBranchAddress("Trigger_volID", &Trigger_volID, &bTrigger_volID);
	m_TChain->SetBranchAddress("Trigger_volName", &Trigger_volName, &bTrigger_volName);
	m_TChain->SetBranchAddress("Trigger_tid", &Trigger_tid, &bTrigger_tid);
	m_TChain->SetBranchAddress("Trigger_pid", &Trigger_pid, &bTrigger_pid);
	m_TChain->SetBranchAddress("Trigger_charge", &Trigger_charge, &bTrigger_charge);

	m_TChain->SetBranchAddress("CdcCell_nHits", &CdcCell_nHits);
	m_TChain->SetBranchAddress("CdcCell_x", &CdcCell_x, &bCdcCell_x);
	m_TChain->SetBranchAddress("CdcCell_y", &CdcCell_y, &bCdcCell_y);
	m_TChain->SetBranchAddress("CdcCell_z", &CdcCell_z, &bCdcCell_z);
	m_TChain->SetBranchAddress("CdcCell_pIx", &CdcCell_pIx, &bCdcCell_pIx);
	m_TChain->SetBranchAddress("CdcCell_pIy", &CdcCell_pIy, &bCdcCell_pIy);
	m_TChain->SetBranchAddress("CdcCell_pIz", &CdcCell_pIz, &bCdcCell_pIz);
	m_TChain->SetBranchAddress("CdcCell_pOx", &CdcCell_pOx, &bCdcCell_pOx);
	m_TChain->SetBranchAddress("CdcCell_pOy", &CdcCell_pOy, &bCdcCell_pOy);
	m_TChain->SetBranchAddress("CdcCell_pOz", &CdcCell_pOz, &bCdcCell_pOz);
	m_TChain->SetBranchAddress("CdcCell_t", &CdcCell_t, &bCdcCell_t);
	m_TChain->SetBranchAddress("CdcCell_px", &CdcCell_px, &bCdcCell_px);
	m_TChain->SetBranchAddress("CdcCell_py", &CdcCell_py, &bCdcCell_py);
	m_TChain->SetBranchAddress("CdcCell_pz", &CdcCell_pz, &bCdcCell_pz);
	m_TChain->SetBranchAddress("CdcCell_e", &CdcCell_e, &bCdcCell_e);
	m_TChain->SetBranchAddress("CdcCell_edep", &CdcCell_edep, &bCdcCell_edep);
	m_TChain->SetBranchAddress("CdcCell_driftD_smeared", &CdcCell_driftD_smeared, &bCdcCell_driftD_smeared);
	m_TChain->SetBranchAddress("CdcCell_driftD", &CdcCell_driftD, &bCdcCell_driftD);
	m_TChain->SetBranchAddress("CdcCell_error", &CdcCell_error, &bCdcCell_error);
	m_TChain->SetBranchAddress("CdcCell_status", &CdcCell_status, &bCdcCell_status);
	m_TChain->SetBranchAddress("CdcCell_nTry", &CdcCell_nTry, &bCdcCell_nTry);
	m_TChain->SetBranchAddress("CdcCell_layerID", &CdcCell_layerID, &bCdcCell_layerID);
	m_TChain->SetBranchAddress("CdcCell_cellID", &CdcCell_cellID, &bCdcCell_cellID);
	m_TChain->SetBranchAddress("CdcCell_tid", &CdcCell_tid, &bCdcCell_tid);
	m_TChain->SetBranchAddress("CdcCell_pid", &CdcCell_pid, &bCdcCell_pid);

	TTree* d_tree = new TTree( "t", "t" );

	int d_evt_num;
	int d_run_num;
	int d_pid;
	int d_tid;
	char d_vid[124];
	char d_prid[124];
	double d_mot_x;
	double d_mot_y;
	double d_mot_z;
	double d_mot_px;
	double d_mot_py;
	double d_mot_pz;
	double d_x;
	double d_y;
	double d_z;
	double d_px;
	double d_py;
	double d_pz;
	int d_nhits;
	double d_hits_x[1000];
	double d_hits_y[1000];
	double d_hits_z[1000];
	double d_hits_t[1000];
	double d_hits_px[1000];
	double d_hits_py[1000];
	double d_hits_pz[1000];
	double d_tri_t;

	d_tree->Branch("evt_num", &d_evt_num, "evt_num/I");
	d_tree->Branch("run_num", &d_run_num, "run_num/I");
	d_tree->Branch("pid", &d_pid, "pid/I");
	d_tree->Branch("tid", &d_tid, "tid/I");
	d_tree->Branch("vid", d_vid, "vid[124]/C");
	d_tree->Branch("prid", d_prid, "prid[124]/C");
	d_tree->Branch("mot_x", &d_mot_x, "mot_x/D");
	d_tree->Branch("mot_y", &d_mot_y, "mot_y/D");
	d_tree->Branch("mot_z", &d_mot_z, "mot_z/D");
	d_tree->Branch("mot_px", &d_mot_px, "mot_px/D");
	d_tree->Branch("mot_py", &d_mot_py, "mot_py/D");
	d_tree->Branch("mot_pz", &d_mot_pz, "mot_pz/D");
	d_tree->Branch("ini_x_cm", &d_x, "ini_x_cm/D");
	d_tree->Branch("ini_y_cm", &d_y, "ini_y_cm/D");
	d_tree->Branch("ini_z_cm", &d_z, "ini_z_cm/D");
	d_tree->Branch("ini_px_GeV", &d_px, "ini_px_GeV/D");
	d_tree->Branch("ini_py_GeV", &d_py, "ini_py_GeV/D");
	d_tree->Branch("ini_pz_GeV", &d_pz, "ini_pz_GeV/D");
	d_tree->Branch("nwirehit", &d_nhits, "nwirehit/I");
	d_tree->Branch("x", d_hits_x, "x[nhits]/D");
	d_tree->Branch("y", d_hits_y, "y[nhits]/D");
	d_tree->Branch("z", d_hits_z, "z[nhits]/D");
	d_tree->Branch("t", d_hits_t, "t[nhits]/D");
	d_tree->Branch("px", d_hits_px, "px[nhits]/D");
	d_tree->Branch("py", d_hits_py, "py[nhits]/D");
	d_tree->Branch("pz", d_hits_pz, "pz[nhits]/D");
	d_tree->Branch("tri_t", &d_tri_t, "tri_t/D");

	//=======================================================================================================
	//************DO THE DIRTY WORK*******************
	if (verbose >= Verbose_SectorInfo) std::cout<<prefix_SectorInfo<<"In DO THE DIRTY WORK ###"<<std::endl;

	if (!strcmp(m_workMode,"gen")){
		Long64_t nEvent = m_TChain->GetEntries();
		for( Long64_t iEvent = 0; iEvent < nEvent; iEvent++ ){
			if (verbose >= Verbose_EventInfo || iEvent%printModule == 0) std::cout<<prefix_EventInfoStart<<"In Event "<<iEvent<<std::endl;
			N0++;
			Long64_t tentry = m_TChain->LoadTree(iEvent);
			if(bMcTruth_pid) bMcTruth_pid->GetEntry(tentry);
			if(bMcTruth_tid) bMcTruth_tid->GetEntry(tentry);
			if(bMcTruth_ptid) bMcTruth_ptid->GetEntry(tentry);
			if(bMcTruth_time) bMcTruth_time->GetEntry(tentry);             
			if(bMcTruth_px) bMcTruth_px->GetEntry(tentry);              
			if(bMcTruth_py) bMcTruth_py->GetEntry(tentry);              
			if(bMcTruth_pz) bMcTruth_pz->GetEntry(tentry);              
			if(bMcTruth_e) bMcTruth_e->GetEntry(tentry);               
			if(bMcTruth_x) bMcTruth_x->GetEntry(tentry);                
			if(bMcTruth_y) bMcTruth_y->GetEntry(tentry);                
			if(bMcTruth_z) bMcTruth_z->GetEntry(tentry);                
			if(bMcTruth_charge) bMcTruth_charge->GetEntry(tentry);
			if(bMcTruth_particleName) bMcTruth_particleName->GetEntry(tentry);
			if(bMcTruth_process) bMcTruth_process->GetEntry(tentry);
			if(bMcTruth_volume) bMcTruth_volume->GetEntry(tentry);

			if(bTrigger_x) bTrigger_x->GetEntry(tentry);
			if(bTrigger_y) bTrigger_y->GetEntry(tentry);
			if(bTrigger_z) bTrigger_z->GetEntry(tentry);
			if(bTrigger_t) bTrigger_t->GetEntry(tentry);
			if(bTrigger_px) bTrigger_px->GetEntry(tentry);
			if(bTrigger_py) bTrigger_py->GetEntry(tentry);
			if(bTrigger_pz) bTrigger_pz->GetEntry(tentry);
			if(bTrigger_e) bTrigger_e->GetEntry(tentry);
			if(bTrigger_edep) bTrigger_edep->GetEntry(tentry);
			if(bTrigger_stepL) bTrigger_stepL->GetEntry(tentry);
			if(bTrigger_volID) bTrigger_volID->GetEntry(tentry);
			if(bTrigger_volName) bTrigger_volName->GetEntry(tentry);
			if(bTrigger_tid) bTrigger_tid->GetEntry(tentry);
			if(bTrigger_pid) bTrigger_pid->GetEntry(tentry);
			if(bTrigger_charge) bTrigger_charge->GetEntry(tentry);

			if(bCdcCell_x) bCdcCell_x->GetEntry(tentry);
			if(bCdcCell_y) bCdcCell_y->GetEntry(tentry);
			if(bCdcCell_z) bCdcCell_z->GetEntry(tentry);
			if(bCdcCell_pIx) bCdcCell_pIx->GetEntry(tentry);
			if(bCdcCell_pIy) bCdcCell_pIy->GetEntry(tentry);
			if(bCdcCell_pIz) bCdcCell_pIz->GetEntry(tentry);
			if(bCdcCell_pOx) bCdcCell_pOx->GetEntry(tentry);
			if(bCdcCell_pOy) bCdcCell_pOy->GetEntry(tentry);
			if(bCdcCell_pOz) bCdcCell_pOz->GetEntry(tentry);
			if(bCdcCell_t) bCdcCell_t->GetEntry(tentry);
			if(bCdcCell_px) bCdcCell_px->GetEntry(tentry);
			if(bCdcCell_py) bCdcCell_py->GetEntry(tentry);
			if(bCdcCell_pz) bCdcCell_pz->GetEntry(tentry);
			if(bCdcCell_e) bCdcCell_e->GetEntry(tentry);
			if(bCdcCell_edep) bCdcCell_edep->GetEntry(tentry);
			if(bCdcCell_driftD_smeared) bCdcCell_driftD_smeared->GetEntry(tentry);
			if(bCdcCell_driftD) bCdcCell_driftD->GetEntry(tentry);
			if(bCdcCell_error) bCdcCell_error->GetEntry(tentry);
			if(bCdcCell_status) bCdcCell_status->GetEntry(tentry);
			if(bCdcCell_nTry) bCdcCell_nTry->GetEntry(tentry);
			if(bCdcCell_layerID) bCdcCell_layerID->GetEntry(tentry);
			if(bCdcCell_cellID) bCdcCell_cellID->GetEntry(tentry);
			if(bCdcCell_tid) bCdcCell_tid->GetEntry(tentry);
			if(bCdcCell_pid) bCdcCell_pid->GetEntry(tentry);

			m_TChain->GetEntry(iEvent);

			// find the electron
			int index = 0;
			N1++;
			double px = (*McTruth_px)[0];
			double py = (*McTruth_py)[0];
			double pz = (*McTruth_pz)[0];
			double pt = sqrt(px*px+py*py);
			double pa = sqrt(pt*pt+pz*pz);
			if (pa<90){ // pa < 90MeV/c
				continue;
			}
			N2++;

			std::string process = (*McTruth_process)[index];
			std::string volume = (*McTruth_volume)[index];
			int tid = (*McTruth_tid)[index];

			if (verbose >= Verbose_EventInfo || iEvent%printModule == 0)
				std::cout<<prefix_EventInfoStart
					     <<" pa = "<<pa
					     <<"MeV/c, process = "<<process
					     <<std::endl;

			// prepare for d_tree
			d_nhits = 0;
			double CdcCell_firstHitTime = -1;
			for ( int i_hit = 0; i_hit < CdcCell_nHits; i_hit++ ){
				int i_tid = (*CdcCell_tid)[i_hit];
				if (i_tid == tid){
					d_hits_x[d_nhits] = (*CdcCell_x)[i_hit];
					d_hits_y[d_nhits] = (*CdcCell_y)[i_hit];
					d_hits_z[d_nhits] = (*CdcCell_z)[i_hit];
					d_hits_t[d_nhits] = (*CdcCell_t)[i_hit];
					d_hits_px[d_nhits] = (*CdcCell_px)[i_hit];
					d_hits_py[d_nhits] = (*CdcCell_py)[i_hit];
					d_hits_pz[d_nhits] = (*CdcCell_pz)[i_hit];
					d_nhits++;
				}
			}
			CdcCell_firstHitTime = d_nhits>0?d_hits_t[0]:-1;
			double Trigger_firstHitTime = -1;
			for ( int i_hit = 0; i_hit < Trigger_nHits; i_hit++ ){
				int i_tid = (*Trigger_tid)[i_hit];
				if (i_tid == tid){
					Trigger_firstHitTime = (*Trigger_t)[i_hit];
					break;
				}
			}
			// Fill the tree
			d_evt_num = evt_num;
			d_run_num = run_num;
			d_pid = 11;
			d_tid = tid;
			strcpy(d_vid,volume.c_str());
			strcpy(d_prid,process.c_str());
			if ( d_vid[0] == 'C'
			  && d_vid[1] == 'd'
			  && d_vid[2] == 'c'){
			  	strcpy(d_vid,"CDCChamber");
			}
			d_tri_t = Trigger_firstHitTime;
			d_mot_x = (*McTruth_x)[0];
			d_mot_y = (*McTruth_y)[0];
			d_mot_z = (*McTruth_z)[0];
			d_mot_px = (*McTruth_px)[0];
			d_mot_py = (*McTruth_py)[0];
			d_mot_pz = (*McTruth_pz)[0];
			d_x = (*McTruth_x)[index];
			d_y = (*McTruth_y)[index];
			d_z = (*McTruth_z)[index];
			d_px = (*McTruth_px)[index]/1000.;
			d_py = (*McTruth_py)[index]/1000.;
			d_pz = (*McTruth_pz)[index]/1000.;

			if (CdcCell_nHits<=0) // not hit the Cdc
				continue;
			N3++;

			if ( CdcCell_firstHitTime == -1) // this electron not hit the Cdc
				continue;
			N4++;

			if (Trigger_nHits<=0) // not hit the trigger
				continue;
			N5++;

			if ( Trigger_firstHitTime == -1) // this electron not hit the trigger
				continue;
			N6++;

			if ( Trigger_firstHitTime <= CdcCell_firstHitTime ) // hit trigger first
				continue;
			N7++;

			if ( (index_temp = get_TH1D("pa")) != -1 ){
				vecH1D[index_temp]->Fill(pa);
			}

			d_tree->Fill();

			if (verbose >= Verbose_EventInfo || iEvent%printModule == 0) std::cout<<prefix_EventInfo<<"Finished!"<<std::endl;
		}/* end of loop in events*/
	}

	//=======================================================================================================

	//=======================================================================================================
	//************WRITE AND OUTPUT********************
	if (verbose >= Verbose_SectorInfo) std::cout<<prefix_SectorInfo<<"In WRITE AND OUTPUT ###"<<std::endl;
	std::string outputFileName = OutputDir + "output.root";
	TFile *file = new TFile(outputFileName.c_str(),"RECREATE");
	std::cout<<"N0 = "<<N0<<std::endl;
	std::cout<<"N1 = "<<N1<<std::endl;
	std::cout<<"N2 = "<<N2<<std::endl;
	std::cout<<"N3 = "<<N3<<std::endl;
	std::cout<<"N4 = "<<N4<<std::endl;
	std::cout<<"N5 = "<<N5<<std::endl;
	std::cout<<"N6 = "<<N6<<std::endl;
	std::cout<<"N7 = "<<N7<<std::endl;

	gStyle->SetPalette(1);
	gStyle->SetOptStat(0);
	gStyle->SetPadTickX(1);
	gStyle->SetPadTickY(1);
	//  gStyle->SetTitleW(0.99);
	//  gStyle->SetTitleH(0.08);
	//Output these histograms
	for ( int i = 0; i < vecH1D.size(); i++ ){
		if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"Output vecH1D["<<i<<"]: "<<nameForH1D[i]<<", "<<titleForH1D[i]<<", "<<xNameForH1D[i]<<", "<<yNameForH1D[i]<<", "<<bin1ForH1D[i]<<", "<<left1ForH1D[i]<<", "<<right1ForH1D[i]<<", Color="<<colorForH1D[i]<<", xlogSyle="<<xlogForH1D[i]<<", ylogSyle="<<ylogForH1D[i]<<", nCompare="<<compareForH1D[i]<<", markerStyle="<<markerForH1D[i]<<", normalize ="<<normForH1D[i]<<", drawOpt=\""<<drawOptForH1D[i]<<"\""<<std::endl;
		vecH1D[i]->SetLineColor(colorForH1D[i]);
		std::string name = vecH1D[i]->GetName();
		TCanvas* c = new TCanvas(name.c_str());
		int nCompare = compareForH1D[i];
		if ( nCompare ) if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<nCompare<<" histograms to be compared"<<std::endl;
		if (normForH1D[i]){
			if (normForH1D[i] == 1) vecH1D[i]->Scale(1./vecH1D[i]->Integral());
			else vecH1D[i]->Scale(1./normForH1D[i]);
		}
		double currentMaximum = vecH1D[i]->GetMaximum();
		if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"    currentMaximum y value is ("<<currentMaximum<<")"<<std::endl;
		for ( int j = 1; j <= nCompare; j++ ){
			if (normForH1D[i+j]){
				if (normForH1D[i+j] == 1) vecH1D[i+j]->Scale(1./vecH1D[i+j]->Integral());
				else vecH1D[i+j]->Scale(1./normForH1D[i+j]);
			}
			double maximum = vecH1D[i+j]->GetMaximum();
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"    Maximum y for "<<nameForH1D[i+j]<<" is ("<<maximum<<")"<<std::endl;
			if ( maximum > currentMaximum ){
				currentMaximum = maximum;
			}
		}
		if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"  maximum y value is ("<<currentMaximum<<")"<<std::endl;
		if ( xlogForH1D[i] ) gPad->SetLogx(1);
		else gPad->SetLogx(0);
		if ( ylogForH1D[i] ) gPad->SetLogy(1);
		else gPad->SetLogy(0);
		if ( xlogForH1D[i] ){
			vecH1D[i]->GetXaxis()->SetRangeUser(minxForH1D[i],right1ForH1D[i]);
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"  Logx! set xRange("<<minxForH1D[i]<<","<<right1ForH1D[i]<<")"<<std::endl;
		}
		else {
			vecH1D[i]->GetXaxis()->SetRangeUser(left1ForH1D[i],right1ForH1D[i]);
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"        set xRange("<<left1ForH1D[i]<<","<<right1ForH1D[i]<<")"<<std::endl;
		}
		if ( ylogForH1D[i] ) {
			vecH1D[i]->GetYaxis()->SetRangeUser(minyForH1D[i],2*currentMaximum);
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"  Logy! set yRange("<<minyForH1D[i]<<","<<2*currentMaximum<<")"<<std::endl;
		}
		else {
			vecH1D[i]->GetYaxis()->SetRangeUser(minyForH1D[i],1.05*currentMaximum);
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"        set yRange("<<minyForH1D[i]<<","<<1.05*currentMaximum<<")"<<std::endl;
		}
		vecH1D[i]->SetMarkerStyle(markerForH1D[i]);
		vecH1D[i]->SetMarkerColor(colorForH1D[i]);
		vecH1D[i]->SetLineColor(colorForH1D[i]);
		vecH1D[i]->GetXaxis()->SetTitle(xNameForH1D[i].c_str());
		vecH1D[i]->GetYaxis()->SetTitle(yNameForH1D[i].c_str());
		if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"    Integral of ("<<nameForH1D[i]<<"): "<<vecH1D[i]->Integral()<<std::endl;
		vecH1D[i]->Draw(drawOptForH1D[i].c_str());
		vecH1D[i]->Write();
		for ( int j = 0; j < nCompare; j++ ){
			i++;
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<" ->"<<j<<", vecH1D["<<i<<"]: "<<nameForH1D[i]<<", "<<titleForH1D[i]<<", "<<xNameForH1D[i]<<", "<<yNameForH1D[i]<<", "<<bin1ForH1D[i]<<", "<<left1ForH1D[i]<<", "<<right1ForH1D[i]<<", Color="<<colorForH1D[i]<<", xlogSyle="<<xlogForH1D[i]<<", ylogSyle="<<ylogForH1D[i]<<", nCompare="<<compareForH1D[i]<<", markerStyle="<<markerForH1D[i]<<", normalize ="<<normForH1D[i]<<", drawOpt=\""<<drawOptForH1D[i]<<"\""<<std::endl;
			vecH1D[i]->SetLineColor(colorForH1D[i]);
			vecH1D[i]->SetMarkerStyle(markerForH1D[i]);
			vecH1D[i]->SetMarkerColor(colorForH1D[i]);
			vecH1D[i]->SetLineColor(colorForH1D[i]);
			std::string drawOpt = drawOptForH1D[i]+"SAME";
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"    Integral of ("<<nameForH1D[i]<<"): "<<vecH1D[i]->Integral()<<std::endl;
			vecH1D[i]->Draw(drawOpt.c_str());
		}
		std::string fileName = OutputDir + name + ".pdf";
		c->Print(fileName.c_str());
	}
	gStyle->SetOptStat(0);
	for ( int i = 0; i < vecH2D.size(); i++ ){
		if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"Output vecH2D["<<i<<"]: "<<nameForH2D[i]<<", "<<titleForH2D[i]<<", "<<xNameForH2D[i]<<", "<<yNameForH2D[i]<<", "<<bin1ForH2D[i]<<", "<<left1ForH2D[i]<<", "<<right1ForH2D[i]<<", "<<bin2ForH2D[i]<<", "<<left2ForH2D[i]<<", "<<right2ForH2D[i]<<std::endl;
		std::string name = vecH2D[i]->GetName();
		TCanvas* c = new TCanvas(name.c_str());
		vecH2D[i]->GetXaxis()->SetTitle(xNameForH2D[i].c_str());
		vecH2D[i]->GetYaxis()->SetTitle(yNameForH2D[i].c_str());
		vecH2D[i]->Draw("COLZ");
		vecH2D[i]->Write();
		std::string fileName = OutputDir + name + ".pdf";
		c->Print(fileName.c_str());
	}
	for ( int i = 0; i < nameForGraph.size(); i++ ){
		int sizeOfThisGraph = xForGraph[i].size();
		if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"Output vecGraph["<<i<<"]: "<<nameForGraph[i]<<", "<<titleForGraph[i]<<", "<<xNameForGraph[i]<<", "<<yNameForGraph[i]<<", Color="<<colorForGraph[i]<<", xlogSyle="<<xlogForGraph[i]<<", ylogSyle="<<ylogForGraph[i]<<", nCompare="<<compareForGraph[i]<<", markerStyle="<<markerForGraph[i]<<", drawOpt=\""<<drawOptForGraph[i]<<"\", size = "<<sizeOfThisGraph<<std::endl;
		if ( sizeOfThisGraph <= 0 ) continue;
		if (verbose >= Verbose_HistInfo){
			for ( int j = 0; j < sizeOfThisGraph; j++ ){
				std::cout<<prefix_HistInfo<<"  ["<<j<<"]: ("<<xForGraph[i][j]<<","<<yForGraph[i][j]<<")"<<std::endl;
			}
		}
		std::string name = nameForGraph[i];
		TCanvas* c = new TCanvas(nameForGraph[i].c_str());
		TGraph *aTGraph = new TGraph(sizeOfThisGraph,&xForGraph[i][0],&yForGraph[i][0]);
		aTGraph->SetTitle(titleForGraph[i].c_str());
		int nCompare = compareForGraph[i];
		if ( nCompare ) if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<nCompare<<" graphs to be compared"<<std::endl;
		std::vector<double> yforgraph = yForGraph[i];
		std::vector<double> xforgraph = xForGraph[i];
		double currentMaximum = *std::max_element(yforgraph.begin(),yforgraph.end());
		if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"    currentMaximum y value is ("<<currentMaximum<<")"<<std::endl;
		for ( int j = 1; j <= nCompare; j++ ){
			double maximum = *std::max_element(yForGraph[i+j].begin(),yForGraph[i+j].end());
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"    Maximum y for "<<nameForGraph[i+j]<<" is ("<<maximum<<")"<<std::endl;
			if ( maximum > currentMaximum ){
				currentMaximum = maximum;
			}
		}
		if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<"  maximum y value is ("<<currentMaximum<<")"<<std::endl;
		if ( xlogForGraph[i] ) gPad->SetLogx(1);
		else gPad->SetLogx(0);
		if ( ylogForGraph[i] ) gPad->SetLogy(1);
		else gPad->SetLogy(0);
		if ( xlogForGraph[i] ) aTGraph->GetXaxis()->SetRangeUser(minxForGraph[i],2*maxxForGraph[i]);
		else aTGraph->GetXaxis()->SetRangeUser(minxForGraph[i],1.05*maxxForGraph[i]);
		if ( ylogForGraph[i] ) aTGraph->GetYaxis()->SetRangeUser(minyForGraph[i],2*currentMaximum);
		else aTGraph->GetYaxis()->SetRangeUser(minyForGraph[i],1.05*currentMaximum);
		aTGraph->GetXaxis()->SetTitle(xNameForGraph[i].c_str());
		aTGraph->GetYaxis()->SetTitle(yNameForGraph[i].c_str());
		aTGraph->SetMarkerStyle(markerForGraph[i]);
		aTGraph->SetMarkerColor(colorForGraph[i]);
		aTGraph->SetLineColor(colorForGraph[i]);
		std::string drawOpt = "A"+drawOptForGraph[i];
		aTGraph->Draw(drawOpt.c_str());
		aTGraph->Write();
		for ( int j = 0; j < nCompare; j++ ){
			i++;
			int sizeOfThisGraph = xForGraph[i].size();
			if (verbose >= Verbose_HistInfo) std::cout<<prefix_HistInfo<<" ->"<<j<<", vecGraph["<<i<<"]: "<<nameForGraph[i]<<", "<<titleForGraph[i]<<", "<<xNameForGraph[i]<<", "<<yNameForGraph[i]<<", Color="<<colorForGraph[i]<<", xlogSyle="<<xlogForGraph[i]<<", ylogSyle="<<ylogForGraph[i]<<", nCompare="<<compareForGraph[i]<<", markerStyle="<<markerForGraph[i]<<", drawOpt=\""<<drawOptForGraph[i]<<"\", size = "<<sizeOfThisGraph<<std::endl;
			if ( sizeOfThisGraph <= 0 ) continue;
			if (verbose >= Verbose_HistInfo){
				for ( int k = 0; k < sizeOfThisGraph; k++ ){
					std::cout<<prefix_HistInfo<<"  ["<<k<<"]: ("<<xForGraph[i][k]<<","<<yForGraph[i][k]<<")"<<std::endl;
				}
			}
			TGraph *bTGraph = new TGraph(sizeOfThisGraph,&xForGraph[i][0],&yForGraph[i][0]);
			bTGraph->SetTitle(titleForGraph[i].c_str());
			bTGraph->GetXaxis()->SetTitle(xNameForGraph[i].c_str());
			bTGraph->GetYaxis()->SetTitle(yNameForGraph[i].c_str());
			bTGraph->SetLineColor(colorForGraph[i]);
			bTGraph->SetMarkerStyle(markerForGraph[i]);
			bTGraph->SetMarkerColor(colorForGraph[i]);
			bTGraph->SetLineColor(colorForGraph[i]);
			bTGraph->Draw(drawOptForGraph[i].c_str());
			bTGraph->Write();
		}
		std::string fileName = OutputDir + name + ".pdf";
		c->Print(fileName.c_str());
	}

	d_tree->Write();
	file->Close();
	std::string backupFileName = OutputDir + "backup.root";

	if (backup){
		TFile *file2 = new TFile(backupFileName.c_str(),"RECREATE");
		m_TChain->CloneTree(-1,"fast");
		file2->Write();
		file2->Close();
	}

	delete file;
	return 0;
}
int main(int argc, char** argv)
{
    // read config files to see which nuclei should be used for calculation
    string configFileName = "config/filesToRead.txt";
    ifstream configFile(configFileName);

    if(!configFile.is_open())
    {
        cerr << "Error: failed to open " << configFileName << "; exiting..." << endl;
        exit(1);
    }

    string relativeFileName = "config/relativePlots.txt";
    ifstream relativeFile(relativeFileName);

    if(!relativeFile.is_open())
    {
        cerr << "Error: failed to open " << relativeFileName << "; exiting..." << endl;
        exit(1);
    }

    string buffer;
    vector<string> nuclides;
    vector<pair<string,string>> relativeDiffNames;

    while(getline(configFile, buffer))
    {
        nuclides.push_back(buffer);
    }

    while(getline(relativeFile, buffer))
    {
        vector<string> tokens;
        istringstream iss(buffer);
        copy(istream_iterator<string>(iss),
                istream_iterator<string>(),
                back_inserter(tokens));

        relativeDiffNames.push_back(make_pair(tokens[0], tokens[1]));
    }

    // begin cross section calculation
    vector<CrossSection> crossSections;

    for(auto& nucleus : nuclides)
    {
        Nucleus N("config/" + nucleus + ".txt");

        cout << "Producing cross section for " << N.Name << endl;

        // define energy range
        vector<double> energyRange;

        double startingPoint = log(1);
        double stepSize = (log(500)-log(1))/100;

        for(unsigned int i=0; i<100; i++)
        {
            energyRange.push_back(exp(i*stepSize+startingPoint));
        }

        // identify which optical model should be used for cross section
        // calculation, and perform calculation
        string argument = argv[1];

        if(argument == "SA")
        {
            // strongly absorbing disk model

            crossSections.push_back(calculateCS_SA(N, energyRange));
        }

        else if(argument == "ROP")
        {
            // optical potential with only a real, Woods-Saxon part

            OpticalPotential OP("config/" + nucleus + "_ROP.txt");
            crossSections.push_back(calculateCS_ROP(N, OP, energyRange));
        }

        else if(argument == "COP")
        {
            // optical potential with real and imaginary Woods-Saxon parts

            OpticalPotential OP("config/" + nucleus + "_COP.txt");
            crossSections.push_back(calculateCS_COP(N, OP, energyRange));
        }

        else if(argument == "COPS")
        {
            // optical potential with real and imaginary Woods-Saxon and surface
            // (derivative of Woods-Saxon) parts

            OpticalPotential OP("config/" + nucleus + "_COPS.txt");
            crossSections.push_back(calculateCS_COPS(N, OP, energyRange));
        }

        else
        {
            cerr << "Error: argument describing the optical potential to be used must be supplied." << endl;
        return 1;
        }
    }

    // cross sections have been calculated; make plots
    TFile* file = new TFile("opticalModel.root","RECREATE");

    for(auto& cs : crossSections)
    {
        TGraph* graph = new TGraph(
                cs.getDataSet().getNumberOfPoints(),
                &cs.getDataSet().getXValues()[0],
                &cs.getDataSet().getYValues()[0]);

        graph->SetNameTitle(cs.name.c_str(), cs.name.c_str());
        graph->Write();
    }

    for(auto& pair : relativeDiffNames)
    {
        CrossSection firstCS;
        CrossSection secondCS;

        for(auto& cs : crossSections)
        {
            if(cs.name == pair.first)
            {
                firstCS = cs;
            }

            if(cs.name == pair.second)
            {
                secondCS = cs;
            }
        }

        if(firstCS.name=="" || secondCS.name=="")
        {
            cerr << "Error: failed to find both cross sections \""
                << pair.first << "\", \"" << pair.second
                << " needed to calculate relative difference." << endl;

            break;
        }

        CrossSection relativeDiff = calculateRelativeDiff(firstCS, secondCS);
        relativeDiff.name = "relativeDiff(" + pair.first + "," + pair.second + ")";
        TGraph* graph = new TGraph(
                relativeDiff.getDataSet().getNumberOfPoints(),
                &relativeDiff.getDataSet().getXValues()[0],
                &relativeDiff.getDataSet().getYValues()[0]);

        graph->SetNameTitle(relativeDiff.name.c_str(), relativeDiff.name.c_str());
        graph->Write();
    }

    file->Close();

    return 0;
}
void processWaveforms(TTree* treeToSort, vector<Plots>& targetPlots, TFile* outFile, string mode)
{
    TH1D* fittedTimeHisto = new TH1D("raw fitted times", "raw fitted times", TOF_BINS,TOF_LOWER_BOUND,TOF_RANGE);

    TH2D* deltaTVsPulseHeight = new TH2D("delta T vs. pulse height","delta T vs. pulse height", 200, -10, 10, 1580, 0, 15800);

    TH2D* deltaTVsPulseIntegral0 = new TH2D("delta T vs. pulse integral, target 0","delta T vs. pulse integral, target 0",100, -10, 10, pow(2,15), 0, pow(2,15));
    TH2D* deltaTVsPulseIntegral1 = new TH2D("delta T vs. pulse integral, target 1","delta T vs. pulse integral, target 1",100, -10, 10, pow(2,15), 0, pow(2,15));
    TH2D* deltaTVsPulseIntegral2 = new TH2D("delta T vs. pulse integral, target 2","delta T vs. pulse integral, target 2",100, -10, 10, pow(2,15), 0, pow(2,15));
    TH2D* deltaTVsPulseIntegral3 = new TH2D("delta T vs. pulse integral, target 3","delta T vs. pulse integral, target 3",100, -10, 10, pow(2,15), 0, pow(2,15));
    TH2D* deltaTVsPulseIntegral4 = new TH2D("delta T vs. pulse integral, target 4","delta T vs. pulse integral, target 4",100, -10, 10, pow(2,15), 0, pow(2,15));
    TH2D* deltaTVsPulseIntegral5 = new TH2D("delta T vs. pulse integral, target 5","delta T vs. pulse integral, target 5",100, -10, 10, pow(2,15), 0, pow(2,15));

    TH1D* triggerAmplitudeHisto = new TH1D("triggerAmplitudeHisto","triggerAmplitudeHisto",pow(2,14),0,pow(2,14));
    TH1D* relativeTriggerTimeHisto = new TH1D("relativeTriggerTimeHisto","relative trigger time, from start of fitted wavelet",200,-5,5);
    TH2D* relativeTriggerTimeVsAmplitude = new TH2D("relativeTriggerTimeVSAmplitude","relative trigger time vs amplitude", 200, -5, 5, pow(2,14), 0, pow(2,14));

    TH1D* gammaToGammaTimeH = new TH1D("gammaToGammaTimeH","time between consecutive gammas", 1000, -5, 5);

    if(mode=="DPP")
    {
        setBranchesHistos(treeToSort);

        int totalEntries = treeToSort->GetEntries();
        cout << "Total waveforms = " << totalEntries << endl;

        vector<double> triggerList;

        waveformWrap = new TMultiGraph("DPP waveforms", "DPP waveforms");
        vector<TGraph*> waveletGraphs;
        vector<TGraph*> triggerGraphs;

        int gammaGate[2] = {80,90};

        double prevGammaTime = 0;

        for(int j=1; j<totalEntries; j++)
        {
            if(j%1000==0)
            {
                cout << "Processing triggers on waveform " << j << "\r";
                fflush(stdout);
            }

            /*if(j>500)
            {
                break;
            }*/

            triggerList.clear();
            triggerValues.clear();

            // pull individual waveform event
            treeToSort->GetEntry(j);

            // calculate the baseline for this waveform
            BASELINE = calculateBaseline(*procEvent.waveform);

            // Loop through all points in the waveform and fit peaks
            for(int k=DPP_PEAKFIT_START; (size_t)k<procEvent.waveform->size(); k++)
            {
                // Check to see if this point creates a new trigger
                if(isTrigger(k, *procEvent.waveform))
                {
                    // trigger found - plot/fit/extract time

                    double timeDiff = procEvent.completeTime-procEvent.macroTime;
                    double microTime = fmod(timeDiff,MICRO_LENGTH);

                    if(microTime > gammaGate[0] && microTime < gammaGate[1])
                    {
                        processTrigger(j, k, triggerList, *procEvent.waveform);

                        double fullTime = procEvent.completeTime-procEvent.macroTime+data.trigger1Time+DPP_PEAKFIT_OFFSET;
                        gammaToGammaTimeH->Fill(fmod(fullTime,MICRO_LENGTH)-prevGammaTime);
                        prevGammaTime=fmod(fullTime,MICRO_LENGTH);

                        fillTriggerHistos(fullTime, targetPlots);
                        fittedTimeHisto->Fill(data.trigger1Time);
                    }

                    //processTrigger(j, k, triggerList, *procEvent.waveform);

                    break;
                }
            }

            //produceTriggerOverlay(j, triggerList, *procEvent.waveform);

            TH2D* deltaTVsPulseIntegralHisto;

            switch(procEvent.targetPos-1)
            {
                case 0:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral0;
                    break;

                case 1:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral1;
                    break;

                case 2:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral2;
                    break;

                case 3:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral3;
                    break;

                case 4:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral4;
                    break;

                case 5:
                    deltaTVsPulseIntegralHisto = deltaTVsPulseIntegral5;
                    break;
            }

            triggerAmplitudeHisto->Fill(data.peak1Amplitude);
            relativeTriggerTimeHisto->Fill(data.trigger1Time+DPP_PEAKFIT_OFFSET);
            relativeTriggerTimeVsAmplitude->Fill(data.trigger1Time+DPP_PEAKFIT_OFFSET,data.peak1Amplitude);

            deltaTVsPulseIntegralHisto->Fill(data.trigger1Time+DPP_PEAKFIT_OFFSET, procEvent.lgQ);
            deltaTVsPulseHeight->Fill(data.trigger1Time+DPP_PEAKFIT_OFFSET, data.peak1Amplitude);

            // Create a new graph for each wavelet
            //waveletGraphs.push_back(new TGraph());

            // Fill each micropulse graph with waveform samples
            /*for (int l=0; l<procEvent.waveform->size(); l++)
              {
              waveletGraphs.back()->SetPoint(l,l*SAMPLE_PERIOD,procEvent.waveform->at(l));
              }*/

            // Create a new graph for each wavelet
            //triggerGraphs.push_back(new TGraph());

            // Fill each micropulse graph with waveform samples
            //triggerGraphs.back()->SetPoint(0,triggerList[0],triggerValues[0]);

            fill(procEvent.waveform->begin(),procEvent.waveform->end(),BASELINE);
        }

        TGraph* exponentialFit = new TGraph();
        exponentialFit->SetPoint(0,-0.78,140);
        exponentialFit->SetPoint(1,0.16,206);
        exponentialFit->SetPoint(2,1.79,305);
        exponentialFit->SetPoint(3,2.82,417);
        exponentialFit->SetPoint(4,3.59,566);
        exponentialFit->SetPoint(5,4.4,929);
        exponentialFit->SetPoint(6,5.2,1482);
        exponentialFit->SetPoint(7,5.7,2149);
        exponentialFit->SetPoint(8,6.9,5319);
        exponentialFit->SetPoint(9,7.3,7808);
        exponentialFit->SetPoint(10,7.7,11395);
        exponentialFit->SetPoint(11,8.0,16200);
        exponentialFit->Write();

        // Add each wavelet graph to the MultiGraph
        for (int m=0; m<waveletGraphs.size(); m++)
        {
            //cout << "adding graph " << m << " to multigraph" << endl;
            waveletGraphs[m]->Draw();
            waveformWrap->Add(waveletGraphs[m],"l");
        }

        // Add each trigger graph to the MultiGraph
        for (int m=0; m<triggerGraphs.size(); m++)
        {
            //cout << "adding graph " << m << " to multigraph" << endl;
            triggerGraphs[m]->SetMarkerSize(2);
            triggerGraphs[m]->SetMarkerColor(2);
            triggerGraphs[m]->Draw();
            waveformWrap->Add(triggerGraphs[m],"*");
        }

        waveformWrap->Write();

        for(Plots p : targetPlots)
        {
            p.getTOFHisto()->Write();
            p.getEnergyHisto()->Write();
        }

        fittedTimeHisto->Write();

        deltaTVsPulseIntegral0->Write();
        deltaTVsPulseIntegral1->Write();
        deltaTVsPulseIntegral2->Write();
        deltaTVsPulseIntegral3->Write();
        deltaTVsPulseIntegral4->Write();
        deltaTVsPulseIntegral5->Write();

        deltaTVsPulseHeight->Write();

        relativeTriggerTimeHisto->Write();
        triggerAmplitudeHisto->Write();
        relativeTriggerTimeVsAmplitude->Write();

        gammaToGammaTimeH->Write();
    }

    else if(mode=="waveform")
    {
        setBranchesHistosW(treeToSort);

        triggerWalk = new TH2I("triggerWalk","trigger time vs. waveform chunk #",200,0,200,1000,0,1000);

        TH1I* monitorHisto = new TH1I("targetPosH", "targetPos", 7, 0, 7);
        monitorHisto->GetXaxis()->SetTitle("target position of each waveform");

        long triggersWithGamma = 0;
        vector<int> fullWaveform(MACRO_LENGTH/2, BASELINE);
        vector<double> triggerList;

        int prevTargetPos = 0;
        double firstTimetagInSeries = 0;

        int totalEntries = treeToSort->GetEntries();
        cout << "Total waveforms = " << totalEntries << endl;

        /*TCanvas *mycan = (TCanvas*)gROOT->FindObject("mycan");

          if(!mycan)
          {
          mycan = new TCanvas("mycan","mycan");
          }*/

        // EVENT LOOP for sorting through channel-specific waveforms
        for(int j=1; j<totalEntries; j++)
        {
            cout << "Processing triggers on waveform " << j << "\r";
            fflush(stdout);

            if(j>30)
            {
                break;
            }

            triggerList.clear();
            triggerValues.clear();

            prevTargetPos = procEvent.targetPos;

            // pull individual waveform event
            treeToSort->GetEntry(j);

            if(procEvent.evtNo==1)
            {
                // new macropulse; process the previous macropulse's waveform

                // calculate the baseline for this waveform
                BASELINE = calculateBaseline(fullWaveform);

                // Loop through all points in the waveform and fit peaks
                for(int k=PEAKFIT_WINDOW; (size_t)k<fullWaveform.size(); k++)
                {
                    // Check to see if this point creates a new trigger
                    if(isTrigger(k, fullWaveform))
                    {
                        // trigger found - plot/fit/extract time
                        processTrigger(j, k, triggerList, fullWaveform);

                        // shift waveform index past the end of this fitting window
                        // so that we don't refit the same data
                        k += PEAKFIT_WINDOW;
                    }
                    /*if(triggerList.size()>10)
                      {
                      for(int m=0; m<triggerList.size(); m++)
                      {
                      cout << "triggerList[" << m << "] = " << triggerList[m] << endl;
                      }
                      break;
                      }*/
                }

                // Use the gamma peaks to find the time offset for this waveform, and
                // adjust the microTime with this offset

                double gammaOffset = calculateGammaOffset(triggerList);

                /*for(int m=0; (size_t)m<triggerList.size(); m++)
                  {
                  fillTriggerHistos(triggerList[m]-gammaOffset, targetPlots);
                  }*/

                if(gammaOffset!=0)
                {
                    for(int m=0; (size_t)m<triggerList.size(); m++)
                    {
                        //fillTriggerHistos(triggerList[m]-gammaOffset+WAVEFORM_OFFSET, targetPlots);
                    }

                    triggersWithGamma++;
                }

                /*if(j<30)
                  {
                  produceTriggerOverlay(j, triggerList, fullWaveform);
                  }*/

                /*temp.str("");
                  temp << "waveformWrap" << j;

                  waveformWrap = new TMultiGraph(temp.str().c_str(), temp.str().c_str());

                  vector<TGraph*> microGraphs;

                // Create a new graph for each micropulse period to be plotted
                for (int m = 0; m<floor(2*procEvent.waveform->size()/MICRO_LENGTH); m++)
                {
                microGraphs.push_back(new TGraph());
                }

                // Fill each micropulse graph with waveform samples
                for (int l = 0; l<procEvent.waveform->size(); l++)
                {
                microGraphs[(int)floor(l/(double)MICRO_LENGTH)]->SetPoint(microGraphs[(int)floor(l/(double)MICRO_LENGTH)]->GetN(),fmod(2*l+WAVEFORM_OFFSET,MICRO_LENGTH),procEvent.waveform->at(l));
                //cout << "Adding value " << procEvent.waveform->at(l) << " to position " << fmod(l,MICRO_LENGTH) << " in microGraph " << floor(l/(double)MICRO_LENGTH) << endl;
                }

                // Add each graph to the MultiGraph
                for (int m = 0; m<microGraphs.size(); m++)
                {
                //cout << "adding graph " << m << " to multigraph" << endl;
                microGraphs[m]->Draw();
                waveformWrap->Add(microGraphs[m],"l");
                }

                waveformWrap->Write();
                */

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

                // Fill trigger histogram
                /*for (int l = 0; l<triggerList.size(); l++)
                  {
                  cout << "trigger " << l << " = " << triggerList[l] << ", " << triggerValues[l] << endl;
                  }*/

                //triggerH->Write();
                //cout << "Finished processing waveform " << j << endl << endl;

                /*if(j==10)
                  {
                  break;
                  }*/

                monitorHisto->Fill(prevTargetPos);

                fill(fullWaveform.begin(),fullWaveform.end(),BASELINE);

                firstTimetagInSeries = procEvent.completeTime;
            }

            if (procEvent.targetPos == 0)
            {
                continue;
            }

            double timeOffset = procEvent.completeTime-firstTimetagInSeries;

            if(timeOffset<MACRO_LENGTH-2*procEvent.waveform->size())
            {
                for(int k=0; k<procEvent.waveform->size(); k++)
                {
                    fullWaveform[timeOffset/SAMPLE_PERIOD+k] = procEvent.waveform->at(k);
                }
            }
        }

        cout << "Triggers with gamma in wavelet: " << triggersWithGamma << endl;

        monitorHisto->Write();

        for(Plots p : targetPlots)
        {
            p.getTOFHisto()->Write();
            p.getEnergyHisto()->Write();
        }

        cout << "Number of good fits: " << numberGoodFits << endl;
        cout << "onePeak = " << numberOnePeakFits << endl; 
        cout << "onePeakExpBack = " << numberOnePeakExpBackFits << endl; 
        cout << "twoPeaks = " << numberTwoPeakFits << endl << endl; 
        cout << "Number of bad fits: " << numberBadFits << endl;
    }

    else
    {
        cerr << "Error: digitizer mode was " << mode << "; only possible options are 'DPP' or 'waveform'. Exiting..." << endl;
        exit(1);
    }
}
Example #27
0
void all(int channels=0, int categ=-1, int sample=2012 /*,bool doSfLepton=true*/){

  double bwSigma[40];
  int mass[40]; int id[40]; double xLow[40]; double xHigh[40];  
  int maxMassBin;

    float masses[1] = {125};
    for(int i=0;i<1;++i) {
      mass[i] = masses[i]; 
      id[i]=masses[i]; 
      xLow[i] = 105.; // getFitEdge(masses[i],width,true); 
      xHigh[i] = 140.; // getFitEdge(masses[i],width,false); 
      //cout << "For mass = " << masses[i] << " width = " << width << "; => Fit Range = [" << xLow[i] << "," << xHigh[i] << "]" << endl;
      bwSigma[i] = 0.004;
    }
    maxMassBin = 1;   // 29;
  // -----------------------



  double massV[40],massE[40];
  for(int i=0; i<maxMassBin;++i){
    massV[i]=mass[i];
    massE[i]=0;
  }
  double A1Val[40],A1Err[40];
  double A2Val[40],A2Err[40];
  double a1Val[40],a1Err[40];
  double a2Val[40],a2Err[40];
  double n1Val[40],n1Err[40];
  double n2Val[40],n2Err[40];
  double meanCBVal[40],meanCBErr[40];
  double sigmaCBVal[40],sigmaCBErr[40];
  double meanBWVal[40],meanBWErr[40];
  double covQualVal[40];

  double fitValues[10];
  double fitErrors[10];
  double covQual[1];

  
  for(int i=0; i<maxMassBin;++i){
    fitSignalShapeW(mass[i],id[i],channels,categ, sample,/* 10.,doSfLepton,*/xLow[i],xHigh[i],bwSigma[i],
		    fitValues,fitErrors,covQual);  

    cout << "a1 value,error: " << fitValues[0] << " , " << fitErrors[0] << endl; 
    a1Val[i]=fitValues[0]; a1Err[i]=fitErrors[0];

    cout << "a2 value,error: " << fitValues[1] << " , " << fitErrors[1] << endl; 
    a2Val[i]=fitValues[1]; a2Err[i]=fitErrors[1];

    cout << "n1 value,error: " << fitValues[4] << " , " << fitErrors[4] << endl; 
    n1Val[i]=fitValues[4]; n1Err[i]=fitErrors[4];

    cout << "n2 value,error: " << fitValues[5] << " , " << fitErrors[5] << endl; 
    n2Val[i]=fitValues[5]; n2Err[i]=fitErrors[5];

    cout << "meanCB value,error: " << fitValues[2] << " , " << fitErrors[2] << endl;
    meanCBVal[i]=fitValues[2]; meanCBErr[i]=fitErrors[2];
    
    cout << "sigmaCB value,error: " << fitValues[6] << " , " << fitErrors[6] << endl; 
    sigmaCBVal[i]=fitValues[6]; sigmaCBErr[i]=fitErrors[6];

    cout << "meanBW value,error: " << fitValues[3] << " , " << fitErrors[3] << endl; 
    meanBWVal[i]=fitValues[3]; meanBWErr[i]=fitErrors[3];

    cout << "A1 value,error: " << fitValues[7] << " , " << fitErrors[7] << endl;
    A1Val[i]=fitValues[7]; A1Err[i]=fitErrors[7];

    cout << "A2 value,error: " << fitValues[8] << " , " << fitErrors[8] << endl;
    A2Val[i]=fitValues[8]; A2Err[i]=fitErrors[8];

    cout << "covQual of the fit: " << covQual[0] << endl;
    covQualVal[i] = covQual[0];

  }
  

  stringstream namefile;
  namefile << "parameters_channel" << channels<< categ << ".root";
  TFile *resultfile = TFile::Open(namefile.str().c_str(),"RECREATE");
 
  TGraphErrors* gA1 = new TGraphErrors(maxMassBin,massV,a1Val,massE,a1Err);
  TGraphErrors* gA2 = new TGraphErrors(maxMassBin,massV,a2Val,massE,a2Err);
  TGraphErrors* gN1 = new TGraphErrors(maxMassBin,massV,n1Val,massE,n1Err);
  TGraphErrors* gN2 = new TGraphErrors(maxMassBin,massV,n2Val,massE,n2Err);
  TGraphErrors* gMeanCB = new TGraphErrors(maxMassBin,massV,meanCBVal,massE,meanCBErr);
  TGraphErrors* gSigmaCB = new TGraphErrors(maxMassBin,massV,sigmaCBVal,massE,sigmaCBErr);
  TGraphErrors* gMeanBW = new TGraphErrors(maxMassBin,massV,meanBWVal,massE,meanBWErr);
  TGraphErrors* gAA1 = new TGraphErrors(maxMassBin,massV,A1Val,massE,A1Err);
  TGraphErrors* gAA2 = new TGraphErrors(maxMassBin,massV,A2Val,massE,A2Err);
  TGraph* gCovQual = new TGraph(maxMassBin,massV,covQualVal);

  gA1->SetName("gA1");  gA1->SetMarkerStyle(20);   gA1->SetMarkerSize(1);
  gA2->SetName("gA2");  gA2->SetMarkerStyle(20);   gA2->SetMarkerSize(1);
  gN1->SetName("gN1");  gN1->SetMarkerStyle(20);   gN1->SetMarkerSize(1);
  gN2->SetName("gN2");  gN2->SetMarkerStyle(20);   gN2->SetMarkerSize(1);
  gMeanCB->SetName("gMeanCB"); gMeanCB->SetMarkerStyle(20);   gMeanCB->SetMarkerSize(1);
  gSigmaCB->SetName("gSigmaCB"); gSigmaCB->SetMarkerStyle(20);   gSigmaCB->SetMarkerSize(1);
  gMeanBW->SetName("gMeanBW"); gMeanBW->SetMarkerStyle(20);   gMeanBW->SetMarkerSize(1);
  gAA1->SetName("gAA1");  gAA1->SetMarkerStyle(20);   gAA1->SetMarkerSize(1);
  gAA2->SetName("gAA2");  gAA2->SetMarkerStyle(20);   gAA2->SetMarkerSize(1);

  gCovQual->SetName("gCovQual"); gCovQual->SetMarkerStyle(20);   gCovQual->SetMarkerSize(1);
  
  gA1->SetTitle("");
  gA1->GetXaxis()->SetTitle("mass (GeV)");
  gA1->GetYaxis()->SetTitle("CB a-parameter");

  gA2->SetTitle("");
  gA2->GetXaxis()->SetTitle("mass (GeV)");
  gA2->GetYaxis()->SetTitle("CB a-parameter");

  gN1->SetTitle("");
  gN1->GetXaxis()->SetTitle("mass (GeV)");
  gN1->GetYaxis()->SetTitle("CB n-parameter");

  gN2->SetTitle("");
  gN2->GetXaxis()->SetTitle("mass (GeV)");
  gN2->GetYaxis()->SetTitle("CB n-parameter");

  gMeanCB->SetTitle("");
  gMeanCB->GetXaxis()->SetTitle("mass (GeV)");
  gMeanCB->GetYaxis()->SetTitle("CB mean");

  gSigmaCB->SetTitle("");
  gSigmaCB->GetXaxis()->SetTitle("mass (GeV)");
  gSigmaCB->GetYaxis()->SetTitle("CB sigma");

  gMeanBW->SetTitle("");
  gMeanBW->GetXaxis()->SetTitle("mass (GeV)");
  gMeanBW->GetYaxis()->SetTitle("BW mean");

  gAA1->SetTitle("");
  gAA1->GetXaxis()->SetTitle("mass (GeV)");
  gAA1->GetYaxis()->SetTitle("Chebyshev a1-parameter");

  gAA2->SetTitle("");
  gAA2->GetXaxis()->SetTitle("mass (GeV)");
  gAA2->GetYaxis()->SetTitle("Chebyshev a2-parameter");


  gCovQual->SetTitle("");
  gCovQual->GetXaxis()->SetTitle("mass (GeV)");
  gCovQual->GetYaxis()->SetTitle("cov. matrix qual.");
  
  resultfile->cd();
  gA1->Fit("pol0"); gA1->Draw("Ap"); gA1->Write();
  gA2->Fit("pol0"); gA2->Draw("Ap"); gA2->Write();
  gN1->Fit("pol1"); gN1->Draw("Ap"); gN1->Write();
  gN2->Fit("pol1"); gN2->Draw("Ap"); gN2->Write();
  gMeanCB->Fit("pol1"); gMeanCB->Draw("Ap"); gMeanCB->Write();
  gSigmaCB->Fit("pol1"); gSigmaCB->Draw("Ap"); gSigmaCB->Write();
  gAA1->Fit("pol0"); gAA1->Draw("Ap"); gAA1->Write();
  gAA2->Fit("pol0"); gAA2->Draw("Ap"); gAA2->Write(); 
  gCovQual->Write();

  resultfile->Close();

}
void Neutrals (/*TH1 *h1*/)//const char *part="e")//,int nevent = 1000)
{
  cout << "TEST VII" << endl; 
  char infile[100];
  int pz[9] = {1,2,4,8,12,16,32,40,50};
  double x[9];
  double means[9] = {0};
  double y[9];
  double mval = 0;
  int lastbincont = 0;
  bool lastbin = false;
  int var = 11;
  double intnum[1000]  = {0};
  double varnum[1000] = {0};
  char *part[] = {"gamma","neutron","anti_neutron"};
  int i = 0;
  int w =4;
  //TCanvas *c3 = new TCanvas("TresGraphitos","stupid graph",1);
  // TH1F *h4 = new TH1F("histo","histo",1000,0,.5);
  //TH2F *h3 = new TH2F("HistoGraph","HistoGraph",1000,0,.55,1000,0,1.2);
  // TMarker *grmark = new TMarker();
  //	  TCanvas *c19 = new TCanvas();
  // h3->Draw();
  for (int q=0; q<3; q++) 
  {
    for (int w=0; w<9;w++)
    {
      cout << "TEST VI" << endl;
      char ffile[100];
      sprintf(ffile,"/phenix/u/jpinkenburg/sPHENIX/analysis/AntiSigma/macros/HistoBaseFiles/%s_ThinBins.root", part[q]);
      TFile *f = TFile::Open(ffile);
      char hname[100];
      sprintf(hname,"%s%dd",part[q],pz[w]);
      TH1F *h1 = (TH1F *)f->Get(hname);
      var = 11;
      i = 0;
      while (var <= 8001)
      {

	if (i<1000)
	{
	  varnum[i] = .005*(i);
	  intnum[i] = (h1->Integral(var-10,var))/10000.;//(h1->Integral());
	  i++;
	}
	var+=10;
      }
      // varnum[0] = 0;
      // intnum[0] = 0;
      char fname [100];
      sprintf(fname, "Gamma_Neutron_Hijing_Energy_Graphs.root");
      TFile *fout = TFile::Open(fname,"UPDATE");
      // h1->Write();
      //fout->Write();
      f->Close();
      //char hname[100];
      //sprintf(hname,"%s%dGeV",part[q],pz[w]);
      // cout << h1->Integral() << " "  <<  hname << " " << pz[i] << endl;
      //TH2 *h2 = new TH2F("hname","hname",1,0,5,1,0,1.2);
      gStyle->SetOptStat(0);

	  
      TMarker *mean = new TMarker();
      mean->SetMarkerStyle(20);
      mean->SetMarkerColor(3);
      char canvname[100];
      sprintf(canvname,"%s%d",part[q],pz[w]);
      //TCanvas *c3 = new TCanvas(canvname,"stupid graph",1);
      //double dtot[9] = {0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9}; 
      cout << "TEST V" << endl;
      TGraph *gr = new TGraph((i-2),varnum,intnum);
      char gtitle[100];
      sprintf(gtitle,"%s%dGeV;ConeSize;Percentage of Energy Deposited",part[q],pz[w]);
      char gname[100];
      sprintf(gname,"%s%dGeV",part[q],pz[w]);
      cout << intnum[50] << " " << varnum[50] << endl;
      gr->SetTitle(gtitle);
      gr->SetName(gname);
      gr->SetMarkerStyle(20);
      if (part[q] == "anti_neutron")
      {
	gr->SetMarkerColor(4);
      }
      else if (part[q] == "neutron")
      {
	gr->SetMarkerColor(2);
      }
      else if (part[q] == "gamma")
      {
	gr->SetMarkerColor(3);
      }
      else 
      {
	cout << "idiot" << endl;
      }
//	  gr->SetMaximum(1.2);
      //h2->Draw();
      //gr->Draw("A*");
      gr->Draw("ALP");
      //c3->DrawFrame(0,0,0.5,1.2);
      // gr->PaintGrapHist((i-1),varnum,intnum,"chopt");
      //	  gr->SetHistogram(h4);
      //h4->Write();
      gr->Write();
      cout << "TEST 1" << endl;
      //  TH2F *h3 = (TH2F *) "HistoGraph";
      cout << "TEST II" << endl;

      cout << "TEST III" << endl;
      //h3->Write();
      cout << "TEST IV" << endl;
      //double x;
      //double y;
      //gr()->GetPoint(

      fout->Write();
      fout->Close();
      //	  gr->Close();
      for (int a=0;a<1000;a++)
      {
	intnum[a] = 0;
	varnum[a] = 0;
      }
	  
    }
  }
}