Пример #1
0
//______________________________________________________________________________
void drawsparse_draw(THnSparse* h)
{
   // Draw a THnSparse using TParallelCoord, creating a temporary TTree.

   TTree* tree = toTree(h);

   TString whatToDraw;
   TIter iLeaf(tree->GetListOfLeaves());
   const TLeaf* leaf = 0;
   while ((leaf = (const TLeaf*)iLeaf())) {
      if (whatToDraw.Length())
         whatToDraw += ":";
      whatToDraw += leaf->GetName();
   }
   tree->Draw(whatToDraw, "", "para");
   TParallelCoord* parallelCoord = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject("ParaCoord");

   TIter iVar(parallelCoord->GetVarList());
   TParallelCoordVar* var = 0;
   for (Int_t d = 0;(var = (TParallelCoordVar*) iVar()) && d < h->GetNdimensions(); ++d) {
      TAxis* axis = h->GetAxis(d);
      var->SetHistogramBinning(axis->GetNbins());
      var->SetCurrentLimits(axis->GetXmin(), axis->GetXmax());
      var->SetTitle(axis->GetTitle());
   }
   var->SetTitle("bin content");
}
void BinLog(TH2F *h) 
{

   TAxis *axis = h->GetXaxis(); 
   int bins = axis->GetNbins();

   Axis_t from = axis->GetXmin();
   Axis_t to = axis->GetXmax();
   Axis_t width = (to - from) / bins;
   Axis_t *new_bins = new Axis_t[bins + 1];

   for (int i = 0; i <= bins; i++) {
     new_bins[i] = TMath::Power(10, from + i * width);
   } 
   axis->Set(bins, new_bins); 

   TAxis *axis2 = h->GetYaxis(); 
   int bins2 = axis2->GetNbins();

   Axis_t from2 = axis2->GetXmin();
   Axis_t to2 = axis2->GetXmax();
   Axis_t width2 = (to2 - from2) / bins2;
   Axis_t *new_bins2 = new Axis_t[bins2 + 1];

   for (int i = 0; i <= bins2; i++) {
     new_bins2[i] = TMath::Power(10, from2 + i * width2);
   } 
   axis2->Set(bins2, new_bins2); 

   delete new_bins;
   delete new_bins2;
}
Пример #3
0
 /** comapre axis for equalitiy
  *
  * check whether the cass histogram axis and the root histogram axis are the
  * same. Test for number of bins, low and high ends and the title of the axis.
  *
  * @return true when both axis are the same
  * @param ca the axis of the cass histogram
  * @param ra the axis of the root histogram
  *
  * @author Lutz Foucar
  */
 bool operator== (const cass::Result<float>::axe_t &ca, const TAxis &ra)
 {
   return (static_cast<int>(ca.nBins) == ra.GetNbins() &&
           fabs(ca.low - ra.GetXmin()) <  sqrt(numeric_limits<double>::epsilon()) &&
           fabs(ca.up  - ra.GetXmax())  <  sqrt(numeric_limits<double>::epsilon()) &&
           ca.title == ra.GetTitle());
 }
