Example #1
0
void MCtoSTATerrors() {
  TLatex *tplus = labelLatex(0.1364943,0.8114407,"MC sample");

  TFile *file0 = TFile::Open("results/StandardCutflow/allmc.root");

  TCanvas *c1 = new TCanvas();
  //TCanvas *c2 = new TCanvas();
  TH1D * LPplus = (TH1D*)file0->Get("RECO_PolPlots_50toinf/RECO_ICVarPFPlus");
  TH1D * LPminus = (TH1D*)file0->Get("RECO_PolPlots_50toinf/RECO_ICVarPFMinus");

  LPplus->Rebin(20);
  LPminus->Rebin(20);

  LPplus->Scale(0.3);
  LPminus->Scale(0.3);

  TH1D * newLPplus = (TH1D*)LPplus->Clone();
  TH1D * newLPminus = (TH1D*)LPminus->Clone();

  for(unsigned int i=1; i < LPplus->GetXaxis()->GetNbins(); i++) {
    newLPplus->SetBinError(i, TMath::Sqrt(LPplus->GetBinContent(i)));
    newLPminus->SetBinError(i, TMath::Sqrt(LPminus->GetBinContent(i)));
  }

  c1->cd();
  newLPplus->GetYaxis()->SetTitle("Events / 300 nb^{-1}");
  //newLPplus->GetXaxis()->SetTitle("LP(#mu^{+})");
  newLPplus->GetXaxis()->SetTitle("LP(#mu)");
  newLPplus->GetXaxis()->SetRangeUser(-1.0,2.0);
  newLPplus->SetLineWidth(3);
  newLPplus->SetLineStyle(2);
  newLPplus->SetLineColor(kRed);
  newLPplus->DrawCopy();
  tplus->DrawClone("same");

//   c2->cd();
//   newLPminus->GetYaxis()->SetTitle("Events / 100 nb^{-1}");
//   newLPminus->GetXaxis()->SetTitle("LP(#mu^{-})");
  newLPminus->SetLineWidth(3);
  newLPminus->SetLineStyle(2);
  newLPminus->SetLineColor(kBlack);
  newLPminus->DrawCopy("same");
//   tplus->DrawClone("same");

  leg = new TLegend(0.762931,0.720339,0.8649425,0.8622881,NULL,"brNDC");
  leg->AddEntry(newLPplus,"#mu^{+}","l");
  leg->AddEntry(newLPminus,"#mu^{-}","l");

  leg->SetFillColor(kWhite);
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->DrawClone();

  file0->Close();

  return;
}
Example #2
0
void Drawbbc(){
	TFile *f = new TFile("merged.root");
	TH1D* hbbcs;
	TH1D* hbbcn;
	TCanvas *c1;
	TCanvas *c2;
	TLegend *leg = new TLegend(0.5,0.7,0.7,0.85);
	leg->SetBorderSize(0);
	leg->SetFillColor(0);
	leg->SetTextSize(0.048);
	TH2F* bbcsbbcn = (TH2F*)f->Get(Form("bbcsbbcn_0"));
	for(int xcent=1; xcent < 6; xcent++){
		TH1F* bbcsbbcndis_t = (TH1F*)f->Get(Form("bbcsbbcn_%d",xcent));
		bbcsbbcn->Add(bbcsbbcndis_t);
	}
	hbbcs = (TH1D*)bbcsbbcn->ProjectionX("bbcs",0,-1);
	hbbcn = (TH1D*)bbcsbbcn->ProjectionY("bbcn",0,-1);
	hbbcs->Rebin(4);
	hbbcn->Rebin(4);
	c1= new TCanvas();
	c1->cd();
	c1->SetLogy();
	SetTitle(*hbbcs,"bbc charge","# of events","");
	SetRange(*hbbcs,0,1e-1,100,hbbcn->GetMaximum()*5);
	SetStyle(*hbbcs,1.2,1,20,0,0);
	SetStyle(*hbbcn,1.2,2,24,0,0);
	hbbcs->Draw("P");
	hbbcn->Draw("Psame");
	leg->AddEntry(hbbcs,"bbc south");
	leg->AddEntry(hbbcn,"bbc north");
	leg->Draw("same");
	c1->Print(Form("bbcdis.png"));
	c2= new TCanvas();
	c2->cd();
	c2->SetLogy();
	hbbcs_norm = (TH1D*)hbbcs->Clone("hbbcs_norm");
	hbbcn_norm = (TH1D*)hbbcn->Clone("hbbcn_norm");
	hbbcs_norm->Scale(1./hbbcs_norm->Integral());
	hbbcn_norm->Scale(1./hbbcn_norm->Integral());
	SetRange(*hbbcs_norm,0,1e-9,100,1);
	hbbcs_norm->Draw("P");
	hbbcn_norm->Draw("Psame");
	leg->Draw("same");
	c2->Print(Form("bbcdis_norm.png"));	
	c3= new TCanvas();
	c3->cd();
	c3->SetLogz();
	SetTitle(*bbcsbbcn,"bbc charge south","bbc charge north","# of events");
	SetRange(*bbcsbbcn,0,0,100,100);
	bbcsbbcn->Draw("colz");
	c3->Print("bbcsbbcn.png");
}
Example #3
0
TH1D* getSample(TString sample, double weight){
	TString dir = "rootFilesV4/central/";
	TFile* file = new TFile(dir + sample + "_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	//TDirectoryFile* folder = (TDirectoryFile*) file->Get("TTbarPlusMetAnalysis/QCD No Iso/Muon/");
	
	TH1D* plot = (TH1D*) file->Get("EventCount/"+Variable);

        if(sample == "TTJet"){
	plot->SetFillColor(kRed+1);
        plot->SetLineColor(kRed+1);
	}else if(sample == "WJetsToLNu" || sample == "W1Jet" || sample == "W2Jets"|| sample == "W3Jets"|| sample == "W4Jets"){
	plot->SetLineColor(kGreen-3);	  
  	plot->SetFillColor(kGreen-3);
	}else if(sample == "DYJetsToLL" || sample == "DY1JetsToLL" || sample == "DY2JetsToLL" || sample == "DY3JetsToLL" || sample == "DY4JetsToLL"){
	plot->SetFillColor(kAzure-2);
	plot->SetLineColor(kAzure-2);
	}else if(sample == "QCD_Pt_20_MuEnrichedPt_15" || sample == "QCD_Pt-15to20_MuEnrichedPt5" || sample=="QCD_Pt-15to20_MuEnrichedPt5" || sample =="QCD_Pt-20to30_MuEnrichedPt5" || sample ==    "QCD_Pt-30to50_MuEnrichedPt5" || sample ==    "QCD_Pt-50to80_MuEnrichedPt5" || sample ==    "QCD_Pt-80to120_MuEnrichedPt5" || sample ==   "QCD_Pt-120to170_MuEnrichedPt5" || sample ==  "QCD_Pt-170to300_MuEnrichedPt5" || sample ==  "QCD_Pt-300to470_MuEnrichedPt5" || sample ==  "QCD_Pt-470to600_MuEnrichedPt5" || sample ==  "QCD_Pt-800to1000_MuEnrichedPt5" || sample =="QCD_Pt-1000_MuEnrichedPt5" 	 ){
	plot->SetFillColor(kYellow);
	plot->SetLineColor(kYellow);
	}else if(sample == "T_t-channel" || sample == "T_tW-channel" || sample == "T_s-channel" || sample == "Tbar_t-channel" || sample == "Tbar_tW-channel" || sample == "Tbar_s-channel"){
	plot->SetFillColor(kMagenta);
	plot->SetLineColor(kMagenta);
	}
	
	if(sample != "SingleMu")
	plot->Scale(19.605/19.584);
	//plot->Scale(weight);
	
	plot->Rebin(rebinFact);
	
	return plot;

}
Example #4
0
TH1D* getQCD(int rebinFact){
	TString dir = "rootFiles/";
	
	TFile* file = new TFile(dir +"qcdest.root");		
	TH1D* plot = (TH1D*) file->Get("muon_AbsEta_0btag");

// 	for(int i = 1; i <= plot->GetNbinsX(); i++){
// 	plot->SetBinError(i, 0.0);
// 	}

	plot->SetFillColor(kYellow);
	plot->SetLineColor(kYellow);
	plot->SetMarkerStyle(1);
		
	TH1D* copyplot = new TH1D("qcd plot", "qcd plot", 30, 0.0, 3.0);
	
	for(int i = 1; i <= plot->GetNbinsX(); i++){
	copyplot->SetBinContent(i, plot->GetBinContent(i));
	//copyplot->SetBinError(i, plot->GetBinError(i));
	}
	copyplot->SetFillColor(kYellow);
	copyplot->SetLineColor(kYellow);
	copyplot->SetMarkerStyle(1);
	copyplot->Scale(1./copyplot->Integral());	
	copyplot->Rebin(rebinFact);
	
	//file->Close("R");
	return copyplot;
	//file->Close();
}
Example #5
0
  /*--------------------------------------------*/
 void FitCosTheta()
 /*--------------------------------------------*/
 {

//TH1F *brgauss = new TH1F("breitg","", 131, 0, 130);
TFile * file = new TFile("cosTheta_allnadjieh.root","READ");
 TH1D * h = (TH1D*)file->Get("cosThetaGen");
//h->Scale(1./h->Integral());

 h->Sumw2();
/*TFile * file= new TFile("WPol_SelectedTTBars.root","read");
TH1D* h = (TH1D*)file->Get("costheta_mm/hCosThetaPosLepton_Gen");*/
h->Rebin(10);
//h->Scale(1./h->Integral());
 TF1 *f = new TF1("f",cosTheta, -1, 1 ,3);
 Double_t par[3];
 par[0] = 1;
 par[1] = 1;
 par[2] = h->GetEntries();
 


 f->SetParameters(par);
 
 h->Fit(f, "RBO");
 h->Fit(f, "RBO");
 h->Fit(f, "RBO");
 h->Fit(f, "RBO");
 h->Fit(f, "RBO");

 }
Example #6
0
TH1D * GetNominal(std::string fname){
	TFile * f = TFile::Open(fname.c_str());
	TH1D * ret = (TH1D*)f->Get("Default_allW/Default_allWcosTheta");
	ret->Rebin(2);
	//delete f;
	return ret;
}
Example #7
0
void rebin (const char* filename, const char* histname, double rebin=2.0) {
        TFile* f = new TFile(filename,"update");
        TH1D* h = (TH1D*)f->Get(histname);
        h->Rebin(rebin);
        h->Scale(1.0/rebin);
        TFile* fileOut = new TFile(Form("rebin_%s",filename), "update");
        h->Write();
}
TH1D* Prediction::GetScaledHisto(TH1D* histo, float scale_fact, float scale_fact_err){
	// takes histo, scale factor and uncertainty on scale factor
	// and returns scaled and rebinned histo with 1 bin with uncertainty on scale factor propagated.
	TH1D *h        = (TH1D*) histo->Clone(histo->GetName());
	h->Rebin(h->GetNbinsX());
	h->SetBinError(1, sqrt(h->GetBinError(1)*  h->GetBinError(1)   *scale_fact    *scale_fact + 
			  h->GetBinContent(1)*h->GetBinContent(1) *scale_fact_err*scale_fact_err));
	h->SetBinContent(1, h->GetBinContent(1)*scale_fact);
	return h;
}
TH1D * getNiceHistogram(int nbins, std::vector<Double_t> binning, TFile * file, TString hist) {
  TH1D *sample = (TH1D*)(file->Get(hist)->Clone());
  TH1D *binned = dynamic_cast<TH1D*>(sample->Rebin(nbins,"madgraph",&binning.front()));
  for (Int_t bin=0; bin < nbins; bin++) {
    // Divide rebinned histogram's bin content by bin width factor (new/old):
    binned->SetBinError(bin+1,sqrt(binned->GetBinContent(bin+1))/((binning.at(bin+1)-binning.at(bin))/sample->GetBinWidth(1)));
    binned->SetBinContent(bin+1,binned->GetBinContent(bin+1)/((binning.at(bin+1)-binning.at(bin))/sample->GetBinWidth(1)));
  }
  binned->Scale(1/binned->Integral("width"));
  return binned;
}
Example #10
0
TH1D * DrawHistogram(TList *list, char *name,char *option, Int_t rebin, Int_t color, Int_t marker, Float_t scale, Bool_t draw = kTRUE){

  TH1D *histo = list->FindObject(name);
  histo->SetMarkerColor(color);
  histo->SetMarkerStyle(marker);
  histo->SetLineColor(color);
  histo->Rebin(rebin);
  histo->Scale(1.0/((Float_t)rebin));
  histo->Scale(scale);
  histo->SetMarkerSize(1.2);
  if(draw) histo->Draw(option);
  return histo;
}
TH1D* Prediction::GetScaledHisto(TH1D* histo, float scale_fact, float scale_fact_err, int ngroup){
	// takes histo, scale factor and uncertainty on scale factor
	// and returns scaled and rebinned histo with ngroup bins merged into 1 with uncertainty on scale factor propagated.
	if(ngroup>=histo->GetNbinsX()) ngroup=histo->GetNbinsX();
	TH1D *h        = (TH1D*) histo->Clone(histo->GetName());
	h->Rebin(ngroup);
	for(int i=1; i<=h->GetNbinsX(); ++i){
		h->SetBinError(i, sqrt(h->GetBinError(i)*  h->GetBinError(i)   *scale_fact    *scale_fact + 
				  h->GetBinContent(i)*h->GetBinContent(i) *scale_fact_err*scale_fact_err));
		h->SetBinContent(i, h->GetBinContent(i)*scale_fact);
	}
	return h;
}
TH1D* readHist(TString nameHist,TString nameFile, int rebin)
{
 TFile* file = new TFile(nameFile);

 TH1D* hist = (TH1D*)file->Get(nameHist);
 hist->GetSumw2();
 // hist->SetLineWidth(2);
 if(rebin>0) hist->Rebin(rebin);
 hist->GetXaxis()->SetTitleSize(.055);
 hist->GetYaxis()->SetTitleSize(.055);
 hist->GetXaxis()->SetLabelSize(.05);
 hist->GetYaxis()->SetLabelSize(.05);
 hist->SetStats(kFALSE);
 return hist;
}
Example #13
0
TH1D* combineRebin10bins(std::vector<TFile*> files, std::string histName, std::vector<double> scalingFactors) {
    TH1::SetDefaultSumw2();
    std::vector<double> massBins = generate10Bins();
    int nBinsX = massBins.size()-1;
    // Get 1st hist in list
    TH1D* h = (TH1D*)files[0]->Get(histName.c_str())->Clone(files[0]->Get(histName.c_str())->GetName());
    h->Scale(scalingFactors[0]);
    
    for (unsigned i = 1; i < files.size(); i++) {
        TH1D* hTmp = (TH1D*) (files[i]->Get(histName.c_str()));
        h->Add(hTmp, scalingFactors[i]);
    }
    // /files[0]->Get(histName.c_str())->GetTitle()
    TH1D* hNew = h->Rebin(nBinsX, files[0]->Get(histName.c_str())->GetTitle(), &massBins[0]);
    return hNew;
}
Example #14
0
std::vector<TH1D*> hists(std::string dname, std::string fname){
	std::vector<TH1D*> ret;
	std::vector<std::string> dirs = SetDirectories();
	cout<<"directory is done "<<dname<<"\t"<<fname<<endl;
	TFile * f = 0;
	for(unsigned int i = 0; i < dirs.size(); i++){
		std::string filename = dname + "/" + dirs[i] + "/All" + fname + ".root";
		f = TFile::Open(filename.c_str());
		TH1D* h = (TH1D*)f->Get("Default_allW/Default_allWcosTheta");
		h->Rebin(10);
		ret.push_back(h);
		cout<<ret[ret.size()-1]->GetName()<<"\t"<<ret[ret.size()-1]->GetXaxis()->GetNbins()<<endl;
	}
	//delete f;
	return ret;
}
Example #15
0
// Draw 1D histos
TH1D *plot1Dhisto(double intLumi,TFile *fileName,TString folderName,TString histoName,int color,int rebin,float xMin,float xMax,TString xName, TString yName,TString sampleName,bool mc) {  
  
  TH1D *hTemp = (TH1D*)fileName->Get(folderName+"/"+histoName);
  hTemp->SetName(histoName+"_"+sampleName);
  if (mc){ 
    hTemp->Scale(intLumi/100.);
  }
  hTemp->Rebin(rebin);
  hTemp->SetLineColor(color);
  hTemp->SetLineWidth(5);
  hTemp->GetXaxis()->SetRangeUser(xMin,xMax);
  hTemp->GetXaxis()->SetTitle(xName);
  hTemp->GetXaxis()->SetTitleSize(0.06);
  hTemp->GetXaxis()->SetLabelSize(0.06);
  hTemp->GetYaxis()->SetTitle(yName);
  hTemp->GetYaxis()->SetTitleSize(0.06);
  hTemp->GetYaxis()->SetLabelSize(0.06);
  hTemp->SetTitleOffset(1.5, "Y");
  // last/first bin: put over/underflow
  hTemp->SetBinContent(hTemp->FindBin(xMax),hTemp->Integral(hTemp->FindBin(xMax),hTemp->GetNbinsX()+1));
  hTemp->SetBinContent(hTemp->FindBin(xMin),hTemp->Integral(-1,hTemp->FindBin(xMin)));  

  hTemp->SetBinError(hTemp->FindBin(xMax),sqrt(hTemp->Integral(hTemp->FindBin(xMax),hTemp->GetNbinsX()+1)));
  hTemp->SetBinError(hTemp->FindBin(xMin),sqrt(hTemp->Integral(-1,hTemp->FindBin(xMin))));
  //fileName->Close();

  /*
  if (histoName != "LP_tot") {
    if (histoName != "SumLepPt_tot") {
      if ((folderName == "ANplots150_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,300.); } 
      if ((folderName == "ANplots250_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,400.); }
      if ((folderName == "ANplots350_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,500.); }
      if ((folderName == "ANplots450_NOLP")) { hTemp->GetXaxis()->SetRangeUser(0.,1000.); }
    }
    else {
      if ((folderName == "ANplots150_NOLP")) { hTemp->GetXaxis()->SetRangeUser(100.,300.); } 
      if ((folderName == "ANplots250_NOLP")) { hTemp->GetXaxis()->SetRangeUser(200.,400.); }
      if ((folderName == "ANplots350_NOLP")) { hTemp->GetXaxis()->SetRangeUser(300.,500.); }
      if ((folderName == "ANplots450_NOLP")) { hTemp->GetXaxis()->SetRangeUser(400.,1000.); }
    }
  } 
  */ 
  return hTemp;
} // ~ end of plot1Dhisto function
Example #16
0
//always data
TH1D* getQCD(TString Obj, TString Variable, int rebinFact){
	TString dir = "rootFilesV4/central/";
	TFile* file = new TFile(dir + "SingleMu_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	//TDirectoryFile* folder = (TDirectoryFile*) file->Get("TTbarPlusMetAnalysis/QCD No Iso/Muon/");

	TH1D* plot = (TH1D*) file->Get("TTbar_plus_X_analysis/MuPlusJets/QCD non iso mu+jets ge4j/"+Obj+Variable+"0btag");

	plot->SetFillColor(kYellow);
	plot->SetLineColor(kYellow);
    	
	plot->Scale(1/plot->Integral());
	plot->Rebin(rebinFact);

	plot->SetDirectory(gROOT);
	file->Close();

	return plot;

}
Example #17
0
TCanvas* Com(TString plot,TString plot_dir,UInt_t rbin, TString xtitle, Double_t max, TString title){
  gROOT->SetStyle("Plain");
  gStyle->SetTitleFontSize(0.07);
 TH1D *Sig = ((TH1D*)Sig->Get(plot_dir+"/"+plot))->Clone();
 TH1D *Bkgd= ((TH1D*)Bkgd->Get(plot_dir+"/"+plot))->Clone();
 Sig->Rebin(rbin);
 Bkgd->Rebin(rbin);
 Sig->Scale(1/(Sig->Integral()));
 Bkgd->Scale(1/(Bkgd->Integral()));
 //TLine *li =new TLine(0.55,0.,0.55,100000);
TCanvas* c = new TCanvas(plot_dir+plot,plot_dir+plot);
 c->SetLogy();

 TLegend *leg = new TLegend(0.5,0.8,0.99,0.99);
 leg->SetFillColor(0);
 leg->AddEntry(Sig,"Selected events","L");
 leg->AddEntry(Bkgd,"Anti-selected events","L");
 Sig->SetLineColor(kRed);
 Sig->SetLineWidth(2);
 Bkgd->SetLineColor(kBlue);
 Bkgd->SetLineWidth(2);
 Sig->Draw("EHIST");
 Bkgd->Draw("HISTSAME");
 leg->Draw("SAME");
 //      li->Draw("SAME");
 Sig->SetTitle(title);

Sig->SetStats(kFALSE);
 Sig->GetXaxis()->SetTitle(xtitle);
 if (max == 999999){

 }
 else{
   Sig->GetXaxis()->SetRangeUser(0.2,max);}
 Sig->GetYaxis()->SetTitle("");
 c->Update();
 c->SaveAs(saving+"IDinv_Delta_"+plot_dir+plot+".png");
 return c;


}
Example #18
0
  // -- Draw 1D histos
TH1D *plot1Dhisto(double intLumi,TFile *fileName,TString folderName,TString histoName,int color,int rebin,float xMin,float xMax,TString xName, TString yName,TString sampleName,bool mc) {

  
  
  TH1D *hTemp = (TH1D*)fileName->Get(folderName+"/"+histoName); hTemp->SetName(histoName+"_"+sampleName);
  //  hTemp->Sumw2();
  if (mc) { hTemp->Scale(intLumi/100.); }
  hTemp->Rebin(rebin);
  hTemp->SetLineColor(color);
  hTemp->SetLineWidth(3);
  hTemp->GetXaxis()->SetRangeUser(xMin,xMax);
  hTemp->GetXaxis()->SetTitle(xName);
  hTemp->GetYaxis()->SetTitle(yName);

  // last bin: put put overflow
  hTemp->SetBinContent(hTemp->FindBin(xMax),hTemp->Integral(hTemp->FindBin(xMax),hTemp->GetNbinsX()+1));
  //  cout << "Nbins=" << hTemp->GetNbinsX() << "\n";
  

  
  return hTemp;
} // ~ end of plot1Dhisto function
Example #19
0
void trksplit()
{
  TFile* f = new TFile("../cfg/dihadroncorrelation_wsplit_real_cent010_mc.root");
  TFile* f1 = new TFile("../cfg/dihadroncorrelation_wosplit_cent010_mc.root");
 
  TH1D* hpt = (TH1D*)f->Get("corr_ana_HI/ptall_trg");
  TH1D* hpt1 = (TH1D*)f1->Get("corr_ana_HI/ptall_trg");
  hpt->SetMarkerStyle(20);
  hpt1->SetMarkerStyle(20);
  hpt->SetMarkerColor(4);
  hpt->Rebin(4);
  hpt1->Rebin(4);

  TCanvas* c = new TCanvas("c","c",500,450);
  hpt->SetAxisRange(0,5.0,"X");
  hpt->Draw("PE");
  hpt1->Draw("PESAME");

  TH1D* hratio = (TH1D*)hpt->Clone("hratio");
  hratio->Divide(hpt1);

  TCanvas* c1 = new TCanvas("c1","c1",500,450);
  hratio->Draw("PE");
}
void RebinHist(TH1D* h1, TFile *out)
{
  // This rebinning method doesn't work
  // It needs to divide by the entries to make an average
  // Also, it doesn't include error weighting.
  cout<<"Rebinning histogram"<<endl;
  Int_t nBins = h1->GetNbinsX();
  TH1D *rebinHist = (TH1D*) h1->Clone();
  rebinHist->Rebin(nBins/2);

  // TFile out("Compare.root","update");
  TDirectory *dir = out->GetDirectory("Rebin");
  if(!dir) dir = out->mkdir("Rebin");
  dir->cd();

  TString histName = h1->GetName();
  histName += "Rebin";
  rebinHist->SetName(histName);
  rebinHist->SetTitle(histName);
  rebinHist->SetDirectory(0);
  rebinHist->Write(rebinHist->GetName(), TObject::kOverwrite);
  // out->Close();

}
Example #21
0
GenVBosonPlot(TString name, int rebin,float min = -1,float max =0, bool log=false){

  //  TCanvas* aCan = new TCanvas(name,name,0.6,0.6,0.8,0.8);

  TCanvas* aCan = new TCanvas(name);
  aCan->Divide(2,1);
  aCan->cd(1);
  if(log) aCan->SetLogy();
  // int rebin= 10;
  TFile* W = new TFile("results5/IC5Calo_WJets_madgraph.root");
  //W->ls();
  TDirectory* Wdir = ( TDirectory*) W->Get("GenVBoson200");
  Wdir->ls();
  TH1D* Wh = (TH1D*) Wdir->Get(name);
  Wh->Rebin(rebin);
  Wh->SetLineWidth(2);
  Wh->SetLineStyle(2);
  //  Wh->
  if(min>-.2)  Wh->GetXaxis()->SetRangeUser(min,max);
 
  Wh->DrawNormalized();
  //cout << Wh->GetMaximum() <<endl;
  Wh->GetXaxis()->SetRangeUser(0.00001,1);

  //  Wh->SetMaximum( Wh->GetMaximum()*1.75);


  TFile* Z = new TFile("results5/IC5Calo_Zinvisible_jets.root");
  //Z->ls();
  TDirectory* Zdir = ( TDirectory*) Z->Get("GenVBoson200");
  //  Zdir->ls();
  TH1D* Zh = (TH1D*) Zdir->Get(name);
  Zh->SetLineColor(kRed);
  Zh->SetLineWidth(2);
  Zh->SetLineStyle(2);

  Zh->Rebin(rebin);
  Zh->DrawNormalized("same");

  TFile* Ph = new TFile("results5/photon.root");
  Ph->ls();
  TDirectory* Phdir = ( TDirectory*) Ph->Get("GenVBoson200");
  // Phdir->ls();
  TH1D* Phh = (TH1D*) Phdir->Get(name);
  Phh->SetLineColor(kBlue);
  Phh->SetLineWidth(2);
  Phh->Rebin(rebin);
  Phh->DrawNormalized("same"); 

  TLegend* leg = new TLegend(0.5,0.5,0.7,0.7);
  leg->AddEntry(Zh,"Z","l" );
  leg->AddEntry(Wh,"W","l" );
  leg->AddEntry(Phh,"#gamma","l" );
  leg->Draw("same");

  aCan->cd(1);

  TH1D*  DivPhh = Phh->Clone();
  DivPhh->Divide(Zh);
  TH1D*  DivWh = Wh->Clone();
  DivWh->Divide(Zh);
  DivPhh->Draw();
DivWh->Draw("same");

}
Example #22
0
void plotFeedDown(int ntest=1, int centL=0,int centH=100)
{
   // B cross-section
   TFile *inf = new TFile("output_pp_Bmeson_5TeV_y1.root");
//   TFile *inf = new TFile("outputBplus_D_pp_rap24.root");
//    TFile *inf = new TFile("outputBplus_pp.root");
   TH1D *hBPtMax = (TH1D*)inf->Get("hmaxall");
   TH1D *hBPtMin = (TH1D*)inf->Get("hminall");
   TH1D *hBPt = (TH1D*)inf->Get("hpt");
   hBPt->SetName("hBPt");
   hBPtMax->SetName("hBPtMax");
   hBPtMin->SetName("hBPtMin");

   TH1D *hBMaxRatio = (TH1D*)hBPt->Clone("hBMaxRatio");
   hBMaxRatio->Divide(hBPtMax);

   TH1D *hBMinRatio = (TH1D*)hBPt->Clone("hBMinRatio");
   hBMinRatio->Divide(hBPtMin);

   
   hBPt->Rebin(1); 
   
   // D cross-section
//   TFile *infD = new TFile("outputD0_D_pp.root");
   TFile *infD = new TFile("output_pp_d0meson_5TeV_y1.root");
   TH1D *hDPtMax = (TH1D*)infD->Get("hmaxall");
   TH1D *hDPtMin = (TH1D*)infD->Get("hminall");
   TH1D *hDPt = (TH1D*)infD->Get("hpt");
   hDPt->SetName("hDPt");
   hDPtMax->SetName("hDPtMax");
   hDPtMin->SetName("hDPtMin");
   hDPt->Rebin(1); 

   // ratio of B->D0: not correct85% from PYTHIA
   //hBPt->Scale(0.85);
   hBPt->Scale(0.598);
   
   // c->D (55.7%)
   hDPt->Scale(0.557);

   
   TFile *inf2 = new TFile("/data/HeavyFlavourRun2/BtoDPythia/treefile_merged.root");
//   TFile *inf2 = new TFile("test.root");
   TTree *hi = (TTree*) inf2->Get("ana/hi");

   hi->SetAlias("yD","log((sqrt(1.86484*1.86484+pt*pt*cosh(eta)*cosh(eta))+pt*sinh(eta))/sqrt(1.86484*1.86484+pt*pt))");			    
   hi->SetAlias("yB","log((sqrt(5.3*5.3+pt*pt*cosh(eta)*cosh(eta))+pt*sinh(eta))/sqrt(5.3*5.3+pt*pt))");			    
   hi->SetAlias("yJ","log((sqrt(3.09692*3.09692+pt*pt*cosh(eta)*cosh(eta))+pt*sinh(eta))/sqrt(3.09692*3.09692+pt*pt))");			    


   // 6.5, 8, 10, 13, 30

/*
   TH1D *hBNoCut = (TH1D*)hBPt->Clone("hBNoCut");
   TH1D *hBHasD  = (TH1D*)hBPt->Clone("hBHasD");
   
   hi->Draw("pt>>hBHasD","(abs(pdg)>500&&abs(pdg)<600&&abs(yB)<2.4)&&Sum$(abs(pdg)==421&&abs(yD)<2)>0");
   hi->Draw("pt>>hBNoCut","(abs(pdg)>500&&abs(pdg)<600&&abs(yB)<2.4)");
;

   hBNoCut->Divide(hBHasD);
   hBPt->Divide(hBNoCut);
  */  

// 0-100%
   int npoint = 7;
   	
   double ptBins_npjpsi[8] = {1,3,6.5,8,10,13,30,300};
  
   double raa_npjpsi[7];//      = {1,0.6, 0.52,0.43,0.43,0.34,0.5};  
   double raaStat_npjpsi[7];//  = {1,0.4,0.12,0.08,0.09,0.07,0.5};
   double raaSyst_npjpsi[7];//  = {0,0,0.06,0.05,0.05,0.04,0};

/*
0-10, 10-20, 20-30, 30-40, 40-50, 50-100
double nonPromptJpsiRAA_2012[]           = {0.,0.38,0.43,0.48,0.52,0.65,0.69};
double nonPromptJpsiRAAError_2012[]      = {0.,0.02,0.03,0.03,0.04,0.06,0.07};
double nonPromptJpsiRAAErrorSyst_2012[]  = {0.,0.04,0.05,0.05,0.06,0.07,0.07};
*/

   if (centL==0&&centH==100) {
      raa_npjpsi[0]=1.0;	raaStat_npjpsi[0]=0.0;		raaSyst_npjpsi[0]=1.0;	// no measurement
      raa_npjpsi[1]=0.6;	raaStat_npjpsi[1]=0.0;		raaSyst_npjpsi[1]=0.4;	// prelim
      raa_npjpsi[2]=0.52;	raaStat_npjpsi[2]=0.12;		raaSyst_npjpsi[2]=0.06;	// np jpsi pas
      raa_npjpsi[3]=0.43;	raaStat_npjpsi[3]=0.08;		raaSyst_npjpsi[3]=0.05;	// np jpsi pas
      raa_npjpsi[4]=0.43;	raaStat_npjpsi[4]=0.09;		raaSyst_npjpsi[4]=0.05;	// np jpsi pas
      raa_npjpsi[5]=0.34;	raaStat_npjpsi[5]=0.07;		raaSyst_npjpsi[5]=0.04;	// np jpsi pas
      raa_npjpsi[6]=0.5;	raaStat_npjpsi[6]=0.0;		raaSyst_npjpsi[6]=0.25;	// b-jet
   }
   
   if (centL==0&&centH==10) {
      raa_npjpsi[0]=1.0;	raaStat_npjpsi[0]=0.0;		raaSyst_npjpsi[0]=1.0;	// no measurement
      raa_npjpsi[1]=1.0;	raaStat_npjpsi[1]=0.0;		raaSyst_npjpsi[1]=1.0;	// no measurement
      raa_npjpsi[2]=0.38;	raaStat_npjpsi[2]=0.02;		raaSyst_npjpsi[2]=0.04;	// np jpsi pas
      raa_npjpsi[3]=0.38;	raaStat_npjpsi[3]=0.02;		raaSyst_npjpsi[3]=0.04;	// np jpsi pas
      raa_npjpsi[4]=0.38;	raaStat_npjpsi[4]=0.02;		raaSyst_npjpsi[4]=0.04;	// np jpsi pas
      raa_npjpsi[5]=0.38;	raaStat_npjpsi[5]=0.02;		raaSyst_npjpsi[5]=0.04;	// np jpsi pas
      raa_npjpsi[6]=0.39;	raaStat_npjpsi[6]=0.0;		raaSyst_npjpsi[6]=0.20;	// b-jet
   
   }

   if (centL==10&&centH==20) {
      raa_npjpsi[0]=1.0;	raaStat_npjpsi[0]=0.0;		raaSyst_npjpsi[0]=1.0;	// no measurement
      raa_npjpsi[1]=1.0;	raaStat_npjpsi[1]=0.0;		raaSyst_npjpsi[1]=1.0;	// no measurement
      raa_npjpsi[2]=0.43;	raaStat_npjpsi[2]=0.03;		raaSyst_npjpsi[2]=0.05;	// np jpsi pas
      raa_npjpsi[3]=0.43;	raaStat_npjpsi[3]=0.03;		raaSyst_npjpsi[3]=0.05;	// np jpsi pas
      raa_npjpsi[4]=0.43;	raaStat_npjpsi[4]=0.03;		raaSyst_npjpsi[4]=0.05;	// np jpsi pas
      raa_npjpsi[5]=0.43;	raaStat_npjpsi[5]=0.03;		raaSyst_npjpsi[5]=0.05;	// np jpsi pas
      raa_npjpsi[6]=0.47;	raaStat_npjpsi[6]=0.0;		raaSyst_npjpsi[6]=0.24;	// b-jet
   
   }

   if (centL==20&&centH==30) {
      raa_npjpsi[0]=1.0;	raaStat_npjpsi[0]=0.0;		raaSyst_npjpsi[0]=1.0;	// no measurement
      raa_npjpsi[1]=1.0;	raaStat_npjpsi[1]=0.0;		raaSyst_npjpsi[1]=1.0;	// no measurement
      raa_npjpsi[2]=0.48;	raaStat_npjpsi[2]=0.03;		raaSyst_npjpsi[2]=0.05;	// np jpsi pas
      raa_npjpsi[3]=0.48;	raaStat_npjpsi[3]=0.03;		raaSyst_npjpsi[3]=0.05;	// np jpsi pas
      raa_npjpsi[4]=0.48;	raaStat_npjpsi[4]=0.03;		raaSyst_npjpsi[4]=0.05;	// np jpsi pas
      raa_npjpsi[5]=0.48;	raaStat_npjpsi[5]=0.03;		raaSyst_npjpsi[5]=0.05;	// np jpsi pas
      raa_npjpsi[6]=0.47;	raaStat_npjpsi[6]=0.0;		raaSyst_npjpsi[6]=0.24;	// b-jet
   
   }

   if (centL==30&&centH==40) {
      raa_npjpsi[0]=1.0;	raaStat_npjpsi[0]=0.0;		raaSyst_npjpsi[0]=1.0;	// no measurement
      raa_npjpsi[1]=1.0;	raaStat_npjpsi[1]=0.0;		raaSyst_npjpsi[1]=1.0;	// no measurement
      raa_npjpsi[2]=0.52;	raaStat_npjpsi[2]=0.04;		raaSyst_npjpsi[2]=0.06;	// np jpsi pas
      raa_npjpsi[3]=0.52;	raaStat_npjpsi[3]=0.04;		raaSyst_npjpsi[3]=0.06;	// np jpsi pas
      raa_npjpsi[4]=0.52;	raaStat_npjpsi[4]=0.04;		raaSyst_npjpsi[4]=0.06;	// np jpsi pas
      raa_npjpsi[5]=0.52;	raaStat_npjpsi[5]=0.04;		raaSyst_npjpsi[5]=0.06;	// np jpsi pas
      raa_npjpsi[6]=0.61;	raaStat_npjpsi[6]=0.0;		raaSyst_npjpsi[6]=0.30;	// b-jet
   
   }

   if (centL==40&&centH==50) {
      raa_npjpsi[0]=1.0;	raaStat_npjpsi[0]=0.0;		raaSyst_npjpsi[0]=1.0;	// no measurement
      raa_npjpsi[1]=1.0;	raaStat_npjpsi[1]=0.0;		raaSyst_npjpsi[1]=1.0;	// no measurement
      raa_npjpsi[2]=0.65;	raaStat_npjpsi[2]=0.06;		raaSyst_npjpsi[2]=0.07;	// np jpsi pas
      raa_npjpsi[3]=0.65;	raaStat_npjpsi[3]=0.06;		raaSyst_npjpsi[3]=0.07;	// np jpsi pas
      raa_npjpsi[4]=0.65;	raaStat_npjpsi[4]=0.06;		raaSyst_npjpsi[4]=0.07;	// np jpsi pas
      raa_npjpsi[5]=0.65;	raaStat_npjpsi[5]=0.06;		raaSyst_npjpsi[5]=0.07;	// np jpsi pas
      raa_npjpsi[6]=0.61;	raaStat_npjpsi[6]=0.0;		raaSyst_npjpsi[6]=0.30;	// b-jet
   
   }

   if (centL==50&&centH==100) {
      raa_npjpsi[0]=1.0;	raaStat_npjpsi[0]=0.0;		raaSyst_npjpsi[0]=1.0;	// no measurement
      raa_npjpsi[1]=1.0;	raaStat_npjpsi[1]=0.0;		raaSyst_npjpsi[1]=1.0;	// no measurement
      raa_npjpsi[2]=0.69;	raaStat_npjpsi[2]=0.07;		raaSyst_npjpsi[2]=0.07;	// np jpsi pas
      raa_npjpsi[3]=0.69;	raaStat_npjpsi[3]=0.07;		raaSyst_npjpsi[3]=0.07;	// np jpsi pas
      raa_npjpsi[4]=0.69;	raaStat_npjpsi[4]=0.07;		raaSyst_npjpsi[4]=0.07;	// np jpsi pas
      raa_npjpsi[5]=0.69;	raaStat_npjpsi[5]=0.07;		raaSyst_npjpsi[5]=0.07;	// np jpsi pas
      raa_npjpsi[6]=0.70;	raaStat_npjpsi[6]=0.0;		raaSyst_npjpsi[6]=0.35;	// b-jet
   
   }


   if (centL==0&&centH==20) {  //averaged by ncoll
      raa_npjpsi[0]=1.0;	raaStat_npjpsi[0]=0.0;		raaSyst_npjpsi[0]=1.0;	// no measurement
      raa_npjpsi[1]=1.0;	raaStat_npjpsi[1]=0.0;		raaSyst_npjpsi[1]=1.0;	// no measurement
      raa_npjpsi[2]=0.4;	raaStat_npjpsi[2]=0.03;		raaSyst_npjpsi[2]=0.05;	// np jpsi pas
      raa_npjpsi[3]=0.4;	raaStat_npjpsi[3]=0.03;		raaSyst_npjpsi[3]=0.05;	// np jpsi pas
      raa_npjpsi[4]=0.4;	raaStat_npjpsi[4]=0.03;		raaSyst_npjpsi[4]=0.05;	// np jpsi pas
      raa_npjpsi[5]=0.4;	raaStat_npjpsi[5]=0.03;		raaSyst_npjpsi[5]=0.05;	// np jpsi pas
      raa_npjpsi[6]=0.42;	raaStat_npjpsi[6]=0.0;		raaSyst_npjpsi[6]=0.21;	// b-jet
   
   }

   if (centL==10&&centH==30) {  //averaged by ncoll
      raa_npjpsi[0]=1.0;	raaStat_npjpsi[0]=0.0;		raaSyst_npjpsi[0]=1.0;	// no measurement
      raa_npjpsi[1]=1.0;	raaStat_npjpsi[1]=0.0;		raaSyst_npjpsi[1]=1.0;	// no measurement
      raa_npjpsi[2]=0.45;	raaStat_npjpsi[2]=0.03;		raaSyst_npjpsi[2]=0.05;	// np jpsi pas
      raa_npjpsi[3]=0.45;	raaStat_npjpsi[3]=0.03;		raaSyst_npjpsi[3]=0.05;	// np jpsi pas
      raa_npjpsi[4]=0.45;	raaStat_npjpsi[4]=0.03;		raaSyst_npjpsi[4]=0.05;	// np jpsi pas
      raa_npjpsi[5]=0.45;	raaStat_npjpsi[5]=0.03;		raaSyst_npjpsi[5]=0.05;	// np jpsi pas
      raa_npjpsi[6]=0.47;	raaStat_npjpsi[6]=0.0;		raaSyst_npjpsi[6]=0.24;	// b-jet
   
   }


   if (centL==30&&centH==50) {  //averaged by ncoll
      raa_npjpsi[0]=1.0;	raaStat_npjpsi[0]=0.0;		raaSyst_npjpsi[0]=1.0;	// no measurement
      raa_npjpsi[1]=1.0;	raaStat_npjpsi[1]=0.0;		raaSyst_npjpsi[1]=1.0;	// no measurement
      raa_npjpsi[2]=0.57;	raaStat_npjpsi[2]=0.06;		raaSyst_npjpsi[2]=0.07;	// np jpsi pas
      raa_npjpsi[3]=0.57;	raaStat_npjpsi[3]=0.06;		raaSyst_npjpsi[3]=0.07;	// np jpsi pas
      raa_npjpsi[4]=0.57;	raaStat_npjpsi[4]=0.06;		raaSyst_npjpsi[4]=0.07;	// np jpsi pas
      raa_npjpsi[5]=0.57;	raaStat_npjpsi[5]=0.06;		raaSyst_npjpsi[5]=0.07;	// np jpsi pas
      raa_npjpsi[6]=0.61;	raaStat_npjpsi[6]=0.0;		raaSyst_npjpsi[6]=0.30;	// b-jet
   
   }


   TH1D *hNPJpsiRAA = new TH1D("hNPJpsiRAA","",npoint,ptBins_npjpsi);

   for (int i=1;i<=npoint;i++)
   {
      hNPJpsiRAA->SetBinContent(i,raa_npjpsi[i-1]);      
      hNPJpsiRAA->SetBinError(i,sqrt(raaSyst_npjpsi[i-1]*raaSyst_npjpsi[i-1]+raaStat_npjpsi[i-1]*raaStat_npjpsi[i-1]));     }

   TCanvas *cJpsiRAA = new TCanvas("cJpsiRAA","",600,600);
   cJpsiRAA->SetLogx();
   TExec *setex2 = new TExec("setex2","gStyle->SetErrorX(0.5)");
   setex2->Draw();
   hNPJpsiRAA->SetXTitle("Non-prompt J/psi R_{AA} (GeV/c)");
   hNPJpsiRAA->SetXTitle("Non-prompt J/psi p_{T} (GeV/c)");
   hNPJpsiRAA->SetYTitle("R_{AA}");
   hNPJpsiRAA->Draw("e1");


   TCanvas *c = new TCanvas("c","",600,600);   

   TH2D *hJpsi= new TH2D("hJpsi","",hBPt->GetNbinsX(),hBPt->GetBinLowEdge(1),hBPt->GetBinLowEdge(hBPt->GetNbinsX()+1),
                            299*4,1,300);
   TH2D *hD= new TH2D("hD","",hBPt->GetNbinsX(),hBPt->GetBinLowEdge(1),hBPt->GetBinLowEdge(hBPt->GetNbinsX()+1),
                            299*4,1,300);
    hi->Draw("pt:BPt>>hJpsi","pdg==443&&BPt>0&&abs(yJ)<1");	
    hi->Draw("pt:BPt>>hD","abs(pdg)==421&&BPt>0&&abs(yD)<1");	
 
   hJpsi->Sumw2();   
   hD->Sumw2();   
   reweighthisto(hBPt,hD);
   reweighthisto(hBPt,hJpsi);
   hJpsi->ProjectionY()->Draw("hist");
   hD->SetLineColor(4);
   hD->SetMarkerColor(4);
   hD->ProjectionY()->Draw("hist same");
   hBPt->Draw("hist same");
   
   hJpsi->SetXTitle("B p_{T} (GeV/c)");
   hJpsi->SetYTitle("J/#psi p_{T} (GeV/c)");
   hD->SetXTitle("B p_{T} (GeV/c)");
   hD->SetYTitle("D^{0} p_{T} (GeV/c)");
   
   TCanvas *c2= new TCanvas("c2","B RAA band",600,600);
   
   TRandom2 rnd;
//   hJpsi	->ProjectionX()->Draw("hist");
   TH2D *hRAATmp = new TH2D("hRAATmp","",97,3,100,100,0,2);
   hRAATmp->SetXTitle("B p_{T} (GeV/c)");
   hRAATmp->SetYTitle("R_{AA}");
   hRAATmp->Draw();

   TCanvas *c3= new TCanvas("c3","D RAA band",600,600);
   TH2D *hDRAATmp = new TH2D("hDRAATmp","",47,3,50,100,0,2);
   hDRAATmp->SetXTitle("D^{0} p_{T} (GeV/c)");
   hDRAATmp->SetYTitle("R_{AA}");

   hDRAATmp->Draw();

   TCanvas *c4= new TCanvas("c4","B->D fraction band",600,600);
   TH2D *hBtoDTmp = new TH2D("hBtoDTmp","",47,3,50,100,0,2);
   hBtoDTmp->SetXTitle("D^{0} p_{T} (GeV/c)");
   hBtoDTmp->SetYTitle("Non-prompt D fraction");
   hBtoDTmp->Draw();
   
   TH1D *hDFromBPt= (TH1D*)hD->ProjectionY()->Clone("hDFromBPt");
   TH1D *hDFromBPtFraction= (TH1D*)hD->ProjectionY()->Clone("hDFromBPtFraction");
   hDFromBPtFraction->Divide(hDPt);
   TH1D *hDFromBPtMax= (TH1D*)hD->ProjectionY()->Clone("hDFromBPtMax");
   TH1D *hDFromBPtMin= (TH1D*)hD->ProjectionY()->Clone("hDFromBPtMin");
   
   setHist(hDFromBPtMax,-1e10);
   setHist(hDFromBPtMin,1e10);
   
   for (int i=0;i<ntest;i++)
   {
       if (i%10==0) cout <<i<<endl;	
       TH1D *hRAASample = (TH1D*)hNPJpsiRAA->Clone(Form(	"hRAASample_%d",i));
       for (int j=1;j<=hRAASample->GetNbinsX();j++) {
          double RAA = (rnd.Rndm()*2-1)*hNPJpsiRAA->GetBinError(j)+hNPJpsiRAA->GetBinContent(j);
	  hRAASample->SetBinContent(j,RAA);
       }
       
       TH2D *hJpsiClone = (TH2D*)hJpsi->Clone(Form("hJpsiClone_%d",i));

       reweighthisto(hBPt,hJpsiClone,hRAASample,1);
       TH1D *hBRAA = hJpsiClone->ProjectionX(Form("hBRAA_%d",i));
       
       c2->cd();
       hBRAA->Divide(hBPt);
       hBRAA->SetLineWidth(3);
       hBRAA->SetLineColor(kGray);
       hBRAA->Rebin(4);
       hBRAA->Scale(1./4.);
       hBRAA->Draw("hist c same");
       
       delete hJpsiClone;
       
       TH2D *hDClone = (TH2D*)hD->Clone(Form("hDClone_%d",i));
       reweighthisto(hBPt,hDClone,hBRAA,0,1);
       
       
       TH1D *hDRAA = hDClone->ProjectionY(Form("hDRAA_%d",i));
       
       getMaximum(hDFromBPtMax,hDRAA);
       getMinimum(hDFromBPtMin,hDRAA);
       
       c3->cd();
       hDRAA->Divide(hDFromBPt);
       hDRAA->SetLineWidth(3);
       hDRAA->SetLineColor(kGray);
       hDRAA->Draw("hist c same");
       
       c4->cd();
       TH1D *hBtoDFrac = hDClone->ProjectionY(Form("hBtoDFrac_%d",i));
       
       hBtoDFrac->Divide(hDPt);
       hBtoDFrac->SetLineWidth(3);
       hBtoDFrac->SetLineColor(kGray);
       hBtoDFrac->Draw("hist same");
       
       delete hDClone;      
//       delete hBRAA;      
//       delete hDRAA;      
       
   }	   
   
   TFile *outf = new TFile(Form("BtoD-%d-%d.root",centL,centH),"recreate");

   TH1D *hDFromBPtCentral=(TH1D*)hDFromBPtMax->Clone("hDFromBPtCentral");
   hDFromBPtCentral->Add(hDFromBPtMin);
   hDFromBPtCentral->Scale(1./2);
   
   hNPJpsiRAA->Write();
   hDFromBPtMax->Write();
   hDFromBPtMin->Write();
   hDFromBPtCentral->Write();
   hDFromBPt->Write();
   hJpsi->Write();
   hD->Write();
   hDFromBPtFraction->Write();
   outf->Write();

   
       
}
void roo_fitWHSStudyBG()
{

    gSystem->Load("libRooFit");
    gSystem->Load("libRooFitCore");
    gSystem->Load("libMatrix");
    gSystem->Load("libGpad");
    using namespace RooFit;

    TString poscharge = "Plus";
    TString negcharge = "Minus";

    std::vector<TString> charge(2);
    charge.at(0) = poscharge;
    charge.at(1) = negcharge;

    TString bin1 = "50toinf";
    TString bin2 = "70toinf";
    TString bin3 = "90toinf";

    TString folder = "hltmu9_goodevsel";
    TString noMTpath = "";

    bool makePlots = true;
    bool printPlots = false;
    bool doToyMC = false;
    bool AddQCD = false;
    bool AddQCDbgtemplate = false;
    bool AddZ = true;
    bool AddZbgtemplate = true;
    bool AddTT = true;
    bool AddTTbgtemplate = true;
    bool noMT = false;
    bool realdata = false;
    if(noMT) noMTpath = "_noMT";

    std::vector<TString> bins(1);
    bins.at(0) = bin1;
    //bins.at(1) = bin2;
    //bins.at(2) = bin3;

    //define the data files
    TFile * templates = new TFile("results/" + folder + "/RecoRoutines_W-selection_WJets_madgraph_June2010.root");
    //TFile * dataplus = new TFile("results/" + folder + "/RecoRoutines_W-selection_realdata.root");
    TFile * dataplus = new TFile("results/" + folder + "/RecoRoutines_W-selection_WJets_madgraph_June2010.root");
    TFile * QCDbg = new TFile("results/" + folder + "/RecoRoutines_W-selection_QCD_AllPtBins_7TeV_Pythia.root");
    TFile * TTbg = new TFile("results/" + folder + "/RecoRoutines_W-selection_TTbarJets_tauola_madgraph_June2010.root");
    TFile * Zbg = new TFile("results/" + folder + "/RecoRoutines_W-selection_ZJets_madgraph_June2010.root");

    //define the reference template file
    TFile * refTemplates = new TFile("results/GenRoutines_WJets_JuneMadgraph_1muonextra.root");

    double err1=0.0;
    double comberr=0.0;
    double value1=0.0;

    double lowlim_fit = -0.5;
    double uplim_fit = 1.8;
    Int_t rbin=10;

    TString canvas_name_plus = "MC_WHelicityFramePlots_PlusLPVar";
    TCanvas *c0 = new TCanvas(canvas_name_plus,"",450,470);//900,320);
    //c0->Divide(3,1);

    TString canvas_name_minus = "MC_WHelicityFramePlots_MinusLPVar";
    TCanvas *c1 = new TCanvas(canvas_name_minus,"",450,470);//900,320);
    //c1->Divide(3,1);

    TString pulls_plus = "MC_WHelicityFramePlots_PlusICVarPull";
    TCanvas *cpp = new TCanvas(pulls_plus,"",450,470);//900,320);
    //cpp->Divide(3,1);

    TString pulls_minus = "MC_WHelicityFramePlots_MinusICVarPull";
    TCanvas *cpm = new TCanvas(pulls_minus,"",450,470);//900,320);
    //cpm->Divide(3,1);

    for(unsigned int i=0; i<bins.size(); i++) {
        for(unsigned int j=0; j<charge.size(); j++) {
            //unsigned int index = i*charge.size() + j;
            //cout << "INDEX= " << index << endl;

            //these histograms define the number of events in the complete templates so we can apply correction factors for acceptance etc.
            //do not change these histograms!
            TString refHist1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LH";
            TString refHist2 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_RH";
            TString refHist3 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LO";
            TString refHistData = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j);
            TH1D *refTempHist1 = (TH1D*)refTemplates->Get(refHist1);
            TH1D *refTempHist2 = (TH1D*)refTemplates->Get(refHist2);
            TH1D *refTempHist3 = (TH1D*)refTemplates->Get(refHist3);
            TH1D *refTempHistData = (TH1D*)refTemplates->Get(refHistData);
            refTempHist1->Rebin(rbin);
            refTempHist2->Rebin(rbin);
            refTempHist3->Rebin(rbin);
            refTempHistData->Rebin(rbin);

            double mLHint=0.0, mRHint=0.0, mLOint=0.0, mDATAint=0.0;
            mLHint = refTempHist1->Integral(refTempHist1->GetXaxis()->FindBin(lowlim_fit), refTempHist1->GetXaxis()->FindBin(uplim_fit));
            mRHint = refTempHist2->Integral(refTempHist2->GetXaxis()->FindBin(lowlim_fit), refTempHist2->GetXaxis()->FindBin(uplim_fit));
            mLOint = refTempHist3->Integral(refTempHist3->GetXaxis()->FindBin(lowlim_fit), refTempHist3->GetXaxis()->FindBin(uplim_fit));
            mDATAint = refTempHistData->Integral(refTempHistData->GetXaxis()->FindBin(lowlim_fit), refTempHistData->GetXaxis()->FindBin(uplim_fit));

            bool firstbg = true;

            if(AddQCD) {
                //add the two QCD charge templates together to get average shape
                TH1D * qcdbg = (TH1D*)((TH1D*)QCDbg->Get("RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPFPlus"))->Clone();
                TH1D * qcdbg2 = (TH1D*)((TH1D*)QCDbg->Get("RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPFMinus"))->Clone();
                qcdbg->Rebin(rbin);
                qcdbg2->Rebin(rbin);
                qcdbg->Add(qcdbg2);
                qcdbg->Scale(0.5);
                if(AddQCDbgtemplate) {
                    if(firstbg) {
                        TH1D * bgtemplate = (TH1D*)qcdbg->Clone();
                        firstbg = false;
                    } else bgtemplate->Add(qcdbg);
                }
            }

            if(AddTT) {
                //Since the shape expected is the same for both charges, do the same as in the QCD case
                TH1D * ttbg = (TH1D*)((TH1D*)TTbg->Get("RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPFPlus"))->Clone();
                TH1D * ttbg2 = (TH1D*)((TH1D*)TTbg->Get("RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPFMinus"))->Clone();
                ttbg->Rebin(rbin);
                ttbg2->Rebin(rbin);
                ttbg->Add(ttbg2);
                ttbg->Scale(0.5);
                if(AddTTbgtemplate) {
                    if(firstbg) {
                        TH1D * bgtemplate = (TH1D*)ttbg->Clone();
                        firstbg = false;
                    } else bgtemplate->Add(ttbg);
                }
            }

            if(AddZ) {
                //check to add the Z bg - but do this separately for both charges (templates expected to be slightly different)
                TH1D *zbg =(TH1D*)((TH1D*)Zbg->Get("RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPF" + charge.at(j)))->Clone();
                zbg->Rebin(rbin);
                if(AddZbgtemplate) {
                    if(firstbg) {
                        TH1D * bgtemplate = (TH1D*)zbg->Clone();
                        firstbg = false;
                    } else bgtemplate->Add(zbg);
                }
            }

            //these histograms are the ones we want to fit
            //TString Hist1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LH";
            //TString Hist2 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_RH";
            //TString Hist3 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LO";
            //TString Hist_data1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j);
            TString Hist1 = "RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPF"+ charge.at(j) + "_LH";
            TString Hist2 = "RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPF"+ charge.at(j) + "_RH";
            TString Hist3 = "RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPF"+ charge.at(j) + "_LO";
            TString Hist_data1 = "RECO_PolPlots_" + bins.at(i) + noMTpath + "/RECO_ICVarPF"+ charge.at(j);

            TH1D *mc1 = (TH1D*)templates->Get(Hist1);
            TH1D *mc2 = (TH1D*)templates->Get(Hist2);
            TH1D *mc3 = (TH1D*)templates->Get(Hist3);
            TH1D *datahist = (TH1D*)dataplus->Get(Hist_data1);

            mc1->Rebin(rbin);
            mc2->Rebin(rbin);
            mc3->Rebin(rbin);
            datahist->Rebin(rbin);

            //calculate the acceptance corrections at this stage - before adding anything to the W templates
            double LHint=0.0, RHint=0.0, LOint=0.0, DATAint=0.0;
            LHint = mc1->Integral(mc1->GetXaxis()->FindBin(lowlim_fit), mc1->GetXaxis()->FindBin(uplim_fit));
            RHint = mc2->Integral(mc2->GetXaxis()->FindBin(lowlim_fit), mc2->GetXaxis()->FindBin(uplim_fit));
            LOint = mc3->Integral(mc3->GetXaxis()->FindBin(lowlim_fit), mc3->GetXaxis()->FindBin(uplim_fit));
            DATAint = datahist->Integral(datahist->GetXaxis()->FindBin(lowlim_fit), datahist->GetXaxis()->FindBin(uplim_fit));

            if(!realdata) {
                if(AddQCD) datahist->Add(qcdbg);
                if(AddTT) datahist->Add(ttbg);
                if(AddZ) datahist->Add(zbg);
            }
            Double_t istat=datahist->Integral();

            // Start RooFit session

            RooRealVar x("x","ICVar",lowlim_fit,uplim_fit);
            // Import binned Data
            RooDataHist data1("data1","dataset with WHICVarPlus",x,mc1);
            RooDataHist data2("data2","dataset with WHICVarPlus",x,mc2);
            RooDataHist data3("data3","dataset with WHICVarPlus",x,mc3);
            RooDataHist data4("data4","dataset with WHICVar",x,bgtemplate);
            RooDataHist test("test_data","dataset with WHICVarPlus",x,datahist);

            //Float_t fr = (1./3.)*istat;
            Float_t fr = (1.0/3.0);

            // Relative fractions - allow them to float to negative values too if needs be
            RooRealVar f1("fL","fL fraction",fr,0.0,1.0);
            RooRealVar f2("fR","fR fraction", fr,0.0,1.0);
            RooRealVar f3("f0","f0 fraction",fr,0.0,1.0);
            RooRealVar f4("fs","fs fraction",1.0 - (bgtemplate->Integral()/istat));//to fix the backgrounds i.e. subtract them
            //RooRealVar f4("fs","fs fraction",0.988);//to fix the backgrounds i.e. subtract them
            //RooRealVar f4("fs","fs fraction",fr,0.0,1.0);//to fit for the QCD (+Z) bg

            // Templates
            RooHistPdf h1("h1","h1",x,data1);
            RooHistPdf h2("h2","h2",x,data2);
            RooHistPdf h3("h3","h3",x,data3);

            // composite PDF
            RooHistPdf bkg("bkg","bkg",x,data4);
            RooAddPdf sig("sig","sig",RooArgList(h1,h2,h3),RooArgList(f1,f2)) ;
            RooAddPdf model("model","model",RooArgList(sig,bkg),f4);
            //RooAddPdf model("model","model",RooArgList(h1,h2,h3),RooArgList(f1,f2)) ;

            // Generate data
            Int_t nevt=static_cast<int>(istat);

            //do {
            //RooDataSet *gtest = model.generate(x,nevt);

            // Fitting
            RooFitResult * res1 = model.fitTo(test,Minos(kTRUE), Save());//replace test with *gtest etc
            //res1->Print();
            //} while((f1.getVal() * (1.0/3.0) / accFactor1) < 0.45 || (f1.getVal() * (1.0/3.0) / accFactor1) > 0.55 || (1.0 - f1.getVal() - f2.getVal()) < 0.0);


            if(makePlots) {
                // Plotting
                gROOT->SetStyle("Plain");
                gStyle->SetOptFit(111);
                gStyle->SetOptTitle(0);
                gStyle->SetOptStat(0);
                //gStyle->SetCanvasDefH(600); //Height of canvas
                //gStyle->SetCanvasDefW(600); //Width of canvas
                //TString canvas_name = "MC_CSFramePlots_" + bins.at(i) + charge.at(j) + "Phi";
                //TCanvas *c0 = new TCanvas(canvas_name,"",300,320);
                if(charge.at(j) == "Plus") c0->cd();//(i+1);
                if(charge.at(j) == "Minus") c1->cd();//(i+1);
                RooPlot* frame = x.frame();
                test.plotOn(frame); //either test or *gtest
                model.plotOn(frame);
                //model.paramOn(frame);
                model.plotOn(frame, Components(h1),LineColor(kRed),LineStyle(kDashed));
                model.plotOn(frame, Components(h2),LineColor(kGreen),LineStyle(kDashed));
                model.plotOn(frame, Components(h3),LineColor(kYellow),LineStyle(kDashed));
                model.plotOn(frame, Components(bkg),LineColor(kBlack),LineStyle(kDashed)) ;
                frame->GetXaxis()->SetRangeUser(-2.5,2.5);
                TString xaxislabel = "";
                if(charge.at(j) == "Plus") xaxislabel = "LP(#mu^{+})";
                else xaxislabel = "LP(#mu^{-})";
                frame->GetXaxis()->SetTitle(xaxislabel);
                frame->Draw();
                //c0->cd(i)->Update();
                //c0->Update();
                //c0->Print(canvas_name+".png");
            }

            const TMatrixDSym& cor = res1->correlationMatrix();
            const TMatrixDSym& cov = res1->covarianceMatrix();
            //Print correlation, covariance matrix
            //cout << "correlation matrix" << endl;
            //cor.Print();
            //cout << "covariance matrix" << endl;
            //cout << "(0,0) = " << cov[0][0] << endl;
            //cout << f1.getVal() << endl;
            cov.Print();

            double F1 = f1.getVal();
            double F2 = f2.getVal();
            double F3 = (1.0 - F1 - F2);

            double F1_err = sqrt(cov[0][0]);
            double F2_err = sqrt(cov[1][1]);
            double COV = cov[0][1];

            cout << "Fitting bin " << bins.at(i) << " for " << charge.at(j) << " charge: " << endl;
            cout << "NO ACCEPTANCE CORRECTIONS: " << endl;
            cout << "fL = " << F1 << " +/- " << F1_err << endl;
            cout << "fR = " << F2 << " +/- " << F2_err << endl;
            //cout << "f0 = " << F3 << " +/- " << "N/A" << endl;
            cout << "Covariance Term = " << COV << endl;

            double accLH=0.0, accRH=0.0;
            accLH = (mLHint / mDATAint) / (LHint / DATAint);
            accRH = (mRHint / mDATAint) / (RHint / DATAint);
            F1 *= accLH;
            F2 *= accRH;
            F1_err *= accLH;
            F2_err *= accRH;
            COV *= accLH;
            COV *= accRH;

            cout << "accLH = " << accLH << endl;
            cout << "accRH = " << accRH << endl;

            cout << "WITH ACCEPTANCE CORRECTIONS: " << endl;
            cout << "fL = " << F1 << " +/- " << F1_err << endl;
            cout << "fR = " << F2 << " +/- " << F2_err << endl;
            cout << "(fL - fR) = " << F1 - F2 << " +/- " << sqrt((F1_err*F1_err) + (F2_err*F2_err) - (2.0 * COV)) << endl;
            cout << "f0 = " << (1.0 - F1 - F2) << " +/- " << sqrt((F1_err*F1_err) + (F2_err*F2_err) + (2.0 * COV)) << endl;
            // toy MC study
            if(doToyMC) {
                RooMCStudy mgr(model,model,x,"","mhv");
                mgr.generateAndFit(1000,nevt,kTRUE);
                RooPlot* m1pframe = mgr.plotPull(f1,-3,3,20,kTRUE);
                if(charge.at(j) == "Plus") cpp->cd();//(i+1);
                if(charge.at(j) == "Minus") cpm->cd();//(i+1);
                m1pframe->Draw();
            }

        }
    }
    if(makePlots && printPlots) {
        c0->Print(canvas_name_plus+".png");
        c1->Print(canvas_name_minus+".png");
        if(doToyMC) {
            cpp->Print(pulls_plus+".png");
            cpm->Print(pulls_minus+".png");
        }
    }

    return;

}
Example #24
0
void Draw3paneleff() {
    gStyle->SetOptStat(kFALSE);
    TString outG="G1.root";
    TCanvas *c1  = new TCanvas("","",1000,400);
    c1->Divide(3);
    gStyle->SetErrorX(0);
    double hfbin[]= {0,1,2,3,4,6,8,10,13,16,20,25,30,40,55,70,90};
    int nhfbin = 16;
    TString name, dirname;
    TFile *fDSeff = TFile::Open("/scratch/xuq7/Centrality/pPbHijing_EffCorr_forNBD.root");
    TFile *ftreff = TFile::Open("/scratch/xuq7/Centrality/pPbHist_Hijing_TrandEs.root");
    TH1D* hbef = (TH1D*)ftreff->Get("hHFEnergy4");
    TH1D* rehbef = (TH1D*)hbef->Rebin(nhfbin,"rehHFEnergy4",hfbin);
    TH1D* haft = (TH1D*)ftreff->Get("hHFEnergy4_tr");
    TH1D* rehaft = (TH1D*)haft->Rebin(nhfbin,"rehHFEnergy4_tr",hfbin);
    TGraphAsymmErrors *gtreff = new TGraphAsymmErrors();
    gtreff->BayesDivide(rehaft,rehbef);

    TGraphAsymmErrors *geff = (TGraphAsymmErrors*)fDSeff->Get("regEffHF4");
    for(int i=0; i<geff->GetN(); i++) {
        geff->SetPointEXlow(i,0);
        geff->SetPointEXhigh(i,0);
        gtreff->SetPointEXlow(i,0);
        gtreff->SetPointEXhigh(i,0);
    }

    geff->SetTitle("");
    geff->SetMarkerStyle(33);
    geff->SetMarkerColor(5);
    geff->SetMarkerSize(1.3);

    gtreff->SetTitle("");
    gtreff->SetMarkerStyle(21);
    gtreff->SetMarkerColor(6);
    gtreff->SetMarkerSize(1.3);

    for(int cenvar=0; cenvar<3; cenvar++) {
        TFile *f = TFile::Open(Form("%s/%s",cenvardir[cenvar].Data(),outG.Data()));
        c1->cd(cenvar+1);
        TObjString* dataname = (TObjString*)f->Get(Form("dataname"));
        TObjString* histoname = (TObjString*)f->Get(Form("histoname"));
        TFile *fdata = TFile::Open(dataname->GetString());
        TH1D *histo_obs = (TH1D*)fdata->Get(histoname->GetString());
        histo_obs->Sumw2();
        TH1D* hFrame = histo_obs->Clone();
        hFrame->Reset();
        hFrame->SetTitle("");
        hFrame->SetMaximum(1.2);
        hFrame->SetMinimum(0);
        if(cenvar==0)hFrame->GetYaxis()->SetTitle("ratio");
        else hFrame->GetYaxis()->SetTitle("");
        hFrame->GetXaxis()->SetRangeUser(0,100);
        hFrame->GetXaxis()->CenterTitle(0);
        hFrame->GetYaxis()->CenterTitle(1);
        hFrame->GetYaxis()->SetTitleOffset(1.1);
        hFrame->GetXaxis()->SetTitleOffset(1.1);
        hFrame->GetXaxis()->SetTitleSize(0.056);
        hFrame->GetYaxis()->SetTitleSize(0.056);
        hFrame->GetXaxis()->SetLabelSize(0.05);
        hFrame->GetYaxis()->SetLabelSize(0.05);

        int binnum = histo_obs->GetNbinsX();
        double Minx = histo_obs->GetXaxis()->GetXmin();
        double Maxx = histo_obs->GetXaxis()->GetXmax();
        double binsize = (Double_t)(Maxx-Minx)/binnum;
        hFrame->Draw();
        TLegend *leg = new TLegend(0.40, 0.2, 0.65, 0.4);

        for(int sth=0; sth<3; sth++) {
            int Gth=0;
            if(sth==0) {
                dirname = "std";
            }
            else if(sth==1) {
                dirname ="Gri055";
            }
            else {
                dirname ="Gri101";
            }
            hFrame->GetXaxis()->SetTitle(cenvariable[cenvar]);

            if(Gth==0)
                name = "G0";
            else if(Gth<nGlau)
                name = Form("Glau_%d",Gth);
            else
                name = Form("bin_%d",Gth-nGlau+1);
            TObjString* Glaubername = (TObjString*)f->Get(Form("%s/%s/Glaubername",dirname.Data(),name.Data()));
            TVectorD* xmin = (TVectorD*)f->Get(Form("%s/%s/xmin",dirname.Data(),name.Data()));
            TVectorD* xmax = (TVectorD*)f->Get(Form("%s/%s/xmax",dirname.Data(),name.Data()));
            TVectorD* mubest = (TVectorD*)f->Get(Form("%s/%s/mubest",dirname.Data(),name.Data()));
            TVectorD* kbest = (TVectorD*)f->Get(Form("%s/%s/kbest",dirname.Data(),name.Data()));
            TVectorD* Ndf = (TVectorD*)f->Get(Form("%s/%s/Ndf",dirname.Data(),name.Data()));
            TVectorD* chis = (TVectorD*)f->Get(Form("%s/%s/chis",dirname.Data(),name.Data()));
            TVectorD *kpoint = (TVectorD*)f->Get(Form("%s/%s/kpoint",dirname.Data(),name.Data()));
            int xbinmin=(int)(((*xmin)[0]-Minx)/binsize);
            int xbinmax=(int)(((*xmax)[0]-Minx)/binsize);
            TFile *fGlauber = TFile::Open(Glaubername->GetString());
            TH1D *histo_exp = new TH1D("histo_exp","Simulated distribution;Multiplicity;Event Fraction",binnum,Minx,Maxx);
            histo_exp->Sumw2();
            Int_t ibin;

            TH1D *histo_obs_norm = (TH1D*)histo_obs->Clone();
            histo_obs_norm->Scale(1/histo_obs->Integral(xbinmin,xbinmax));

            TF1 *NBD_fun = new
            TF1("NBD_fun","[0]*TMath::Gamma(x+[1])/(TMath::Gamma(x+1)*TMath::Gamma([1]))*TMath::Power([2]/[1],x)/TMath::Power([2]/[1]+1,x+[1])",0,100);
            NBD_fun->SetParameter(0,1);	//[0]: Normalized constant
            NBD_fun->SetParameter(1,(*kbest)[0]);	//[1]: k value
            NBD_fun->SetParameter(2,(*mubest)[0]);	//[2]: mu value

            TTree *t = (TTree*) fGlauber->Get("nt_p_Pb");
            Long_t Nevent;

            Nevent = (Long_t) t->GetEntries();

            Long_t Ev;
            Int_t Bino;
            Double_t Para, Bi_Para, Mult;
            Float_t Ncoll;
            t->SetBranchAddress("Ncoll",&Ncoll);

            for(Ev=0; Ev<Nevent; Ev++) {
                if(Ev%100000==0)	 cout<<"Have run "<<Ev<<" events"<<endl;
                t->GetEntry(Ev);
                Para = 0; //make sure that Para doesn't accumulate through loops
                for(Bino=0; Bino<Ncoll; Bino++) {
                    Bi_Para = NBD_fun->GetRandom();
                    Para += Bi_Para;
                }
                histo_exp->Fill(Para);
            }
            Double_t SumEvent, scale;
            SumEvent = histo_exp->Integral(xbinmin,xbinmax);
            scale = 1/SumEvent;
            TH1D *histo_exp_norm = (TH1D*) histo_exp->Clone();
            histo_exp_norm->Scale(scale);


            rehisto_obs_norm = (TH1D*)histo_obs_norm->Rebin(nhfbin,"rehisto_obs_norm",hfbin);
            normalizeByBinWidth(rehisto_obs_norm);
            rehisto_exp_norm = (TH1D*)histo_exp_norm->Rebin(nhfbin,"rehisto_exp_norm",hfbin);
            normalizeByBinWidth(rehisto_exp_norm);
            TH1D* ratio = (TH1D*)rehisto_obs_norm->Clone("ratio");
            ratio->Divide(rehisto_exp_norm);

            ratio->SetTitle("");
            ratio->SetLineColor(1);
            ratio->SetMarkerStyle(20);
            ratio->SetMarkerColor(color_[sth]);
            ratio->SetMarkerSize(1.3);
            ratio->Draw("Psame");
            geff->Draw("Psame");
            gtreff->Draw("Psame");
            leg->AddEntry(ratio,Form("data/fit %s",Grilist[sth].Data()),"p");
        }

        leg->SetFillColor(10);
        leg->SetFillStyle(0);
        leg->SetBorderSize(0.035);
        leg->SetTextFont(42);
        leg->SetTextSize(0.045);
        leg->AddEntry(geff,"DS efficiency","p");
        leg->AddEntry(gtreff,"Event selection efficiency","p");
        if(cenvar==2) leg->Draw("same");

        TLine *l = new TLine(0,1,90,1);
        l->SetLineStyle(2);
        l->Draw("same");
    }
    c1->SaveAs(Form("ratiovseff.png"));
    c1->SaveAs(Form("ratiovseff.pdf"));
}
Example #25
0
void getAiZ() 
{
  TFile *data1 = new TFile("results/CSFrame_ZJets_madgraph_0_inf_plus.root");
  TFile *data2 = new TFile("results/CSFrame_ZJets_madgraph_0_inf_minus.root");

  TString HistPA0 = "MC_CSFramePlots_0toinf/MC_CSWPlusA0Numerator";
  TString HistPA1 = "MC_CSFramePlots_0toinf/MC_CSWPlusA1Numerator";
  TString HistPA2 = "MC_CSFramePlots_0toinf/MC_CSWPlusA2Numerator";
  TString HistPA3 = "MC_CSFramePlots_0toinf/MC_CSWPlusA3Numerator";
  TString HistPA4 = "MC_CSFramePlots_0toinf/MC_CSWPlusA4Numerator";
  TString HistPD = "MC_CSFramePlots_0toinf/MC_CSWPlusAiDenominator";

  TString HistMA0 = "MC_CSFramePlots_0toinf/MC_CSWMinusA0Numerator";
  TString HistMA1 = "MC_CSFramePlots_0toinf/MC_CSWMinusA1Numerator";
  TString HistMA2 = "MC_CSFramePlots_0toinf/MC_CSWMinusA2Numerator";
  TString HistMA3 = "MC_CSFramePlots_0toinf/MC_CSWMinusA3Numerator";
  TString HistMA4 = "MC_CSFramePlots_0toinf/MC_CSWMinusA4Numerator";
  TString HistMD = "MC_CSFramePlots_0toinf/MC_CSWMinusAiDenominator";

  TH1D *hPA0 = (TH1D*)data1->Get(HistPA0);
  TH1D *hPA1 = (TH1D*)data1->Get(HistPA1);
  TH1D *hPA2 = (TH1D*)data1->Get(HistPA2);
  TH1D *hPA3 = (TH1D*)data1->Get(HistPA3);
  TH1D *hPA4 = (TH1D*)data1->Get(HistPA4);
  TH1D *hPD = (TH1D*)data1->Get(HistPD);

  TH1D *hMA0 = (TH1D*)data2->Get(HistMA0);
  TH1D *hMA1 = (TH1D*)data2->Get(HistMA1);
  TH1D *hMA2 = (TH1D*)data2->Get(HistMA2);
  TH1D *hMA3 = (TH1D*)data2->Get(HistMA3);
  TH1D *hMA4 = (TH1D*)data2->Get(HistMA4);
  TH1D *hMD = (TH1D*)data2->Get(HistMD);

  hPA0->Rebin(20);
  hPA1->Rebin(20);
  hPA2->Rebin(20);
  hPA3->Rebin(20);
  hPA4->Rebin(20);
  hPD->Rebin(20);

  hMA0->Rebin(20);
  hMA1->Rebin(20);
  hMA2->Rebin(20);
  hMA3->Rebin(20);
  hMA4->Rebin(20);
  hMD->Rebin(20);

  TCanvas * aCanvas = new TCanvas("CSAiZ", "CSAiZ", 1100, 500);
  aCanvas->SetFillColor(0);
  aCanvas->SetFrameFillColor(0);
  aCanvas->SetFrameBorderMode(0);
  aCanvas->Divide(2,1);

  setPadMargins(aCanvas->cd(1));

  TLegend * aLegend = new TLegend(0.23,0.92,0.4,0.62);
  aLegend->SetFillColor(0);
  aLegend->SetLineColor(0);
  aLegend->SetTextSize(0.0625);

  aLegend->AddEntry(hPA0,"A0", "L");
  //aLegend->AddEntry(hPA1,"A1", "L");
  aLegend->AddEntry(hPA2,"A2", "L");
  aLegend->AddEntry(hPA3,"A3", "L");
  //aLegend->AddEntry(hPA4,"A4", "L");

  hPA0->Scale(20.0/3.0);
  hPA0->Divide(hPD);
  for(unsigned int i=0; i<hPA0->GetNbinsX(); i++) {
    hPA0->SetBinContent(i, (2.0/3.0) + hPA0->GetBinContent(i));
  }
  hPA0->SetLineWidth(3);
  hPA0->GetYaxis()->SetRangeUser(-1.,2.);
  hPA0->GetXaxis()->SetTitle("P_{T}(Z) [GeV]");
  hPA0->GetXaxis()->SetRangeUser(0,220);
  hPA0->GetYaxis()->SetTitle("A_{i}");
  hPA0->GetXaxis()->SetTitleSize(0.0625);
  hPA0->GetYaxis()->SetTitleSize(0.0625);
  hPA0->GetXaxis()->SetTitleOffset(1.00);
  hPA0->GetYaxis()->SetTitleOffset(1.20);
  hPA0->GetXaxis()->SetLabelSize(0.052);
  hPA0->GetYaxis()->SetLabelSize(0.052);
  hPA0->GetXaxis()->SetLabelOffset(0.01);
  hPA0->GetYaxis()->SetLabelOffset(0.01);
  hPA0->DrawCopy("hist");

  hPA1->Scale(5.0);
  hPA1->Divide(hPD);
  hPA1->SetLineColor(kRed);
  hPA1->SetLineWidth(3);
  //hPA1->DrawCopy("histsame");//we don't have sensitivity to A1 - sign of cos(theta_CS)

  hPA2->Scale(10.0);
  hPA2->Divide(hPD);
  hPA2->SetLineColor(kBlue);
  hPA2->SetLineWidth(3);
  hPA2->DrawCopy("histsame");

  hPA3->Scale(4.0);
  hPA3->Divide(hPD);
  hPA3->SetLineColor(kGreen);
  hPA3->SetLineWidth(3);
  hPA3->DrawCopy("histsame");

  hPA4->Scale(4.0);
  hPA4->Divide(hPD);
  hPA4->SetLineColor(kCyan);
  hPA4->SetLineWidth(3);
  //hPA4->DrawCopy("histsame");//we don't have sensitivity to A4 - sign of cos(theta_CS)

  TLatex *tplus = labelLatex(0.25,0.25,"Lepton Plus Charge");
  tplus->DrawClone("same");

  aLegend->DrawClone("same");  

  setPadMargins(aCanvas->cd(2));

  hMA0->Scale(20.0/3.0);
  hMA0->Divide(hMD);
  for(unsigned int i=0; i<hMA0->GetNbinsX(); i++) {
    hMA0->SetBinContent(i, (2.0/3.0) + hMA0->GetBinContent(i));
  }
  hMA0->SetLineWidth(3);
  hMA0->GetYaxis()->SetRangeUser(-1.,2.);
  hMA0->GetXaxis()->SetTitle("P_{T}(Z) [GeV]");
  hMA0->GetXaxis()->SetRangeUser(0,220);
  hMA0->GetYaxis()->SetTitle("A_{i}");
  hMA0->GetXaxis()->SetTitleSize(0.0625);
  hMA0->GetYaxis()->SetTitleSize(0.0625);
  hMA0->GetXaxis()->SetTitleOffset(1.00);
  hMA0->GetYaxis()->SetTitleOffset(1.20);
  hMA0->GetXaxis()->SetLabelSize(0.052);
  hMA0->GetYaxis()->SetLabelSize(0.052);
  hMA0->GetXaxis()->SetLabelOffset(0.01);
  hMA0->GetYaxis()->SetLabelOffset(0.01);
  hMA0->DrawCopy("hist");

  hMA1->Scale(5.0);
  hMA1->Divide(hMD);
  hMA1->SetLineColor(kRed);
  hMA1->SetLineWidth(3);
  //hMA1->DrawCopy("histsame");

  hMA2->Scale(10.0);
  hMA2->Divide(hMD);
  hMA2->SetLineColor(kBlue);
  hMA2->SetLineWidth(3);
  hMA2->DrawCopy("histsame");

  hMA3->Scale(4.0);
  hMA3->Divide(hMD);
  hMA3->SetLineColor(kGreen);
  hMA3->SetLineWidth(3);
  hMA3->DrawCopy("histsame");

  hMA4->Scale(4.0);
  hMA4->Divide(hMD);
  hMA4->SetLineColor(kCyan);
  hMA4->SetLineWidth(3);
  //hMA4->DrawCopy("histsame");

  TLatex *tminus = labelLatex(0.25,0.25,"Lepton Minus Charge");
  tminus->DrawClone("same");

  aLegend->DrawClone("same");  

  aCanvas->Print(".png");

  return;
}
Example #26
0
void comparisonJetMCData(string plot,int rebin){
  string tmp;

  string dir="/gpfs/cms/data/2011/Observables/Approval/";
	
  if (isAngularAnalysis){
    mcfile=dir+"MC_zjets"+version;
    back_w=dir+"MC_wjets"+version;
    back_ttbar=dir+"MC_ttbar"+version;
    WW=dir+"MC_diW"+version;
    ZZ=dir+"MC_siZ"+version;
    WZ=dir+"MC_diWZ"+version;
    datafile=dir+"DATA"+version;
    mcfiletau=dir+"MC_zjetstau"+version;
  }
  // List of files

  TFile *dataf = TFile::Open(datafile.c_str()); //data file
  TFile *mcf = TFile::Open(mcfile.c_str()); //MC file
  TFile *mcftau = TFile::Open(mcfiletau.c_str()); //MC file
  TFile *ttbarf = TFile::Open(back_ttbar.c_str()); //MC background file
  TFile *wf = TFile::Open(back_w.c_str());


  TFile *qcd23emf = TFile::Open(qcd23em.c_str());
  TFile *qcd38emf = TFile::Open(qcd38em.c_str());
  TFile *qcd817emf = TFile::Open(qcd817em.c_str());

  TFile *qcd23bcf = TFile::Open(qcd23bc.c_str());
  TFile *qcd38bcf = TFile::Open(qcd38bc.c_str());
  TFile *qcd817bcf = TFile::Open(qcd817bc.c_str());

  TFile *WZf = TFile::Open(WZ.c_str());
  TFile *ZZf = TFile::Open(ZZ.c_str());
  TFile *WWf = TFile::Open(WW.c_str());


  // Canvas
  if (CanvPlot) delete CanvPlot;
  CanvPlot = new TCanvas("CanvPlot","CanvPlot",0,0,800,600);

  // Getting, defining ...
  dataf->cd("validationJEC");
  if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");
	
  TObject * obj;
  gDirectory->GetObject(plot.c_str(),obj);

  TH1 *data;
  TH2F *data2; 
  TH1D *data3; 

  THStack *hs = new THStack("hs","Total MC");


  int flag=-1;
  if ((data = dynamic_cast<TH1F *>(obj)) ){
    flag=1;
    gROOT->Reset();
    gROOT->ForceStyle();
    gStyle->SetPadRightMargin(0.03);
    gPad->SetLogy(1);
    gPad->Modified();
    gPad->Update();
  }
  if ((data2 = dynamic_cast<TH2F *>(obj)) ){
    flag=2;
    gStyle->SetPalette(1);
    gStyle->SetPadRightMargin(0.15);
    gPad->Modified();
  }



  //===================
  // Dirty jobs :)
  if (flag==1){
    CanvPlot->cd();
    TPad *pad1 = new TPad("pad1","pad1",0.01,0.33,0.99,0.99);
    pad1->Draw();
    pad1->cd();
    pad1->SetTopMargin(0.1);
    pad1->SetBottomMargin(0.01);
    pad1->SetRightMargin(0.1);
    pad1->SetFillStyle(0);
    pad1->SetLogy(1);
    TString str=data->GetTitle();
    if (str.Contains("jet") && !str.Contains("zMass") && !str.Contains("Num") && !str.Contains("Eta") && !str.Contains("Phi") && !str.Contains("eld") && !str.Contains("meanPtZVsNjet")) {
      if (!isAngularAnalysis) rebin=1;
    }

    //======================
    // DATA
    Double_t dataint = data->Integral();
    data->SetLineColor(kBlack);
    data->Rebin(rebin);
    if(str.Contains("nJetVtx")) data->GetXaxis()->SetRangeUser(0,10);	
    if(str.Contains("zMass")) data->GetXaxis()->SetRangeUser(70,110);	
    data->SetMinimum(1.);
    data->Sumw2();

    //Canvas style copied from plotsHistsRatio.C
    data->SetLabelSize(0.0);
    data->GetXaxis()->SetTitleSize(0.00);
    data->GetYaxis()->SetLabelSize(0.07);
    data->GetYaxis()->SetTitleSize(0.08);
    data->GetYaxis()->SetTitleOffset(0.76);
    data->SetTitle("");
    gStyle->SetOptStat(0);

    data->GetYaxis()->SetLabelSize(0.06);
    data->GetYaxis()->SetTitleSize(0.06);
    data->GetYaxis()->SetTitleOffset(0.8);

    data->Draw("E1");


    TLegend* legend = new TLegend(0.725,0.27,0.85,0.72);
    legend->SetFillColor(0);
    legend->SetFillStyle(0);
    legend->SetBorderSize(0);
    legend->SetTextSize(0.060);
    legend->AddEntry(data,"data","p");

    // hack to calculate some yields in restricted regions...
    int num1=0, num2=0, num3=0, num4=0, num5=0;
    if(str.Contains("invMass") && !str.Contains("PF")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z ci sono tra 60 e 120 GeV
	if(j>10&&j<=50) num2 += data->GetBinContent(j); // ... tra 70 e 110
	if(j>15&&j<=45) num3 += data->GetBinContent(j); // ... tra 75 e 105
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the invmass histo\n";
      printf("Number of Z in 60-120 %i --- 70-110 %i --- 75-105 %i \n",num1,num2,num3);
      cout << "\n";
    }
    if(str.Contains("zYieldVsjets") && !str.Contains("Vtx")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z
	if(j>1) num2 += data->GetBinContent(j); // ... +1,2,3,4... jets
	if(j>2) num3 += data->GetBinContent(j); // ... +2,3,4... jets
	if(j>3) num4 += data->GetBinContent(j); // ..    if(str=="jet_pT"){
	if(j>4) num5 += data->GetBinContent(j); // ... +4... jets
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the zYieldVsjets histo\n";
      printf("Number of Z+n jet %i --- >1 %i --- >2 %i --- >3 %i --- >4 %i \n",num1,num2,num3,num4,num5);
      cout << "\n";
    }    

    //======================
    // Z + jets signal
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    TH1F* mc;
    gDirectory->GetObject(plot.c_str(),mc);
    TH1F * hsum;
    if(mc){
      hsum =  (TH1F*) mc->Clone();
      hsum->SetTitle("hsum");
      hsum->SetName("hsum");
      hsum->Reset();

      Double_t mcint = mc->Integral();
      mc->SetFillColor(kRed);
      mc->Sumw2();
      if(lumiweights==0) mc->Scale(dataint/mcint);
		
      // Blocco da propagare negli altri MC
      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) mc->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else mc->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) mc->Scale(zjetsScale);
      }

      // fin qui
      if(lumiweights==1) mc->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      mc->Rebin(rebin);
      if(lumiweights==0) mc->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(mc);
      legend->AddEntry(mc,"Z+jets","f");
    }

    //======================
    // ttbar
    ttbarf->cd("validationJEC");
    if (isMu) ttbarf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ttbarf->cd("validationJEC/");
      if (isMu) ttbarf->cd("validationJECmu/");
    }

    TH1F* ttbar;
    gDirectory->GetObject(plot.c_str(),ttbar);
	
    if(ttbar){
      ttbar->SetFillColor(kBlue);
      ttbar->Sumw2();

      if(ttNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ttbar->Scale( dataLumi2011pix / (ttNumEvents / ttbarXsect));
	    else ttbar->Scale( dataLumi2011 / (ttNumEvents / ttbarXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Apix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011A / (ttNumEvents / ttbarXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Bpix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011B / (ttNumEvents / ttbarXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ttbar->Scale(ttwemean);
      }
      // fin qui
		
      if(lumiweights==1) ttbar->Scale(1./ttwemean);  // perche' i Weights non fanno 1...
      ttbar->Rebin(rebin);
      if(lumiweights==0) ttbar->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ttbar);
      if(lumiweights==1)legend->AddEntry(ttbar,"ttbar","f");

      //////////
      //Storing the bckgrounds!
      //////////
      cout<<str<<endl;
      if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ttbar,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ttbar,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ttbar,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ttbar,"jet_pT4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ttbar,"jet_Multiplicity");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ttbar,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ttbar,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ttbar,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ttbar,"jet_eta4");
      if(str=="HT") evaluateAndFillBackgrounds(ttbar,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ttbar,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ttbar,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ttbar,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ttbar,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ttbar,"PhiStar");
      }
    }

    //======================
    // w+jets
    wf->cd("validationJEC");
    if (isMu) wf->cd("validationJECmu/");
    if (isAngularAnalysis) {
      wf->cd("validationJEC/");
      if (isMu) wf->cd("validationJECmu/");      
    }

    TH1F* w;
    gDirectory->GetObject(plot.c_str(),w);
    if(w){

      w->SetFillColor(kViolet+2);
      w->Sumw2();

      if(wNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) w->Scale( dataLumi2011pix / (wNumEvents / wjetsXsect));
	    else w->Scale( dataLumi2011 / (wNumEvents / wjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Apix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011A / (wNumEvents / wjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Bpix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011B / (wNumEvents / wjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) w->Scale(wwemean);
      }
      // fin qui
		
      if(lumiweights==1) w->Scale(1./wwemean);  // perche' i Weights non fanno 1...
      w->Rebin(rebin);
      if(lumiweights==0) w->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(w);
      if(lumiweights==1)legend->AddEntry(w,"W+jets","f");
    }

    //======================
    // wz+jets
    WZf->cd("validationJEC");
    if (isMu) WZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WZf->cd("validationJEC/");
      if (isMu) WZf->cd("validationJECmu/");
    }

    TH1F* wz;
    gDirectory->GetObject(plot.c_str(),wz);
    if(wz){
      wz->SetFillColor(kYellow+2);
      wz->Sumw2();

      if(wzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) wz->Scale( dataLumi2011pix / (wzEvents / WZXsect));
	    else wz->Scale( dataLumi2011 / (wzEvents / WZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Apix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011A / (wzEvents / WZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Bpix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011B / (wzEvents / WZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) wz->Scale(wzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) wz->Scale(1./wzwemean);  // perche' i Weights non fanno 1...
      wz->Rebin(rebin);
      if(lumiweights==0) wz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(wz);
      legend->AddEntry(wz,"WZ+jets","f");


      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(wz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(wz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(wz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(wz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(wz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(wz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(wz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(wz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(wz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(wz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(wz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(wz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(wz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(wz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(wz,"PhiStar");
     }
    }
    
		
    //======================
    // zz+jets
    ZZf->cd("validationJEC");
    if (isMu) ZZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ZZf->cd("validationJEC/");
      if (isMu) ZZf->cd("validationJECmu/");
    }

    TH1F* zz;
    gDirectory->GetObject(plot.c_str(),zz);
    if(zz){
      zz->SetFillColor(kOrange+2);
      zz->Sumw2();

      if(zzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) zz->Scale( dataLumi2011pix / (zzEvents / ZZXsect));
	    else zz->Scale( dataLumi2011 / (zzEvents / ZZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Apix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011A / (zzEvents / ZZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Bpix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011B / (zzEvents / ZZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) zz->Scale(zzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) zz->Scale(1./zzwemean);  // perche' i Weights non fanno 1...
      zz->Rebin(rebin);
      if(lumiweights==0) zz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(zz);
      legend->AddEntry(zz,"ZZ+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(zz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(zz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(zz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(zz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(zz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(zz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(zz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(zz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(zz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(zz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(zz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(zz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(zz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(zz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(zz,"PhiStar");
     }  
    }
    
    //======================
    // ww+jets
    WWf->cd("validationJEC");
    if (isMu) WWf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WWf->cd("validationJEC/");
      if (isMu) WWf->cd("validationJECmu/");
    }

    TH1F* ww;
    gDirectory->GetObject(plot.c_str(),ww);
    if(ww){
      ww->SetFillColor(kBlack);
      ww->Sumw2();

      if(wwEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ww->Scale( dataLumi2011pix / (wwEvents / WWXsect));
	    else ww->Scale( dataLumi2011 / (wwEvents / WWXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Apix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011A / (wwEvents / WWXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Bpix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011B / (wwEvents / WWXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ww->Scale(wwjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) ww->Scale(1./wwwemean);  // perche' i Weights non fanno 1...
      ww->Rebin(rebin);
      if(lumiweights==0) ww->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ww);
      legend->AddEntry(ww,"WW+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ww,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ww,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ww,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ww,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ww,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ww,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ww,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ww,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ww,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(ww,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ww,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ww,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ww,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ww,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ww,"PhiStar");
     }
    }

    /// Tau 

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

    mcftau->cd("validationJEC");
    if (isMu) mcftau->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcftau->cd("validationJEC/");
      if (isMu) mcftau->cd("validationJECmu/");
    }

    TH1F* tau;
    gDirectory->GetObject(plot.c_str(),tau);
    if(tau){
      tau->SetFillColor(kGreen);
      tau->Sumw2();

      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) tau->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else tau->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) tau->Scale(zjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) tau->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      tau->Rebin(rebin);
      if(lumiweights==0) tau->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      tau->Scale(1./1000.); //aaaaaaa
      hsum->Add(tau);
      legend->AddEntry(tau,"#tau#tau+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(tau,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(tau,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(tau,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(tau,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(tau,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(tau,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(tau,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(tau,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(tau,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(tau,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(tau,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(tau,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(tau,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(tau,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(tau,"PhiStar");
     }
    }


    /////////
    // Print the bkg contributions
    ////////

    for(int j=0;j<bckg_leadingJetPt.size();j++){      
      cout<<bckg_leadingJetPt[j]<<endl;
    }	

    //======================
    // QCD EM enriched
    qcd23emf->cd("validationJEC");
    TH1F* qcd23emp;
    gDirectory->GetObject(plot.c_str(),qcd23emp);

    if(qcd23emp){
      TH1D * qcdTotEM =  (TH1D*) qcd23emp->Clone(); 
      qcdTotEM->SetTitle("qcd em");
      qcdTotEM->SetName("qcd em");
      qcdTotEM->Reset();
      qcdTotEM->Rebin(rebin);

      qcd38emf->cd("validationJEC");
      TH1F* qcd38emp;
      gDirectory->GetObject(plot.c_str(),qcd38emp);


      qcd817emf->cd("validationJEC");
      TH1F* qcd817emp;
      gDirectory->GetObject(plot.c_str(),qcd817emp);

      qcd23emp->Rebin(rebin);
      qcd23emp->Sumw2();
      qcd23emp->Scale(qcd23emScale); 
      qcd38emp->Rebin(rebin);
      qcd38emp->Sumw2();
      qcd38emp->Scale(qcd38emScale); 
      qcd817emp->Rebin(rebin);
      qcd817emp->Sumw2();
      qcd817emp->Scale(qcd817emScale); 

      qcdTotEM->SetFillColor(kOrange+1);
      qcdTotEM->Add(qcd23emp);
      qcdTotEM->Add(qcd38emp);
      qcdTotEM->Add(qcd817emp);

      hsum->Add(qcdTotEM);

      //if(lumiweights==1)legend->AddEntry(qcdTotEM,"QCD em","f");
    }

    //======================
    // QCD bc
    qcd23bcf->cd("validationJEC");
    TH1F* qcd23bcp;
    TH1D * qcdTotBC;
    bool  qcdbcempty=true;
    gDirectory->GetObject(plot.c_str(),qcd23bcp);

    if(qcd23bcp){
      qcdTotBC =  (TH1D*) qcd23bcp->Clone(); 
      qcdTotBC->SetTitle("qcd bc");
      qcdTotBC->SetName("qcd bc");
      qcdTotBC->Reset();
      qcdTotBC->Rebin(rebin);

      qcd38bcf->cd("validationJEC");
      TH1F* qcd38bcp;
      gDirectory->GetObject(plot.c_str(),qcd38bcp);

      qcd817bcf->cd("validationJEC");
      TH1F* qcd817bcp;
      gDirectory->GetObject(plot.c_str(),qcd817bcp);

      qcd23bcp->Rebin(rebin);
      qcd23bcp->Sumw2();
      qcd23bcp->Scale(qcd23bcScale); 
      qcd38bcp->Rebin(rebin);
      qcd38bcp->Sumw2();
      qcd38bcp->Scale(qcd38bcScale); 
      qcd817bcp->Rebin(rebin);
      qcd817bcp->Sumw2();
      qcd817bcp->Scale(qcd817bcScale); 

      qcdTotBC->SetFillColor(kGreen+2);
      qcdTotBC->Add(qcd23bcp);
      qcdTotBC->Add(qcd38bcp);
      qcdTotBC->Add(qcd817bcp);

      hsum->Add(qcdTotBC);
      if (qcdTotBC->GetEntries()>0) qcdbcempty=false; 

      //if(lumiweights==1)legend->AddEntry(qcdTotBC,"QCD bc","f");
    }

    //======================
    // Add here other backgrounds


    //======================
    // Stacked Histogram
    //if(qcd23em) 	hs->Add(qcdTotEM);
    if(!qcdbcempty) 	hs->Add(qcdTotBC);
    if(w)  	        hs->Add(w);
    if (ww)         hs->Add(ww);
    if(tau)		hs->Add(tau); //Z+Jets
    if (zz)         hs->Add(zz);
    if (wz)         hs->Add(wz);
    if (ttbar)	hs->Add(ttbar);
    if(mc)		hs->Add(mc); //Z+Jets

    // per avere le statistiche
    if(lumiweights==1) hsum->Draw("HISTO SAME");


    //======================
    // Setting the stats
    //pad1->Update(); // altrimenti non becchi la stat
    
    //TPaveStats *r2;
    //if(lumiweights==0) r2 = (TPaveStats*)mc->FindObject("stats");
    //if(lumiweights==1) r2 = (TPaveStats*)hsum->FindObject("stats");
    //r2->SetY1NDC(0.875);     //Uncomment if you wonna add your statistics in the top right corner
    //r2->SetY2NDC(0.75); 
    //r2->SetTextColor(kRed);
		
    if(lumiweights==1) hs->Draw("HISTO SAME");
    gPad->RedrawAxis();
    data->Draw("E1 SAME");
    //r2->Draw(); //here to reactivate the stats
    legend->Draw();
    TLegend* lumi = new TLegend(0.45,0.3,0.75,0.2);
    lumi->SetFillColor(0);
    lumi->SetFillStyle(0);
    lumi->SetBorderSize(0);
    //lumi->AddEntry((TObject*)0,"#int L dt =4.9 1/fb","");
    lumi->Draw();
    string channel;
    if (isMu) channel="Z#rightarrow#mu#mu";
    if (!isMu) channel="Z#rightarrow ee";
    TLatex *latexLabel=CMSPrel(4.890,channel,0.55,0.85); // make fancy label
    latexLabel->Draw("same");

    CanvPlot->Update();

	


    //===============//
    // RATIO DATA MC //
    //===============//
    CanvPlot->cd();
    TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.32);
    pad2->Draw();
    pad2->cd();
    pad2->SetTopMargin(0.01);
    pad2->SetBottomMargin(0.3);
    pad2->SetRightMargin(0.1);
    pad2->SetFillStyle(0);

    TH1D * ratio =  (TH1D*) data->Clone();
    ratio->SetTitle("");
    ratio->SetName("ratio");
    ratio->Reset();

    ratio->Sumw2();
    //data->Sumw2();
    hsum->Sumw2(); // FIXME controlla che sia corretto questo... 
    ratio->SetMarkerSize(.5);
    ratio->SetLineColor(kBlack);
    ratio->SetMarkerColor(kBlack);
    //gStyle->SetOptStat("m");
    TH1F* sumMC;

    hs->Draw("nostack"); 
 
   sumMC=(TH1F*) hs->GetHistogram();
    cout<<sumMC->GetEntries()<<endl;
    ratio->Divide(data,hsum,1.,1.);
    ratio->GetYaxis()->SetRangeUser(0.5,1.5);
    ratio->SetMarkerSize(0.8);
    //pad2->SetTopMargin(1);

   //Canvas style copied from plotsHistsRatio.C
    ratio->GetYaxis()->SetNdivisions(5);
    ratio->GetXaxis()->SetTitleSize(0.14);
    ratio->GetXaxis()->SetLabelSize(0.14);
    ratio->GetYaxis()->SetLabelSize(0.11);
    ratio->GetYaxis()->SetTitleSize(0.11);
    ratio->GetYaxis()->SetTitleOffset(0.43);
    ratio->GetYaxis()->SetTitle("ratio data/MC");   

    ratio->Draw("E1");
		
    TLine *OLine = new TLine(ratio->GetXaxis()->GetXmin(),1.,ratio->GetXaxis()->GetXmax(),1.);
    OLine->SetLineColor(kBlack);
    OLine->SetLineStyle(2);
    OLine->Draw();
 
    TLegend* label = new TLegend(0.60,0.9,0.50,0.95);
    label->SetFillColor(0);
    label->SetFillStyle(0);
    label->SetBorderSize(0);
    //horrible mess
    double binContent = 0;
    double binSum = 0;
    double weightSum = 0;
    double binError = 1;
    double totalbins = ratio->GetSize() -2;
    for(unsigned int bin=1;bin<=totalbins;bin++){
      binContent = ratio->GetBinContent(bin);
      binError = ratio->GetBinError(bin);
      if(binError!=0){
	binSum += binContent/binError;
	weightSum += 1./binError;
      }
    }
    double ymean = binSum / weightSum;
    //double ymean = ratio->GetMean(2);
    stringstream sYmean;
    sYmean << ymean;
    string labeltext=sYmean.str()+" mean Y";
    //label->AddEntry((TObject*)0,labeltext.c_str(),""); // mean on Y
    //label->Draw();
		
    //TPaveStats *r3 = (TPaveStats*)ratio->FindObject("stats");
    //r3->SetX1NDC(0.01);
    //r3->SetX2NDC(0.10); 
    //r3->SetY1NDC(0.20);
    //r3->SetY2NDC(0.50); 
    //gStyle->SetOptStat("mr");
    //r3->SetTextColor(kWhite);
    //r3->SetLineColor(kWhite);
    //r3->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+".png";
    CanvPlot->Print(tmp.c_str());

  }
  else if (flag==2){
    //CanvPlot.Divide(2,1);
    //CanvPlot.cd(1);

    // data
    dataf->cd("validationJEC");
    if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");

    gDirectory->GetObject(plot.c_str(),data2);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    TPaveStats *r1 = (TPaveStats*)data2->FindObject("stats");
    //r1->SetX1NDC(0.70); Uncomment if you wonna draw your stat in the top right corner
    //r1->SetX2NDC(0.85); 
    //r1->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"data.png";
    CanvPlot->Print(tmp.c_str());


    //CanvPlot.cd(2);
    // montecarlo
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    gDirectory->GetObject(plot.c_str(),data2);

    data2->SetMinimum(1);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    //TPaveStats *r2 = (TPaveStats*)data2->FindObject("stats");
    //r2->SetX1NDC(0.70);
    //r2->SetX2NDC(0.85); 
    //r2->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"mc.png";
    CanvPlot->Print(tmp.c_str());
  }
  //	else { cout << "You're getting an exception! Most likely there's no histogram here... \n"; }

  delete data;
  delete data2;
  delete hs;
  //delete CanvPlot;

  dataf->Close();
  mcf->Close();
  ttbarf->Close();
  wf->Close();
  qcd23emf->Close();
  qcd38emf->Close();
  qcd817emf->Close();
  qcd23bcf->Close();
  qcd38bcf->Close();
  qcd817bcf->Close();
  WZf->Close();
  ZZf->Close();
  
  if (isAngularAnalysis){
    if (bckg_leadingJetPt.size()>0 && bckg_2leadingJetPt.size()>0 && bckg_3leadingJetPt.size()>0 && bckg_4leadingJetPt.size()>0  && bckg_JetMultiplicity.size()>0 && bckg_HT.size()>0 && bckg_leadingJetEta.size()>0 && bckg_PhiStar.size()>0 && cold){
      fzj->cd();
      treeBKG_->Fill();
      treeBKG_->Write();
      TH1F *leadhisto=new TH1F("leadhisto","leading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto2=new TH1F("leadhisto2","subleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto3=new TH1F("leadhisto3","subsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto4=new TH1F("leadhisto4","subsubsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *multiphisto=new TH1F("multiphisto","jet multiplicity background contribution",bckg_JetMultiplicity.size(),0,bckg_JetMultiplicity.size());

      TH1F *HT=new TH1F("HT","HT background contribution",bckg_HT.size(),0,bckg_HT.size());
      TH1F *HT1=new TH1F("HT1","HT background contribution when >= 1 jet",bckg_HT1.size(),0,bckg_HT1.size());
      TH1F *HT2=new TH1F("HT2","HT background contribution when >= 2 jets",bckg_HT2.size(),0,bckg_HT2.size());
      TH1F *HT3=new TH1F("HT3","HT background contribution when >= 3 jets",bckg_HT3.size(),0,bckg_HT3.size());
      TH1F *HT4=new TH1F("HT4","HT background contribution when >= 4 jets",bckg_HT4.size(),0,bckg_HT4.size());

      TH1F *leadhistoeta=new TH1F("leadhistoeta","leading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta2=new TH1F("leadhistoeta2","subleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta3=new TH1F("leadhistoeta3","subsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta4=new TH1F("leadhistoeta4","subsubsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());

      TH1F *PhiStar=new TH1F("PhiStar","PhiStar background contribution",bckg_PhiStar.size(),0,bckg_PhiStar.size());

      for (int i=0; i< bckg_leadingJetPt.size(); i++){
	leadhisto->Fill(i,bckg_leadingJetPt[i]);
	leadhisto2->Fill(i,bckg_2leadingJetPt[i]);
	leadhisto3->Fill(i,bckg_3leadingJetPt[i]);
	leadhisto4->Fill(i,bckg_4leadingJetPt[i]);
      }
      leadhisto->Write();
      leadhisto2->Write();
      leadhisto3->Write();
      leadhisto4->Write();

      for (int i=0; i< bckg_leadingJetEta.size(); i++){
	leadhistoeta->Fill(i,bckg_leadingJetEta[i]);
	leadhistoeta2->Fill(i,bckg_2leadingJetEta[i]);
	leadhistoeta3->Fill(i,bckg_3leadingJetEta[i]);
	leadhistoeta4->Fill(i,bckg_4leadingJetEta[i]);
      }
      leadhistoeta->Write();
      leadhistoeta2->Write();
      leadhistoeta3->Write();
      leadhistoeta4->Write();
      //fzj->Close();

      for (int i=0; i< bckg_JetMultiplicity.size(); i++){
	multiphisto->Fill(i,bckg_JetMultiplicity[i]);
      }
      multiphisto->Write();
      
      ///////////////

      for (int i=0; i< bckg_HT.size(); i++){
	HT->Fill(i,bckg_HT[i]);
      }
      HT->Write();
      
      for (int i=0; i< bckg_HT1.size(); i++){
	HT1->Fill(i,bckg_HT1[i]);
      }
      HT1->Write();
      
      for (int i=0; i< bckg_HT2.size(); i++){
	HT2->Fill(i,bckg_HT2[i]);
      }
      HT2->Write();
      
      for (int i=0; i< bckg_HT3.size(); i++){
	HT3->Fill(i,bckg_HT3[i]);
      }
      HT3->Write();
      
      for (int i=0; i< bckg_HT4.size(); i++){
	HT4->Fill(i,bckg_HT4[i]);
      }
      HT4->Write();

      //Phi star
      for (int i=0; i< bckg_PhiStar.size(); i++){
	PhiStar->Fill(i,bckg_PhiStar[i]);
      }
      PhiStar->Write();

    cold=false;
    }
  }
  return;
}
Example #27
0
// New function: takes as input a blank histogram with the right binning, then turns it to a template.
// We used to first make a global hybrid template, then rebin it to match the toporegion
// Instead here we first rebin the golbal template to match the toporegion, and only afterwards we hybridize it
int makeHybridTemplate(TString srname, TH1D* & h_template, TString name , TFile * fData, TFile * fZinv, TFile * fDY, int & lastmt2val_hybrid) {

  //cout<<"purityRandNorm for template "<<name<<endl;
  //h_template->Print("all");
  int lastbin_hybrid = 1;
  lastmt2val_hybrid = 200;
  TString name_emu = name + "emu";
  TString name_zinv = name;
  name_zinv.ReplaceAll("crdy", "sr");
  TH1D* hSF   = (TH1D*) fData->Get(name);    
  TH1D* hOF   = (TH1D*) fData->Get(name_emu);    
  TH1D* hDY    = (TH1D*) fDY->Get(name);    
  TH1D* hZinv  = (TH1D*) fZinv->Get(name_zinv); 

  if (h_template == 0) {
    cout<<"ZinvMaker::makeHybridTemplate  :  could not finde input template"<<endl;
    h_template = 0; // Make sure template isn't used
    return lastbin_hybrid;
  }
  if (hDY == 0 || hZinv == 0) {
    cout<<"ZinvMaker::makeHybridTemplate  :  could not find DY or Zinv MC histogram "<<name<<endl;
    h_template = 0;  // Make sure template isn't used
    return lastbin_hybrid;
  }

  double *TopoRegionBins = h_template->GetXaxis()->GetXbins()->fArray;
  int nTopoRegionBins    = h_template->GetXaxis()->GetNbins();

  if(hSF == 0) {
      cout << "ZinvMaker::makeHybridTemplate : didn't find SF data histogram " << name << ". Using Zinv MC for template" << endl;
      TH1D* h_RebinnedTemplate = (TH1D*) hZinv->Rebin(nTopoRegionBins, "h_RebinnedTemplate", TopoRegionBins);
      h_RebinnedTemplate->Scale(1./h_RebinnedTemplate->Integral());
      for ( int ibin=1; ibin <= h_RebinnedTemplate->GetNbinsX(); ++ibin ) {
          h_template->SetBinContent(ibin, h_RebinnedTemplate->GetBinContent(ibin));
          h_template->SetBinError(ibin, h_RebinnedTemplate->GetBinError(ibin));
      }
      lastmt2val_hybrid = 200;
      return 1;      
  }

  // Rebin all the histograms relevant to the template
  TH1D* h_RebinnedTemplate = (TH1D*) hSF->Rebin(nTopoRegionBins, "h_RebinnedTemplate", TopoRegionBins);
  TH1D* hOF_Rebin = 0;
  if (hOF) hOF_Rebin = (TH1D*) hOF->Rebin(nTopoRegionBins, "hOF_Rebin", TopoRegionBins);
  TH1D* hDY_Rebin = (TH1D*) hDY->Rebin(nTopoRegionBins, "hDY_Rebin", TopoRegionBins);
  TH1D* hZinv_Rebin = (TH1D*) hZinv->Rebin(nTopoRegionBins, "hZinv_Rebin", TopoRegionBins);
  if (hOF) h_RebinnedTemplate->Add(hOF_Rebin, -1*rSFOF);



  lastmt2val_hybrid = -1;
  // find the last bin (hardcoded)
  // for every topological region, just hardcode lastbin_hybrid and lastmt2val_hybrid
  // lastmt2val_hybrid = findLastMT2Hardcoded(srname);
  // if (lastmt2val_hybrid>0) lastbin_hybrid = hDY_Rebin->GetXaxis()->FindBin(lastmt2val_hybrid+1);

  // find the last bin (flexible)
  if (lastmt2val_hybrid == -1) {
    cout<<"Could not find hardcoded last bin for this region. Counting "<<hybrid_nevent_threshold<<" MC events"<<endl;
    for ( int ibin = hDY_Rebin->GetNbinsX()+1; ibin >= 1; --ibin ) {
      //cout<<hDY_Rebin->Integral(ibin,-1)<<endl;
      if (hDY_Rebin->Integral(ibin,-1) < hybrid_nevent_threshold && ibin!=1) continue;
      lastbin_hybrid = ibin;
      lastmt2val_hybrid = hDY_Rebin->GetBinLowEdge(ibin);
    break;
    }
  }

  if (verbose) cout<<lastbin_hybrid<<" "<<lastmt2val_hybrid<<endl;
  //if (verbose) hDY->Print("all");
  //if (verbose) hDY_Rebin->Print("all");
  //if (verbose) hZinv_Rebin->Print("all");
  //if (verbose) h_RebinnedTemplate->Print("all");

  // Get the integrals to normalize the Zinv tails
  // and the uncertainties on the CR yield (dominated by data stats in the last N bins)
  double integratedYieldErrZinv = 0;
  float integratedYieldZinv = hZinv_Rebin->IntegralAndError(lastbin_hybrid, -1., integratedYieldErrZinv);
  float relativeErrorZinv = integratedYieldErrZinv/integratedYieldZinv;
  double integratedYieldErrDY = 0;
  float integratedYieldDY = hDY_Rebin->IntegralAndError(lastbin_hybrid, -1., integratedYieldErrDY);
  float relativeErrorDY = integratedYieldErrDY/integratedYieldDY;
  double integratedYieldErr = 0;
  float integratedYield = h_RebinnedTemplate->IntegralAndError(lastbin_hybrid,-1,integratedYieldErr); 
  float relativeError = integratedYieldErr/integratedYield;

  // Hybridize the template: last N bins have a common stat uncertainty, and they follow the Zinv MC shape
  for ( int ibin=1; ibin <= hZinv_Rebin->GetNbinsX()+1; ++ibin ) {

    if (ibin < lastbin_hybrid) {
      // (SF-OF)*Zinv/DY
      float cont =  h_RebinnedTemplate->GetBinContent(ibin) * hZinv_Rebin->GetBinContent(ibin) / hDY_Rebin->GetBinContent(ibin);
      float err2 =  pow( h_RebinnedTemplate->GetBinError(ibin) / h_RebinnedTemplate->GetBinContent(ibin),2 )  
	+ pow( hZinv_Rebin->GetBinError(ibin) / hZinv_Rebin->GetBinContent(ibin),2)  
	+ pow( hDY_Rebin->GetBinError(ibin)   / hDY_Rebin->GetBinContent(ibin), 2 );
      
      h_RebinnedTemplate->SetBinContent(ibin, cont);
      h_RebinnedTemplate->SetBinError(ibin, sqrt(err2)*cont);

    }
    else {
      float cont = integratedYield * integratedYieldZinv / integratedYieldDY;
      float kMT2 = hZinv_Rebin->GetBinContent(ibin) / integratedYieldZinv;
      float err2 = pow( relativeError, 2 )+ pow( relativeErrorDY, 2 ) + pow(hZinv_Rebin->GetBinError(ibin)/hZinv_Rebin->GetBinContent(ibin), 2);
      h_RebinnedTemplate->SetBinContent(ibin, cont * kMT2);
      h_RebinnedTemplate->SetBinError(ibin, cont*sqrt(err2) * kMT2 );

    }

  }

  // Normalize it: we just need a shape after all
  h_RebinnedTemplate->Scale(1./h_RebinnedTemplate->Integral());

  //h_template->Print("all");

  for ( int ibin=1; ibin <= hZinv_Rebin->GetNbinsX(); ++ibin ) {
    h_template->SetBinContent(ibin, h_RebinnedTemplate->GetBinContent(ibin));
    h_template->SetBinError(ibin, h_RebinnedTemplate->GetBinError(ibin));
  }

  return lastbin_hybrid;
}
Example #28
0
void pc3matching() {

  TFile *f = TFile::Open("output_perform.root");

  ofstream fout("run16dAupc3matching.h");
  ofstream fout2("run16dAupc3matchingfirst.h");
  fout << "float pc3dphimean[2][2][5][50];" << endl;
  fout << "float pc3dphisigma[2][2][5][50];" << endl;
  fout << "float pc3dzmean[2][2][5][50];" << endl;
  fout << "float pc3dzsigma[2][2][5][50];" << endl;
  fout << "float pc3dphimeanerr[2][2][5][50];" << endl;
  fout << "float pc3dphisigmaerr[2][2][5][50];" << endl;
  fout << "float pc3dzmeanerr[2][2][5][50];" << endl;
  fout << "float pc3dzsigmaerr[2][2][5][50];" << endl;
  fout << " " << endl;
  fout << "void fetchpc3dphidz();" << endl;
  fout << " " << endl;
  fout << "void fetchpc3dphidz() {" << endl;


  float max = 0.0;
  float sigma = 0.0;
  float mean = 0.0;

  for (Int_t iarm = 0; iarm < 2; iarm++) {
    for (Int_t ich = 0; ich < 2; ich++) {
      for (Int_t ipt = 0; ipt < 50; ipt++) {
        for(Int_t ivz = 0; ivz < 5; ivz++) {
           // if(ipt!=3 || iarm!=0 || ich!=0 || ivz!=0)continue;
            cout<<iarm<<" "<<ich<<" "<<ipt<<" "<<ivz<<endl;
          double sigmaerr=0.0;
	  double meanerr=0.0;
          TString ch = "";
            if(ich == 0) ch = "pos";
            if(ich == 1) ch = "neg";
	  TString histname = Form("pc3dphidz_arm%d_%s_z%d_%d",iarm,ch.Data(),ivz*2,ipt);
	  TString histname1 = Form("pc3dphidz_arm%d_%s_z%d_%d",iarm,ch.Data(),ivz*2+1,ipt);
          TH2D *hist = (TH2D*) f->Get(histname);
          TH2D *hist1 = (TH2D*) f->Get(histname1);
          hist->Add(hist1);

          TH1D *dphi = (TH1D*) hist->ProjectionX(Form("pc3dphi_%d_%d_%d_%d",iarm,ich,ipt,ivz));
          TH1D *dz = (TH1D*) hist->ProjectionY(Form("pc3dz_%d_%d_%d_%d",iarm,ich,ipt,ivz));

	  dphi->GetXaxis()->SetRangeUser(-0.1,0.1);

          gStyle->SetOptFit(1101);

          TF1 *fphi1 = new TF1("fphi1","gaus",-0.1,0.1);
          TF1 *fz1 = new TF1("fz1","gaus",-10,10);
          TF1 *fphi2 = new TF1("fphi2","gaus(0)+gaus(3)",-0.1,0.1);
          TF1 *fz2 = new TF1("fz2","gaus(0)+gaus(3)",-10,10);
          TF1 *phi_gaus1 = new TF1("phi_gaus1","gaus",-0.1,0.1);
          TF1 *phi_gaus2 = new TF1("phi_gaus2","gaus",-0.1,0.1);
          TF1 *z_gaus1 = new TF1("z_gaus1","gaus",-10,10);
          TF1 *z_gaus2 = new TF1("z_gaus2","gaus",-10,10);


          Float_t Xbins = dphi->GetNbinsX();
          Float_t Xmin = dphi->GetXaxis()->GetXmin();
          Float_t Xmax = dphi->GetXaxis()->GetXmax();
          mean = (dphi->GetMaximumBin() * (Xmax-Xmin))/Xbins + Xmin;
          max = dphi->GetMaximum();
          fphi1->SetRange(mean-0.01,mean+0.01);
	  fphi1->SetParameters(max,mean);

          TCanvas *c = new TCanvas("c","c",500,500);
	  //dphi->Scale(1./dphi->Integral());
	  dphi->SetTitle("dphi matching");
	  dphi->GetXaxis()->SetTitle("dphi");
	  dphi->GetYaxis()->SetTitle("# tracks");
	  if (iarm == 1 && ich ==0) dphi->Rebin(2);
	//  dphi->Rebin(2);
	  dphi->SetMarkerSize(1);
	  dphi->SetMarkerStyle(kFullCircle);
          dphi->Draw("P");
          dphi->Fit("fphi1","RQ0");
          double dphi_par[6];
          fphi1->GetParameters(dphi_par);
          dphi_par[3] = 0.1*dphi_par[0];
          dphi_par[4] = dphi_par[1];
          dphi_par[5] = 8*dphi_par[2];
          fphi2->SetParameters(dphi_par);
	  fphi2->SetParLimits(3,0,5*dphi_par[3]);
	  fphi2->SetParLimits(4,-1,1);
	  fphi2->SetParLimits(5,0,100*dphi_par[2]);
          dphi->Fit("fphi2","RQ0");
	  fphi2->Draw("same");
          fphi2->GetParameters(dphi_par);
	  meanerr = fphi2->GetParError(1);
	  sigmaerr = fphi2->GetParError(2);

          fout << "pc3dphimean[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" << dphi_par[1] << ";" << endl;
          fout << "pc3dphisigma[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" <<  dphi_par[2] << ";" << endl;
          fout << "pc3dphimeanerr[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" << meanerr << ";" << endl;
          fout << "pc3dphisigmaerr[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" <<  sigmaerr << ";" << endl;
          if(ipt == 2){
            fout2 << "PC3_dphifirst_mean[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "] = " << dphi_par[1] << ";" << endl;
            fout2 << "PC3_dphifirst_sigma[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "] = " <<  dphi_par[2] << ";" << endl;
          }

          phi_gaus1->SetParameters(dphi_par[0],dphi_par[1],dphi_par[2]);
          phi_gaus1->SetLineColor(1);
          phi_gaus1->Draw("SAME");
          phi_gaus2->SetParameters(dphi_par[3],dphi_par[4],dphi_par[5]);
          phi_gaus2->SetLineColor(6);
          phi_gaus2->Draw("SAME");

          //c->Print(Form("matching/pc3dphi_%d_%d_%d_%d.png",iarm,ich,ipt,ivz));
          delete c;



          Float_t Xbins = dz->GetNbinsX();
          Float_t Xmin = dz->GetXaxis()->GetXmin();
          Float_t Xmax = dz->GetXaxis()->GetXmax();
          mean = (dz->GetMaximumBin() * (Xmax-Xmin))/Xbins + Xmin;
          max = dz->GetMaximum();
          fz1->SetRange(mean-4,mean+4);
	  fz1->SetParameters(max,mean);

          TCanvas *c = new TCanvas("c","c",500,500);
	  //dz->Scale(1./dz->Integral());
	  dz->SetTitle("dz matching");
	  dz->GetXaxis()->SetTitle("dz");
	  dz->GetYaxis()->SetTitle("# tracks");
	  dz->Rebin(5);
          dz->SetMarkerSize(1);
	  dz->SetMarkerStyle(kFullCircle);
	  dz->Draw("P");
          dz->Fit("fz1","RQ0");
          double dz_par[6];
          fz1->GetParameters(dz_par);
          dz_par[3] = 0.1*dz_par[0];
          dz_par[4] = dz_par[1];
          dz_par[5] = 7*dz_par[2];
          fz2->SetParameters(dz_par);
	  fz2->SetParLimits(3,0,5*dz_par[3]);
	  fz2->SetParLimits(4,-1,1);
	  fz2->SetParLimits(5,2*dz_par[2],8*dz_par[2]);
          dz->Fit("fz2","RQ0");
	  fz2->Draw("same");
          fz2->GetParameters(dz_par);
	  meanerr = fz2->GetParError(1);
	  sigmaerr = fz2->GetParError(2);


          fout << "pc3dzmean[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" << dz_par[1] << ";" << endl;
          fout << "pc3dzsigma[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" <<  dz_par[2] << ";" << endl;
          fout << "pc3dzmeanerr[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" << meanerr << ";" << endl;
          fout << "pc3dzsigmaerr[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "]=" <<  sigmaerr << ";" << endl;
          if(ipt == 2){
            fout2 << "PC3_dzfirst_mean[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "] = " << dz_par[1] << ";" << endl;
            fout2 << "PC3_dzfirst_sigma[" << iarm << "][" << ich << "][" << ivz << "][" << ipt << "] = " <<  dz_par[2] << ";" << endl;
          }

          z_gaus1->SetParameters(dz_par[0],dz_par[1],dz_par[2]);
          z_gaus1->SetLineColor(1);
          z_gaus1->Draw("SAME");
          z_gaus2->SetParameters(dz_par[3],dz_par[4],dz_par[5]);
          z_gaus2->SetLineColor(6);
          z_gaus2->Draw("SAME");

          //c->Print(Form("matching/pc3dz_%d_%d_%d_%d.png",iarm,ich,ipt,ivz));
          delete c;
	}
      }
    }
  }
  fout << "}" << endl;

}
Example #29
0
void roo_fitWH()
{

  gSystem->Load("libRooFit"); 
  gSystem->Load("libRooFitCore");
  gSystem->Load("libMatrix");
  gSystem->Load("libGpad");
  using namespace RooFit;

  TString poscharge = "Plus";
  TString negcharge = "Minus";

  std::vector<TString> charge(2);
  charge.at(0) = poscharge;
  charge.at(1) = negcharge;

  TString bin1 = "50to75";
  TString bin2 = "75to100";
  TString bin3 = "100toinf";

  std::vector<TString> bins(3);
  bins.at(0) = bin1;
  bins.at(1) = bin2;
  bins.at(2) = bin3;

  //we only set up the machinery for the plus charge
  //TFile *dataplus = new TFile("results/GenW_CS_WJets-lite_madgraph_50_75_100.root");
  TFile *dataplus = new TFile("results/RecoW_WJets-lite_madgraph_50_75_100.root");
  TFile *refTemplates = new TFile("results/GenW_CS_WJets-lite_madgraph_50_75_100.root");

  bool makePlots = false;

  TString canvas_name_plus = "MC_WHelicityFramePlots_PlusICVar";
  TCanvas *c0 = new TCanvas(canvas_name_plus,"",900,320);
  c0->Divide(3,1);

  TString canvas_name_minus = "MC_WHelicityFramePlots_MinusICVar";
  TCanvas *c1 = new TCanvas(canvas_name_minus,"",900,320);
  c1->Divide(3,1);
 
  for(unsigned int i=0; i<bins.size(); i++) {
    for(unsigned int j=0; j<charge.size(); j++) {
      //unsigned int index = i*charge.size() + j;
      //cout << "INDEX= " << index << endl;

      //these histograms define the number of events in the complete templates so we can apply correction factors for acceptance etc.
      //do not change these histograms!
      TString refHist1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LH";
      TString refHist2 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_RH";
      TString refHist3 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LO";
      TH1D *refTempHist1 = (TH1D*)refTemplates->Get(refHist1);
      TH1D *refTempHist2 = (TH1D*)refTemplates->Get(refHist2);
      TH1D *refTempHist3 = (TH1D*)refTemplates->Get(refHist3);

      //these histograms are the ones we want to fit
      //TString Hist1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LH";
      //TString Hist2 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_RH";
      //TString Hist3 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j) + "_LO";
      //TString Hist_data1 = "MC_WPlots_" + bins.at(i) + "/MC_ICVar" + charge.at(j);
      TString Hist1 = "RECO_PolPlots_" + bins.at(i) + "/RECO_ICVar"+ charge.at(j) + "_LH";
      TString Hist2 = "RECO_PolPlots_" + bins.at(i) + "/RECO_ICVar"+ charge.at(j) + "_RH";
      TString Hist3 = "RECO_PolPlots_" + bins.at(i) + "/RECO_ICVar"+ charge.at(j) + "_LO";
      TString Hist_data1 = "RECO_PolPlots_" + bins.at(i) + "/RECO_ICVar"+ charge.at(j);

      Int_t rbin=10;
      TH1D *mc1 = (TH1D*)dataplus->Get(Hist1);
      TH1D *mc2 = (TH1D*)dataplus->Get(Hist2);
      TH1D *mc3 = (TH1D*)dataplus->Get(Hist3);
      TH1D *datahist = (TH1D*)dataplus->Get(Hist_data1);

      //we are only fitting for fL and fR
      double accFactor1 = refTempHist1->Integral() / mc1->Integral();
      double accFactor2 = refTempHist2->Integral() / mc2->Integral();
      double accFactor3 = refTempHist3->Integral() / mc3->Integral();
      double normFactor = (mc1->Integral() + mc2->Integral() + mc3->Integral()) / (refTempHist1->Integral() + refTempHist2->Integral() + refTempHist3->Integral());

      mc1->Rebin(rbin);
      mc2->Rebin(rbin);
      mc3->Rebin(rbin);
      datahist->Rebin(rbin);
      //datahist->Scale(10);
      //datahist->Scale(invWeightW);//to get MC errors - otherwise comment out

      Double_t istat=datahist->Integral();
      
      // Start RooFit session
  
      RooRealVar x("x","ICVar",-1.9,1.9);
      // Import binned Data
      RooDataHist data1("data1","dataset with WHICVarPlus",x,mc1);
      RooDataHist data2("data2","dataset with WHICVarPlus",x,mc2);
      RooDataHist data3("data3","dataset with WHICVarPlus",x,mc3);
      RooDataHist test("test_data","dataset with WHICVarPlus",x,datahist);

      //Float_t fr = (1./3.)*istat;
      Float_t fr = (1.0/3.0);

      // Relative fractions - allow them to float to negative values too if needs be
      RooRealVar f1("fL","fL fraction",fr,0.0,1.0);
      RooRealVar f2("fR","fR fraction", fr,0.0,1.0);
      RooRealVar f3("f0","f0 fraction",fr,0.0,1.0);

      // Templates 
      RooHistPdf h1("h1","h1",x,data1);
      RooHistPdf h2("h2","h2",x,data2);
      RooHistPdf h3("h3","h3",x,data3);
      
      // composite PDF  
      RooAddPdf model("model","model",RooArgList(h1,h2,h3),RooArgList(f1,f2)) ;
 
      // Generate data 
      Int_t nevt=static_cast<int>(istat);

      RooDataSet *gtest = model.generate(x,nevt);

      // Fitting
      RooFitResult * res1 = model.fitTo(test,Minos(kTRUE), Save());
      res1->Print();

      if(makePlots) {
	// Plotting
	gROOT->SetStyle("Plain");  
	gStyle->SetOptFit(111);
	gStyle->SetOptTitle(0);
	gStyle->SetOptStat(0);
	 //gStyle->SetCanvasDefH(600); //Height of canvas
	 //gStyle->SetCanvasDefW(600); //Width of canvas   
	//TString canvas_name = "MC_CSFramePlots_" + bins.at(i) + charge.at(j) + "Phi";
	//TCanvas *c0 = new TCanvas(canvas_name,"",300,320);
	if(charge.at(j) == "Plus") c0->cd(i+1);
	if(charge.at(j) == "Minus") c1->cd(i+1);
	RooPlot* frame = x.frame();
	test.plotOn(frame); 
	model.plotOn(frame);
	//model.paramOn(frame);
	model.plotOn(frame, Components(h1),LineColor(kRed),LineStyle(kDashed));
	model.plotOn(frame, Components(h2),LineColor(kGreen),LineStyle(kDashed));
	model.plotOn(frame, Components(h3),LineColor(kYellow),LineStyle(kDashed));
	frame->GetXaxis()->SetTitle("LP Variable");
	frame->Draw();
	//c0->cd(i)->Update();
	//c0->Update();
	//c0->Print(canvas_name+".png");
      }

      const TMatrixDSym& cor = res1->correlationMatrix();
      const TMatrixDSym& cov = res1->covarianceMatrix();
      //Print correlation, covariance matrix
      //cout << "correlation matrix" << endl;
      //cor.Print();
      //cout << "covariance matrix" << endl;
      //cout << "(0,0) = " << cov[0][0] << endl;
      //cout << f1.getVal() << endl;
      //cov.Print();

      double F1 = f1.getVal() * accFactor1 * normFactor;
      double F2 = f2.getVal() * accFactor2 * normFactor;
      double F3 = (1.0 - F1 - F2);

      double F1_err = sqrt(cov[0][0]) * accFactor1 * normFactor;
      double F2_err = sqrt(cov[1][1]) * accFactor2 * normFactor;

      cout << "Fitting bin " << bins.at(i) << " for " << charge.at(j) << " charge: " << endl;
      cout << "fL = " << F1 << " +/- " << F1_err << endl;
      cout << "fR = " << F2 << " +/- " << F2_err << endl;
      cout << "f0 = " << F3 << " +/- " << "N/A" << endl;

    }
  }
  if(makePlots) {
    c0->Print(canvas_name_plus+".png");
    c1->Print(canvas_name_minus+".png");
  }
  return;

}
//___________________________________________________________________________
Double_t* Ifit( TFile* fin, std::string name, std::string output=".", std::string xTitle="", std::string yTitle="Events", int rebin=1, int channel=0, int fit_data=1 )
{
    Double_t* fitted = new Double_t[8];

    TCanvas *c1 = new TCanvas("HF1", "Histos1", 258,92,748,702);
    c1->Range(-104.4905,-2560.33,537.9965,11563.46);
    c1->SetFillColor(0);
    c1->SetBorderMode(0);
    c1->SetBorderSize(2);
    c1->SetLeftMargin(0.1626344);
    c1->SetRightMargin(0.05913978);
    c1->SetTopMargin(0.05349183);
    c1->SetBottomMargin(0.1812779);
    c1->SetFrameBorderMode(0);
    c1->SetFrameBorderMode(0);

    double count=0;
    dataColl.clear();
    sigColl.clear();
    bkgColl.clear();

    totalColl.clear();
    ctauColl.clear();

    //Get data from looping tree

    //TFile *fin = new TFile("results/15Dec_LepJet_MCDATA/Template_EvtChi2_Top_Hadronic_Mass.root");
    //TFile *fin = new TFile("results/15Dec_LepJet_MCDATA/Template_EvtChi2_Top_Leptonic_Mbl.root");


    //   TH1D *hsig = new TH1D();
    //   TH1D *hbkg = new TH1D();
    TH1D *hsig_toymc = new TH1D();
    TH1D *hbkg_toymc = new TH1D();

    char hname[30];
    std::string ch;
    if( channel == 1 )
        ch="_El";
    else if( channel == 2)
        ch="_Mu";
    else
        ch="";

    TH1D * hsig = (TH1D*)((TH1D*)fin->Get(("SigMC"+ch).c_str()))->Clone();
    TH1D * hbkg = (TH1D*)((TH1D*)fin->Get(("BkgMC"+ch).c_str()))->Clone();
    TH1D *hEGdata;
    hEGdata = (TH1D*)((TH1D*)fin->Get(("DATA"+ch).c_str()))->Clone();

    // hsig->Sumw2();
    //hbkg->Sumw2();

    // hsig->Rebin(2);
    // hbkg->Rebin(2);
    // hEGdata->Rebin(2);
    // hbkg_toymc->Rebin(2);
    // hsig_toymc->Rebin(2);

    hsig->Rebin(rebin);
    hbkg->Rebin(rebin);
    hEGdata->Rebin(rebin);

    // normalize template
    hsig->Scale(1./hsig->Integral());
    hbkg->Scale(1./hbkg->Integral());  
    if(fit_data==0){
        hsig_toymc->Scale(1./hsig_toymc->Integral());
        hbkg_toymc->Scale(1./hbkg_toymc->Integral());
    }

  TH1D *hsum = new TH1D();
  int ntemplate = 1000.;
  float sigfrac = 0.5;
  TH1D *hsum_norm = new TH1D();
  TH1D *hdata = new TH1D();

  int ndata=0;
  if ( fit_data>0 ) {
    hdata = (TH1D*)hEGdata->Clone();
    ndata = hdata->GetEntries();
  }else { //generate toymc
    hsum = (TH1D*)hsig_toymc->Clone();
    hsum->Scale(toymc_sig);
    hsum->Add(hbkg_toymc,toymc_bkg);
    
    hsum_norm = (TH1D*)hsum->Clone();  
    hsum_norm->Scale(1./hsum->Integral());
    hdata = (TH1D*)hsum_norm->Clone();
    //ndata = (int) gRandom->Poisson(hsum->Integral());
    ndata=toymc_sig+toymc_bkg;
    hdata->FillRandom(hsum_norm, ndata);
  }
  if(ndata==0) {
    printf(" ---  no events in the fit \n");
    fitted[0] = 0.;
    fitted[1] = 0.;
    fitted[2] = 0.;
    fitted[3] = 0.;
    fitted[4] = 0.;
    fitted[5] = 0.;
    fitted[6] = 0.;
    fitted[7] = 0.;
    fin_data->Close();
    fin->Close();
    fin_gjet6000->Close();

    return fitted;
  }    

  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,  test sample size %4d\n", hsig->Integral()/hsum->Integral(), hsum->Integral(), ndata);
  printf(" -------------------------------------- \n");

  int nbins = hdata->GetNbinsX();
  for (int ibin=1; ibin<=nbins; ibin++) {
    dataColl.push_back(hdata->GetBinContent(ibin));
    sigColl.push_back(hsig->GetBinContent(ibin));
    bkgColl.push_back(hbkg->GetBinContent(ibin));    
  }
  printf( " -----  Got %d, %d, %d events for fit ----- \n ", dataColl.size(), sigColl.size(), bkgColl.size() );  
  if ( dataColl.size() != sigColl.size() || sigColl.size()!=bkgColl.size() ) {
    printf(" error ...  inconsistent hit collection size \n");
    fin_data->Close();
    fin->Close();
    fin_gjet6000->Close();

    return fitted;
  }

  //--------------------------------------------------
  //init parameters for fit
  Double_t vstart[10] = {1., 1.};
  vstart[0] = sigfrac*ndata;
  vstart[1] = (1-sigfrac)*ndata;
 
  TMinuit *gMinuit = new TMinuit(NPAR);  
  gMinuit->Command("SET STR 1");
  gMinuit->SetFCN(fcn);
  Double_t arglist[10];
  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[] = { 0.1, 0.1,};

  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);
  
  printf(" --------------------------------------------------------- \n");
  printf(" Now ready for minimization step \n --------------------------------------------------------- \n");
  
  arglist[0] = 2000; // number of iteration
  arglist[1] = 1.;
  gMinuit->mnexcm("MIGRAD", arglist ,2,ierflg);
  printf (" -------------------------------------------- \n");
  printf("Finished.  ierr = %2.2f \n", ierflg);

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

  double para[NPAR+1],errpara[NPAR+1];
  if ( ierflg == 0 ) 
    {
      for(int j=0; j<=NPAR-1;j++) {
        gMinuit->GetParameter(j, para[j],errpara[j]);
        para[NPAR] = dataColl.size();
        info.push_back(para[j]);
        info_err.push_back(errpara[j]);
        printf("Parameter (yeild) %d = %f +- %f\n",j,para[j],errpara[j]);
	
      }
      printf(" fitted yield %2.3f \n", (para[0]+para[1])/ndata );

      info.push_back(sigColl.size());

      //do minos if fit sucessed.
//       printf("         ---------------------------------------------------------\n");
//       printf("          Now call for minos step \n");
//       printf("         ---------------------------------------------------------\n");
      
//       arglist[0] = 200; // number of iteration
//       arglist[1] = 1;
//       gMinuit->mnexcm("MINOS", arglist ,2,ierflg);
//       printf("         --------------------------------------------------------- \n");
//       printf("         Done Minos.  ierr = %d \n", ierflg);
//       Double_t amin;
//       gMinuit->mnprin(1,amin);
    }
  else {
    printf(" *********** Fit failed! ************\n");
    gMinuit->GetParameter(0, para[0],errpara[0]);
    gMinuit->GetParameter(1, para[1],errpara[1]);
    para[0]=0.; errpara[0]=0.;
  }

  
  // 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);

  double yerr[100];
  for(int i=0;i<100;i++){
    yerr[i] = 0.;
  }

  hsig->Scale(para[0]);
  hbkg->Scale(para[1]);
  TH1D *hfit = (TH1D*)hbkg->Clone();
  hfit->Add(hsig);

  hsig->SetLineColor(4);
  hsig->SetLineWidth(2);
//   hsig->SetFillColor(5);
//   hsig->SetFillStyle(3001);

//   hbkg->SetLineWidth(2);
  // plot
  c1->Draw();  
    gStyle->SetOptStat(0);
    gStyle->SetOptTitle(0); 
  //gPad->SetLogy();
  hdata->SetLineColor(1);

  hdata->SetXTitle(xTitle.c_str());
  hdata->SetYTitle(yTitle.c_str());
  hdata->SetTitle("");
  hdata->SetMarkerStyle(8);
  hdata->SetMinimum(0.);
  hdata->GetXaxis()->SetNdivisions(505);
  hdata->GetXaxis()->SetLabelFont(42);
  hdata->GetXaxis()->SetLabelSize(0.05);
  hdata->GetXaxis()->SetTitleSize(0.06);
  hdata->GetXaxis()->SetTitleOffset(1.15);
  hdata->GetXaxis()->SetTitleFont(42);
  hdata->GetYaxis()->SetNdivisions(505);
  hdata->GetYaxis()->SetLabelFont(42);
  hdata->GetYaxis()->SetLabelSize(0.035);
  hdata->GetYaxis()->SetTitleSize(0.06);
  hdata->GetYaxis()->SetTitleOffset(1.21);
  hdata->GetYaxis()->SetTitleFont(42);

  float ymax = hdata->GetMaximum();
  if ( hfit->GetMaximum() > hdata->GetMaximum() ) ymax = hfit->GetMaximum();
  if ( hdata->GetMaximum() < 15 ) ymax = 15;
  hdata->SetMaximum(ymax*1.4);
  hfit->SetMaximum(ymax*1.4);
  hsig->SetMaximum(ymax*1.4);
  hbkg->SetMaximum(ymax*1.4);

  hdata->Draw("p e");

  hbkg->SetMarkerStyle(0);
  hbkg->SetFillColor(2);
  hbkg->SetLineWidth(1);
  hbkg->SetLineColor(2);
  hbkg->SetFillStyle(3005);
  hbkg->SetError(yerr);
  hbkg->Draw("h same");

  hsig->SetMarkerStyle(0);
  hsig->SetError(yerr);
  hsig->Draw("h same");

  hfit->SetMarkerStyle(0);
  hfit->SetLineColor(1);
  hfit->SetLineWidth(2);
  hfit->SetError(yerr);
  //printf("nbins hfit %d \n", hfit->GetNbinsX());
  hfit->Draw("h same");
  hdata->Draw("p e same");
  
  TLegend *tleg = new TLegend(0.5241935,0.6344725,0.8682796,0.9331352,NULL,"brNDC");
  char text[50];
  sprintf(text,"Top Mass");
  //tleg->SetHeader(text);
  tleg->SetBorderSize(0);
  tleg->SetTextSize(0.03120357);
  tleg->SetLineColor(1);
  tleg->SetLineStyle(1);
  tleg->SetLineWidth(1);
  tleg->SetFillColor(0);
  tleg->SetFillStyle(0);
  sprintf(text,"Data %5.1f events",hdata->Integral());
  tleg->AddEntry(hdata,text,"pl");
  sprintf(text,"Fitted %5.1f events",hfit->Integral());
  
  tleg->AddEntry(hfit,text,"l");
  sprintf(text,"SIG %5.1f #pm %5.1f events",para[0], errpara[0]);
  tleg->AddEntry(hsig,text,"f");
  sprintf(text,"BKG %5.1f #pm %5.1f events",para[1], errpara[1]);
  
  tleg->AddEntry(hbkg,text,"f");
  tleg->Draw();
  
  TLatex *tlx = new TLatex(6.247421e-06,9218.143,"CMS #sqrt{s} = 8TeV, L=19.7 fb^{-1}");
  tlx->SetTextSize(0.035);
  tlx->SetLineWidth(2);
  tlx->Draw();

  //gPad->RedrawAxis();
  
  if(fit_data>0) hdata->Chi2Test(hfit,"P");

  c1->SaveAs((output+"/FittingResults_"+name+ch+".pdf").c_str());
  return fitted;

//   float sig_part = hsig->Integral(ibin1,hfit->GetNbinsX());
//   float sig_part_err = hsig->Integral(ibin1,hfit->GetNbinsX())*errpara[0]/para[0];
//   float bkg_part = hbkg->Integral(ibin1,hfit->GetNbinsX());
//   float bkg_part_err = hbkg->Integral(ibin1,hfit->GetNbinsX())*errpara[1]/para[1];
//   printf("%s Data %5.1f events, fitted %5.1f\n", EBEE, hdata->Integral(), hfit->Integral());
//   printf("%s Data %5.1f, and fitted (in 5GeV) %5.1f events \n", EBEE, hdata->Integral(ibin1,hfit->GetNbinsX()), hfit->Integral(ibin1,hfit->GetNbinsX()));
//   printf("%s SIG %5.1f #pm %5.1f events \n", EBEE, para[0], errpara[0]);
//   printf("%s SIG (in 5GeV) %5.1f #pm %5.1f events \n", EBEE, sig_part, sig_part_err);
//   printf("%s BKG %5.1f #pm %5.1f events \n", EBEE, para[1], errpara[1]);
//   printf("%s BKG (in 5GeV) %5.1f #pm %5.1f events \n", EBEE, bkg_part, bkg_part_err);
   

//   char fname[30];
//   sprintf(fname,"plots/test_Ifit%s_%d_%d.pdf",EBEE, jetbin, ptbin);
  
//   printf("----- fit results with signal projection   ----------- \n");
//   if(fit_data>0) hdata->Chi2Test(hfit,"P");
//   //ftemplate->Close();

//   fitted[0] = para[0];
//   fitted[1] = errpara[0]/TMath::Sqrt(2);
//   fitted[2] = para[1];
//   if (fit_data==2 ) fitted[2] += hdata->GetBinContent(hdata->GetNbinsX()+1);
//   fitted[3] = errpara[1]/TMath::Sqrt(2);
//   fitted[4] = sig_part;
//   fitted[5] = sig_part_err/TMath::Sqrt(2);
//   fitted[6] = bkg_part;
//   fitted[7] = bkg_part_err/TMath::Sqrt(2);
  
//   if(fit_data==0){
//     fin_filter->Close();
//     fin_data->Close();
//     fin->Close();
//     fin_gjet6000->Close();
//     fin_DYMC->Close();
//     fin_DYData->Close();
//     fin_WJetMC->Close();
//     fin_WJetData->Close();
//     fin_WJetTemplate->Close();
//     fin_WJetTemplate_alt->Close();
//   }

  return fitted;
}