void performClosure(RooRealVar *mass, RooAbsPdf *pdf, RooDataSet *data, string closurename, double wmin=110., double wmax=130., double slow=110., double shigh=130., double step=0.002) {
  
  // plot to perform closure test
  cout << "Performing closure test..." << endl; 
  double nbins = (wmax-wmin)/step;
  TH1F *h = new TH1F("h","h",int(floor(nbins+0.5)),wmin,wmax);
  if (data){
    pdf->fillHistogram(h,RooArgList(*mass),data->sumEntries());
    h->Scale(2*h->GetNbinsX()/double(binning_));
  }
  else {
    pdf->fillHistogram(h,RooArgList(*mass));
  }
  int binLow = h->FindBin(slow);
  int binHigh = h->FindBin(shigh)-1;
  TH1F *copy = new TH1F("copy","c",binHigh-binLow,h->GetBinLowEdge(binLow),h->GetBinLowEdge(binHigh+1));
  for (int b=0; b<copy->GetNbinsX(); b++) copy->SetBinContent(b+1,h->GetBinContent(b+1+binLow));
  double areaCov = 100*h->Integral(binLow,binHigh)/h->Integral();
 
  // style
  h->SetLineColor(kBlue);
  h->SetLineWidth(3);
  h->SetLineStyle(7);
  copy->SetLineWidth(3);
  copy->SetFillColor(kGray);
  
  TCanvas *c = new TCanvas();
  if (data){
    RooPlot *plot = mass->frame(Bins(binning_),Range("higgsRange"));
    plot->addTH1(h,"hist");
    plot->addTH1(copy,"same f");
    if (data) data->plotOn(plot);
    pdf->plotOn(plot,Normalization(h->Integral(),RooAbsReal::NumEvent),NormRange("higgsRange"),Range("higgsRange"),LineWidth(1),LineColor(kRed),LineStyle(kDashed));
    plot->Draw();
    c->Print(closurename.c_str());
  }
  else {
    RooPlot *plot = mass->frame(Bins(binning_),Range("higgsRange"));
    h->Scale(plot->getFitRangeBinW()/h->GetBinWidth(1));
    copy->Scale(plot->getFitRangeBinW()/h->GetBinWidth(1));
    pdf->plotOn(plot,LineColor(kRed),LineWidth(3));
    plot->Draw();
    h->Draw("hist same");
    copy->Draw("same f");
    c->Print(closurename.c_str());
  }
  cout << "IntH: [" << h->GetBinLowEdge(binLow) << "-" << h->GetBinLowEdge(binHigh+1) << "] Area = " << areaCov << endl;
  delete c;
  delete copy;
  delete h;
}
Example #2
0
  TH1F * getpdgs(std::string const & dr, std::string const & we) {
    
    TCanvas * canvas_temp = new TCanvas("temp");
    tree->Draw((dr+">>h").c_str(), we.c_str());
    TH1F * hist = (TH1F*)gDirectory->Get("h");
    int const min = hist->GetBinLowEdge(hist->FindFirstBinAbove(0));
    int const max = hist->GetBinLowEdge(hist->FindLastBinAbove(0)) +
      hist->GetBinWidth(hist->FindLastBinAbove(0)) + 1;
    int const binno = max - min;
    delete canvas_temp;
    delete hist;

    canvas_temp = new TCanvas("temp");
    tree->Draw(Form((dr+">>h(%d,%d,%d)").c_str(), binno, min, max), we.c_str());
    ofile->cd();
    delete canvas_temp; 
    TH1F * histb = (TH1F*)gDirectory->Get("h");

    if(histb->GetEntries() == 0) {
      delete histb;
      return nullptr;
    }    

    return histb;
    
  }
// get FWHHM
vector<double> getFWHM(RooRealVar *mass, RooAbsPdf *pdf, RooDataSet *data, double wmin=110., double wmax=130., double step=0.0004) {
 
  cout << "Computing FWHM...." << endl;
  double nbins = (wmax-wmin)/step;
  TH1F *h = new TH1F("h","h",int(floor(nbins+0.5)),wmin,wmax);
  if (data){
    pdf->fillHistogram(h,RooArgList(*mass),data->sumEntries());
  }
  else {
    pdf->fillHistogram(h,RooArgList(*mass));
  }
  
  double hm = h->GetMaximum()*0.5;
  double low = h->GetBinCenter(h->FindFirstBinAbove(hm));
  double high = h->GetBinCenter(h->FindLastBinAbove(hm));

  cout << "FWHM: [" << low << "-" << high << "] Max = " << hm << endl;
  vector<double> result;
  result.push_back(low);
  result.push_back(high);
  result.push_back(hm);
  result.push_back(h->GetBinWidth(1));
  
  delete h;
  return result;
}
Example #4
0
// Called within makePlot when making the pu plot
// Basically adds in the +/- 5% systematic error bars
TGraphAsymmErrors makePUPlot( THStack stack, TString anaType, const float lumi ) {

  // Got the stack, now sum the =/- 5% histograms and make two new stacks
  // Make dummy legend etc.
  THStack p5Stack("Background MC p5","");
  THStack m5Stack("Background MC m5","");
  TLegend *legend= new TLegend(0.1,0.1,0.1,0.1);

  addBackgroundHistos( anaType, "nRecoPV_p5", p5Stack, legend, lumi );
  addBackgroundHistos( anaType, "nRecoPV_m5", m5Stack, legend, lumi );

  // Get last histogram in stacks i.e. sum of all backgrounds
  TH1F * hist = new TH1F( *(TH1F*)(stack.GetStack()->Last()) );
  TH1F * p5Hist = new TH1F( *(TH1F*)p5Stack.GetStack()->Last() );
  TH1F * m5Hist = new TH1F( *(TH1F*)m5Stack.GetStack()->Last() );

  // Create structures to make TGraphAssymErrors
  Int_t n=p5Hist->GetNbinsX();
  Double_t x[n]; // x values
  Double_t y[n]; // y values
  Double_t exl[n]; // low x error
  Double_t eyl[n]; // low y error
  Double_t exh[n]; // high x error
  Double_t eyh[n]; // high y error

  // Loop over histos and get values
  for ( int bin=1; bin < n+1; bin++ ) {
    x[bin-1]=hist->GetBinCenter( bin );
    y[bin-1]=hist->GetBinContent( bin );
    exl[bin-1]=hist->GetBinWidth( bin )/2;
    eyl[bin-1]=p5Hist->GetBinContent( bin )-y[bin-1];
    exh[bin-1]=hist->GetBinWidth( bin )/2;
    eyh[bin-1]=y[bin-1]-m5Hist->GetBinContent( bin );
  }


  // Make TGraphAssymErrors
  TGraphAsymmErrors gr(n,x,y,exl,exh,eyl,eyh);

  return gr;
}
void FitterCBForSignificance(){



  //  TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_gg_TuneD6T_Emine2013.root");

  TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_qg_TuneD6T_Emine2013.root");



  //  TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_Qstar_2012_D6T_ak5_fat30_save.root");
  //  TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_RSGraviton_2012_D6T_ak5_GGtoGG_fat30_save.root");
  //TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_RSGraviton_2012_D6T_ak5_QQtoQQ_fat30_save.root");

  //TFile* _shapes = new TFile("/afs/cern.ch/user/m/mgouzevi/scratch0/CMGTools/CMSSW_4_2_8/src/StatTools/BayesianDijetFit/Results/Resonance_Shapes_Qstar_ak5_fat30.root");
  for (int i = 1; i < 2; i++){
	   TH1F* shape = (TH1F*) _shapes->Get(Form("h_qg_%d;1", 1000+i*100));
	   TH1F* shape_largeBinning = new TH1F("shape_large_binning", "", NBINS, BOUNDARIES);

	   for (int j = 1; j < shape->GetNbinsX()+1; j++){
	     double binCenter = shape->GetBinCenter(j);
	     double weight = shape->GetBinContent(j);
	     double binWidth = shape->GetBinWidth(j);
	     shape_largeBinning->Fill(binCenter, weight);
	     //	     cout << "j = " << j << " binWidth = " << binWidth << " weight = " << weight << endl;
	     shape->SetBinContent(j, weight/binWidth);
	   }

	   for (int j = 1; j < shape_largeBinning->GetNbinsX()+1; j++){
	     double weight = shape_largeBinning->GetBinContent(j);
	     double binWidth = shape_largeBinning->GetBinWidth(j);
	     shape_largeBinning->SetBinContent(j, weight/binWidth*1000000);
	   }

	   shape->Draw();

	   shape_largeBinning->SetLineColor(kRed);
	   shape_largeBinning->Draw("SAME");

	   //   
	   FitHistWithCBShape(shape_largeBinning, 1000.+i*100);		
	}

	  cout << "mass\tsMean\tsSigma\tsAlphaHigh\tsAlphaLow\tsNHigh\tsNLow\tsFrac"<<endl;

	for (int i = 0; i < 40; i++){
	
	  cout << Masses[i] << "\t" << Means[i] << "\t" << Sigmas[i] << "\t"
	       << alphaHights[i] << "\t\t" << alphaLows[i] << "\t"
	       << nHighs[i] << "\t\t" << nLows[i] << "\t" << fracs[i] << endl;

	}
}
Example #6
0
void PIDPedes()
{
  TH1F* Energy;
  Char_t Buff[256];

  for(Int_t ch=0; ch<24; ch++)
  {
    sprintf(Buff, "PID_Energy%d", ch);
    Energy = (TH1F*)gROOT->FindObject(Buff);
    printf("%4.0f\n", Energy->GetMaximumBin()*Energy->GetBinWidth(Energy->GetMaximumBin()));
  }
}
Example #7
0
void PIDTimes()
{
  TH1F* Time;
  Char_t Buff[256];

  for(Int_t ch=0; ch<24; ch++)
  {
    sprintf(Buff, "PID_Time%d", ch);
    Time = (TH1F*)gROOT->FindObject(Buff);
    printf("%5.1f\n", Time->GetMaximumBin()*Time->GetBinWidth(Time->GetMaximumBin()) - 200.0);
  }
}
Example #8
0
void VetoTimes()
{
  TH1F* Time;
  Char_t Buff[256];

  for(Int_t ch=0; ch<384; ch++)
  {
    sprintf(Buff, "Veto_Time%d", ch);
    Time = (TH1F*)gROOT->FindObject(Buff);
    printf("%6.1f\n", (Time->GetMaximumBin()*Time->GetBinWidth(Time->GetMaximumBin()) - 500.0)/0.05000);
  }
}
Example #9
0
void LadderTimes()
{
  TH1F* Time;
  Double_t par[4];
  Double_t Max;
  Char_t Buff[256];

  for(Int_t ch=0; ch<352; ch++)
  {
    sprintf(Buff, "Ladder_Time%d", ch);
    Time = (TH1F*)gROOT->FindObject(Buff);
    Max = Time->GetMaximumBin()*Time->GetBinWidth(Time->GetMaximumBin()) - 1000.0;
   
    TF1* gauss = new TF1("gauss", "gaus", Max-8, Max+8);
    Time->Fit(gauss, "RQ+");
    gauss->GetParameters(&par[0]);
    
    printf("%5.2f\n", par[1]/0.117710);
  }
}
Example #10
0
void countZs(const char* filename, int run1=1, int run2=0, float lumi=0, bool add=false) {
   TFile *file = new TFile(filename);
   if (!file) return;
   
   TCanvas *c1 = new TCanvas();
   c1->cd();

   TH1F *h = (TH1F*) file->Get("Run summary/DiMuonHistograms/GlbGlbMuon_HM");
   h->GetYaxis()->SetRangeUser(0,200);
   h->Draw();

   TF1 *f = new TF1("f","gaus(0)+pol2(3)",70,110);
   f->SetParName(0,"norm");
   f->SetParName(1,"mass");
   f->SetParName(2,"width");
   f->SetParameters(1.16028e+02,9.07785e+01,2.11556e+00,-2.17600e+01,9.67443e-01,-6.98382e-03);
   f->SetParLimits(0,0,1e6);
   f->SetParLimits(1,85,95);
   f->SetParLimits(2,1.5,5);
   h->Fit(f,"","",70,110);
   h->GetYaxis()->SetRangeUser(0,200);
   c1->Update();

   TF1 *f2 = new TF1("f2","gaus(0)",70,110);
   f2->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2));
   int integral = (int) (f2->Integral(70,110) / h->GetBinWidth(2));

   TLatex *tl = new TLatex();
   tl->DrawLatexNDC(0.1,0.95,Form("pPb 8TeV [%i-%i, %.1f nb^{-1}]",run1,run2,lumi));
   tl->DrawLatexNDC(0.18,0.75,Form("%i Z bosons",integral));
   tl->DrawLatexNDC(0.18,0.7,Form("(#sigma = %.1f nb)",integral/lumi));

   if (!add) c1->SaveAs(Form("plotZ_%i_%i.pdf",run1,run2));
   else c1->SaveAs("plotZ.gif+100");

   file->Close();
}
Example #11
0
//............................................
// Constructor for accpetance from a ROOT Tfile
SlicedAcceptance::SlicedAcceptance( string type, string fileName,string histName, bool fluctuate, bool quiet ) :
	slices(), nullSlice(new AcceptanceSlice(0.,0.,0.)), tlow(), thigh(), beta(), _sortedSlices(false), maxminset(false), t_min(0.), t_max(0.), _hasChecked(false), _storedDecision(false)
{
	if(!quiet) cout << "Root file being used for acceptance" << endl;
	(void)type;
	if( type != "RootFile" ) {   }//do nothing for now

	string fullFileName = StringProcessing::FindFileName( fileName, quiet );

	if( !quiet ) cout << "Opening: " << fullFileName << endl;

	TFile* file = TFile::Open(TString(fullFileName));
 	if(!quiet) cout << "File " << fullFileName << " opened!" << endl;
	TH1F* histo = (TH1F*)file->Get(TString(histName));
	if(!quiet) cout << "Histo " << histName << " opened!" << endl;
	histo->Draw();
	if(!quiet) cout << "Histo " << histName << " drawn!" << endl;
//	histo->Sumw2();

	if(fluctuate){
	cout << "WARNING! You have fluctuated the acceptance." << endl;
	cout << "WARNING! This is for systematic studies only. " << endl;
	cout << "WARNING! Projections and pull fits will have a different fluctuated acceptance to the PDF you fit with." << endl;
	cout << "WARNING! ONLY USE FluctuateAcceptance:True FOR SYSTEMATIC STUDIES" << endl;
	TRandom3 * rng = new TRandom3(0);	
	//Randomly fluctuate bin contents within error: 
	for (int l = 1; l <= histo->GetNbinsX(); ++l){
	if(!quiet)	cout << "Bin content and error before: " << histo->GetBinContent(l) << "+/-" << histo->GetBinError(l);
		histo->SetBinContent(l,rng->Gaus(histo->GetBinContent(l),histo->GetBinError(l)));
	if(!quiet)	cout <<  " and after: " << histo->GetBinContent(l) << "+/-" << histo->GetBinError(l) << endl;
	}
	delete rng;
	}

	histo->Scale(1./(histo->GetBinContent(histo->GetMaximumBin())));
	histo->SetMinimum(0);


	double maxend = histo->GetBinLowEdge(histo->GetNbinsX()) + histo->GetBinWidth(histo->GetNbinsX());
	double height;
	double start;
	double end  = histo->GetBinLowEdge(histo->GetNbinsX()) + histo->GetBinWidth(histo->GetNbinsX());
	double dheight;
	for (int l = 1; l <= histo->GetNbinsX(); ++l){
		height = histo->GetBinContent(l);
		dheight = height;
		for (int n = l; n>0; n--){
			if(histo->GetBinContent(n)<height){
				dheight = height - histo->GetBinContent(n);
				cout << l << " " << n << " " << dheight << endl;
				break;
			}
		}
		start = histo->GetBinLowEdge(l);
		end = maxend;
		for (int m = l; m <= histo->GetNbinsX(); ++m){
			double thisbinheight = histo->GetBinContent(m);
			if(thisbinheight<height){
				end = histo->GetBinLowEdge(m);
				break;
			}
		}
		slices.push_back( new AcceptanceSlice( start, end, dheight ) );
	if(!quiet)	cout << start << "	" << end << "      " << dheight << endl;
	}
	histo->Delete();
//	delete histo;
	file->Close();
	delete file;

	if( !quiet ) cout << "Time Acc Slices: " << slices.size() << endl;
	if( slices.size() == 1 )
	{
		cout << "SlicedAcceptance: SERIOUS ERROR" << endl;
		exit(0);
	}
	//....done.....


	_sortedSlices = this->isSorted();

	if( _sortedSlices )
	{
		if( !quiet ) cout << "Sliced Acceptance is using sorted horizontal slices" << endl;
	}
	else
	{
		if( !quiet ) cout << "Sliced Acceptance is NOT using sorted horizontal slices" << endl;
	}
}
Example #12
0
int main(int argc, char **argv)
{
	TString xvar = "TMath::Power(J_psi_1S_MM/1000,2)";
	TString xvarname = "q2";
	TString type = "All";
	TCut extCut = "";
	
	string drawopt = "";
	TString outFileName = "";
	bool rel = false, doSys = false, percent = false, jpsi = false, pythia6 = false;
	
	int xnbins = 12;
	double def_xbins[] = {0.1, 2.0, 4.0, 6.0, 8.0, 9.1, 10.1, 11.0, 12.5, 15.0, 16.0, 18.0, 20.0};
	//double def_xbins[] = {1.1, 6.0, 15.0, 20.0};
	double * xbins = &def_xbins[0];
	
	if(argc > 1)
	{
		for(int a = 1; a < argc; a++)
		{
			string arg = argv[a];
			string str = arg.substr(2,arg.length()-2);
			
			if(arg.find("-t") != string::npos) type = (TString)str;
			if(arg == "-r") rel = true;
			if(arg.find("-b") != string::npos ) xbins = decodeBinning(str,&xnbins);
			if(arg.find("-c") != string::npos ) xbins = decodeBinning(str,&xnbins,"custom");
			if(arg.find("-C") != string::npos ) extCut = (TCut)((TString)str);
			if(arg == "-highq2Cut") extCut = (TCut)"( TMath::Power(J_psi_1S_MM/1000,2) > 15. && TMath::Power(J_psi_1S_MM/1000,2) < 20. )";
			if(arg == "-Pythia6") pythia6 = true;
			if(arg.find("-X") != string::npos) { xvar = str; xvarname = xvar; }
			if(arg.find("-D") != string::npos) drawopt = str;
			if(arg.find("-sys") != string::npos) doSys = true;
			if(arg.find("-percent") != string::npos) percent = true;
			if(arg.find("-o") != string::npos) outFileName = str;
			if(arg.find("-jpsi") != string::npos) jpsi = true;
		}
	}
	
	if(jpsi) { if(xvarname=="q2") xbins = decodeBinning("[1,0,25]",&xnbins); rel = false; doSys = false; }

	// Set trees of cancdidates previously created

	TString mctype = "MC_Pythia8_NBweighted";
	if(pythia6) mctype = "MC_Pythia6_NBweighted"; 
	TString weight = "MCnorm*(lifeTimeW > 0)*(physRate_pol0_noDecay > 0)";
	cout << "Using: " << mctype << endl;
	cout << "Plotting: " << xvar << endl;
	cout << "Binning: [";
	for(int i = 0; i < xnbins; i++) cout << xbins[i] << ",";
	cout << xbins[xnbins] << "]" << endl;	

	TString namefileMCgeom = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2Lmumu_geom"+mctype+".root";
	TString namefileMC = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2Lmumu_"+mctype+".root";
	TString namefileMCjpsi = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2JpsiL_"+mctype+".root";
	TString namefileMCjpsiGeom = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2JpsiL_geom"+mctype+".root";
	TString namefileDataJpsi = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/Lb2Lmumu_CL_NBweighted.root";

	TString nameGeomTree = "MCtree";
	if(xvar=="cosThetaB") nameGeomTree = "MCtreeDecay";
	TFile * MCfile = TFile::Open(namefileMCgeom);
	TTree * treeMCgeom = (TTree *)MCfile->Get(nameGeomTree);
	MCfile = TFile::Open(namefileMC);
	TTree * treeMC = (TTree *)MCfile->Get("tree");
	TTree * treeMCGen = (TTree *)MCfile->Get("MCtreeDecay");
	TTree * treeMCAllGen = (TTree *)MCfile->Get("MCtree");
	MCfile = TFile::Open("/afs/cern.ch/work/p/pluca/weighted/Lmumu/trainingSamples.root");
	TTree * treeMCmva = (TTree *)MCfile->Get("sigTestSample");

	TTree * treeMCjpsi = NULL, * treeMCjpsi_Gen = NULL, * treeMCjpsi_AllGen = NULL, * treeMCjpsi_geom = NULL;
	if(rel || jpsi)
	{
		
		MCfile = TFile::Open(namefileMCjpsi);
		if(jpsi) {
		treeMC = (TTree *)MCfile->Get("tree");
		treeMCmva = (TTree *)MCfile->Get("tree");
		treeMCGen = (TTree *)MCfile->Get("MCtreeDecay");
		treeMCAllGen = (TTree *)MCfile->Get("MCtree");	}
		else {
		treeMCjpsi = (TTree *)MCfile->Get("tree");
		treeMCjpsi_Gen = (TTree *)MCfile->Get("MCtreeDecay");
		treeMCjpsi_AllGen = (TTree *)MCfile->Get("MCtree");	}
		
		MCfile = TFile::Open(namefileMCjpsiGeom);		
		if(jpsi) treeMCgeom = (TTree *)MCfile->Get(nameGeomTree);
		else treeMCjpsi_geom = (TTree *)MCfile->Get(nameGeomTree);

	
/*	
		MCfile = TFile::Open(namefileMC);
		treeMCjpsi = (TTree *)MCfile->Get("tree");
		treeMCjpsi_Gen = (TTree *)MCfile->Get("MCtreeDecay");
		treeMCjpsi_AllGen = (TTree *)MCfile->Get("MCtree");	
		
		MCfile = TFile::Open(namefileMCgeom);		
		treeMCjpsi_geom = (TTree *)MCfile->Get(nameGeomTree);
*/

	}
	
	TCut geomCut = CutsDef::geomCut;
	TCut baseCut = extCut + CutsDef::baseCutMuMu;
	if(jpsi) baseCut = extCut + CutsDef::baseCutJpsi;
	TCut baseJpsiCut = extCut + CutsDef::baseCutJpsi;
	TCut binCut = "TMath::Power(J_psi_1S_MM/1000,2) > 9.1 && TMath::Power(J_psi_1S_MM/1000,2) < 10.1";
	if(type == "DD") { baseCut += CutsDef::DDcut; baseJpsiCut += CutsDef::DDcut; }
	else if(type == "LL") { baseCut += CutsDef::LLcut; baseJpsiCut += CutsDef::LLcut; }
	cout << "Analysisng " << type << " events" << endl;

	//TCut simpleEffCut = geomCut + (TCut)"TMath::Sqrt(TMath::Power(pplus_TRUEP_X,2) + TMath::Power(pplus_TRUEP_Y,2) + TMath::Power(pplus_TRUEP_Z,2)) > 6000 && TMath::Sqrt(TMath::Power(piminus_TRUEP_X,2) + TMath::Power(piminus_TRUEP_Y,2) + TMath::Power(piminus_TRUEP_Z,2)) > 2000 && TMath::Sqrt(TMath::Power(muminus_TRUEP_X,2) + TMath::Power(muminus_TRUEP_Y,2) + TMath::Power(muminus_TRUEP_Z,2)) > 3000 && TMath::Sqrt(TMath::Power(muplus_TRUEP_X,2) + TMath::Power(muplus_TRUEP_Y,2) + TMath::Power(muplus_TRUEP_Z,2)) > 3000 && pplus_TRUEPT > 400 && muplus_TRUEPT > 100 && muminus_TRUEPT > 100";


	TString myName = "Lbeff";
	if(rel) myName = "Lbreleff";
	if(doSys) myName += "AndSys";
	if(jpsi) myName += "_Jpsi"; 
	myName += ("vs"+xvarname+"_"+type+".root");
	if(outFileName!="") myName = outFileName;
	TFile * histFile = new TFile(myName,"recreate");

	/**      Calc efficiencies and systematics        */

	vector <TString> effnames;
	effnames.push_back("geom");
	effnames.push_back("det");
	effnames.push_back("reco");
	effnames.push_back("mva");
	effnames.push_back("trig");

	vector <TH1F * >  hdefault;
	vector <TH1F * >  lfsys_plus, lfsys_minus;
	vector <TH1F * >  decaysys, DDsys;
	vector <TH1F * >  polsys_minus, polsys_plus;
	vector <TH1F * >  poljpsi1, poljpsi2, poljpsi3, poljpsi4, poljpsi5, poljpsi6, poljpsi7, poljpsi8;
	
	cout << "Analysing GEO sys" << endl;
	getAllEffSys("GEO", xvar, xnbins, xbins, weight,
			treeMCgeom, geomCut+extCut, treeMCgeom, extCut,
			treeMCjpsi_geom, geomCut+extCut+binCut, treeMCjpsi_geom, extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "-f0.5", jpsi);

	cout << "Analysing DET sys" << endl;
	if(xvar=="cosThetaB")
		getAllEffSys("DET", xvar, xnbins, xbins, weight,
			treeMCGen, extCut, treeMCgeom, geomCut+extCut,
			treeMCjpsi_Gen, extCut+binCut, treeMCjpsi_AllGen, geomCut+extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );	
	else
		getAllEffSys("DET", xvar, xnbins, xbins, weight,
			treeMCGen, extCut, treeMCAllGen, extCut,
			treeMCjpsi_Gen, extCut+binCut, treeMCjpsi_AllGen, extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );
	
	cout << "Analysing RECO sys" << endl;
	getAllEffSys("RECO", xvar, xnbins, xbins, weight,
			treeMC, baseCut, treeMCGen, extCut,
			treeMCjpsi, baseJpsiCut+binCut, treeMCjpsi_Gen, extCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );
	
	cout << "Analysing MVA sys" << endl;
	getAllEffSys("MVA", xvar, xnbins, xbins, weight,
			treeMCmva, baseCut+CutsDef::MVAcut, treeMCmva, baseCut,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+binCut, treeMCjpsi, baseJpsiCut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );

	cout << "Analysing TRIG sys" << endl;
	getAllEffSys("TRIG", xvar, xnbins, xbins, weight,
			treeMC, baseCut+CutsDef::MVAcut+CutsDef::TrigPassed, treeMC, baseCut+CutsDef::MVAcut,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+CutsDef::TrigPassed+binCut, treeMCjpsi, baseJpsiCut+CutsDef::MVAcut+binCut,
			&hdefault, &lfsys_plus, &lfsys_minus, &decaysys, &polsys_minus, &polsys_plus,
			&poljpsi1, &poljpsi2, &poljpsi3, &poljpsi4, &poljpsi5, &poljpsi6, &poljpsi7, &poljpsi8, &DDsys, doSys, "", jpsi );
	
	TH1F * toteff_lowSel = NULL;
	if(rel || jpsi)
	{
		TString polweight = "physRate_polp006";
		if(jpsi) polweight = "physRate_pol0";
		TH1F * mva_lowSel = getEff("UPPER", xvar, xnbins, xbins,
			treeMCmva, baseCut+CutsDef::MVAcut, treeMCmva, baseCut,
			weight+"*lifeTimeW*pt_weight*"+polweight,
			treeMCjpsi, baseJpsiCut+CutsDef::MVAcut_lowSel+binCut, treeMCjpsi, baseJpsiCut+binCut,
			weight+"*lifeTimeW*physRate_pol0*pt_weight" );
		mva_lowSel->Write("hmvaeff_lowSel");
		TH1F * uppereff_lowSel = (TH1F *)hdefault[2]->Clone("huppereff_lowSel");
		uppereff_lowSel->Multiply(hdefault[3]);
		uppereff_lowSel->Multiply(mva_lowSel);
		toteff_lowSel = (TH1F *)hdefault[0]->Clone("htoteff_lowSel");
		toteff_lowSel->Multiply(hdefault[1]);
		toteff_lowSel->Multiply(uppereff_lowSel);
		uppereff_lowSel->Write("huppereff_lowSel");
		toteff_lowSel->Write("htoteff_lowSel");
	}

	//Simply model
	//TH1F * simpleeff = getEff("SIMPLY", xvar, xnbins, xbins,
	//		treeMCgeom, simpleEffCut, treeMCgeom, "", weight);


			
	TCanvas * c = new TCanvas();
	gStyle->SetOptStat(0);
	gStyle->SetOptFit();
	TH1F * uppereff = (TH1F *)hdefault[2]->Clone("huppereff");
	uppereff->Multiply(hdefault[3]);
	uppereff->Multiply(hdefault[4]);

	TH1F * toteff = (TH1F *)hdefault[0]->Clone("htoteff");
	if(xvar=="cosThetaB") hdefault[1]->Scale(1./hdefault[1]->Integral());
	toteff->Multiply(hdefault[1]);
	toteff->Multiply(uppereff);
	toteff->SetTitle("Total eff");
	//toteff->Fit("pol2");
	c->Print("effvs"+xvarname+"_"+type+"_tot.pdf");
	toteff->Write("htoteff");
	//uppereff->Fit("pol2");
	c->Print("effvs"+xvarname+"_"+type+"_upper.pdf");
	uppereff->Write("huppereff");
	TH1F * tot_nodet_eff = (TH1F *)hdefault[0]->Clone("htot_nodet_eff");
	tot_nodet_eff->Multiply(uppereff);
	tot_nodet_eff->Write("htot_nodet_eff");
	//simpleeff->Write("simplified_eff");
	
	for(unsigned i = 0; i < effnames.size(); i++)
	{
		//hdefault[i]->Fit("pol2");
		if(!jpsi)
		for(int b = 0; b < hdefault[i]->GetNbinsX(); b++)
		{
			hdefault[i]->SetBinContent(hdefault[i]->GetXaxis()->FindBin(8.5),0);
			hdefault[i]->SetBinError(hdefault[i]->GetXaxis()->FindBin(8.5),0);
			hdefault[i]->SetBinContent(hdefault[i]->GetXaxis()->FindBin(10.5),0);
			hdefault[i]->SetBinError(hdefault[i]->GetXaxis()->FindBin(10.5),0);
		}
		if(rel) hdefault[i]->SetMinimum(0.5);
		if(rel) hdefault[i]->SetMaximum(1.5);
		hdefault[i]->Draw();
		c->Print("effvs"+xvarname+"_"+type+"_"+effnames[i]+".pdf");
		hdefault[i]->Write("h"+effnames[i]+"eff");
	}

	gStyle->SetOptFit(0);



	/** Printing out efficiencies and systematics **/

	vector <TString> sysnames;
	sysnames.push_back("Lifetime");
	sysnames.push_back("Decay Model");
	sysnames.push_back("Polarization");
	if(type=="DD") sysnames.push_back("DD vtx");
	
	/** Print efficiencies */ 

	cout << "\n\n" << xvarname << " bin " << " \t\t\t& ";
	for(unsigned s = 0; s < effnames.size(); s++) cout << effnames[s] << " \t\t\t\t& ";
	cout << "Upper \t\t\t\t& Total  \\\\" << endl;

	TGraphErrors * grtoteff = new TGraphErrors();
	TGraphErrors * grtoteff_lowSel = new TGraphErrors();
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		if(xbins[j]==9.1 || xbins[j-1]==10.1) continue;
		cout << fixed << setprecision(1) << "eff " << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(5) << " \t & ";

		for(unsigned i = 0; i < hdefault.size(); i++)	
			cout << "$" << hdefault[i]->GetBinContent(j) << " \\pm " << hdefault[i]->GetBinError(j) << "$ \t & ";

		cout << "$" << uppereff->GetBinContent(j) << " \\pm " << uppereff->GetBinError(j) << "$ \t & ";
		cout << "$" << toteff->GetBinContent(j) << " \\pm " << toteff->GetBinError(j) << "$ \\\\ " << endl;

		grtoteff->SetPoint(j,toteff->GetBinCenter(j),toteff->GetBinContent(j));
		grtoteff->SetPointError(j,toteff->GetBinWidth(j)/2.,toteff->GetBinError(j));
		if(toteff_lowSel) grtoteff_lowSel->SetPoint(j,toteff_lowSel->GetBinCenter(j),toteff_lowSel->GetBinContent(j));
		if(toteff_lowSel) grtoteff_lowSel->SetPointError(j,toteff_lowSel->GetBinWidth(j)/2.,toteff_lowSel->GetBinError(j));
	}

	grtoteff->Write("toteff");
	if(toteff_lowSel) grtoteff_lowSel->Write("toteff_lowSel");
	if(!doSys) { delete MCfile; delete histFile; return 0; }


	/** Print sys separate in efficiency */
	
	vector < TH1F * > tmp;
	vector < vector < TH1F * > > sys_eff(4,tmp);
	vector < TH1F * > tot_sys_eff;

	cout << endl << endl << endl;
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << "\t& " << sysnames[s];
	cout << " \\\\" << endl;

	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		if(xbins[j]==9.1 || xbins[j-1]==10.1) continue;
		cout << "-----------------------------------------------------------------------------------------" << endl;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3) << endl;
		cout << "-----------------------------------------------------------------------------------------" << endl;
		if(!percent) cout << fixed << setprecision(5);

		for(unsigned i = 0; i < effnames.size(); i++)
		{
			if(j==1)
			{
				sys_eff[0].push_back((TH1F*)toteff->Clone("sys_lf_"+effnames[i]));
				sys_eff[1].push_back((TH1F*)toteff->Clone("sys_decay_"+effnames[i]));
				sys_eff[2].push_back((TH1F*)toteff->Clone("sys_pol_"+effnames[i]));
				sys_eff[3].push_back((TH1F*)toteff->Clone("sys_DD_"+effnames[i]));
				tot_sys_eff.push_back((TH1F*)toteff->Clone("tot_sys_eff"));
				sys_eff[0][i]->Reset();
				sys_eff[1][i]->Reset();
				sys_eff[2][i]->Reset();
				sys_eff[3][i]->Reset();
				tot_sys_eff[i]->Reset();
			}

			double lf_sys = createSys(j,hdefault[i], lfsys_minus[i], lfsys_plus[i]);
			double decay_sys = createSys(j,hdefault[i], decaysys[i], decaysys[i]);
			double DD_sys = 0;
			double pol_sys = createSys(j, hdefault[i], polsys_minus[i], polsys_plus[i]);
			pol_sys = createSys(j, hdefault[i], poljpsi1[i], poljpsi2[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi3[i], poljpsi4[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi5[i], poljpsi6[i], pol_sys);
			pol_sys = createSys(j, hdefault[i], poljpsi7[i], poljpsi8[i], pol_sys);
			double cureff = hdefault[i]->GetBinContent(j);
			double curerr = hdefault[i]->GetBinError(j);
			double tot_eff_sys = TMath::Sqrt( TMath::Power(lf_sys,2) + TMath::Power(pol_sys,2) + TMath::Power(decay_sys,2) );
			
			if(type=="DD")
			{
				DD_sys = createSys(j, hdefault[i], DDsys[i], DDsys[i]);
				tot_eff_sys = TMath::Sqrt( TMath::Power(tot_eff_sys,2) + TMath::Power(DD_sys,2) );
				sys_eff[3][i]->SetBinContent(j,DD_sys);
			}

			cout << effnames[i] << " \t  & ";
			if(percent)
			{
				cout << lf_sys*100 << "\\% \t & " << decay_sys*100 << "\\% \t & " << pol_sys*100 << "\\% \t";
				if(type=="DD") cout << " & " << DD_sys*100 << " \t ";	
			}	
			else
			{
				cout << cureff << " \t & " << curerr << " \t & ";
				cout << lf_sys*cureff << " \t & " << decay_sys*cureff << " \t & " << pol_sys*cureff << " \t";
				if(type=="DD") cout << " & " << DD_sys*cureff << " \t";	
			}	
			cout << " \\\\ " << endl;
			sys_eff[0][i]->SetBinContent(j,lf_sys);
			sys_eff[1][i]->SetBinContent(j,decay_sys);
			sys_eff[2][i]->SetBinContent(j,pol_sys);
			tot_sys_eff[i]->SetBinContent(j,tot_eff_sys);
		}
	}


		/** Print total sys */

	vector< TH1F * > sys;
	TH1F * tot_sys = getErrHist(toteff);

	for(unsigned s = 0; s < sysnames.size(); s++)
	{
		TH1F * tmp_sys = NULL;
		
		for(unsigned i = 0; i < effnames.size(); i++)
			tmp_sys = sqSum(tmp_sys,sys_eff[s][i]); 
		
		sys.push_back( tmp_sys );
		tmp_sys->Write("sys_"+sysnames[s]);
		tot_sys = sqSum(tot_sys,tmp_sys);
	}
	tot_sys->Write("sys_tot");

	cout << endl << endl << endl;	
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << " \t & " << sysnames[s];
	cout << " \t & Total \\\\" << endl;
	
	for(unsigned i = 0; i < effnames.size(); i++)
	{
		TGraphErrors * grtot_eff = new TGraphErrors();
		cout << endl << effnames[i] << endl;

		for(int j = 1; j <= toteff->GetNbinsX(); j++)
		{
			if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
			cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3) << "  \t & ";
		
			double cureff = hdefault[i]->GetBinContent(j);
			if(!percent) cout << fixed << setprecision(5) << cureff << " \t & " << hdefault[i]->GetBinError(j) << "   \t & ";
		
			for(unsigned s = 0; s < sysnames.size(); s++)
				if(percent) cout << sys_eff[s][i]->GetBinContent(j)*100 << "\\% \t & ";
				else cout << sys_eff[s][i]->GetBinContent(j)*cureff << " \t & ";
			
			if(percent) cout << tot_sys_eff[i]->GetBinContent(j)*100 << "\\%";
			else cout << tot_sys_eff[i]->GetBinContent(j)*cureff;
			cout << " \\\\ " << endl;

			grtot_eff->SetPoint(j,tot_sys_eff[i]->GetBinCenter(j),tot_sys_eff[i]->GetBinContent(j));
			grtot_eff->SetPointError(j,tot_sys_eff[i]->GetBinWidth(j)/2.,0.);
		}

		grtot_eff->Write(effnames[i]+"sys");
	}

	cout << endl << endl;	
	if(!percent) cout << "\n\n" << xvarname << " bin\t\t& Value \t\t & Stats";
	else cout << "\n\n" << xvarname << " bin ";
	for(unsigned s = 0; s < sysnames.size(); s++) cout << " \t\t & " << sysnames[s];
	cout << " \\\\" << endl;

	TGraphErrors * grtot = new TGraphErrors();
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(3);
		double cureff = toteff->GetBinContent(j);
		if(!percent) cout << fixed << setprecision(5) << cureff << " \t\t & " << toteff->GetBinError(j);
		
		for(unsigned s = 0; s < sysnames.size(); s++)
			if(percent) cout << "  \t\t\t & " << sys[s]->GetBinContent(j)*100 << "\\% ";
			else cout << " \t\t\t & " << sys[s]->GetBinContent(j)*cureff;
			
		cout << " \\\\ " << endl;

		grtot->SetPoint(j,tot_sys->GetBinCenter(j),tot_sys->GetBinContent(j));
		grtot->SetPointError(j,tot_sys->GetBinWidth(j)/2.,0.);
	}
	
	grtot->Write("totsys");