Пример #4
0
//Get background counts on NRS from Geant4 simulation template (histogram)
void ResonanceSimulator::get_background(){
	TAxis *xaxis = hbkg->GetXaxis(); 
	int binx = xaxis->FindBin(e_cut);
	int binmax = xaxis->GetXmax();
	N_background = hbkg->Integral(binx,binmax);

return;
}
Пример #5
0
int getBin(TH1* theHist, double x) {

    // Find the bin number for the given x value
    if (!theHist) {return 0;}

    TAxis* xAxis = theHist->GetXaxis();
    double xMin = xAxis->GetXmin();
    double xMax = xAxis->GetXmax();
    int nX = theHist->GetNbinsX();
    double dx = (xMax - xMin)/(nX*1.0);
    
    int theBin = int(((x - xMin)/dx) + 0.5);
    return theBin;
    
}
Пример #6
0
void findFilterEnergyLoss::BinLogY(TH2 *h) {
   TAxis *axis = h->GetYaxis();
   int bins = axis->GetNbins();

   Axis_t from = axis->GetXmin();
   Axis_t to = axis->GetXmax();
   Axis_t width = (to - from) / bins;

   Axis_t *new_bins = new Axis_t[bins+1];

   for (int i=0; i <= bins; i++) {
      new_bins[i] = TMath::Power(10, from + i * width);
   }

   axis->Set(bins, new_bins);
   delete new_bins;
}
Пример #7
0
void rebin() {
   //create a fix bin histogram
   TH1F *h = new TH1F("h","test rebin",100,-3,3);
   Int_t nentries = 1000;
   h->FillRandom("gaus",nentries);
   Double_t xbins[1001];
   Int_t k=0;
   TAxis *axis = h->GetXaxis();
   for (Int_t i=1;i<=100;i++) {
      Int_t y = (Int_t)h->GetBinContent(i);
      if (y <=0) continue;
      Double_t dx = axis->GetBinWidth(i)/y;
      Double_t xmin = axis->GetBinLowEdge(i);
      for (Int_t j=0;j<y;j++) {
         xbins[k] = xmin +j*dx;
         k++;
      }
   }
   xbins[k] = axis->GetXmax();
   //create a variable bin-width histogram out of fix bin histogram
   //new rebinned histogram should have about 10 entries per bin
   TH1F *hnew = new TH1F("hnew","rebinned",k,xbins);
   hnew->FillRandom("gaus",10*nentries);

   //rebin hnew keeping only 50% of the bins
   Double_t xbins2[501];
   Int_t kk=0;
   for (Int_t j=0;j<k;j+=2) {
      xbins2[kk] = xbins[j];
      kk++;
   }
   xbins2[kk] = xbins[k];
   TH1F *hnew2 = (TH1F*)hnew->Rebin(kk,"hnew2",xbins2);

   //draw the 3 histograms
   TCanvas *c1 = new TCanvas("c1","c1",800,1000);
   c1->Divide(1,3);
   c1->cd(1);
   h->Draw();
   c1->cd(2);
   hnew->Draw();
   c1->cd(3);
   hnew2->Draw();
}
Пример #8
0
void BinLogAxis(const TH1 *h)
{
  //
  // Method for the correct logarithmic binning of histograms
  //
  TAxis *axis = const_cast<TAxis*>(h->GetXaxis());
  const Int_t bins = axis->GetNbins();
  
  const Double_t from = axis->GetXmin();
  const Double_t to = axis->GetXmax();
  Double_t *newBins = new Double_t[bins + 1];
  
  newBins[0] = from;
  Double_t factor = pow(to / from, 1. / bins);
  
  for (Int_t i = 1; i <= bins; i++) {
    newBins[i] = factor * newBins[i - 1];
  }
  axis->Set(bins, newBins);
  delete [] newBins;
  
}
void makePlot_wrapper(const TString& title, 
		      const TH1* histogram_numerator_Data_passed, const TH1* histogram_denominator_Data_passed, 
		      const TH1* histogram_numerator_mcSum_passed, const TH1* histogram_denominator_mcSum_passed, 
		      const TH1* histogram_numerator_Data_failed, const TH1* histogram_denominator_Data_failed, 
		      const TH1* histogram_numerator_mcSum_failed, const TH1* histogram_denominator_mcSum_failed, 
		      const TString& legendEntry_Data, const TString& legendEntry_mcSum, 
		      const TString& region_passed, const TString& region_failed,
		      const TString& outputFileName)
{
  TAxis* xAxis = histogram_numerator_Data_passed->GetXaxis();
  Double_t xMin = xAxis->GetXmin();
  Double_t xMax = xAxis->GetXmax();

  std::cout << "processing Data, region " << region_passed.Data() << "..." << std::endl;
  TGraphAsymmErrors* graph_efficiency_Data_passed = 
    getEfficiency(histogram_numerator_Data_passed, histogram_denominator_Data_passed);   
  TF1* fit_efficiency_Data_passed = new TF1("fit_efficiency_Data_passed", &integralCrystalBall_f, xMin, xMax, 5);
  initializeCrystalBall(fit_efficiency_Data_passed);
  graph_efficiency_Data_passed->Fit(fit_efficiency_Data_passed, "0");
  TString legendEntry_Data_passed = Form("%s, %s", legendEntry_Data.Data(), region_passed.Data());

  std::cout << "processing mcSum, region " << region_passed.Data() << "..." << std::endl;
  TGraphAsymmErrors* graph_efficiency_mcSum_passed = 
    getEfficiency(histogram_numerator_mcSum_passed, histogram_denominator_mcSum_passed);   
  TF1* fit_efficiency_mcSum_passed = new TF1("fit_efficiency_mcSum_passed", &integralCrystalBall_f, xMin, xMax, 5);
  initializeCrystalBall(fit_efficiency_mcSum_passed);
  graph_efficiency_mcSum_passed->Fit(fit_efficiency_mcSum_passed, "0");
  TString legendEntry_mcSum_passed = Form("%s, %s", legendEntry_mcSum.Data(), region_passed.Data());

  std::cout << "processing Data, region " << region_failed.Data() << "..." << std::endl;
  TGraphAsymmErrors* graph_efficiency_Data_failed = 
    getEfficiency(histogram_numerator_Data_failed, histogram_denominator_Data_failed);   
  TF1* fit_efficiency_Data_failed = new TF1("fit_efficiency_Data_failed", &integralCrystalBall_f, xMin, xMax, 5);
  initializeCrystalBall(fit_efficiency_Data_failed);
  graph_efficiency_Data_failed->Fit(fit_efficiency_Data_failed, "0");
  TString legendEntry_Data_failed = Form("%s, %s", legendEntry_Data.Data(), region_failed.Data());

  std::cout << "processing mcSum, region " << region_failed.Data() << "..." << std::endl;
  TGraphAsymmErrors* graph_efficiency_mcSum_failed = 
    getEfficiency(histogram_numerator_mcSum_failed, histogram_denominator_mcSum_failed);   
  TF1* fit_efficiency_mcSum_failed = new TF1("fit_efficiency_mcSum_failed", &integralCrystalBall_f, xMin, xMax, 5);
  initializeCrystalBall(fit_efficiency_mcSum_failed);
  graph_efficiency_mcSum_failed->Fit(fit_efficiency_mcSum_failed, "0");
  TString legendEntry_mcSum_failed = Form("%s, %s", legendEntry_mcSum.Data(), region_failed.Data());

  makePlot(title,
	   graph_efficiency_Data_passed,  fit_efficiency_Data_passed,  legendEntry_Data_passed,
	   graph_efficiency_mcSum_passed, fit_efficiency_mcSum_passed, legendEntry_mcSum_passed,
	   graph_efficiency_Data_failed,  fit_efficiency_Data_failed,  legendEntry_Data_failed,
	   graph_efficiency_mcSum_failed, fit_efficiency_mcSum_failed, legendEntry_mcSum_failed,
	   outputFileName);

  delete graph_efficiency_Data_passed;
  delete fit_efficiency_Data_passed;
  delete graph_efficiency_mcSum_passed;
  delete fit_efficiency_mcSum_passed;
  delete graph_efficiency_Data_failed;
  delete fit_efficiency_Data_failed;
  delete graph_efficiency_mcSum_failed;
  delete fit_efficiency_mcSum_failed;
}
void BkgDemo_Diplot(TCanvas* c, TH1F** h, TLegend* l1, TLegend* l2){
		//Make a split canvas, comparison of methods and tag above, bkg subtracted tag below
//	printf("\nDo BkgDemo_Diplot for canvas %s\n",c->GetName());
//	printf("integrals stage1: tag %f usb %f lsb %f\n",h[1]->Integral(),h[5]->Integral(),h[6]->Integral());

	
	TLatex * TEX_CMSPrelim;
	if(preliminary) TEX_CMSPrelim = new TLatex(0.177136,0.953368,"CMS Preliminary"); 
	else TEX_CMSPrelim = new TLatex(0.177136,0.953368,"CMS"); 
	PrettyLatex(TEX_CMSPrelim,0.03);
	TLatex * TEX_E_TeV = new TLatex(0.800251,0.953368,"#sqrt{s} = 8 TeV");
	PrettyLatex(TEX_E_TeV,0.03);
	TLatex * TEX_lumi_fb = new TLatex(0.621859,0.953368,Form("#intL dt = %.1f fb^{-1}",Integrated_Luminosity_Data));
	PrettyLatex(TEX_lumi_fb,0.03);
	string sp1 = string(c->GetName())+"_p1";
	string sp2 = string(c->GetName())+"_p2";
    TPad *p1 = new TPad((char*)sp1.c_str(),"",0.,0.3,1.,1.);
    p1->SetBottomMargin(0);
    p1->cd();
//	c->Divide(1,2);
//	c->cd(1);
	PrettyHist(h[3],kRed);
	PrettyHist(h[5],kBlue);
	PrettyHist(h[1]);
	PrettyHist(h[6],kGreen);
	//PrettyHist(h[3],kRed);
	PrettyHist(h[7],kTeal);
PrettyBlock2(h[5],kBlue,3354,2);
	//PrettyBlock(h[5],kBlue,string("//thatch"));//PrettyMarker(h[5],kBlue,4);
	PrettyMarker(h[1]);
PrettyBlock2(h[6],kGreen,3345,2);
	//PrettyBlock(h[6],kGreen,string("\\thatch"));//PrettyMarker(h[6],kGreen,4);
	//PrettyMarker(h[3],kRed);
	PrettyMarker(h[7],kTeal);
//	h[5]->Scale(mHwidth/sidebandwidth);//lsb scaled
//	h[6]->Scale(mHwidth/sidebandwidth);//usb scaled
//	printf("integrals stage2: tag %f usb %f lsb %f\n",h[1]->Integral(),h[5]->Integral(),h[6]->Integral());
//	printf("ranges maximi before setrange tag %f lsb %f, usb %f\n",h[1]->GetMaximum(),h[5]->GetMaximum(),h[6]->GetMaximum());
//	printf("integrals stage3: tag %f usb %f lsb %f\n",h[1]->Integral(),h[5]->Integral(),h[6]->Integral());
//	printf("ranges maximi before after tag %f lsb %f usb %f\n",h[1]->GetMaximum(),h[5]->GetMaximum(),h[6]->GetMaximum());
	h[3]->SetFillStyle(0);//open rectangle
	h[3]->SetLineColor(kRed);
	h[3]->SetLineWidth(4);

	h[6]->SetMinimum(0.0);
	//float linmax = h[6]->GetMaximum();
	//float linmin = h[6]->GetMinimum();
	playNiceWithLegend(h[6],0.30,0.0);
	playNiceWithLegend(h[3],0.30,0.0);
	playNiceWithLegend(h[5],0.30,0.0);
	playNiceWithLegend(h[1],0.30,0.0);
	SameRange(h[3],h[1]);
	SameRange(h[3],h[5],h[6]);
	SameRange(h[3],h[1]);
	h[3]->Draw("e2p");
	h[5]->Draw("e2psame");
	h[6]->Draw("e2psame");
	h[3]->Draw("e2psame");
	//if(showTag) h[1]->Draw("e1psame");//tag
	TPad *p2 = new TPad((char*)sp2.c_str(),"",0.,0.125,1.,0.3);
    p2->SetTopMargin(0);
    p2->cd();
//	c->cd(2);
	TAxis * x = h[7]->GetXaxis();
	TAxis * y = h[7]->GetYaxis();
	float fontsize = 0.25;
	float fontsizeY = 0.10;
	x->SetTitleSize(fontsize);
	y->SetTitleSize(fontsizeY);
	x->SetLabelSize(fontsize);
	y->SetLabelSize(fontsizeY);

	h[7]->GetYaxis()->SetRangeUser(0.,2.);
	h[7]->Draw("e1p");
	TLine *OneLine = new TLine(x->GetXmin(),1.0,x->GetXmax(),1.0);
	OneLine->SetLineColor(kBlack);
	OneLine->SetLineWidth(2);
	OneLine->SetLineStyle(7);//dashed.
	OneLine->Draw("same");
	h[7]->Draw("e1psame");
	
	p1->cd();
//  c->cd(1);
	if(showTag) l1->AddEntry(h[1],"Higgs Mass Region");
        TH1F * box = new TH1F("box","asdf",1,0,1);
        box->SetMarkerColor(kRed);
        box->SetMarkerStyle(25);
        box->SetMarkerSize(2);
        box->SetLineColor(0);
	l1->AddEntry(box,"Data Driven Background");
	l1->AddEntry(h[5],"Lower Mass Sideband");
	l1->AddEntry(h[6], "Upper Mass Sideband");
	l1->Draw("same");
        TEX_CMSPrelim->Draw("same");
        TEX_E_TeV->Draw("same");
        TEX_lumi_fb->Draw("same");
	p2->cd();
		//c->cd(2);
	l2->SetTextSize(fontsize*0.8);
	l2->AddEntry(h[7],"Lower/Upper Sideband Ratio");
	l2->Draw("same");
    c->cd();
	p1->Draw();
	p2->Draw();
}
void format_plots_data(){
	cout<<"hello world"<<endl;
	CMSStyle();
	
		///////////////////////////// Switcehs //////////////////////////////////////

        int nKinemVars = nKinemVars_all;
	string *s_KinemVars = s_KinemVars_all;


	int printlevel = 1;
	bool saveImages = true;
	
	bool makediphoMassPlot = 1;
	bool makeBkgDemo = 1;
	bool makeBkg1 = 0;
	bool makeBkgRat = 0;	
		///////////////////////////// File Work ///////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Start File work" << endl;

		///INPUT FILES
	const int nDataAndMcFiles = 1;
	string Data = "Data";
	string s_DataAndMcFiles[nDataAndMcFiles]    = {Data};//** FOR INEDEXING
	string s_DataAndMcFiles_v4[nDataAndMcFiles] = {Data};

		///Output File
	TFile* fplots = new TFile(formatedplotsroot_data.c_str(),"RECREATE");

	TFileMap PostAnaAnaFiles;
	TFileMap MainAnaFiles;
	cout<<endl<<"Reading in data file "<<plotsAndBackground_data<<endl<<endl;
	PostAnaAnaFiles[Data] = new TFile(plotsAndBackground_data.c_str());
	MainAnaFiles[Data]    = new TFile(plotsroot_data.c_str());
	
//	PostAnaAnaFiles["st350ho200"] = new TFile(plotsAndBackground_mc.c_str());
//	MainAnaFiles["st350ho200"]    = new TFile(plotsroot_mc.c_str());

	cout<<endl<<"Writing finished plots to file "<<plotsroot_data<<endl<<endl;

                ///////////////////////////// STANDARD MARKINGS ///////////////////////////////////////
        TLatex * TEX_CMSPrelim;
        if(preliminary) TEX_CMSPrelim = new TLatex(0.177136,0.953368,"CMS Preliminary");
        else TEX_CMSPrelim = new TLatex(0.177136,0.953368,"CMS");
        PrettyLatex(TEX_CMSPrelim,0.03);
        TLatex * TEX_E_TeV = new TLatex(0.800251,0.953368,"#sqrt{s} = 8 TeV");
        PrettyLatex(TEX_E_TeV,0.03);
        TLatex * TEX_lumi_fb = new TLatex(0.621859,0.953368,Form("#intL dt = %.1f fb^{-1}",Integrated_Luminosity_Data));
        PrettyLatex(TEX_lumi_fb,0.03);


		///////////////////////////// Other Lists ///////////////////////////////////////	
	/*Debug*/ if(printlevel > 0) cout << "Make Other Lists" << endl;


	
		/////////////// FOR INDEXING, USE THESE /////////////////////////
		///	string s_MassBkgDists[nPhoMassAndBkgDists]={lowSB,tag,upperSB,bkg,tag_subbkg,lowSB_scaled,upperSB_scaled};
		/// string s_EventTopology[nEventTopologies]={"","1Jb","3J","3Jb","metCut"};
		/// string s_KinemVars[nKinemVars]={"MET","ST","PtGG","HT","MHT"};
		/// string s_DataAndMcFiles[nDataAndMcFiles]={Data,"MC_st350ho200"...}
		/////////////////////////////////////////////////////////////////



		//	const int nEventTopologies = 5; // the number of types of cuts selected, like 1JB...
		//string s_EventTopology[nEventTopologies] = {"","1Jb","3J","3Jb","metCut"};//** FOR INEDEXING
	string s_EventTopology_v2[nEventTopologies];//{"","_1Jb","_3J","_3Jb","_metCut"};
	string s_EventTopology_v3[nEventTopologies];//{"","_1Jb_","_3J_","_3Jb_","_metCut_"};
	//s_EventTopology_v2[0]=s_EventTopology[0];
	//s_EventTopology_v3[0]=s_EventTopology[0];
	for (int i=0; i<nEventTopologies; i++) {
		s_EventTopology_v2[i] = string("_")+s_EventTopology[i];
		s_EventTopology_v3[i] = string("_")+s_EventTopology[i]+"_";
	}

	//const int nPhoMassAndBkgDists //lsb, tag, usb...
	//	string s_MassBkgDists[] = {"lowSB","tag","upperSB","bkg","tag_subbkg","lowSB_scaled","upperSB_scaled"};
	//	string s_MassBkgDists_v2[] = {"_lowSB","_tag","_upperSB","_bkg","_tag_subbkg","_lowSB_scaled","_upperSB_scaled"};
	string s_MassBkgDists_v2[nPhoMassAndBkgDists];
	for (int i=0; i<nPhoMassAndBkgDists; i++) {s_MassBkgDists_v2[i]=string("_")+s_MassBkgDists[i];}

	string s_DataAndMcFiles_v2[nDataAndMcFiles];
	string s_DataAndMcFiles_v3[nDataAndMcFiles];
	s_DataAndMcFiles_v2[0]=Data;//{Data,"MC_st350ho200"...}
	s_DataAndMcFiles_v3[0]=Data;//{Data,"MC","MC","MC"...}
	for (int i=1; i<nDataAndMcFiles; i++) {s_DataAndMcFiles_v3[i]=string("MC_")+s_DataAndMcFiles[i];}
	for (int i=1; i<nDataAndMcFiles; i++) {s_DataAndMcFiles_v3[i]=string("MC");}

		///////////////////////////// LUMI SCALES ///////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Set Lumi Scales" << endl;
	Labledflaot lumiscalemap;
	lumiscalemap[Data] = 1.;
	const float Integrated_Luminosity_Data = 5.725; /*fb^-1*/
	lumiscalemap["st350ho200"] = (Integrated_Luminosity_Data * 447.4 /*fb*/)/((float) 1000000 /*events*/);


		//////////////////////////////////////////////////////////////////////////////
		///////////////////////////////Load h_mGG/////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Load h_mGG" << endl;
		//load mGG_unsliced histograms from all files. 
	Lable2Hist h_mGG_unsliced;
	for (int jFile=0; jFile<nDataAndMcFiles; jFile++) { //loop over all files
		LableHist tmp; // this is the collection of histograms, indexed by topology name
		/*Debug*/ if(printlevel > 2) cout << "first loop, jFile = "<<jFile << endl;
		for (int iTop = 0; iTop<nEventTopologies; iTop++) {
			/*Debug*/ if(printlevel > 4) cout << "second loop, iTop = "<<iTop <<endl;
			string instring = string("h_mGG") +s_EventTopology[iTop] + "_unsliced";
			/*Debug*/ if(printlevel > 4) cout << "loading "<<instring<< " from file " << s_DataAndMcFiles[jFile] << " for topology "<<s_EventTopology[iTop] <<endl;
			tmp[s_EventTopology[iTop]] = (TH1F*)PostAnaAnaFiles[s_DataAndMcFiles[jFile]]->Get(instring.c_str());
			/*Debug*/ if(printlevel > 4) cout << "succeeded"<<endl;
			
				//fix the root names
			string newname = instring+"_"+s_DataAndMcFiles[jFile];
			/*Debug*/ if(printlevel > 4) cout << "resetting name to "<<newname<<" for topology "<<s_EventTopology[iTop]<<endl;
//			/*Debug*/ if(printlevel > 6) cout << tmp[s_EventTopology[iTop]]->Integral()<<endl;
			
			tmp[s_EventTopology[iTop]]->SetName((newname).c_str());
			/*Debug*/ if(printlevel > 4) cout << "succeeded"<<endl;
		}
		/*Debug*/ if(printlevel > 2) cout << "Attempting to write tmp to h_mGG_unsliced with tag "<<s_DataAndMcFiles[jFile] << endl;
		h_mGG_unsliced[s_DataAndMcFiles[jFile]] = tmp;
		/*Debug*/ if(printlevel > 2) cout << "succeeded"<<endl;
	}
//	TH1F* h_mGG_unsliced = (TH1F*)fin.Get("h_mGG_unsliced");
//	TH1F* h_mGG_1Jb_unsliced = (TH1F*)fin.Get("h_mGG_1Jb_unsliced");
	
		////////////////////////////// Load Kin Var Plots //////////////////////////////////////
	/*Debug*/ if(printlevel > 0) cout << "Load Kin Var Plots" << endl;
	Lable3HistArr KinVarHistMap;
	for (int jFile=0; jFile<nDataAndMcFiles; jFile++) {
		
		/*Debug*/ if(printlevel >2) cout << "first loop, jFile = "<<jFile <<endl;	
		Lable2HistArr tmpMapTopo;
		for (int iTop = 0; iTop<nEventTopologies; iTop++) {
			/*Debug*/ if(printlevel >4) cout << "second loop, iTop = "<<iTop <<endl;
			
			LableHistArr tmpMapKinVar;
			for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++) {
				/*Debug*/ if(printlevel >6) cout << "third loop, kKinVar = "<<kKinVar <<endl;
				
					//there is no MET dist for metCut, so don't try to load it. 
				if (s_EventTopology[iTop].compare("metCut") == 0 && s_KinemVars[kKinVar].compare("MET") == 0) continue;
				if (iTop == 2 && kKinVar==0) {cout << endl<<endl<<" ***** ERROR!! your attempt to skip metCut|MET failed"<<endl<<endl; 	}
				
				TH1F** tmpHistArray = new TH1F*[nPhoMassAndBkgDists];
					//LoadHistSet(hMET, &fin, "MET");
				for (int lMassDist=0; lMassDist < nPhoMassAndBkgDists; lMassDist++){
					/*Debug*/ if(printlevel >8) cout << "forth loop, lMassDist = "<<lMassDist <<" out of "<<nPhoMassAndBkgDists<<endl;
					string instring = string("h")+s_KinemVars[kKinVar]+s_EventTopology[iTop]+"_"+s_MassBkgDists[lMassDist];
					/*Debug*/ if(printlevel >8) cout << "Load hist "<<instring<< " from file "<< s_DataAndMcFiles[jFile] << " into tmpHistArray["<<lMassDist<<"]"<<endl;

					tmpHistArray[lMassDist] = (TH1F*) PostAnaAnaFiles[s_DataAndMcFiles[jFile]]->Get( instring.c_str() );
						//fix the root name
					string newname = instring+"_"+s_DataAndMcFiles[jFile];
					/*Debug*/ if(printlevel >8) cout << "rename hist "<<newname <<endl;
					tmpHistArray[lMassDist]->SetName((newname).c_str());
					/*Debug*/ if(printlevel >8) cout << "success" <<endl;
					string newtitle = string(";")+s_KinemVars[kKinVar]+" (GeV)";
					tmpHistArray[lMassDist]->SetTitle((char*)newtitle.c_str());
				}//end for every Mass Dist
				/*Debug*/ if(printlevel >6) cout << "load hist array into tmpMapKinVar for "<< s_KinemVars[kKinVar] <<endl;
				tmpMapKinVar[s_KinemVars[kKinVar]] = tmpHistArray;
								
			}//End for each kinematic varraible
			/*Debug*/ if(printlevel >4) cout << "load hist array into tmpMapTopo for "<< s_EventTopology[iTop] <<endl;
			tmpMapTopo[s_EventTopology[iTop]] = tmpMapKinVar;
			
		}//end for each topology
		/*Debug*/ if(printlevel >2) cout << "load hist array into KinVarHistMap for "<< s_DataAndMcFiles[jFile] <<endl;
		KinVarHistMap[s_DataAndMcFiles[jFile]] = tmpMapTopo;
	}//end for each file

	/*Debug*/ if(printlevel >2){
		cout << "***KinVarHistMap should now be loaded, but did it work?***"<<endl;
		//cout << "Data 1Jb MHT tag name:" <<KinVarHistMap["Data"]["1Jb"]["MHT"][1]->GetName()<<endl;
		//cout << "Data 3Jb MHT tag name:" <<KinVarHistMap["Data"]["3Jb"]["MHT"][1]->GetName()<<endl;
		//cout << "Data 1Jb ST tag name:" <<KinVarHistMap["Data"]["1Jb"]["ST"][1]->GetName()<<endl;
		//cout << "Data 1Jb MHT sb name:" <<KinVarHistMap["Data"]["1Jb"]["MHT"][5]->GetName()<<endl;
		cout << "Data MHT L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["MHT"][7]->GetBinContent(1)<<endl;
		cout << "Data HT L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["HT"][7]->GetBinContent(1)<<endl;
		cout << "Data ST L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["ST"][7]->GetBinContent(1)<<endl;
		cout << "***If this is printing, then the answer is probably Yes ***"<<endl;
	}

	
//	h_mGG_unsliced->SetName("h_mGG_unsliced");
/*	TH1F * hMET[nPhoMassAndBkgDists];
	LoadHistSet(hMET, &fin, "MET");

	TH1F * hST_1Jb[nPhoMassAndBkgDists];
	LoadHistSet(hST_1Jb,&fin,"ST_1Jb");
	*/
	
		////////////////////////////////////////////////////////////////////
		/*Debug*/ if(printlevel > 0) cout << "Load the Fit Curves" << endl;
		//load the fit curves for the data. 
	TF1* mgg_fit_curve[nEventTopologies];
	for (int iTop=0; iTop<nEventTopologies; iTop++) {
		/*Debug*/ if(printlevel > 1) cout << "first loop, iTop = "<<iTop <<endl;
		string instring = string("mgg") + s_EventTopology_v3[iTop] + "fit";
		/*Debug*/ if(printlevel > 1) cout << "instring = "<<instring <<endl;//mggNULLfit, am I naming it wrong? 
		mgg_fit_curve[iTop] = (TF1*)PostAnaAnaFiles[Data]->Get(instring.c_str());
		/*Debug*/ if(printlevel > 1) cout << "supposidly loaded it, try it "<<endl;
		/*Debug*/ if(printlevel > 1) cout << mgg_fit_curve[iTop]->GetProb() <<endl;//seg faults the first time it's exectuted. 
		
/*	mgg_fit_curve[0] = (TF1*)fin.Get("mggfit");
	mgg_fit_curve[1] = (TF1*)fin.Get("mgg_1Jb_fit");
	mgg_fit_curve[2] = (TF1*)fin.Get("mgg_3J_fit");
	mgg_fit_curve[3] = (TF1*)fin.Get("mgg_3Jb_fit");
	mgg_fit_curve[4] = (TF1*)fin.Get("mgg_metCut_fit");*/
	}
	
	
		// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//     ___              __       ____           ___  __     __    
//    / _ \___ ___ ____/ /_ __  / __/__  ____  / _ \/ /__  / /____
//   / , _/ -_) _ `/ _  / // / / _// _ \/ __/ / ___/ / _ \/ __(_-<
//  /_/|_|\__/\_,_/\_,_/\_, / /_/  \___/_/   /_/  /_/\___/\__/___/
//                     /___/                                      
		/*Debug*/ if(printlevel > 0) cout << "Start Building Plots" << endl;

	fplots->cd();

		//if there is not a plots folder, make it. 
	
//     __  ___            ___  __     __ 
//    /  |/  /__ ____ _  / _ \/ /__  / /_
//   / /|_/ / _ `/ _ `/ / ___/ / _ \/ __/
//  /_/  /_/\_, /\_, / /_/  /_/\___/\__/ 
//         /___//___/ 


		/*Debug*/ if(printlevel > 0) cout << "Build mass plots" << endl;
	
		//diphoton mass plots, one for each data plot, for each topology. 
	if(makediphoMassPlot){
	for (int iTop = 0; iTop<nEventTopologies; iTop++) {
		/*Debug*/ if(printlevel > 1) cout << "first loop, iTop = "<<iTop <<endl;
		string canvName = string("c_mgg")+s_EventTopology_v2[iTop]+"_unsliced";
		/*Debug*/ if(printlevel > 1) cout << "made tempCanv with name "<<canvName  <<endl;
		TCanvas* tempCanv = newTCanvas((char*)canvName.c_str()); //char*error
		/*Debug*/ if(printlevel > 1) cout << "Enter the merky deptsh of diphoMassPlot"<<endl;
		diphoMassPlot(h_mGG_unsliced[Data][s_EventTopology[iTop]],tempCanv,mgg_fit_curve[iTop]);
		/*Debug*/ if(printlevel > 1) cout << "fin dinphoMass plot, try to write to fplots" <<endl;
		tempCanv->Write();
		if(saveImages) SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfjpgepspng");//save as all types
		//if(saveImages) SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types
	}
	}
	

		// %%%%%%%%%%%%%%%%%%%%%%%% Kinematics and backgrounds %%%%%%%%%%%%%%%%%
//     ___  __        ___                   ___  __     __    
//    / _ )/ /_____ _/ _ \___ __ _  ___    / _ \/ /__  / /____
//   / _  /  '_/ _ `/ // / -_)  ' \/ _ \  / ___/ / _ \/ __(_-<
//  /____/_/\_\\_, /____/\__/_/_/_/\___/ /_/  /_/\___/\__/___/
//            /___/                                           

	/*Debug*/ if(printlevel > 0) cout << "Build Kin Var plots type 1" << endl;
		//Arrangement 1
        TH1F * box = new TH1F("box","asdf",1,0,1);
        box->SetMarkerColor(kRed);
        box->SetMarkerStyle(25);
        box->SetMarkerSize(2);
        box->SetLineColor(0);
		///Demonstrate background. Plot two side bands with their ratio as a sub-plot. include a switchable Tag.


	if(makeBkgDemo){
	for (int iTop = 0; iTop<nEventTopologies; iTop++){
		for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++){
			/*Debug*/ if(printlevel >2) cout << "iTop="<<iTop<<" kKinVar="<<kKinVar<<endl;
			if (s_EventTopology[iTop].compare("metCut")==0 && s_KinemVars[kKinVar].compare("MET")==0 ){
				/*Debug*/ if(printlevel >2) cout << "skipping met plot for met cut"<<endl;
				continue;
			}
			string canvName = string("BkgFull_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			/*Debug*/ if(printlevel >6) {TH1F** h = KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]];
			/*Debug*/ if(printlevel >6) printf("Scan1 Ratio bin1 for %s %s  = %f\n",s_EventTopology[iTop].c_str(),s_KinemVars[kKinVar].c_str(),h[7]->GetBinContent(1));}
			TCanvas* tempCanv = newTCanvas((char*)canvName.c_str());
			BkgDemo_Diplot(tempCanv,
					 KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]],
						   makeL1(0.2072864,0.7203704,0.4070352,0.9203704),
						   makeL2(0.51005,0.706436,0.708543,0.902669));
			//tempCanv->Write();
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggif");//save as all types
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types
		}//edn for each kinematic varriable
	}//end for each topology
	}