/*
	cout << "\n\n" << xvarname << " bin\t\t& Value \\\\" << endl;
	for(int j = 1; j <= toteff->GetNbinsX(); j++)
	{
		if((xbins[j]==11 && !rel) || xbins[j]==15) continue;
		cout << fixed << setprecision(1) << xbins[j-1] << "-" << xbins[j] << fixed << setprecision(5) << " \t & ";
		cout << "$" << toteff->GetBinContent(j) << " \\pm " << tot_sys->GetBinContent(j)*toteff->GetBinContent(j) << "$ \\\\ " << endl;
	}
*/
	delete MCfile;
	delete histFile;
	return 0;
}
void 
postfit_use(const char* inputfile, const char* analysis = "SM", const char* dataset = "2011+2012", const char* extra="", const char* extra2="", float min=0.1, float max=-1., bool log=true)
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  // switch for MSSM/SM
  bool MSSM = std::string(analysis) == std::string("MSSM");
  // determine label
  if (std::string(dataset) == std::string("2011"     )){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV"; }
  if (std::string(dataset) == std::string("2012"     )){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.8 fb^{-1} at 8 TeV"; }
  if (std::string(dataset) == std::string("2011+2012")){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV, 19.8 fb^{-1} at 8 TeV"; }
  // determine category tag
  const char* category_extra = "";
  if(std::string(extra2) == std::string("0jet_low"  )){ category_extra = "0 jet, low p_{T}";  }
  if(std::string(extra2) == std::string("0jet_high" )){ category_extra = "0 jet, high p_{T}"; }
  if(std::string(extra2) == std::string("0jet"      )){ category_extra = "0 jet";             }
  if(std::string(extra2) == std::string("1jet_low"  )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(extra2) == std::string("1jet_high" )){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(extra2) == std::string("1jet"      )){ category_extra = "1 jet";             }
  if(std::string(extra2) == std::string("vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(extra2) == std::string("nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(extra2) == std::string("btag"      )){ category_extra = "B-Tag";             }

  TFile* input = new TFile(inputfile);
  TH1F* Fakes  = refill((TH1F*)input->Get("Fakes"   ), "Fakes/QCD"); 
  TH1F* EWK    = refill((TH1F*)input->Get("EWK"     ), "EWK"      ); 
  TH1F* ttbar  = refill((TH1F*)input->Get("ttbar"   ), "ttbar"    ); 
  TH1F* Ztt    = refill((TH1F*)input->Get("Ztt"     ), "Ztt"      ); 
  TH1F* Zmm    = refill((TH1F*)input->Get("Zmm"     ), "Zmm"      ); 
  TH1F* Zee    = refill((TH1F*)input->Get("Zee"     ), "Zee"      ); 
  TH1F* ggH    = refill((TH1F*)input->Get("ggH"     ), "ggH"      ); 
  TH1F* data   = (TH1F*)input->Get("data_obs"); 
  // determine channel for etau Z->ee (EWK) will be shown separated from the rest (EWK1)
  TH1F* EWK1   = 0;
  if(std::string(extra) == std::string("e#tau_{h}")){
    EWK1 = refill((TH1F*)input->Get("EWK1"),  "EWK1");
  }
  TH1F* ggH_hww = 0;
  if(std::string(extra) == std::string("e#mu") and HWWBG){
    ggH_hww= refill((TH1F*)input->Get("ggH_hww" ), "ggH_hww"  ); 
  }
  TH1F* errorBand = (TH1F*)input->Get("errorBand");

  /* 
    mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  if(log) canv->SetLogy(1);
  // reduce the axis range if necessary for linea plots and SM
  if(MSSM && !log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
  if(!MSSM){ data->GetXaxis()->SetRange(0, data->FindBin(345)); }
  data->SetNdivisions(505);
  data->SetMinimum(min);
  if(std::string(extra) == std::string("#mu#mu")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Zmm, log)));
    data->Draw("e");
    if(log){
      Zmm  ->Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      Fakes->Draw("same");
      EWK  ->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
  }
  else if(std::string(extra) == std::string("ee")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Zee, log)));
    data->Draw("e");
    if(log){
      Zee  ->Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      Fakes->Draw("same");
      EWK  ->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
  }
  else if(std::string(extra) == std::string("e#tau_{h}")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
    data->Draw("e");
    if(log){
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      EWK1 ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      EWK1 ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  else if(std::string(extra) == std::string("e#mu") && HWWBG){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(ggH_hww, log)));
    data->Draw("e");
    if(log){
      ggH_hww -> Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      ggH_hww -> Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  else{
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
    data->Draw("e");
    if(log){
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  if(errorBand){
    errorBand->Draw("e2same");
  }
  data->Draw("esame");
  canv->RedrawAxis();




  //CMSPrelim(dataset, extra, 0.17, 0.835);
  CMSPrelim(dataset, "", 0.18, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(extra);
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  if(MSSM){
    float lower_bound = EWK1 ? 0.45 : 0.50;
    TPaveText* massA      = new TPaveText(0.55, lower_bound+0.061, 0.95, lower_bound+0.161, "NDC");
    massA->SetBorderSize(   0 );
    massA->SetFillStyle(    0 );
    massA->SetTextAlign(   12 );
    massA->SetTextSize ( 0.03 );
    massA->SetTextColor(    1 );
    massA->SetTextFont (   62 );
    massA->AddText("m^{h}_{max} (m_{A}=$MA GeV, tan#beta=$TANB)");
    massA->Draw();
  }    
  float lower_bound = EWK1 ? 0.60 : 0.65;
  TLegend* leg = new TLegend(MSSM ? 0.55 : 0.50, lower_bound, 0.93, 0.90);
  SetLegendStyle(leg);
  if(MSSM){
    leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau", "L" );
  }
  else{
    if(ggH){
      if(SIGNAL_SCALE!=1){
	leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
      }
      else{
	leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
      }
    }
  }
  leg->AddEntry(data , "observed"                       , "LP");
  
  if(std::string(extra) == std::string("#mu#mu")){
    leg->AddEntry(Zmm  , "Z#rightarrow#mu#mu"    , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
  }
  else if(std::string(extra) == std::string("ee")){
    leg->AddEntry(Zee  , "Z#rightarrowee"        , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
  }
  else if(std::string(extra) == std::string("e#tau_{h}")){
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(EWK  , "Z#rightarrow ee"              , "F" );
    leg->AddEntry(EWK1 , "electroweak"                  , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  else if(std::string(extra) == std::string("e#mu") && HWWBG){
    leg->AddEntry(ggH_hww  , "H(125 GeV)#rightarrowWW" , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  else{
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  if(errorBand){
    leg->AddEntry(errorBand, "bkg. uncertainty" , "F" );
  }
  leg->Draw();

  /*
    prepare output
  */
  std::string newName = std::string(inputfile).substr(0, std::string(inputfile).find(".root"));
  canv->Print(TString::Format("%s.png", newName.c_str())); 
  canv->Print(TString::Format("%s.pdf", newName.c_str())); 
  canv->Print(TString::Format("%s.eps", newName.c_str())); 

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd(); 
  TH1F* model;
  if(CONSERVATIVE_CHI2){
    if(std::string(extra) == std::string("#mu#mu")){
      model = (TH1F*)Zmm ->Clone("model");
    }
    else if(std::string(extra) == std::string("ee")){
      model = (TH1F*)Zee ->Clone("model");
    }
    else if(std::string(extra) == std::string("e#mu") && HWWBG){
      model = (TH1F*)ggH_hww ->Clone("model");
    }
    else{  
      model = (TH1F*)Ztt ->Clone("model");
    }
  }
  else{
    model = (TH1F*)errorBand->Clone("model");
  }
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONSERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)Ztt->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, errorBand->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/errorBand->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, errorBand->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/errorBand->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, errorBand->GetBinContent(ibin+1)>0 ? errorBand ->GetBinError  (ibin+1)/errorBand->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  if((std::string(extra) == std::string("#mu#mu") || std::string(extra) == std::string("ee")) && !MSSM){
    rat1->GetXaxis()->SetTitle("#bf{D}");
  }
  else{
    rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  }
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f,  P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    prepare output
  */
  newName = std::string(inputfile).substr(0, std::string(inputfile).find(".root")) + "_datamc";
  canv0->Print(TString::Format("%s.png", newName.c_str())); 
  canv0->Print(TString::Format("%s.pdf", newName.c_str())); 
  canv0->Print(TString::Format("%s.eps", newName.c_str())); 
}
Example #14
0
void printBfraction(char *tagger="discr_ssvHighEff", Double_t workingPoint=2, char *taggerName="ssvHighEff", int doCent=2, int do3bin=1) {

  gROOT->ForceStyle(1);

  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);


  gStyle->SetTextFont(42);
  gStyle->SetLabelFont(42,"XYZ");
  gStyle->SetTitleFont(42,"XYZ");

  // hack
  if(doCent)gStyle->SetErrorX(0);
  gStyle->SetLabelSize(0.05,"xy");
  gStyle->SetTitleSize(0.05,"xy");
  gStyle->SetTitleOffset(1.5,"xy");
  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadBottomMargin(0.12);
  gStyle->SetNdivisions(408,"y");


  TFile *fin1, *fin2;
  if(doCent){
    if(doCent==1){
      fin1 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL1_centDep_80_100.root");
      fin2 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL0_centDep_80_100.root");
    }
    if(doCent==2){
      fin1 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL1_centDep_100_120.root");
      fin2 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL0_centDep_100_120.root");
    }
    // broken
    //fin1 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL1_centDep_80_100.root");
    //fin2 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL0_centDep_80_100.root");
  }
  else{
    // try to smear by 2 sigma
    //fin1 = new TFile("output/bFractionMerged_Smear2Sigma_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
    //fin2 = new TFile("output/bFractionMerged_Smear2Sigma_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
    // with reg tracks in reco jets
    //fin1 = new TFile("output/bFractionMerged_regPFJets_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
    //fin2 = new TFile("output/bFractionMerged_regPFJets_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
    if(do3bin){
      fin1 = new TFile("output/bFractionMerged_3bins_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
      fin2 = new TFile("output/bFractionMerged_3bins_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
    }
    else{
      fin1 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
      fin2 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
      // old naming convention
    //fin1 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL1_bin_0_40_eta_0_2.root");
    //fin2 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL0_bin_0_40_eta_0_2.root");

    }
  }

  TH1F *hBFractionMC = (TH1F*) fin1->Get("hBFractionMC");

  TH1F *hBFractionData = (TH1F*) fin1->Get("hBFractionData");
  TH1F *hBFractionDataLTJP = (TH1F*) fin1->Get("hBFractionDataLTJP");
  TH1F *hBFractionJPdirect = (TH1F*) fin1->Get("hBFractionJPdirect");

  TH1F *hBFractionDataFixC = (TH1F*) fin2->Get("hBFractionData");
  TH1F *hBFractionDataLTJPFixC = (TH1F*) fin2->Get("hBFractionDataLTJP");
  TH1F *hBFractionJPdirectFixC = (TH1F*) fin2->Get("hBFractionJPdirect");

  


  /*  --- correction due to Jet Energy Scale (calcul) ---
  correct(hBFractionMC);
  correct(hBFractionData);
  correct(hBFractionDataMoreC);
  correct(hBFractionDataLessC);
  correct(hBFractionDataLTJP);
  correct(hBFractionDataLTJPMoreC);
  correct(hBFractionDataLTJPLessC);
  correct(hBFractionJPdirect);
  correct(hBFractionJPdirectMoreC);
  correct(hBFractionJPdirectLessC);
  //*/

  //*  --- correction due to Jet Energy Scale (by hand) ---
  if(doCent){
    correctByCent(hBFractionMC,doCent);
    correctByCent(hBFractionData,doCent);
    correctByCent(hBFractionDataFixC,doCent);
    correctByCent(hBFractionDataLTJP,doCent);
    correctByCent(hBFractionDataLTJPFixC,doCent);
    correctByCent(hBFractionJPdirect,doCent);
    correctByCent(hBFractionJPdirectFixC,doCent);
  }
  else{
    //*
    correct2(hBFractionMC,do3bin);
    correct2(hBFractionData,do3bin);
    correct2(hBFractionDataFixC,do3bin);
    correct2(hBFractionDataLTJP,do3bin);
    correct2(hBFractionDataLTJPFixC,do3bin);
    correct2(hBFractionJPdirect,do3bin);
    correct2(hBFractionJPdirectFixC,do3bin);
    //*/
  }
  //*/

  //  --- plots with variation of charm ---


  TCanvas *cBFraction1 = new TCanvas("cBFraction1","b-jet fraction",600,600);
  hBFractionMC->SetLineColor(2);
  hBFractionMC->SetLineWidth(2);
  hBFractionMC->SetMarkerColor(2);
  //hBFractionMC->SetMarkerStyle(4);
  if(!doCent)hBFractionMC->SetAxisRange(80,200,"X");
  hBFractionMC->SetAxisRange(0,0.06,"Y");
  hBFractionMC->SetTitleOffset(1,"X");  
  hBFractionMC->GetYaxis()->SetTitle("b-jet fraction");;
  //hBFractionMC->Draw("e1"); 
  
  //hBFractionMC->GetYaxis()->SetNdivisions(505);
  
  TH1F *hBFractionMC_dummy= (TH1F*)hBFractionMC->Clone("hBFractionMC_dummy");
  hBFractionMC_dummy->SetLineWidth(0);
  hBFractionMC_dummy->SetLineColor(0);
  hBFractionMC_dummy->SetMarkerSize(0);
  hBFractionMC_dummy->Draw(); 
  //  hBFractionMC->Draw("hist"); 

  hBFractionData->SetMarkerStyle(8);
  hBFractionData->Draw("e1,same");  
  hBFractionDataLTJP->SetLineColor(kGreen-2); 
  hBFractionDataLTJP->SetMarkerColor(kGreen-2); 
  hBFractionDataLTJP->SetMarkerStyle(8); 
  hBFractionDataLTJP->Draw("e1,same");
  hBFractionJPdirect->SetMarkerStyle(8); 
  hBFractionJPdirect->SetMarkerColor(kBlue);
  hBFractionJPdirect->SetLineColor(kBlue);
  hBFractionJPdirect->Draw("e1,same");

  
  hBFractionDataFixC->SetLineStyle(2);
  //hBFractionDataFixC->Draw("e1same");   
  hBFractionDataLTJPFixC->SetLineColor(kGreen-2);
  hBFractionDataLTJPFixC->SetMarkerColor(kGreen-2);
  hBFractionDataLTJPFixC->SetMarkerStyle(4);
  hBFractionDataLTJPFixC->SetLineStyle(2);
  hBFractionDataLTJPFixC->Draw("e1same");
  hBFractionJPdirectFixC->SetLineStyle(2);
  //hBFractionJPdirectFixC->Draw("e1same");

  
  TLegend *legFrac1 = new TLegend(0.15,0.65,0.87,0.95);

  legFrac1->SetBorderSize(0);
  legFrac1->SetFillStyle(0);
  legFrac1->SetHeader("PbPb, #sqrt{s_{NN}} = 2.76 TeV");
  legFrac1->AddEntry(hBFractionDataLTJP,Form("SSVHE, LT method",taggerName,workingPoint),"pl");
  legFrac1->AddEntry(hBFractionDataLTJPFixC,Form("SSVHE, LT method, Floating Charm Norm.",taggerName,workingPoint),"pl");
  legFrac1->AddEntry(hBFractionData,Form("SSVHE, MC eff.",taggerName,workingPoint),"pl");
  legFrac1->AddEntry(hBFractionJPdirect,"Jet Probability","pl");
  //legFrac1->AddEntry(hBFractionMC,"MC Input (reconstructed)","l");

  legFrac1->Draw();




  //  --- plots of LT method with syst. uncertainty ---

  TCanvas *cBFraction2 = new TCanvas("cBFraction2","b-jet fraction",600,600);

  TH1F *hBFractionMC2 = hBFractionMC->Clone("hBFractionMC2");
  if(!doCent)hBFractionMC2->GetXaxis()->SetRangeUser(80,200);
  hBFractionMC2->SetMarkerSize(0);
  hBFractionMC2->SetMaximum(0.06);
  hBFractionMC2->SetMinimum(0.0);
  hBFractionMC2->Draw("hist");


  TGraphAsymmErrors *gBFractionMC2 = new TGraphAsymmErrors(hBFractionMC);
  if(!doCent){
    setMeanPt(gBFractionMC2,hBFractionMC,0,do3bin);
    gBFractionMC2->GetXaxis()->SetRangeUser(80,200);
  }



  TLatex *prel;
  if(doCent)prel= new TLatex(10,0.0615,"CMS preliminary");
  else prel= new TLatex(85,0.0615,"CMS preliminary");
  prel->Draw();

  TLatex *roots = new TLatex(147,0.0615,"#sqrt{s_{NN}} = 2.76 TeV");
  roots->Draw();

  if(!doCent){
    TLatex *csel = new TLatex(90,0.05,"Centrality 0-100%");
    csel->Draw();
  }
  TLatex *ptlabel;
  if(doCent==1) ptlabel= new TLatex(20,0.005,"80 < Jet p_{T} < 100 GeV/c");
  if(doCent==2) ptlabel= new TLatex(20,0.005,"100 < Jet p_{T} < 120 GeV/c");
  if(doCent)ptlabel->Draw();

  // to be precise we should evaluate mcStatErr for 3 bins seperately
  float mcStatErr[4] = {0.03,0.06,0.07,0.15};

  
  //TGraphAsymmErrors *gSyst = new TGraphAsymmErrors(3);
  TGraphErrors *gSyst;
  if(do3bin) gSyst= new TGraphErrors(3);
  else gSyst= new TGraphErrors(4);
  Double_t errCLratio, errMethod, totalSystErr;

  for(Int_t i=1;i<=hBFractionDataLTJP->GetNbinsX();i++) {
    gSyst->SetPoint(i-1,hBFractionDataLTJP->GetBinCenter(i),hBFractionDataLTJP->GetBinContent(i));
    cout<<" central value "<<hBFractionDataLTJP->GetBinContent(i)<<endl;
    errCLratio = abs(hBFractionDataLTJP->GetBinContent(i)-hBFractionDataLTJPFixC->GetBinContent(i));
    errMethod = max(abs(hBFractionDataLTJP->GetBinContent(i)-hBFractionData->GetBinContent(i)),abs(hBFractionDataLTJP->GetBinContent(i)-hBFractionJPdirect->GetBinContent(i)));
    double errJES = 0.14*hBFractionDataLTJP->GetBinContent(i);
    
    totalSystErr = norm(errCLratio,errMethod,errJES);
    gSyst->SetPointError(i-1,hBFractionDataLTJP->GetBinWidth(i)/2,totalSystErr);
    cout<<" sys error "<<totalSystErr<<endl;
    // add in MC template uncertainties
    float origStatErr = hBFractionDataLTJP->GetBinError(i);
    int statBin=i-1;
    if(doCent==1) statBin=0;
    if(doCent==2) statBin=1;
    float extraStatErr = mcStatErr[statBin]*hBFractionDataLTJP->GetBinContent(i);
    float totalStatErr = sqrt(origStatErr*origStatErr + extraStatErr*extraStatErr);
    hBFractionDataLTJP->SetBinError(i,totalStatErr);
    cout<<" total error "<<sqrt(totalSystErr*totalSystErr+totalStatErr*totalStatErr)<<endl;

  }

  gSyst->SetFillColor(5);
  gSyst->Draw("2");


  gBFractionMC2->Draw("Z,p,same");
  hBFractionMC2->Draw("hist,same");


  TGraphAsymmErrors *gBFractionDataLTJP2 = new TGraphAsymmErrors(hBFractionDataLTJP);
  if(!doCent)setMeanPt(gBFractionDataLTJP2,hBFractionDataLTJP,1,do3bin);
  gBFractionDataLTJP2->SetLineColor(1);
  gBFractionDataLTJP2->SetMarkerColor(1);
  gBFractionDataLTJP2->SetMarkerSize(1.5);
  gBFractionDataLTJP2->Draw("p,e1,same");


  TLegend *legFrac2 = new TLegend(0.2,0.15,0.8,0.34);
  if(doCent){
    legFrac2->SetX1(0.365);
    legFrac2->SetY1(0.657);
    legFrac2->SetX2(0.965);
    legFrac2->SetY2(0.848);
  }

  legFrac2->SetHeader("#int L dt = 150 #mub^{-1}");
  legFrac2->SetBorderSize(0);
  legFrac2->SetFillStyle(0);
  legFrac2->AddEntry(gBFractionDataLTJP2,"PbPb data","p");
  legFrac2->AddEntry(gBFractionMC2,"PYTHIA+HYDJET 1.8","lp");
  legFrac2->AddEntry(gSyst,"Exp. uncertainty","f");
  legFrac2->Draw();

 
  cBFraction2->RedrawAxis();

}
Example #15
0
void DrawMass(int iSEL)
{
  gROOT->ForceStyle();
  TString SET[2] = {"A","B"};
  RooMsgService::instance().setSilentMode(kTRUE);
  for(int i=0;i<2;i++) {
    RooMsgService::instance().setStreamStatus(i,kFALSE);
  }
  TString SELECTION[2] = {"NOM","VBF"};
  TString MASS_RAW[2]  = {"mbb[1]","mbb[2]"};
  TString MASS_REG[2]  = {"mbbReg[1]","mbbReg[2]"};

 // TFile *inf = TFile::Open("Fit_VBFPowheg125_sel"+SELECTION[iSEL]+".root");
  TFile *inf = TFile::Open("/usb/data2/UAData/2015/flatTree_VBFPowheg125.root");
  TTree *tr  = (TTree*)inf->Get("Hbb/events");

  TH1F *hRaw = new TH1F("hRawMass","hRawMass",150,0,300);
  TH1F *hReg = new TH1F("hRegMass","hRegMass",150,0,300);

  RooRealVar x("mbb","mbb",60,170);

  TCanvas *can = new TCanvas("Mbb_sel"+SELECTION[iSEL],"Mbb_sel"+SELECTION[iSEL],900,750);
  
  TCut ct1 = TCut("triggerResult[0]==1||triggerResult[1]==1");
  TCut cs1 = TCut("jetBtag[b1[1]]>0.244 && jetBtag[b2[1]]>0.244 && jetPt[3]>40. && jetPt[2]>50. && jetPt[1]>70. && jetPt[0]>80. && dEtaqq[1]>2.5 && mqq[1]>250 && dPhibb[1]<2.0 && nLeptons==0");
  tr->Draw(MASS_RAW[iSEL]+">>hRawMass",ct1&&cs1);
  tr->Draw(MASS_REG[iSEL]+">>hRegMass",ct1&&cs1);

  hRaw->Sumw2();
  hReg->Sumw2();
  hRaw->Scale(1./(hRaw->Integral()*hRaw->GetBinWidth(1)));
  hReg->Scale(1./(hReg->Integral()*hReg->GetBinWidth(1)));

  RooDataHist *rRaw = new RooDataHist("rRaw","rRaw",x,hRaw);
  RooDataHist *rReg = new RooDataHist("rReg","rReg",x,hReg);

  RooRealVar m1("m1","m1",125,110,140); 
  RooRealVar m2("m2","m2",125,110,140);
  RooRealVar sL1("sL1","sL1",12,3,30); 
  RooRealVar sL2("sL2","sL2",12,3,30);
  RooRealVar sR1("sR1","sR1",12,3,30); 
  RooRealVar sR2("sR2","sR2",12,3,30);
  RooRealVar a1("a1","a1",1,-10,10); 
  RooRealVar a2("a2","a2",1,-10,10); 
  RooRealVar n1("n1","n1",1,0,100); 
  RooRealVar n2("n2","n2",1,0,100);        
  RooRealVar b10("b10","b10",0.5,0.,1.);
  RooRealVar b11("b11","b11",0.5,0.,1.);
  RooRealVar b12("b12","b12",0.5,0.,1.);
  RooRealVar b13("b13","b13",0.5,0.,1.);
  RooRealVar b20("b20","b20",0.5,0.,1.);
  RooRealVar b21("b21","b21",0.5,0.,1.);
  RooRealVar b22("b22","b22",0.5,0.,1.); 
  RooRealVar b23("b23","b23",0.5,0.,1.);     
        
  RooBernstein bkg1("bkg1","bkg1",x,RooArgSet(b10,b11,b12,b13));
  RooBernstein bkg2("bkg2","bkg2",x,RooArgSet(b20,b21,b22,b23));
  RooRealVar fsig1("fsig1","fsig1",0.7,0.,1.); 
  RooRealVar fsig2("fsig2","fsig2",0.7,0.,1.);     
  RooBifurGauss sig1("sig1","sig1",x,m1,sL1,sR1);
  RooBifurGauss sig2("sig2","sig2",x,m2,sL2,sR2);
  //RooCBShape sig1("sig1","sig1",x,m1,s1,a1,n1);
  //RooCBShape sig2("sig2","sig2",x,m2,s2,a2,n2);
        
  RooAddPdf *model1 = new RooAddPdf("model1","model1",RooArgList(sig1,bkg1),fsig1);
  RooAddPdf *model2 = new RooAddPdf("model2","model2",RooArgList(sig2,bkg2),fsig2);

  model1->fitTo(*rRaw,SumW2Error(kFALSE),"q");
  model2->fitTo(*rReg,SumW2Error(kFALSE),"q");

  hRaw->SetLineWidth(2);
  hReg->SetLineWidth(2);
  hRaw->SetLineColor(kBlack);
  hReg->SetLineColor(kRed+1); 
  hReg->SetFillColor(kRed-10);
  hRaw->SetMarkerStyle(21);
  hReg->SetMarkerStyle(20);
  hRaw->SetMarkerSize(1.5);
  hReg->SetMarkerSize(1.5);
  hRaw->SetMarkerColor(kBlack);
  hReg->SetMarkerColor(kRed+1);
  
  RooPlot* frame = x.frame();
  rRaw->plotOn(frame,LineColor(kBlack),LineWidth(1),MarkerColor(kBlack),MarkerStyle(21));
  model1->plotOn(frame,LineColor(kBlack),LineWidth(2));
  rReg->plotOn(frame,LineColor(kRed+1),LineWidth(1),MarkerColor(kRed+1),MarkerStyle(20));
  model2->plotOn(frame,LineColor(kRed+1),LineWidth(2));

  
  TF1 *tmp_func1 = model1->asTF(x,fsig1,x);
  TF1 *tmp_func2 = model2->asTF(x,fsig2,x);
  double y01 = tmp_func1->GetMaximum();
  double x01 = tmp_func1->GetMaximumX();
  double x11 = tmp_func1->GetX(y01/2,60,x01);
  double x21 = tmp_func1->GetX(y01/2,x01,200);
  double FWHM1 = x21-x11;
  
  double y02 = tmp_func2->GetMaximum();
  double x02 = tmp_func2->GetMaximumX();
  double x12 = tmp_func2->GetX(y02/2,60,x02);
  double x22 = tmp_func2->GetX(y02/2,x02,200);
  double FWHM2 = x22-x12;
  
  hReg->GetXaxis()->SetRangeUser(60,170);
  hReg->GetXaxis()->SetTitle("m_{bb} (GeV)");
  hReg->GetYaxis()->SetTitle("1/N #times dN/dm_{bb} (GeV^{-1})");
  hReg->GetYaxis()->SetNdivisions(505);
  hReg->SetMaximum(0.035);
  hReg->Draw("HIST");
  hRaw->Draw("HIST SAME");
  frame->Draw("same");

  TLegend *leg = new TLegend(0.18,0.7,0.43,0.91);
  leg->SetTextFont(42);
  leg->SetTextSize(0.05);
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->SetHeader("m_{H} = 125 GeV (set "+SET[iSEL]+")");
  leg->AddEntry(hReg,"Regressed","LP");
  leg->AddEntry(hRaw,"Raw","LP");
  leg->Draw();

  TPaveText *pave1 = new TPaveText(0.18,0.56,0.43,0.7,"NDC");
  pave1->AddText(TString::Format("PEAK = %1.1f GeV",x02));
  pave1->AddText(TString::Format("FWHM = %1.1f GeV",FWHM2));
  pave1->SetTextFont(42);
  pave1->SetTextSize(0.04);
  pave1->SetTextColor(kRed+1);
  pave1->SetBorderSize(0);
  pave1->SetFillColor(0);
  pave1->Draw();

  TPaveText *pave2 = new TPaveText(0.18,0.42,0.43,0.56,"NDC");
  pave2->AddText(TString::Format("PEAK = %1.1f GeV",x01));
  pave2->AddText(TString::Format("FWHM = %1.1f GeV",FWHM1));
  pave2->SetTextFont(42);
  pave2->SetTextSize(0.04);
  pave2->SetTextColor(kBlack);
  pave2->SetBorderSize(0);
  pave2->SetFillColor(0);
  pave2->Draw();


  can->SaveAs("regressionKost.pdf");
//  CMS_lumi(can,0,0); 
}
Example #16
0
void aliceReferror()
{
  cout<<endl;
  cout<<endl;
  gStyle->SetOptFit(0);

  //Fill ALice(7TeV,|y|<0.5) and CMS(2.76TeV,|y|<1) FONLL values
  cout<<"---- Fill ALice(7TeV,|y|<0.5) and CMS(2.76TeV,|y|<1) FONLL values"<<endl;

  TString infnameAlice="fonllInput/fo_Dzero_pp_7_y0p5_curve.dat";
  TString infnameAnly="fonllInput/fo_Dzero_pp_2p76_y1_curve.dat";
  ifstream getdataAlice(infnameAlice.Data());
  ifstream getdataAnly(infnameAnly.Data());

  TH1F* hptAlice = new TH1F("hptAlice","",fo_BIN_NUM,HMIN,HMAX);          TH1F* hptAnly = new TH1F("hptAnly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hminallAlice = new TH1F("hminallAlice","",fo_BIN_NUM,HMIN,HMAX);  //TH1F* hminallAnly = new TH1F("hminallAnly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hmaxallAlice = new TH1F("hmaxallAlice","",fo_BIN_NUM,HMIN,HMAX);  //TH1F* hmaxallAnly = new TH1F("hmaxllAnly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt11Alice = new TH1F("hpt11Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt11Anly = new TH1F("hpt11Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt55Alice = new TH1F("hpt55Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt55Anly = new TH1F("hpt55Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt22Alice = new TH1F("hpt22Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt22Anly = new TH1F("hpt22Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt21Alice = new TH1F("hpt21Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt21Anly = new TH1F("hpt21Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt12Alice = new TH1F("hpt12Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt12Anly = new TH1F("hpt12Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt15Alice = new TH1F("hpt15Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt15Anly = new TH1F("hpt15Anly","",fo_BIN_NUM,HMIN,HMAX);
  TH1F* hpt51Alice = new TH1F("hpt51Alice","",fo_BIN_NUM,HMIN,HMAX);      TH1F* hpt51Anly = new TH1F("hpt51Anly","",fo_BIN_NUM,HMIN,HMAX);

  Double_t a11_Alice[fo_BIN_NUM],a55_Alice[fo_BIN_NUM],a22_Alice[fo_BIN_NUM],a21_Alice[fo_BIN_NUM],a12_Alice[fo_BIN_NUM],a15_Alice[fo_BIN_NUM],a51_Alice[fo_BIN_NUM];
  Double_t a11_Anly[fo_BIN_NUM],a55_Anly[fo_BIN_NUM],a22_Anly[fo_BIN_NUM],a21_Anly[fo_BIN_NUM],a12_Anly[fo_BIN_NUM],a15_Anly[fo_BIN_NUM],a51_Anly[fo_BIN_NUM];
  Double_t min_all_Alice[fo_BIN_NUM],max_all_Alice[fo_BIN_NUM],min_sc_Alice[fo_BIN_NUM],max_sc_Alice[fo_BIN_NUM],min_mass_Alice[fo_BIN_NUM],max_mass_Alice[fo_BIN_NUM],min_pdf_Alice[fo_BIN_NUM],max_pdf_Alice[fo_BIN_NUM];
  Double_t min_all_Anly[fo_BIN_NUM],max_all_Anly[fo_BIN_NUM],min_sc_Anly[fo_BIN_NUM],max_sc_Anly[fo_BIN_NUM],min_mass_Anly[fo_BIN_NUM],max_mass_Anly[fo_BIN_NUM],min_pdf_Anly[fo_BIN_NUM],max_pdf_Anly[fo_BIN_NUM];
  Int_t i,j;
  Double_t tem=0.;
  Double_t pdfrac=0.557*1.e-6;
  for(i=0;i<fo_BIN_NUM;i++)
    {
      getdataAlice>>tem;
      getdataAlice>>a11_Alice[i];
      getdataAlice>>min_all_Alice[i];
      getdataAlice>>max_all_Alice[i];
      getdataAlice>>min_sc_Alice[i];
      getdataAlice>>max_sc_Alice[i];
      getdataAlice>>min_mass_Alice[i];
      getdataAlice>>max_mass_Alice[i];
      getdataAlice>>min_pdf_Alice[i];
      getdataAlice>>max_pdf_Alice[i];
      getdataAlice>>a55_Alice[i];
      getdataAlice>>a22_Alice[i];
      getdataAlice>>a21_Alice[i];
      getdataAlice>>a12_Alice[i];
      getdataAlice>>a15_Alice[i];
      getdataAlice>>a51_Alice[i];
    }
  for(i=0;i<fo_BIN_NUM;i++)
    {
      getdataAnly>>tem;
      getdataAnly>>a11_Anly[i];
      getdataAnly>>min_all_Anly[i];
      getdataAnly>>max_all_Anly[i];
      getdataAnly>>min_sc_Anly[i];
      getdataAnly>>max_sc_Anly[i];
      getdataAnly>>min_mass_Anly[i];
      getdataAnly>>max_mass_Anly[i];
      getdataAnly>>min_pdf_Anly[i];
      getdataAnly>>max_pdf_Anly[i];
      getdataAnly>>a55_Anly[i];
      getdataAnly>>a22_Anly[i];
      getdataAnly>>a21_Anly[i];
      getdataAnly>>a12_Anly[i];
      getdataAnly>>a15_Anly[i];
      getdataAnly>>a51_Anly[i];
    }
  for(i=0;i<fo_BIN_NUM;i++)
    {
      hptAlice->SetBinContent(i+1,a11_Alice[i]*pdfrac);
      hminallAlice->SetBinContent(i+1,min_all_Alice[i]*pdfrac);
      hmaxallAlice->SetBinContent(i+1,max_all_Alice[i]*pdfrac);
      hpt11Alice->SetBinContent(i+1,a11_Alice[i]*pdfrac);
      hpt55Alice->SetBinContent(i+1,a55_Alice[i]*pdfrac);
      hpt22Alice->SetBinContent(i+1,a22_Alice[i]*pdfrac);
      hpt21Alice->SetBinContent(i+1,a21_Alice[i]*pdfrac);
      hpt12Alice->SetBinContent(i+1,a12_Alice[i]*pdfrac);
      hpt15Alice->SetBinContent(i+1,a15_Alice[i]*pdfrac);
      hpt51Alice->SetBinContent(i+1,a51_Alice[i]*pdfrac);
      hptAnly->SetBinContent(i+1,a11_Anly[i]*pdfrac);
      hpt11Anly->SetBinContent(i+1,a11_Anly[i]*pdfrac);
      hpt55Anly->SetBinContent(i+1,a55_Anly[i]*pdfrac);
      hpt22Anly->SetBinContent(i+1,a22_Anly[i]*pdfrac);
      hpt21Anly->SetBinContent(i+1,a21_Anly[i]*pdfrac);
      hpt12Anly->SetBinContent(i+1,a12_Anly[i]*pdfrac);
      hpt15Anly->SetBinContent(i+1,a15_Anly[i]*pdfrac);
      hpt51Anly->SetBinContent(i+1,a51_Anly[i]*pdfrac);
    }

  //Calculate data weighted ptbin centers
  cout<<"---- Calculate data weighted ptbin centers"<<endl;
  Double_t da_bincenter[da_BIN_NUM];
  Double_t summul=0,sum=0;
  for(i=0;i<da_BIN_NUM;i++)
    {
      summul=0;
      sum=0;
      for(j=da_ptbin[i]*4;j<da_ptbin[i+1]*4;j++)
	{
	  summul+=hptAlice->GetBinContent(j+1)*hptAlice->GetBinCenter(j+1);
	  sum+=hptAlice->GetBinContent(j+1);
	}
      da_bincenter[i] = summul/sum;
    }
  
  //Back up
  TH1F* hptAliceRef=(TH1F*)hptAlice->Clone();
  hptAliceRef->SetName("hptAliceRef");
  TH1F* hptAnlyRef=(TH1F*)hptAnly->Clone();
  hptAnlyRef->SetName("hptAnlyRef");

  Double_t apt[da_BIN_NUM],aptl[da_BIN_NUM],aptlsyst[da_BIN_NUM],aptlscaling[da_BIN_NUM];
  TH1F* hptAlice_rebinalice = (TH1F*)hptAliceRef->Rebin(da_BIN_NUM,"hptAlice_rebinalice",da_ptbin);
  for(i=0;i<da_BIN_NUM;i++)
    {
      apt[i] = hptAlice_rebinalice->GetBinCenter(i+1);
      aptl[i] = hptAlice_rebinalice->GetBinWidth(i+1)/2.;
      aptlsyst[i] = 1./6.;
      aptlscaling[i] = 1./4.;
    }
  
  //Test ALICE results
  if(testAliceData)
    {
      cout<<"---- Test Alice data points"<<endl;
      Double_t asigma[da_BIN_NUM],aerrorl[da_BIN_NUM],aerrorh[da_BIN_NUM],aminall[da_BIN_NUM],amaxall[da_BIN_NUM];
      TH1F* hminallAlice_rebinalice = (TH1F*)hminallAlice->Rebin(da_BIN_NUM,"hminallAlice_rebinalice",da_ptbin);
      TH1F* hmaxallAlice_rebinalice = (TH1F*)hmaxallAlice->Rebin(da_BIN_NUM,"hmaxallAlice_rebinalice",da_ptbin);
      for(i=0;i<da_BIN_NUM;i++)
	{
	  hptAlice_rebinalice->SetBinContent(i+1,hptAlice_rebinalice->GetBinContent(i+1)/(hptAlice_rebinalice->GetBinWidth(i+1)*4));
	  asigma[i]=hptAlice_rebinalice->GetBinContent(i+1);
	  hminallAlice_rebinalice->SetBinContent(i+1,hminallAlice_rebinalice->GetBinContent(i+1)/(hminallAlice_rebinalice->GetBinWidth(i+1)*4));
	  aminall[i]=hminallAlice_rebinalice->GetBinContent(i+1);
	  hmaxallAlice_rebinalice->SetBinContent(i+1,hmaxallAlice_rebinalice->GetBinContent(i+1)/(hmaxallAlice_rebinalice->GetBinWidth(i+1)*4));
	  amaxall[i]=hmaxallAlice_rebinalice->GetBinContent(i+1);
	  aerrorl[i] = asigma[i]-aminall[i];
	  aerrorh[i] = amaxall[i]-asigma[i];
	}
      TCanvas* cReproduceAlice = new TCanvas("cReproduceAlice","",600,600);
      cReproduceAlice->SetLogy();
      TH2F* hempty_cReproduceAlice = new TH2F("hempty_cReproduceAlice","",10,0,25.,10.,0.006,1.e+3);
      hempty_cReproduceAlice->SetStats(0);
      hempty_cReproduceAlice->GetXaxis()->SetTitle("p_{t} (GeV/c)");
      hempty_cReproduceAlice->GetYaxis()->SetTitle("d#sigma(D^{0})/dp_{T}(pb GeV-1c)");
      hempty_cReproduceAlice->GetXaxis()->SetTitleOffset(1.);
      hempty_cReproduceAlice->GetYaxis()->SetTitleOffset(.9);
      hempty_cReproduceAlice->GetXaxis()->SetTitleSize(0.045);
      hempty_cReproduceAlice->GetYaxis()->SetTitleSize(0.045);
      hempty_cReproduceAlice->GetXaxis()->SetTitleFont(42);
      hempty_cReproduceAlice->GetYaxis()->SetTitleFont(42);
      hempty_cReproduceAlice->GetXaxis()->SetLabelFont(42);
      hempty_cReproduceAlice->GetYaxis()->SetLabelFont(42);
      hempty_cReproduceAlice->GetXaxis()->SetLabelSize(0.04);
      hempty_cReproduceAlice->GetYaxis()->SetLabelSize(0.04);  
      hempty_cReproduceAlice->Draw();
      TGraphAsymmErrors* gAliceFONLL = new TGraphAsymmErrors(da_BIN_NUM, apt, asigma, aptl, aptl, aerrorl, aerrorh);
      gAliceFONLL->SetFillColor(kRed);
      gAliceFONLL->SetFillStyle(3002);
      gAliceFONLL->SetLineWidth(2.);
      gAliceFONLL->SetLineColor(kRed);
      gAliceFONLL->Draw("5same");
      TGraphAsymmErrors* gAliceSyst = new TGraphAsymmErrors(da_BIN_NUM, apt, da_cs, aptlsyst, aptlsyst, da_syst_dw, da_syst_up);
      gAliceSyst->SetFillColor(0);
      gAliceSyst->SetFillStyle(0);
      gAliceSyst->SetLineWidth(2.);
      gAliceSyst->SetLineColor(kBlack);
      gAliceSyst->Draw("5same");
      TGraphAsymmErrors* gAliceStat = new TGraphAsymmErrors(da_BIN_NUM, apt, da_cs, aptl, aptl, da_stat, da_stat);
      gAliceStat->SetMarkerStyle(21);
      gAliceStat->SetMarkerColor(kBlack);
      gAliceStat->SetLineWidth(2);
      gAliceStat->SetLineColor(kBlack);
      gAliceStat->Draw("psame");
      cReproduceAlice->SaveAs(Form("plots/%s/reproduceAlice.pdf",rapi.Data()));
    }

  cout<<"---- Rebin into data ptbins"<<endl;
  TH1F* hpt11Alice_rebin = (TH1F*)hpt11Alice->Rebin(da_BIN_NUM,"hpt11Alice_rebin",da_ptbin);
  TH1F* hpt55Alice_rebin = (TH1F*)hpt55Alice->Rebin(da_BIN_NUM,"hpt55Alice_rebin",da_ptbin);
  TH1F* hpt22Alice_rebin = (TH1F*)hpt22Alice->Rebin(da_BIN_NUM,"hpt22Alice_rebin",da_ptbin);
  TH1F* hpt21Alice_rebin = (TH1F*)hpt21Alice->Rebin(da_BIN_NUM,"hpt21Alice_rebin",da_ptbin);
  TH1F* hpt12Alice_rebin = (TH1F*)hpt12Alice->Rebin(da_BIN_NUM,"hpt12Alice_rebin",da_ptbin);
  TH1F* hpt15Alice_rebin = (TH1F*)hpt15Alice->Rebin(da_BIN_NUM,"hpt15Alice_rebin",da_ptbin);
  TH1F* hpt51Alice_rebin = (TH1F*)hpt51Alice->Rebin(da_BIN_NUM,"hpt51Alice_rebin",da_ptbin);
  TH1F* hpt11Anly_rebin = (TH1F*)hpt11Anly->Rebin(da_BIN_NUM,"hpt11Anly_rebin",da_ptbin);
  TH1F* hpt55Anly_rebin = (TH1F*)hpt55Anly->Rebin(da_BIN_NUM,"hpt55Anly_rebin",da_ptbin);
  TH1F* hpt22Anly_rebin = (TH1F*)hpt22Anly->Rebin(da_BIN_NUM,"hpt22Anly_rebin",da_ptbin);
  TH1F* hpt21Anly_rebin = (TH1F*)hpt21Anly->Rebin(da_BIN_NUM,"hpt21Anly_rebin",da_ptbin);
  TH1F* hpt12Anly_rebin = (TH1F*)hpt12Anly->Rebin(da_BIN_NUM,"hpt12Anly_rebin",da_ptbin);
  TH1F* hpt15Anly_rebin = (TH1F*)hpt15Anly->Rebin(da_BIN_NUM,"hpt15Anly_rebin",da_ptbin);
  TH1F* hpt51Anly_rebin = (TH1F*)hpt51Anly->Rebin(da_BIN_NUM,"hpt51Anly_rebin",da_ptbin);

  //Calculate ratios and errors with different sets of scaling
  cout<<"---- Calculate ratios and errors with different sets of scaling"<<endl;
  TH1F* hratio11_rebin = (TH1F*)hpt11Anly_rebin->Clone();  hratio11_rebin->SetName("hratio11_rebin");  hratio11_rebin->Divide(hpt11Alice_rebin);  Double_t aratio11[da_BIN_NUM];
  TH1F* hratio55_rebin = (TH1F*)hpt55Anly_rebin->Clone();  hratio55_rebin->SetName("hratio55_rebin");  hratio55_rebin->Divide(hpt55Alice_rebin);  Double_t aratio55[da_BIN_NUM];
  TH1F* hratio22_rebin = (TH1F*)hpt22Anly_rebin->Clone();  hratio22_rebin->SetName("hratio22_rebin");  hratio22_rebin->Divide(hpt22Alice_rebin);  Double_t aratio22[da_BIN_NUM];
  TH1F* hratio21_rebin = (TH1F*)hpt21Anly_rebin->Clone();  hratio21_rebin->SetName("hratio21_rebin");  hratio21_rebin->Divide(hpt21Alice_rebin);  Double_t aratio21[da_BIN_NUM];
  TH1F* hratio12_rebin = (TH1F*)hpt12Anly_rebin->Clone();  hratio12_rebin->SetName("hratio12_rebin");  hratio12_rebin->Divide(hpt12Alice_rebin);  Double_t aratio12[da_BIN_NUM];
  TH1F* hratio15_rebin = (TH1F*)hpt15Anly_rebin->Clone();  hratio15_rebin->SetName("hratio15_rebin");  hratio15_rebin->Divide(hpt15Alice_rebin);  Double_t aratio15[da_BIN_NUM];
  TH1F* hratio51_rebin = (TH1F*)hpt51Anly_rebin->Clone();  hratio51_rebin->SetName("hratio51_rebin");  hratio51_rebin->Divide(hpt51Alice_rebin);  Double_t aratio51[da_BIN_NUM];
  Double_t aratioErrup[da_BIN_NUM], aratioErrdw[da_BIN_NUM];

  for(i=0;i<da_BIN_NUM;i++)
    {
      Double_t sortup=-1,sortdw=10000;
      aratio11[i] = hratio11_rebin->GetBinContent(i+1);  if(aratio11[i]>sortup){sortup=aratio11[i];}  if(aratio11[i]<sortdw){sortdw=aratio11[i];}
      aratio55[i] = hratio55_rebin->GetBinContent(i+1);  if(aratio55[i]>sortup){sortup=aratio55[i];}  if(aratio55[i]<sortdw){sortdw=aratio55[i];}
      aratio22[i] = hratio22_rebin->GetBinContent(i+1);  if(aratio22[i]>sortup){sortup=aratio22[i];}  if(aratio22[i]<sortdw){sortdw=aratio22[i];}
      aratio21[i] = hratio21_rebin->GetBinContent(i+1);  if(aratio21[i]>sortup){sortup=aratio21[i];}  if(aratio21[i]<sortdw){sortdw=aratio21[i];}
      aratio12[i] = hratio12_rebin->GetBinContent(i+1);  if(aratio12[i]>sortup){sortup=aratio12[i];}  if(aratio12[i]<sortdw){sortdw=aratio12[i];}
      aratio15[i] = hratio15_rebin->GetBinContent(i+1);  if(aratio15[i]>sortup){sortup=aratio15[i];}  if(aratio15[i]<sortdw){sortdw=aratio15[i];}
      aratio51[i] = hratio51_rebin->GetBinContent(i+1);  if(aratio51[i]>sortup){sortup=aratio51[i];}  if(aratio51[i]<sortdw){sortdw=aratio51[i];}
      aratioErrup[i] = sortup-aratio11[i];
      aratioErrdw[i] = aratio11[i]-sortdw;
    }
  TGraph* gratio11 = new TGraph(da_BIN_NUM,da_ptctr,aratio11);
  TGraph* gratio55 = new TGraph(da_BIN_NUM,da_ptctr,aratio55);
  TGraph* gratio22 = new TGraph(da_BIN_NUM,da_ptctr,aratio22);
  TGraph* gratio21 = new TGraph(da_BIN_NUM,da_ptctr,aratio21);
  TGraph* gratio12 = new TGraph(da_BIN_NUM,da_ptctr,aratio12);
  TGraph* gratio15 = new TGraph(da_BIN_NUM,da_ptctr,aratio15);
  TGraph* gratio51 = new TGraph(da_BIN_NUM,da_ptctr,aratio51);

  cout<<"  -- Plot FONLL ratio center values"<<endl;
  TCanvas* ccenterRatio = new TCanvas("ccenterRatio","",700,500);
  TH2F* hempty_ccenterRatio = new TH2F("hempty_ccenterRatio","",10,0,17.,10.,0.2,2.2);
  hempty_ccenterRatio->SetStats(0);
  hempty_ccenterRatio->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_ccenterRatio->GetYaxis()->SetTitle("#sigma(2.76TeV,|y|<1)/#sigma(7TeV.|y|<0.5)");
  hempty_ccenterRatio->GetXaxis()->SetTitleOffset(1.);
  hempty_ccenterRatio->GetYaxis()->SetTitleOffset(.9);
  hempty_ccenterRatio->GetXaxis()->SetTitleSize(0.045);
  hempty_ccenterRatio->GetYaxis()->SetTitleSize(0.045);
  hempty_ccenterRatio->GetXaxis()->SetTitleFont(42);
  hempty_ccenterRatio->GetYaxis()->SetTitleFont(42);
  hempty_ccenterRatio->GetXaxis()->SetLabelFont(42);
  hempty_ccenterRatio->GetYaxis()->SetLabelFont(42);
  hempty_ccenterRatio->GetXaxis()->SetLabelSize(0.04);
  hempty_ccenterRatio->GetYaxis()->SetLabelSize(0.04);
  hempty_ccenterRatio->Draw();
  gratio11->SetLineColor(1);   gratio11->SetLineWidth(2);  gratio11->Draw("lsame");
  ccenterRatio->SaveAs(Form("plots/%s/cratioCenter.pdf",rapi.Data()));

  cout<<"  -- Plot FONLL ratios with different sets of scaling"<<endl;  
  TCanvas* ccompareRatio = new TCanvas("ccompareRatio","",700,500);
  TH2F* hempty_ccompareRatio = new TH2F("hempty_ccompareRatio","",10,0,17.,10.,0.2,2.2);
  hempty_ccompareRatio->SetStats(0);
  hempty_ccompareRatio->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_ccompareRatio->GetYaxis()->SetTitle("#sigma(2.76TeV,|y|<1)/#sigma(7TeV.|y|<0.5)");
  hempty_ccompareRatio->GetXaxis()->SetTitleOffset(1.);
  hempty_ccompareRatio->GetYaxis()->SetTitleOffset(.9);
  hempty_ccompareRatio->GetXaxis()->SetTitleSize(0.045);
  hempty_ccompareRatio->GetYaxis()->SetTitleSize(0.045);
  hempty_ccompareRatio->GetXaxis()->SetTitleFont(42);
  hempty_ccompareRatio->GetYaxis()->SetTitleFont(42);
  hempty_ccompareRatio->GetXaxis()->SetLabelFont(42);
  hempty_ccompareRatio->GetYaxis()->SetLabelFont(42);
  hempty_ccompareRatio->GetXaxis()->SetLabelSize(0.04);
  hempty_ccompareRatio->GetYaxis()->SetLabelSize(0.04);
  hempty_ccompareRatio->Draw();
  TGraphAsymmErrors* gratioGlobal = new TGraphAsymmErrors(da_BIN_NUM, apt, aratio11, aptl, aptl, aratioErrdw, aratioErrup);
  gratioGlobal->SetFillStyle(1001);
  gratioGlobal->SetFillColor(kYellow-9);
  gratioGlobal->Draw("2same");
  gratio11->SetLineColor(1);   gratio11->SetLineWidth(2);  gratio11->Draw("lsame");
  gratio55->SetLineColor(3);   gratio55->SetLineWidth(2);  gratio55->Draw("lsame");
  gratio22->SetLineColor(9);   gratio22->SetLineWidth(2);  gratio22->Draw("lsame");
  gratio21->SetLineColor(47);  gratio21->SetLineWidth(2);  gratio21->Draw("lsame");
  gratio12->SetLineColor(6);   gratio12->SetLineWidth(2);  gratio12->Draw("lsame");
  gratio15->SetLineColor(7);   gratio15->SetLineWidth(2);  gratio15->Draw("lsame");
  gratio51->SetLineColor(43);  gratio51->SetLineWidth(2);  gratio51->Draw("lsame");
  TLegend* legratioScaling = new TLegend(0.60,0.50,0.80,0.89);
  legratioScaling->SetFillColor(0);
  legratioScaling->SetBorderSize(0);
  legratioScaling->AddEntry((TObject*)0,"#mu_{F}/#mu_{0}  #mu_{R}/#mu_{0}","");
  legratioScaling->AddEntry(gratio11,"  1       1","l");
  legratioScaling->AddEntry(gratio55," 0.5     0.5","l");
  legratioScaling->AddEntry(gratio22,"  2       2","l");
  legratioScaling->AddEntry(gratio21,"  2       1","l");
  legratioScaling->AddEntry(gratio12,"  1       2","l");
  legratioScaling->AddEntry(gratio15,"  1      0.5","l");
  legratioScaling->AddEntry(gratio51," 0.5      1","l");
  legratioScaling->Draw("same");
  ccompareRatio->SaveAs(Form("plots/%s/cratioGlobal.pdf",rapi.Data()));

  //Plot global relative FONLL ratio errors
  cout<<"  -- Plot global relative FONLL ratio errors"<<endl;
  Double_t aratioRela[da_BIN_NUM],aratioErrdwRela[da_BIN_NUM],aratioErrupRela[da_BIN_NUM];
  for(i=0;i<da_BIN_NUM;i++)
    {
      aratioRela[i] = 0;
      aratioErrdwRela[i] = aratioErrdw[i]/aratio11[i];
      aratioErrupRela[i] = aratioErrup[i]/aratio11[i];
    }
  TCanvas* cratioRela = new TCanvas("cratioRela","",700,500);
  cratioRela->SetGrid();
  TH2F* hempty_cratioRela = new TH2F("hempty_cratioRela","",10,1,16.,10.,-1,1);
  hempty_cratioRela->SetStats(0);
  hempty_cratioRela->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_cratioRela->GetYaxis()->SetTitle("#sigma(2.76TeV,|y|<1.)/#sigma(7TeV,|y|<0.5) Relative unc.");
  hempty_cratioRela->GetXaxis()->SetTitleOffset(1.);
  hempty_cratioRela->GetYaxis()->SetTitleOffset(.9);
  hempty_cratioRela->GetXaxis()->SetTitleSize(0.045);
  hempty_cratioRela->GetYaxis()->SetTitleSize(0.045);
  hempty_cratioRela->GetXaxis()->SetTitleFont(42);
  hempty_cratioRela->GetYaxis()->SetTitleFont(42);
  hempty_cratioRela->GetXaxis()->SetLabelFont(42);
  hempty_cratioRela->GetYaxis()->SetLabelFont(42);
  hempty_cratioRela->GetXaxis()->SetLabelSize(0.04);
  hempty_cratioRela->GetYaxis()->SetLabelSize(0.04);
  hempty_cratioRela->Draw();
  TGraphAsymmErrors* gratioRela = new TGraphAsymmErrors(da_BIN_NUM, apt, aratioRela, aptl, aptl, aratioErrdwRela, aratioErrupRela);
  gratioRela->SetFillStyle(3001);
  gratioRela->SetFillColor(8);
  gratioRela->Draw("2same");
  cratioRela->SaveAs(Form("plots/%s/cratioRela.pdf",rapi.Data()));

  //Scale ALICE data points and propagate uncertainties
  cout<<"---- Scale ALice data center values and propagate uncertainties"<<endl;
  Double_t acrosssec[da_BIN_NUM],aminErr[da_BIN_NUM],amaxErr[da_BIN_NUM],aminErrrel[da_BIN_NUM],amaxErrrel[da_BIN_NUM],aminErrsyst[da_BIN_NUM],amaxErrsyst[da_BIN_NUM],aminErrstat[da_BIN_NUM],amaxErrstat[da_BIN_NUM],aminErrscaling[da_BIN_NUM],amaxErrscaling[da_BIN_NUM];
  for(i=0;i<da_BIN_NUM;i++)
    {
      acrosssec[i] = da_cs[i]*aratio11[i];
      aminErr[i] = acrosssec[i]*TMath::Sqrt((da_syst_dw[i]*da_syst_dw[i]+da_stat[i]*da_stat[i])/(da_cs[i]*da_cs[i])
					  + aratioErrdwRela[i]*aratioErrdwRela[i]);
      aminErrrel[i] = aminErr[i]/acrosssec[i];
      amaxErr[i] = acrosssec[i]*TMath::Sqrt((da_syst_up[i]*da_syst_up[i]+da_stat[i]*da_stat[i])/(da_cs[i]*da_cs[i])
					  + aratioErrupRela[i]*aratioErrupRela[i]);
      amaxErrrel[i] = amaxErr[i]/acrosssec[i];
      aminErrsyst[i] = acrosssec[i]*(da_syst_dw[i]/da_cs[i]);
      amaxErrsyst[i] = acrosssec[i]*(da_syst_up[i]/da_cs[i]);
      aminErrstat[i] = acrosssec[i]*(da_stat[i]/da_cs[i]);
      amaxErrstat[i] = acrosssec[i]*(da_stat[i]/da_cs[i]);
      aminErrscaling[i] = acrosssec[i]*aratioErrdwRela[i];
      amaxErrscaling[i] = acrosssec[i]*aratioErrupRela[i];
    }
  cout<<"---- Plot scaled data with different components of uncertainties"<<endl;
  TCanvas* cErrors = new TCanvas("cErrors","",500,500);
  cErrors->SetLogy();
  TH2F* hempty_cErrors = new TH2F("hempty_cErrors","",10,0,17.,10.,1.e-2,1.e+3);
  hempty_cErrors->SetStats(0);
  hempty_cErrors->GetXaxis()->SetTitle("p_{t} (GeV/c)");
  hempty_cErrors->GetYaxis()->SetTitle("d#sigma(D^{0})/dp_{T}(#mub GeV-1c)");
  hempty_cErrors->GetXaxis()->SetTitleOffset(1.);
  hempty_cErrors->GetYaxis()->SetTitleOffset(.9);
  hempty_cErrors->GetXaxis()->SetTitleSize(0.045);
  hempty_cErrors->GetYaxis()->SetTitleSize(0.045);
  hempty_cErrors->GetXaxis()->SetTitleFont(42);
  hempty_cErrors->GetYaxis()->SetTitleFont(42);
  hempty_cErrors->GetXaxis()->SetLabelFont(42);
  hempty_cErrors->GetYaxis()->SetLabelFont(42);
  hempty_cErrors->GetXaxis()->SetLabelSize(0.04);
  hempty_cErrors->GetYaxis()->SetLabelSize(0.04);
  hempty_cErrors->Draw();
  for(i=0;i<da_BIN_NUM;i++)
   {
     aptlscaling[i] = 1./3.;
   }
  TGraphAsymmErrors* gErrScaling = new TGraphAsymmErrors(da_BIN_NUM, da_ptctr, acrosssec, aptlscaling, aptlscaling, aminErrscaling, amaxErrscaling); gErrScaling->SetName("gErrScaling");
  gErrScaling->SetLineWidth(0);
  gErrScaling->SetFillStyle(1001);
  gErrScaling->SetFillColor(kMagenta-7);
  gErrScaling->Draw("2same");
  TGraphAsymmErrors* gErrTotal = new TGraphAsymmErrors(da_BIN_NUM, da_ptctr, acrosssec, aptl, aptl, aminErr, amaxErr);
  gErrTotal->SetFillStyle(0);
  gErrTotal->SetLineColor(kMagenta+2);
  gErrTotal->SetLineWidth(2);
  gErrTotal->Draw("5same");
  TGraphAsymmErrors* gErrSyst = new TGraphAsymmErrors(da_BIN_NUM, da_ptctr, acrosssec, aptlsyst, aptlsyst, aminErrsyst, amaxErrsyst);
  gErrSyst->SetFillStyle(0);
  gErrSyst->SetLineColor(kAzure-2);
  gErrSyst->SetLineWidth(2.);
  gErrSyst->Draw("5same");
  TGraphAsymmErrors* gErrStat = new TGraphAsymmErrors(da_BIN_NUM, da_ptctr, acrosssec, aptl, aptl, aminErrstat, amaxErrstat);
  gErrStat->SetMarkerSize(0);
  gErrStat->SetLineColor(kAzure-2);
  gErrStat->SetLineWidth(2.);
  gErrStat->Draw("psame");
  TGraph* gErr = new TGraph(da_BIN_NUM, da_ptctr, acrosssec);
  gErr->SetMarkerStyle(20);
  gErr->SetMarkerSize(1.);
  gErr->SetMarkerColor(kMagenta+2);
  gErr->Draw("psame");
  TLegend* legErrors = new TLegend(0.60,0.70,0.90,0.90);
  legErrors->SetFillColor(0);
  legErrors->SetBorderSize(0);
  legErrors->AddEntry(gErrTotal,"Total unc.","f");
  legErrors->AddEntry(gErrSyst,"Data syst. unc.","f");
  legErrors->AddEntry(gErrStat,"Data stat. unc.","lep");
  legErrors->AddEntry(gErrScaling,"FONLL scaling unc.","f");
  legErrors->Draw("same");
  cErrors->SaveAs(Form("plots/%s/cErrors.pdf",rapi.Data()));

  //Print out scaled data points center values and total uncert.
  cout<<"---- Print out scaled data points center values and total uncert."<<endl;
  Int_t q=0;
  cout<<endl;
  cout<<"  -- Scaled reference before rebin"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"pT bins[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString sptbin = Form("(%.1f,%.1f)",da_ptbin[q],da_ptbin[q+1]);
      cout<<setiosflags(std::ios::left)<<setw(12)<<sptbin;
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Center value[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<acrosssec[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Up errors[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<amaxErr[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Up errors[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString percsign = "%";
      TString sperc = Form("%.2f%s",amaxErrrel[q]*100.,percsign.Data());
      cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Dw errors[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<aminErr[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Dw errors[]";
  cout<<" = {";
  for(q=0;q<da_BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString percsign = "%";
      TString sperc = Form("%.2f%s",aminErrrel[q]*100.,percsign.Data());
      cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
    }
  cout<<"};"<<endl;
  cout<<endl;

  //Plot and fit scaled data points
  cout<<"---- Plot and fit scaled data"<<endl;
  cout<<"  -- Plot scaled data with total uncertainty"<<endl;
  Double_t iexl[da_BIN_NUM],iexr[da_BIN_NUM];
  for(i=0;i<da_BIN_NUM;i++)
    {
      iexl[i] = da_bincenter[i]-da_ptbin[i];
      iexr[i] = da_ptbin[i+1]-da_bincenter[i];
    }
  TGraphAsymmErrors* gcrosssec_rescaled = new TGraphAsymmErrors(da_BIN_NUM, da_bincenter, acrosssec, iexl, iexr, aminErr, amaxErr);
  gcrosssec_rescaled->SetMarkerStyle(20);
  gcrosssec_rescaled->SetMarkerSize(0.7);
  gcrosssec_rescaled->SetMarkerColor(kBlack);
  gcrosssec_rescaled->SetLineWidth(2);
  gcrosssec_rescaled->SetLineColor(kBlack);
  TCanvas* crescaled =  new TCanvas("crescaled","",400,400);
  crescaled->SetLogy();
  TH2F* hempty_crescaled=new TH2F("hempty_crescaled","",10,0,20.,10.,1.e-2,1.e+3);
  hempty_crescaled->SetStats(0);
  hempty_crescaled->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_crescaled->GetYaxis()->SetTitle("Scaled d#sigma(D^{0})/dp_{T}(#mub GeV-1c)");
  hempty_crescaled->GetXaxis()->SetTitleOffset(1.);
  hempty_crescaled->GetYaxis()->SetTitleOffset(.9);
  hempty_crescaled->GetXaxis()->SetTitleSize(0.045);
  hempty_crescaled->GetYaxis()->SetTitleSize(0.045);
  hempty_crescaled->GetXaxis()->SetTitleFont(42);
  hempty_crescaled->GetYaxis()->SetTitleFont(42);
  hempty_crescaled->GetXaxis()->SetLabelFont(42);
  hempty_crescaled->GetYaxis()->SetLabelFont(42);
  hempty_crescaled->GetXaxis()->SetLabelSize(0.04);
  hempty_crescaled->GetYaxis()->SetLabelSize(0.04);
  hempty_crescaled->Draw();
  gcrosssec_rescaled->Draw("psame");
  TLegend* legcrosssec_rescaled = new TLegend(0.60,0.80,0.90,0.90);
  legcrosssec_rescaled->SetFillColor(0);
  legcrosssec_rescaled->SetBorderSize(0);
  legcrosssec_rescaled->AddEntry(gcrosssec_rescaled,"Total unc.","lep");
  legcrosssec_rescaled->Draw("same");

  //Fit scaled data points
  cout<<"  -- Fit scaled data"<<endl;
  TF1* fdata = new TF1("fdata","pow(10,[0]*exp([1]*x)+[2])",da_ptbin[0],da_ptbin[da_BIN_NUM]);
  //fdata->SetParameter(1,-0.055);
  fdata->SetParLimits(1,-0.100,-0.055);
  fdata->SetParLimits(0,5.,8.);
  fdata->SetParLimits(2,-4.,-2.);

  //TF1* fdata = new TF1("fdata","pow(10,[0]*exp([1]*x)+[2])",da_ptbin[0],da_ptbin[da_BIN_NUM]);
  //fdata->SetParLimits(1,-0.070,-0.055);
  //fdata->SetParLimits(0,5.,7.);
  //fdata->SetParLimits(2,-4.,-3.);

  //TF1* fdata = new TF1("fdata"," exp([1]+[2]*x+[3]*x*x+[4]*x*x*x)",da_ptbin[0],da_ptbin[da_BIN_NUM]);
  //fdata->SetParameter(1,6.91);
  //fdata->SetParameter(2,-0.72);
  //fdata->SetParLimits(3,-0.01,0.008);
  //fdata->SetParLimits(4,0.0008,0.0012);
  gcrosssec_rescaled->Fit("fdata","q","",da_ptbin[1],da_ptbin[da_BIN_NUM]);
  cout<<fdata->GetParameter(0)<<"  "<<fdata->GetParameter(1)<<"  "<<fdata->GetParameter(2)<<"  "<<fdata->GetParameter(3)<<endl;
  crescaled->SaveAs(Form("plots/%s/rescaled.pdf",rapi.Data()));

  //Rebin into 2.76TeV PbPb ptbins
  cout<<"---- Rebin into 2.76TeV PbPb ptbins"<<endl;
  TH1F* hfitref = new TH1F("hfitref","",BIN_NUM,ptbin);
  TH1F* hfitreffitDoublecheck = new TH1F("hfitreffitDoublecheck","",da_BIN_NUM,da_ptbin);
  Double_t integ;
  Double_t afinalsc[BIN_NUM],afinapt[BIN_NUM],afinaptl[BIN_NUM];
  Double_t afinalupWeighted[BIN_NUM],afinaldwWeighted[BIN_NUM],afinaluprelWeighted[BIN_NUM],afinaldwrelWeighted[BIN_NUM];
  Double_t afinalupUnWeighted[BIN_NUM],afinaldwUnWeighted[BIN_NUM],afinaluprelUnWeighted[BIN_NUM],afinaldwrelUnWeighted[BIN_NUM];
  Double_t afitDoublecheck[da_BIN_NUM];

  //Calculate error rebin fraction
  cout<<"  -- Calculate error rebin fraction"<<endl;
  Double_t afracWeighted[BIN_NUM][COB_NUM],afracUnWeighted[BIN_NUM][COB_NUM];
  for(i=0;i<BIN_NUM;i++)
    {
      for(j=0;j<COB_NUM;j++)
	{
	  afracWeighted[i][j]=0;
	  afracUnWeighted[i][j]=0;
	}
    }
  for(i=0;i<BIN_NUM;i++)
    {
      for(j=0;j<COB_NUM;j++)
	{
	  if(ind[i][j]>-1)
	    {
	      afracWeighted[i][j] = fdata->Integral(lowridge[i][j],highridge[i][j]) / fdata->Integral(ptbin[i],ptbin[i+1]);
	      afracUnWeighted[i][j] = (highridge[i][j]-lowridge[i][j]) / (ptbin[i+1]-ptbin[i]);
	    }
	}
    }
  cout<<"  -- Rebin center value by fitting function"<<endl;
  cout<<"  -- Rebin uncertainties by statistic weight"<<endl;
  for(i=0;i<da_BIN_NUM;i++)
    {
      integ = fdata->Integral(da_ptbin[i],da_ptbin[i+1])/hfitreffitDoublecheck->GetBinWidth(i+1);
      afitDoublecheck[i] = integ/acrosssec[i];
    }
  TGraph* gfitDoublecheck = new TGraph(da_BIN_NUM,da_ptctr,afitDoublecheck);  
  TCanvas* cfitDoublecheck = new TCanvas("cfitDoublecheck","",500,500);
  TH2F* hempty_cfitDoublecheck = new TH2F("hempty_cfitDoublecheck","",10,0,17.,10.,0.2,2.2);
  hempty_cfitDoublecheck->SetStats(0);
  hempty_cfitDoublecheck->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_cfitDoublecheck->GetYaxis()->SetTitle("#sigma(scaled data)/#sigma(rebin by fit)");
  hempty_cfitDoublecheck->GetXaxis()->SetTitleOffset(1.);
  hempty_cfitDoublecheck->GetYaxis()->SetTitleOffset(.9);
  hempty_cfitDoublecheck->GetXaxis()->SetTitleSize(0.045);
  hempty_cfitDoublecheck->GetYaxis()->SetTitleSize(0.045);
  hempty_cfitDoublecheck->GetXaxis()->SetTitleFont(42);
  hempty_cfitDoublecheck->GetYaxis()->SetTitleFont(42);
  hempty_cfitDoublecheck->GetXaxis()->SetLabelFont(42);
  hempty_cfitDoublecheck->GetYaxis()->SetLabelFont(42);
  hempty_cfitDoublecheck->GetXaxis()->SetLabelSize(0.04);
  hempty_cfitDoublecheck->GetYaxis()->SetLabelSize(0.04);
  hempty_cfitDoublecheck->Draw();
  gfitDoublecheck->SetMarkerStyle(2);   gfitDoublecheck->SetMarkerSize(2);  gfitDoublecheck->Draw("psame");
  cfitDoublecheck->SaveAs(Form("plots/%s/cfitDoublecheck.pdf",rapi.Data()));


  for(i=0;i<BIN_NUM;i++)
    {
      integ = fdata->Integral(ptbin[i],ptbin[i+1])/hfitref->GetBinWidth(i+1);
      afinalsc[i] = integ;
      hfitref->SetBinContent(i+1,integ);
      afinalupWeighted[i]=0;  afinalupUnWeighted[i]=0;
      afinaldwWeighted[i]=0;  afinaldwUnWeighted[i]=0;
      for(j=0;j<COB_NUM;j++)
	{
	  if(ind[i][j]<0) continue;
	  afinaldwrelWeighted[i]+=aminErrrel[ind[i][j]]*afracWeighted[i][j];
	  afinaldwWeighted[i] = afinaldwrelWeighted[i]*afinalsc[i];
	  afinaluprelWeighted[i]+=amaxErrrel[ind[i][j]]*afracWeighted[i][j];
	  afinalupWeighted[i] = afinaluprelWeighted[i]*afinalsc[i];
	  afinaldwrelUnWeighted[i]+=aminErrrel[ind[i][j]]*afracUnWeighted[i][j];
	  afinaldwUnWeighted[i] = afinaldwrelUnWeighted[i]*afinalsc[i];
	  afinaluprelUnWeighted[i]+=amaxErrrel[ind[i][j]]*afracUnWeighted[i][j];
	  afinalupUnWeighted[i] = afinaluprelUnWeighted[i]*afinalsc[i];
	}
      afinapt[i] = hfitref->GetBinCenter(i+1);
      afinaptl[i] = hfitref->GetBinWidth(i+1)/2.;
    }



  //Print out 2.76TeV data-driven pp reference values
  cout<<"---- Print out 2.76TeV data-driven pp reference results"<<endl;
  cout<<endl;
  //weighted
  cout<<"  -- Final reference after rebin"<<endl;
  if(displayAreaUnweighted) cout<<"  -- Area Weighted"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"pT bins[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString sptbin = Form("(%.1f,%.1f)",ptbin[q],ptbin[q+1]);
      cout<<setiosflags(std::ios::left)<<setw(12)<<sptbin;
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Center value[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<afinalsc[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Up errors[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<afinalupWeighted[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Up errors[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString percsign = "%";
      TString sperc = Form("%.2f%s",afinaluprelWeighted[q]*100,percsign.Data());
      cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Dw errors[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      cout<<setiosflags(std::ios::left)<<setw(12)<<afinaldwWeighted[q];
    }
  cout<<"};"<<endl;
  cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Dw errors[]";
  cout<<" = {";
  for(q=0;q<BIN_NUM;q++)
    {
      if(q!=0) cout<<", ";
      TString percsign = "%";
      TString sperc = Form("%.2f%s",afinaldwrelWeighted[q]*100,percsign.Data());
      cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
    }
  cout<<"};"<<endl;
  //unweighted
  if(displayAreaUnweighted)
    {
      cout<<"  -- Area UnWeighted"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"pT bins[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  TString sptbin = Form("(%.1f,%.1f)",ptbin[q],ptbin[q+1]);
	  cout<<setiosflags(std::ios::left)<<setw(12)<<sptbin;
	}
      cout<<"};"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Center value[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  cout<<setiosflags(std::ios::left)<<setw(12)<<afinalsc[q];
	}
      cout<<"};"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Up errors[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  cout<<setiosflags(std::ios::left)<<setw(12)<<afinalupUnWeighted[q];
	}
      cout<<"};"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Up errors[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  TString percsign = "%";
	  TString sperc = Form("%.2f%s",afinaluprelUnWeighted[q]*100,percsign.Data());
	  cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
	}
      cout<<"};"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Dw errors[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  cout<<setiosflags(std::ios::left)<<setw(12)<<afinaldwUnWeighted[q];
	}
      cout<<"};"<<endl;
      cout<<setiosflags(std::ios::left)<<"     "<<setw(20)<<"Relative Dw errors[]";
      cout<<" = {";
      for(q=0;q<BIN_NUM;q++)
	{
	  if(q!=0) cout<<", ";
	  TString percsign = "%";
	  TString sperc = Form("%.2f%s",afinaldwrelUnWeighted[q]*100,percsign.Data());
	  cout<<setiosflags(std::ios::left)<<setw(12)<<sperc;
	}
      cout<<"};"<<endl;
    }
  cout<<endl;
  
  //Plot 2.76TeV data-driven pp reference
  cout<<"---- Plot rebinned 2.76TeV data-driven pp reference"<<endl;
  TGraphAsymmErrors* gfinalref = new TGraphAsymmErrors(BIN_NUM, afinapt, afinalsc, afinaptl, afinaptl, afinaldwWeighted, afinalupWeighted);
  gfinalref->SetMarkerStyle(20);
  gfinalref->SetMarkerSize(0.7);
  gfinalref->SetMarkerColor(kBlack);
  gfinalref->SetLineWidth(2);
  gfinalref->SetLineColor(kBlack);
  TCanvas* cfinalref = new TCanvas("cfinalref","",400,400);
  cfinalref->SetLogy();
  TH2F* hempty_cfinalref = new TH2F("hempty_cfinalref","",10,0,20.,10.,1.e-2,1.e+3);
  hempty_cfinalref->SetStats(0);
  hempty_cfinalref->GetXaxis()->SetTitle("p_{t} (GeV/c)");
  hempty_cfinalref->GetYaxis()->SetTitle("Fitted d#sigma(D^{0})/dp_{T}(#mub/(GeV/c))");
  hempty_cfinalref->GetXaxis()->SetTitleOffset(1.);
  hempty_cfinalref->GetYaxis()->SetTitleOffset(.9);
  hempty_cfinalref->GetXaxis()->SetTitleSize(0.045);
  hempty_cfinalref->GetYaxis()->SetTitleSize(0.045);
  hempty_cfinalref->GetXaxis()->SetTitleFont(42);
  hempty_cfinalref->GetYaxis()->SetTitleFont(42);
  hempty_cfinalref->GetXaxis()->SetLabelFont(42);
  hempty_cfinalref->GetYaxis()->SetLabelFont(42);
  hempty_cfinalref->GetXaxis()->SetLabelSize(0.04);
  hempty_cfinalref->GetYaxis()->SetLabelSize(0.04);  
  hempty_cfinalref->Draw();
  gfinalref->Draw("psame");
  cfinalref->SaveAs(Form("plots/%s/finalref.pdf",rapi.Data()));
  
  //Plot ratio of data-driven pp reference and pure FONLL
  cout<<"---- Plot ratio of data-driven pp reference and FONLL"<<endl;
  TH1F* hptAnlyRef_rebin = (TH1F*)hptAnlyRef->Rebin(BIN_NUM,"hptAnlyRef_rebin",ptbin);
  for(i=0;i<BIN_NUM;i++)
    {
      hptAnlyRef_rebin->SetBinContent(i+1,hptAnlyRef_rebin->GetBinContent(i+1)/(hptAnlyRef_rebin->GetBinWidth(i+1)*4));      
    }
  Double_t aratiosc[BIN_NUM],aratioup[BIN_NUM],aratiodw[BIN_NUM];
  for(i=0;i<BIN_NUM;i++)
    {
      aratiosc[i] = afinalsc[i]/hptAnlyRef_rebin->GetBinContent(i+1);
      aratioup[i] = afinalupWeighted[i]/hptAnlyRef_rebin->GetBinContent(i+1);
      aratiodw[i] = afinaldwWeighted[i]/hptAnlyRef_rebin->GetBinContent(i+1);
    }
  TGraphAsymmErrors* gratioref = new TGraphAsymmErrors(BIN_NUM, afinapt, aratiosc, afinaptl, afinaptl, aratiodw, aratioup);
  gratioref->SetMarkerStyle(20);
  gratioref->SetMarkerSize(0.7);
  gratioref->SetMarkerColor(kBlack);
  gratioref->SetLineWidth(2);
  gratioref->SetLineColor(kBlack);
  TCanvas* cratioref = new TCanvas("cratioref","",400,400);
  TH2F* hempty_cratioref = new TH2F("hempty_cratioref","",10,0,18.,10.,0.,3.5);
  hempty_cratioref->SetStats(0);
  hempty_cratioref->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hempty_cratioref->GetYaxis()->SetTitle("data/FONLL");
  hempty_cratioref->GetXaxis()->SetTitleOffset(1.);
  hempty_cratioref->GetYaxis()->SetTitleOffset(.9);
  hempty_cratioref->GetXaxis()->SetTitleSize(0.045);
  hempty_cratioref->GetYaxis()->SetTitleSize(0.045);
  hempty_cratioref->GetXaxis()->SetTitleFont(42);
  hempty_cratioref->GetYaxis()->SetTitleFont(42);
  hempty_cratioref->GetXaxis()->SetLabelFont(42);
  hempty_cratioref->GetYaxis()->SetLabelFont(42);
  hempty_cratioref->GetXaxis()->SetLabelSize(0.04);
  hempty_cratioref->GetYaxis()->SetLabelSize(0.04);  
  hempty_cratioref->Draw();
  gratioref->Draw("psame");
  cratioref->SaveAs(Form("plots/%s/ratioref.pdf",rapi.Data()));

  cout<<endl;

}
void plotInclusiveMass(  FileList fileList  , float Lumi_ = 30) {

  for(int i = 0; i<fileList.size(); i++){
    (fileList[i].first)->Close();
    delete (fileList[i].first);
  }

  TFile* fVBF115 = new TFile("/data_CMS/cms/lbianchini/MuTauStream/treeMuTauStream_VBFH115.root","READ");
  TFile* fVBF135 = new TFile("/data_CMS/cms/lbianchini/MuTauStream/treeMuTauStream_VBFH135.root","READ");
  TFile* fDYJets = new TFile("/data_CMS/cms/lbianchini/MuTauStream/treeMuTauStream_DYJets-madgraph-50-PU.root","READ");
  TFile* fTT     = new TFile("/data_CMS/cms/lbianchini/MuTauStream/treeMuTauStream_TT-madgraph-PU.root","READ");
  TFile* fWJets  = new TFile("/data_CMS/cms/lbianchini/MuTauStream/treeMuTauStream_WJets-madgraph-PU.root","READ");
  TFile* fT      = new TFile("/data_CMS/cms/lbianchini/MuTauStream/treeMuTauStream_TToBLNu-tW-madhraph-PU.root","READ");
  TFile* fQCD    = new TFile("/data_CMS/cms/lbianchini/MuTauStream/treeMuTauStream_QCD-pythia-PU.root","READ");

  FileList fileList_;
  fileList_.push_back( make_pair(fT,      make_pair("tW",        10.6      )  ));
  fileList_.push_back( make_pair(fQCD,    make_pair("QCD",   349988.0      )  ));
  fileList_.push_back( make_pair(fWJets,  make_pair("Wjets",  31314.0      )  ));
  fileList_.push_back( make_pair(fTT,     make_pair("ttbar",    157.5      )  ));
  fileList_.push_back( make_pair(fDYJets, make_pair("Zjets",   3048.0      )  ));
  fileList_.push_back( make_pair(fVBF115, make_pair("qqH115",       0.1012 )  ));
  fileList_.push_back( make_pair(fVBF135, make_pair("qqH135",       0.05049)  ));
 

  TCanvas *c1 = new TCanvas("c1InclusiveMass","",5,30,650,600);
  c1->SetGrid(0,0);
  c1->SetFillStyle(4000);
  c1->SetFillColor(10);
  c1->SetTicky();
  c1->SetObjectStat(0);
  c1->SetLogy(1);


  TPad* pad1 = new TPad("pad1InclusiveMass","",0.05,0.27,0.96,0.97);
  TPad* pad2 = new TPad("pad2InclusiveMass","",0.05,0.02,0.96,0.26);
  pad1->SetFillColor(0);
  pad2->SetFillColor(0);
  pad1->Draw();
  pad2->Draw();

  pad1->cd();
  pad1->SetLogy(1);

  TLegend* leg = new TLegend(0.60,0.47,0.90,0.85,NULL,"brNDC");
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->SetFillColor(10);
  leg->SetTextSize(0.04);
  leg->SetHeader( "#mu+#tau Inclusive" );
  
  THStack* aStack = new THStack("aStack",Form("CMS Preliminary 2010    #sqrt{s}=7 TeV L=%.0f pb^{-1}",Lumi_));
  TH1F* hqqH115 = new TH1F();
  TH1F* hqqH135 = new TH1F();
  TH1F* hSiml   = new TH1F();

  float signalScale = 1;

  for(unsigned int i = 0 ; i < fileList_.size() ; i++){

    TFile* currentFile = (TFile*)fileList_[i].first ;
    if( currentFile->IsZombie() ) continue;
    TH1F* allEvents = (TH1F*)currentFile->Get("allEventsFilter/totalEvents");
    float totalEvents = allEvents->GetBinContent(1);

    TTree* currentTree = (TTree*)currentFile->Get("muTauStreamAnalyzer/tree");
    string h1Name = "h1_"+(fileList_[i].second).first;
    TH1F* h1 = new TH1F( h1Name.c_str() ,"", 28 , 20, 300);

    if( ((fileList_[i].second).first).find("Zjets")!=string::npos ) {
      h1->SetFillColor(kRed);
      leg->AddEntry(h1,"MadGraph Z+jets","F");
    }
    if( ((fileList_[i].second).first).find("ttbar")!=string::npos ) {
      h1->SetFillColor(kBlue);
      leg->AddEntry(h1,"MadGraph t#bar{t}+jets","F");
    }
    if( ((fileList_[i].second).first).find("Wjets")!=string::npos ) {
      h1->SetFillColor(kGreen);
      leg->AddEntry(h1,"MadGraph W+jets","F");
    }
    if( ((fileList_[i].second).first).find("tW")!=string::npos ){
      h1->SetFillColor( 44 );
      leg->AddEntry(h1,"MadGraph single-top","F");
    }
    if( ((fileList_[i].second).first).find("QCD")!=string::npos ) {
      h1->SetFillColor(11);
      leg->AddEntry(h1,"Pythia QCD","F");
    }
    if( ((fileList_[i].second).first).find("qqH115")!=string::npos ) {
      h1->SetLineColor(kBlack);
      h1->SetLineStyle(kDashed);
      h1->SetLineWidth(3.0);
      leg->AddEntry(h1,"VBF H(115)#rightarrow#tau#tau X 100","l");
      signalScale = 100;
    }
    if( ((fileList_[i].second).first).find("qqH135")!=string::npos ) {
      h1->SetLineColor(kBlack);
      h1->SetLineStyle(kDotted);
      h1->SetLineWidth(3.0);
      leg->AddEntry(h1,"VBF H(135)#rightarrow#tau#tau X 100","l");
      signalScale = 100;
    }

    int nEntries = currentTree->GetEntries() ;
    
    std::vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > >* diTauSVfit3;
    currentTree->SetBranchAddress("diTauSVfit3P4",&diTauSVfit3);

    for (int n = 0; n < nEntries ; n++) {
      currentTree->GetEntry(n);
      if( diTauSVfit3->size() < 1) continue;
      h1->Fill( (*diTauSVfit3)[0].M() ) ;
    }

    h1->Scale( Lumi_ / (totalEvents/((fileList_[i].second).second * signalScale)) );

    if(((fileList_[i].second).first).find("qqH115")!=string::npos){
      hqqH115=(TH1F*)h1->Clone("hqqH115");
      hqqH115 = h1;
      hqqH115->Sumw2();
      continue;
    }
    if(((fileList_[i].second).first).find("qqH135")!=string::npos){
      hqqH135=(TH1F*)h1->Clone("hqqH135");
      hqqH135 = h1;
      hqqH135->Sumw2();
      continue;
    }

    if(i==0) hSiml=(TH1F*)h1->Clone("hSiml");
    else hSiml->Add(h1);

    aStack->Add(h1);

  }

  //float numData = hData->GetEntries();
  //float numSiml = hSiml->Integral();
  //float dataToSimlRatio = numData/numSiml;
  //cout << "data " << numData << "  ---  simul " << numSiml << endl;  

  aStack->Draw("HIST");
  hqqH115->Draw("HISTSAME");
  hqqH135->Draw("HISTSAME");
  TH1F* hStack = (TH1F*)aStack->GetHistogram();
  hStack->SetXTitle("SVfit #tau#tau mass");
  hStack->SetYTitle(Form("Number of events/%.0f GeV",hStack->GetBinWidth(1)));
  hStack->SetTitleSize(0.05,"X");
  hStack->SetTitleSize(0.05,"Y");
  hStack->SetTitleOffset(0.75,"Y");
  leg->Draw();

  pad2->cd();
  TH1F* hRatio = new TH1F("hRatio", " ; ; purity",
			  hStack->GetNbinsX(), 
			  hStack->GetXaxis()->GetXmin(), hStack->GetXaxis()->GetXmax());
  hRatio->SetLineStyle(kDashed);
  hRatio->SetLineWidth(1.0);
  hRatio->SetLabelSize(0.12,"X");
  hRatio->SetLabelSize(0.10,"Y");
  hRatio->SetTitleSize(0.12,"Y");
  hRatio->SetTitleOffset(0.36,"Y");
  TH1F* hqqH115Clone = (TH1F*)hqqH115->Clone("hqqH115Clone");
  TH1F* hqqH135Clone = (TH1F*)hqqH135->Clone("hqqH135Clone");
  hqqH115Clone->Divide( hqqH115 ,hSiml,1./signalScale,1.0);
  hqqH135Clone->Divide( hqqH135 ,hSiml,1./signalScale,1.0);
  hRatio->SetAxisRange(0.,0.001,"Y");

  hRatio->Draw();
  hqqH115Clone->Draw("HISTSAME");
  hqqH135Clone->Draw("HISTSAME");

  if(SAVE) c1->SaveAs("Zmm_InclusiveMass.png");

}
Example #18
0
void t1pfmetPhiwithCorr(double pt1min, double pt2min, double METmin, double DPHImin){
gStyle->SetPadTickY(1);
gStyle->SetPadTickX(1);

int  i = 0;
  TLegend* leg = new TLegend(0.35,0.65,0.87,0.87);
  leg->SetNColumns(2);
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);

  TCanvas *canvas = new TCanvas("c1n","",500,600);
  TPad *mainPad = new TPad("mainPad","",0,0.3,1,1);
  TPad *smallPad = new TPad("smallPad","",0,0.05,1,0.3);
  mainPad->SetBottomMargin(0.015);


  smallPad->SetTopMargin(0.05);
  smallPad->SetBottomMargin(0.25);

  canvas->cd();

  mainPad->Draw();
  mainPad->cd();







 
  //  gPad->SetLogy();
  TCut mggmax = "mgg<180";
  TCut mggmin = "mgg>100";
  TCut pt1Cut = Form("pt1/mgg>%lf",pt1min);
  TCut pt2Cut = Form("pt2/mgg>%lf",pt2min);
  //  TCut METCut = Form("t1pfmetCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0)>%lf",METmin);
  TCut METCut = "";
 TCut DPHICut =  Form("Delta(pt1,eta1,phi1,pt2,eta2,phi2,t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>%lf",DPHImin);
  TCut eveto1 = "eleveto1 == 1";
  TCut eveto2 = "eleveto2 == 1";
  TCut eveto = eveto1 && eveto2;
  TCut genmatch = "((genmatch1==1 && genmatch2==0)||(genmatch1==0 && genmatch2==1)||(genmatch1==0 && genmatch2==0))";  
  TCut metF = "((metF_GV==1) && (metF_HBHENoise==1) && (metF_HBHENoiseIso==1) && (metF_CSC==1) && (metF_eeBadSC==1))";  
  TCut NegWeight = "weight>0.";

  /* 
     TFile *M1 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M1.root","READ");  
     TFile *M10 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M10.root","READ");
     TFile *M100 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M100.root","READ");  
     TFile *M1000 =  TFile::Open("./50ns_betaV3/NewWeightDMHtoGG_M1000.root","READ");
  */

  TFile *data = TFile::Open("./25ns_2246inv_v3/DoubleEG.root","READ");
  
  TFile *sig1 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP600.root","READ");
  TFile *sig2 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP800.root","READ");
  TFile *sig3 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1000.root","READ");
  TFile *sig4 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1200.root","READ");
  TFile *sig5 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1400.root","READ");  
  TFile *sig6 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP1700.root","READ");
  TFile *sig7 = TFile::Open("./25ns_2246inv_v3/2HDM_mZP2500.root","READ");
  /*
    TFile *bkg1 =  TFile::Open("./50ns_betaV3/DiPhoton.root","READ");  
    TFile *bkg2 =  TFile::Open("./50ns_betaV3/DYJetsToLL.root","READ");  
    TFile *bkg3 =  TFile::Open("./50ns_betaV3/GJets.root","READ");  
    TFile *bkg4 =  TFile::Open("./50ns_betaV3/GluGluHToGG.root","READ");  
    TFile *bkg5 =  TFile::Open("./50ns_betaV3/QCD.root","READ");  
    TFile *bkg6 =  TFile::Open("./50ns_betaV3/VH.root","READ");  
  */

  TFile *bkg1 =  TFile::Open("./25ns_2246inv_v3/DiPhoton.root","READ");  
  TFile *bkg2 =  TFile::Open("./25ns_2246inv_v3/DYJetsToLL.root","READ");  
  TFile *bkg3 =  TFile::Open("./25ns_2246inv_v3/GJets.root","READ");  
  TFile *bkg4 =  TFile::Open("./25ns_2246inv_v3/GluGluHToGG.root","READ");  
  TFile *bkg5 =  TFile::Open("./25ns_2246inv_v3/QCD.root","READ");  
  TFile *bkg6 =  TFile::Open("./25ns_2246inv_v3/VH.root","READ");  
  TFile *bkg7 =  TFile::Open("./25ns_2246inv_v3/ttHJetToGG.root","READ");
  TFile *bkg8 =  TFile::Open("./25ns_2246inv_v3/VBFHToGG.root","READ");
  TFile *bkg9 =  TFile::Open("./25ns_2246inv_v3/TGJets.root","READ");
  TFile *bkg10 =  TFile::Open("./25ns_2246inv_v3/TTGJets.root","READ");
  TFile *bkg11 =  TFile::Open("./25ns_2246inv_v3/WGToLNuG.root","READ");
  TFile *bkg12 =  TFile::Open("./25ns_2246inv_v3/ZGTo2LG.root","READ");
  /*
    TTree *tree_M1 = (TTree*) M1->Get("DiPhotonTree");
    TTree *tree_M10 = (TTree*) M10->Get("DiPhotonTree");
    TTree *tree_M100 = (TTree*) M100->Get("DiPhotonTree");
    TTree *tree_M1000 = (TTree*) M1000->Get("DiPhotonTree");
  */

  TTree *tree_data = (TTree*) data->Get("DiPhotonTree");
  
  TTree *tree_sig1 = (TTree*) sig1->Get("DiPhotonTree");
  TTree *tree_sig2 = (TTree*) sig2->Get("DiPhotonTree");
  TTree *tree_sig3 = (TTree*) sig3->Get("DiPhotonTree");
  TTree *tree_sig4 = (TTree*) sig4->Get("DiPhotonTree");
  TTree *tree_sig5 = (TTree*) sig5->Get("DiPhotonTree");
  TTree *tree_sig6 = (TTree*) sig6->Get("DiPhotonTree");
  TTree *tree_sig7 = (TTree*) sig7->Get("DiPhotonTree");
 
  
  
  TTree *tree_bkg1 = (TTree*) bkg1->Get("DiPhotonTree");
  TTree *tree_bkg2 = (TTree*) bkg2->Get("DiPhotonTree");
  TTree *tree_bkg3 = (TTree*) bkg3->Get("DiPhotonTree");
  TTree *tree_bkg4 = (TTree*) bkg4->Get("DiPhotonTree");
  TTree *tree_bkg5 = (TTree*) bkg5->Get("DiPhotonTree");
  TTree *tree_bkg6 = (TTree*) bkg6->Get("DiPhotonTree");
  TTree *tree_bkg7 = (TTree*) bkg7->Get("DiPhotonTree");
  TTree *tree_bkg8 = (TTree*) bkg8->Get("DiPhotonTree");
  TTree *tree_bkg9 = (TTree*) bkg9->Get("DiPhotonTree");
  TTree *tree_bkg10 = (TTree*) bkg10->Get("DiPhotonTree");
  TTree *tree_bkg11 = (TTree*) bkg11->Get("DiPhotonTree");
  TTree *tree_bkg12 = (TTree*) bkg12->Get("DiPhotonTree");
  
  
  /* 
     tree_M1->Draw("(t1pfmet)>>h1(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h1 =(TH1F*)gPad->GetPrimitive("h1");
     tree_M10->Draw("(t1pfmet)>>h2(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h2 =(TH1F*)gPad->GetPrimitive("h2");
     tree_M100->Draw("(t1pfmet)>>h3(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h3 =(TH1F*)gPad->GetPrimitive("h3");
     tree_M1000->Draw("(t1pfmet)>>h4(30,100,200)","weight*10"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto && Cut_Jets));
     TH1F *h4 =(TH1F*)gPad->GetPrimitive("h4");  
  */
  
  tree_data->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,1))>>hdata(10,-4,4)","(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && eveto && METCut  && metF&& DPHICut ));
  TH1F *hdata =(TH1F*)gPad->GetPrimitive("hdata");

  tree_sig1->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h1(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h1 =(TH1F*)gPad->GetPrimitive("h1");
  tree_sig2->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h2(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h2 =(TH1F*)gPad->GetPrimitive("h2");
  tree_sig3->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h3(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h3 =(TH1F*)gPad->GetPrimitive("h3");
  tree_sig4->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h4(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h4 =(TH1F*)gPad->GetPrimitive("h4");
  tree_sig5->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h5(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h5 =(TH1F*)gPad->GetPrimitive("h5");
  tree_sig6->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h6(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h6 =(TH1F*)gPad->GetPrimitive("h6");
  tree_sig7->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>h7(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *h7 =(TH1F*)gPad->GetPrimitive("h7");

  





  tree_bkg1->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg1(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg1 =(TH1F*)gPad->GetPrimitive("hbkg1");
  tree_bkg2->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg2(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg2 =(TH1F*)gPad->GetPrimitive("hbkg2");
  tree_bkg3->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg3(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && genmatch && DPHICut));
  TH1F *hbkg3 =(TH1F*)gPad->GetPrimitive("hbkg3");
     
tree_bkg4->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg4(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut)); 
  TH1F *hbkg4 =(TH1F*)gPad->GetPrimitive("hbkg4");
  tree_bkg5->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg5(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && genmatch && DPHICut));
  TH1F *hbkg5 =(TH1F*)gPad->GetPrimitive("hbkg5");
  tree_bkg6->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg6(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg6 =(TH1F*)gPad->GetPrimitive("hbkg6");  
  tree_bkg7->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg7(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg7 =(TH1F*)gPad->GetPrimitive("hbkg7");  
  tree_bkg8->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg8(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg8 =(TH1F*)gPad->GetPrimitive("hbkg8");  
  tree_bkg9->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg9(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut)); 
  TH1F *hbkg9 =(TH1F*)gPad->GetPrimitive("hbkg9");  
  tree_bkg10->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg10(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg10 =(TH1F*)gPad->GetPrimitive("hbkg10");  
 tree_bkg11->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg11(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg11 =(TH1F*)gPad->GetPrimitive("hbkg11");  
 tree_bkg12->Draw("(t1pfmetPhiCorr(t1pfmet,t1pfmetPhi,t1pfmetSumEt,0))>>hbkg12(10,-4,4)","weight*(mgg<115||mgg>135)"*(mggmax && mggmin && pt1Cut && pt2Cut && METCut && eveto  && DPHICut));
  TH1F *hbkg12 =(TH1F*)gPad->GetPrimitive("hbkg12");  



 

  hdata->SetMarkerColor(kBlack);
  hdata->SetLineColor(kBlack);
  hdata->SetMarkerStyle(20);
  
  h1->SetLineColor(kRed+3);
  h2->SetLineColor(kRed+1);
  h3->SetLineColor(kRed);
  h4->SetLineColor(kPink+2);
  h5->SetLineColor(kPink+4);
 h6->SetLineColor(kPink+7);
 h7->SetLineColor(kMagenta+2);
 h1->SetLineWidth(2);
 h2->SetLineWidth(2);
 h3->SetLineWidth(2);
 h4->SetLineWidth(2);
 h5->SetLineWidth(2);
 h6->SetLineWidth(2);
 h7->SetLineWidth(2);


  
  
  THStack *hs=new THStack("hs","");
  hbkg7->SetFillColor(kGreen+2);
  hbkg6->SetFillColor(kGreen);
  hbkg8->SetFillColor(kYellow);
  hbkg4->SetFillColor(kOrange);
  hbkg9->SetFillColor(kOrange+7);
  hbkg10->SetFillColor(kOrange+4);
  hbkg11->SetFillColor(kCyan);
  hbkg12->SetFillColor(kCyan+1);
  hbkg5->SetFillColor(kBlue+2);
  hbkg2->SetFillColor(kBlue);  
  hbkg3->SetFillColor(kMagenta-2);
  hbkg1->SetFillColor(kViolet);

  hbkg1->SetLineColor(kBlack);
  hbkg2->SetLineColor(kBlack);
  hbkg3->SetLineColor(kBlack);
  hbkg4->SetLineColor(kBlack);
  hbkg5->SetLineColor(kBlack);
  hbkg6->SetLineColor(kBlack);
  hbkg7->SetLineColor(kBlack);
  hbkg8->SetLineColor(kBlack);
  hbkg9->SetLineColor(kBlack);
  hbkg10->SetLineColor(kBlack);
  hbkg11->SetLineColor(kBlack);
  hbkg12->SetLineColor(kBlack);

  hs->Add(hbkg7);
  hs->Add(hbkg6);
  hs->Add(hbkg8);
  hs->Add(hbkg4);
  hs->Add(hbkg9);
  hs->Add(hbkg10);
  hs->Add(hbkg11);
  hs->Add(hbkg12);
  hs->Add(hbkg2);
  hs->Add(hbkg5);
  hs->Add(hbkg3);
  hs->Add(hbkg1);
  
  TH1F *hsum = (TH1F*)hbkg1->Clone("hsum"); 
  hsum->Add(hbkg2);
  hsum->Add(hbkg3);
  hsum->Add(hbkg4);
  hsum->Add(hbkg5);
  hsum->Add(hbkg6);
  hsum->Add(hbkg7);
  hsum->Add(hbkg8);
  hsum->Add(hbkg9);
  hsum->Add(hbkg10);
  hsum->Add(hbkg11);
  hsum->Add(hbkg12);
  


  canvas->SetLeftMargin(0.12);

  // hs->SetMinimum(0.01);
  hs->SetMaximum(5700);

  hs->SetTitle("");
  hs->Draw("HIST"); 
  hsum->SetMarkerStyle(1);
  hsum->SetFillColor(kGray+3);
  hsum->SetFillStyle(3002);
  hsum->Draw("same e2");
  //  h2->Draw("same hist");
  // h3->Draw("same hist"); 
  // h4->Draw("same hist");
  // h1->Draw("same hist");
  //h5->Draw("same hist"); //only for 25ns samples
  //h7->Draw("same hist"); //only for 25ns samples
  // h6->Draw("same hist"); //only for 25ns samples
  hdata->Draw("same E1");
  

  hs->GetXaxis()->SetLabelOffset(999);
  hs->GetYaxis()->SetTitleOffset(1.5);
  hs->GetYaxis()->SetTitle("Events/0.8");  
  //int  iPos = 11;
//  CMS_lumi(canvas,true,iPos,false);
  gPad->Modified();


  leg->AddEntry(hdata,"Data","elp");
  /*leg->AddEntry(h1,"m_{#chi} = 1 GeV","l");
  leg->AddEntry(h2,"m_{#chi} = 10 GeV","l");
  leg->AddEntry(h3,"m_{#chi} = 100 GeV","l");      
  leg->AddEntry(h4,"m_{#chi} = 1000 GeV","l");*/
  //  leg->AddEntry(h1,"m_{Z'} = 600 GeV","l");
  leg->AddEntry(hbkg1,"#gamma #gamma","f");
  // leg->AddEntry(h2,"m_{Z'} = 800 GeV","l");
  leg->AddEntry(hbkg2,"Drell Yann","f");
  // leg->AddEntry(h3,"m_{Z'} = 1000 GeV","l");
  leg->AddEntry(hbkg3,"#gamma + Jets","f");
  // leg->AddEntry(h4,"m_{Z'} = 1200 GeV","l");
  leg->AddEntry(hbkg5,"QCD","f");
  // leg->AddEntry(h5,"m_{Z'} = 1400 GeV","l"); //only for 25ns samples                                                              
  leg->AddEntry(hbkg4,"ggH","f");
  //leg->AddEntry(h6,"m_{Z'} = 1700 GeV","l"); //only for 25ns samples                                                              
  leg->AddEntry(hbkg6,"VH","f");
  // leg->AddEntry(h7,"m_{Z'} = 2500 GeV","l"); //only for 25ns samples                                                              
  leg->AddEntry(hbkg7,"ttH","f");
  leg->AddEntry(hbkg8,"VBF H","f");
  leg->AddEntry(hbkg9,"t + #gamma + Jets","f");
  leg->AddEntry(hbkg10,"tt + #gamma +Jets","f");
  leg->AddEntry(hbkg11,"#gamma+W","f");
  leg->AddEntry(hbkg12,"#gamma+Z","f");
 leg->AddEntry(hsum,"Bkg uncertainty","f");
  leg->Draw("same");




  
  gStyle->SetOptStat(0);  
 

  canvas->cd();
  smallPad->Draw();
  smallPad->cd();

  TGraphErrors *gr = new TGraphErrors(0);
  double integralData=hdata->Integral();
  double integralBKG=hsum->Integral();
  double error, ratio;
  for(int w=1; w<20; w++){
    if((hdata->GetBinContent(w)!=0) && (hsum->GetBinContent(w)!=0)){

      gr->SetPoint(w, hdata->GetBinCenter(w),(hdata->GetBinContent(w))/(hsum->GetBinContent(w)));
      ratio= (hdata->GetBinContent(w))/(hsum->GetBinContent(w));
      error= (hdata->GetBinContent(w)*sqrt(hsum->GetBinContent(w))/(hsum->GetBinContent(w)*hsum->GetBinContent(w)) + sqrt(hdata->GetBinContent(w))/hsum->GetBinContent(w));
      std::cout<<"VALUE: "<<ratio<<" ERROR: "<<error<<std::endl;
      gr->SetPointError(w, hdata->GetBinWidth(w)/2,error);
    }else{
      gr->SetPoint(w, hdata->GetBinCenter(w),10);
    }
  }



  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);
  gr->GetHistogram()->SetMaximum(2);
  gr->GetHistogram()->SetMinimum(0.1);

  gStyle->SetTextSize(14);
  gROOT->ForceStyle();

  gr->GetXaxis()->SetLabelFont(43);
  gr->GetXaxis()->SetLabelSize(15);
  gr->GetYaxis()->SetLabelFont(43);
  gr->GetYaxis()->SetLabelSize(15);

  gr->GetXaxis()->SetLimits(-4,4);


  gPad->SetGrid();
  gStyle->SetStripDecimals(kTRUE);
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(0.7);


  gr->Draw("AZP");
  gr->GetXaxis()->SetTitle("#phi_{MET}^{corr}");
  gr->GetXaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetTitleSize(0.1);
  gr->GetYaxis()->SetNdivisions(505);

  gr->GetXaxis()->SetTitleOffset(1);
  gr->GetYaxis()->SetTitle("Data/MC");
  gr->GetYaxis()->SetTitleOffset(0.4);
  gr->SetTitle("");
  smallPad->Update();
  TF1* line = new TF1("line","1",-4,4);
  line->SetLineColor(kRed);
  line->SetLineWidth(2);
  line->Draw("L same");
  gr->Draw("ZP SAME");


  canvas->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/metphicorr_MET%.0lf.pdf",METmin)); 
  canvas->SaveAs(Form("./25ns_2246inv_v3/plots/kinematics/metphicorr_MET%.0lf.png",METmin)); 
    
}
Example #19
0
pair <float,float> find_point(TH2F* histo, int xbin, bool mSUGRA=true) {
  TH1F *flathisto;
  if(mSUGRA) flathisto = new TH1F("flat","flat",histo->GetNbinsY(),histo->GetYaxis()->GetBinLowEdge(1),histo->GetYaxis()->GetBinLowEdge(histo->GetNbinsY())+histo->GetYaxis()->GetBinWidth(histo->GetNbinsY()));
  else flathisto = new TH1F("flat","flat",histo->GetNbinsX(),histo->GetXaxis()->GetBinLowEdge(1),histo->GetXaxis()->GetBinLowEdge(histo->GetNbinsX())+histo->GetXaxis()->GetBinWidth(histo->GetNbinsX()));
  
  int nbins=histo->GetNbinsY();
  if(!mSUGRA) nbins=histo->GetNbinsX();
  for(int i=1;i<nbins;i++) {
    float value=(histo->GetBinContent(xbin,i));
    if(value<20&&value>0) flathisto->SetBinContent(i,value);
  }
  
  float pointone=-100;
  nbins=flathisto->GetNbinsX();
  if(!mSUGRA) nbins=flathisto->GetNbinsY();
  for(int i=nbins;i>=1;i--) {
    if(pointone<0&&flathisto->GetBinContent(i)<1&&flathisto->GetBinContent(i)>0) pointone=flathisto->GetBinLowEdge(i)+flathisto->GetBinWidth(i);
  }
  pair <float,float> anything;
  if(mSUGRA) anything.first=histo->GetXaxis()->GetBinCenter(xbin);
  else anything.first=histo->GetYaxis()->GetBinCenter(xbin);
  anything.second=pointone;
  delete flathisto;
  return anything;
}
void 
//HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., TString datacard="htt_et_1_7TeV", string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category_extra = "0-jet high p_{T}^{#tau_{h}}";         }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category_extra = "1-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category_extra= "1-jet high p_{T}^{#tau_{h}}";  }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra= "1-jet high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra2= "boosted"; }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category_extra = "VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category_extra = "Loose VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category_extra = "Tight VBF tag";              }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category_extra = "no b-tag";     }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category_extra = "b-tag";  }        
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra2 = "medium p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }

  const char* dataset;
#ifdef MSSM
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                19.7 fb^{-1} (8 TeV)";}
#else
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS, 19.7 fb^{-1} at 8 TeV";}
#endif
  
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"     , directory)), "QCD"); InitHist(Fakes, "", "", TColor::GetColor(250,202,255), 1001); 
  TH1F* EWK0   = refill((TH1F*)input->Get(TString::Format("%s/VV"      , directory)), "VV" ); InitHist(EWK0 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"       , directory)), "W"  ); InitHist(EWK1 , "", "", TColor::GetColor(222,90,106), 1001);
#ifdef EXTRA_SAMPLES
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"      , directory)), "ZJ" ); InitHist(EWK2 , "", "", TColor::GetColor(100,182,232), 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/ZL"      , directory)), "ZL" ); InitHist(EWK  , "", "", TColor::GetColor(100,182,232), 1001);
#else
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/ZLL"     , directory)), "ZLL"); InitHist(EWK  , "", "", TColor::GetColor(100,182,232), 1001);
#endif
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"      , directory)), "TT" ); InitHist(ttbar, "", "", TColor::GetColor(155,152,204), 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"); InitHist(Ztt  , "", "", TColor::GetColor(248,206,104), 1001);
#ifdef MSSM
  TH1F* ggH    = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA" , directory)), "ggH"); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA" , directory)), "bbH"); InitSignal(bbH); bbH->Scale($TANB);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125"  , directory)), "ggH"); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125"  , directory)), "qqH"); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125"   , directory)), "VH" ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK0 );
  ref->Add(EWK1 );
#ifdef EXTRA_SAMPLES
  ref->Add(EWK2 );
#endif
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK0 ->Integral();
  unscaled[1]+= EWK1 ->Integral();
#ifdef EXTRA_SAMPLES
  unscaled[1]+= EWK2 ->Integral();
#endif
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif
#endif

  if(scaled){

/*    Fakes = refill(shape_histos(Fakes, datacard, "QCD"), "QCD");
    EWK0 = refill(shape_histos(EWK0, datacard, "VV"), "VV"); 
    EWK1 = refill(shape_histos(EWK1, datacard, "W"), "W"); 
#ifdef EXTRA_SAMPLES
    EWK2 = refill(shape_histos(EWK2, datacard, "ZJ"), "ZJ");
    EWK = refill(shape_histos(EWK, datacard, "ZL"), "ZL");
#else
    //    EWK = refill(shape_histos(EWK, datacard, "ZLL"), "ZLL");
#endif
    ttbar = refill(shape_histos(ttbar, datacard, "TT"), "TT");
    Ztt = refill(shape_histos(Ztt, datacard, "ZTT"), "ZTT");
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MA"), "ggH$MA"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MA"), "bbH$MA"); 
#else
#ifndef DROP_SIGNAL
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH"); 
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH"); 
    VH = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif  
#endif
*/

    rescale(Fakes, 7); 
    rescale(EWK0 , 6); 
    rescale(EWK1 , 3); 
#ifdef EXTRA_SAMPLES
    rescale(EWK2 , 4); 
    rescale(EWK  , 5);
#else
    rescale(EWK  , 4);
#endif 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
#ifndef DROP_SIGNAL
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);
#endif  
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK0 ->Integral()
					       +EWK1 ->Integral()
#ifdef EXTRA_SAMPLES
					       +EWK2 ->Integral()
#endif
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
#ifndef DROP_SIGNAL
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif
#endif

  EWK0 ->Add(Fakes);
  EWK1 ->Add(EWK0 );
#ifdef EXTRA_SAMPLES
  EWK2 ->Add(EWK1 );
  EWK  ->Add(EWK2 );
#else
  EWK  ->Add(EWK1 );
#endif
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    EWK1 ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    EWK1 ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{e}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
#if defined MSSM
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
  if (category_extra2!="") chan     = new TPaveText(0.20, 0.69+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
#endif
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
#if defined MSSM
  if (category_extra2!="") chan->AddText(category_extra2);
#else
  chan->AddText(category_extra2);
#endif
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  TPaveText* cat2      = new TPaveText(0.20, 0.66+0.061, 0.32, 0.66+0.161, "NDC");
  cat2->SetBorderSize(   0 );
  cat2->SetFillStyle(    0 );
  cat2->SetTextAlign(   12 );
  cat2->SetTextSize ( 0.05 );
  cat2->SetTextColor(    1 );
  cat2->SetTextFont (   62 );
  cat2->AddText(category_extra2);
  cat2->Draw();
*/  
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("MSSM m^{h}_{max} scenario");
  massA->AddText("m_{A}=$MA GeV, tan#beta=$TANB");
  massA->Draw();
#endif

#ifdef MSSM
  TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "h,A,H#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.52, 0.58, 0.92, 0.89);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "SM H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "Observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(EWK  , "Z#rightarrow ee"                , "F" );
  leg->AddEntry(EWK1 , "W+jets"                         , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", TColor::GetColor(250,202,255), 1001);
  InitHist  (scales[1], "", "", TColor::GetColor(222,90,106), 1001);
  InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
  InitHist  (scales[3], "", "", TColor::GetColor(248,206,104), 1001);
#ifndef DROP_SIGNAL
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
#ifndef DROP_SIGNAL
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same"); 
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
    EWK  ->Write("Zee"     );
    EWK1 ->Write("EWK"    );
  //EWK  ->Write("EWK"     );
  EWK1 ->Write("EWK1"    );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
void 
HTT_EE_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="ee_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("ee_0jet_low"             )){ category = "ee, 0 jet";          }    
  if(std::string(directory) == std::string("ee_0jet_low"             )){ category_extra = "p_{T}(lep1) low";          }    
  if(std::string(directory) == std::string("ee_0jet_high"            )){ category = "ee, 0 jet";          }    
  if(std::string(directory) == std::string("ee_0jet_high"            )){ category_extra = "p_{T}(lep1) high";         }    
  if(std::string(directory) == std::string("ee_1jet_low"          )){ category = "ee, 1 jet";          }    
  if(std::string(directory) == std::string("ee_1jet_low"          )){ category_extra = "p_{T}(lep1) low";       }    
  if(std::string(directory) == std::string("ee_1jet_high"          )){ category = "ee, 1 jet";          }    
  if(std::string(directory) == std::string("ee_1jet_high"          )){ category_extra = "p_{T}(lep1) high";       }    
  if(std::string(directory) == std::string("ee_vbf"            )){ category = "ee, 2 jet";          }    
  if(std::string(directory) == std::string("ee_vbf"            )){ category_extra = "VBF";              }    
  if(std::string(directory) == std::string("ee_nobtag"               )){ category = "ee";          }    
  if(std::string(directory) == std::string("ee_nobtag"               )){ category_extra = "No B-Tag";                        }    
  if(std::string(directory) == std::string("ee_btag"                 )){ category = "ee";          }    
  if(std::string(directory) == std::string("ee_btag"                 )){ category_extra = "B-Tag";                           }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.8 fb^{-1} at 8 TeV";}
 
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* ZTT     = refill((TH1F*)input ->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"     ); InitHist(ZTT     , "", "", kOrange  -  4, 1001);
  TH1F* ZEE     = refill((TH1F*)input ->Get(TString::Format("%s/ZEE"     , directory)), "ZEE"     ); InitHist(ZEE     , "", "", kAzure   +  2, 1001);
  TH1F* TTJ     = refill((TH1F*)input ->Get(TString::Format("%s/TTJ"     , directory)), "TTJ"     ); InitHist(TTJ     , "", "", kBlue    -  8, 1001);
  TH1F* QCD     = refill((TH1F*)input ->Get(TString::Format("%s/QCD"     , directory)), "QCD"     ); InitHist(QCD     , "", "", kMagenta - 10, 1001);
  TH1F* Dibosons= refill((TH1F*)input ->Get(TString::Format("%s/Dibosons", directory)), "Dibosons"); InitHist(Dibosons, "", "", kGreen   -  4, 1001);
  TH1F* WJets   = refill((TH1F*)input ->Get(TString::Format("%s/WJets"   , directory)), "WJets"   ); InitHist(WJets   , "", "", kRed     +  2, 1001);
#ifdef MSSM
  TH1F* ggH     = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA"  , directory)), "ggH"     ); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH     = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA"  , directory)), "bbH"     ); InitSignal(bbH); bbH->Scale($TANB);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH     = refill((TH1F*)input ->Get(TString::Format("%s/ggH125"  , directory)), "ggH"     ); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH     = refill((TH1F*)input ->Get(TString::Format("%s/qqH125"  , directory)), "qqH"     ); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH      = refill((TH1F*)input ->Get(TString::Format("%s/VH125"   , directory)), "VH"      ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
#ifdef MSSM
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}" , "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);
#else
  InitHist(data, "#bf{D}", "#bf{dN/dD}"     ); InitData(data);
#endif

  TH1F* ref=(TH1F*)ZTT->Clone("ref");
  ref->Add(ZEE);
  ref->Add(TTJ);
  ref->Add(QCD);
  ref->Add(Dibosons);
  ref->Add(WJets);

  double unscaled[9];
  unscaled[0] = ZTT->Integral();
  unscaled[1] = ZEE->Integral();
  unscaled[2] = TTJ->Integral();
  unscaled[3] = QCD->Integral();
  unscaled[4] = Dibosons->Integral();
  unscaled[5] = WJets->Integral();
#ifdef MSSM
  unscaled[6] = ggH->Integral();
  unscaled[7] = bbH->Integral();
  unscaled[8] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[6] = ggH->Integral();
  unscaled[7] = qqH->Integral();
  unscaled[8] = VH ->Integral();
#endif
#endif
  
  if(scaled){
    rescale(ZTT, 1); 
    rescale(ZEE, 2); 
    rescale(TTJ, 3); 
    rescale(QCD, 4); 
    rescale(Dibosons, 5); 
    rescale(WJets,    6);
#ifdef MSSM 
    rescale(ggH, 7);
    rescale(bbH, 8);
#else
#ifndef DROP_SIGNAL
    rescale(ggH, 7);
    rescale(qqH, 8);
    rescale(VH,  9);
#endif
#endif
  }

  TH1F* scales[9];
  scales[0] = new TH1F("scales-ZTT", "", 9, 0, 9);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (ZTT->Integral()/unscaled[0]-1.)      : 0.);
  scales[1] = new TH1F("scales-ZEE"  , "", 9, 0, 9);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (ZEE->Integral()/unscaled[1]-1.)      : 0.);
  scales[2] = new TH1F("scales-TTJ", "", 9, 0, 9);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (TTJ->Integral()/unscaled[2]-1.)      : 0.);
  scales[3] = new TH1F("scales-QCD"  , "", 9, 0, 9);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (QCD->Integral()/unscaled[3]-1.)      : 0.);
  scales[4] = new TH1F("scales-Dibosons", "", 9, 0, 9);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (Dibosons->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-WJets"  , "", 9, 0, 9);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (WJets->Integral()/unscaled[5]-1.)    : 0.);
#ifdef MSSM
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[6]-1.)      : 0.);
  scales[7] = new TH1F("scales-bbH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (bbH->Integral()/unscaled[7]-1.)      : 0.);
  scales[8] = new TH1F("scales-NONE" , "", 9, 0, 9);
  scales[8]->SetBinContent(9, 0.);
#else
#ifndef DROP_SIGNAL
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[4]-1.)      : 0.);
  scales[7] = new TH1F("scales-qqH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (qqH->Integral()/unscaled[5]-1.)      : 0.);
  scales[8] = new TH1F("scales-VH"   , "", 9, 0, 9);
  scales[8]->SetBinContent(9, unscaled[8]>0 ? (VH ->Integral()/unscaled[6]-1.)      : 0.);
#endif
#endif

  WJets->Add(Dibosons);
  QCD->Add(WJets);
  TTJ->Add(QCD);
  ZTT->Add(TTJ);
  ZEE->Add(ZTT);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(WJets);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(WJets);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }


  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(ZTT, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(ZTT, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)ZEE ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    ZEE->Draw("histsame");
    ZTT->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    WJets->Draw("histsame");
    //Dibosons->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH->Draw("histsame");
#endif

  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    ZEE->Draw("histsame");
    ZTT->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    WJets->Draw("histsame");
    //Dibosons->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{e}#tau_{e}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.20, (category_extra2 && category_extra2[0]=='\0') ? 0.65+0.061 : 0.65+0.061, 0.32, 0.75+0.161, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
  chan->AddText(category_extra2);
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();
*/
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.55, 0.50+0.061, 0.95, 0.50+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m^{h}_{max} (m_{A}=$MA GeV, tan#beta=$TANB)");
  massA->Draw();
#endif

#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"           , "LP");
#else
  leg->AddEntry(data , "observed"                    , "LP");
#endif
  leg->AddEntry(ZEE  , "Z#rightarrowee"              , "F" );
  leg->AddEntry(ZTT  , "Z#rightarrow#tau#tau"        , "F" );
  leg->AddEntry(TTJ  , "t#bar{t}"                    , "F" );
  leg->AddEntry(QCD  , "QCD"                         , "F" );
  leg->AddEntry(WJets, "electroweak"                 , "F" );
  //leg->AddEntry(Dibosons  , "Dibosons"             , "F" );
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)ZEE ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, ZEE->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/ZEE->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, ZEE->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/ZEE->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, ZEE->GetBinContent(ibin+1)>0 ? ZEE ->GetBinError  (ibin+1)/ZEE->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
#ifdef MSSM
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}"); 
#else
  rat1->GetXaxis()->SetTitle("#bf{D}");
#endif
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) ZEE->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? ZEE->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? ZEE->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
#if defined MSSM
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}"); 
#else
  rat2->GetXaxis()->SetTitle("#bf{D}");
#endif
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kOrange  -  4, 1001);
  InitHist  (scales[1], "", "", kAzure   +  2, 1001);
  InitHist  (scales[2], "", "", kBlue    -  8, 1001);
  InitHist  (scales[3], "", "", kMagenta - 10, 1001);
  InitHist  (scales[4], "", "", kGreen   -  4, 1001);
  InitHist  (scales[5], "", "", kRed     +  2, 1001);  
#ifndef DROP_SIGNAL
  InitSignal(scales[6]);
  InitSignal(scales[7]);
  InitSignal(scales[8]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{ZTT}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{ZEE}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{TTJ}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{QCD}"  );
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{Dibosons}");
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{WJets}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{NONE}" );
#else
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  scales[5]->Draw("same");
#ifndef DROP_SIGNAL
  scales[6]->Draw("same");
  scales[7]->Draw("same");
  scales[8]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
 bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  ZTT->Write("Ztt"  );
  ZEE->Write("Zee"  );
  TTJ->Write("ttbar");
  QCD->Write("Fakes");
  Dibosons->Write("Dibosons");
  WJets->Write("EWK");
#ifdef MSSM
  ggH  ->Write("ggH");
  bbH  ->Write("bbH");
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH");
  qqH  ->Write("qqH");
  VH   ->Write("VH" );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
Example #22
0
TCanvas *PlotDataMC(TChain *data, TChain *mc, TString branchname, TString binning, 
		    TString category, TString selection, 
		    TString dataLabel, TString mcLabel, TString xLabel, TString yLabelUnit, 
		    bool logy=false, bool usePU=true, bool smear=false, bool scale=false){
  
  TString yLabel; 
  std::cout<<"entering"<<std::endl;
  
  TCanvas *c = new TCanvas("c","");
  TString branchNameData=branchname;
  TString branchNameMC=branchname;

  ElectronCategory_class cutter;

  std::cout<<"entering2"<<std::endl;

  TCut selection_data="";
  if(category.Sizeof()>1) selection_data = cutter.GetCut(category, false,0,true);
  selection_data.Print();
  //  return NULL;
  selection_data+=selection;
  TCut selection_MC="";
  if(category.Sizeof()>1) selection_MC = cutter.GetCut(category, false,0);
  selection_MC+=selection;

  std::cout<<"qui"<<std::endl;

  if(smear){
    branchNameMC.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*smearEle) ");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*smearEle[1])");

  }
  if(scale){
    branchNameData.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(corrEle[0]*corrEle[1]))");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*corrEle)");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*corrEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*corrEle[1])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_ele ","(energySCEle_regrCorr_ele*corrEle)");
    branchNameData.ReplaceAll("energySCEle_regrCorr_ele[0]","(energySCEle_regrCorr_ele[0]*corrEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_ele[1]","(energySCEle_regrCorr_ele[1]*corrEle[1])");

  }
  //std::cout << branchNameData << "\t" << branchNameMC << std::endl;


  if(branchname=="HLT"){
    TH1F *hlt_data = new TH1F("data_hist","",500,0,500);
    TH1F *hlt_mc = new TH1F("mc_hist","",500,0,500);
    
    
    std::vector< std::string > *HLTNames = new std::vector<std::string>; ///< List of HLT names
    std::vector<Bool_t> *HLTResults = new std::vector<Bool_t>;      ///< 0=fail, 1=fire
    
    data->SetBranchAddress("HLTNames", &HLTNames);
    data->SetBranchAddress("HLTResults", &HLTResults);
    
    data->GetEntries();
    for(Long64_t jentry=0; jentry < data->GetEntriesFast(); jentry++){
      data->GetEntry(jentry);
      std::vector<Bool_t>::const_iterator hltRes_itr=HLTResults->begin();
      for(std::vector<std::string>::const_iterator hlt_itr=HLTNames->begin();
	  hlt_itr!=HLTNames->end();
	  hlt_itr++,hltRes_itr++){
	std::cout << *hlt_itr << std::endl;
	hlt_data->Fill(hlt_itr-HLTNames->begin(),*hltRes_itr);
      }
    }
    data->ResetBranchAddresses();

    mc->SetBranchAddress("HLTNames", &HLTNames);
    mc->SetBranchAddress("HLTResults", &HLTResults);
    
    mc->GetEntries();
    for(Long64_t jentry=0; jentry < mc->GetEntriesFast(); jentry++){
      mc->GetEntry(jentry);
      std::vector<Bool_t>::const_iterator hltRes_itr=HLTResults->begin();
      for(std::vector<std::string>::const_iterator hlt_itr=HLTNames->begin();
	  hlt_itr!=HLTNames->end();
	  hlt_itr++,hltRes_itr++){
	std::cout << *hlt_itr << std::endl;
	hlt_mc->Fill(hlt_itr-HLTNames->begin(),*hltRes_itr);
      }
    }

    for(std::vector<std::string>::const_iterator hlt_itr=HLTNames->begin();
	hlt_itr!=HLTNames->end();
	hlt_itr++){
      int index=hlt_itr-HLTNames->begin()+1;
      if(hlt_mc->GetBinContent(index)>0)
      hlt_mc->GetXaxis()->SetBinLabel(index,(*hlt_itr).c_str());
    }
  } else {

  std::cout<<"qui"<<std::endl;
    data->Draw(branchNameData+">>data_hist"+binning, selection_data);
    if(mc!=NULL){
      if(usePU)  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC *"puWeight");
    else  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC);
  std::cout<<"qui"<<std::endl;
    }
  }

  c->Clear();
  TH1F *d = (TH1F *) gROOT->FindObject("data_hist");
  TH1F *s = (TH1F *) gROOT->FindObject("mc_hist");
  if(s==NULL) s=d;
  //d->SaveAs("tmp/d_hist.root");
  s->SaveAs("tmp/s_hist.root");
  std::cout<<"qui"<<std::endl;

  yLabel.Form("Events /(%.2f %s)", s->GetBinWidth(2), yLabelUnit.Data());
  float max = 1.1 * std::max(
			     d->GetMaximum(),///d->Integral(),
			     s->GetMaximum() ///s->Integral()
			     );
  max=1.1*d->GetMaximum();
  std::cout << "max = " << max << std::endl;
  std::cout << "nEvents data: " << d->Integral() << "\t" << d->GetEntries() << std::endl;
  std::cout << "nEvents signal: " << s->Integral() << "\t" << s->GetEntries() << std::endl;
  if(logy){
    max*=10;
    d->GetYaxis()->SetRangeUser(0.1,max);
    s->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    d->GetYaxis()->SetRangeUser(0,max);
    s->GetYaxis()->SetRangeUser(0,max);
  }
  s->GetYaxis()->SetTitle(yLabel);
  s->GetXaxis()->SetTitle(xLabel);
  d->GetYaxis()->SetTitle(yLabel);
  d->GetXaxis()->SetTitle(xLabel);


  d->SetMarkerStyle(20);
  d->SetMarkerSize(1);
  if(d != s){
    s->SetMarkerStyle(20);
    s->SetMarkerSize(1);
    s->SetFillStyle(3001);
    s->SetFillColor(kRed);
  }

  TH1F* s_norm = (TH1F *) (s->DrawNormalized("hist", d->Integral()));
  //TH1F* d_norm = s_norm;
  //if(d!=s) d_norm = (TH1F *) (d->DrawNormalized("p same", d->Integral()));
  if(d!=s) d->Draw("p same");

  if(logy){
    //d_norm->GetYaxis()->SetRangeUser(0.1,max);
    s_norm->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    //d_norm->GetYaxis()->SetRangeUser(0,max);  
    s_norm->GetYaxis()->SetRangeUser(0,max);  
  }
  std::cout << "Variable  & Data & Simulation \\" << std::endl;
  std::cout << "Mean      & " << d->GetMean() << " " << d->GetMeanError() 
	    << " & " << s_norm->GetMean() <<  " " << s_norm->GetMeanError() << " \\" << std::endl;
  std::cout << "Std. dev. & " << d->GetRMS() << " " << d->GetRMSError() 
	    << " & " << s_norm->GetRMS() << " " << s_norm->GetRMSError() << " \\" << std::endl;
  std::cout << "\\hline" << std::endl;
  std::cout << "$\\Chi^2$ " <<  d->Chi2Test(s_norm, "UW CHI2/NDF NORM") << std::endl;
  

  TLegend *leg = new TLegend(0.6,0.8,1,1);
  if(dataLabel !="") leg->AddEntry(d,dataLabel,"p");
  if(mcLabel   !="") leg->AddEntry(s,mcLabel, "lf");
  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  leg->SetTextSize(0.04);
  if(dataLabel !="" && mcLabel !="") leg->Draw();
  //c->GetListOfPrimitives()->Add(leg,"");

  TPaveText *pv = new TPaveText(0.2,0.95,0.7,1,"NDC");
  pv->AddText("CMS Preliminary 2016");
  pv->SetFillColor(0);
  pv->SetBorderSize(0);
  pv->Draw();


  return c;

}
Example #23
0
void makePlotTriggers3(){
    
    bool DCSonly = false;//always false

    string whichdata = "SingleMuon";
    //string whichdata = "DoubleMuon";
    //string whichdata = "MuonEG";
    //string whichdata = "SingleElectron";

  
  //  vector<char*> bgnames, signames;
  vector<string> bgstrings, sigstrings;
  vector<Color_t> colors;
  const unsigned int datasetsize = 4;//12
  const unsigned int bgsetsize = 4;//8
  const unsigned int sigsetsize = datasetsize-bgsetsize;
  string datasets[datasetsize]={"TTbar_amcnlo_50ns","WJets_50ns","DY_M50_50ns","DY_M10_50ns"};
  //char* dataset[datasetsize]={"TTbar1l","TTbar2l","SingleT","VJets","Rare","Stop_425_325","Stop_500_325","Stop_650_325","Stop_850_100"};
  const Color_t mccolor[datasetsize]={kBlue+1,kGreen+1,kMagenta+1,kMagenta-2};//
  
  string outputdir = "../plots/first_20150727/";
  string  inputdir = "../rootfiles/first_20150727/";
    if(DCSonly) outputdir = "../plots/first_20150727/DCSonly/";
  
  for(unsigned int n=0; n<bgsetsize; ++n) {
    //bgnames.push_back(dataset[n]);
    bgstrings.push_back(datasets[n]);
    colors.push_back(mccolor[n]);
  }
  for(unsigned int n=bgsetsize; n<datasetsize; ++n) {
    //signames.push_back(dataset[n]);
    sigstrings.push_back(datasets[n]);
    colors.push_back(mccolor[n]);
  }
  TFile *fbg[bgsetsize];

    vector<string> histonames;
    vector<string> histonames1;
    vector<string> histonames2;
    vector<float> fithisto;
    vector<string> xt;
    vector<string> yt;


    //histonames.push_back("TriggerEff__Mu50_Pt"); fithisto.push_back(52);
    //histonames1.push_back("Trigger__Mu50Tag_Pt");
    //histonames2.push_back("Trigger__Mu50Probe_Pt");
    histonames.push_back("TriggerEff_IsoMu27_Pt"); fithisto.push_back(29);          xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)");
    histonames1.push_back("Trigger_IsoMu27Tag_Pt");
    histonames2.push_back("Trigger_IsoMu27Probe_Pt");
    histonames.push_back("TriggerEff_IsoMu27_Eta"); fithisto.push_back(-1);          xt.push_back("muon #eta"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)");
    histonames1.push_back("Trigger_IsoMu27Tag_Eta");
    histonames2.push_back("Trigger_IsoMu27Probe_Eta");
    histonames.push_back("TriggerEff_IsoMu27_RelIso03"); fithisto.push_back(-1);          xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)");
    histonames1.push_back("Trigger_IsoMu27Tag_RelIso03");
    histonames2.push_back("Trigger_IsoMu27Probe_RelIso03");
    histonames.push_back("TriggerEff_IsoMu27_RelIso03EA"); fithisto.push_back(-1);          xt.push_back("muon rel.iso-EA"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)");
    histonames1.push_back("Trigger_IsoMu27Tag_RelIso03EA");
    histonames2.push_back("Trigger_IsoMu27Probe_RelIso03EA");
    histonames.push_back("TriggerEff_IsoMu27_RelIso03DB"); fithisto.push_back(-1);      xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)");
    histonames1.push_back("Trigger_IsoMu27Tag_RelIso03DB");
    histonames2.push_back("Trigger_IsoMu27Probe_RelIso03DB");
    histonames.push_back("TriggerEff_IsoMu27_miniiso"); fithisto.push_back(-1);         xt.push_back("muon rel.miniiso"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)");
    histonames1.push_back("Trigger_IsoMu27Tag_miniiso");
    histonames2.push_back("Trigger_IsoMu27Probe_miniiso");
    histonames.push_back("TriggerEff_IsoMu27_miniisoDB"); fithisto.push_back(-1);       xt.push_back("muon rel.miniiso-DB"); yt.push_back("Efficiency(IsoMu27||IsoTkMu27)");
    histonames1.push_back("Trigger_IsoMu27Tag_miniisoDB");
    histonames2.push_back("Trigger_IsoMu27Probe_miniisoDB");
    histonames.push_back("TriggerEff_IsoMu20_Pt"); fithisto.push_back(22);          xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)");
    histonames1.push_back("Trigger_IsoMu20Tag_Pt");
    histonames2.push_back("Trigger_IsoMu20Probe_Pt");
    histonames.push_back("TriggerEff_IsoMu20_Eta"); fithisto.push_back(-1);          xt.push_back("muon #eta"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)");
    histonames1.push_back("Trigger_IsoMu20Tag_Eta");
    histonames2.push_back("Trigger_IsoMu20Probe_Eta");
    histonames.push_back("TriggerEff_IsoMu20_RelIso03"); fithisto.push_back(-1);          xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)");
    histonames1.push_back("Trigger_IsoMu20Tag_RelIso03");
    histonames2.push_back("Trigger_IsoMu20Probe_RelIso03");
    histonames.push_back("TriggerEff_IsoMu20_RelIso03EA"); fithisto.push_back(-1);         xt.push_back("muon rel.iso-EA"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)");
    histonames1.push_back("Trigger_IsoMu20Tag_RelIso03EA");
    histonames2.push_back("Trigger_IsoMu20Probe_RelIso03EA");
    histonames.push_back("TriggerEff_IsoMu20_RelIso03DB"); fithisto.push_back(-1);      xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)");
    histonames1.push_back("Trigger_IsoMu20Tag_RelIso03DB");
    histonames2.push_back("Trigger_IsoMu20Probe_RelIso03DB");
    histonames.push_back("TriggerEff_IsoMu20_miniiso"); fithisto.push_back(-1);        xt.push_back("muon rel.miniiso"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)");
    histonames1.push_back("Trigger_IsoMu20Tag_miniiso");
    histonames2.push_back("Trigger_IsoMu20Probe_miniiso");
    histonames.push_back("TriggerEff_IsoMu20_miniisoDB"); fithisto.push_back(-1);     xt.push_back("muon rel.miniiso-DB"); yt.push_back("Efficiency(IsoMu20||IsoTkMu20)");
    histonames1.push_back("Trigger_IsoMu20Tag_miniisoDB");
    histonames2.push_back("Trigger_IsoMu20Probe_miniisoDB");
    //histonames.push_back("TriggerEff__Mu45eta2p1_Pt"); fithisto.push_back(47);
    //histonames1.push_back("Trigger__Mu45eta2p1Tag_Pt");
    //histonames2.push_back("Trigger__Mu45eta2p1Probe_Pt");
    histonames.push_back("TriggerEff_IsoMu24eta2p1_Pt"); fithisto.push_back(26);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoMu24eta2p1Tag_Pt");
    histonames2.push_back("Trigger_IsoMu24eta2p1Probe_Pt");
    histonames.push_back("TriggerEff_IsoMu24eta2p1_Eta"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoMu24eta2p1Tag_Eta");
    histonames2.push_back("Trigger_IsoMu24eta2p1Probe_Eta");
    histonames.push_back("TriggerEff_IsoMu24eta2p1_RelIso03"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoMu24eta2p1Tag_RelIso03");
    histonames2.push_back("Trigger_IsoMu24eta2p1Probe_RelIso03");
    histonames.push_back("TriggerEff_IsoMu24eta2p1_RelIso03EA"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoMu24eta2p1Tag_RelIso03EA");
    histonames2.push_back("Trigger_IsoMu24eta2p1Probe_RelIso03EA");
    histonames.push_back("TriggerEff_IsoMu24eta2p1_RelIso03DB"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoMu24eta2p1Tag_RelIso03DB");
    histonames2.push_back("Trigger_IsoMu24eta2p1Probe_RelIso03DB");
    histonames.push_back("TriggerEff_IsoMu24eta2p1_miniiso"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoMu24eta2p1Tag_miniiso");
    histonames2.push_back("Trigger_IsoMu24eta2p1Probe_miniiso");
    histonames.push_back("TriggerEff_IsoMu24eta2p1_miniisoDB"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoMu24eta2p1Tag_miniisoDB");
    histonames2.push_back("Trigger_IsoMu24eta2p1Probe_miniisoDB");
    histonames.push_back("TriggerEff_DiMu_LeadPt"); fithisto.push_back(20);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_DiMuTag_LeadPt");
    histonames2.push_back("Trigger_DiMuProbe_LeadPt");
    histonames.push_back("TriggerEff_DiMu_TrailPt"); fithisto.push_back(10);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_DiMuTag_TrailPt");
    histonames2.push_back("Trigger_DiMuProbe_TrailPt");
 
    histonames.push_back("TriggerEff_PureIsoMu20_Pt"); fithisto.push_back(22);          xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoMu20)");
    histonames1.push_back("Trigger_PureIsoMu20Tag_Pt");
    histonames2.push_back("Trigger_PureIsoMu20Probe_Pt");
    histonames.push_back("TriggerEff_PureIsoMu20_Eta"); fithisto.push_back(-1);         xt.push_back("muon #eta"); yt.push_back("Efficiency(IsoMu20)");
    histonames1.push_back("Trigger_PureIsoMu20Tag_Eta");
    histonames2.push_back("Trigger_PureIsoMu20Probe_Eta");
    histonames.push_back("TriggerEff_PureIsoMu20_Phi"); fithisto.push_back(-1);         xt.push_back("muon #phi"); yt.push_back("Efficiency(IsoMu20)");
    histonames1.push_back("Trigger_PureIsoMu20Tag_Phi");
    histonames2.push_back("Trigger_PureIsoMu20Probe_Phi");
    histonames.push_back("TriggerEff_PureIsoMu20_RelIso03"); fithisto.push_back(-1);          xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoMu20)");
    histonames1.push_back("Trigger_PureIsoMu20Tag_RelIso03");
    histonames2.push_back("Trigger_PureIsoMu20Probe_RelIso03");
    histonames.push_back("TriggerEff_PureIsoMu20_RelIso03DB"); fithisto.push_back(-1);          xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoMu20)");
    histonames1.push_back("Trigger_PureIsoMu20Tag_RelIso03DB");
    histonames2.push_back("Trigger_PureIsoMu20Probe_RelIso03DB");
    histonames.push_back("TriggerEff_IsoTkMu20_Pt"); fithisto.push_back(22);          xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoTkMu20)");
    histonames1.push_back("Trigger_IsoTkMu20Tag_Pt");
    histonames2.push_back("Trigger_IsoTkMu20Probe_Pt");
    histonames.push_back("TriggerEff_IsoTkMu20_Eta"); fithisto.push_back(-1);         xt.push_back("muon #eta"); yt.push_back("Efficiency(IsoTkMu20)");
    histonames1.push_back("Trigger_IsoTkMu20Tag_Eta");
    histonames2.push_back("Trigger_IsoTkMu20Probe_Eta");
    histonames.push_back("TriggerEff_IsoTkMu20_Phi"); fithisto.push_back(-1);         xt.push_back("muon #phi"); yt.push_back("Efficiency(IsoTkMu20)");
    histonames1.push_back("Trigger_IsoTkMu20Tag_Phi");
    histonames2.push_back("Trigger_IsoTkMu20Probe_Phi");
    histonames.push_back("TriggerEff_IsoTkMu20_RelIso03"); fithisto.push_back(-1);          xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoTkMu20)");
    histonames1.push_back("Trigger_IsoTkMu20Tag_RelIso03");
    histonames2.push_back("Trigger_IsoTkMu20Probe_RelIso03");
    histonames.push_back("TriggerEff_IsoTkMu20_RelIso03DB"); fithisto.push_back(-1);          xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoTkMu20)");
    histonames1.push_back("Trigger_IsoTkMu20Tag_RelIso03DB");
    histonames2.push_back("Trigger_IsoTkMu20Probe_RelIso03DB");
    
    histonames.push_back("TriggerEff_PureIsoMu20_Pt_etarestrict"); fithisto.push_back(22);          xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoMu20)");
    histonames1.push_back("Trigger_PureIsoMu20Tag_Pt_etarestrict");
    histonames2.push_back("Trigger_PureIsoMu20Probe_Pt_etarestrict");
    histonames.push_back("TriggerEff_PureIsoMu20_Phi_etarestrict"); fithisto.push_back(-1);         xt.push_back("muon #phi"); yt.push_back("Efficiency(IsoMu20)");
    histonames1.push_back("Trigger_PureIsoMu20Tag_Phi_etarestrict");
    histonames2.push_back("Trigger_PureIsoMu20Probe_Phi_etarestrict");
    histonames.push_back("TriggerEff_IsoTkMu20_Pt_etarestrict"); fithisto.push_back(22);          xt.push_back("muon p_{T} [GeV]"); yt.push_back("Efficiency(IsoTkMu20)");
    histonames1.push_back("Trigger_IsoTkMu20Tag_Pt_etarestrict");
    histonames2.push_back("Trigger_IsoTkMu20Probe_Pt_etarestrict");
    histonames.push_back("TriggerEff_IsoTkMu20_Phi_etarestrict"); fithisto.push_back(-1);       xt.push_back("muon #phi"); yt.push_back("Efficiency(IsoTkMu20)");
    histonames1.push_back("Trigger_IsoTkMu20Tag_Phi_etarestrict");
    histonames2.push_back("Trigger_IsoTkMu20Probe_Phi_etarestrict");
    histonames.push_back("TriggerEff_PureIsoMu20_RelIso03_etarestrict"); fithisto.push_back(-1);          xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoMu20)");
    histonames1.push_back("Trigger_PureIsoMu20Tag_RelIso03_etarestrict");
    histonames2.push_back("Trigger_PureIsoMu20Probe_RelIso03_etarestrict");
    histonames.push_back("TriggerEff_PureIsoMu20_RelIso03DB_etarestrict"); fithisto.push_back(-1);          xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoMu20)");
    histonames1.push_back("Trigger_PureIsoMu20Tag_RelIso03DB_etarestrict");
    histonames2.push_back("Trigger_PureIsoMu20Probe_RelIso03DB_etarestrict");
    histonames.push_back("TriggerEff_IsoTkMu20_RelIso03_etarestrict"); fithisto.push_back(-1);          xt.push_back("muon rel.iso"); yt.push_back("Efficiency(IsoTkMu20)");
    histonames1.push_back("Trigger_IsoTkMu20Tag_RelIso03_etarestrict");
    histonames2.push_back("Trigger_IsoTkMu20Probe_RelIso03_etarestrict");
    histonames.push_back("TriggerEff_IsoTkMu20_RelIso03DB_etarestrict"); fithisto.push_back(-1);          xt.push_back("muon rel.iso-DB"); yt.push_back("Efficiency(IsoTkMu20)");
    histonames1.push_back("Trigger_IsoTkMu20Tag_RelIso03DB_etarestrict");
    histonames2.push_back("Trigger_IsoTkMu20Probe_RelIso03DB_etarestrict");
    
    histonames.push_back("TriggerEff_PureIsoMu27_Pt"); fithisto.push_back(29);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_PureIsoMu27Tag_Pt");
    histonames2.push_back("Trigger_PureIsoMu27Probe_Pt");
    histonames.push_back("TriggerEff_PureIsoMu27_Eta"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_PureIsoMu27Tag_Eta");
    histonames2.push_back("Trigger_PureIsoMu27Probe_Eta");
    histonames.push_back("TriggerEff_PureIsoMu27_Phi"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_PureIsoMu27Tag_Phi");
    histonames2.push_back("Trigger_PureIsoMu27Probe_Phi");
    histonames.push_back("TriggerEff_PureIsoMu27_RelIso03"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_PureIsoMu27Tag_RelIso03");
    histonames2.push_back("Trigger_PureIsoMu27Probe_RelIso03");
    histonames.push_back("TriggerEff_PureIsoMu27_RelIso03DB"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_PureIsoMu27Tag_RelIso03DB");
    histonames2.push_back("Trigger_PureIsoMu27Probe_RelIso03DB");
    histonames.push_back("TriggerEff_IsoTkMu27_Pt"); fithisto.push_back(29);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoTkMu27Tag_Pt");
    histonames2.push_back("Trigger_IsoTkMu27Probe_Pt");
    histonames.push_back("TriggerEff_IsoTkMu27_Eta"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoTkMu27Tag_Eta");
    histonames2.push_back("Trigger_IsoTkMu27Probe_Eta");
    histonames.push_back("TriggerEff_IsoTkMu27_Phi"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoTkMu27Tag_Phi");
    histonames2.push_back("Trigger_IsoTkMu27Probe_Phi");
    histonames.push_back("TriggerEff_IsoTkMu27_RelIso03"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoTkMu27Tag_RelIso03");
    histonames2.push_back("Trigger_IsoTkMu27Probe_RelIso03");
    histonames.push_back("TriggerEff_IsoTkMu27_RelIso03DB"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoTkMu27Tag_RelIso03DB");
    histonames2.push_back("Trigger_IsoTkMu27Probe_RelIso03DB");
    
    histonames.push_back("TriggerEff_PureIsoMu24eta2p1_Pt"); fithisto.push_back(26);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_PureIsoMu24eta2p1Tag_Pt");
    histonames2.push_back("Trigger_PureIsoMu24eta2p1Probe_Pt");
    histonames.push_back("TriggerEff_PureIsoMu24eta2p1_Eta"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_PureIsoMu24eta2p1Tag_Eta");
    histonames2.push_back("Trigger_PureIsoMu24eta2p1Probe_Eta");
    histonames.push_back("TriggerEff_PureIsoMu24eta2p1_Phi"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_PureIsoMu24eta2p1Tag_Phi");
    histonames2.push_back("Trigger_PureIsoMu24eta2p1Probe_Phi");
    histonames.push_back("TriggerEff_PureIsoMu24eta2p1_RelIso03"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_PureIsoMu24eta2p1Tag_RelIso03");
    histonames2.push_back("Trigger_PureIsoMu24eta2p1Probe_RelIso03");
    histonames.push_back("TriggerEff_PureIsoMu24eta2p1_RelIso03DB"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_PureIsoMu24eta2p1Tag_RelIso03DB");
    histonames2.push_back("Trigger_PureIsoMu24eta2p1Probe_RelIso03DB");
    histonames.push_back("TriggerEff_IsoTkMu24eta2p1_Pt"); fithisto.push_back(25);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoTkMu24eta2p1Tag_Pt");
    histonames2.push_back("Trigger_IsoTkMu24eta2p1Probe_Pt");
    histonames.push_back("TriggerEff_IsoTkMu24eta2p1_Eta"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoTkMu24eta2p1Tag_Eta");
    histonames2.push_back("Trigger_IsoTkMu24eta2p1Probe_Eta");
    histonames.push_back("TriggerEff_IsoTkMu24eta2p1_Phi"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoTkMu24eta2p1Tag_Phi");
    histonames2.push_back("Trigger_IsoTkMu24eta2p1Probe_Phi");
    histonames.push_back("TriggerEff_IsoTkMu24eta2p1_RelIso03"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoTkMu24eta2p1Tag_RelIso03");
    histonames2.push_back("Trigger_IsoTkMu24eta2p1Probe_RelIso03");
    histonames.push_back("TriggerEff_IsoTkMu24eta2p1_RelIso03DB"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_IsoTkMu24eta2p1Tag_RelIso03DB");
    histonames2.push_back("Trigger_IsoTkMu24eta2p1Probe_RelIso03DB");
    
    histonames.push_back("TriggerEff_Mu50_Pt"); fithisto.push_back(52);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_Mu50Tag_Pt");
    histonames2.push_back("Trigger_Mu50Probe_Pt");
    histonames.push_back("TriggerEff_Mu50_Eta"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_Mu50Tag_Eta");
    histonames2.push_back("Trigger_Mu50Probe_Eta");
    histonames.push_back("TriggerEff_Mu50_Phi"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_Mu50Tag_Phi");
    histonames2.push_back("Trigger_Mu50Probe_Phi");
    histonames.push_back("TriggerEff_Mu50_RelIso03"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_Mu50Tag_RelIso03");
    histonames2.push_back("Trigger_Mu50Probe_RelIso03");
    histonames.push_back("TriggerEff_Mu50_RelIso03DB"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_Mu50Tag_RelIso03DB");
    histonames2.push_back("Trigger_Mu50Probe_RelIso03DB");

    histonames.push_back("TriggerEff_Mu45eta2p1_Pt"); fithisto.push_back(47);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_Mu45eta2p1Tag_Pt");
    histonames2.push_back("Trigger_Mu45eta2p1Probe_Pt");
    histonames.push_back("TriggerEff_Mu45eta2p1_Eta"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_Mu45eta2p1Tag_Eta");
    histonames2.push_back("Trigger_Mu45eta2p1Probe_Eta");
    histonames.push_back("TriggerEff_Mu45eta2p1_Phi"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_Mu45eta2p1Tag_Phi");
    histonames2.push_back("Trigger_Mu45eta2p1Probe_Phi");
    histonames.push_back("TriggerEff_Mu45eta2p1_RelIso03"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_Mu45eta2p1Tag_RelIso03");
    histonames2.push_back("Trigger_Mu45eta2p1Probe_RelIso03");
    histonames.push_back("TriggerEff_Mu45eta2p1_RelIso03DB"); fithisto.push_back(-1);        xt.push_back(histonames.back()); yt.push_back("Efficiency");
    histonames1.push_back("Trigger_Mu45eta2p1Tag_RelIso03DB");
    histonames2.push_back("Trigger_Mu45eta2p1Probe_RelIso03DB");
    
    TString fdataname = (inputdir+"Histos3Trigger_"+whichdata+".root");
    if(DCSonly) fdataname = (inputdir+"Histos3TriggerDCS_"+whichdata+".root");
    TFile *fdata = TFile::Open(fdataname.Data());



    TCanvas *c1 = new TCanvas("c1", "",477,41,750,500);
    gStyle->SetOptFit(1);
    gStyle->SetOptStat(0);
    gStyle->SetOptTitle(0);
    c1->SetFillColor(0);
    c1->SetBorderMode(0);
    c1->SetBorderSize(2);
    c1->SetTickx(1);
    c1->SetTicky(1);
    c1->SetLeftMargin(0.18);
    c1->SetRightMargin(0.05);
    c1->SetTopMargin(0.07);
    c1->SetBottomMargin(0.15);
    c1->SetFrameFillStyle(0);
    c1->SetFrameBorderMode(0);
    c1->SetFrameFillStyle(0);
    c1->SetFrameBorderMode(0);    float scale;
    for(unsigned int i = 0; i<histonames1.size();++i){
        for(unsigned int j = 0; j<7;++j){
            string prefix = "";
            if(j==1) prefix = "Run251244_";
            else if(j==2) prefix = "Run251251_";
            else if(j==3) prefix = "Run251252_";
            else if(j==4) prefix = "RunPre251561_";
            else if(j==5) prefix = "RunAllPre251561_";
            else if(j>=6) prefix = "RunAfter251561_";
            //if(j==5 && !(histonames1[i]=="TriggerEff_PureIsoMu20_Pt"||histonames1[i]=="TriggerEff_PureIsoMu20_Phi"||histonames1[i]=="TriggerEff_PureIsoMu20_Eta"||
            //             histonames1[i]=="TriggerEff_IsoTkMu20_Pt"  ||histonames1[i]=="TriggerEff_IsoTkMu20_Phi"  ||histonames1[i]=="TriggerEff_IsoTkMu20_Eta")) continue;
            //if(j!=5) continue;
            string name = prefix + histonames1[i]+"_"+whichdata;
            TH1F *hdatatag = (TH1F*)fdata->Get(name.c_str());
            name = prefix + histonames2[i]+"_"+whichdata;
            TH1F *hdataprobe = (TH1F*)fdata->Get(name.c_str());
            name = prefix + histonames[i]+"_"+whichdata;
            float xup = hdatatag->GetBinLowEdge(hdatatag->GetNbinsX())+hdatatag->GetBinWidth(hdatatag->GetNbinsX());
            TH1F *ht = (TH1F*)hdatatag->Clone("ht");
            TH1F *hp = (TH1F*)hdataprobe->Clone("hp");
            if(ht->Integral()<=0) continue;
            TEfficiency *tdataeff = new TEfficiency((*hp),(*ht));
            TH1F *hdataeff = new TH1F(name.c_str(),"",hdatatag->GetNbinsX(), hdatatag->GetBinLowEdge(1), xup);
            //hdataeff->Divide(hdataprobe,hdatatag);
            //hdataeff->GetYaxis()->SetTitle("Efficiency");
            //hdataeff->GetXaxis()->SetTitle(histonames[i].c_str());
            hdataeff->GetYaxis()->SetTitle(yt[i].c_str());
            hdataeff->GetXaxis()->SetTitle(xt[i].c_str());
            hdataeff->Draw();
            hdataeff->GetYaxis()->SetRangeUser(0.,1.2);
            hdataeff->SetMinimum(0.);
            hdataeff->SetMaximum(1.2);
            c1->Clear();
            c1->cd();
            hdataeff->Draw("axis");
            tdataeff->Draw("same");
            //TGraphAsymmErrors *gdataeff = new TGraphAsymmErrors();
            //for(unsigned int i = )
            TGraphAsymmErrors *gdataeff = (TGraphAsymmErrors*)tdataeff->CreateGraph();
            hdataeff->Draw("axis");
            gdataeff->Draw("P");
            c1->Update();
            string outname = outputdir +whichdata + "/" + prefix+ histonames[i] + ".pdf";
            c1->SaveAs(outname.c_str());
            if(fithisto[i]>0){
                name = name + "_fit";
                TF1 *fitfunc = new TF1(name.c_str(),"[0]",fithisto[i],xup);
                //hdataeff->Fit(fitfunc,"R");
                //gdataeff->Fit(fitfunc,"WR");
                gdataeff->Fit(fitfunc,"R");
                c1->Update();
                fitfunc->Draw("same");
                outname = outputdir +whichdata + "/" + prefix + histonames[i] + "_fitted.pdf";
                c1->SaveAs(outname.c_str());
                //std::ostringstream Stream;
                //Stream << "Fit = " << fitfunc->GetParameter(0);
                //TString fitnumber = Stream.str().c_str();
                //TLatex *   tex = new TLatex(0.328859,0.95,fitnumber.Data());
                //tex->SetNDC();
                //tex->SetTextFont(42);
                //tex->SetTextSize(0.04181185);
                //tex->SetLineWidth(2);
                //tex->Draw();
            }
        }
    }
}
Example #24
0
TCanvas *PlotDataMCMC(TChain *data, TChain *mc, TChain *mc2,
		      TString branchname, TString binning, 
		      TString category, TString selection, 
		      TString dataLabel, TString mcLabel, TString mc2Label,
		      TString xLabel, TString yLabelUnit, 
		      bool logy=false, bool usePU=true, bool smear=false, bool scale=false){
  
  TString yLabel; 
  
  TCanvas *c = new TCanvas("c","");
  TString branchNameData=branchname;
  TString branchNameMC=branchname;

  ElectronCategory_class cutter;
  TCut selection_data="";
  if(category.Sizeof()>1) selection_data = cutter.GetCut(category, false,0);
  selection_data+=selection;
  TCut selection_MC="";
  if(category.Sizeof()>1) selection_MC = cutter.GetCut(category, true,0);
  selection_MC+=selection;

  if(smear){
    branchNameMC.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*smearEle) ");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*smearEle[1])");

  }
  if(scale){
    branchNameData.ReplaceAll("invMass_SC_regrCorr_pho ","(invMass_SC_regrCorr_pho*sqrt(corrEle[0]*corrEle[1]))");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho ","(energySCEle_regrCorr_pho*corrEle)");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*corrEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*corrEle[1])");
  }
  //std::cout << branchNameData << "\t" << branchNameMC << std::endl;


  data->Draw(branchNameData+">>data_hist"+binning, selection_data);
  if(mc!=NULL){
    if(usePU)  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC *"puWeight");
    else  mc->Draw(branchNameMC+">>mc_hist"+binning, selection_MC);
  }
  if(mc2!=NULL){
    if(usePU)  mc2->Draw(branchNameMC+">>mc2_hist"+binning, selection_data *"puWeight");
    else  mc2->Draw(branchNameMC+">>mc2_hist"+binning, selection_data);
  }
  

  c->Clear();
  TH1F *d = (TH1F *) gROOT->FindObject("data_hist");
  TH1F *s = (TH1F *) gROOT->FindObject("mc_hist");
  TH1F *s2 = (TH1F *) gROOT->FindObject("mc2_hist");
  if(s==NULL){
    std::cerr << "[WARNING] no mc" << std::endl;
    s=d;
  }
  if(s2==NULL){
    std::cerr << "[WARNING] no mc2" << std::endl;
    s2=s;
  }
  std::cout << s->GetEntries() << "\t" << s2->GetEntries() << "\t" << d->GetEntries() << std::endl;

  //d->SaveAs("tmp/d_hist.root");
  s->SaveAs("tmp/s_hist.root");
  s2->SaveAs("tmp/s2_hist.root");


  yLabel.Form("Events /(%.2f %s)", s->GetBinWidth(2), yLabelUnit.Data());
  float max = 1.1 * std::max(
			     d->GetMaximum(),///d->Integral(),
			     s->GetMaximum() ///s->Integral()
			     );
  max=1.1*d->GetMaximum();
  std::cout << "max = " << max << std::endl;
  std::cout << "nEvents data: " << d->Integral() << "\t" << d->GetEntries() << std::endl;
  std::cout << "nEvents signal: " << s->Integral() << "\t" << s->GetEntries() << std::endl;
  std::cout << "nEvents signal2: " << s2->Integral() << "\t" << s2->GetEntries() << std::endl;
  if(logy){
    max*=10;
    d->GetYaxis()->SetRangeUser(0.1,max);
    s->GetYaxis()->SetRangeUser(0.1,max);
    s2->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    d->GetYaxis()->SetRangeUser(0,max);
    s->GetYaxis()->SetRangeUser(0,max);
    s2->GetYaxis()->SetRangeUser(0,max);
  }
  s->GetYaxis()->SetTitle(yLabel);
  s->GetXaxis()->SetTitle(xLabel);
  s2->GetYaxis()->SetTitle(yLabel);
  s2->GetXaxis()->SetTitle(xLabel);
  d->GetYaxis()->SetTitle(yLabel);
  d->GetXaxis()->SetTitle(xLabel);


  d->SetMarkerStyle(20);
  d->SetMarkerSize(1);
  if(d != s){
    s->SetMarkerStyle(20);
    s->SetMarkerSize(1);
    s->SetFillStyle(3001);
    s->SetFillColor(kRed);
  }
  if(s2 != s){
    //s2->SetMarkerStyle(1);
    //s2->SetMarkerSize(0);
    //s->SetFillStyle(0);
    //s->SetFillColor(kB);
    s2->SetLineWidth(3);
    s2->SetLineColor(kBlack);
  }


  TH1F* s_norm = (TH1F *) (s->DrawNormalized("hist", d->Integral()));
  TH1F* s2_norm = (TH1F *) (s2->DrawNormalized("hist same", d->Integral()));
  //TH1F* d_norm = s_norm;
  //if(d!=s) d_norm = (TH1F *) (d->DrawNormalized("p same", d->Integral()));
  if(d!=s) d->Draw("p same");

  if(logy){
    //d_norm->GetYaxis()->SetRangeUser(0.1,max);
    s_norm->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
    //d_norm->GetYaxis()->SetRangeUser(0,max);  
    s_norm->GetYaxis()->SetRangeUser(0,max);  
  }
  std::cout << "Variable  & Data & Simulation & Simulation2 \\" << std::endl;
  std::cout << "Mean      & " << d->GetMean() << " " << d->GetMeanError() 
	    << " & " << s_norm->GetMean() <<  " " << s_norm->GetMeanError() 
	    << " & " << s2_norm->GetMean() <<  " " << s2_norm->GetMeanError() 
	    << " \\" << std::endl;
  std::cout << "Std. dev. & " << d->GetRMS() << " " << d->GetRMSError() 
	    << " & " << s_norm->GetRMS() << " " << s_norm->GetRMSError() 
	    << " & " << s2_norm->GetRMS() << " " << s2_norm->GetRMSError() 
	    << " \\" << std::endl;
  std::cout << "\\hline" << std::endl;
  std::cout << "$\\Chi^2$ " <<  d->Chi2Test(s_norm, "UW CHI2/NDF NORM") << std::endl;
  

  TLegend *leg = new TLegend(0.6,0.8,1,1);
  if(dataLabel !="") leg->AddEntry(d,dataLabel,"p");
  if(mcLabel   !="") leg->AddEntry(s,mcLabel, "lf");
  if(mc2Label   !="") leg->AddEntry(s2,mc2Label, "l");
  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  leg->SetTextSize(0.04);
  if(dataLabel !="" && mcLabel !="") leg->Draw();
  //c->GetListOfPrimitives()->Add(leg,"");

  TPaveText *pv = new TPaveText(0.23,0.95,0.6,1,"NDC");
  pv->AddText("CMS Preliminary 2016");
  pv->SetFillColor(0);
  pv->SetBorderSize(0);
  pv->Draw();


  return c;

}
Example #25
0
void plotHitEnergy(string inputDir, int hittype=1, float radius=0.4) {
    setNCUStyle(true);

    string decversion;
    if(inputDir.find("rfull009")!=std::string::npos)decversion="rfull009";
    else if(inputDir.find("rfull012")!=std::string::npos)decversion="rfull012";

    TH1F* hecal;
    TH1F* hhcal;
    std::string ecalhitname = hittype==1? "EM_BARREL":"EcalBarrelHits";
    std::string hcalhitname = hittype==1? "HAD_BARREL":"HcalBarrelHits";

    TString energy=gSystem->GetFromPipe(Form("file=%s; test=${file##*/}; test2=${test%%mumu*}; echo \"${test2##*tev}\"",inputDir.data()));
    cout << "energy = " << energy.Data() << endl;

    string inputFile = inputDir + "/radius" + Form("%0.1f",radius)+ (hittype==1? "_rawhit.root": "_rawhit_new.root");
    cout << "opening " << inputFile.data() << endl;



    TFile *f = TFile::Open(inputFile.data());
    hecal = (TH1F*)f->FindObjectAny("hecalhit_energy");
    hecal->SetLineWidth(3);
    hecal->SetFillStyle(1001);
    hecal->SetFillColor(4);
    hecal->SetLineColor(4);
    hecal->SetXTitle(Form("%s hit energy [GeV]",ecalhitname.data()));
    hecal->SetYTitle(Form("Number of hits per %.1f GeV",hecal->GetBinWidth(1)));
    hecal->SetTitleOffset(1.2,"X");
    hecal->SetTitleOffset(1.4,"Y");
    hhcal = (TH1F*)f->FindObjectAny("hhcalhit_energy");
    hhcal->SetLineWidth(3);
    hhcal->SetFillStyle(1001);
    hhcal->SetFillColor(2);
    hhcal->SetLineColor(2);
    hhcal->SetXTitle(Form("%s hit energy [GeV]",hcalhitname.data()));
    hhcal->SetYTitle(Form("Number of hits per %.1f GeV",hhcal->GetBinWidth(1)));
    hhcal->SetTitleOffset(1.2,"X");
    hhcal->SetTitleOffset(1.4,"Y");


    TLegend* leg = new TLegend(0.444,0.690,0.990,0.903);
    leg->SetFillColor(0);
    leg->SetFillStyle(0);

    TCanvas* c1 = new TCanvas("c1","",500,500);
    int lastbin=hecal->FindLastBinAbove(0)+20;
    float xmax=hecal->GetBinLowEdge(lastbin);
    hecal->GetXaxis()->SetRangeUser(0,xmax);
    hecal->Draw("hist");
    c1->SetLogy(1);

    leg->SetHeader(decversion.data());
    leg->AddEntry(hecal,Form("%s-TeV Z'#rightarrow qq",energy.Data()),"f");
    leg->Draw("same");

    std::string outputname = decversion + "/" + decversion + "_" + ecalhitname + "hit_energy_" + Form("%s",energy.Data()) + "TeVZp";
    c1->Print(Form("%s.pdf",outputname.data()));
    c1->Print(Form("%s.eps",outputname.data()));
    leg->Clear();


    lastbin=hhcal->FindLastBinAbove(0)+20;
    xmax=hhcal->GetBinLowEdge(lastbin);
    hhcal->GetXaxis()->SetRangeUser(0,xmax);
    hhcal->Draw("hist");
    c1->SetLogy(1);

    leg->SetHeader(decversion.data());
    leg->AddEntry(hhcal,Form("%s-TeV Z'#rightarrow qq",energy.Data()),"f");
    leg->Draw("same");

    outputname = decversion + "/" + decversion + "_" + hcalhitname + "hit_energy_" + Form("%s",energy.Data()) + "TeVZp";

    c1->Print(Form("%s.pdf",outputname.data()));
    c1->Print(Form("%s.eps",outputname.data()));

}
Example #26
0
TCanvas *PlotDataMCs(TChain *data, std::vector<TChain *> mc_vec, TString branchname, TString binning, 
		     TString category,  TString selection, 
		     TString dataLabel, std::vector<TString> mcLabel_vec, TString xLabel, TString yLabelUnit, TString outputPath, TString label4Print,
		     bool logy=false, bool usePU=true, bool ratio=true,bool smear=false, bool scale=false, bool useR9Weight=false, TString pdfIndex=""){
  std::cout<<"Using macro/PlotDataMC.C:: PlotDataMCs"<<std::endl;
  TStopwatch watch;
  watch.Start();
  //gStyle->SetOptStat(11);

  int nHist= mc_vec.size();
  int colors[4]={kRed,kGreen,kBlue,kCyan};
  int fillstyle[4]={0,0,0,0}; //3003,3004,3005,3006};
  if(nHist>4) return NULL;
  TString yLabel; 
  
  TCanvas *c = new TCanvas("c","");
  TPad * pad1 = new TPad("pad1", "pad1",0.01,0.13,0.75,1.);  
  TPad * pad2 = new TPad("pad2", "pad2",0.01,0.001,0.75,0.2);  
  TPad * pad3 = new TPad("pad3", "pad3",0.68,0.001,1.,0.2);
  
  pad1->SetRightMargin(0.1);
  pad1->SetLogy();
  pad1->Draw();
  pad1->cd();
  
  pad2->SetGrid();
  pad2->SetBottomMargin(0.4);
  pad2->SetRightMargin(0.1);
  pad2->Draw();
  pad2->cd();
  
  pad3->SetGrid();    
  //pad2->SetTopMargin(0.01);
  pad3->SetBottomMargin(0.4);
  pad3->SetRightMargin(0.1);
  pad3->Draw();
  pad3->cd();
    
  pad1->cd();
  
  TString branchNameData=branchname;
  TString branchNameMC=branchname;

  ElectronCategory_class cutter;
  data->SetBranchStatus("*",0);
  std::set<TString> branchList = cutter.GetBranchNameNtuple(category);
   for(std::set<TString>::const_iterator itr = branchList.begin();
       itr != branchList.end();
       itr++){
     std::cout << "[STATUS] Enabling branch: " << *itr << std::endl;
     data->SetBranchStatus(*itr, 1);
   }
   data->SetBranchStatus(branchname, 1);
   data->SetBranchStatus("scaleEle", 1);

  if(branchNameData.Contains("energySCEle_regrCorrSemiParV5_pho")) cutter.energyBranchName="energySCEle_regrCorrSemiParV5_pho";
  else if(branchNameData.Contains("energySCEle_regrCorrSemiParV5_ele")) cutter.energyBranchName="energySCEle_regrCorrSemiParV5_ele";
  else if (branchNameData.Contains("energySCEle")) cutter.energyBranchName="energySCEle";

  TCut selection_data="";
  if(category.Sizeof()>1) selection_data = cutter.GetCut(category, false,0,scale);
  selection_data+=selection;
  TCut selection_MC="";
  if(category.Sizeof()>1) selection_MC = cutter.GetCut(category, false,0);
  selection_MC+=selection;

  if(smear){
    std::cout<<"Apply smear to the MC"<<std::endl;
    branchNameMC.ReplaceAll("invMass_SC_corr","(invMass_SC_corr*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("invMass_SC_regrCorr_pho","(invMass_SC_regrCorr_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("invMass_SC_regrCorrSemiParV5_pho","(invMass_SC_regrCorrSemiParV5_pho*sqrt(smearEle[0]*smearEle[1]))");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho","(energySCEle_regrCorr_pho*smearEle) ");
    branchNameMC.ReplaceAll("energySCEle_corr[0]","(energySCEle_corr[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_corr[1]","(energySCEle_corr[1]*smearEle[1])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[0]","(energySCEle_regrCorr_pho[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorr_pho[1]","(energySCEle_regrCorr_pho[1]*smearEle[1])");
    branchNameMC.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[0]","(energySCEle_regrCorrSemiParV5_ele[0]*smearEle[0])");
    branchNameMC.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[1]","(energySCEle_regrCorrSemiParV5_ele[1]*smearEle[1])");
    if(!branchNameMC.Contains("smear")) branchNameMC.ReplaceAll("energySCEle_regrCorrSemiParV5_ele","(energySCEle_regrCorrSemiParV5_ele*smearEle)");

  }
  if(scale){
    std::cout << "Apply scale to the data" << std::endl;
    branchNameData.ReplaceAll("invMass_SC_corr","(invMass_SC_corr*sqrt(scaleEle[0]*scaleEle[1]))");
    branchNameData.ReplaceAll("invMass_SC_regrCorr_pho","(invMass_SC_regrCorr_pho*sqrt(scaleEle[0]*scaleEle[1]))");
    branchNameData.ReplaceAll("invMass_SC_regrCorrSemiParV5_pho","(invMass_SC_regrCorrSemiParV5_pho*sqrt(scaleEle[0]*scaleEle[1]))");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_pho ","(energySCEle_regrCorrSemiParV5_pho*scaleEle)");
    branchNameData.ReplaceAll("energySCEle_corr[0]","(energySCEle_corr*scaleEle[0])");
    branchNameData.ReplaceAll("energySCEle_corr[1]","(energySCEle_corr*scaleEle[1])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_pho[0]","(energySCEle_regrCorrSemiParV5_pho[0]*scaleEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_pho[1]","(energySCEle_regrCorrSemiParV5_pho[1]*scaleEle[1])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[0]","(energySCEle_regrCorrSemiParV5_ele[0]*scaleEle[0])");
    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_ele[1]","(energySCEle_regrCorrSemiParV5_ele[1]*scaleEle[1])");
    if(!branchNameData.Contains("scale"))    branchNameData.ReplaceAll("energySCEle_regrCorrSemiParV5_ele","(energySCEle_regrCorrSemiParV5_ele*scaleEle)");
  }    

  std::cout <<"For data you are plotting: "<<branchNameData <<std::endl;
  std::cout <<"For MC your are plotting:  " << branchNameMC << std::endl;
  std::cout << "Selection for data is "<<selection_data<<std::endl;
  std::cout << "binning is "<<binning<<std::endl;
  
  // Draw histograms
    data->Draw(branchNameData+">>data_hist"+binning, selection_data);
    if(nHist > 0){//for MC
      for(std::vector<TChain *>::const_iterator mc_itr = mc_vec.begin();
	  mc_itr != mc_vec.end();
	  mc_itr++){
	TChain *mc = *mc_itr;
 	mc->SetBranchStatus("*",0);
 	for(std::set<TString>::const_iterator itr = branchList.begin();
 	    itr != branchList.end();
 	    itr++){
 	  //std::cout << "[STATUS] Enabling branch: " << *itr << std::endl;
 	  mc->SetBranchStatus(*itr, 1);
 	}
	mc->SetBranchStatus(branchname, 1);
	mc->SetBranchStatus("smearEle", 1);
	mc->SetBranchStatus("puWeight",1);
	mc->SetBranchStatus("mcGenWeight", 1);
	mc->SetBranchStatus("r9Weight", 1);
 	

	TString mcHistName;  mcHistName+="hist_"; mcHistName+=mc_itr-mc_vec.begin();//better for .C generation
	//TString mcHistName; mcHistName+=mc_itr-mc_vec.begin(); mcHistName+="_hist";//better for .C generation
	
	//decide this for MC
	//TString weights="mcGenWeight";
	//if(pdfIndex!="") weights+="*(pdfWeights_cteq66["+pdfIndex+"]/pdfWeights_cteq66[0])";
	//if(usePU) weights+="*puWeight";
	//if(useR9Weight) weights+="*r9Weight";
	//std::cout<<"Complete selection for MC is "<<selection_MC *weights.Data()<<std::endl;
	//mc->Draw(branchNameMC+">>"+mcHistName+binning, selection_MC *weights.Data());
	mc->Draw(branchNameMC+">>"+mcHistName+binning, selection_MC);
      }
    }


  c->Clear();
  TLegend *leg = new TLegend(0.5,0.7,0.7,0.85);
  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  leg->SetTextSize(0.04);
//   if(dataLabel !="" && mcLabel !="") leg->Draw();
//   //c->GetListOfPrimitives()->Add(leg,"");


  TH1F *d = (TH1F *) gROOT->FindObject("data_hist");
  if(dataLabel !="") leg->AddEntry(d,dataLabel,"p");
  d->SetStats(0);
  d->SetTitle("");

  d->SetMarkerStyle(20);
  d->SetMarkerSize(1);

  if(d->GetEntries()==0 || d->Integral()==0){
    //d=(TH1F *) gROOT->FindObject("0_hist");
    d=(TH1F *) gROOT->FindObject("hist_0");
    d->SetMarkerSize(0);
  }
  //d->SaveAs("tmp/d_hist.root");
  //s->SaveAs("tmp/s_hist.root");

  yLabel.Form("Events /(%.2f %s)", d->GetBinWidth(2), yLabelUnit.Data());
  
  std::cout << "nEvents data: " << d->Integral() << "\t" << d->GetEntries() << std::endl;
  std::cout << "Now normalizing data to 1: "<<std::endl;
  std::cout << "80 is in bin "<<d->FindBin(80)<<std::endl;
  std::cout << "100 is in bin "<<d->FindBin(100)<<std::endl;
  std::cout << "d integral is "<<d->Integral()<<std::endl;
  std::cout << "d integral(1,100) is "<<d->Integral(1,100)<<std::endl;
  d->Scale(1./d->Integral());
  float max = 0;
  max=1.2*d->GetMaximum();
  std::cout << "max = " << max << std::endl;  

  d->GetYaxis()->SetTitle(yLabel);
  d->GetXaxis()->SetTitle(xLabel);
  if(logy){
    max*=10;
    d->GetYaxis()->SetRangeUser(0.1,max);
    c->SetLogy();
  } else {
      d->GetYaxis()->SetRangeUser(0,max);
  }

  for(int i=0; i < nHist; i++){
    //TString mcHistName; mcHistName+=i; mcHistName+="_hist";
    TString mcHistName; mcHistName+="hist_";mcHistName+=i;
    TH1F *s = (TH1F *) gROOT->FindObject(mcHistName);
    s->SetStats(0);
    s->SetTitle("");
    if(s==NULL) continue;
    std::cout << "nEvents signal: " << s->Integral() << "\t" << s->GetEntries() << std::endl;
    if(d->Integral()==0 && s->Integral()==0){
      delete c;
      return NULL;
    }
    if(logy){
      s->GetYaxis()->SetRangeUser(0.1,max);
    } else {
      s->GetYaxis()->SetRangeUser(0,max);
    }
    s->GetYaxis()->SetTitle(yLabel);
    s->GetXaxis()->SetTitle(xLabel);

    s->SetMarkerStyle(20);
    s->SetMarkerSize(1);
    s->SetMarkerColor(colors[i]);
    s->SetFillStyle(fillstyle[i]);
    s->SetFillColor(colors[i]);
    s->SetLineColor(colors[i]);
    s->SetLineWidth(2);

    TH1F* s_norm = NULL;
    if(i==0) s_norm = (TH1F *) (s->DrawNormalized("hist", d->Integral()));
    else s_norm = (TH1F *) (s->DrawNormalized("hist same", d->Integral()));
    if(logy){
      //d_norm->GetYaxis()->SetRangeUser(0.1,max);
      s_norm->GetYaxis()->SetRangeUser(0.1,max);
    } else {
      //d_norm->GetYaxis()->SetRangeUser(0,max);  
      s_norm->GetYaxis()->SetRangeUser(0,max);  
    }

    if(mcLabel_vec[i] !="") leg->AddEntry(s,mcLabel_vec[i], "lf");

//     TH1F *sRatio = (TH1F *) s->Clone(mcHistName+"_ratio");
//     sRatio->Divide(d);
//     if(ratio){
//       pad2->cd();
//       if(i==0) sRatio->Draw();
//       else sRatio->Draw("same");
//     }
//     pad1->cd();
  }

  //TH1F* d_norm = s_norm;
  //if(d!=s) d_norm = (TH1F *) (d->DrawNormalized("p same", d->Integral()));
  std::cout<<"After normalization "<<std::endl;
  //std::cout<<"s_norm" <<s_norm->Integral()<<std::endl;
  std::cout<<"data Integral " <<d->Integral()<<std::endl;
  if(nHist>0) d->Draw("p same");
  else d->Draw("p");

//   std::cout << "Variable  & Data & Simulation \\" << std::endl;
//   std::cout << "Mean      & " << d->GetMean() << " " << d->GetMeanError() 
// 	    << " & " << s_norm->GetMean() <<  " " << s_norm->GetMeanError() << " \\" << std::endl;
//   std::cout << "Std. dev. & " << d->GetRMS() << " " << d->GetRMSError() 
// 	    << " & " << s_norm->GetRMS() << " " << s_norm->GetRMSError() << " \\" << std::endl;
//   std::cout << "\\hline" << std::endl;
//   std::cout << "$\\Chi^2$ " <<  d->Chi2Test(s_norm, "UW CHI2/NDF NORM") << std::endl;
  
  if(mcLabel_vec.size()!=0) leg->Draw();

  TPaveText *pv = new TPaveText(0.25,0.95,0.65,1,"NDC");
  pv->AddText("CMS Preliminary 2016");
  pv->SetFillColor(0);
  pv->SetBorderSize(0);
  pv->Draw();

  watch.Stop();
  watch.Print();

  c->SaveAs(outputPath+label4Print+".png","png");
  c->SaveAs(outputPath+label4Print+".pdf","pdf");
  c->SaveAs(outputPath+label4Print+".eps","eps");
  c->SaveAs(outputPath+label4Print+".C","C");

  return c;

}
Example #27
0
void makeStack(TString myVar, TString myCut, TString myName, TString myAxisNameX, TString myAxisNameY, 
               vector<const Sample*>& listOfSignals, vector<const Sample*>& listOfSamples, vector<const Sample*> listOfDatasets, 
               TString inFileName,
               bool isBlind, bool isLog, bool drawSignal, bool drawLegend,
               int nBins, float xLow, float xHigh,
               float* xlowVec)
{
  // prepare the input file
  TFile* infile = new TFile(inFileName, "READ"); 
  infile -> cd();
  
  // prepare the stack
  THStack *hs = new THStack("hs","");
  // prepare the histos pointers
  TH1F*   hist[20];
  // prepare the tree pointers
  TTree*  tree[20];
  // prepare the legend
  TLegend* leg = new TLegend(.7485,.7225,.9597,.9604);
  leg->SetFillColor(0);
  // prepare the colors
  Int_t col[20] = {46,2,12,5,3,4,9,7,47,49,49,50,51,52,53,54,55,56,57,58};
  // prepare the cut
  if (isBlind) myCut += "*(phoMetDeltaPhi < 2.9)";        
  // prepare the Y axis lable
  if (xlowVec != 0) myAxisNameY = "Events/" + myAxisNameY;
  else {
    float binWidth = (xHigh-xLow)/nBins;
    TString tempString;
    tempString.Form("%.2f ",binWidth); 
    myAxisNameY = "Events/" + tempString + myAxisNameY;
  }
  // prepare the legend strings
  vector<TString> theLegends;
  
  // loop through the datasets and produce the plots
  TH1F* hdata;
  TH1F* hsignal;
  //prepare data and signal histos
  if (xlowVec != 0) hdata   = new TH1F("hdata","",nBins,xlowVec);
  else hdata = new TH1F("hdata","",nBins,xLow,xHigh);
  if (xlowVec != 0) hsignal = new TH1F("hsignal","",nBins,xlowVec);
  else hsignal = new TH1F("hsignal","",nBins,xLow,xHigh);

  TTree*  treedata[20];
  for (UInt_t iDatas=0; iDatas < listOfDatasets.size(); iDatas++) {
    //get the tree
    treedata[iDatas] = (TTree*) infile -> Get(listOfDatasets.at(iDatas)->Name()->Data());

    //fill the histogram
    if ( iDatas == 0 ) treedata[iDatas] -> Draw(myVar + " >> hdata","evt_weight*kf_weight*pu_weight" + myCut);
    else treedata[iDatas] -> Draw(myVar + " >>+ hdata","evt_weight*kf_weight*pu_weight" + myCut);
    
    if ( isBlind && iDatas == 0 ) leg -> AddEntry(hdata, "DATA (19.8 fb^{-1})", "pl");    
    
  }//end loop on datasets
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinError  (iBin,hdata->GetBinError(iBin)/hdata->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinContent(iBin,hdata->GetBinContent(iBin)/hdata->GetBinWidth(iBin));
  }

  TTree*  treesignal[20];
  for (UInt_t iSignal=0; iSignal < listOfSignals.size(); iSignal++) {
    //get the tree
    treesignal[iSignal] = (TTree*) infile -> Get(listOfSignals.at(iSignal)->Name()->Data());

    //fill the histogram
    TString thisScale = Form("%f *", *(listOfSignals.at(iSignal)->Scale()));
    if ( iSignal == 0 ) treesignal[iSignal] -> Draw(myVar + " >> hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    else treesignal[iSignal] -> Draw(myVar + " >>+ hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    
    if ( drawSignal && iSignal == 0 ) leg -> AddEntry(hsignal, "Signal", "l");    
    
  }//end loop on signals
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinError  (iBin,hsignal->GetBinError(iBin)/hsignal->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinContent(iBin,hsignal->GetBinContent(iBin)/hsignal->GetBinWidth(iBin));
  }
  hsignal -> SetLineColor(49);
  hsignal -> SetLineWidth(4.0);
       
  int theHistCounter = 0;
  // loop through the samples and produce the plots
  for (UInt_t iSample=0; iSample < listOfSamples.size(); iSample++) {

    //determine if the histo is first of the series
    bool isFirstOfSerie = (*listOfSamples.at(iSample)->Legend()).CompareTo(" ");
    bool isLastOfSerie = false;
    if (iSample == listOfSamples.size() - 1) isLastOfSerie = true;
    if (iSample < listOfSamples.size() - 1 && (*listOfSamples.at(iSample+1)->Legend()).CompareTo(" ") != 0) isLastOfSerie = true;
    
    //get the tree
    tree[iSample] = (TTree*) infile -> Get(listOfSamples.at(iSample)->Name()->Data());
    //if sample first of the list create a new histogram
    if (isFirstOfSerie) {
       TString thisHistName = "h_" + *(listOfSamples.at(iSample)->Name());
       //variable bin histo
       if (xlowVec != 0) hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xlowVec);
       //fixed bin histo
       else hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xLow,xHigh);
       hist[theHistCounter] -> Sumw2();
       hist[theHistCounter] -> SetFillColor(col[theHistCounter]);
       hist[theHistCounter] -> SetFillStyle(1001);
       theLegends.push_back(*listOfSamples.at(iSample)->Legend());
    }

    //fill the histogram
    TString thisScale = Form("%f *", *(listOfSamples.at(iSample)->Scale()));
    if (isFirstOfSerie) tree[iSample] -> Draw(myVar + " >> " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    else tree[iSample] -> Draw(myVar + " >>+ " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    
    //add the histogram to the stack if the last of the series:
    //either last sample or ~ sample followed by non ~ sample
    if (isLastOfSerie) {
       if (xlowVec != 0) {
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinError  (iBin,hist[theHistCounter]->GetBinError(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinContent(iBin,hist[theHistCounter]->GetBinContent(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
       }
       hs -> Add(hist[theHistCounter]);
       theHistCounter++;
    }
    
  }//end loop on samples

  //Fix the legend
  for (int iHisto = theHistCounter-1; iHisto >= 0; iHisto--) {
    leg -> AddEntry(hist[iHisto], theLegends[iHisto], "f");   
  }
  
  //get the maximum to properly set the frame
  float theMax = hdata -> GetBinContent(hdata -> GetMaximumBin()) + hdata -> GetBinError(hdata -> GetMaximumBin());
  TH1* theMCSum = (TH1*) hs->GetStack()->Last();
  float theMaxMC = theMCSum->GetBinContent(theMCSum->GetMaximumBin()) + theMCSum->GetBinError(theMCSum->GetMaximumBin());
  if (theMaxMC > theMax) theMax = theMaxMC;
  
  //prepare the ratio band and plot
  TH1* theMCRatioBand = makeRatioBand(theMCSum);
  TH1* theRatioPlot = makeRatioPlot(hdata,theMCSum);
    
  TCanvas* can = new TCanvas();
  can -> SetLogy(isLog);
  
  TPad *pad1 = new TPad("pad1","top pad",0,0.30,1,1);
  pad1->SetBottomMargin(0.02);
  pad1->SetLeftMargin(0.13);
  pad1->Draw();
  TPad *pad2 = new TPad("pad2","bottom pad",0,0.0,1,0.30);
  pad2->SetTopMargin(0.02);
  pad2->SetLeftMargin(0.13);
  pad2->SetBottomMargin(0.4);
  pad2->SetGridy();
  pad2->Draw();
  
  pad1->cd();
  hs->Draw("hist");
  hdata->Draw("same,pe");
  if (drawSignal) hsignal->Draw("same,hist");
  if (drawLegend) leg->Draw("same");
  //hs->GetXaxis()->SetTitle(myAxisNameX);
  hs->GetYaxis()->SetTitle(myAxisNameY);
  hs->GetXaxis()->SetLabelSize(0.04);
  hs->GetYaxis()->SetLabelSize(0.04);
  hs->GetXaxis()->SetLabelOffset(0.025);
  hs->GetYaxis()->SetLabelOffset(0.035);
  //hs->GetXaxis()->SetTitleOffset(1.1);
  hs->GetYaxis()->SetTitleOffset(1.1);
  hs->SetMaximum(theMax);
  if (isLog) hs->SetMinimum(0.01);
  
  pad2->cd();
  theMCRatioBand->GetXaxis()->SetTitle(myAxisNameX);
  theMCRatioBand->GetXaxis()->SetTitleSize(0.16);
  theMCRatioBand->GetXaxis()->SetTitleOffset(1.1);
  theMCRatioBand->GetXaxis()->SetLabelSize(0.12);
  theMCRatioBand->GetXaxis()->SetLabelOffset(0.07);
  theMCRatioBand->GetYaxis()->SetTitle("Data/MC");
  theMCRatioBand->GetYaxis()->SetTitleSize(0.10);
  theMCRatioBand->GetYaxis()->SetTitleOffset(0.6);
  theMCRatioBand->GetYaxis()->SetLabelSize(0.06);
  theMCRatioBand->GetYaxis()->SetLabelOffset(0.03);
  theMCRatioBand->SetFillStyle(3001);
  theMCRatioBand->SetFillColor(kBlue);
  theMCRatioBand->SetLineWidth(1);
  theMCRatioBand->SetLineColor(kBlack);
  theMCRatioBand->SetMarkerSize(0.1);
  theMCRatioBand->SetMaximum(4.);
  theMCRatioBand->SetMinimum(0.);
  theMCRatioBand->Draw("E2");
  TLine *line = new TLine(xLow,1,xHigh,1);
  line->SetLineColor(kBlack);
  line->Draw("same");
  theRatioPlot->Draw("same,pe");
  
  can->cd();
  can->Modified();
  can -> SaveAs(myName + ".pdf","pdf");
  
  //cleanup the memory allocation
  delete theMCSum;
  delete hs;
  delete leg;
  delete hdata;
  delete pad1;
  delete pad2;
  delete can;
  delete theMCRatioBand;
  delete theRatioPlot;
  infile -> Close();
  delete infile;
  
  return;
}
Example #28
0
void Unfold2(int algo= 3,bool useSpectraFromFile=0, bool useMatrixFromFile=0, int doToy = 0, int isMC = 0,char *spectraFileName = (char*)"pbpb_spectra_akPu3PF.root",double recoJetPtCut = 60.,double trackMaxPtCut = 0, int nBayesianIter = 4, int doBjets=1, int doTrigEffCorr=1) // algo 2 =akpu2 ; 3 =akpu3 ; 4 =akpu4 ;1 = icpu5
{
  
  gStyle->SetErrorX(0.);
  gStyle->SetPaintTextFormat("3.2f");
  gStyle->SetOptLogz(1);
  gStyle->SetPadRightMargin(0.13);	
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);


  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  
  // input files
  char *fileNamePP_mc = NULL;
  char *fileNamePbPb_mc = NULL;
  char *fileNamePP_data = NULL;
  char *fileNamePbPb_data = NULL;
  

  // pp file needs replacing
  if(doBjets)fileNamePP_data = (char*)"~/Work/bTagging/outputTowardsFinal/NewFormatV5_bFractionMCTemplate_pppp1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root";
  //else fileNamePP_data = (char*)"../spectra/rawIncSpectra_MB_fixedBinSize_v4.root";
  else fileNamePP_data = (char*)"../spectra/rawIncSpectra_MB_varBinSize_v4.root";
  //if(doBjets)fileNamePbPb_data = (char*)"~/Work/bTagging/outputTowardsFinal/AltBinningV6_bFractionMCTemplate_ppPbPb1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root";
  if(doBjets)fileNamePbPb_data = (char*)"~/Work/bTagging/outputTowardsFinal/bFractionMCTemplate_ppPbPb1_SSVHEat2.0FixCL0_bin_0_40_eta_0_2_binomErrors_jet55_wideBin_v2.root";
  //else fileNamePbPb_data = (char*)"../spectra/rawIncSpectra_MB_fixedBinSize_v4.root";
  else fileNamePbPb_data = (char*)"../spectra/rawIncSpectra_MB_varBinSize_v4.root";
  if(doBjets) fileNamePP_mc = (char*)"~/Work/bTagging/histos/ppMC_ppReco_ak3PF_BjetTrig_noIPupperCut.root";
  else fileNamePP_mc = (char*)"~/Work/bTagging/histos/ppMC_ppReco_ak3PF_QCDjetTrig_noIPupperCut.root";
  if(doBjets)fileNamePbPb_mc = (char*) "~/Work/bTagging/histos/PbPbBMC_pt30by3_ipHICalibCentWeight_noTrig.root";
  else fileNamePbPb_mc = (char*) "~/Work/bTagging/histos/PbPbQCDMC_pt30by3_ipHICalibCentWeight_noTrig.root";


  // grab ntuples
  TFile *infPbPb_mc = new TFile(fileNamePbPb_mc);
  TFile *infPP_mc = new TFile(fileNamePP_mc);
  

  string bJetString = "Inc";
  if(doBjets) bJetString = "bJets";

  // Output file
  TFile *pbpb_Unfo;
  if (isMC) pbpb_Unfo = new TFile(Form("pbpb_Unfo_%s_MC_v2.root",algoName[algo]),"RECREATE");
  else pbpb_Unfo  = new TFile(Form("pbpb_Unfo_%s_jtpt%.0f_%s_v4.root",algoName[algo],recoJetPtCut,bJetString.c_str()),"RECREATE");

  // Histograms used by RooUnfold
  UnfoldingHistos *uhist[nbins_cent+1];
		
  // Initialize Histograms   
	
  for (int i=0;i<=nbins_cent;i++) uhist[i] = new UnfoldingHistos(i);
	
  // Initialize reweighting functions
  /*
  TCut dataSelection;
  TCut dataSelectionPP;
  TCut TriggerSelectionPP;
  TCut TriggerSelectionPbPb80;

  if(doBjets)dataSelection = "weight*(abs(refparton_flavorForB)==5&&abs(jteta)<2)";
  else dataSelection = "weight*(abs(jteta)<2)";
  */

  if (isMC) cout<<"This is a MC closure test"<<endl;
  else cout<< "This is a data analysis"<<endl;    		     
	     	
  // Setup jet data branches, basically the jet tree branches are assigned to this object when we loop over the events
	
  JetDataPbPb *dataPbPb   = new JetDataPbPb(fileNamePbPb_mc,(char*)"nt"); // PbPb data	
  JetDataPP *dataPP = new JetDataPP(fileNamePP_mc,(char*)"nt");	// pp data
	
  TFile *fSpectra(0);		
  if (useSpectraFromFile||useMatrixFromFile){
    fSpectra = new TFile(spectraFileName,"read");
  }
  
  // Come back to the output file dir
  pbpb_Unfo->cd();

  cout <<"MC..."<<endl;	
  
  TH1F *hCent = new TH1F("hCent","",nbins_cent,boundaries_cent);
 

  // if you change the binning you have to change these, too
  // inclusive trig eff
  /*
    float trigEffInc[6]={0.777265,
			 0.95765,
			 0.998357,
			 0.999941,
			 1.,
			 1.};
  */

    // b-jet trig eff
    /*
    float trigEffbJet[6]={0.660276,
		      0.908997,
		      0.980793,
		      0.998767,
		      0.999442,
		      1.};
    */



 
		
  // Fill PbPb MC   
  if (!useMatrixFromFile) {
    for (Long64_t jentry2=0; jentry2<dataPbPb->tJet->GetEntries();jentry2++) {
      dataPbPb->tJet->GetEntry(jentry2);
      
      // change when we switch to centrality binning
      int cBin = 0;
            
      if ( dataPbPb->refpt  < 0. ) continue;
      if ( dataPbPb->jteta  > 2. || dataPbPb->jteta < -2. ) continue;
      if ( dataPbPb->refpt<0) dataPbPb->refpt=0;
      if (doBjets && fabs(dataPbPb->refparton_flavorForB)!=5) continue;
      //if (doBjets&& dataPbPb->discr_ssvHighEff<2) continue;
      if (doBjets && dataPbPb->jtptB < recoJetPtCut) continue;
      if (!doBjets && dataPbPb->jtptA < recoJetPtCut) continue;
      //if (!doTrigEffCorr && dataPbPb->isTrig <1) continue;
      if ( dataPbPb->isTrig <1) continue;
      
      //if(!doBjets)if(dataPbPb->refpt < 50 && dataPbPb->jtptA>120) continue;
      //if(doBjets)if(dataPbPb->refpt < 50 && dataPbPb->jtptB>120) continue;

      float weight = dataPbPb->weight;

      if(doTrigEffCorr){
	for(int iBin = 0; iBin<nbins_rec; iBin++){
	  float myJtPt = 0.;
	  if(doBjets) myJtPt = dataPbPb->jtptB;
	  else myJtPt = dataPbPb->jtptA;
	  if(myJtPt > boundaries_rec[iBin] && myJtPt < boundaries_rec[iBin+1]){
	    if(doBjets) weight/= trigEffbJet[iBin];
	    else weight/= trigEffInc[iBin];
	  }							  
	}
      }
      if (!isMC||jentry2 % 2 == 1) {
	if(doBjets)uhist[cBin]-> hMatrix->Fill(dataPbPb->refpt,dataPbPb->jtptB,weight);
	else uhist[cBin]-> hMatrix->Fill(dataPbPb->refpt,dataPbPb->jtptA,weight);
      }	  
      if (jentry2 % 2 == 0) {
	uhist[cBin]-> hGen->Fill(dataPbPb->refpt,weight);   
	if(doBjets)uhist[cBin]-> hMeas->Fill(dataPbPb->jtptB,weight);  	 
	else uhist[cBin]-> hMeas->Fill(dataPbPb->jtptA,weight);  	 
	//uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtpt*(1.+0.02/nbins_cent*(nbins_cent-i)),weight); 
	// FIXME!!!!!!  i is supposed to be a loop over centrality !!!!
	if(doBjets)uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtptB*(1.+0.02/nbins_cent*(nbins_cent-0)),weight); 
	else uhist[cBin]-> hMeasJECSys->Fill(dataPbPb->jtptA*(1.+0.02/nbins_cent*(nbins_cent-0)),weight); 
      }
    }

    //pp will just fill the last index of the centrality array

    // fill pp MC
    for (Long64_t jentry2=0; jentry2<dataPP->tJet->GetEntries();jentry2++) {
      dataPP->tJet->GetEntry(jentry2);
      
      if ( dataPP->refpt<0) continue;
      if ( dataPP->jteta  > 2. || dataPP->jteta < -2. ) continue;
      if ( dataPP->refpt<0) dataPP->refpt=0;
      if ( doBjets && fabs(dataPP->refparton_flavorForB)!=5) continue;
      //if ( doBjets && dataPP->discr_ssvHighEff<2) continue;
      if ( dataPP->jtpt < recoJetPtCut) continue;
      
      if (!isMC||jentry2 % 2 == 1) {
	uhist[nbins_cent]-> hMatrix->Fill(dataPP->refpt,dataPP->jtpt,dataPP->weight);
      }	  
      if (jentry2 % 2 == 0) {
	uhist[nbins_cent]-> hGen->Fill(dataPP->refpt,dataPP->weight);   
	uhist[nbins_cent]-> hMeas->Fill(dataPP->jtpt,dataPP->weight); 
      }           
    }
  }
  /*
  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	float binContent = uhist[i]->hGen->GetBinContent(x);
	float binError = uhist[i]->hGen->GetBinError(x);
	float binWidth =  uhist[i]->hGen->GetXaxis()->GetBinWidth(x);
	uhist[i]->hGen->SetBinContent(x,binContent/binWidth);
	uhist[i]->hGen->SetBinError(x,binError/binWidth);
    }
  }

<<<<<<< HEAD
  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	float binContent = uhist[i]->hMeas->GetBinContent(x);
	float binError = uhist[i]->hMeas->GetBinError(x);
	float binWidth =  uhist[i]->hMeas->GetXaxis()->GetBinWidth(x);
	uhist[i]->hMeas->SetBinContent(x,binContent/binWidth);
	uhist[i]->hMeas->SetBinError(x,binError/binWidth);
    }
  }

  for (int i=0;i<=nbins_cent;i++){
    for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
      for (int y=1;y<=uhist[i]->hMatrix->GetNbinsY();y++) {
	float binContent = uhist[i]->hMatrix->GetBinContent(x,y);
	float binError = uhist[i]->hMatrix->GetBinError(x,y);
	float binWidth2 =  uhist[i]->hMatrix->GetXaxis()->GetBinWidth(x)*uhist[i]->hMatrix->GetYaxis()->GetBinWidth(y);
	uhist[i]->hMatrix->SetBinContent(x,y,binContent/binWidth2);
	uhist[i]->hMatrix->SetBinError(x,y,binError/binWidth2);
      }      
    }
  }	
  */


  if (isMC==0) {
    // Use measured histogram from Matt & Kurt's file
	   
    // PbPb file:

    TFile *infMatt = new TFile(fileNamePbPb_data);
    TH1F *hMattPbPb = NULL;
    TH1F *hTagEffPbPb = NULL;

    if(doBjets){
      hMattPbPb = (TH1F*) infMatt->Get("hRawBData");
      hTagEffPbPb = (TH1F*) infMatt->Get("hBEfficiencyMC");
    }
    else hMattPbPb = (TH1F*) infMatt->Get("hPbPb");
    //divideBinWidth(hMattPbPb);
           
    // Need to match the binning carefully, please double check whenever you change the binning
    for (int i=1;i<=hMattPbPb->GetNbinsX();i++)
      {
     	float binContent = hMattPbPb->GetBinContent(i);  
	float binError = hMattPbPb->GetBinError(i); 

	if(doBjets){
	  float tagEff =hTagEffPbPb->GetBinContent(i);
	  float tagEffErr =     hTagEffPbPb->GetBinError(i);   
	  
	  if(tagEff>0){
	    // careful of the order here!
	    binError=binContent/tagEff *sqrt(tagEffErr*tagEffErr/tagEff/tagEff + binError*binError/binContent/binContent);
	    binContent /= tagEff;
	  }
	  else cout<<" TAGEFF = 0"<<endl;	  
	}

	float binCenter = hMattPbPb->GetBinCenter(i);  
	if(binCenter - hMattPbPb->GetBinWidth(i)/2.  < recoJetPtCut) continue;
	
	int ibin=0;
	
	for(ibin=1;ibin<=uhist[0]->hMeas->GetNbinsX();ibin++){
	  float testLowEdge = uhist[0]->hMeas->GetBinLowEdge(ibin);
	  float testBinWidth = uhist[0]->hMeas->GetBinWidth(ibin);
	  if(binCenter>testLowEdge && binCenter < testLowEdge+testBinWidth) break;
	}
	
	
	if(doTrigEffCorr){
	  float trigEff = 0;
	  if(doBjets) trigEff = trigEffbJet[ibin-1];
	  else  trigEff = trigEffInc[ibin-1];

	  cout<<" binCenter = "<<binCenter<<" trigEff "<<trigEff<<endl;

	  if(trigEff>0){
	    // careful of the order here!
	    binContent /= trigEff;
	    binError /= trigEff;
	  }
	  else cout<<" TRIGEFF = 0"<<endl;	  
	}


     
	uhist[0]->hMeas->SetBinContent(ibin,binContent);  
	uhist[0]->hMeas->SetBinError(ibin,binError);  

      }

    // pp file:
    TFile *infMattPP = new TFile(fileNamePP_data);
    TH1F *hMattPP = NULL;
    TH1F *hTagEffPP = NULL;
    if(doBjets){
      hMattPP = (TH1F*) infMattPP->Get("hRawBData");
      hTagEffPP = (TH1F*) infMattPP->Get("hBEfficiencyMC");
    }
    else hMattPP = (TH1F*) infMattPP->Get("hpp");
    //divideBinWidth(hMattPP);	   
    for (int i=1;i<=hMattPP->GetNbinsX();i++)
      {
      	float binContent = hMattPP->GetBinContent(i);  
	float binError = hMattPP->GetBinError(i);  
	
	if(doBjets){
	  float tagEff =hTagEffPP->GetBinContent(i);
	  float tagEffErr =     hTagEffPP->GetBinError(i);   
	  if(tagEff>0){
	    // careful of the order here!
	    binError=binContent/tagEff *sqrt(tagEffErr*tagEffErr/tagEff/tagEff + binError*binError/binContent/binContent);
	    binContent /= tagEff;
	  }
	  else cout<<" TAGEFF = 0"<<endl;	  
	}
	
     	float binCenter = hMattPP->GetBinCenter(i);  
	if(binCenter - hMattPP->GetBinWidth(i)/2.  < recoJetPtCut) continue;

	int ibin=0;

	for(ibin=1;ibin<=uhist[nbins_cent]->hMeas->GetNbinsX();ibin++){
	  float testLowEdge = uhist[nbins_cent]->hMeas->GetBinLowEdge(ibin);
	  float testBinWidth = uhist[nbins_cent]->hMeas->GetBinWidth(ibin);
	  if(binCenter>testLowEdge && binCenter < testLowEdge+testBinWidth) break;
	}
	uhist[nbins_cent]->hMeas->SetBinContent(ibin,binContent);  
	uhist[nbins_cent]->hMeas->SetBinError(ibin,binError);  

    
	/*
	cout<<" i "<<i<<endl;
	int newBin = i+uhist[nbins_cent]->hMeas->FindBin(61)-1;

	cout<<" newBin "<<newBin<<endl;
	cout<<"hMattPP->GetBinCenter(i) "<<hMattPP->GetBinCenter(i)<<endl;
	cout<<"uhist[nbins_cent]->hMeas->GetBinCenter(newBin) "<<uhist[nbins_cent]->hMeas->GetBinCenter(newBin)<<endl;
	*/
      }

  }



   //=========================================Response Matrix========================================================= 

  cout <<"Response Matrix..."<<endl;
	
  TCanvas * cMatrix = new TCanvas("cMatrix","Matrix",800,400);
  cMatrix->Divide(2,1);

  for (int i=0;i<=nbins_cent;i++){
    cMatrix->cd(i+1);
    if (!useMatrixFromFile) {
      TF1 *f = new TF1("f","[0]*pow(x+[2],[1])");
      f->SetParameters(1e10,-8.8,40);
      for (int y=1;y<=uhist[i]->hMatrix->GetNbinsY();y++) {
	double sum=0;
	for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {
	  if (uhist[i]->hMatrix->GetBinContent(x,y)<=1*uhist[i]->hMatrix->GetBinError(x,y)) {
	    uhist[i]->hMatrix->SetBinContent(x,y,0);
	    uhist[i]->hMatrix->SetBinError(x,y,0);
	  }
	  sum+=uhist[i]->hMatrix->GetBinContent(x,y);
	}
				
	for (int x=1;x<=uhist[i]->hMatrix->GetNbinsX();x++) {	   
	  double ratio = 1;
	  uhist[i]->hMatrix->SetBinContent(x,y,uhist[i]->hMatrix->GetBinContent(x,y)*ratio);
	  uhist[i]->hMatrix->SetBinError(x,y,uhist[i]->hMatrix->GetBinError(x,y)*ratio);
	}
      }
    }
    uhist[i]->hResponse = (TH2F*)uhist[i]->hMatrix->Clone(Form("hResponse_cent%d",i));

    for (int y=1;y<=uhist[i]->hResponse->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {
	if (uhist[i]->hResponse->GetBinContent(x,y)<=0*uhist[i]->hResponse->GetBinError(x,y)) {
	  uhist[i]->hResponse->SetBinContent(x,y,0);
	  uhist[i]->hResponse->SetBinError(x,y,0);
	}
	sum+=uhist[i]->hResponse->GetBinContent(x,y);
      }
			
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {  	
	if (sum==0) continue;
	double ratio = uhist[i]->hMeas->GetBinContent(y)/sum;
	if (uhist[i]->hMeas->GetBinContent(y)==0) ratio = 1e-100/sum;
      }
    }
		
    TH1F *hProj = (TH1F*)uhist[i]->hResponse->ProjectionY(Form("hProj_cent%d",i));
    
    for (int y=1;y<=uhist[i]->hResponse->GetNbinsY();y++) {
      for (int x=1;x<=uhist[i]->hResponse->GetNbinsX();x++) {  	
	double sum=hProj->GetBinContent(y);
	cout <<y<<" "<<x<<" "<<sum<<endl;
	if (sum==0) continue;
	double ratio = uhist[i]->hMeas->GetBinContent(y)/sum;
	if (uhist[i]->hMeas->GetBinContent(y)==0) ratio = 1e-100/sum;
        uhist[i]->hResponse->SetBinContent(x,y,uhist[i]->hResponse->GetBinContent(x,y)*ratio);
	uhist[i]->hResponse->SetBinError(x,y,uhist[i]->hResponse->GetBinError(x,y)*ratio);
      }
    }

    uhist[i]->hResponseNorm = (TH2F*)uhist[i]->hMatrix->Clone(Form("hResponseNorm_cent%d",i));
    for (int x=1;x<=uhist[i]->hResponseNorm->GetNbinsX();x++) {
      double sum=0;
      for (int y=1;y<=uhist[i]->hResponseNorm->GetNbinsY();y++) {
	if (uhist[i]->hResponseNorm->GetBinContent(x,y)<=0*uhist[i]->hResponseNorm->GetBinError(x,y)) {
	  uhist[i]->hResponseNorm->SetBinContent(x,y,0);
	  uhist[i]->hResponseNorm->SetBinError(x,y,0);
	}
	sum+=uhist[i]->hResponseNorm->GetBinContent(x,y);
      }
			
      for (int y=1;y<=uhist[i]->hResponseNorm->GetNbinsY();y++) {  	
	if (sum==0) continue;
	double ratio = 1./sum;
	uhist[i]->hResponseNorm->SetBinContent(x,y,uhist[i]->hResponseNorm->GetBinContent(x,y)*ratio);
	uhist[i]->hResponseNorm->SetBinError(x,y,uhist[i]->hResponseNorm->GetBinError(x,y)*ratio);
      }
    }
		
    uhist[i]->hResponse->Draw("colz");
		
    if (!useMatrixFromFile) uhist[i]->hMatrixFit = uhist[i]->hMatrix;
    uhist[i]->hMatrixFit->SetName(Form("hMatrixFit_cent%d",i));
  }

  pbpb_Unfo->cd();
	
  cout << "==================================== UNFOLD ===================================" << endl;
	
  //char chmet[100]; 
	
  // ======================= Reconstructed pp and PbPb spectra =========================================================
  TCanvas * cPbPb = new TCanvas("cPbPb","Comparison",1200,600);
  cPbPb->Divide(2,1); 
  cPbPb->cd(1);
	
  TH1F *hRecoBW[nbins_cent+1], *hRecoBinByBinBW[nbins_cent+1], *hMeasBW[nbins_cent+1], *hGenBW[nbins_cent+1];


  TCanvas * cPbPbMeas = new TCanvas("cPbPbMeas","Measurement",1200,600);
  cPbPbMeas->Divide(2,1); 
  cPbPbMeas->cd(1);
	

  for (int i=0;i<=nbins_cent;i++) {
    cPbPb->cd(i+1)->SetLogy();   
    // Do Bin-by-bin
    TH1F *hBinByBinCorRaw = (TH1F*)uhist[i]->hResponse->ProjectionY(); 
    TH1F *hMCGen           = (TH1F*)uhist[i]->hResponse->ProjectionX(); // gen
    hBinByBinCorRaw->Divide(hMCGen);
    TF1 *f = new TF1("f","[0]+[1]*x");
    hBinByBinCorRaw->Fit("f","LL ","",90,300);
    TH1F* hBinByBinCor = (TH1F*)hBinByBinCorRaw->Clone();//functionHist(f,hBinByBinCorRaw,Form("hBinByBinCor_cent%d",i));
    uhist[i]->hRecoBinByBin = (TH1F*) uhist[i]->hMeas->Clone(Form("hRecoBinByBin_cent%d",i));
    uhist[i]->hRecoBinByBin->Divide(hBinByBinCor);
		
    // Do unfolding
    //if (isMC) uhist[i]->hMeas = (TH1F*)uhist[i]->hMatrix->ProjectionY()->Clone(Form("hMeas_cent%d",i));
    prior myPrior(uhist[i]->hMatrixFit,uhist[i]->hMeas,0);
    myPrior.unfold(uhist[i]->hMeas,1);
    TH1F *hPrior;//=(TH1F*) functionHist(fPow,uhist[i]->hMeas,Form("hPrior_cent%d",i));
//    hPrior = (TH1F*)uhist[i]->hGen->Clone("hPrior");
//    hPrior = (TH1F*)uhist[i]->hMeas->Clone(Form("hPrior_cent%d",i));
    hPrior=(TH1F*)hMCGen->Clone("hPrior");
    removeZero(hPrior);
    TH1F *hReweighted = (TH1F*)(TH1F*)uhist[i]->hResponse->ProjectionY(Form("hReweighted_cent%d",i));
		
    bayesianUnfold myUnfoldingJECSys(uhist[i]->hMatrixFit,hPrior,0);
    myUnfoldingJECSys.unfold(uhist[i]->hMeasJECSys,nBayesianIter);
    bayesianUnfold myUnfoldingSmearSys(uhist[i]->hMatrixFit,hPrior,0);
    myUnfoldingSmearSys.unfold(uhist[i]->hMeasSmearSys,nBayesianIter);
    bayesianUnfold myUnfolding(uhist[i]->hMatrixFit,myPrior.hPrior,0);
    myUnfolding.unfold(uhist[i]->hMeas,nBayesianIter);
    cout <<"Unfolding bin "<<i<<endl;

    delete hBinByBinCorRaw;
    delete hMCGen;

    // Iteration Systematics
    for (int j=2;j<=7;j++)
      {

	bayesianUnfold myUnfoldingSys(uhist[i]->hMatrixFit,hPrior,0);
	myUnfoldingSys.unfold(uhist[i]->hMeas,j);
	uhist[i]->hRecoIterSys[j]  = (TH1F*) myUnfoldingSys.hPrior->Clone(Form("hRecoRAA_IterSys%d_cent%d",j,i));
      }
    
    
    uhist[i]->hReco         = (TH1F*) uhist[i]->hRecoIterSys[nBayesianIter]->Clone(Form("Unfolded_cent%i",i));
    uhist[i]->hRecoJECSys   = (TH1F*) myUnfoldingJECSys.hPrior->Clone(Form("UnfoldedJeCSys_cent%i",i));
    uhist[i]->hRecoSmearSys   = (TH1F*) myUnfoldingSmearSys.hPrior->Clone(Form("UnfoldedSmearSys_cent%i",i));
    uhist[i]->hRecoBinByBin->SetName(Form("UnfoldedBinByBin_cent%i",i));
    
    if (doToy) {
      TCanvas *cToy = new TCanvas("cToy","toy",600,600);
      cToy->cd();
      int nExp=1000;
      TH1F *hTmp[nbins_truth+1];
      TH1F *hTmp2[nbins_truth+1];
      for (int j=1;j<=nbins_truth;j++) {
	hTmp[j] = new TH1F(Form("hTmp%d",j),"",200,0,10.+uhist[i]->hReco->GetBinContent(j)*2);
	hTmp2[j] = new TH1F(Form("hTmp2%d",j),"",200,0,10.+uhist[i]->hRecoBinByBin->GetBinContent(j)*2);
      }
      for (int exp =0; exp<nExp; exp++) {
	TH1F *hToy = (TH1F*)uhist[i]->hMeas->Clone();   
	TH2F *hMatrixToy = (TH2F*)uhist[i]->hMatrixFit->Clone();
	hToy->SetName("hToy");
	if (exp%100==0) cout <<"Pseudo-experiment "<<exp<<endl;
	for (int j=1;j<=hToy->GetNbinsX();j++) {
	  double value = gRandom->Poisson(uhist[i]->hMeas->GetBinContent(j));
	  hToy->SetBinContent(j,value);
	}
				
	for (int j=1;j<=hMatrixToy->GetNbinsX();j++) {
	  for (int k=1;k<=hMatrixToy->GetNbinsY();k++) {
	    double value = gRandom->Gaus(uhist[i]->hMatrixFit->GetBinContent(j,k),uhist[i]->hMatrixFit->GetBinError(j,k));
	    hMatrixToy->SetBinContent(j,k,value);
	  }
	}

	prior myPriorToy(hMatrixToy,hToy,0.0);
	myPriorToy.unfold(hToy,1);
	bayesianUnfold myUnfoldingToy(hMatrixToy,myPriorToy.hPrior,0.0);
	myUnfoldingToy.unfold(hToy,nBayesianIter);
	TH1F *hRecoTmp = (TH1F*) myUnfoldingToy.hPrior->Clone();
				
	for (int j=1;j<=hRecoTmp->GetNbinsX();j++) {
	  hTmp[j]->Fill(hRecoTmp->GetBinContent(j));
	}
	delete hToy;
	delete hRecoTmp;
	delete hMatrixToy;
      }
      TF1 *fGaus = new TF1("fGaus","[0]*TMath::Gaus(x,[1],[2])");
      for (int j=1;j<=nbins_truth;j++)
	{

	  f->SetParameters(hTmp[j]->GetMaximum(),hTmp[j]->GetMean(),hTmp[j]->GetRMS());
				
	  if (hTmp[j]->GetMean()>0) {
	    hTmp[j]->Fit(fGaus,"LL Q ");
	    hTmp[j]->Fit(fGaus,"LL Q ");
	    uhist[i]->hReco->SetBinError(j,f->GetParameter(2));
	  }	       
	  f->SetParameters(hTmp2[j]->GetMaximum(),hTmp2[j]->GetMean(),hTmp2[j]->GetRMS());
	  if (hTmp2[j]->GetMean()>0) {
	    hTmp2[j]->Fit(fGaus,"LL Q ");
	    hTmp2[j]->Fit(fGaus,"LL Q ");
	    uhist[i]->hRecoBinByBin->SetBinError(j,f->GetParameter(2));
	  }	       
	  delete hTmp[j];
	  delete hTmp2[j];
	}
      cPbPb->cd(i+1);
    }

    uhist[i]->hMeas->SetMarkerStyle(20);
    uhist[i]->hMeas->SetMarkerColor(2);
    uhist[i]->hReco->SetMarkerStyle(25);
    uhist[i]->hReco->SetName(Form("hReco_cent%d",i));
    
    uhist[i]->hReco->SetXTitle("p_{T} (GeV/c)");    
    uhist[i]->hReco->SetYTitle("Counts");    
    uhist[i]->hReco->GetXaxis()->SetNdivisions(505);
    //uhist[i]->hReco->Draw("");    
    uhist[i]->hReco->SetAxisRange(0,250,"X");
    uhist[i]->hReco->Draw("");   
     
    uhist[i]->hGen->SetLineWidth(2);
    uhist[i]->hGen->SetLineColor(2);
    //if(isMC)uhist[i]->hGen->Draw("hist same");
    //uhist[i]->hReco->Draw("same");    
    uhist[i]->hRecoBinByBin->SetMarkerStyle(28);
    uhist[i]->hRecoBinByBin->Draw("same");    

    uhist[i]->hReco->SetAxisRange(recoJetPtCut,300);
    TH1F *hReproduced = (TH1F*)myUnfolding.hReproduced->Clone(Form("hReproduced_cent%d",i));
    hReproduced->SetMarkerColor(4);
    hReproduced->SetMarkerStyle(24);
    //uhist[i]->hMeas->Draw("same");    

    hRecoBW[i] = (TH1F*)uhist[i]->hReco->Clone(Form("hReco%d",i));
    hRecoBinByBinBW[i] = (TH1F*)uhist[i]->hRecoBinByBin->Clone(Form("hRecoBinByBin%d",i));
    hMeasBW[i] = (TH1F*)uhist[i]->hMeas->Clone(Form("hMeas%d",i));
    if(isMC)hGenBW[i] = (TH1F*)uhist[i]->hGen->Clone(Form("hGen%d",i));

    divideBinWidth(hRecoBW[i]);    
    if(isMC)divideBinWidth(hGenBW[i]);    
    divideBinWidth(hRecoBinByBinBW[i]);    
    divideBinWidth(hMeasBW[i]);    

    hRecoBW[i]->Draw();
    if(isMC)hGenBW[i]->Draw("hist,same");
    hRecoBinByBinBW[i]->Draw("same");
    hMeasBW[i]->Draw("same");
    

    uhist[i]->hReco->SetTitle("Baysian Unfolded");
    uhist[i]->hRecoBinByBin->SetTitle("Bin-by-bin Unfolded");

    TLegend *leg = new TLegend(0.45,0.65,0.85,0.95);
    leg->SetBorderSize(0);
    leg->SetFillStyle(0);
    leg->AddEntry(uhist[i]->hMeas,"Measured","pl");
    leg->AddEntry(uhist[i]->hReco,"Bayesian unfolded","pl");
    leg->AddEntry(uhist[i]->hRecoBinByBin,"Bin-by-bin unfolded","pl");
    if(isMC)leg->AddEntry(uhist[i]->hGen,"Generator level truth","l");
    leg->Draw();

    cPbPbMeas->cd(i+1)->SetLogy();   
    uhist[i]->hMeas->SetAxisRange(0,240,"X");
    uhist[i]->hMeas->Draw();
    hReproduced->Draw("same");

    TLegend *leg2 = new TLegend(0.5,0.5,0.85,0.9);
    leg2->SetBorderSize(0);
    leg2->SetFillStyle(0);
    leg2->AddEntry(uhist[i]->hMeas,"Measured","pl");
    leg2->AddEntry(hReproduced,"Reproduced","pl");

    leg2->Draw();
  }	     
  
 
  pbpb_Unfo->Write();

  SysData systematics;
  TLine *line = new TLine(60,1,250,1);

  // Iteration systematics
  TCanvas *cIterSys = new TCanvas("cIterSys","cIterSys",1200,600);
  cIterSys->Divide(2,1);
  cIterSys->cd(2);
  TH1F *hRecoIterSysPP[100];
  TH1F *hRebinPP_tmp         = rebin(uhist[nbins_cent]->hReco, (char*)"hRebinPP_tmp");
  TLegend *legBayesianIterPP = myLegend(0.4,0.7,0.9,0.9);
  legBayesianIterPP->AddEntry("","PP","");
         
  for (int j=2;j<7;j++) {
    hRecoIterSysPP[j] = rebin(uhist[nbins_cent]->hRecoIterSys[j],Form("hRecoIterSysPP_IterSys%d",j));
    hRecoIterSysPP[j]->SetLineColor(colorCode[j-2]);
    hRecoIterSysPP[j]->SetMarkerColor(colorCode[j-2]);
    hRecoIterSysPP[j]->Divide(hRebinPP_tmp);
    if (j==2){
      makeHistTitle(hRecoIterSysPP[j],(char*)"",(char*)"Jet p_{T} (GeV/c)",(char*)"Ratio (Unfolded / Nominal)");
      hRecoIterSysPP[j]->SetTitleOffset(1.4,"Y");
      hRecoIterSysPP[j]->SetTitleOffset(1.2,"X");
      hRecoIterSysPP[j]->SetAxisRange(0.5,1.5,"Y");
      hRecoIterSysPP[j]->Draw(); 
    } else {
      hRecoIterSysPP[j]->Draw("same");
    }
         
    checkMaximumSys(systematics.hSysIter[nbins_cent],hRecoIterSysPP[j],0,1.1);
    legBayesianIterPP->AddEntry(hRecoIterSysPP[j],Form("Iteration %d",j),"pl");     
  }

  legBayesianIterPP->Draw();
  line->Draw();
  drawEnvelope(systematics.hSysIter[nbins_cent],(char*)"hist same");


  cIterSys->cd(1);
  TH1F *hRecoIterSysPbPb[100];
  TH1F *hRebinPbPb_tmp         = rebin(uhist[0]->hReco, (char*)"hRebinPbPb_tmp");
  TLegend *legBayesianIterPbPb = myLegend(0.4,0.7,0.9,0.9);
  legBayesianIterPbPb->AddEntry("","PbPb","");
  for (int j=2;j<7;j++) {
    hRecoIterSysPbPb[j] = rebin(uhist[0]->hRecoIterSys[j],Form("hRecoIterSysPbPb_IterSys%d",j));
    hRecoIterSysPbPb[j]->SetLineColor(colorCode[j-2]);
    hRecoIterSysPbPb[j]->SetMarkerColor(colorCode[j-2]);
    hRecoIterSysPbPb[j]->Divide(hRebinPbPb_tmp);
    if (j==2){
      makeHistTitle(hRecoIterSysPbPb[j],(char*)"",(char*)"Jet p_{T} (GeV/c)",(char*)"Ratio (Unfolded / Nominal)");
      hRecoIterSysPbPb[j]->SetTitleOffset(1.4,"Y");
      hRecoIterSysPbPb[j]->SetTitleOffset(1.2,"X");
      hRecoIterSysPbPb[j]->SetAxisRange(0.5,1.5,"Y");
      hRecoIterSysPbPb[j]->Draw(); 
    } else {
      hRecoIterSysPbPb[j]->Draw("same");
    }
         
    checkMaximumSys(systematics.hSysIter[0],hRecoIterSysPbPb[j],0,1.1);
    legBayesianIterPbPb->AddEntry(hRecoIterSysPbPb[j],Form("Iteration %d",j),"pl");     
  }
  legBayesianIterPbPb->Draw();
  line->Draw();
  drawEnvelope(systematics.hSysIter[0],(char*)"hist same");
}
//___________________________________________________________________________
Double_t* Ifit(int shift, Double_t& dataResult, Double_t& dataErr, std::string dataFile, 
	       TH1D* hsig, TH1D* hbkg, TH1D* hEGdata, Double_t* FitPar,
	       int ptbin=30, char EBEE[10]="EB", int fit_data=2)
{
  
  printf(" *** calling Ifit for %s , ptbin %d *** \n\n", EBEE,ptbin);

  cout << "The number of bins are: " << endl;
  cout << "hdata nbins = " << hEGdata->GetNbinsX() << endl;
  cout << "hsig nbins = " << hsig->GetNbinsX() << endl;
  cout << "hbkg nbins = " << hbkg->GetNbinsX() << endl;
  

  TCanvas *c1 = new TCanvas("HF1", "Histos1", 0, 0, 600, 600);
  gStyle->SetOptFit(0);

  if(fit_data != 3) dataColl.clear();
  sigColl.clear();
  bkgColl.clear();

  totalColl.clear();
  ctauColl.clear();
  Para.clear();
  Para_err.clear();

  info.clear();
  info_err.clear();

  float ptmax=0.;  
  if(ptbin== 21) ptmax= 23;
  if(ptbin== 23) ptmax= 26;
  if(ptbin== 26) ptmax= 30;
  if(ptbin== 30) ptmax= 35;
  if(ptbin== 35) ptmax= 40;
  if(ptbin== 40) ptmax= 45;
  if(ptbin== 45) ptmax= 50;
  if(ptbin== 50) ptmax= 60;
  if(ptbin== 60) ptmax= 85;
  if(ptbin== 85) ptmax= 120;
  if(ptbin== 120) ptmax= 300;
  if(ptbin== 300) ptmax= 500;



  Double_t* fitted = new Double_t[6];
  fitted[0] = 0.;    fitted[1] = 0.;    fitted[2] = 0.;    fitted[3] = 0.;
  fitted[4] = 0.;    fitted[5] = 0.;

  char hname[30];


  hsig->SetLineColor(1);
  hbkg->SetLineColor(1);
  hsig->SetNdivisions(505,"XY");
  hbkg->SetNdivisions(505,"XY");
  hsig->SetTitle("");
  hbkg->SetTitle("");
  hsig->SetXTitle("combined ISO (GeV)");
  hbkg->SetXTitle("combined ISO (GeV)");

  TH1F *hsum = (TH1F*)hsig->Clone();  
  hsum->Add(hbkg,1);
  float ntemplate = 1.;
  if (hsum->Integral()>1.) ntemplate = hsum->Integral();
  float sigfrac = hsig->Integral()/ntemplate*0.8;

  TH1F *hsum_norm = (TH1F*)hsum->Clone();  
  hsum_norm->Scale(1./hsum->Integral());

  TH1F *hdata = new TH1F();
  int ndata=0;
  if ( fit_data==1 ) {
    hdata = (TH1F*)hEGdata->Clone();
    ndata = (int)hdata->Integral();    
    for(int ibin=1; ibin<=hdata->GetNbinsX(); ibin++){
      for(int ipoint=0; ipoint<hdata->GetBinContent(ibin); ipoint++) {
	dataColl.push_back(hdata->GetBinCenter(ibin));
      }
    }
    ndata = dataColl.size();
  }else if (fit_data==2 ){
      hdata = (TH1F*)hEGdata->Clone();
    hdata -> Reset();
    dataColl.clear();
    FILE *infile =  fopen(dataFile.data(),"r");  
    float xdata, xdata1, xdata2; // combined isolation, pt, eta

    int flag = 1;
    while (flag!=-1){
      flag =fscanf(infile,"%f %f %f",&xdata, &xdata1, &xdata2);
      if( xdata1 >= ptbin && xdata1 < ptmax && xdata<20.) {
	if((strcmp(EBEE,"EB")==0 && TMath::Abs(xdata2)<1.45) ||
	   (strcmp(EBEE,"EE")==0 && TMath::Abs(xdata2)<2.5 && TMath::Abs(xdata2)>1.7) ) {
 	  dataColl.push_back(xdata);
	  hdata->Fill(xdata);
 	}
      } 
    }// keep reading files as long as text exists
    ndata = dataColl.size();

    printf("test print data 2 %2.3f \n", dataColl[2]);    
//     cout << "ndata in dataColl = " << ndata << endl;
    if ( ndata == 0 ) {
      printf(" no data to fit \n");
      return fitted;
    }
  }

  if(ndata==0) {
    printf(" ---  no events in the fit \n");
    return fitted;
  }
    
  //test fit the template and get PDFs
  TCanvas *c10 = new TCanvas("c10","c10",1000,500);
  c10->Divide(2,1);
  c10->cd(1);

  double par[20] = {hsig->GetMaximum(), 1., 0.6, 0.3,
		    hbkg->GetMaximum(), -.45, -0.05, 0.03, 1., 1., 1., 1.};

  if(strcmp(EBEE,"EE")==0) { par[2]=-0.1, par[3]=0.2; par[6]=-0.15; par[7]=0.02; };
  int fit_status;

  TF1 *f1 = new TF1("f1", exp_conv, -1., 20., 11);
  TF1 *fmcsigfit = new TF1("fmcsigfit", exp_conv, -1., 20., 11);
  fmcsigfit->SetLineColor(4);
  fmcsigfit->SetLineWidth(2);

  f1->SetNpx(10000);
  f1->SetParameters(par);
  f1->SetLineWidth(2);
  c10->cd(1);
  fit_status = hsig->Fit(f1,"","",-1., 5.);

  hsig->Draw();
  f1->Draw("same");
  if ( fit_status > 0 ) {
     printf("fit signal template failed. QUIT \n");
     return fitted;
  }
  if(para_index>0 && para_index<4){
    double tmppar = f1->GetParameter(para_index);
    f1->SetParameter(para_index, tmppar+para_sigma*f1->GetParError(para_index));
  }

  TF1 *fmcsig = (TF1*)f1->Clone();
  TF1 *fmcsigcorr = (TF1*)f1->Clone();
  fmcsig->SetNpx(10000);
  fmcsigcorr->SetNpx(10000);
  fmcsigfit->SetNpx(10000);
  
  TCanvas *c101 = new TCanvas("c101","c101",1000,500);
  c101->Divide(2,1);
  c101->cd(1);

  fmcsig->SetLineColor(1);
//   fmcsig->Draw();
//   f1->Draw("same");
  TH1F *htmp1 = (TH1F*)fmcsig->GetHistogram();
//   TH1F *htmp2 = (TH1F*)fmcsigcorr->GetHistogram();
  
  TH2F *htmp2 = new TH2F("htmp2","",210, -1., 20., 100, 0., htmp1->GetMaximum()*1.25);

  htmp2->SetNdivisions(505,"XY");
  htmp2->SetXTitle("Iso");
  htmp2->SetYTitle("A.U.");
  htmp2->SetLineColor(1);

//   htmp2->Draw();
//   htmp1->Draw("same");
//   htmp2->Add(htmp1,-1);
//   htmp2->Divide(htmp1);
  htmp2->GetXaxis()->SetRangeUser(-1., 10.);
  htmp2->SetMinimum(-1.);
  //htmp2->SetMaximum(1.5);
  htmp2->Draw();
  fmcsig->Draw("same");
//   fmcsigcorr->Draw("same");
  
  TLegend *tleg1 = new TLegend(0.5, 0.7, 0.93, 0.92);
  tleg1->SetHeader("");
  tleg1->SetFillColor(0);
  tleg1->SetShadowColor(0);
  tleg1->SetBorderSize(0);
  tleg1->AddEntry(fmcsig,"Zee data","l");
  //tleg1->AddEntry(fmcsigcorr,"corrected shape","l");
  tleg1->AddEntry(fmcsigfit,"shape from data","l");
  tleg1->Draw();

  //return fitted;
       
  SigPDFnorm = f1->Integral(-1.,20.);
  printf("status %d, sig area %3.3f \n", fit_status,f1->Integral(-1., 20.));


  f1->SetParameter(2,f1->GetParameter(2)+0.2);
  f1->SetParameter(3,f1->GetParameter(3)+0.1);

  Para.push_back(f1->GetParameter(0));
  Para.push_back(f1->GetParameter(1));
  Para.push_back(f1->GetParameter(2));
  Para.push_back(f1->GetParameter(3));

  Para_err.push_back(f1->GetParError(0));
  Para_err.push_back(f1->GetParError(1));
  Para_err.push_back(f1->GetParError(2));
  Para_err.push_back(f1->GetParError(3));

  c10->cd(2);
  TF1 *fbkgfit = new TF1("fbkgfit", expinv_power, -1., 20., 11);  

  TF1 *f3 = new TF1("f3", expinv_power, -1., 20., 11);
  fbkgfit->SetNpx(10000);  
  fbkgfit->SetLineColor(4);
  fbkgfit->SetLineWidth(2);

  f3->SetNpx(10000);
  f3->SetLineWidth(2);
  f3->SetParameters(f1->GetParameters());
    
  f3->SetParLimits(5,-5.,0.);
  f3->SetParLimits(6,-0.5,0.);
  f3->SetParLimits(7,0.001,0.2);
  f3->SetParLimits(8,0.5,5.);
  if ( strcmp(EBEE,"EB")==0 ){  
//     f3->FixParameter(8,1.);
//     f3->FixParameter(6,-0.1);
    f3->SetParLimits(8,1.,1.5);
  }

  float bkg_bend_power = 1.;
  if ( ptbin==21 ) bkg_bend_power = 4.5;
  if ( ptbin==23 ) bkg_bend_power = 4.;
  if ( ptbin==26 ) bkg_bend_power = 3.5;
  if ( ptbin==30 ) bkg_bend_power = 2.6;
  if ( ptbin==35 ) bkg_bend_power = 2.2;
  if ( ptbin==40 ) bkg_bend_power = 2.;
  if ( ptbin==45 ) bkg_bend_power = 2.;
  if ( ptbin==50 ) bkg_bend_power = 1.8;
  if ( ptbin==60 ) bkg_bend_power = 1.5;
  if ( ptbin==85 ) bkg_bend_power = 1.;
  if ( ptbin==120 ) bkg_bend_power = 1.;


  if ( strcmp(EBEE,"EE")==0 ){  
    f3->SetParameter(8,bkg_bend_power);
    f3->SetParLimits(8,bkg_bend_power-1., bkg_bend_power+1.);
  }

  f3->FixParameter(0,f3->GetParameter(0));
  f3->FixParameter(1,f3->GetParameter(1));
  f3->FixParameter(2,f3->GetParameter(2));
  f3->FixParameter(3,f3->GetParameter(3));

  hbkg->SetMaximum(hbkg->GetMaximum()*3.);
  fit_status = hbkg->Fit(f3,"b","",-1., 20.);
  hbkg->Draw();
  if ( fit_status > 0 ) {
    printf("fit background template failed. QUIT \n");    
    return fitted;
  }else {
    f3->Draw("same");
  }

  TF1 *fmcbkg = (TF1*)f3->Clone();
  fmcbkg->SetLineColor(1);
  c101->cd(2);

  htmp1 = (TH1F*)fmcbkg->GetHistogram();
  htmp2 = new TH2F("htmp2","",210, -1., 20., 100, 0., htmp1->GetMaximum()*1.25);

  htmp2->SetNdivisions(505,"XY");
  htmp2->SetXTitle("Iso");
  htmp2->SetYTitle("A.U.");
  htmp2->SetLineColor(1);

  htmp2->GetXaxis()->SetRangeUser(-1., 20.);
  htmp2->SetMinimum(-1.);
  htmp2->SetMaximum(1.5);
  htmp2->Draw();
  fmcbkg->Draw("same");

  TLegend *tleg2 = new TLegend(0.25, 0.2, 0.6, 0.42);
  tleg2->SetHeader("");
  tleg2->SetFillColor(0);
  tleg2->SetShadowColor(0);
  tleg2->SetBorderSize(0);
  if ( strcmp(EBEE,"EB")==0 ){  
    tleg2->AddEntry(fmcbkg,"MC shape","l");
  }else {
    tleg2->AddEntry(fmcbkg,"Data SB shape","l");
  }
  tleg2->AddEntry(fbkgfit,"shape from data","l");
  tleg2->Draw();
  
  if(para_index>4){
    double tmppar = f3->GetParameter(para_index);
    f3->SetParameter(para_index, tmppar+para_sigma*f3->GetParError(para_index));
  }

//   f3->SetParameter(5,-0.5);
//   f3->SetParameter(6,-0.05);
//   f3->SetParameter(7,0.02);
//   f3->SetParameter(8,1.);

  Para.push_back(f3->GetParameter(4));
  Para.push_back(f3->GetParameter(5));
  Para.push_back(f3->GetParameter(6));
  Para.push_back(f3->GetParameter(7)); 
  Para.push_back(f3->GetParameter(8)); 

  Para_err.push_back(f3->GetParError(4));
  Para_err.push_back(f3->GetParError(5));
  Para_err.push_back(f3->GetParError(6));
  Para_err.push_back(f3->GetParError(7));
  Para_err.push_back(f3->GetParError(8));

  BkgPDFnorm = f3->Integral(-1., 20.);
  printf("status %d, bkg area %3.3f \n", fit_status,f3->Integral(-1., 20.)/hdata->GetBinWidth(2));

  //test PDFs
  TCanvas *c11 = new TCanvas("c11","c11",1000,500);
  c11->Divide(2,1);
  c11->cd(1);
  TF1 *f11 = new TF1("f11",exp_conv_norm, -1., 20., 11);
  f11->SetNpx(10000);
  f11->SetParameters(f3->GetParameters());
  f11->Draw();
  printf(" SIG PDF area %2.3f \n", f11->Integral(-1., 20.));

  c11->cd(2);
  TF1 *f12 = new TF1("f12",expinv_power_norm, -1., 20., 11);
  f12->SetNpx(10000);
  f12->SetParameters(f3->GetParameters());
  f12->Draw();
  printf(" BKG PDF area %2.3f \n", f12->Integral(-1., 20.));

  //c1->cd();

  printf(" --------- before the fit ------------- \n");
  printf("Nsig %2.3f, Nbg %2.3f, Ntemplate %3.3f \n", hsig->Integral(), hbkg->Integral(), ntemplate);
  printf("Purity %2.3f, init size %4.3f,  fit sample size %4d\n", hsig->Integral()/hsum->Integral(), hsum->Integral(), ndata);
  printf(" -------------------------------------- \n");



  printf( " -----  Got %d, %d, %d events for fit ----- \n ", dataColl.size(),
	  sigColl.size(), bkgColl.size() );  

  //--------------------------------------------------
  //init parameters for fit
  Double_t vstart[11] = {1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.};
  vstart[0] = sigfrac*ndata;
  vstart[1] = (1-sigfrac)*ndata;
  for (int ii=0; ii<9; ii++) {    
    vstart[ii+2] = Para[ii]; //8 shape parameters
  }
  TMinuit *gMinuit = new TMinuit(NPAR);  
  gMinuit->Command("SET STR 1");
  gMinuit->SetFCN(fcn);
  Double_t arglist[11];
  Int_t ierflg = 0;
  
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
  arglist[0] = 1;
  gMinuit->mnexcm("SET PRINT", arglist ,1,ierflg);

  Double_t step[] = { 1.,1.,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,};

  for ( int ii=0; ii<9; ii++){
    printf(" para %d, %.5f, err %.5f \n", ii, Para[ii], Para_err[ii]);
  }

  float sigma = 3.;
  gMinuit->mnparm(0,  "Signal yield"  , vstart[0],  step[0], 0., ndata*2.  , ierflg);
  gMinuit->mnparm(1,  "background yield"  , vstart[1],  step[1], 0., ndata*2. , ierflg);

//   gMinuit->mnparm(2,  "constant"     , Para[0],  0.00,  Para[0], Para[0] , ierflg);
//   gMinuit->mnparm(3,  "exp tail"     , Para[1],  0.01,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg);
//   gMinuit->mnparm(4,  "exg mean"     , Para[2],  0.01,  Para[2]-sigma*Para_err[2], Para[2]+sigma*Para_err[2], ierflg);
//   gMinuit->mnparm(5,  "exg width"    , Para[3],  0.01,  Para[3]-sigma*Para_err[3], Para[3]+sigma*Para_err[3], ierflg);
//   gMinuit->mnparm(6,  "constant"     , Para[4],  0.00,  Para[4]                  , Para[4]                  , ierflg);
//   gMinuit->mnparm(7,  "bg exp turnon", Para[5],  0.01,  Para[5]-sigma*Para_err[5], Para[5]+sigma*Para_err[5], ierflg);
//   gMinuit->mnparm(8,  "bg x offset  ", Para[6],  0.01,  Para[6]-sigma*Para_err[6], Para[6]+sigma*Para_err[6], ierflg);
//   gMinuit->mnparm(9,  "bg bend slope", Para[7],  0.01,  0.001                    , 0.1                      , ierflg);
// //   gMinuit->mnparm(10, "bg bend power", Para[8],  0.01,  Para[8]-sigma*Para_err[8], Para[8]+sigma*Para_err[8], ierflg);
//   gMinuit->mnparm(10, "bg bend power", Para[8],  0.01,  0.5                       , 5.                       , ierflg);

//   gMinuit->mnparm(2,  "constant"     , Para[0], TMath::Abs(Para[0]*0.0) ,  Para[0], Para[0], ierflg);
//   gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.01) ,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg); 
// //   gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.1) ,  0.8    , 1.3    , ierflg);
//   gMinuit->mnparm(4,  "exg mean"     , Para[2], TMath::Abs(Para[2]*0.1) ,  0.5    , 1.0    , ierflg);
//   gMinuit->mnparm(5,  "exg width"    , Para[3], TMath::Abs(Para[3]*0.1) ,  0.25   , 0.5    , ierflg);
//   gMinuit->mnparm(6,  "constant"     , Para[4], TMath::Abs(Para[4]*0.0) ,  Para[4], Para[4], ierflg);
//   gMinuit->mnparm(7,  "bg exp turnon", Para[5], TMath::Abs(Para[5]*0.1) ,  -0.7   , -0.3   , ierflg);
//   gMinuit->mnparm(8,  "bg x offset  ", Para[6], TMath::Abs(Para[6]*0.0) ,  -0.15  , -0.05  , ierflg);
//   gMinuit->mnparm(9,  "bg bend slope", Para[7], TMath::Abs(Para[7]*0.1) ,  0.01   , 0.05   , ierflg);
//   gMinuit->mnparm(10, "bg bend power", Para[8], TMath::Abs(Para[8]*0.1) ,  0.5    , 1.5    , ierflg);

  gMinuit->mnparm(2,  "constant"     , Para[0],  0.00,  Para[0], Para[0] , ierflg);
  gMinuit->mnparm(3,  "exp tail"     , Para[1],  0.00,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg);
  gMinuit->mnparm(4,  "exg mean"     , Para[2],  0.00,  Para[2]-sigma*Para_err[2], Para[2]+sigma*Para_err[2], ierflg);
  gMinuit->mnparm(5,  "exg width"    , Para[3],  0.00,  Para[3]-sigma*Para_err[3], Para[3]+sigma*Para_err[3], ierflg);
  gMinuit->mnparm(6,  "constant"     , Para[4],  0.00,  Para[4]                  , Para[4]                  , ierflg);
  gMinuit->mnparm(7,  "bg exp turnon", Para[5],  0.00,  Para[5]-sigma*Para_err[5], Para[5]+sigma*Para_err[5], ierflg);
  gMinuit->mnparm(8,  "bg x offset  ", Para[6],  0.00,  Para[6]-sigma*Para_err[6], Para[6]+sigma*Para_err[6], ierflg);
  gMinuit->mnparm(9,  "bg bend slope", Para[7],  0.00,  0.001                    , 0.1                      , ierflg);
  gMinuit->mnparm(10, "bg bend power", Para[8],  0.00,  Para[8]-sigma*Para_err[8], Para[8]+sigma*Para_err[8], ierflg);
  
  printf(" --------------------------------------------------------- \n");
  printf(" Now ready for minimization step \n --------------------------------------------------------- \n");
  
  arglist[0] = 500; // number of iteration
  gMinuit->mnexcm("MIGRAD", arglist,1,ierflg);
  //can do scan
//   arglist[0] = 0;
//   gMinuit->mnexcm("SCAN", arglist,1,ierflg);

  printf (" -------------------------------------------- \n");
  printf("Finished.  ierr = %d \n", ierflg);

  double para[NPAR+1],errpara[NPAR+1];

  double tmp_errpara[NPAR+1];

  for(int j=0; j<=NPAR-1;j++) { tmp_errpara[j]=0.1; }
  for(int j=2; j<=NPAR-1;j++) { 
    if(Para_err[j-2]!=0.) tmp_errpara[j]=TMath::Abs(Para_err[j-2]); 
  }
  
  int ni=6;       if ( strcmp(EBEE,"EE")==0 ) { ni=6; }//if(ptbin==21) ni=0;}
  
  if ( ierflg == 0 ) {
    for(int i=0; i<ni; i++) {
      float istep[10] = {0.,0.,0.,0.,0.,0.,0.};
      if (i<(ni-1)) {
	istep[i] = 0.001;
      }else {
	for (int j=0; j<ni-1; j++) {istep[j] = 0.001;}
      }

      for(int j=0; j<=NPAR-1;j++) {
	gMinuit->GetParameter(j, para[j], errpara[j]);
	if (errpara[j] != 0. ) {
	  tmp_errpara[j] = TMath::Abs(errpara[j]);
	}
      }

      if ( strcmp(EBEE,"EB")==0 ) {

	sigma = 10.;

 	if ( i==(ni-1) ) { sigma=5.;istep[1]=istep[4]=0.; }
	if ( ptbin==21 && i==1 ){ sigma=3.; }
 	if ( ptbin==21 && i==(ni-1) ){ sigma=20.; }
	if ( ptbin==23 && i==0 ){ para[7]=-0.5; }
	if ( ptbin==23 && i==1 ){ istep[1]=0.; istep[3]=0.01; }
 	if ( ptbin==23 && i==3 ){ istep[1]=0.01; istep[3]=0.0; }
	if ( ptbin==23 && i==(ni-1) ){ sigma=20.; }
 	if ( ptbin==26 && i==1 ){ sigma=5.; }	
	if ( ptbin==26 && i==(ni-1) ){ sigma=20.; }
	if ( ptbin==30 && i==(ni-1) ){ sigma=3.; }
 	if ( ptbin==35 && i==(ni-1) ) { sigma=10.; }
 	if ( ptbin==40 && i==(ni-1) ) { sigma=5.; istep[4]=0.01; }
 	if ( ptbin==45 && i==(ni-1) ) { sigma=10.; }
	if ( ptbin==60 && i==0 ) { para[3]=1.; para[4]=0.6; para[5]=0.32; para[7]=-0.45; para[9]=0.025; para[10] = 1.;}
 	if ( ptbin==60 && i==(ni-1) ) { sigma=5.; istep[4]=0.01;}
	if ( ptbin>=85 && i==(ni-1) ){ sigma=3.; }
	if ( ptbin==300 ) { istep[2]=istep[3]=istep[4]=0.; }// para[7] = -5.11907e-02; istep[1]=0.; }
	float tmp8=0.;
	
// 	if( i!= (ni-1) ) {
	  gMinuit->mnparm(0,  "Signal yield"  ,   para[0],  1., para[0]-100.*tmp_errpara[0], para[0]+100.*tmp_errpara[0], ierflg);
	  gMinuit->mnparm(1,  "background yield", para[1],  1., para[1]-100.*tmp_errpara[1], para[1]+100.*tmp_errpara[1], ierflg);
	  gMinuit->mnparm(2,  "constant"     , para[2],  0., para[2]-100.*tmp_errpara[2], para[2]+100.*tmp_errpara[2], ierflg);
	  gMinuit->mnparm(6,  "constant"     , para[6],  0., para[6]-100.*tmp_errpara[6], para[6]+100.*tmp_errpara[6], ierflg);
	  gMinuit->mnparm(3,  "exp tail"     , para[3],  istep[4],  para[3]-sigma*tmp_errpara[3], para[3]+sigma*tmp_errpara[3], ierflg);
	  gMinuit->mnparm(4,  "exg mean"     , para[4],  istep[3],  para[4]-sigma*tmp_errpara[4], para[4]+sigma*tmp_errpara[4], ierflg);
	  gMinuit->mnparm(5,  "exg width"    , para[5],  istep[2],  para[5]-sigma*tmp_errpara[5], para[5]+sigma*tmp_errpara[5], ierflg);
	  gMinuit->mnparm(7,  "bg exp turnon", para[7],  istep[1],  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);
	  gMinuit->mnparm(8,  "bg x offset  ", para[8],  tmp8    ,  para[8]-sigma*tmp_errpara[8], para[8]+sigma*tmp_errpara[8], ierflg);
	  gMinuit->mnparm(9,  "bg bend slope", para[9],  istep[0],  para[9]-sigma*tmp_errpara[9], para[9]+sigma*tmp_errpara[9], ierflg);      
	  float sigma10=5.;
	  if ( para[10]-sigma10*tmp_errpara[10] < 1. )// && i!=(ni-1))
	    gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], 1.,  para[10]+sigma10*tmp_errpara[10], ierflg);      
	  else
	    gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], para[10]-sigma10*tmp_errpara[10],  para[10]+sigma10*tmp_errpara[10], ierflg);      
// 	}else {
// 	  gMinuit->mnparm(2,  "constant"     , Para[0], TMath::Abs(Para[0]*0.0) ,  Para[0], Para[0], ierflg);
// 	  //gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.01) ,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg); 
// 	  gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.0) ,  0.8    , 1.3    , ierflg);
// 	  gMinuit->mnparm(4,  "exg mean"     , Para[2], TMath::Abs(Para[2]*0.1) ,  0.5    , 1.0    , ierflg);
// 	  gMinuit->mnparm(5,  "exg width"    , Para[3], TMath::Abs(Para[3]*0.1) ,  0.25   , 0.5    , ierflg);
// 	  gMinuit->mnparm(6,  "constant"     , Para[4], TMath::Abs(Para[4]*0.0) ,  Para[4], Para[4], ierflg);
// 	  gMinuit->mnparm(7,  "bg exp turnon", Para[5], TMath::Abs(Para[5]*0.0) ,  -0.7   , -0.3   , ierflg);
// 	  gMinuit->mnparm(8,  "bg x offset  ", Para[6], TMath::Abs(Para[6]*0.0) ,  -0.15  , -0.05  , ierflg);
// 	  gMinuit->mnparm(9,  "bg bend slope", Para[7], TMath::Abs(Para[7]*0.1) ,  0.01   , 0.05   , ierflg);
// 	  gMinuit->mnparm(10, "bg bend power", Para[8], TMath::Abs(Para[8]*0.1) ,  0.5    , 1.5    , ierflg);
// 	}


	if( ptbin >=300 ) { 
	  gMinuit->mnparm(3,  "exp tail"  , 1.257281,  0.0,  para[1]-3.*tmp_errpara[1], para[1]+3.*tmp_errpara[1], ierflg);
	  gMinuit->mnparm(4,  "exg mean"  , 0.856906,  0.0,  para[2]-3.*tmp_errpara[2], para[2]+3.*tmp_errpara[2], ierflg);
	  gMinuit->mnparm(5,  "exg width" , 0.320847,  0.0,  para[3]-3.*tmp_errpara[3], para[3]+3.*tmp_errpara[3], ierflg);
	}      

    }else{	

	sigma=10.;
	if ( i==0 ) { para[10] = bkg_bend_power; tmp_errpara[10] = 0.3; }
 	if ( i==(ni-1) ) { sigma=3.;istep[1]=istep[4]=0.; } //test of not changing signal template
     	if ( i==(ni-1) ) { istep[4]=0.;}

   	if ( ptbin==21 && i==(ni-1) ) { sigma=20.;}
  	if ( ptbin==23 && i==0 ) { sigma=5.;}
  	if ( ptbin==23 && i==(ni-1) ) { sigma=10.;}
	if ( ptbin<30 && ptbin>21 && i==1 ){ istep[1]=0.; istep[3]=0.01; }
 	if ( ptbin<30 && ptbin>21 && i==3 ){ istep[1]=0.01; istep[3]=0.0; }
	if ( ptbin==26 && i==1 ) { para[7] = -0.8; }
	if ( ptbin==26 && i==(ni-1) ) { sigma=10.; }
  	if ( ptbin==30 && i==(ni-1) ) { sigma=10.; }
 	if ( ptbin==35) {para[7] = -0.75;}
 	if ( ptbin==40 && i==0) {para[7] = -0.65; para[10] = 2.;}
	if ( ptbin==45 && i==(ni-1) ) {sigma=5.;}
	if ( ptbin==85 && i==(ni-1) ) {sigma=10.; istep[4]=0.01;}
	if (ptbin >= 85 ) { para[10] = bkg_bend_power; tmp_errpara[10] = 1.; }

	if ( ptbin==120 ) { para[7] = -0.615255; istep[1]=0.;}

	
//     	if ( ptbin==120 && i==0 ) { 
// 	  para[3] = 1.446454; para[4]=-0.016373; para[5]=0.163238;
// 	  istep[2]=istep[3]=istep[4]=0.; sigma=5.; tmp_errpara[10]=0.2;
// 	}
//     	if ( ptbin==120 && i==(ni-1) ) { istep[2]=istep[3]=istep[4]=0.; sigma=5.;}

	gMinuit->mnparm(0,  "Signal yield"  ,   para[0],  1., para[0]-100.*tmp_errpara[0], para[0]+100.*tmp_errpara[0], ierflg);
	gMinuit->mnparm(1,  "background yield", para[1],  1., para[1]-100.*tmp_errpara[1], para[1]+100.*tmp_errpara[1], ierflg);
	gMinuit->mnparm(2,  "constant"     , para[2],  0.,  para[2], para[2] , ierflg);
	gMinuit->mnparm(6,  "constant"     , para[6],  0.,  para[6], para[6], ierflg);	
	gMinuit->mnparm(3,  "exp tail"     , para[3],  istep[4],  para[3]-sigma*tmp_errpara[3], para[3]+sigma*tmp_errpara[3], ierflg);
	gMinuit->mnparm(4,  "exg mean"     , para[4],  istep[3],  para[4]-sigma*tmp_errpara[4], para[4]+sigma*tmp_errpara[4], ierflg);
	gMinuit->mnparm(5,  "exg width"    , para[5],  istep[2],  para[5]-sigma*tmp_errpara[5], para[5]+sigma*tmp_errpara[5], ierflg);
	gMinuit->mnparm(7,  "bg exp turnon", para[7],  istep[1],  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);
	gMinuit->mnparm(8,  "bg x offset  ", para[8],  0.00,      para[8]-sigma*tmp_errpara[8], para[8]+sigma*tmp_errpara[8], ierflg);
	gMinuit->mnparm(9,  "bg bend slope", para[9],  istep[0],  para[9]-sigma*tmp_errpara[9], para[9]+sigma*tmp_errpara[9], ierflg);	
  
	float minerr=1.;
	//if ( tmp_errpara[10] > 0.5) tmp_errpara[10] = 0.5;
	float sigma10=5.;
	if ( para[10]-sigma10*tmp_errpara[10] < 1. ) 
	  gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], minerr,  para[10]+sigma10*tmp_errpara[10], ierflg);
	else 
	  gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], para[10]-sigma10*tmp_errpara[10],  para[10]+sigma10*tmp_errpara[10], ierflg);

      }
      printf(" ************ \n");
      printf("  do %d th fit  \n", i);
      if(i==5 && dataFile.find("toy")    != std::string::npos)
	{
	  cout << "dataResult = " << dataResult << "\t dataErr = " << dataErr << endl;
	  // fixed turn on at +- 1 sigma
	  gMinuit->mnparm(7,  "bg exp turnon", dataResult-(float)shift*dataErr,  0.00,  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);

	}
      else if(dataFile.find("toy")    == std::string::npos)
	{
	  dataResult = para[7];
	  dataErr    = tmp_errpara[7];
	}
      arglist[0] = 500; // number of iteration
      gMinuit->mnexcm("MIGRAD", arglist ,1,ierflg);      
      if ( ierflg != 0 ) {
  	printf("fit failed at %d iteration \n", i);
  	c1->cd();	c1->Draw();  	hdata->Draw("phe");
  	return fitted;
      }
    }
  }
 
  Double_t amin,edm,errdef; 
  if ( ierflg == 0 ) {
    for(int j=0; j<=NPAR-1;j++) {
      gMinuit->GetParameter(j, para[j],errpara[j]);
      info.push_back(para[j]);
      info_err.push_back(errpara[j]);
      printf("Parameter  %d = %f +- %f\n",j,para[j],errpara[j]);	
    }
    para[NPAR] = dataColl.size();
    printf(" fitted yield %2.3f \n", (para[0]+para[1])/ndata );
    
    info.push_back(sigColl.size());
    
    for(int j=0; j<=NPAR-1;j++) {
      tmp_errpara[j] = errpara[j];
      if( tmp_errpara[j] == 0. ) tmp_errpara[j] = par[j]*.1;      
    }
    //do minos if fit sucessed.

  }
  if (ierflg != 0 )  {
    printf(" *********** Fit failed! ************\n");
    gMinuit->GetParameter(0, para[0],errpara[0]);
    gMinuit->GetParameter(1, para[1],errpara[1]);
    para[0]=0.; errpara[0]=0.;

    c1->cd();
    c1->Draw();  
    //gPad->SetLogy();
    hdata->SetNdivisions(505,"XY");
    hdata->SetXTitle("comb. ISO (GeV)");
    hdata->SetYTitle("Entries");
    hdata->SetTitle("");
    hdata->SetMarkerStyle(8);
    hdata->SetMinimum(0.);
    if ( hdata->GetMaximum()<10.) hdata->SetMaximum(15.);
    else hdata->SetMaximum(hdata->GetMaximum()*1.25);
    if ( strcmp(EBEE,"EE")==0 &&ptbin == 15 ) hdata->SetMaximum(hdata->GetMaximum()*1.25);
   
    hdata->Draw("phe");  

    return fitted;    
  }

  
  // Print results
//   Double_t amin,edm,errdef;
  Int_t nvpar,nparx,icstat;
  gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
  gMinuit->mnprin(1,amin);  
  gMinuit->mnmatu(1);
  printf(" ========= happy ending !? =========================== \n");
  
  printf("FCN =  %3.3f \n", amin);

  //use new PDF form
  double tmppar[12];
  for(int ii=0; ii<9; ii++){
    tmppar[ii] = para[ii+2];
    fmcsigfit->SetParameter(ii,tmppar[ii]);
    fbkgfit->SetParameter(ii,tmppar[ii]);
  }

  c101->cd(1);
  
  //fmcsigfit->SetParameters(tmppar);
  //fmcsigfit->SetParameter(2,0.1);
  //fmcsigfit->SetLineStyle(2);

  fmcsigfit->Draw("same");
  c101->cd(2);

  fbkgfit->SetParameter(4,fbkgfit->GetParameter(4)*fmcbkg->Integral(-1., 20.)/fbkgfit->Integral(-1., 20.));
  fbkgfit->Draw("same");

  char fname[100];
  sprintf(fname,"plots/template_Ifit%s_%d.pdf",EBEE,ptbin);
  c101->SaveAs(fname);


  f11->SetParameters(tmppar);
  SigPDFnorm = f11->Integral(-1., 20.);
  f12->SetParameters(tmppar);
  BkgPDFnorm = f12->Integral(-1., 20.);


  // plot
  c1->cd();
  c1->Draw();  
  //gPad->SetLogy();
   hdata->SetNdivisions(505,"XY");
   hdata->SetXTitle("comb. ISO (GeV)");
   hdata->SetYTitle("Entries");
   hdata->SetTitle("");
   hdata->SetMarkerStyle(8);
   hdata->SetMinimum(0.);
   if ( hdata->GetMaximum()<10.) hdata->SetMaximum(15.);
   else hdata->SetMaximum(hdata->GetMaximum()*1.5);
   if ( strcmp(EBEE,"EE")==0 &&ptbin == 15 ) hdata->SetMaximum(hdata->GetMaximum()*1.2);

   hdata->Draw("p e ");

  f11->SetParameter(0, para[0]*f11->GetParameter(0)/f11->Integral(-1., 20.)*hdata->GetBinWidth(2));
//   f11->SetFillColor(5);
  f11->SetLineColor(4);
  //f11->SetFillColor(603);
  f11->SetLineWidth(2);
//   f11->SetFillStyle(3001);
  f11->Draw("same");

  f12->SetParameter(4, para[1]*f12->GetParameter(4)/f12->Integral(-1., 20.)*hdata->GetBinWidth(2));
//   f12->SetFillColor(8);
  f12->SetLineColor(2);
  //f12->SetFillColor(603);
  f12->SetLineWidth(2);
//   f12->SetFillStyle(3013);
  f12->Draw("same");

  TF1 *f13 = new TF1("f13",sum_norm, -1., 20 ,11);
  f13->SetNpx(10000);
  f13->SetParameters(f12->GetParameters());
  f13->SetParameter(0, para[0]*f11->GetParameter(0)/f11->Integral(-1., 20.)*hdata->GetBinWidth(2));
  f13->SetParameter(4, para[1]*f12->GetParameter(4)/f12->Integral(-1., 20.)*hdata->GetBinWidth(2));  
  f13->SetLineWidth(2);
  f13->SetLineColor(1);
  f13->Draw("same");
  f11->Draw("same");
  hdata->Draw("pe same");

//   cout << "The number of bins are: " << endl;
//   cout << "hdata nbins = " << hdata->GetNbinsX() << endl;
//   cout << "hsig nbins = " << hsig->GetNbinsX() << endl;
//   cout << "hbkg nbins = " << hbkg->GetNbinsX() << endl;

  // get chi2/NDF
  double chi2ForThisBin=0;
  int nbinForThisBin=0;
  chi2Nbins(f13, hdata, chi2ForThisBin, nbinForThisBin);
  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f11 parameter " << epar << " = " << 
// 	f11->GetParameter(epar) << endl;
      FitPar[epar] = f11->GetParameter(epar);
    }

  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f12 parameter " << epar << " = " << 
// 	f12->GetParameter(epar) << endl;
      FitPar[epar+11] = f12->GetParameter(epar);
    }

  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f13 parameter " << epar << " = " << 
// 	f13->GetParameter(epar) << endl;
      FitPar[epar+22] = f13->GetParameter(epar);

    }

//   cout << "hdata integral = " << hdata->Integral() << endl;
//   cout << endl;

//   printf("fit area %3.2f; sig area %3.2f; bg area %3.2f\n", f13->Integral(-1., 20.)/hdata->GetBinWidth(2),  f11->Integral(-1., 20.)/hdata->GetBinWidth(2),f12->Integral(-1., 20.)/hdata->GetBinWidth(2));

//   for(int i=0; i<12; i++){
//     printf(" fit para %d = %4.3f \n", i, f13->GetParameter(i));
//   }

   TLegend *tleg = new TLegend(0.5, 0.7, 0.93, 0.92);
   char text[50];
   sprintf(text,"%s Pt %d ~ %.0f GeV",EBEE, ptbin, ptmax);
   tleg->SetHeader(text);
   tleg->SetFillColor(0);
   tleg->SetShadowColor(0);
   tleg->SetBorderSize(0);
   sprintf(text,"#chi^{2}/NDF = %.1f/%d",chi2ForThisBin,nbinForThisBin);
   tleg->AddEntry(hdata,text,"");
   sprintf(text,"Data %.1f events",hdata->Integral());
   tleg->AddEntry(hdata,text,"pl");
   sprintf(text,"Fitted %.1f events",para[0]+para[1]);//f13->Integral(-1., 20.)/hdata->GetBinWidth(2));
   tleg->AddEntry(f13,text,"l");
   sprintf(text,"SIG %.1f #pm %.1f events",para[0], errpara[0]);
   tleg->AddEntry(f11,text,"f");
   sprintf(text,"BKG %.1f #pm %.1f events",para[1], errpara[1]);
   tleg->AddEntry(f12,text,"f");
   tleg->Draw();


   gPad->RedrawAxis();

   printf("%s, ptbin %d, Data %.1f events \n",EBEE, ptbin, hdata->Integral());
   printf("Fitted %.1f (in 5GeV) %.1f events \n",para[0]+para[1],f13->Integral(-1.,5.));
   printf("SIG %.1f #pm %.1f events \n",para[0], errpara[0]);
   printf("SIG (in 5GeV) %.1f #pm %.1f events \n",f11->Integral(-1.,5.)/hdata->GetBinWidth(2), f11->Integral(-1.,5.)*errpara[0]/para[0]/hdata->GetBinWidth(2));
   printf("BKG %.1f #pm %.1f events \n",para[1], errpara[1]);
   printf("BKG (in 5GeV) %.1f #pm %.1f events \n",f12->Integral(-1.,5.)/hdata->GetBinWidth(2), f12->Integral(-1.,5.)*errpara[1]/para[1]/hdata->GetBinWidth(2));
   
   float purity = f11->Integral(-1.,5.)/hdata->GetBinWidth(2)/(f11->Integral(-1.,5.)/hdata->GetBinWidth(2)+f12->Integral(-1.,5.)/hdata->GetBinWidth(2));
   float purity_err = purity*errpara[0]/para[0];
   printf("Purity (in 5GeV) %.3f #pm %.3f  \n", purity, purity_err);


//   hsig->Scale(para[0]/hsig->Integral());
//   hbkg->Scale(para[1]/hbkg->Integral());
//   hbkg->Add(hsig);

//   hsig->SetLineColor(1);
//   hsig->SetFillColor(5);
//   hsig->SetFillStyle(3001);

//   hbkg->SetLineWidth(2);


//   hsig->Draw("same");
//   hbkg->Draw("same");


  sprintf(fname,"plots/unbinned_free_Ifit%s_%d.pdf",EBEE,ptbin);
  if (para_index>0) sprintf(fname,"plots/unbinned_Ifit%s_%d_para%d_sigma%1.0f.pdf",EBEE,ptbin,para_index,para_sigma);
  if(Opt_SavePDF == 1) {
    c1->SaveAs(fname);


  } else {

   c1->Close();
   c10->Close();
   c101->Close();
   c11->Close();

  }

  printf("----- fit results with signal projection   ----------- \n");

  fitted[0] = para[0];
  fitted[1] = errpara[0];
  fitted[2] = para[1];
  fitted[3] = errpara[1];
  fitted[4] = f11->Integral(-1.,5.)/hdata->GetBinWidth(2);
  fitted[5] = f11->Integral(-1.,5.)*errpara[0]/para[0]/hdata->GetBinWidth(2);

  return fitted;
}
Example #30
0
void AlignTopAndBottomTOFs(string ArrayPart="NV",Float_t Start=-5,Float_t End=25){
  
  for (int bar=1;bar<13;bar++){
    stringstream nameTop;
    stringstream nameBottom;

    nameTop<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"_TopCutTOFPr";
    TH1F * CurrentTop = (TH1F*)gDirectory->Get(nameTop.str().c_str());


    nameBottom<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"_BottomCutTOFPr";
    TH1F * CurrentBottom = (TH1F*)gDirectory->Get(nameBottom.str().c_str());
  
    // TCanvas *c=new TCanvas("c");
    // c->cd(1);
    // CurrentTop->Draw();
    // CurrentBottom->Draw("same");

    int binsTop = CurrentTop->GetNbinsX();

    int binsBottom= CurrentBottom->GetNbinsX();
  
    if ( binsTop !=binsBottom){
      cout<<"Nubmer of bins for the top channel not the same as for the bottom channel"<<endl;
      cout<<"This was for "<<CurrentTop->GetName()<<" and "<<CurrentBottom->GetName()<<endl;
      return;
    }
  
    int bins=binsTop;
  
    double topLow = CurrentTop->GetBinLowEdge(1);//ROOT histograms start at bin 1. bin 0 is underflow
    double topHigh= CurrentBottom->GetBinLowEdge(binsTop) +CurrentBottom->GetBinWidth(binsTop);//ROOT histograms end at bin N. N+1 is overflow bin.

    double NanoSecsPerBin = ((topHigh-topLow)*4)/binsTop;
  
    //    cout<<topLow<<" "<<topHigh<<endl;
    //    cout<<"NanoSecsPerBin "<<NanoSecsPerBin<<endl;
  
 
    int ForthOfBins = TMath::Floor(0.25* bins);
    int EighthOfBins = TMath::Floor( (1.0/8)* bins);

    int NumberOfShifts = 2*EighthOfBins; // 1/8 of the number of bins *2 for left/right shifts
  
    int TopZeroBin = CurrentTop->GetMaximumBin();
  
    int StartBin = CurrentTop->FindBin(Start);
    int EndBin = CurrentTop->FindBin(End);

    //Find shift That moves Bottom -> Top
    vector <double> TheChi2s;
    vector <int> TheShifts;
    for (int i=0;i<NumberOfShifts;i++){
      double binShift = (i - NumberOfShifts/2);

      double chi2=0;
      // cout<<"Looking in bin range "<<TopZeroBin-EighthOfBins<<" "<<TopZeroBin+EighthOfBins<<endl;
      // cout<<"That is from "<<CurrentTop->GetBinCenter(TopZeroBin-EighthOfBins)<<" "<<CurrentTop->GetBinCenter(TopZeroBin+EighthOfBins)<<endl;

      for (int bin=StartBin ;bin<EndBin;bin++){
	double b = CurrentBottom->GetBinContent(bin + binShift);
	double t = CurrentTop->GetBinContent(bin);
	if (b !=0 && t!=0){
	  double temp =((b-t)*(b-t))/( TMath::Sqrt(t) );
	  chi2+=temp;
	}
      }
    
      TheChi2s.push_back(chi2);
      TheShifts.push_back(binShift);

    }
  
    ///Find miminum by linear search 
    double min = 9999999999.0;
    int MinSpot=-1;
    for (int i=0;i<NumberOfShifts;i++){
      if ( TheChi2s[i] < min){
	min=TheChi2s[i];
	MinSpot=i;
      }
    }

    cout<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"B  "<<"1  0  "<<fixed<<setw(6)<<setprecision(4)<<TheShifts[MinSpot]/4.0*NanoSecsPerBin<<endl;
    cout<<ArrayPart<<setfill('0')<<setw(2)<<bar<<"T  "<<"1  0  0"<<endl;

  }


  cout<<"There were "<<NanoSecsPerBin<<" nano secs per bin"<<endl;
  // TGraph * graph = new TGraph();
  
  // cout<<"Size of Chi2s "<<TheChi2s.size()<<endl;
  // cout<<"Num "<<NumberOfShifts<<endl;

  // for (int i=0;i<NumberOfShifts;i++){
  //   graph->SetPoint(i,TheShifts[i],TheChi2s[i]);
  // }

  // TCanvas *c2 = new TCanvas("c2");
  // c2->cd(1);
  // graph->Draw("A*");


}