//     ___  __       ___  ___  __     __    
//    / _ )/ /_____ <  / / _ \/ /__  / /____
//   / _  /  '_/ _ `/ / / ___/ / _ \/ __(_-<
//  /____/_/\_\\_, /_/ /_/  /_/\___/\__/___/
//            /___/                         

		///Demostrate background-upper. Plot the two side bands together, but ignore the ratio. (Arr2)
	if(makeBkg1){
	for (int iTop = 0; iTop<nEventTopologies; iTop++) {
		for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++) {
			if (s_EventTopology[iTop].compare("metCut")==0 && s_KinemVars[kKinVar].compare("MET")==0 ) continue;
			string canvName = string("Bkg1_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			string canvNamelog = string("Bkg1Log_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			TCanvas* tempCanv = newTCanvas((char*)canvName.c_str());
			TCanvas* tempCanvlog = newTCanvas((char*)canvNamelog.c_str());
			tempCanvlog->SetTopMargin(0.06);
                        tempCanvlog->SetBottomMargin(0.15);

			TH1F** h = KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]];
			tempCanv->cd();
			//RaiseRangeRoof(h[5],1.25);
			//RaiseRangeRoof(h[1],1.25);
			//RaiseRangeRoof(h[6],1.25);
			PrettyHist(h[5],kBlue);
			PrettyHist(h[1],1);
			PrettyHist(h[6],kGreen);
			PrettyHist(h[3],kRed);

//			string cname = tempCanv->GetName();
//			if(cname.find("_HT")!=string::npos)//if found "_HT" in the name
//				h[5]->GetXaxis()->SetLabelSize(0.04);
				//SPECIAL
			if (s_KinemVars[kKinVar].compare("HT") == 0) {
				h[5]->GetXaxis()->SetLabelSize(0.04);}

			PrettyBlock2(h[5],kBlue,3354,2);//PrettyMarker(h[5],kBlue,4);
			//PrettyBlock(h[5],kBlue,string("//thatch"));//PrettyMarker(h[5],kBlue,4);
			PrettyMarker(h[1]);
			PrettyBlock2(h[6],kGreen,3345,2);//PrettyMarker(h[6],kGreen,4);
			h[3]->SetFillStyle(0);//open rectangle
                        h[3]->SetLineColor(kRed);
                        h[3]->SetLineWidth(4);
			//PrettyBlock(h[6],kGreen,string("\\thatch"));//PrettyMarker(h[6],kGreen,4);
			playNiceWithLegend(h[3],0.30,0.0);
                        playNiceWithLegend(h[6],0.30,0.0);
                        playNiceWithLegend(h[5],0.30,0.0);
                        playNiceWithLegend(h[1],0.30,0.0);
			h[6]->SetMinimum(0.0);
			SameRange(h[1],h[3]);
			SameRange(h[5],h[6],h[1]);
			SameRange(h[1],h[3]);
			h[5]->Draw("e2p");
			h[6]->Draw("e2psame");
			h[3]->Draw("e2psame");
			//if(showTag) h[1]->Draw("e1psame");//tag
			TLegend* l1 = makeL1_v2(0.443467,0.720207,0.643216,0.919689);
			if(showTag) l1->AddEntry(h[1],"Higgs Mass Region");
			l1->AddEntry(h[5],"Lower Mass Sideband");
			l1->AddEntry(h[6],"Upper Mass Sideband");
			l1->AddEntry(box,"Data Driven Background");//h[3
			l1->Draw("same");
		        TEX_CMSPrelim->Draw("same");
			TEX_E_TeV->Draw("same");
			TEX_lumi_fb->Draw("same");
			tempCanv->Write();
			if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggif");//save as all types
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types

			tempCanvlog->cd();
			h[5]->SetMinimum(0.05);
                        tempCanvlog->SetLogy();
			h[5]->Draw("e2p");
			h[6]->Draw("e2psame");
			h[3]->Draw("e2psame");
			l1->Draw("same");
			TEX_CMSPrelim->Draw("same");
			TEX_E_TeV->Draw("same");
			TEX_lumi_fb->Draw("same");
			if(saveImages)SaveCanvas(tempCanvlog,plotsdir+tempCanvlog->GetName(),"ggif");//save as all types
			
		}//edn for each kinematic varriable
	}//end for each topology
	}//end if


//     ___  __          ___       __  _        ___  __     __    
//    / _ )/ /_____ _  / _ \___ _/ /_(_)__    / _ \/ /__  / /____
//   / _  /  '_/ _ `/ / , _/ _ `/ __/ / _ \  / ___/ / _ \/ __(_-<
//  /____/_/\_\\_, / /_/|_|\_,_/\__/_/\___/ /_/  /_/\___/\__/___/
//            /___/                                              

		///Demostrate background--Ratio. Plot the ratio of the two side bands, and nothing else. 
	if(makeBkgRat){
	for (int iTop = 0; iTop<nEventTopologies; iTop++) {
		for (int kKinVar = 0; kKinVar<nKinemVars; kKinVar++) {
			/*Debug*/ if(printlevel >6) cout << "Data MHT L/R bin 0:" <<KinVarHistMap["Data"]["NULL"]["MHT"][7]->GetBinContent(1)<<endl;
			if (s_EventTopology[iTop].compare("metCut")==0 && s_KinemVars[kKinVar].compare("MET")==0 ) continue;
			string canvName = string("BkgRat_")+s_KinemVars[kKinVar]+s_EventTopology_v2[iTop];
			TCanvas* tempCanv = newTCanvas((char*)canvName.c_str());
			TH1F** h = KinVarHistMap[Data][s_EventTopology[iTop]][s_KinemVars[kKinVar]];
			/*Debug*/ if(printlevel >6)	printf("Scan2 Ratio bin1 for %s %s  = %f\n",s_EventTopology[iTop].c_str(),s_KinemVars[kKinVar].c_str(),h[7]->GetBinContent(1));
			tempCanv->cd();
			PrettyHist(h[7],kTeal);
			h[7]->GetYaxis()->SetRangeUser(0.,2.);
			if (s_KinemVars[kKinVar].compare("HT") == 0) {
				h[7]->GetXaxis()->SetLabelSize(0.04);}

			PrettyMarker(h[7],kTeal);
			h[7]->Draw("e1p");
			TAxis* xaxis = h[7]->GetXaxis();
			TLine *OneLine = new TLine(xaxis->GetXmin(),1.0,xaxis->GetXmax(),1.0);
			OneLine->SetLineColor(kBlack);
			OneLine->SetLineWidth(2);
			OneLine->SetLineStyle(7);//dashed.
			OneLine->Draw("same");
			h[7]->Draw("e1psame");
			TLegend* l1 = makeL1_v2(0.330402,0.836788,0.530151,0.919689);
			l1->AddEntry(h[7],"Lower/Upper Sideband Ratio");
			l1->Draw("same");
			TEX_CMSPrelim->Draw("same");
			TEX_E_TeV->Draw("same");
			TEX_lumi_fb->Draw("same");

			tempCanv->Write();
			if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggif");//save as all types
			//if(saveImages)SaveCanvas(tempCanv,plotsdir+tempCanv->GetName(),"ggifpdfeps");//save as all types
		}//edn for each kinematic varriable
	}//end for each topology
	}//end if makeBkgRat

		///END MAKE PLOTS
	/*Debug*/ if(printlevel > 0) cout << "Close Files" << endl;
	fplots->Close(); 
		//itterate over the map. close everything. 
	for( TFileMap::iterator i=PostAnaAnaFiles.begin(); i!=PostAnaAnaFiles.end(); ++i){
		(*i).second->Close();
	}
	for( TFileMap::iterator i=MainAnaFiles.begin(); i!=MainAnaFiles.end(); ++i){
		(*i).second->Close();
	}


}//end format plots
//effsigma function from Chris
double effSigma(TH1 * hist)
{

  TAxis *xaxis = hist->GetXaxis();
  Int_t nb = xaxis->GetNbins();
  if(nb < 10) {
    cout << "effsigma: Not a valid histo. nbins = " << nb << endl;
    return 0.;
  }
  
  Double_t bwid = xaxis->GetBinWidth(1);
  if(bwid == 0) {
    cout << "effsigma: Not a valid histo. bwid = " << bwid << endl;
    return 0.;
  }
  Double_t xmax = xaxis->GetXmax();
  Double_t xmin = xaxis->GetXmin();
  Double_t ave = hist->GetMean();
  Double_t rms = hist->GetRMS();

  Double_t total=0.;
  for(Int_t i=0; i<nb+2; i++) {
    total+=hist->GetBinContent(i);
  }

  Int_t ierr=0;
  Int_t ismin=999;
  
  Double_t rlim=0.683*total;
  Int_t nrms=rms/(bwid);    // Set scan size to +/- rms
  if(nrms > nb/10) nrms=nb/10; // Could be tuned...

  Double_t widmin=9999999.;
  for(Int_t iscan=-nrms;iscan<nrms+1;iscan++) { // Scan window centre
    Int_t ibm=(ave-xmin)/bwid+1+iscan;
    Double_t x=(ibm-0.5)*bwid+xmin;
    Double_t xj=x;
    Double_t xk=x;
    Int_t jbm=ibm;
    Int_t kbm=ibm;
    Double_t bin=hist->GetBinContent(ibm);
    total=bin;
    for(Int_t j=1;j<nb;j++){
      if(jbm < nb) {
        jbm++;
        xj+=bwid;
        bin=hist->GetBinContent(jbm);
        total+=bin;
        if(total > rlim) break;
      }
      else ierr=1;
      if(kbm > 0) {
        kbm--;
        xk-=bwid;
        bin=hist->GetBinContent(kbm);
        total+=bin;
        if(total > rlim) break;
      }
      else ierr=1;
    }
    Double_t dxf=(total-rlim)*bwid/bin;
    Double_t wid=(xj-xk+bwid-dxf)*0.5;
    if(wid < widmin) {
      widmin=wid;
      ismin=iscan;
    }   
  }
  if(ismin == nrms || ismin == -nrms) ierr=3;
  if(ierr != 0) cout << "effsigma: Error of type " << ierr << endl;
  
  return widmin;
  
}
void fit(TH1* histogram, double xMin, double xMax, double massValue, std::vector<fitParameterType>& fitParameter)
{
  // create fit variable
  TAxis* xAxis = histogram->GetXaxis();
  if ( xMin < 0. ) xMin = xAxis->GetXmin(); 
  if ( xMax < 0. ) xMax = xAxis->GetXmax(); 
  std::string fitVariableName = Form("%s_fitVariable", histogram->GetName());
  RooRealVar fitVariable(fitVariableName.data(), fitVariableName.data(), xMin, xMax);
   
  // convert histogram to RooFit format
  std::string histogramName_data = Form("%s_data", histogram->GetName());
  RooDataHist histogram_data(histogramName_data.data(), histogramName_data.data(), fitVariable, histogram, 1.0);

  // create product of linear * Heaviside * Gaussian Error function
  std::string svFitLineShapeName_slope = Form("%s_svFitLineShape_slope", histogram->GetName());
  RooRealVar svFitLineShape_slope(svFitLineShapeName_slope.data(), svFitLineShapeName_slope.data(), 2./(massValue*massValue), 0., 1.);
  std::string svFitLineShapeName_offset = Form("%s_svFitLineShape_offset", histogram->GetName());
  RooRealVar svFitLineShape_offset(svFitLineShapeName_offset.data(), svFitLineShapeName_offset.data(), 0., -1., +1.);

  std::string heavisideName_threshold = Form("%s_heaviside_threshold", histogram->GetName());
  RooRealVar heaviside_threshold(heavisideName_threshold.data(), heavisideName_threshold.data(), 0.2*massValue, 1.e-2*massValue, 0.5*massValue);

  std::string sculptingName_bias = Form("%s_sculpting_bias", histogram->GetName());
  RooRealVar sculpting_bias(sculptingName_bias.data(), sculptingName_bias.data(), 0.25*massValue, 0.*massValue, 0.9*massValue);
  std::string sculptingName_width = Form("%s_sculpting_width", histogram->GetName());
  RooRealVar sculpting_width(sculptingName_width.data(), sculptingName_width.data(), 0.1*massValue, 1.e-2*massValue, 1.0*massValue);

  std::string svFitLineShapeName = Form("%s_svFitLineShape", histogram->GetName());
  std::string svFitLineShapeFormula = "(@0*@1 + @2)*0.5*(1.0 + TMath::Sign(+1, @0 - @3))*0.5*(1.0 + TMath::Erf((@0 - @4)/@5))";
  RooArgList svFitLineShapeArgs(fitVariable, 
				svFitLineShape_slope,
				svFitLineShape_offset,
				heaviside_threshold,
				sculpting_bias,
				sculpting_width);
  RooGenericPdf svFitLineShape(svFitLineShapeName.data(), svFitLineShapeName.data(), svFitLineShapeFormula.data(), svFitLineShapeArgs);

  // create Gaussian 
  std::string gaussianName_mean = Form("%s_gaussian_mean", histogram->GetName());
  RooConstVar gaussian_mean(gaussianName_mean.data(), gaussianName_mean.data(), 0.);
  std::string gaussianName_sigma = Form("%s_gaussian_sigma", histogram->GetName());
  RooRealVar gaussian_sigma(gaussianName_sigma.data(), gaussianName_sigma.data(), 0.2*massValue, 1.e-2*massValue, 0.5*massValue);
  std::string gaussianName = Form("%s_gaussian", histogram->GetName());
  RooGaussian gaussian(gaussianName.data(), gaussianName.data(), fitVariable, gaussian_mean, gaussian_sigma);

  // numerically convolute both PDFs using fast Fourier transform
  std::string fitFunctionName = Form("%s_fitFunction", histogram->GetName());
  RooFFTConvPdf fitFunction(fitFunctionName.data(), fitFunctionName.data(), fitVariable, svFitLineShape, gaussian);

  // fit histogram
  fitFunction.fitTo(histogram_data);

  // save fit parameter
  fitParameter.resize(6);
  fitParameter[0] = fitParameterType(&svFitLineShape_slope);
  fitParameter[1] = fitParameterType(&svFitLineShape_offset);
  fitParameter[2] = fitParameterType(&gaussian_sigma);
  fitParameter[3] = fitParameterType(&heaviside_threshold);
  fitParameter[4] = fitParameterType(&sculpting_bias);
  fitParameter[5] = fitParameterType(&sculpting_width);

  // create control plot
  std::string frameTitle = Form("%s_frame", histogram->GetName());
  RooPlot* frame = fitVariable.frame(RooFit::Title(frameTitle.data()));
  histogram_data.plotOn(frame);
  fitFunction.plotOn(frame, RooFit::LineColor(kRed));
  
  std::string canvasName = Form("%s_canvas", histogram->GetName());
  TCanvas* canvas = new TCanvas(canvasName.data(), canvasName.data(), 800, 600);
  gPad->SetLeftMargin(0.15); 
  frame->GetYaxis()->SetTitleOffset(1.4);
  frame->Draw();
    
  std::string outputFileName_plot = Form("svFitPerformance_%s_fit", histogram->GetName());
  canvas->Print(std::string(outputFileName_plot).append(".eps").data());
  canvas->Print(std::string(outputFileName_plot).append(".png").data());
  canvas->Print(std::string(outputFileName_plot).append(".pdf").data());
  
  delete canvas;
}
Пример #14
0
void PlotPubHisto(TObjArray histograms,TEnv *params){
    // This is a modification of the AddHistos macro
    
    // Number of histos to plot:
    Int_t ntot = histograms.GetEntries();
    
    // Check we have what we expect (the order should be: data, qcd, wjets, etc...)
    for(Int_t i = 0; i<ntot; i++){
	if(histograms[i]==0) {
	    cout<<"Error in AddHistos: histogram "<<i<<" is a NULL pointer!"<<endl;
	    return;
	}
	TH1F * hthis = (TH1F*) histograms[i];
	// include the overflow/underflow bins:
	int numbins = hthis->GetNbinsX(); //this is the last bin plotted
	double hicontent = hthis->GetBinContent(numbins);
	double overflow  = hthis->GetBinContent(numbins+1);// this bin contains the overflow
	double locontent = hthis->GetBinContent(1);// this is the first bin plotted
	double underflow = hthis->GetBinContent(0);// this bin contains the underflow
	if (underflow>0 || overflow>0){
	    //printf("%-20s numbins=%4i hicontent=%4.2f over=%4.2f locontent=%4.2f underflow=%4.2f \n",
	    //	 title.Data(),numbins,hicontent,overflow,locontent,underflow);
	}
	hthis->SetBinContent(numbins,hicontent+overflow);
	hthis->SetBinContent(1,locontent+underflow);
    }
    
    // define a few additional line styles:
    gStyle->SetLineStyleString(5,"20 12 4 12");
    gStyle->SetLineStyleString(6,"20 12 4 12 4 12 4 12");
    gStyle->SetLineStyleString(7,"20 20");
    gStyle->SetLineStyleString(8,"20 12 4 12 4 12");
    gStyle->SetLineStyleString(9,"80 25");
    gStyle->SetLineStyleString(10,"50 10 10 10");
    gStyle->SetLineStyleString(17,"30 25");
    gStyle->SetLineStyleString(20,"60 20");
    gStyle->SetLineStyleString(21,"60 20 20 20");
    int lineStyle[20];
    for(int i=0;i<20;i++) {
	lineStyle[i]=i;
    }

    // the first histogram in the list:
    TH1F *h0=((TH1F*) histograms[0])->Clone();
    
    // histogram output filename
    TString oFileName=params->GetValue("Histo.Output.Filename","bogus.eps");
    
    // figure out the number of signals
    Int_t nsig=1;
    if(params->Defined("Histo.Signal.Title.1")) nsig=1;
    if(params->Defined("Histo.Signal.Title.2")) nsig=2;
    if(params->Defined("Histo.Signal.Title.3")) nsig=3;
    
    cout << " I will use nsig = " << nsig << " signal sources" << endl;
    
    // Do the cumulative summing, except for the data
    TObjArray addedhistos; addedhistos.Clear();
    TObjArray signalhistos; signalhistos.Clear();
    TString sampletitles[20];
    Int_t nbkg=0;
    for(Int_t i = 1; i<ntot; i++){// i runs over histograms[i], so data is for i=0
	ostringstream baseSrcName;
	baseSrcName << "Files." << i+1 << ".";// Counting starts at 1: Files.1.Name: Data
	TString bSrcName(baseSrcName.str().c_str());
	// skip some if we want to show them as lines
	TString htitle=params->GetValue(bSrcName+"Title","");
	sampletitles[i-1]=htitle;
	if(params->GetValue("Histo.ShowSignalSeparately",0)==1 &&
	   // skip the last two if the signal title is not defined:
	   ( ( !(params->Defined("Histo.Signal.Title")||params->Defined("Histo.Signal.Title.1")) && i>=ntot-nsig) 
	     // skip the signal if the signal title is defined
	     || params->GetValue("Histo.Signal.Title",".")==htitle
	     || params->GetValue("Histo.Signal.Title.1",".")==htitle
	     || params->GetValue("Histo.Signal.Title.2",".")==htitle
	     || params->GetValue("Histo.Signal.Title.3",".")==htitle
	     ) ) {
	    TH1F * hthis = (TH1F*) histograms[i]->Clone();
	    cout<<" Found signal in location "<<i+1<<" with name "<<htitle.Data()<<endl;
	    signalhistos.Add(hthis);
	} else {
	    TH1F * hthis = (TH1F*) histograms[i]->Clone();
	    addedhistos.Add(hthis); // Fill in the new TObjArray with a copy 
	    //cout << " Adding bkg " << i << " " << htitle.Data() << " " << hthis->Integral() << endl;
	    // add all of the backgrounds
	    if (i>1) {// i=0 is the data, and we must start with the second
		      // background to add the previous
		TH1F * hprevious = (TH1F*) addedhistos[i-2];
		if ( hthis->GetXaxis()->GetNbins() != hprevious->GetXaxis()->GetNbins() ) {
		    // Protection against _whoran histogram. 
		    // We cannot add two histograms with different numbers of bins!
		    cout<<"Error in AddHistos: incompatible number of bins!"<<endl;  
		    return;
		}
		hthis->Add(hprevious); // Do the addition
		addedhistos.RemoveAt(i-1); // And substitute whatever we had 
		addedhistos.AddAt(hthis,i-1);
		nbkg++;
		//cout << "Substituing bkg " << i << " + " << i-1 << " in addedhistos["<< i-1 <<"]" << endl;
	    }	    
	} // end of: if adding histograms
    }
    cout << " nbkg = " << nbkg << endl; 
    
    // Rebin histos if necessary, but first calculate KS:
    TH1F *hbkg = (TH1F*) addedhistos[nbkg];
    double KS = h0->KolmogorovTest(hbkg);
    double chi2ndf = h0->Chi2Test(hbkg, "UWUFOFCHI2/NDF");
    //cout << title.Data() << " KS = " << KS << " chi2/NDF = " << chi2ndf << endl;
    // Rebin? Set nrebin = 0 to NOT do rebinning. 
    // Will rebin only histos whose maximum x axis value exceeds 20. 
    // Anything with less will most probably be already made of integers, so no
    // need to rebin that! 
    Int_t nbinsx = h0->GetXaxis()->GetNbins();
    Int_t nbinsy = 100;
    Int_t nrebin = 5;
    if ( nbinsx > 750 && nbinsx <= 1000) nrebin = 30;
    if ( nbinsx > 400 && nbinsx <= 750 ) nrebin = 25;//20
    if ( nbinsx > 300 && nbinsx <= 400 ) nrebin = 25;//15
    if ( nbinsx > 200 && nbinsx <= 300 ) nrebin = 25;//15
    if ( nbinsx > 150 && nbinsx <= 200 ) nrebin = 10;//10
    if ( nbinsx > 100 && nbinsx <= 150 ) nrebin = 10;//10
    if ( nbinsx > 50 && nbinsx <= 100 )  nrebin = 10;//10
    if ( nbinsx > 20 && nbinsx <= 50 )   nrebin = 2;
    if ( nbinsx <= 20 ) nrebin = 1;  
    
    printf(" Saw nbins =%4i, rebinning by nrebin =%2i to final %3i bins \n",nbinsx,nrebin,int(nbinsx/nrebin));	

    if ( nrebin != 0 ) {
	h0->Rebin(nrebin); // data
	for (Int_t i = 0; i<=nbkg; i++){
	    TH1F * h = (TH1F*) addedhistos[i];
	    h->Rebin(nrebin);
	}
	for (Int_t i = 0; i<nsig; i++){
	    TH1F * h = (TH1F*) signalhistos[i];
	    h->Rebin(nrebin);
	}
    }

    // default text size: 0.045
    // make it bigger for the paper
    float textSize = 0.045;
    if(params->GetValue("Histo.Preliminary","yes")==TString("paper")) textSize=0.07;
    if(params->Defined("Histo.TextSize")) textSize=params->GetValue("Histo.TextSize",0.07);
    
    // Now, check largest dimensions so that we can plot all histograms at once.
    Float_t xmin=9999., xmax=-9999., ymin=9999., ymax=-9999.;
    for(Int_t i = 0; i<=nbkg; i++){
	TH1F * h = (TH1F*) addedhistos[i];
	ostringstream baseSrcName;
	baseSrcName << "Files." << i+1 << ".";
	TString bSrcName(baseSrcName.str().c_str());
	
	TAxis *axis = h->GetXaxis();
	if( axis->GetXmin() < xmin ) xmin = axis->GetXmin();
	if( axis->GetXmax() > xmax ) xmax = axis->GetXmax();
	if( h->GetMinimum() < ymin ) ymin = h->GetMinimum();
	if( h->GetMaximum() > ymax ) ymax = h->GetMaximum();
    }
    ymax = TMath::Nint(ymax*1.25+1); // Make enough room for the big legend
    TString title = h0->GetTitle();
    
    //
    // now check if we should simply use the ranges that was passed to us.
    if(params->Defined("Histo.Xmin")) xmin = params->GetValue("Histo.Xmin",0.);
    if(params->Defined("Histo.Xmax")) xmax = params->GetValue("Histo.Xmax",0.);
    if(params->Defined("Histo.Ymin")) ymin = params->GetValue("Histo.Ymin",0.);
    if(params->Defined("Histo.Ymax")) ymax = params->GetValue("Histo.Ymax",0.);
    
    // Now make the frame:
    TH2F * frame = new TH2F("frame","",nbinsx,xmin,xmax,nbinsy,ymin,ymax);
    cout<<" frame has xmin "<<xmin<<", xmax "<<xmax<<", ymax "<<ymax<<endl;
    
    // get the x- and y-axis titles
    TString ytitle=params->GetValue("Histo.YTitle","");
    if ( params->Defined("Histo.XTitle")) {
	frame->SetXTitle(params->GetValue("Histo.XTitle",""));
    } else {
	frame->SetXTitle(h0->GetTitle());
    }
    frame->SetYTitle(ytitle.Data()); 
    // also set the text size for the X and Y axis titles and numbers
    // do this globally for the style we are using
    float axisLabelSize=textSize;
    frame->GetXaxis()->SetLabelSize(axisLabelSize);
    frame->GetYaxis()->SetLabelSize(axisLabelSize);
    frame->GetXaxis()->SetTitleSize(axisLabelSize);
    frame->GetYaxis()->SetTitleSize(axisLabelSize);
    
    frame->SetStats(false);
    // reduce the axis title offset if the fonts are very large
    if(textSize>0.055) frame->GetXaxis()->SetTitleOffset(1.0);
    // also change the X axis title offset to move it farther away from the numbers
    if(params->Defined("Histo.XTitle.Offset")) {
	float xtitoffset=params->GetValue("Histo.XTitle.Offset",1.0);
	frame->GetXaxis()->SetTitleOffset(xtitoffset);
    }
    
    // also change the y axis title offset to move it farther away from the numbers
    frame->GetYaxis()->SetTitleOffset(1.0);
    // reduce the axis title offset if the fonts are very large
    if(textSize>0.055) frame->GetYaxis()->SetTitleOffset(1.0);
    
    // set the axes divisions
    frame->GetXaxis()->SetNdivisions(505,true);
    if(params->Defined("Histo.XNdivisions")) frame->GetXaxis()->SetNdivisions(params->GetValue("Histo.XNdivisions",505),kTRUE);
    if(params->Defined("Histo.YNdivisions")) frame->GetYaxis()->SetNdivisions(params->GetValue("Histo.YNdivisions",505),kTRUE);
    
    // make sure the X axis title and Y axis title are in black!
    frame->GetXaxis()->SetTitleColor(1);
    frame->GetYaxis()->SetTitleColor(1);

    // Could plot in log scale...
    //gPad->SetLogy();

    // finally: Draw
    frame->Draw();
    
    // Draw the background ones:
    for(Int_t i=nbkg; i>=0; i--){
	TH1F * h = (TH1F*) addedhistos[i];
	h->SetStats(kFALSE);
	
	ostringstream baseSrcName;
	baseSrcName << "Files." << i+2 << ".";// to account for the data which is Files.1
	TString bSrcName(baseSrcName.str().c_str());
	Int_t hcolor=params->GetValue(bSrcName+"Color",1); 	
	h->SetLineColor(1);      
	h->SetFillColor(hcolor);
        if (i==nbkg) printf(" Data Yield = %5.2f ; SumBkg = %5.2f ; Data-SumBkg diff = %5.2f%% \n",
	   		     h0->Integral(),h->Integral(),(h0->Integral()-h->Integral())*100./h0->Integral());
	printf(" plotting bkg i=%2i name=%20.20s file=%2i integral=%5.1f color=%2i\n",
	       i,sampletitles[i].Data(),i+2,h->Integral(),hcolor);
	int fillStyle=params->GetValue(bSrcName+"FillStyle",1001);
	h->SetFillStyle(fillStyle);
	h->DrawCopy("Hist,Same");
    }
    //
    // and draw the signal ones
    // draw them in reverse order so that the last one will be on top.
    //for(Int_t i=ntot-3; i<ntot; i++){
    for(Int_t i=nsig-1; i>=0; i--){
	ostringstream baseSrcName;
	baseSrcName << "Files." << ntot+1-nsig+i << ".";
	TString bSrcName(baseSrcName.str().c_str());
	
	Int_t hcolor=params->GetValue(bSrcName+"Color",1);
	TH1F * h = (TH1F*) signalhistos[i];
       	if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=90"))        h->Add (h, 1.07874865  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=100"))  h->Add (h, 1.62317373  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=110"))  h->Add (h, 2.31347600  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=120"))  h->Add (h, 3.25275183  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=130"))  h->Add (h, 4.54142919  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=140"))  h->Add (h, 6.19195046  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=150"))  h->Add (h, 8.38307290  -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=160"))  h->Add (h, 11.31721008 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=170"))  h->Add (h, 14.85376469 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=180"))  h->Add (h, 19.54537459 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=190"))  h->Add (h, 25.44594010 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=200"))  h->Add (h, 32.94784356 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=220"))  h->Add (h, 54.09499080 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=240"))  h->Add (h, 86.85079034 -1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=260"))  h->Add (h, 136.31406761-1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=280"))  h->Add (h, 210.70375053-1.000);
	else if (sampletitles[ntot-1-nsig+i].Contains("m_{H}=300"))  h->Add (h, 319.79533099-1.000);
	
	printf(" plotting sig i=%2i name=%20.20s file=%2i integral=%5.1f color=%2i\n",
	       i,sampletitles[ntot-1-nsig+i].Data(),ntot+1-nsig+i,h->Integral(),hcolor);
	// create a white background around each line (helps readibility):
	TH1F *h1=h->Clone();
	h1->SetStats(kFALSE);
	h1->SetLineWidth(6);
	h1->SetLineColor(0);h1->SetFillColor(0);
	h1->SetLineStyle(1);
	h1->SetFillStyle(0);
	h1->Draw("HIST,SAME");
	// now draw the proper line:
	h->SetStats(kFALSE);
	h->SetLineWidth(6);
	h->SetLineColor(hcolor);h->SetFillColor(0);	
	Int_t hlinestyle = params->GetValue(bSrcName+"LineStyle",1);
	h->SetLineStyle(hlinestyle);
	h->SetFillStyle(0);	
	// finally, draw!
	h->Draw("HIST,SAME");      
    } // end of: drawing signal as separate lines
    
    // Data is special: 
    // change the default size of the little bar at the end of the error bar here
    gStyle->SetEndErrorSize(3);
    // also, maybe don't display the error bars along the X axis:
    //gStyle->SetErrorX(0);  // X error bars not displayed
    gStyle->SetErrorX(0.5);  // X error bars have width of a bin
    // now set the rest
    h0->SetMarkerSize(2);
    // if there are too many points (>80), keep the marker size smaller
    if(h0->GetNbinsX()>=50) h0->SetMarkerSize(1);
    //if(h0->GetNbinsX()>=100) h0->SetMarkerSize(1);
    h0->SetLineWidth(3);
    h0->SetMarkerStyle(8);
    h0->SetMarkerColor(1);
    h0->Draw("E1,SAME");
    
    // Print some comparison:
    //ostringstream basefactor;
    //basefactor << "Files." << nbkg+3 << "." << "Factor";
    //TString timesfactor(basefactor.str().c_str()); 
    //Double_t nprod = params->GetValue(timesfactor,1.000);
    //printf("Data Yield = %5.2f ; SumBkg = %5.2f ; SumBkg+Sig = %5.2f ; Data-SumBkg diff = %5.2f%% \n",
    //        h0->Integral(),hbkg2->Integral,(hbkg2->Integral()+(signalhistos[0]->Integral()/nprod),
    //        (h0->Integral()-hbkg2->Integral)*100./h0->Integral()));

    //
    // Print D0 and lumi:
    //
    TText *t1 = new TText();
    t1->SetTextFont(62);
    t1->SetTextColor(1);   
    t1->SetNDC();
    t1->SetTextAlign(12);
    t1->SetTextSize(textSize);
    TString prelim="D\328 Preliminary";
    if(oFileName.EndsWith(".eps")) {
	prelim="D\349 Preliminary L=3.7 fb^-1#";
    }
    else if(oFileName.EndsWith(".gif")) {
	prelim="D\328 Preliminary L=3.7 fb^-1#";
    }
    t1->DrawTextNDC(0.13,0.965,prelim.Data());

    // a counter of how much text we have added from the top
    int nAddTextLines=0;
    
    // any additional text?
    for(int iText=1;iText<20;iText++) {
	ostringstream baseTextName;
	baseTextName << "Histo.AddText." << iText;
	TString bTextName(baseTextName.str().c_str());
	if(params->Defined(bTextName)) {
	    // we are adding a line of text
	    TLatex *t2 = new TLatex();
	    t2->SetTextFont(62);
	    t2->SetTextColor(13);   
	    t2->SetTextAlign(32);
	    t2->SetNDC();
	    t2->SetTextSize(textSize);
	    TString addText(params->GetValue(bTextName,"."));
	    float x0=0.94;
	    float y0=0.96-(nAddTextLines)*0.05;
	    
	    // check if the user specified an alternative location for the text
	    if(params->Defined(bTextName+".X0")) x0=params->GetValue(bTextName+".X0",0.94);
	    if(params->Defined(bTextName+".Y0")) y0=params->GetValue(bTextName+".Y0",0.8);
	    if(params->Defined(bTextName+".TextSize")) t2->SetTextSize(params->GetValue(bTextName+".TextSize",textSize));
	    
	    // and increment the counter keeping track of how much we added,
	    // but only if the user didn't move the label around.
	    if(!params->Defined(bTextName+".X0")) nAddTextLines++;
	    printf("AddText %4.2f %4.2f %s\n",x0,y0,addText.Data());
	    
	    t2->DrawLatex(x0,y0,addText.Data()); 
	}
    }// end additional text
    
    // now draw the frame axis again so that we can see the tick marks
    frame->Draw("sameaxis");
    
    // Legend:
    TString showLegend(params->GetValue("Histo.ShowLegend","."));
    if( showLegend != "no" ){ 
	float lgdxmin=.65, lgdxmax=.90, lgdymin=.50, lgdymax=.91;
	if(showLegend=="yes" || showLegend=="right") {
	    
	} else if (showLegend=="left"){
	    lgdxmin=.16;
	    lgdxmax=.42;
	}
	TLegend *lgd = new TLegend(lgdxmin,lgdymin,lgdxmax,lgdymax); 
	// This line makes the legend transparent (not grey, ewwww!): 
	lgd->SetBorderSize(0); lgd->SetTextSize(textSize*0.9);// 10% less size 
	lgd->SetTextFont(62); lgd->SetFillColor(0);
	// Plot the legend in reverse order (but data goes first):
	NiceAddEntry(lgd,h0,params->GetValue("Files.1.Title","Data"),"PL");
	for(Int_t i = nbkg; i>=0; i--){
	    TH1F * h = (TH1F*) addedhistos[i];
	    TString lgd_entry= sampletitles[i]; // sampletitles runs from 0 (firstbkg) to ntot-1
	    NiceAddEntry(lgd,h,lgd_entry.Data(),"F");	
	}
	for(Int_t i = nsig-1; i>=0; i--){
	    TH1F * h = (TH1F*) signalhistos[i];
	    TString lgd_entry = sampletitles[i+nbkg+1]; // sampletitles runs from 0 (firstbkg) to ntot-1
	    ostringstream basefactor;
	    basefactor << "Files." << i+nbkg+3 << "." << "Factor";
	    TString timesfactor(basefactor.str().c_str());
	    Double_t nprod = params->GetValue(timesfactor,1.000);
	    if (nprod != 1.0 ) lgd_entry.Form("%s x%2.0f",lgd_entry.Data(),nprod);
	    //cout << i+nbkg+3 << " " << nprod << " " << lgd_entry.Data() << endl;
	    NiceAddEntry(lgd,h,lgd_entry.Data(),"L"); 
	}
	lgd->Draw("SAME");	
    }// show legend


    // Draw the KS:
    TLatex *ks = new TLatex();
    ks->SetTextFont(62);
    ks->SetTextColor(1);   
    TString ks_val = Form("KS = %3.2f",KS);
    ks->SetTextAlign(11); ks->SetTextSize(0.03); // ks->SetTextAngle(90); 
    ks->DrawTextNDC(0.83,0.93,ks_val.Data());
    TString chi2_val = Form("#chi^{2}/ndf = %3.1f",chi2ndf);
    ks->SetNDC(true); ks->DrawLatex(0.83,0.97,chi2_val.Data());
    //
    // Voila!
    //
}
Пример #15
0
void dileptonMassFit(const char* pInFileName="PanchoSkim4JanAll.root",
                     // "PromtRecoV2V3V3H_DiMuonPlot_TightSTACutsAll15Dec.root",
                     // "Z0_DataMixPt50_PatDiMuonPlots_NewCutAll14Dec.root",
                     const char* pHistNameOpCh="diMuonsGlobalInvMassVsPt",//diMuonsGlobalInvMassVsPtW",
                     const char* pHistNameSameCh="diMuonsGlobalSameChargeInvMassVsPt",
                     const char* pSpectra="pt",  // pt, y, centr
                     bool doMc=false,
                     int nFitFunction = 3,
                     int getYield = 1)
{
    gROOT->Macro("setStyle.C+");

    //gROOT->Macro("/Users/eusmartass/Software/utilities/setStyle.C+");
    char szBuf[256];

    ////////  definitions of Switches   ///////////
    //  nFitFunction  = 1  RBW + Pol2
    //  nFitFunction  = 2  Gaus + Pol2
    //  nFitFunction  = 3  RBWGaus + Pol2

    //  getYield = 1  Bin counting
    //  getYield = 2  Integral
    ////////////////////////////////////////////////////////////

    // make some choices
    float MassZ0         = 91.1876;
    float WidthZ0        = 2.4952;
    float massFit_low    = 60;
    float massFit_high   = 120;   // Fit ranges
    float massDraw_low   = 30.0;  // 0.
    float massDraw_high  = 130.0; // 200/
    int nrebin           = 80;
    bool isLog           = 0;
    bool isFit           = 1; // draw ranges

    float massCount_low  = 60.0; //78.0
    float massCount_high = 120.0; //102.0

    //___________________________________________________________________________________
    // ------- Open input file
    sprintf(szBuf,"%s",pInFileName);
    TString inFileName(szBuf);
    TFile *pfInFile = new TFile(inFileName);

    // ------- get histograms:
    sprintf(szBuf,"%s",pHistNameOpCh);
    TH2D *phDimuMass_1  = (TH2D*)pfInFile->Get(szBuf)->Clone("phDimuMass_1");

    sprintf(szBuf,"%s",pHistNameSameCh);
    TH2D *phDimuMass_1S = (TH2D*)pfInFile->Get(szBuf)->Clone("phDimuMass_1S");

    phDimuMass_1->SetDirectory(0);
    phDimuMass_1S->SetDirectory(0);

    // Open pp data file

    TFile *ppFile = new TFile("Zmumu_40-200_35pb.root");
    TH1F *Zmumu  = (TH1F*)ppFile->Get("hdata");


    //___________________________________________________________________________________
    // bins definition:
    const char* Xname[] = {" ", "p_{T}^{Dimuon} (GeV/c)", "rapidity", "centrality"};
    bool doPt   = false;
    bool doY    =  false;
    bool doCent = false;

    int GenRange, nBins;
    double binEdge[10];
    char* label;
    sprintf(szBuf,"%s",pSpectra);
    TString wichSpectra(szBuf);

    if ( wichSpectra.CompareTo("pt") == 0) {
        doPt               = true;
        label              = (char*)Xname[1];
        GenRange           = 20;
        nBins              = 1;
        binEdge[0] = 0.0;
        binEdge[1]= 100.0;
        //    double binEdge[10] = {0.0, 10., 20., 100.0};
        if(doMc) {
            nBins              = 1;
            binEdge[0] = 0.0;
            binEdge[1]= 50.0;
            //	  nBins          = 7;
            // binEdge[0] =  0.0;  binEdge[1] =  2.0;  binEdge[2] =  4.0;  binEdge[3] = 8.0;
            //binEdge[4] = 12.0;  binEdge[5] = 16.0;  binEdge[6] = 22.0;  binEdge[7] = 50.0;
        }
    } else {
        if ( wichSpectra.CompareTo("y") == 0) {
            doY              = true;
            label            = (char*)Xname[2];
            nBins            = 3;
            GenRange         = 4.8;
            binEdge[0] = -2.4;
            binEdge[1] = -0.8;
            binEdge[2] =  0.8;
            binEdge[3] =  2.4;
        } else {
            if ( wichSpectra.CompareTo("cent") == 0) 	{
                doCent           = true;
                label            = (char*)Xname[3];
                nBins            = 4;
                GenRange         = 40;
                binEdge[0] = 0.;
                binEdge[1] =   4;
                binEdge[2] = 8.;
                binEdge[3] =  16;
                binEdge[4] =  40;
            } else {
                cout<<"Don't know what you want to do!!!!"<<endl;
                return;
            }
        }
    }

    double PT[10], DelPT[10], mom_err[100];
    for (Int_t ih = 0; ih < nBins; ih++)  {
        PT[ih]      = (binEdge[ih] + binEdge[ih+1])/2.0;
        DelPT[ih]   = binEdge[ih+1] - binEdge[ih];
        mom_err[ih] = DelPT[ih]/2.0;
    }

    //___________________________________________________________________________________

    double gen_pt[10];
    double egen_pt[10];

    TCanvas *pcPt_1 = new TCanvas("pcPt_1"," Z0 Yield Vs. Pt ", 40,40,600,600);

    if(doMc) {
        pcPt_1->Divide(nBins,2);

        //TH2D *genMass_1 = (TH2D*)pfInFile->Get("diMuonsGenInvMassVsPt");
        TH2D *genMass_1 = (TH2D*)pfInFile->Get("diMuonsGenInvMassVsPtW");
        TH1D *ptaxis    = (TH1D*)genMass_1->ProjectionY("ptaxis");

        for (Int_t ih = 0; ih < nBins; ih++) {
            pcPt_1->cd(ih+nBins+1);

            int bin1 = ptaxis->FindBin(binEdge[ih]+0.0000001);
            int bin2 = ptaxis->FindBin(binEdge[ih+1]+0.0000001);

            TH1D * genMassVsPt = (TH1D*)genMass_1->ProjectionX("genMassVsPt", bin1, bin2-1);
            genMassVsPt->Draw("EPL");
            pcPt_1->Update();

            TAxis *axs        = genMassVsPt->GetXaxis();
            int binlow        = axs->FindBin(massCount_low);
            int binhi         = axs->FindBin(massCount_high);

            double int_sig_gen;
            double int_sig_gen_sqr;
            for(Int_t bin = binlow; bin<=binhi; bin++) {
                //    cout << "	  int_sig += dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin);"<<int_sigpow_gen <<"+="<< "bin" << bin << " content"<<genMassVsPt->GetBinContent(bin)<<endl;
                int_sig_gen += genMassVsPt->GetBinContent(bin);
                int_sig_gen_sqr += pow(genMassVsPt->GetBinContent(bin),2);
            }


            gen_pt[ih] = int_sig_gen;//genMassVsPt->GetEntries();
            cout<<" gen entries : "<< gen_pt[ih]<<endl;
            egen_pt[ih] =int_sig_gen_sqr;

        }
    }
    else {
        if (nBins == 2)  pcPt_1->Divide(2,1);
        if (nBins == 3 || nBins == 4)  pcPt_1->Divide(2,2);
        if (nBins == 5 || nBins == 6)  pcPt_1->Divide(3,2);

    }


    //___________________________________________________________________________________
    // Fit Function
    //  const char *name_fit[] = {"  ", "RBWPol1", "GausPol1", "RBWGausPol2"};
    int nParam[]           = {0,6,6,7};
    int nFitParam          = nParam[nFitFunction];
    TF1 *RBWPOL=0;
    if(nFitFunction == 1) RBWPOL = new TF1("RBWPOL", RBWPol2,     0, 200, nFitParam);
    if(nFitFunction == 2) RBWPOL = new TF1("RBWPOL", GausPol2,    0, 200, nFitParam);
    if(nFitFunction == 3) RBWPOL = new TF1("RBWPOL", RBWGausPol2, 0, 200, nFitParam);
    TF1 *EXP               = new TF1("EXP", Exp, 0, 200, 2);

    RBWPOL->SetLineWidth(1);
    RBWPOL->SetParameter(1, MassZ0);
    RBWPOL->SetParameter(2, WidthZ0);

    RBWPOL->SetParLimits(1, 0.9*MassZ0, 1.1*MassZ0);
    RBWPOL->SetParLimits(2, 0.1*WidthZ0, 5.0*WidthZ0);

    if(nFitFunction  == 1 || nFitFunction  == 2) RBWPOL->FixParameter(5, 0);
    if(nFitFunction  == 3 || nFitFunction  == 4)  {
        RBWPOL->SetParameter(3, WidthZ0);
        RBWPOL->SetParLimits(3, 0.1, 20);
        RBWPOL->FixParameter(2, WidthZ0);

        RBWPOL->FixParameter(4, 0);   // for no bkg
        RBWPOL->FixParameter(5, 0);   // for no bkg
        RBWPOL->FixParameter(6, 0);
    }


    //___________________________________________________________________________________
    // Efficiency

    double yld_cat_1[10], cyld_cat_1[10], eyld_cat_1[10], ceyld_cat_1[10];
    double Eff_cat_1[10], errEff_cat_1[10];


    ///// Write the spectra
    sprintf(szBuf,"fileSpecta%d.root", getYield);
    //  TFile *fileSpectra = new TFile(szBuf, "recreate");


    //___________________________________________________________________________________
    // Drawing
    // Category _1
    TLegend *pLegCategory = new TLegend(.66, .74, .92, .94);
    //  pLegCategory = new TLegend(.1, .82, .50, .93);
    pLegCategory->SetBorderSize(0);
    pLegCategory->SetFillStyle(0);
    pLegCategory->SetFillColor(0);
    pLegCategory->SetTextSize(0.03);
    //  pLegCategory->AddEntry(RBWPOL," CMS Preliminary", " ");

    pLegCategory->AddEntry(RBWPOL," CMS Pb+Pb ", " ");
    pLegCategory->AddEntry(RBWPOL," #sqrt{s_{NN}} = 2.76 TeV ", " ");
    pLegCategory->AddEntry(RBWPOL," #int Ldt  = 6.6 #mub^{-1} ", " ");

    //  pLegCategory->AddEntry(RBWPOL," Global-Global ", "");
    //pLegCategory->AddEntry(RBWPOL," |y| < 2.4 ", "P");
    //pLegCategory->AddEntry(RBWPOL," Run# 150431-151027 ", "P");

    TLegend *legend_1[12];
    for(int i=0; i<12; i++) {
        if(isFit) legend_1[i] = new TLegend(.13, .66, .52, 0.94);
        if(!isFit) legend_1[i] = new TLegend(.13, .66, .52, 0.94 );
        //    legend_1[i] = new TLegend(.68, .62, .91, 0.93 );
        legend_1[i]->SetBorderSize(0);
        legend_1[i]->SetFillStyle(0);
        legend_1[i]->SetFillColor(0);
        legend_1[i]->SetTextSize(0.028);
    }

    int bin_bound[100];
    TH1D *dimuonsGlobalInvMassVsPt[10];
    TH1D *dimuonsGlobalInvMassVsPtS[10];
    TH1D *service = (TH1D*)phDimuMass_1->ProjectionY("service");

    //  cout << endl << label << "    Yield      Mass (GeV)    Width (GeV)    GauWidth    chi2/ndf " << endl << endl;
    for (Int_t ih = 0; ih < nBins; ih++)  {
        pcPt_1->cd(ih+1);
        gPad->SetTickx();
        gPad->SetTicky();

        // Project 1 D
        bin_bound[ih]   = service->FindBin(binEdge[ih]+0.0000001);
        bin_bound[ih+1] = service->FindBin(binEdge[ih+1]+0.0000001);

        sprintf(szBuf,"Z0_1_pt_%d",ih);
        dimuonsGlobalInvMassVsPt[ih]  = (TH1D*)phDimuMass_1->ProjectionX(szBuf, bin_bound[ih], bin_bound[ih+1]-1+1, "e");
        sprintf(szBuf,"Z0_1S_pt_%d",ih);
        dimuonsGlobalInvMassVsPtS[ih] = (TH1D*)phDimuMass_1S->ProjectionX(szBuf, bin_bound[ih], bin_bound[ih+1]-1+1);
        cout << "reco entries" << dimuonsGlobalInvMassVsPt[ih]->GetEntries() <<endl;
        if(doPt || doY) {
            sprintf(szBuf," %s [%.1f, %.1f]",
                    label,
                    service->GetBinLowEdge(bin_bound[ih]),
                    service->GetBinLowEdge(bin_bound[ih+1]-1) + service->GetBinWidth(bin_bound[ih+1]));
        }

        if(doCent) {
            sprintf(szBuf," %s [%.1f, %.1f] %s",
                    label,
                    2.5*service->GetBinLowEdge(bin_bound[ih]),
                    2.5*(service->GetBinLowEdge(bin_bound[ih+1]-1) + service->GetBinWidth(bin_bound[ih+1])), "%");
        }

        dimuonsGlobalInvMassVsPt[ih]->Rebin(nrebin);
        dimuonsGlobalInvMassVsPtS[ih]->Rebin(nrebin);

        // -------- Fit Function + Bkg Function
        double part[20];
        dimuonsGlobalInvMassVsPt[ih]->Fit("EXP","LEQ", "", 34, 60);
        EXP->GetParameters(part);
        if(nFitFunction  == 4) {
            RBWPOL->FixParameter(4, part[0]);
            RBWPOL->FixParameter(5, part[1]);
        }

        if(isFit) {
            //dimuonsGlobalInvMassVsPt[ih]->Fit("RBWPOL","LEQ", "", massFit_low, massFit_high);
            //TFitResultPtr r =
            dimuonsGlobalInvMassVsPt[ih]->Fit("RBWPOL","LEQS0","", massFit_low, massFit_high);
            //	if(r->IsValid()) r->Print();
            //else cout<<"Fit not valid!!!\n"<<endl;
        }

        //------  get fit parameters
        double par[20];
        RBWPOL->GetParameters(par);

        float GGphDimuMass = RBWPOL->GetParameter(1);
        float GGZ0Width    = RBWPOL->GetParameter(2);
        float GauWidth     =0;
        if(nFitFunction  == 3 || nFitFunction  == 4) GauWidth = RBWPOL->GetParameter(3);

        double chisq      = RBWPOL->GetChisquare();
        int ndf           = RBWPOL->GetNDF();
        double chisqdf    =1000;
        if(ndf!=0) chisqdf=chisq/ndf;

        // +++ set backgroudn fit
        sprintf(szBuf,"pt_1B_%d",ih);
        TF1 *bkgFit_1 = new TF1(szBuf, Pol2, massFit_low, massFit_high, 3);
        // if(nFitFunction  == 4) bkgFit_1 = new TF1(namePt_1B, Exp, massFit_low, massFit_high, 2);

        bkgFit_1->SetParameters(&par[3]);
        if(nFitFunction  == 3 || nFitFunction  == 4) bkgFit_1->SetParameters(&par[4]);

        // ----------  Integrated Yield
        //    float massCount_low =GGphDimuMass-(4.0*GGZ0Width);
        //    float massCount_high =GGphDimuMass+(4.0*GGZ0Width);

        TAxis *axs        = dimuonsGlobalInvMassVsPt[ih]->GetXaxis();
        int binlow        = axs->FindBin(massCount_low);
        int binhi         = axs->FindBin(massCount_high);
        Double_t bin_size = (1.0*dimuonsGlobalInvMassVsPt[ih]->GetNbinsX())/(axs->GetXmax() - axs->GetXmin());

        Float_t int_sig   = 0.0;
        Float_t int_sig_sqr   = 0.0;
        for(Int_t bin = binlow; bin<=binhi; bin++) {
            //	  cout << "	  int_sig += dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin);"<<int_sig <<"+="<< "bin" << bin << " content"<<dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin)<<endl;
            int_sig += dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin);
            int_sig_sqr += pow(dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin),2);
        }

        if(getYield == 2) {
            int_sig =  RBWPOL->Integral(massCount_low, massCount_high)*bin_size;
            yld_cat_1[ih]   = int_sig - bin_size*bkgFit_1->Integral(massCount_low, massCount_high);
            eyld_cat_1[ih] = TMath::Sqrt(int_sig + bin_size*bkgFit_1->Integral(massCount_low, massCount_high) );
        }

        else {
            yld_cat_1[ih]   = int_sig ;
            eyld_cat_1[ih] = int_sig_sqr;
        }
        cout << "int_sig - bin_size*bkgFit_1->Integral(massCount_low, massCount_high);" << int_sig<< "  -"<< bin_size<<"*"<<bkgFit_1->Integral(massCount_low, massCount_high)<< " with low"<< massCount_low<<" high "<< massCount_high<<endl;
        //// Printing /////
        cout <<  PT[ih] << "    " << yld_cat_1[ih] << " +- " << eyld_cat_1[ih] <<"     " << GGphDimuMass << "    " << GGZ0Width  << "    " << GauWidth <<"   "<< chisq << "/" << ndf  << endl;


        // -------------- Draw
        //    dimuonsGlobalInvMassVsPt[ih]->SetMinimum(-.05*dimuonsGlobalInvMassVsPt[ih]->GetMaximum());

        if(isLog) gPad->SetLogy(1);

        TColor *pal    = new TColor();
        Int_t kblue    = pal->GetColor(9,0,200);
        //    Int_t korange  = pal->GetColor(101, 42,  0);

        // +++ opposite charge
        dimuonsGlobalInvMassVsPt[ih]->SetMarkerStyle(21);
        dimuonsGlobalInvMassVsPt[ih]->SetMarkerColor(kblue);
        dimuonsGlobalInvMassVsPt[ih]->SetLineColor(kblue);
        dimuonsGlobalInvMassVsPt[ih]->SetMarkerSize(1.1);
        dimuonsGlobalInvMassVsPt[ih]->GetXaxis()->SetTitle("Dimuon mass (GeV/c^{2})");
        dimuonsGlobalInvMassVsPt[ih]->GetYaxis()->SetTitle("dN/dM (2 GeV/c^{2})^{-1}");

        dimuonsGlobalInvMassVsPt[ih]->GetXaxis()->SetRangeUser(massDraw_low,massDraw_high);
        //    dimuonsGlobalInvMassVsPt[ih]->Add(dimuonsGlobalInvMassVsPtS[ih], -1);

        pcPt_1->cd(ih+1);


        dimuonsGlobalInvMassVsPt[ih]->DrawCopy("EPLsame");

        // pp data

        TAxis *axs1   = Zmumu->GetXaxis();
        int ll        = axs1->FindBin(massCount_low);
        int hh        = axs1->FindBin(massCount_high);

        double scalefactor =  yld_cat_1[ih]/Zmumu->Integral(ll, hh);

        cout << Zmumu->Integral(ll, hh) << endl;

        Zmumu->Scale(scalefactor);

        Zmumu->SetFillColor(19);

        Zmumu->Draw("same");

        dimuonsGlobalInvMassVsPt[ih]->DrawCopy("EPLsame");

        //    dimuonsGlobalInvMassVsPt[ih]->Draw("B");

        // +++ same charge
        dimuonsGlobalInvMassVsPtS[ih]->SetMarkerStyle(8);
        dimuonsGlobalInvMassVsPtS[ih]->SetMarkerColor(46);
        dimuonsGlobalInvMassVsPtS[ih]->SetLineColor(46);

        dimuonsGlobalInvMassVsPtS[ih]->SetMarkerSize(1.1);
        dimuonsGlobalInvMassVsPtS[ih]->DrawCopy("EPsame");


        // background
        //    RBWPOL->SetLineColor(kblue);
        bkgFit_1->SetLineColor(46);
        bkgFit_1->SetLineWidth(1);
        //    if(isFit) bkgFit_1->Draw("same");

        // ++++ legend
        pLegCategory->Draw("same");


        //    legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," Global-Global", " ");

        legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," |#eta^{#mu}| < 2.4, p_{T}^{#mu} > 10 GeV/c ", "");
        legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," Unlike Sign ", "LP");
        legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPtS[ih]," Like Sign ", "LP");
        legend_1[ih]->AddEntry(Zmumu," pp Data ", "L");




        //    legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], text, "");


        sprintf(szBuf, "N=%1.0f #pm %1.1f ", yld_cat_1[ih], sqrt(yld_cat_1[ih]) );

        legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], szBuf, "");

        //    sprintf(label_1, "N_{Z^{0}} = 27");

        sprintf(szBuf, "mass = %1.2f #pm %1.2f GeV/c^{2}", RBWPOL->GetParameter(1), RBWPOL->GetParError(1));
        //    if(isFit) legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih],szBuf, "");

        sprintf(szBuf, "#sigma_{Gauss} = %1.2f #pm %1.2f GeV/c^{2}", RBWPOL->GetParameter(2), RBWPOL->GetParError(2));

        if(nFitFunction ==3 || nFitFunction  == 4)
            sprintf(szBuf, "#sigma_{Gauss} = %1.2f #pm %1.2f GeV/c^{2}", RBWPOL->GetParameter(3), RBWPOL->GetParError(3));

        //    if(isFit) legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], szBuf, "");

        sprintf(szBuf, "#chi^{2}/ndf = %1.2f / %d", chisq, ndf);

        //    if(isFit) legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], label_4, "");

        legend_1[ih]->Draw("same");

        pcPt_1->Update();
    }

    cout << endl << endl;


    TGraphErrors *Z0pt_cat_1 = new TGraphErrors(nBins, PT, yld_cat_1, mom_err, eyld_cat_1);
    Z0pt_cat_1->SetMarkerStyle(20);
    Z0pt_cat_1->SetMarkerColor(2);
    Z0pt_cat_1->GetXaxis()->SetTitle(label);
    Z0pt_cat_1->GetYaxis()->SetTitle("counts");

    TCanvas *pc2 = new TCanvas("pc2","pc2");
    Z0pt_cat_1->SetMinimum(0.0);
    Z0pt_cat_1->SetName("Z0pt_cat_1");
    Z0pt_cat_1->Draw("AP");


    TGraphErrors *Z0ptC_cat_1_gen = new TGraphErrors(nBins, PT, gen_pt, mom_err, egen_pt);
    //  Z0ptC_cat_1_gen->SetMarkerStyle(23);
    //Z0ptC_cat_1_gen->SetMarkerColor(3);
    //Z0ptC_cat_1_gen->Draw("AP");


    pLegCategory->Draw("same");

    Z0pt_cat_1->Write();
    pLegCategory->Write();


    //    gPad->Print("Pt_Z0YieldCat_1.png");
    pcPt_1->Print("Pt_Z0YieldCat_1.png");


    cout << endl << endl;




    //////////////////////////////////////////////////////////////////////////////

    // Efficiency correction
    if(doMc)  {
        ofstream fileout("correction.txt");
        cout << label << "   Eff_cat_1  " << endl;

        for (Int_t ih = 0; ih < nBins; ih++)  {
            Eff_cat_1[ih] = yld_cat_1[ih]/gen_pt[ih];

            errEff_cat_1[ih] = sqrt( (pow(Eff_cat_1[ih]/yld_cat_1[ih],2))*eyld_cat_1[ih]
                                     +(pow((1-Eff_cat_1[ih]/yld_cat_1[ih]),2))*( yld_cat_1[ih]-gen_pt[ih]/ yld_cat_1[ih]));
            //	  errEff_cat_1[ih] = sqrt( (pow(Eff_cat_1[ih]/yld_cat_1[ih],2))*eyld_cat_1[ih]
            //			   +(pow((1-Eff_cat_1[ih]/yld_cat_1[ih]),2))*event failing);


            //	fileout << PT[ih] <<"   "<< Eff_cat_1[ih] << "   " << Eff_cat_2[ih] <<"    " << Eff_cat_3[ih] << endl;
            //	cout <<"    " << PT[ih] <<"      "<< Eff_cat_1[ih] << "      " << Eff_cat_2[ih] << "      " << Eff_cat_3[ih] << endl;

            fileout << PT[ih] <<"   "<< Eff_cat_1[ih] << "   " << errEff_cat_1[ih] << endl;
            cout <<"    " << PT[ih] <<"    "<< Eff_cat_1[ih] << " +- " << errEff_cat_1[ih] << endl;
            cyld_cat_1[ih] = Eff_cat_1[ih];
            ceyld_cat_1[ih] = errEff_cat_1[ih];

        }
    }
    else {
        ifstream filein("correction.txt");
        cout <<  label << " yld_cat_1 "  << "  efficiency " <<  " corr. yld_cat_1  " << endl;
        for (Int_t ih = 0; ih < nBins; ih++)  {

            //      filein >> PT[ih] >>  Eff_cat_1[ih] >>  Eff_cat_2[ih]  >>  Eff_cat_3[ih] ;
            //      cout << "       " << PT[ih] << "      "<< yld_cat_1[ih] << "       " << yld_cat_2[ih] <<"      " <<  yld_cat_3[ih] << endl;

            filein >> PT[ih] >>  Eff_cat_1[ih]  >> errEff_cat_1[ih];
            cout << "    " << PT[ih] << "     " << yld_cat_1[ih] << "     " << Eff_cat_1[ih] << "     " << yld_cat_1[ih]/Eff_cat_1[ih] << endl;
            cyld_cat_1[ih] = yld_cat_1[ih]/Eff_cat_1[ih];
            ceyld_cat_1[ih] = eyld_cat_1[ih]/Eff_cat_1[ih];

        }
    }

    //  TF1 *EXPA = new TF1("EXPA", Exp, 0, 100, 2);

    TGraphErrors *Z0ptC_cat_1 = new TGraphErrors(nBins, PT, cyld_cat_1, mom_err, ceyld_cat_1);
    Z0ptC_cat_1->SetMarkerStyle(20);
    Z0ptC_cat_1->SetMarkerColor(2);
    Z0ptC_cat_1->GetXaxis()->SetTitle(label);
    Z0ptC_cat_1->GetYaxis()->SetTitle("Acc x Eff");
    //  if(part == 2) Z0ptC_cat_1->Fit("EXPA","LEQ", "", 7, 16);


    new TCanvas;
    Z0ptC_cat_1->SetMinimum(0.0);
    Z0ptC_cat_1->SetMaximum(0.8);
    Z0ptC_cat_1->SetName("Z0ptC_cat_1");
    Z0ptC_cat_1->Draw("AP");


    pLegCategory->Draw("same");

    cout << endl << endl;

    Z0ptC_cat_1->Write();

}