std::pair<float,float> getFitRange(TH1D& hist) {
  int maxBin = hist.GetMaximumBin();
  float targetVal = hist.GetBinContent( maxBin ) /2.;


  int nBins = hist.GetNbinsX();
  
  std::pair<float,float> results = {hist.GetBinLowEdge(1),hist.GetBinLowEdge(nBins+1)};

  int diff=0;
  while( maxBin-(++diff) >0) {
    if( hist.GetBinContent(maxBin-diff) < targetVal ){
      results.first = hist.GetBinCenter(maxBin-diff);
      break;
    }
  }

  diff=0;
  while( maxBin+(++diff) <=nBins) {
    if( hist.GetBinContent(maxBin+diff) < targetVal ){
      results.second = hist.GetBinCenter(maxBin+diff);
      break;
    }
  }
  
  
  return results;
}
Пример #2
0
void loglikdistrib(Int_t ntrials = 10000, Bool_t print = kFALSE)
{
  // compute distribution of log likelihood value
  TH1D * hmc   = gStack[gPadNr][gOrder[gPadNr][0]];
  TH1D * hdata = gStack[gPadNr][gMaxProcess-1];
  Int_t nbins = hmc->GetNbinsX();
  Double_t loglik = loglikelihood(hmc, hdata, 1, nbins);
  TH1D * htest = new TH1D(*hdata);
  TH1D * lldistrib = new TH1D("lldistrib", "log(Likelihood) distribution", 
			      1000, loglik-200, loglik+200);
  setopt(lldistrib);
  for (Int_t n = 0; n < ntrials; n++) {
    // generate poisson around theorie
    for (Int_t i = 1; i <= nbins; i++) {
      htest->SetBinContent(i, gRandom->Poisson(hmc->GetBinContent(i)));
    }
    lldistrib->Fill(loglikelihood(hmc, htest, 1, nbins));
  }
  TCanvas * llcanvas = new TCanvas("llcanvas", "Log(Likelihood) distribution", 
				   40, 40, 800, 600);
  setopt(llcanvas);
  lldistrib->SetFillColor(kYellow);
  lldistrib->Draw();
  lldistrib->GetYaxis()->SetTitle("Anzahl Ereignisse");
  lldistrib->GetXaxis()->SetTitle("-ln L");
  // autozoom
  Int_t lowbin = 1;
  while (lldistrib->GetBinContent(lowbin) == 0)
    lowbin++;
  Int_t highbin = lldistrib->GetNbinsX();
  while (lldistrib->GetBinContent(highbin) == 0)
    highbin--;
  lldistrib->SetAxisRange(lldistrib->GetBinLowEdge(lowbin), 
			  lldistrib->GetBinLowEdge(highbin));
  TH1D * hworse = (TH1D *) lldistrib->Clone();
  for (Int_t nbin = 1; nbin < 501; nbin++) {
    hworse->SetBinContent(nbin, 0);
  }
  hworse->SetFillColor(95);
  hworse->Draw("same");
  Double_t pvalue = lldistrib->Integral(501,1000) / lldistrib->Integral();
  TLatex * tex = new TLatex(0.18, 0.96, Form("-ln L_{obs} = %5.2f", loglik));
  tex->SetNDC();
  tex->SetTextAlign(13);
  tex->Draw();
  tex = new TLatex(0.18, 0.86, Form("CL_{obs} = %.3f", pvalue));
  tex->SetNDC();
  tex->SetTextAlign(13);
  tex->Draw();
  TLine * l = new TLine(loglik, 0, loglik, lldistrib->GetMaximum());
  l->SetLineWidth(3);
  l->SetLineColor(kBlue);
  l->Draw();
  llcanvas->Modified();
  llcanvas->Update();
  if (print)
    llcanvas->Print("lldistrib.pdf");
  cd(gPadNr+1);
}
Пример #3
0
void Normalize(TH1D &h, double normalization, bool norm_per_avg_width) {
    int nbins = h.GetNbinsX();
    double low = h.GetBinLowEdge(1);
    double high = h.GetBinLowEdge(nbins+1);
    double width = (high-low)/nbins;
    if(norm_per_avg_width) normalization *= width;
    double integral = h.Integral("width");
    h.Scale(normalization/integral);
}
Пример #4
0
void AdjustDensityForBinWidth(TH1D &h) {
    double entries = h.GetEntries();
    int nbins = h.GetNbinsX();
    double low = h.GetBinLowEdge(1);
    double high = h.GetBinLowEdge(nbins+1);
    double width = (high-low)/nbins;
    for(int bin = 1; bin <= nbins; ++bin) {
        double content = h.GetBinContent(bin);
        double error = h.GetBinError(bin);
        double this_width = h.GetBinWidth(bin);
        double scale = width/this_width;
        h.SetBinContent(bin, content*scale);
        h.SetBinError(bin, error*scale);
    }
    h.SetEntries(entries);
}
Пример #5
0
// Rebin first histogram to match the second
TH1D *tools::Rebin(const TH1D *h, const TH1D* href) {

  //assert(href->GetNbinsX()<=h->GetNbinsX());
  if (!(href->GetNbinsX()<=h->GetNbinsX())) {
    cout << "Histo has less bins than ref: "
	 << h->GetNbinsX() << " vs " << href->GetNbinsX()
	 << " for " << h->GetName() << endl;
  }
  
  // First, we need to rebin inclusive jets to match b-tagged jets
  TH1D *hre = (TH1D*)href->Clone(Form("%s_rebin",h->GetName()));
  hre->Reset();

  for (int i = 1; i != h->GetNbinsX()+1; ++i) {

    double x = h->GetBinLowEdge(i);
    int j = hre->FindBin(x);
    // Check that h is fully contained within href bin
    if (h->GetBinContent(i)!=0) {

      if (!(h->GetBinLowEdge(i)>=hre->GetBinLowEdge(j) - 1e-5 &&
	    h->GetBinLowEdge(i+1)<=hre->GetBinLowEdge(j+1) + 1e-5)) {
	cerr << Form("Warning, bin edges overlapping: h=[%1.0f,%1.0f],"
		     " hre=[%1.0f,%1.0f] (%s)",
		     h->GetBinLowEdge(i), h->GetBinLowEdge(i+1),
		     hre->GetBinLowEdge(j), hre->GetBinLowEdge(j+1),
		     h->GetName()) << endl;
      }

      double y = ( hre->GetBinContent(j)*hre->GetBinWidth(j)
		   + h->GetBinContent(i)*h->GetBinWidth(i) )
	/ hre->GetBinWidth(j);
      //double ey = ( hre->GetBinError(j)*hre->GetBinWidth(j)
      //	    + h->GetBinError(i)*h->GetBinWidth(i) )
      // / hre->GetBinWidth(j);
      double ey = sqrt( pow(hre->GetBinError(j)*hre->GetBinWidth(j),2)
			+ pow(h->GetBinError(i)*h->GetBinWidth(i),2) )
	/ hre->GetBinWidth(j);
      hre->SetBinContent(j, y);
      hre->SetBinError(j, ey);
    }
  } // for i

  return hre;
} // Rebin
Пример #6
0
void FindMCToDataScaleFactor() {

  std::string data_filename = "~/data/out/v92/total.root";
  TFile* data_file = new TFile(data_filename.c_str(), "READ");
  std::string data_plotname = "TME_Al50_EvdE/all_particles/SiL_EvdE";
  TH2F* hEvdE_data = (TH2F*) data_file->Get(data_plotname.c_str());
  hEvdE_data->SetDirectory(0);
  data_file->Close();

  std::string MC_filename = "plots.root";
  TFile* MC_file = new TFile(MC_filename.c_str(), "READ");
  std::string MC_plotname = "hAll_EvdE_SiL";
  TH2F* hEvdE_MC = (TH2F*) MC_file->Get(MC_plotname.c_str());
  hEvdE_MC->SetDirectory(0);
  MC_file->Close();

  double energy_slice = 3000;
  int energy_slice_bin = hEvdE_data->GetXaxis()->FindBin(energy_slice);
  TH1D* hDataProjection = hEvdE_data->ProjectionY("_py", energy_slice_bin, energy_slice_bin);  
  energy_slice_bin = hEvdE_MC->GetXaxis()->FindBin(energy_slice);
  TH1D* hMCProjection = hEvdE_MC->ProjectionY("_py", energy_slice_bin, energy_slice_bin);

  TFitResultPtr data_fit_result = hDataProjection->Fit("gaus", "S");
  TFitResultPtr MC_fit_result = hMCProjection->Fit("gaus", "S");

  hDataProjection->SetLineColor(kBlack);
  hDataProjection->GetXaxis()->SetRangeUser(0, energy_slice);
  hDataProjection->Draw();
  hMCProjection->SetLineColor(kRed);
  hMCProjection->GetXaxis()->SetRangeUser(0, energy_slice);
  hMCProjection->Draw("SAME");

  //EvdE_data->Draw("COLZ");
  double data_mean = data_fit_result->Parameter(1);
  double MC_mean = MC_fit_result->Parameter(1);
  double scale_factor = data_mean / MC_mean;
  std::cout << "data / MC = " <<  data_mean << " / " << MC_mean << " = " << scale_factor << std::endl;

  // Go through the MC projection and scale each bin by the scale factor
  int n_bins = hMCProjection->GetNbinsX();
  double min_x = hMCProjection->GetXaxis()->GetXmin();
  double max_x = hMCProjection->GetXaxis()->GetXmax();
  TH1F* hMCProjection_scaled = new TH1F("hMCProjection_scaled", "", n_bins,min_x,max_x);

  for (int i_bin = 1; i_bin <= n_bins; ++i_bin) {
    double old_energy = hMCProjection->GetBinLowEdge(i_bin);
    double new_energy = old_energy * scale_factor;

    double old_bin_content = hMCProjection->GetBinContent(i_bin);
    hMCProjection_scaled->Fill(new_energy, old_bin_content);
  }

  hMCProjection_scaled->Draw();
  hDataProjection->Draw("SAME");
}
Пример #7
0
void reweighthisto(TH1D* hBPt, TH2D* h2D, TH1D *hRAA=0, bool weightByJpsiRAA=0, bool weightByBRAA=0)
{
   TH1D *htmp = h2D->ProjectionX("htmp");
   TH1D *htmp2 = h2D->ProjectionY("htmp2");
   
   for (int x=1;x<=h2D->GetNbinsX()+1;x++){
      if (htmp->GetBinContent(x)==0) continue;
      double ratio = hBPt->GetBinContent(x)/htmp->GetBinContent(x);
      if (weightByBRAA) ratio *= hRAA->GetBinContent(hRAA->FindBin(htmp->GetBinLowEdge(x)));   
       
      for (int y=1;y<=h2D->GetNbinsY()+1;y++){
         double ratio2 = ratio;
         if (weightByJpsiRAA) ratio2 *= hRAA->GetBinContent(hRAA->FindBin(htmp2->GetBinLowEdge(y)));   
         double val = h2D->GetBinContent(x,y)*ratio2;
         double valError = h2D->GetBinError(x,y)*ratio2;
	 h2D->SetBinContent(x,y,val);
	 h2D->SetBinError(x,y,valError);
      }   
   }
   delete htmp;
   
}
void run_DataGammaJetsZllToZnunu(){

	// defs ---------------------------------------------------------
	gSystem->CompileMacro("../MT2Code/src/MT2Shapes.cc", "k");
	
	// logStream
	fLogStream = new std::ostringstream();
	
	// create dir
	if(!fOutDir.EndsWith("/")) fOutDir += "/";
	char cmd[500];
	sprintf(cmd,"mkdir -p %s", fOutDir.Data());
	system(cmd);

	DefineCutStreams(fHTmin, fHTmax, fMT2min, fMT2max);
	TString filename=fOutDir+"/"+fRootFile;
	fOutFile = new TFile(filename.Data(), "RECREATE");
	fDir     = (TDirectory*) fOutFile;

	// fix output dir
//	if(fHTmax <10000) fOutDir= TString::Format("%s_%d_HT_%d",  fOutDir.Data(), abs(fHTmin),  abs(fHTmax));
//	else              fOutDir= TString::Format("%s_%d_HT_%s",  fOutDir.Data(), abs(fHTmin),  "Inf");
//	if(fMT2max<10000) fOutDir= TString::Format("%s_%d_MT2_%d", fOutDir.Data(), abs(fMT2min), abs(fMT2max));
//	else              fOutDir= TString::Format("%s_%d_MT2_%s", fOutDir.Data(), abs(fMT2min), "Inf");
	
	// log MT2 and HT cuts
	*fLogStream << "------------------------------------------------------------------------------------------------" << endl;
	*fLogStream << "+++ new Znunu with Gamma+jets prediction                                                     +++" << endl;
	*fLogStream << "+++ outputdir: " << fOutDir <<                                                              "+++" << endl; 
	*fLogStream << "------------------------------------------------------------------------------------------------" << endl;
	
	// new prediction ------------------------------------------------------
	Prediction* prediction = new Prediction();
	prediction->fVerbose=fVerbose;
	prediction->fSave   =fSaveResults;


	// Photon Pt
	if(fDoPhotonPtShape){
  	const int gNMT2bins                   = 11;
  	double  gMT2bins[gNMT2bins+1]   = {150, 160, 170, 180, 190, 200, 225, 250, 300, 400, 550, 800}; 	
	prediction->ChPhotonPt = new Channel("PhotonPt", "photon[0].lv.Pt()", cutStream_PhotonPt.str().c_str(), fTriggerStream.str().c_str(),fSamplesPhotonPt);
	prediction->ChPhotonPt->fVerbose =prediction->fVerbose;
//	prediction->ChPhotonPt->GetShapes("PhotonPt", "#gamma Pt", 2, 300, 800);
	prediction->ChPhotonPt->GetShapes("PhotonPt", "#gamma Pt", 100, 150, 800);
//	prediction->ChPhotonPt->GetShapes("PhotonPt", "#gamma Pt", gNMT2bins, gMT2bins);
	}
	
	// Zll Pt
	if(fDoZllPtShape){
  	const int gNMT2bins                   = 11;
  	double  gMT2bins[gNMT2bins+1]   = {150, 160, 170, 180, 190, 200, 225, 250, 300, 400, 550, 800}; 	
	prediction->ChZllPt = new Channel("ZllPt", "RecoOSDiLeptPt(20,2.4,71,111)", cutStreamZll.str().c_str(), fTriggerStream.str().c_str(),fSamplesZllPt);
	prediction->ChZllPt->fVerbose =prediction->fVerbose;
//	prediction->ChZllPt->GetShapes("ZllPt", "Zll Pt", 2, 300, 800);
	prediction->ChZllPt->GetShapes("ZllPt", "Zll Pt", 100, 150, 800);
//	prediction->ChZllPt->GetShapes("ZllPt", "Zll Pt", gNMT2bins, gMT2bins);
	}

	// compute Zll/gamma pt ratio
	if(fDoPhotonPtShape && fDoZllPtShape){
		TH1D* hPhotonToZllPtRatio = prediction->GetRatio(fDoDataZllToPhotonRatio? prediction->ChZllPt->hData    : prediction->ChZllPt->hZJetsToLL, 
				                                 fDoDataZllToPhotonRatio? prediction->ChPhotonPt->hData : prediction->ChPhotonPt->hPhotons, 4);
		DrawHisto(hPhotonToZllPtRatio,hPhotonToZllPtRatio->GetName(),"EX0");
		TString rationame=hPhotonToZllPtRatio->GetName();
		rationame +="_fittedRatio";
		TF1 *f_lin = new TF1(rationame,"pol0(0)", fZllToGammaFitMin , fZllToGammaFitMax);   f_lin->SetLineColor(8);
		if(fDoFits){ 
			hPhotonToZllPtRatio->Fit(rationame,"0L","", fZllToGammaFitMin, fZllToGammaFitMax);    // set al weights to 1
			fZllToPhotonRatio   = f_lin->GetParameter(0);
		} else{
			fZllToPhotonRatio   = prediction->GetLimitedRatio(fDoDataZllToPhotonRatio? prediction->ChZllPt->hData: prediction->ChZllPt->hZJetsToLL,
			                                              fDoDataZllToPhotonRatio? prediction->ChPhotonPt->hData : prediction->ChPhotonPt->hPhotons,
				                                      fZllToGammaFitMin, fZllToGammaFitMax, false, fZllToPhotonRatioRelErr);
			f_lin->SetParameter(0,fZllToPhotonRatio);
		}
  		const int nBins= 3;
		const double Bins[nBins+1] = {150, fZllToGammaFitMin>150?fZllToGammaFitMin:150.0001, fZllToGammaFitMax<800? fZllToGammaFitMax:799.99, 800};
		TH1D* hErrorbar = new TH1D(rationame.Data(), "", nBins, Bins);
		hErrorbar->SetBinContent(2,fZllToPhotonRatio);
		hErrorbar->SetBinError(2,fZllToPhotonRatioRelErr*fZllToPhotonRatio);
		hErrorbar->SetBinContent(1,-10);
		hErrorbar->SetBinError( 1,0);
		hErrorbar->SetFillColor(5);
		hErrorbar->SetFillStyle(3001);
		hErrorbar->Draw("e2same");
		f_lin->Draw("same");
		hPhotonToZllPtRatio->Draw("EX0same");
	}
	
	// GenLevel Zll Pt, no acceptance cuts
	if(fDoGenZllShape){
	prediction->ChGenZllPt = new Channel("GenZllPt", "GenDiLeptPt(0,10,0,1000,true)", cutStreamGenZll.str().c_str(), fTriggerStream.str().c_str(),fSamplesZllPtMConly);
	prediction->ChGenZllPt->fVerbose =prediction->fVerbose;
	prediction->ChGenZllPt->GetShapes("GenZllPt", "GenZll Pt", 8, 0, 800);
	}
	
	// GenLevel Zll Pt, within acceptance
	if(fDoGenAccZllShape){
	prediction->ChGenZllPtAcc = new Channel("GenZllPtAcc", "GenDiLeptPt(20,2.4,71,111,true)", cutStreamGenZllAcc.str().c_str(), fTriggerStream.str().c_str(),fSamplesZllPtMConly);
	prediction->ChGenZllPtAcc->fVerbose =prediction->fVerbose;
	prediction->ChGenZllPtAcc->GetShapes("GenZllPtAcc", "GenZll Pt", 8, 0, 800);
	}
	// Get Acceptance Efficiency
	if(fDoGenZllShape && fDoGenAccZllShape){
		Bool_t binomial =true;
		TH1D* hZllAccEff = prediction->GetRatio(prediction->ChGenZllPtAcc->hZJetsToLL, prediction->ChGenZllPt->hZJetsToLL, 1, binomial);
		DrawHisto(hZllAccEff,hZllAccEff->GetName(),"EX");
//		TString rationame=hZllAccEff->GetName();
//		rationame +="_fittedRatio";
//		TF1 *f_lin = new TF1(rationame,"pol0(0)", fZllAccFitMin ,   fZllAccFitMax);   f_lin->SetLineColor(8);
//		if(fDoFits){ 
//			hZllAccEff->Fit(rationame,"0L","", fZllAccFitMin, fZllAccFitMax);    // set al weights to 1
//			fZllAccEff= f_lin->GetParameter(0);
//		} else{
//			fZllAccEff= prediction->GetLimitedRatio(prediction->ChGenZllPtAcc->hZJetsToLL,prediction->ChGenZllPt->hZJetsToLL,
//				                                fZllAccFitMin, fZllAccFitMax, true, fZllAccEffRelErr);
//			f_lin->SetParameter(0,fZllAccEff);
//		}
//  		const int nBins= 3;
//		const double Bins[nBins+1] = {150, fZllAccFitMin>150?fZllAccFitMin:150.0001, fZllAccFitMax<800? fZllAccFitMax:799.99, 800};
//		TH1D* hErrorbar = new TH1D(rationame.Data(), "", nBins,Bins);
//		hErrorbar->SetBinContent(2,fZllAccEff);
//		hErrorbar->SetBinError(2,fZllAccEffRelErr*fZllAccEff);
//		hErrorbar->SetBinContent(1,-1);
//		hErrorbar->SetBinError(1,0);
//		hErrorbar->SetFillColor(5);
//		hErrorbar->SetFillStyle(3001);
//		hErrorbar->Draw("e2same");
//		f_lin->Draw("same");
//		hZllAccEff->Draw("EX0same");
	}
	
	// GenLevel Zll Pt, within acceptance, OS dilepton recoed
	if(fDoGenAccZllRecoShape){
	prediction->ChGenZllPtAccRecoed = new Channel("GenZllPtAccRecoed", "GenDiLeptPt(20,2.4,71,111,true)", cutStreamGenZllAcc_recoed.str().c_str(), fTriggerStream.str().c_str(),fSamplesZllPtMConly);
	prediction->ChGenZllPtAccRecoed->fVerbose =prediction->fVerbose;
	prediction->ChGenZllPtAccRecoed->GetShapes("GenZllPtAccRecoed", "GenZll Pt", 100, 150, 800);
	}
	if(fDoGenAccZllShape && fDoGenAccZllRecoShape){
		Bool_t binomial =true;
		TH1D* hZllRecoEff = prediction->GetRatio(prediction->ChGenZllPtAccRecoed->hZJetsToLL, prediction->ChGenZllPtAcc->hZJetsToLL, 4, binomial);
		DrawHisto(hZllRecoEff,hZllRecoEff->GetName(),"EX");
		TString rationame=hZllRecoEff->GetName();
		rationame +="_fittedRatio";
		TF1 *f_lin = new TF1(rationame,"pol0(0)", fZllRecoEffFitMin , fZllRecoEffFitMax);   f_lin->SetLineColor(8);
		if(fDoFits){ 
			hZllRecoEff->Fit(rationame,"0L","", fZllRecoEffFitMin, fZllRecoEffFitMax);    // set al weights to 1
			fZllRecoEff= f_lin->GetParameter(0);
		} else{
			fZllRecoEff= prediction->GetLimitedRatio(prediction->ChGenZllPtAccRecoed->hZJetsToLL,prediction->ChGenZllPtAcc->hZJetsToLL,
				                                fZllRecoEffFitMin, fZllRecoEffFitMax, true, fZllRecoEffRelErr);
			f_lin->SetParameter(0,fZllRecoEff);
		}
  		const int nBins= 3;
		const double Bins[nBins+1] = {150, fZllRecoEffFitMin>150?fZllRecoEffFitMin:150.001, fZllRecoEffFitMax<800? fZllRecoEffFitMax:799.99, 800};
		TH1D* hErrorbar = new TH1D(rationame.Data(), "", nBins,Bins);
		hErrorbar->SetBinContent(2,fZllRecoEff);
		hErrorbar->SetBinError(2,fZllRecoEffRelErr*fZllRecoEff);
		hErrorbar->SetBinContent(1,-1);
		hErrorbar->SetBinError(1,0);
		hErrorbar->SetFillColor(5);
		hErrorbar->SetFillStyle(3001);
		hErrorbar->Draw("e2same");
		f_lin->Draw("same");
		hZllRecoEff->Draw("EX0same");
	}
	
	// Photons Hadronic Search MT2
	if(fDoPhotonMT2Shape){
	prediction->ChPhotonsMT2 = new Channel("PhotonsMT2", "photon[0].lv.Pt()", cutStreamPhotonMT2.str().c_str(), fTriggerStream.str().c_str(),fSamplesPhotonPt);
	prediction->ChPhotonsMT2->fVerbose =prediction->fVerbose;
	prediction->ChPhotonsMT2->GetShapes("PhotonsMT2", "MET", 40, 0, 800);
	}

	// Znunu Hadronic Search MT2
	if(fDoZnunuMT2Shape){
	prediction->ChZnunuMT2 = new Channel("ZnunuMT2", "misc.MET", cutStreamZnunuMT2.str().c_str(), fTriggerStream.str().c_str(),fSamplesZnunu);
	prediction->ChZnunuMT2->fVerbose =prediction->fVerbose;
	prediction->ChZnunuMT2->GetShapes("ZnunuMT2", "MET", 40, 0, 800);
	}

	if(fDoZnunuMT2Shape && fDoPhotonMT2Shape){
	TH1D* ZnunuToPhotonMT2Ratio = prediction->GetRatio(prediction->ChZnunuMT2->hZJetsToNuNu, prediction->ChPhotonsMT2->hPhotons, 1);
	DrawHisto(ZnunuToPhotonMT2Ratio,ZnunuToPhotonMT2Ratio->GetName(),"EX0");
	}


	
	// Do Pt spectra comparison plot
	if(fDoPtSpectraComparison && fDoPhotonPtShape && fDoZllPtShape){
		*fLogStream<< "************************* produce pr spectra plot ****************************** " << endl;
		TH1D* hZllMC_cp      = prediction->GetScaledHisto(prediction->ChZllPt->hZJetsToLL, fDoPtSpectraComparisonScaling?(prediction->ChZllPt->hData->Integral())/(prediction->ChZllPt->hZJetsToLL->Integral())    :1, 0, 1);
		TH1D* hZllData_cp    = prediction->GetScaledHisto(prediction->ChZllPt->hData,    1, 0, 1) ;
		TH1D* hPhotonMC_cp   = prediction->GetScaledHisto(prediction->ChPhotonPt->hPhotons,fDoPtSpectraComparisonScaling?(prediction->ChPhotonPt->hData->Integral())/(prediction->ChPhotonPt->hPhotons->Integral()):1, 0, 1);
		TH1D* hPhotonData_cp = prediction->GetScaledHisto(prediction->ChPhotonPt->hData,    1, 0, 1);

		if(fDoPtSpectraComparisonAccCorr){
			TFile *f = new TFile("../RootMacros/ZllAcceptance.root", "OPEN");
			TH1D*  hZllAcc = (TH1D*) f->Get("ZJetsToLL_GenZllPtAcc_ZJetsToLL_GenZllPt_Ratio");
			if (hZllAcc==0) {cout << "WARNING: could not get histo ZJetsToLL_GenZllPtAcc_ZJetsToLL_GenZllPt_Ratio" << endl; exit(1);}
			for(int i=1; i<=hZllMC_cp->GetNbinsX(); ++i){
				if(hZllAcc->GetBinLowEdge(i) != hZllMC_cp->GetBinLowEdge(i)) {cout << "Zll Acc Correction: binnin does not match!!" << endl; exit(1);}
				if(hZllMC_cp  ->GetBinContent(i)<=0) continue;
				double acc_eff   = hZllAcc->GetBinContent(i);
				double orig_mc   = hZllMC_cp     ->GetBinContent(i);
				double orig_data = hZllData_cp   ->GetBinContent(i);
				cout << "bin i " << i << " acc eff " << acc_eff << " orig_mc " << orig_mc << " become " << orig_mc/acc_eff 
				     << " orig_data " << orig_data << " becomes " << orig_data/acc_eff << endl;
				hZllMC_cp   ->SetBinContent(i, orig_mc  /acc_eff);
				hZllData_cp ->SetBinContent(i, orig_data/acc_eff);
			}
			delete f;
		}
		
		hZllMC_cp->SetMarkerStyle(22);
		hZllMC_cp->SetLineColor(kOrange);
		hZllMC_cp->SetMarkerColor(kOrange);
		hZllMC_cp->SetMarkerSize(1.2);
		hZllData_cp->SetMarkerStyle(26);
		hZllData_cp->SetMarkerColor(kBlack);
		hZllData_cp->SetLineColor(kBlack);
		hPhotonMC_cp->SetLineColor(kMagenta+2);
		hPhotonMC_cp->SetMarkerColor(kMagenta+2);
		hPhotonMC_cp->SetMarkerStyle(20);
		hPhotonMC_cp->SetMarkerSize(1.2);
		hPhotonData_cp->SetMarkerStyle(4);
		hPhotonData_cp->SetMarkerColor(kBlack);
		hPhotonData_cp->SetLineColor(kBlack);

		TCanvas *col = new TCanvas("ZllToGammaPtSpectra", "", 0, 0, 500, 500);
		col->SetFillStyle(0);
		col->SetFrameFillStyle(0);
//		col->cd();
		gPad->SetFillStyle(0);
		gStyle->SetPalette(1);
		gPad->SetRightMargin(0.15);

		TLegend* leg2 = new TLegend(0.2, 0.6, 0.5, 0.9);	
		leg2->AddEntry(hPhotonMC_cp,"Gamma+Jets MC","p" );
		leg2->AddEntry(hPhotonData_cp,"Photon Data","p" );
		leg2->AddEntry(hZllMC_cp ,"Zll MC","p" );
		leg2->AddEntry(hZllData_cp,"Zll Data","p" );
		leg2 -> SetFillColor(0);
		leg2 -> SetBorderSize(0);
	//	
		hPhotonMC_cp->SetXTitle("V boson p_{T} (GeV)");
		hPhotonMC_cp->SetYTitle("Events / 7 GeV");
		hPhotonMC_cp->Draw("EX");
		hPhotonData_cp->Draw("EXsame");
		hZllMC_cp->Draw("EXsame");
		hZllData_cp->Draw("EXsame");
		leg2->Draw();
	
		TCanvas *c3 = new TCanvas("ZllToGammaPtSpectraRatio", "", 500, 500);
		TH1D* h_ratio         = (TH1D*) hZllMC_cp      ->Clone("h_ratio");	
		TH1D* h_ratioData     = (TH1D*) hZllData_cp    ->Clone("h_ratioData");	
		TH1D* hPhotonMC_cp2   = (TH1D*) hPhotonMC_cp   ->Clone("hPhotonMC_cp2");
		TH1D* hPhotonData_cp2 = (TH1D*) hPhotonData_cp ->Clone("hPhotonData_cp2");
		h_ratio->Rebin(1); h_ratioData->Rebin(1);
		h_ratio->SetYTitle("#frac{Z(ll)}{#gamma}");
		h_ratio->SetXTitle("boson p_{T} (GeV)");
		h_ratio    ->Divide(hPhotonMC_cp2->Rebin(1));
		h_ratioData->Divide(hPhotonData_cp2->Rebin(1));
		h_ratio    ->SetMarkerStyle(20);
		h_ratio    ->SetMarkerSize(1.2);
		h_ratio    ->SetLineColor(kMagenta+2);
		h_ratio    ->SetMarkerColor(kMagenta+2);
		h_ratioData->SetMarkerStyle(26);
		h_ratioData->SetMarkerColor(kBlack);
		h_ratio    ->Draw("EX0");
		h_ratioData->Draw("EX0same");
		
		TLegend* leg3 = new TLegend(0.2, 0.6, 0.5, 0.9);	
		leg3->AddEntry(h_ratioData,"Zll/photon Data","p" );
		leg3->AddEntry(h_ratio    ,"Zll/photon MC","p" );
		leg3 -> SetFillColor(0);
		leg3 -> SetBorderSize(0);
		leg3 ->Draw();
	}

	if(fDoMT2SpectraCompaison && fDoZnunuMT2Shape && fDoPhotonMT2Shape){
		*fLogStream<<  "************************* MT2 spectra comparison ***************  " << endl;
		TH1D* hZNunuMT2      = prediction->GetScaledHisto(prediction->ChZnunuMT2   ->hZJetsToNuNu, fDoMT2SpectraCompaisonScaling?(prediction->ChPhotonsMT2 ->hData->Integral())/(prediction->ChPhotonsMT2 ->hPhotons->Integral()):1, 0, 1);
		TH1D* hPhotonMT2     = prediction->GetScaledHisto(prediction->ChPhotonsMT2 ->hPhotons,     fDoMT2SpectraCompaisonScaling?(prediction->ChPhotonsMT2 ->hData->Integral())/(prediction->ChPhotonsMT2 ->hPhotons->Integral()):1, 0, 1);
		TH1D* hPhotonDataMT2 = prediction->GetScaledHisto(prediction->ChPhotonsMT2 ->hData, 1, 0, 1);
		
		hZNunuMT2->SetFillStyle(0);
		hZNunuMT2->SetLineWidth(3);

		TCanvas *col = new TCanvas("ZnunuToGammaPtSpectra", "", 0, 0, 500, 500);
		col->SetFillStyle(0);
		col->SetFrameFillStyle(0);
//		col->cd();
		gPad->SetFillStyle(0);
		gStyle->SetPalette(1);
		gPad->SetRightMargin(0.15);
		gPad->SetLogy(1);

		TLegend* leg2 = new TLegend(0.2, 0.6, 0.5, 0.9);	
		leg2->AddEntry(hPhotonMT2,"#gamma+jets MC","f" );
		leg2->AddEntry(hZNunuMT2,"Z(#nu#nu)+jets MC","l" );
		leg2->AddEntry(hPhotonDataMT2,"data","p" );
		leg2 -> SetFillColor(0);
		leg2 -> SetBorderSize(0);
	//	
		hPhotonMT2->SetXTitle("min #Delta #phi(jets,MET)");
		hPhotonMT2->SetYTitle("Events");
		hPhotonMT2->Draw("hist");
		hZNunuMT2->Draw("histsame");
		hPhotonDataMT2->Draw("EXsame");
		leg2->Draw();
//		gPad->RedrawAxis();
		// cout integral above 250 in MT2 and ratio
//		double sumPhotons=0;
//		double sumZnunu  =0;
//		for(int i=1;  i<=hPhotonMT2->GetNbinsX(); ++i){
//			if(hPhotonMT2->GetBinLowEdge(i)>=250){
//				sumPhotons+=hPhotonMT2->GetBinContent(i);
//				sumZnunu  +=hZNunuMT2 ->GetBinContent(i);
//			}
//		}
//		*fLogStream<< ">>> hPhotonMT2: integral above 250: " << sumPhotons << endl;
//		*fLogStream<< ">>> hZNunuMT2 : integral above 250: " << sumZnunu   << endl;
//		*fLogStream<< ">>> -> Ratio  : "                     << sumZnunu/sumPhotons << endl;
		
	}

	if(fDoZnunuGammaGenPtSpectraComparison){
		*fLogStream<< "*************************ZnunuGammaGenPtSpectraComparison**********" << endl;
		// gen photons
		prediction->ChGenPhotonPt = new Channel("GenPhotonPt", "GenPhoton[0].Pt()", cutStreamGenPhoton.str().c_str(), fTriggerStream.str().c_str(),fSamplesPhotonPtMConly);
		prediction->ChGenPhotonPt->fVerbose =prediction->fVerbose;
		prediction->ChGenPhotonPt->GetShapes("GenPhotonPt", "Gen-level #gamma Pt", 50, 150, 800);
		
		// Gen Znunu
		prediction->ChGenZnunuPt = new Channel("GenZnunuPt", "GenZ[0].Pt()", cutStreamGenZnunu.str().c_str(), fTriggerStream.str().c_str(),fSamplesZnunu);
		prediction->ChGenZnunuPt->fVerbose =prediction->fVerbose;
		prediction->ChGenZnunuPt->GetShapes("GenZnunuPt", "Gen-level Z(#nu#nu) Pt", 50, 150, 800);
		
		prediction->DrawHistos(prediction->ChGenPhotonPt->hPhotons, prediction->ChGenZnunuPt->hZJetsToNuNu,
				       "EX0"                              , "EX0same",
				       kViolet+3                          , kBlack,
				       20                                 ,4,
				       "#gamma Pt"                        ,"Z(#nu#nu)");

		TH1D* hGenPhotonToZnunuRatio = prediction->GetRatio(prediction->ChGenZnunuPt->hZJetsToNuNu, prediction->ChGenPhotonPt->hPhotons, 1, false);
		hGenPhotonToZnunuRatio->SetMarkerColor(kBlack);
		hGenPhotonToZnunuRatio->SetLineColor(kBlack);
		hGenPhotonToZnunuRatio->SetMarkerStyle(4);
		DrawHisto(hGenPhotonToZnunuRatio, "GenPhotonToZnunuRatio","EX0", prediction->ChGenPhotonPt);
	}

	if(fDoPhotonRecoEff){
		prediction->ChGenPhotonPtForRecoEff = new Channel("GenPhotonPtForRecoEff", "GenPhoton[0].Pt()", cutStream_GenPhotonforRecoEff.str().c_str(), fTriggerStream.str().c_str(),fSamplesPhotonPtMConly);
		prediction->ChGenPhotonPtForRecoEff->fVerbose =prediction->fVerbose;
		prediction->ChGenPhotonPtForRecoEff->GetShapes("GenPhotonPtForRecoEff", "Gen-level #gamma Pt", 50, 150, 800);
		
		prediction->ChPhotonPtForRecoEff = new Channel("PhotonPtForRecoEff", "GenPhoton[0].Pt()", cutStream_PhotonPtforRecoEff.str().c_str(), fTriggerStream.str().c_str(),fSamplesPhotonPtMConly);
		prediction->ChPhotonPtForRecoEff->fVerbose =prediction->fVerbose;
		prediction->ChPhotonPtForRecoEff->GetShapes("PhotonPtForRecoEff", "Gen-level #gamma Pt", 50, 150, 800);
		
		prediction->DrawHistos(prediction->ChGenPhotonPtForRecoEff->hPhotons, prediction->ChPhotonPtForRecoEff->hPhotons,
				       "EX0"                              , "EX0same",
				       kViolet+3                          , kBlack,
				       20                                 ,4,
				       "#all"                             ,"recoed");
		TH1D* hPhotonRecoEff = prediction->GetRatio(prediction->ChPhotonPtForRecoEff->hPhotons, prediction->ChGenPhotonPtForRecoEff->hPhotons, 1, false);
		hPhotonRecoEff->SetMarkerColor(kBlack);
		hPhotonRecoEff->SetLineColor(kBlack);
		hPhotonRecoEff->SetMarkerStyle(4);
		DrawHisto(hPhotonRecoEff, "PhotonRecoEff","EX0", prediction->ChPhotonPtForRecoEff);
	}

	// Prediction
	if(fDoPrediction){
		*fLogStream<< "************************* Prediction ****************************** " << endl;

		TH1D* MCZnunu = prediction->GetScaledHisto(prediction->ChZnunuMT2->hZJetsToNuNu,fLumiCorr,0);  // scale to lumi 4400
		double MCZnunuEst    = MCZnunu->GetBinContent(1);
		double MCZnunuEstErr = MCZnunu->GetBinError(1);
		delete MCZnunu;
		if(fDoData){ 
		double nGamma    = prediction->ChPhotonsMT2->hData->Integral();
		double nGammaErr = sqrt(nGamma);
		*fLogStream << "********** Data Prediction ***************************************************** " << endl;
		MakePrediction(nGamma, nGammaErr, fZllToPhotonRatio, fZllToPhotonRatioRelErr, fZllAccEff, fZllAccEffRelErr, fZllRecoEff, fZllRecoEffRelErr, MCZnunuEst, MCZnunuEstErr);
		}
		TH1D* hDummy =   prediction->GetScaledHisto(prediction->ChPhotonsMT2->hPhotons, 1, 0);
		float nGammaMC   =hDummy->GetBinContent(1);
		float nGammaMCErr=hDummy->GetBinError(1);
		*fLogStream << "********** MC Prediction ***************************************************** " << endl;
		MakePrediction(nGammaMC, nGammaMCErr, fZllToPhotonRatio, fZllToPhotonRatioRelErr, fZllAccEff, fZllAccEffRelErr, fZllRecoEff, fZllRecoEffRelErr, MCZnunuEst, MCZnunuEstErr);
	}

	// write -----------
	if(fWriteToFile){
		TString logname =fOutDir + ".log"; 
		ofstream f_log (logname.Data(), ios::app);
		f_log << fLogStream->str();
	} else{
		cout << fLogStream->str();
	}

//	fOutFile->Close();

}
Пример #9
0
TF1* fit(Double_t ptmin, Double_t ptmax)
{
  TCanvas* c = new TCanvas(Form("c_%.0f_%.0f",ptmin,ptmax),"",600,600);
  TFile* infile = new TFile(Form("%s_%s_%.0f_%.0f.root",infname.Data(),collisionsystem.Data(),ptmin,ptmax));
  TH1D* h = (TH1D*)infile->Get("h");                    h->SetName(Form("h_%.0f_%.0f",ptmin,ptmax));
  TH1D* hMCSignal = (TH1D*)infile->Get("hMCSignal");    hMCSignal->SetName(Form("hMCSignal_%.0f_%.0f",ptmin,ptmax));
  TH1D* hMCSwapped = (TH1D*)infile->Get("hMCSwapped");  hMCSwapped->SetName(Form("hMCSwapped_%.0f_%.0f",ptmin,ptmax));
  TF1* f = new TF1(Form("f_%.0f_%.0f",ptmin,ptmax),"[0]*([7]*([9]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[9])*Gaus(x,[1],[10])/(sqrt(2*3.14159)*[10]))+(1-[7])*Gaus(x,[1],[8])/(sqrt(2*3.14159)*[8]))+[3]*exp([4]*x)", 1.7, 2.0);

  f->SetParLimits(10,0.001,0.05);
  f->SetParLimits(2,0.01,0.1);
  f->SetParLimits(8,0.02,0.2);
  f->SetParLimits(7,0,1);
  f->SetParLimits(9,0,1);
  
  f->SetParameter(0,setparam0);
  f->SetParameter(1,setparam1);
  f->SetParameter(2,setparam2);
  f->SetParameter(10,setparam10);
  f->SetParameter(9,setparam9);

  f->FixParameter(8,setparam8);
  f->FixParameter(7,1);
  f->FixParameter(1,fixparam1);
  f->FixParameter(3,0);
  f->FixParameter(4,0);
  h->GetEntries();
  
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSignal->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L m","",minhisto,maxhisto);
  
  f->FixParameter(1,f->GetParameter(1));
  f->FixParameter(2,f->GetParameter(2));
  f->FixParameter(10,f->GetParameter(10));
  f->FixParameter(9,f->GetParameter(9));
  f->FixParameter(7,0);
  f->ReleaseParameter(8);
  f->SetParameter(8,setparam8);
  
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  hMCSwapped->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L m","",minhisto,maxhisto);
  
  f->SetParLimits(0,0,1.e+6);
  f->FixParameter(7,hMCSignal->Integral(0,1000)/(hMCSwapped->Integral(0,1000)+hMCSignal->Integral(0,1000)));
  f->FixParameter(8,f->GetParameter(8));
  f->ReleaseParameter(3);
  f->ReleaseParameter(4);
  f->SetParLimits(3,0,1.e+10);
  f->SetParameter(3,1.e+3);

  f->SetLineColor(kRed);
  
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"q","",minhisto,maxhisto);
  f->ReleaseParameter(1);
  f->SetParLimits(1,1.85,1.90);
  //f->ReleaseParameter(2);                                     // you need to release these two parameters if you want to perform studies on the sigma shape
  //f->ReleaseParameter(10);                                   // you need to release these two parameters if you want to perform studies on the sigma shape
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L q","",minhisto,maxhisto);
  h->Fit(Form("f_%.0f_%.0f",ptmin,ptmax),"L m","",minhisto,maxhisto);
  
  TF1* background = new TF1(Form("background_%.0f_%.0f",ptmin,ptmax),"[0]*exp([1]*x)");
  background->SetParameter(0,f->GetParameter(3));
  background->SetParameter(1,f->GetParameter(4));
  background->SetLineColor(4);
  background->SetRange(minhisto,maxhisto);
  background->SetLineStyle(2);
  
  TF1* mass = new TF1(Form("fmass_%.0f_%.0f",ptmin,ptmax),"[0]*([3]*([4]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[4])*Gaus(x,[1],[5])/(sqrt(2*3.14159)*[5])))");
  mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(7),f->GetParameter(9),f->GetParameter(10));
  mass->SetParError(0,f->GetParError(0));
  mass->SetParError(1,f->GetParError(1));
  mass->SetParError(2,f->GetParError(2));
  mass->SetParError(3,f->GetParError(7));
  mass->SetParError(4,f->GetParError(9));
  mass->SetParError(5,f->GetParError(10));
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);
  
  TF1* massSwap = new TF1(Form("fmassSwap_%.0f_%.0f",ptmin,ptmax),"[0]*(1-[2])*Gaus(x,[1],[3])/(sqrt(2*3.14159)*[3])");
  massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(7),f->GetParameter(8));
  massSwap->SetParError(0,f->GetParError(0));
  massSwap->SetParError(1,f->GetParError(1));
  massSwap->SetParError(2,f->GetParError(7));
  massSwap->SetParError(3,f->GetParError(8));
  massSwap->SetFillColor(kGreen+4);
  massSwap->SetFillStyle(3005);
  massSwap->SetLineColor(kGreen+4);
  massSwap->SetLineWidth(3);
  massSwap->SetLineStyle(1);
  
  h->SetXTitle("m_{#piK} (GeV/c^{2})");
  h->SetYTitle("Entries / (5 MeV/c^{2})");
  h->GetXaxis()->CenterTitle();
  h->GetYaxis()->CenterTitle();
  h->SetAxisRange(0,h->GetMaximum()*1.4*1.2,"Y");
  h->GetXaxis()->SetTitleOffset(1.3);
  h->GetYaxis()->SetTitleOffset(1.8);
  h->GetXaxis()->SetLabelOffset(0.007);
  h->GetYaxis()->SetLabelOffset(0.007);
  h->GetXaxis()->SetTitleSize(0.045);
  h->GetYaxis()->SetTitleSize(0.045);
  h->GetXaxis()->SetTitleFont(42);
  h->GetYaxis()->SetTitleFont(42);
  h->GetXaxis()->SetLabelFont(42);
  h->GetYaxis()->SetLabelFont(42);
  h->GetXaxis()->SetLabelSize(0.04);
  h->GetYaxis()->SetLabelSize(0.04);
  h->SetMarkerSize(0.8);
  h->SetMarkerStyle(20);
  h->SetStats(0);
  h->Draw("e");

  background->Draw("same");   
  mass->SetRange(minhisto,maxhisto);	
  mass->Draw("same");
  massSwap->SetRange(minhisto,maxhisto);
  massSwap->Draw("same");
  f->Draw("same");
  
  Double_t yield = mass->Integral(minhisto,maxhisto)/binwidthmass;
  Double_t yieldErr = mass->Integral(minhisto,maxhisto)/binwidthmass*mass->GetParError(0)/mass->GetParameter(0);
  
  std::cout<<"YIELD="<<yield<<std::endl;

  TLegend* leg = new TLegend(0.65,0.58,0.82,0.88,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.04);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry(h,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"D^{0}+#bar{D^{#lower[0.2]{0}}} Signal","f");
  leg->AddEntry(massSwap,"K-#pi swapped","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->Draw("same");

  TLatex* texCms = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  texCms->SetNDC();
  texCms->SetTextAlign(12);
  texCms->SetTextSize(0.04);
  texCms->SetTextFont(42);
  texCms->Draw();

  TLatex* texCol = new TLatex(0.96,0.93, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));
  texCol->SetNDC();
  texCol->SetTextAlign(32);
  texCol->SetTextSize(0.04);
  texCol->SetTextFont(42);
  texCol->Draw();

  TLatex* texPt = new TLatex(0.22,0.78,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax));
  texPt->SetNDC();
  texPt->SetTextFont(42);
  texPt->SetTextSize(0.04);
  texPt->SetLineWidth(2);
  texPt->Draw();

  TLatex* texY = new TLatex(0.22,0.83,"|y| < 1.0");
  texY->SetNDC();
  texY->SetTextFont(42);
  texY->SetTextSize(0.04);
  texY->SetLineWidth(2);
  texY->Draw();

  TLatex* texYield = new TLatex(0.22,0.73,Form("N_{D} = %.0f #pm %.0f",yield,yieldErr));
  texYield->SetNDC();
  texYield->SetTextFont(42);
  texYield->SetTextSize(0.04);
  texYield->SetLineWidth(2);
  texYield->Draw();

  c->SaveAs(Form("plotFits/DMass_expo_%s_%.0f_%.0f.pdf",collisionsystem.Data(),ptmin,ptmax));
  
  TCanvas* cPull = new TCanvas(Form("cPull_%.0f_%.0f",ptmin,ptmax),"",600,700);
  TH1D* hPull = (TH1D*)h->Clone("hPull");
  for(int i=0;i<h->GetNbinsX();i++)
    {
      Double_t nfit = f->Integral(h->GetBinLowEdge(i+1),h->GetBinLowEdge(i+1)+h->GetBinWidth(i+1))/h->GetBinWidth(i+1);
      hPull->SetBinContent(i+1,(h->GetBinContent(i+1)-nfit)/h->GetBinError(i+1));
      hPull->SetBinError(i+1,0);
    }
  hPull->SetMinimum(-4.);
  hPull->SetMaximum(4.);
  hPull->SetYTitle("Pull");
  hPull->GetXaxis()->SetTitleOffset(1.);
  hPull->GetYaxis()->SetTitleOffset(0.65);
  hPull->GetXaxis()->SetLabelOffset(0.007);
  hPull->GetYaxis()->SetLabelOffset(0.007);
  hPull->GetXaxis()->SetTitleSize(0.12);
  hPull->GetYaxis()->SetTitleSize(0.12);
  hPull->GetXaxis()->SetLabelSize(0.1);
  hPull->GetYaxis()->SetLabelSize(0.1);
  hPull->GetYaxis()->SetNdivisions(504);
  TLine* lPull = new TLine(1.7, 0, 2., 0);
  lPull->SetLineWidth(1);
  lPull->SetLineStyle(7);
  lPull->SetLineColor(1);
  TPad* pFit = new TPad("pFit","",0,0.3,1,1);
  pFit->SetBottomMargin(0);
  pFit->Draw();
  pFit->cd();
  h->Draw("e");
  background->Draw("same");
  mass->Draw("same");
  massSwap->Draw("same");
  f->Draw("same");
  leg->Draw("same");
  texCms->Draw();
  texCol->Draw();
  texPt->Draw();
  texY->Draw();
  texYield->Draw();
  cPull->cd();
  TPad* pPull = new TPad("pPull","",0,0,1,0.3);
  pPull->SetTopMargin(0);
  pPull->SetBottomMargin(0.3);
  pPull->Draw();
  pPull->cd();
  hPull->Draw("p");
  lPull->Draw();
  cPull->cd();
  cPull->SaveAs(Form("plotFits/DMass_expo_%s_%.0f_%.0f_Pull.pdf",collisionsystem.Data(),ptmin,ptmax));

  return mass;
}
Пример #10
0
void plotAnaMult4(char *infname="ana.root")
{    
   TFile *inf = new TFile(infname);
   
   TTree *tData = (TTree*) inf->Get("Data_tree");
   TTree *tMC   = (TTree*) inf->Get("MC_tree");
   TTree *tPP   = (TTree*) inf->Get("PP_tree");

   TCanvas *c1 = new TCanvas("c","",1200,700);
//   c->Divide(4,1);
   TCut recoCut = "leadingJetPt>120&&subleadingJetPt>50&&dphi>5*3.14159265358979/6.&&abs(leadingJetEta)<1.6&&abs(subleadingJetEta)<1.6";
   TCut genCut = "genleadingJetPt>120&&gensubleadingJetPt>50&&genDphi>5*3.14159265358979/6.&&abs(genleadingJetEta)<1.6&&abs(gensubleadingJetEta)<1.6";

   
   const int nPtBin=5;
   Float_t PtBins[nPtBin+1] = {0.001,0.5,1,1.5,2,3.2};
   
   Int_t centBin[5] = {200,100,60,20,0};
   makeMultiPanelCanvas(c1,4,2,0.0,0.0,0.2,0.2,0.02);
   
   for (int i=0;i<4;i++) {
      c1->cd(i+1);
      TH1D * empty=new TH1D("empty","",100,0,3.19);
//      empty->Fill(0.5,1000); 
      empty->SetMaximum(39.99); 
      empty->SetMinimum(0.001); 
      empty->SetNdivisions(105,"X");
      empty->GetXaxis()->SetTitleSize(28);
      empty->GetXaxis()->SetTitleFont(43); 
      empty->GetXaxis()->SetTitleOffset(1.8);
      empty->GetXaxis()->SetLabelSize(22);
      empty->GetXaxis()->SetLabelFont(43);
      empty->GetYaxis()->SetTitleSize(28);
      empty->GetYaxis()->SetTitleFont(43); 
      empty->GetYaxis()->SetTitleOffset(1.8);
      empty->GetYaxis()->SetLabelSize(22);
      empty->GetYaxis()->SetLabelFont(43);
      empty->GetXaxis()->CenterTitle();
      empty->GetYaxis()->CenterTitle();

      empty->SetXTitle("#Delta#eta_{1,2}");
      empty->SetYTitle("Multiplicity Difference");
   
      TProfile *pData = new TProfile(Form("pData%d",i),"",nPtBin,PtBins);
      TProfile *pMC = new TProfile(Form("pMC%d",i),"",nPtBin,PtBins);
      TProfile *pPP = new TProfile(Form("pPP%d",i),"",nPtBin,PtBins);
      TProfile *pGen = new TProfile(Form("pGen%d",i),"",nPtBin,PtBins);
      TCut centCut = Form("hiBin>=%d&&hiBin<%d",centBin[i+1],centBin[i]);
      tData->Draw(Form("-multDiff:abs(leadingJetEta-subleadingJetEta)>>pData%d",i),recoCut&&centCut);
      tPP->Draw(Form("-multDiff:abs(leadingJetEta-subleadingJetEta)>>pPP%d",i),recoCut);
      tMC->Draw(Form("-multDiff:abs(leadingJetEta-subleadingJetEta)>>pMC%d",i),recoCut&&centCut);  
      tMC->Draw(Form("-genMultDiff:abs(genleadingJetEta-gensubleadingJetEta)>>pGen%d",i),genCut&&centCut);  

      pMC->SetLineColor(2);
      pMC->SetMarkerColor(2);
      pPP->SetLineColor(4);
      pPP->SetMarkerColor(4);
      
//      pData->SetAxisRange(0,50,"Y");
//      pData->SetAxisRange(0,0.49,"X");
      empty->Draw();

      double diff=0;
      if (i==0) diff=0.1;
      drawText(Form("%d-%d %%",(int)(0.5*centBin[i+1]),(int)(0.5*centBin[i])),0.22+diff,0.65);
      if (i==0) drawText("PbPb #sqrt{s_{NN}}=2.76 TeV 150/#mub",0.22+diff,0.85);
      if (i==0) drawText("pp      #sqrt{s_{NN}}=2.76 TeV 5.3/pb",0.22+diff,0.75);
      if (i==3) drawText("CMS Preliminary",0.3+diff,0.85);
            
      Float_t sys[4]={1,1,2.5,3};
      

      for (int j=1;j<=pData->GetNbinsX();j++)
      {
         TBox *b = new TBox(pData->GetBinLowEdge(j),pData->GetBinContent(j)-sys[i],pData->GetBinLowEdge(j+1),pData->GetBinContent(j)+sys[i]);
	 //b->SetFillColor(kGray);
	 b->SetFillStyle(0);
	 b->SetLineColor(1);
	 b->Draw();
         TBox *b2 = new TBox(pPP->GetBinLowEdge(j),pPP->GetBinContent(j)-1,pPP->GetBinLowEdge(j+1),pPP->GetBinContent(j)+1);
	 //b2->SetFillColor(65);
	 b2->SetFillStyle(0);
	 b2->SetLineColor(4);
	 b2->Draw();
      }
      pData->Draw("same");
      pMC->Draw("same");
      pPP->Draw("same");
      pGen->SetMarkerColor(4);
      pGen->SetMarkerStyle(24);
      pData->Draw("same");
      
//      pGen->Draw(" same");

      c1->cd(5+i);
      TH1D *empty2 = (TH1D*)empty->Clone("empty2");
      empty2->SetYTitle("PbPb - pp");
      empty2->SetMinimum(-5);
      empty2->SetMaximum(+29.99);
      empty2->Draw();
//      TProfile *pDiff = (TProfile*)pData->Clone("pDiff");
      TH1D *pDiff = new TH1D("pDiff","",nPtBin,PtBins);
      
      for (int j=1;j<=pData->GetNbinsX();j++)
      {
	 pDiff->SetBinContent(j,pData->GetBinContent(j)-pPP->GetBinContent(j));
  	 pDiff->SetBinError(j,sqrt(pData->GetBinError(j)*pData->GetBinError(j)+pPP->GetBinError(j)*pPP->GetBinError(j)));
         TBox *b = new TBox(pDiff->GetBinLowEdge(j),pDiff->GetBinContent(j)-sys[i],pDiff->GetBinLowEdge(j+1),pDiff->GetBinContent(j)+sys[i]);
         TBox *b2 = new TBox(pDiff->GetBinLowEdge(j),pDiff->GetBinContent(j)-sys[i],pDiff->GetBinLowEdge(j+1),pDiff->GetBinContent(j)+sys[i]);
         b->SetFillColor(TColor::GetColor("#FFEE00"));
	 b2->SetLineColor(1);
	 b2->SetFillStyle(0);
	 b->Draw();
	 b2->Draw();
      }
      
      pDiff->Draw("p same");


      TLegend *leg = new TLegend(0.3,0.6,0.9,0.9);
      leg->SetFillStyle(0);
      leg->SetBorderSize(0);
      leg->AddEntry(pData,"PbPb","pl");
      leg->AddEntry(pPP,"pp","pl");
      leg->AddEntry(pMC,"PYTHIA+HYDJET","pl");
      if (i==0) leg->Draw();

      if (i==1) drawText("p_{T,1} > 120 GeV/c",0.22+diff,0.85);
      if (i==1) drawText("p_{T,2} >  50 GeV/c",0.22+diff,0.75);
      if (i==1) drawText("#Delta#phi_{1,2} > 5#pi/6",0.22+diff,0.65);

   }
/*
   TCanvas *c1 = new TCanvas("c1","",(ncent+1)*300,700);
   makeMultiPanelCanvas(c1,ncent+1,2,0.0,0.0,0.2,0.2,0.02);
   TH1D * empty=new TH1D("empty",Form(";%s;<#slash{p}_{T}^{#parallel}> (GeV)",axistitle[index_var].Data()),nalpha/2+1,frac);
   TH1D * empty2=new TH1D("empty2",Form(";%s;<#slash{p}_{T}^{#parallel}> (GeV)",axistitle[index_var].Data()),nalpha/2+1,frac);
   empty->Fill(0.5,1000); 
   empty2->Fill(0.5,1000);   
   if(doIntegrate){
      if(index_var==0){
         empty->SetMaximum(30); 
         empty->SetMinimum(-70); 
      }else{
         empty->SetMaximum(35); 
         empty->SetMinimum(-45); 
      }
   }else{
      empty->SetMaximum(15); 
      empty->SetMinimum(-10); 
      empty2->SetMaximum(15); 
      empty2->SetMinimum(-10); 
   }
   empty->GetXaxis()->SetTitleSize(28);
   empty->GetXaxis()->SetTitleFont(43); 
   empty->GetXaxis()->SetTitleOffset(2.2);
   empty->GetXaxis()->SetLabelSize(22);
   empty->GetXaxis()->SetLabelFont(43);
   empty->GetYaxis()->SetTitleSize(28);
   empty->GetYaxis()->SetTitleFont(43); 
   empty->GetYaxis()->SetTitleOffset(2.2);
   empty->GetYaxis()->SetLabelSize(22);
   empty->GetYaxis()->SetLabelFont(43);
   empty2->GetXaxis()->SetTitleSize(28);
   empty2->GetXaxis()->SetTitleFont(43); 
   empty2->GetXaxis()->SetTitleOffset(2.2);
   empty2->GetXaxis()->SetLabelSize(22);
   empty2->GetXaxis()->SetLabelFont(43);
   empty2->GetYaxis()->SetTitleSize(28);
   empty2->GetYaxis()->SetTitleFont(43); 
   empty2->GetYaxis()->SetTitleOffset(2.2);
   empty2->GetYaxis()->SetLabelSize(22);
   empty2->GetYaxis()->SetLabelFont(43);
   
   
   c1->cd(ncent+2); 
*/

   c1->SaveAs("results/MultiplicityDifference-DeltaEta.C");
   c1->SaveAs("results/MultiplicityDifference-DeltaEta.gif");
   c1->SaveAs("results/MultiplicityDifference-DeltaEta.eps");
   c1->SaveAs("results/MultiplicityDifference-DeltaEta.pdf");


}
Пример #11
0
void compare_emu(std::string mcfile1, std::string mcfile2, 
		std::string var1, std::string var2="",
		float xmin=-9999.0, float xmax=-9999.0,
		std::string output="test",
		std::string header="Before unfolding",
		std::string mcName1="e",
		std::string mcName2="#mu",
		bool logScale=false
		)
{
  
  setTDRStyle();
  gStyle->SetOptStat(0);

  TH1F* h1;
  TH1F* h2;

  char tempName[300];
  if(var2 ==  "" )var2=var1;
  
  // first get the histogram files
  TFile *fmc1 = TFile::Open(mcfile1.data());
  TFile *fmc2   = TFile::Open(mcfile2.data());

  h1  = (TH1F*)(fmc1->Get(var1.data()));
  h2    = (TH1F*)(fmc2->Get(var2.data()));

  TH1D* hscale =(TH1D*) h1->Clone("hscale");
  hscale->SetYTitle(Form("%s/%s",mcName1.data(),mcName2.data()));

  h1->GetXaxis()->SetNdivisions(5);
  h1->GetYaxis()->SetDecimals();

  h2->GetXaxis()->SetNdivisions(5);
  h2->GetYaxis()->SetDecimals();

  hscale->GetXaxis()->SetNdivisions(5);
  hscale->GetYaxis()->SetDecimals();


  h1->SetLineColor(2);
  h1->SetMarkerColor(2);
  h1->SetMarkerSize(1);
  h1->SetMarkerStyle(24);


  h2->SetLineColor(4);
  h2->SetMarkerColor(4);
  h2->SetMarkerSize(1);
  h2->SetMarkerStyle(21);

  // if normalizing to the same area, set the scale 

  int binLo = -1;
  int binHi = -1;
  int nbins = h1->GetNbinsX();
  if(xmin>-9999.0 && xmax>-9999.0)
    {

      binLo = h1->FindBin(xmin);
      binHi = h1->FindBin(xmax)-1;

    }

  else
    {
      binLo = 1;
      binHi = nbins;
      xmin = h1->GetBinLowEdge(1);
      xmax = h1->GetBinLowEdge(nbins+1);
    }



  h1->Sumw2();
  h1->Scale(1.0/h1->Integral(binLo, binHi));

  h2->Sumw2();
  h2->Scale(1.0/h2->Integral(binLo, binHi));

  cout << "h2 integral = " << h2->Integral() << endl;
  cout << "h1 integral = "   << h1->Integral() << endl;;

  // get the ratio
  hscale->Divide(h1, h2, 1,1);
  
  cout << "===========================================================" << endl;
  cout << "Central value " << endl;
  for(int i=1;i<=hscale->GetNbinsX();i++)
    cout << "Bin " << i << " ( " << hscale->GetBinLowEdge(i) << "~" 
	 << hscale->GetBinLowEdge(i+1) << " ): " 
	 << h1->GetBinContent(i) << "/" << h2->GetBinContent(i) << " = " 
	 << hscale->GetBinContent(i) << " +- " << hscale->GetBinError(i) 
	 << endl;

  cout << "Uncertainty " << endl;

  for(int i=1;i<=hscale->GetNbinsX();i++)
    cout << "Bin " << i << " ( " << hscale->GetBinLowEdge(i) << "~" 
	 << hscale->GetBinLowEdge(i+1) << " ): " 
	 << h1->GetBinError(i) << "/" << h2->GetBinError(i) << " = " 
	 << h1->GetBinError(i) / h2->GetBinError(i) 
	 << endl;

  cout << "===========================================================" << endl;

  cout << "Relative uncertainty is " << endl;
  for(int i=1;i<=hscale->GetNbinsX();i++)
    if(hscale->GetBinContent(i)>1e-6)
    cout << "Bin " << i << " ( " << hscale->GetBinLowEdge(i) << "~" 
	 << hscale->GetBinLowEdge(i+1) << " ): " 
	 << hscale->GetBinError(i)/hscale->GetBinContent(i) << endl;


  h1->GetXaxis()->SetRangeUser(xmin,xmax);
  h2->GetXaxis()->SetRangeUser(xmin,xmax);
  hscale->GetXaxis()->SetRangeUser(xmin,xmax);


  TCanvas* c1 = new TCanvas("c1","",700,1000);  
  c1->Divide(1,2,0.01,0);
  c1->cd(1);
  if(logScale)
    gPad->SetLogy(1);
  gPad->SetTopMargin(0.01);
  gPad->SetBottomMargin(0);
  gPad->SetRightMargin(0.04);

  
  float max_data  = h1->GetBinError(h1->GetMaximumBin()) + h1->GetMaximum();
  float max_mc    = h2->GetBinError(h2->GetMaximumBin()) + h2->GetMaximum();

  if(max_data > max_mc)
    {
      h1->Draw("e");
      h2->Draw("hesame");
    }
  else
    { h2->Draw("he");
      h1->Draw("esame");
    }


  float x1NDC = 0.798232;
  float y1NDC = 0.811949;
  float x2NDC = 0.877295;
  float y2NDC = 0.953398;

  TLegend* leg = new TLegend(x1NDC,y1NDC,x2NDC,y2NDC);
  
//   leg->SetHeader(header.data());
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetTextSize(0.06);
  leg->SetBorderSize(0);
  leg->AddEntry(h1, mcName1.data());
  leg->AddEntry(h2, mcName2.data());
  leg->Draw("same");



  c1->cd(2);
  gStyle->SetStatW       (0.3);
  gStyle->SetStatH       (0.3);
  gStyle->SetStatX       (0.879447);
  gStyle->SetStatY       (0.939033);
  gStyle->SetStatFontSize(0.05);
  gStyle->SetStatBorderSize(0);
  gPad->SetRightMargin(0.04);
  gPad->SetTopMargin(0);
  gPad->SetBottomMargin(0.2);
  gPad->SetTickx();
  gStyle->SetOptFit(1);
  hscale->SetTitle("");
  hscale->SetMaximum(1.2);
  hscale->SetMinimum(0.8);
  hscale->SetTitleOffset(1.2,"Y");
  hscale->Draw("e1");
  TF1* fline = new TF1("fline","pol1");
  TLine* l2 = new TLine(xmin,1.,xmax,1.);
  l2->SetLineColor(4);
  l2->SetLineStyle(3);
  fline->SetLineWidth(3);
  fline->SetLineColor(6);
  fline->SetNpx(2500);
//   hscale->Fit("fline","","");
  l2->Draw("same");


  string dirName = "unfolding";
  gSystem->mkdir(dirName.data());

  std::string filename;
  std::string psname = dirName + "/" + var1;
  if(output !="test")
    psname = dirName+ "/" + output;
  else
    psname = dirName+ "/" + var1;
  filename = psname + ".eps";
  c1->Print(filename.data());
  filename = psname + ".gif";
  c1->Print(filename.data());
  filename = psname + ".pdf";
  c1->Print(filename.data());
  //   c1->Close();
}
Пример #12
0
void JetFragAna::Loop()
{
  if (fChain == 0) return;

  Long64_t nentries = fChain->GetEntriesFast();
  Long64_t jetTreeNEntries[10] = {nentries,jetTree_[1]->GetEntries(),0,0,0};
  cout << "==============" << endl;
  cout << " Begin Loop" << endl;
  cout << "Tree: " << nentries << " jetTree: " << jetTreeNEntries[jetTreeMode_] << endl;
  cout << "==============" << endl;

  for (int i=0;i<fileTrackingCorr_.size();++i) {
    cout << fileTrackingCorr_[i]->GetName() << endl;
    for (int j=0;j<trackingCentBin_.size();++j)
    {
      cout << trackingCentBin_[j];
      cout << " Eff: " << trackingEffCorr_[i][j]->GetEntries();
      cout << " Fak: " << trackingFakCorr_[i][j]->GetEntries();
      cout << " Mul: " << trackingMulCorr_[i][j]->GetEntries();
      cout << " Sec: " << trackingSecCorr_[i][j]->GetEntries();
      cout << endl;
    }
  }

  // Random Number
  r3 = new TRandom3(mixOffset_);

  // =====================================================
  // Initialize Counters
  // =====================================================
  numDJ_=0,numDJReWeighted_=0;
  for (Int_t i=0; i<2; ++i) {
    numJ_[i]=0;
    numJReWeighted_[i]=0;
  }
  Int_t numTotEvt=0, numDJNoBkgLimit=0;
  Long64_t nbytes = 0, nb = 0;

  // Pt Bin
  TH1D * hPt = (TH1D*)hPtPDR[0]->ProjectionX();
  Int_t numPtBins = hPt->GetNbinsX();

  // Set Tree Pt bins
  jc_.resizePtBins(numPtBins);

  // =====================================================
  // Centrality ReWeighting
  // =====================================================
  TH1D *hCent = new TH1D("hCent","",40,0,100);
  fChain->Project("hCent","cent",""); // no evt sel, assume centrality distribution of bkg is independent of the signal
  hCent->Scale(1./hCent->GetEntries());   
  // Centrality Weight
  hCentralityWeight_->Divide(hCentralityData_,hCent);
  // ReWeighted Centrality distribution
  TH1D *hCentReWeighted = new TH1D("hCentReWeighted","",40,0,100);

  //=======================================================================================================================
  // Main Loop 
  //=======================================================================================================================
  for (Long64_t jentry=0; jentry<nentries;jentry++) {
    Long64_t ientry = LoadTree(jentry);
    if (jentry%500==0) cout << "jentry: " << jentry << " " << jentry/float(nentries) << endl;
    if (ientry < 0) break;
    nb = GetEntry(jentry);   nbytes += nb;
    GetJetEntry(jetTree_[jetTreeMode_],vj_[jetTreeMode_],(jentry+mixOffset_)%jetTreeNEntries[jetTreeMode_]);
    ++numTotEvt;

    // Clear counters
    jettrk_.clear();
    jc_.clear();

    // =====================================================
    // Main Event Selection
    // =====================================================
    if (!doEvtSel_||(Cut(ientry)>=0&&!GetEvtMask())) {
      ++numDJNoBkgLimit;
      // =====================================================
      // Jet Phase Space Limit (if Bkg Subtraction)
      // =====================================================
      if (cut.BkgSubType=="EtaRefl") {
	if (fabs(anaJets_[0].eta())<cut.ConeSize||fabs(anaJets_[1].eta())<cut.ConeSize) continue;
      }
      if (cut.BkgSubType=="PhiRot") {
	if (fabs(anaJets_[0].eta()-anaJets_[1].eta())<cut.ConeSize*2) continue;
      }
      // If we want to restrict eta for j0,j1 separately
      // Classify events into j0 events or j1 events
      bool jetEvt[2] = { true, true };
      if (cut.BkgSubType=="EtaReflSingle") {
	for (Int_t j=0; j<2; ++j) {
	  if (fabs(anaJets_[j].eta())<cut.ConeSize) jetEvt[j]=false;
	}
      }
      // systematic checks on eta regions
      if (cut.BkgSubType=="EtaReflSingleEtaPos") {
	for (Int_t j=0; j<2; ++j) {
	  if (fabs(anaJets_[j].eta())<cut.ConeSize||anaJets_[j].eta()<0) jetEvt[j]=false;
	}
      }
      if (cut.BkgSubType=="EtaReflSingleEtaNeg") {
	for (Int_t j=0; j<2; ++j) {
	  if (fabs(anaJets_[j].eta())<cut.ConeSize||anaJets_[j].eta()>=0) jetEvt[j]=false;
	}
      }

      // =====================================================
      // Set Centrality Weight
      // =====================================================
      int cBin = hCent->FindBin(cent);
      double weight=1;
      if (doCentralityReweighting_) {
	if (hCentralityData_->GetBinContent(cBin)==0 || hCent->GetBinContent(cBin)==0) {
	  weight = 0; 
	} else {
	  weight = hCentralityWeight_->GetBinContent(cBin);
	}
      }

      // =====================================================
      // Fill Event Level Histograms
      // =====================================================
      hJDPhi->Fill(anaJetDPhi_,weight);
      hAj->Fill((anaJets_[0].pt()-anaJets_[1].pt())/(anaJets_[0].pt()+anaJets_[1].pt()),weight);
      hJDEta->Fill(anaJets_[1].eta()-anaJets_[0].eta(),weight);
      hCentReWeighted->Fill(cent,weight);
      ++numDJ_;
      numDJReWeighted_+=weight;
      jettrk_.cent = cent;
      jettrk_.centwt = weight;

      for (Int_t j=0; j<2; ++j) {
	if (jetEvt[j]) {
	  hJEt[j]->Fill(anaJets_[j].pt(),weight);
	  hJEta[j]->Fill(anaJets_[j].eta(),weight);
	  jettrk_.jtpt[j] = anaJets_[j].pt();
	  jettrk_.jteta[j] = anaJets_[j].eta();
	  jettrk_.jtphi[j] = anaJets_[j].phi();
	  ++numJ_[j];
	  numJReWeighted_[j]+=weight;
	}
      }
      jettrk_.jdphi = anaJetDPhi_;

      if (doJetOnly_) continue;

      // Initialize Counters
      Double_t conePtSum[2] = { 0,0 };
      Double_t conePtBgSum[2] = { 0,0 };
      Double_t metx=0,metx0=0,metx1=0,metx2=0,metx3=0,metx4=0,metx5=0;
      Double_t mety=0,mety0=0,mety1=0,mety2=0,mety3=0,mety4=0,mety5=0;
      Double_t metConex=0,metConex0=0,metConex1=0,metConex2=0,metConex3=0,metConex4=0,metConex5=0;
      Double_t metOutOfConex=0,metOutOfConex0=0,metOutOfConex1=0,metOutOfConex2=0,metOutOfConex3=0,metOutOfConex4=0,metOutOfConex5=0;
      // =====================================================
      // Fill Particle Level Histograms
      // =====================================================
      for (Int_t i=0; i<evtnp;++i) {
	// ------------------------
	// Trk Cut
	// ------------------------
	if (anaGenpType_==1 && pch[i]==0) continue;
	if (anaGenpType_==10 && (psube[i]>0 || pch[i]==0)) continue;
	if (cut.Name.Contains("PFChHad") && pfid[i]!=1) continue;
	if (cut.Name.Contains("PFPhoton") && pfid[i]!=4) continue;
	if (ppt[i]<cut.TrkPtMin||fabs(peta[i])>=2.4) continue;
	// ------------------------
	// Track Efficiency/Fake Correction
	// ------------------------
	Double_t trackWeight=1;
	Float_t trkcorr[4]={1,1,1,1};
	if (doTrackingEffFakeCorr_) {
	  trackWeight = getEffFakeCorrection(ppt[i],peta[i],anaJets_[0].pt(),cent,trkcorr);
	}
	// Dead forward pixel xcheck
	//if (peta[i]>2&&pphi[i]>-0.1&&pphi[i]<0.8) trackWeight=0;

	jettrk_.ppt.push_back(p_[i].pt());
	jettrk_.peta.push_back(p_[i].eta());
	jettrk_.pphi.push_back(p_[i].phi());
	jettrk_.trkeff.push_back(trkcorr[0]);
	jettrk_.trkfak.push_back(trkcorr[1]);
	jettrk_.trkmul.push_back(trkcorr[2]);
	jettrk_.trksec.push_back(trkcorr[3]);
	// ------------------------
	// calculate particle jet correlations
	// ------------------------
	Double_t pdphi[2]={ 9999,9999 };
	Double_t pdr[2]={ 9999,9999 };
	Double_t pdrbg[2]={ 9999,9999 };
	for (Int_t j=0; j<2; ++j) {
	  // signal
	  pdphi[j] = reco::deltaPhi(p_[i].phi(),anaJets_[j].phi());
	  pdr[j] = reco::deltaR(p_[i].eta(),p_[i].phi(),anaJets_[j].eta(),anaJets_[j].phi());
	  // bcksub
	  // * If don't do event selection, make eta reflection the default bkg axis
	  if (cut.BkgSubType.Contains("EtaRefl"||!doEvtSel_)) {
	    pdrbg[j] = reco::deltaR(p_[i].eta(),p_[i].phi(),-1*anaJets_[j].eta(),anaJets_[j].phi());
	  }
	  // monitor histograms
	  hPJDPhi[j]->Fill(pdphi[j],trackWeight);
	  jettrk_.pdr[j].push_back(pdr[j]);
	  jettrk_.pdrbg[j].push_back(pdrbg[j]);
	}

	Float_t trkEnergy=p_[i].pt();
	// ------------------------
	// met calculation
	// ------------------------
	Float_t pptx=cos(pdphi[0])*trkEnergy*trackWeight;
	metx+=pptx;
	Float_t ppty=sin(pdphi[0])*trkEnergy*trackWeight;
	mety+=ppty;
	if (fabs(pdr[0])<0.8||fabs(pdr[1])<0.8) metConex+=pptx; else metOutOfConex+=pptx;
	//for (int i=0;i<hPt->GetNbinsX()+2;++i) cout << "Bin " << i << " ledge: " << hPt->GetBinLowEdge(i) << endl;
	if (trkEnergy>=hPt->GetBinLowEdge(1)&&trkEnergy<hPt->GetBinLowEdge(2)) {
	  metx0+=pptx;
	  mety0+=ppty;
	  if (fabs(pdr[0])<0.8||fabs(pdr[1])<0.8) metConex0+=pptx; else metOutOfConex0+=pptx;
	} else if (trkEnergy>=hPt->GetBinLowEdge(2)&&trkEnergy<hPt->GetBinLowEdge(3)) {
	  metx1+=pptx;
	  mety1+=ppty;
	  if (fabs(pdr[0])<0.8||fabs(pdr[1])<0.8) metConex1+=pptx; else metOutOfConex1+=pptx;
	} else if (trkEnergy>=hPt->GetBinLowEdge(3)&&trkEnergy<hPt->GetBinLowEdge(4)) {
	  metx2+=pptx;
	  mety2+=ppty;
	  if (fabs(pdr[0])<0.8||fabs(pdr[1])<0.8) metConex2+=pptx; else metOutOfConex2+=pptx;
	} else if (trkEnergy>=hPt->GetBinLowEdge(4)&&trkEnergy<hPt->GetBinLowEdge(5)) {
	  metx3+=pptx;
	  mety3+=ppty;
	  if (fabs(pdr[0])<0.8||fabs(pdr[1])<0.8) metConex3+=pptx; else metOutOfConex3+=pptx;
	} else if (trkEnergy>=hPt->GetBinLowEdge(5)&&trkEnergy<hPt->GetBinLowEdge(6)) { 
	  metx4+=pptx;
	  mety4+=ppty;
	  if (fabs(pdr[0])<0.8||fabs(pdr[1])<0.8) metConex4+=pptx; else metOutOfConex4+=pptx;
	} else if (trkEnergy>=hPt->GetBinLowEdge(6)&&trkEnergy<hPt->GetBinLowEdge(7)) { 
	  metx5+=pptx;
	  mety5+=ppty;
	  if (fabs(pdr[0])<0.8||fabs(pdr[1])<0.8) metConex5+=pptx; else metOutOfConex5+=pptx;
	}

	// =====================================================
	// Calculate Cone Sums
	// =====================================================
	// cone sum
	for (Int_t j=0; j<2; ++j) {
	  for (Int_t b=0; b<numPtBins; ++b) {
	    if (trkEnergy>=hPt->GetBinLowEdge(b+1)&&trkEnergy<hPt->GetBinLowEdge(b+2)) {
	      // Signal Cone
	      if (pdr[j]<cut.ConeSize) {
		jc_.cpt[j][b]+=trkEnergy*trackWeight;
		jc_.cptpara[j][b]+=cos(reco::deltaPhi(p_[i].phi(),anaJets_[0].phi()))*trkEnergy*trackWeight;
	      }
	      // Bkg Cone
	      if (pdrbg[j]<cut.ConeSize) {
		jc_.cptbg[j][b]+=trkEnergy*trackWeight;
		jc_.cptparabg[j][b]+=cos(reco::deltaPhi(p_[i].phi(),anaJets_[0].phi()))*trkEnergy*trackWeight;
	      }
	      break;
	    }
	  }
	}

	// =====================================================
	// Take the reweighting into account for later histogram
	// **This should not be applied before the met calculation.**
	// =====================================================
	trackWeight *= weight;

	// =====================================================
	// Fill Jet-Particle Histograms
	// =====================================================
	for (Int_t j=0; j<2; ++j) {
	  if (jetEvt[j]) {
	    // Signal Cone
	    if (pdr[j]<cut.ConeSize) {
	      conePtSum[j]+=trkEnergy*trackWeight;
	      hCPPt[j]->Fill(trkEnergy,trackWeight);
	      hPtPDR[j]->Fill(trkEnergy,pdr[j],trkEnergy*trackWeight);
	    }
	    // Background Cone
	    if (pdrbg[j]<cut.ConeSize) {
	      hCPPtBg[j]->Fill(trkEnergy,trackWeight);
	      conePtBgSum[j]+=trkEnergy*trackWeight;
	      hPtPDRBg[j]->Fill(trkEnergy,pdrbg[j],trkEnergy*trackWeight);
	    }
	  }
	}
      } // end of particles loop

      // =====================================================
      // Fill Cone Sums
      // =====================================================
      for (Int_t j=0; j<2; ++j) {
	if (jetEvt[j]) {
	  hCPt[j]->Fill(conePtSum[j]);
	  hCPtBg[j]->Fill(conePtBgSum[j]);
	  hCPtBgSub[j]->Fill(conePtSum[j]-conePtBgSum[j]);
	}
      }

      // =====================================================
      // Fill Ntuple
      // =====================================================
      Float_t var[100];
      var[0]=anaJets_[0].pt();
      var[1]=anaJets_[0].eta();
      var[2]=anaJets_[0].phi();
      var[3]=anaJets_[1].pt();
      var[4]=anaJets_[1].eta();
      var[5]=anaJets_[1].phi();
      var[6]=metx;
      var[7]=metx0;
      var[8]=metx1;
      var[9]=metx2;
      var[10]=metx3;
      var[11]=metx4;
      var[12]=metx5;
      var[13]=mety;
      var[14]=mety0;
      var[15]=mety1;
      var[16]=mety2;
      var[17]=mety3;
      var[18]=mety4;
      var[19]=mety5;
      var[20]=metConex;
      var[21]=metConex0;
      var[22]=metConex1;
      var[23]=metConex2;
      var[24]=metConex3;
      var[25]=metConex4;
      var[26]=metConex5;
      var[27]=metOutOfConex;
      var[28]=metOutOfConex0;
      var[29]=metOutOfConex1;
      var[30]=metOutOfConex2;
      var[31]=metOutOfConex3;
      var[32]=metOutOfConex4;
      var[33]=metOutOfConex5;
      var[34]=GetEvtMask();
      var[35]=cent;
      var[36]=anaJetDPhi_;
      var[37]=weight;
      ntjt->Fill(var);    // fit ntuple

      tjttrk->Fill();

      tcone->Fill();
    } // End of Main Event Selection
    // if (Cut(ientry) < 0) continue;
  }

  // =====================================================
  // Summarize Event Loop
  // =====================================================
  cout << "Total Events: " << numTotEvt << endl;
  cout << "DiJets Selected w/o Bkg Limit: " << numDJNoBkgLimit << " (same as draw cut unless there is jet eta correction)" << endl;
  cout << "DiJets Selected: " << numDJ_ << " Reweighted: " << numDJReWeighted_ << endl;
  for (Int_t j=0; j<2; ++j) {
    cout << "num Jet" << j << " Selected: " << numJ_[j] << " Reweighted: " << numJReWeighted_[j] << endl;
  }

  // =====================================================
  // Normalize by Number of Selected Events
  // =====================================================
  hJDPhi->Scale(1./(numDJReWeighted_));
  hJDEta->Scale(1./(numDJReWeighted_));
  hAj->Scale(1./(numDJReWeighted_));
  hCentReWeighted->Scale(1./(numDJReWeighted_));

  for (Int_t j=0; j<2; ++j) {
    hJEt[j]->Scale(1./(numJReWeighted_[j]));
    hJEta[j]->Scale(1./(numJReWeighted_[j]));

    hCPPt[j]->Scale(1./numJReWeighted_[j]);
    hCPPtBg[j]->Scale(1./numJReWeighted_[j]);
    hCPPtBgSub[j]->Add(hCPPt[j],hCPPtBg[j],1,-1);

    hCPt[j]->Scale(1./(numJReWeighted_[j]));
    hCPtBg[j]->Scale(1./(numJReWeighted_[j]));
    hCPtBgSub[j]->Scale(1./(numJReWeighted_[j]));

    hPtPDR[j]->Scale(1./(numJReWeighted_[j]));
    hPtPDRBg[j]->Scale(1./(numJReWeighted_[j]));
  }
}
Пример #13
0
//_______________________________________________________________________________
void makeZinvFromDY( TFile* fData , TFile* fZinv , TFile* fDY ,TFile* fTop, vector<string> dirs, string output_name ) {

  // Generate histogram file with Zinv prediction based on DYData * R(Zinv/DY)

  TFile * outfile = new TFile(output_name.c_str(),"RECREATE") ; 
  outfile->cd();
  const unsigned int ndirs = dirs.size();

//  // Obtain inclusive templates
//  int lastmt2_VL23J=0, lastmt2_VL2J=0, lastmt2_VL4J=0;
//  int lastmt2_L23J=0,  lastmt2_L26J=0, lastmt2_L46J=0, lastmt2_L7J=0;
//  int lastmt2_M23J=0,  lastmt2_M26J=0, lastmt2_M46J=0, lastmt2_M7J=0;
//  int lastmt2_H23J=0,  lastmt2_H26J=0, lastmt2_H46J=0, lastmt2_H7J=0;
//  int lastmt2_UH=0;
//  TH1D* h_TemplateVL23J      = (TH1D*) fData->Get("crdybaseVL/h_mt2bins23J"); 
//  int lastbin_VL23J = purityRandNorm(h_TemplateVL23J, "crdybaseVL/h_mt2bins23J", fData, fZinv, fDY, lastmt2_VL23J);
//  TH1D* h_TemplateVL2J       = (TH1D*) fData->Get("crdybaseVL/h_mt2bins"); 
//  int lastbin_VL2J  = purityRandNorm(h_TemplateVL2J, "crdybaseVL/h_mt2bins", fData, fZinv, fDY, lastmt2_VL2J);
//  TH1D* h_TemplateVL4J       = (TH1D*) fData->Get("crdybaseVL/h_mt2bins4J");  
//  int lastbin_VL4J  = purityRandNorm(h_TemplateVL4J, "crdybaseVL/h_mt2bins4J", fData, fZinv, fDY, lastmt2_VL4J);  
//  TH1D* h_TemplateL23J       = (TH1D*) fData->Get("crdybaseL/h_mt2bins23J");
//  int lastbin_L23J  = purityRandNorm(h_TemplateL23J, "crdybaseL/h_mt2bins23J", fData, fZinv, fDY, lastmt2_L23J);    
//  TH1D* h_TemplateL26J       = (TH1D*) fData->Get("crdybaseL/h_mt2bins26J");
//  int lastbin_L26J  = purityRandNorm(h_TemplateL26J, "crdybaseL/h_mt2bins26J", fData, fZinv, fDY, lastmt2_L26J);    
//  TH1D* h_TemplateL46J       = (TH1D*) fData->Get("crdybaseL/h_mt2bins46J");   
//  int lastbin_L46J  = purityRandNorm(h_TemplateL46J, "crdybaseL/h_mt2bins46J", fData, fZinv, fDY, lastmt2_L46J); 
//  TH1D* h_TemplateL7J        = (TH1D*) fData->Get("crdybaseL/h_mt2bins7J");    
//  int lastbin_L7J   = purityRandNorm(h_TemplateL7J, "crdybaseL/h_mt2bins7J", fData, fZinv, fDY, lastmt2_L7J);
//  TH1D* h_TemplateM23J       = (TH1D*) fData->Get("crdybaseM/h_mt2bins23J");    
//  int lastbin_M23J  = purityRandNorm(h_TemplateM23J, "crdybaseM/h_mt2bins23J", fData, fZinv, fDY, lastmt2_M23J);
//  TH1D* h_TemplateM26J       = (TH1D*) fData->Get("crdybaseM/h_mt2bins26J");    
//  int lastbin_M26J  = purityRandNorm(h_TemplateM26J, "crdybaseM/h_mt2bins26J", fData, fZinv, fDY, lastmt2_M26J);
//  TH1D* h_TemplateM46J       = (TH1D*) fData->Get("crdybaseM/h_mt2bins46J");    
//  int lastbin_M46J  = purityRandNorm(h_TemplateM46J, "crdybaseM/h_mt2bins46J", fData, fZinv, fDY, lastmt2_M46J);
//  TH1D* h_TemplateM7J        = (TH1D*) fData->Get("crdybaseM/h_mt2bins7J");    
//  int lastbin_M7J   = purityRandNorm(h_TemplateM7J, "crdybaseM/h_mt2bins7J", fData, fZinv, fDY, lastmt2_M7J);
//  TH1D* h_TemplateH23J       = (TH1D*) fData->Get("crdybaseH/h_mt2bins23J");    
//  int lastbin_H23J  = purityRandNorm(h_TemplateH23J, "crdybaseH/h_mt2bins23J", fData, fZinv, fDY, lastmt2_H23J);
//  TH1D* h_TemplateH26J       = (TH1D*) fData->Get("crdybaseH/h_mt2bins26J");    
//  int lastbin_H26J  = purityRandNorm(h_TemplateH26J, "crdybaseH/h_mt2bins26J", fData, fZinv, fDY, lastmt2_H26J);
//  TH1D* h_TemplateH46J       = (TH1D*) fData->Get("crdybaseH/h_mt2bins46J");    
//  int lastbin_H46J  = purityRandNorm(h_TemplateH46J, "crdybaseH/h_mt2bins46J", fData, fZinv, fDY, lastmt2_H46J);
//  TH1D* h_TemplateH7J        = (TH1D*) fData->Get("crdybaseH/h_mt2bins7J");    
//  int lastbin_H7J   = purityRandNorm(h_TemplateH7J, "crdybaseH/h_mt2bins7J", fData, fZinv, fDY, lastmt2_H7J);
//  TH1D* h_TemplateUH        = (TH1D*) fData->Get("crdybaseUH/h_mt2bins");    
//  int lastbin_UH    = purityRandNorm(h_TemplateUH, "crdybaseUH/h_mt2bins", fData, fZinv, fDY, lastmt2_UH);


  for ( unsigned int idir = 0; idir < ndirs; ++idir ) {
    
    TString srname = dirs.at(idir);
    TString directory = "sr"+dirs.at(idir);
    TString directoryDY = "crdy"+dirs.at(idir);

    TString fullhistname = directory + "/h_mt2bins";
    TString fullhistnameDY = directoryDY + "/h_mt2bins";
    TString fullhistnameEM = directoryDY + "/h_mt2binsemu";

    TH1D* hData = (TH1D*) fData->Get(fullhistnameDY);    
    TH1D* hDY   = (TH1D*) fDY->Get(fullhistnameDY);
    TH1D* hDataEM   = (TH1D*) fData->Get(fullhistnameEM);    
    TH1D* hZinv = (TH1D*) fZinv->Get(fullhistname);    
    TH1D* hTop  = (TH1D*) fTop->Get(fullhistnameDY);    

    TH1D* hDY_lepeff_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_lepeff_UP");
    TH1D* hDY_lepeff_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_lepeff_DN");
    TH1D* hDY_trigeff_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_trigeff_UP");
    TH1D* hDY_trigeff_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_trigeff_DN");
    TH1D* hDY_ZNJet_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_ZNJet_UP");
    TH1D* hDY_ZNJet_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_ZNJet_DN");
    TH1D* hZinv_ZNJet_UP   = (TH1D*) fZinv->Get(fullhistname+"_ZNJet_UP");
    TH1D* hZinv_ZNJet_DN   = (TH1D*) fZinv->Get(fullhistname+"_ZNJet_DN");
    TH1D* hDY_renorm_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_renorm_UP");
    TH1D* hDY_renorm_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_renorm_DN");
    TH1D* hZinv_renorm_UP   = (TH1D*) fZinv->Get(fullhistname+"_renorm_UP");
    TH1D* hZinv_renorm_DN   = (TH1D*) fZinv->Get(fullhistname+"_renorm_DN");
    
    // If Zinv or DY histograms are not filled, just leave (shouldn't happen when running on full stat MC)
    if(!hDY || !hZinv || !hData){
      cout<<"could not find histogram "<<fullhistname<<endl;
      continue;
    }
    
    if (hDY->GetNbinsX() != hZinv->GetNbinsX() ) {
      cout<<"different binning for histograms "<<fullhistname<<endl;
      continue;
    }
    
    // Make directory and plot(s) in the output file
    TDirectory* dir = 0;
    dir = (TDirectory*)outfile->Get(directory.Data());
    if (dir == 0) {
      dir = outfile->mkdir(directory.Data());
    } 
    dir->cd();

    cout<<"Looking at histo "<<fullhistname<<endl;

    int lastbin_hybrid = 1;
    int lastmt2val_hybrid = 200;
    int ht_LOW = 0, ht_HI = 0, njets_LOW = 0, njets_HI = 0, nbjets_LOW = 0, nbjets_HI = 0;
    TH1D* h_MT2Template = (TH1D*) hZinv->Clone("h_MT2Template");  
    TString inclusiveTemplateName = "";

    TH1D *h_ht_LOW, *h_ht_HI, *h_njets_LOW, *h_njets_HI, *h_nbjets_LOW, *h_nbjets_HI;
    if (doHybridInclusiveTemplate) {
      //  Inclusive template: use inclusive template corresponding to this region
      
      //Get variable boundaries for signal region.
      h_ht_LOW = (TH1D*) fData->Get(directory+"/h_ht_LOW");
      h_ht_HI  = (TH1D*) fData->Get(directory+"/h_ht_HI");
      if (h_ht_LOW) ht_LOW = h_ht_LOW->GetBinContent(1);
      if (h_ht_HI)  ht_HI = h_ht_HI->GetBinContent(1);
      h_njets_LOW = (TH1D*) fData->Get(directory+"/h_njets_LOW");
      h_njets_HI  = (TH1D*) fData->Get(directory+"/h_njets_HI");
      if (h_njets_LOW) njets_LOW = h_njets_LOW->GetBinContent(1);
      if (h_njets_HI)  njets_HI = h_njets_HI->GetBinContent(1);
      h_nbjets_LOW = (TH1D*) fData->Get(directory+"/h_nbjets_LOW");
      h_nbjets_HI  = (TH1D*) fData->Get(directory+"/h_nbjets_HI");
      if (h_nbjets_LOW) nbjets_LOW = h_nbjets_LOW->GetBinContent(1);
      if (h_nbjets_HI)  nbjets_HI = h_nbjets_HI->GetBinContent(1);
      
      //Determine which inclusive template to use. If none works, this reverts to HybridSimple, taking template from its own TopoRegion 
      // Start from the Aggregate Regions (hardcoded, since they can partially overlap with the standard regions)
      if (srname == "20") inclusiveTemplateName = "crdy20/h_mt2bins";  // self (2j, HT1200)
      else if (srname == "base") inclusiveTemplateName = "crdybase/h_mt2bins";
      else if (srname == "baseVL") inclusiveTemplateName = "crdybaseVL/h_mt2bins";
      else if (srname == "baseL") inclusiveTemplateName = "crdybaseL/h_mt2bins";
      else if (srname == "baseM") inclusiveTemplateName = "crdybaseM/h_mt2bins";
      else if (srname == "baseH") inclusiveTemplateName = "crdybaseH/h_mt2bins";
      else if (srname == "baseUH") inclusiveTemplateName = "crdybaseUH/h_mt2bins";
      else if (srname == "21") inclusiveTemplateName = "crdy21/h_mt2bins"; // self (2j, HT1500)
      else if (srname == "22") inclusiveTemplateName = "crdy22/h_mt2bins"; // self (4j, HT1200)
      else if (srname == "23") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21 
      else if (srname == "24") inclusiveTemplateName = "crdy24/h_mt2bins"; // self (7J, HT1200)
      else if (srname == "25") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      else if (srname == "26") inclusiveTemplateName = "crdy20/h_mt2bins"; // from 20
      else if (srname == "27") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      else if (srname == "28") inclusiveTemplateName = "crdy20/h_mt2bins3J"; // need a 3J histogram within SR20
      //      else if (srname == "28") inclusiveTemplateName = "crdy20/h_mt2bins"; // test
      else if (srname == "29") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      else if (srname == "30") inclusiveTemplateName = "crdy24/h_mt2bins"; // from 24
      else if (srname == "31") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      // Now the standard regions
      else if (ht_LOW == 250) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseVL/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7) inclusiveTemplateName = "crdybaseVL/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseVL/h_mt2bins23J"; 
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseVL/h_mt2bins46J"; 
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseVL/h_mt2bins7J"; 
      }
      else if (ht_LOW == 450) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseL/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7)  inclusiveTemplateName = "crdybaseL/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseL/h_mt2bins23J"; 
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseL/h_mt2bins46J"; 
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseL/h_mt2bins7J"; 
      }
      else if (ht_LOW == 575) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseM/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7) inclusiveTemplateName = "crdybaseM/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseM/h_mt2bins23J"; 
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseM/h_mt2bins46J"; 
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseM/h_mt2bins79J"; 
	else if (njets_LOW == 10)  inclusiveTemplateName = "crdybaseM/h_mt2bins10J"; 
      }
      else if (ht_LOW == 1200) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseH/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7)  inclusiveTemplateName = "crdybaseH/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseH/h_mt2bins23J";
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseH/h_mt2bins46J";
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseH/h_mt2bins79J";
	else if (njets_LOW == 10)  inclusiveTemplateName = "crdybaseH/h_mt2bins10J";
      }
      else if (ht_LOW == 1500) inclusiveTemplateName = "crdybaseUH/h_mt2bins";

      if (inclusiveTemplateName == "") {
	cout<< "Can't find template for region: HT "<<ht_LOW<<"-"<<ht_HI<<" and NJ "<<njets_LOW<<"-"<<njets_HI<<endl;
	lastbin_hybrid = 1;
	h_MT2Template = 0;
	cout<<"h_MT2Template is 0, using hybrid within this region (no external templates)"<<endl;
      }
      else {
	cout<< "Using inclusive template "<<inclusiveTemplateName<<" for region: HT "<<ht_LOW<<"-"<<ht_HI<<" and NJ "<<njets_LOW<<"-"<<njets_HI<<endl; 
	// Get the template
	lastbin_hybrid = makeHybridTemplate(srname, h_MT2Template, inclusiveTemplateName , fData, fZinv, fDY, lastmt2val_hybrid);
	cout<<"lastbin_hybrid "<<lastbin_hybrid<<" and lastmt2val_hybrid "<<lastmt2val_hybrid<<endl;
	if (h_MT2Template!=0) h_MT2Template->Print();
	else cout<<"h_MT2Template is 0, using hybrid within this region (no external templates)"<<endl;
      }

   


    }

  


    // If there is no template for this region, go back to the standard hybrid
    if (doHybridSimple || (doHybridInclusiveTemplate && h_MT2Template == 0)) {
      // hybrid method: use nominal MC CR yield histogram to determine how many MT2 bins to use
      //  by default: use all MT2 bins integrated (no bin-by-bin).
      //  choose the last bin to try to have at least hybrid_nevent_threshold integrated events

      // Calculate last bin on local histogram
      for ( int ibin=1; ibin <= hDY->GetNbinsX(); ++ibin ) {
	float top = 0, integratedYield = 0;
	//if (hDataEM) top = hDataEM->Integral(ibin,-1)*rSFOF;
	integratedYield = hDY->Integral(ibin,-1) - top;
	if (integratedYield < hybrid_nevent_threshold) {
	  if (ibin == 1) lastbin_hybrid = 1;
	  else {
	    lastbin_hybrid = ibin-1;
	    lastmt2val_hybrid = hDY->GetBinLowEdge(ibin);
	  }
	  break;
	}
      }
      cout<<"lastbin_hybrid for doHybridSimple: "<<lastbin_hybrid<<endl;
    }
    
    

    TH1D* ratio = (TH1D*) hZinv->Clone("ratio");
    ratio->Divide(hDY);
    double errNum, errDen;
    float ratioValue = hZinv->IntegralAndError(1,-1,errNum) / hDY->IntegralAndError(1,-1,errDen);
    float ratioErr = ratioValue*sqrt(pow(errNum/hZinv->Integral(), 2) + pow(errDen/hDY->Integral(),2));

    TH1D* CRyield = (TH1D*) hData->Clone("h_mt2binsCRyield");

    TH1D* purityMC = (TH1D*) hDY->Clone("h_mt2binsPurityMC");
    if (hTop) purityMC->Add(hTop, -1);
    purityMC->Divide(hDY);

    TH1D* purityData = (TH1D*) hData->Clone("h_mt2binsPurityData");
    if (hDataEM) purityData->Add(hDataEM, -1*rSFOF); 
    purityData->Divide(purityData, hData, 1, 1, "B");
    
    TH1D* Stat = (TH1D*) CRyield->Clone("h_mt2binsStat");
    Stat->Multiply(purityData);
    Stat->Multiply(ratio);

    TH1D* Syst = (TH1D*) Stat->Clone("h_mt2binsSyst");
    TH1D* pred = (TH1D*) Stat->Clone("h_mt2bins");
    for ( int ibin = 0; ibin <= Stat->GetNbinsX(); ++ibin) { 
      Syst->SetBinError(ibin, (1-purityData->GetBinContent(ibin))*0.2*Stat->GetBinContent(ibin));
      double quadrature = Stat->GetBinError(ibin)*Stat->GetBinError(ibin) + Syst->GetBinError(ibin)*Syst->GetBinError(ibin);
      pred->SetBinError(ibin, sqrt(quadrature));
    }
    //pred->Print("all");

    // Inputs to cardMaker
    TH1D* ratioCard  = (TH1D*) ratio->Clone("ratioCard");
    TH1D* purityCard  = (TH1D*) purityData->Clone("purityCard");   
    TH1D* CRyieldCard  = (TH1D*) CRyield->Clone("CRyieldCard");

    TH1D *CRyieldEM = 0, *CRyieldEMCard = 0;
    if (hDataEM){
        CRyieldEM = (TH1D*) hDataEM->Clone("h_mt2binsCRyieldEM");
        CRyieldEMCard = (TH1D*) CRyieldEM->Clone("CRyieldEMCard");
    }

    if (  doHybridSimple || (doHybridInclusiveTemplate && h_MT2Template==0) ) { 
      // purity needs to describe the integrated purity of the CR
      // ratio needs to be modified so that the last N bins include kMT2
      // CRyield needs to be modified so that the last N bins have the same yield (which is the integral over those N bins)
      if (verbose) cout<<" Implementing simple hybrid "<<endl;

      for ( int ibin=1; ibin <= hZinv->GetNbinsX(); ++ibin ) {

	if (ibin < lastbin_hybrid) continue;
	
	double integratedYieldErr = 0;
	float integratedYield = CRyield->IntegralAndError(lastbin_hybrid,-1,integratedYieldErr);
	CRyieldCard->SetBinContent(ibin, integratedYield);
	CRyieldCard->SetBinError(ibin, integratedYieldErr);
	
	float integratedDen = integratedYield;
	double EM = 0, errEM = 0;
	if (hDataEM) EM =  hDataEM->IntegralAndError(lastbin_hybrid, -1, errEM) * rSFOF;
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, EM);
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, errEM);
        float integratedNum = integratedDen - EM;
	if (integratedNum < 0) integratedNum = 0;
	float integratedPurity = integratedNum/integratedDen;
	float integratedPurityErr = sqrt(integratedPurity*(1-integratedPurity)/integratedDen);// sqrt(e(1-e)/N)   
	purityCard->SetBinContent(ibin, integratedPurity);
	purityCard->SetBinError(ibin, integratedPurityErr);

	float integratedZinv = 1;
	float kMT2 = 0;
	integratedZinv = hZinv->Integral(lastbin_hybrid, -1);
	kMT2 = hZinv->GetBinContent(ibin) / integratedZinv;
	ratioCard->SetBinContent(ibin, ratioCard->GetBinContent(ibin) * kMT2);
	ratioCard->SetBinError(ibin, ratioCard->GetBinError(ibin) * kMT2 ); // just rescale the error by the same amount

      }
    } 
    else if (doHybridInclusiveTemplate && h_MT2Template!=0) {
      // For Inclusive template: 
      // CRyield: this is flat, just the integral
      // purity: also flat
      // ratio: this contains the normalized template scaled by the Zinv/DY ratio for this control region
      // Template should be rebinned to match this region. lastbin_hybrid will have to be updated to refer to the new binning
      
      if (verbose) cout<<" Implementing hybrid with template "<<endl;

//      // MT2template needs to be rebinned for this topological region Rebin
//      double *TopoRegionBins = hZinv->GetXaxis()->GetXbins()->fArray;
//      int nTopoRegionBins    = hZinv->GetXaxis()->GetNbins();
//      h_MT2Template->Print("all");
//      TH1D* h_MT2TemplateRebin = (TH1D*) h_MT2Template->Rebin(nTopoRegionBins, "h_MT2TemplateRebin", TopoRegionBins);
//      int newlastbin = h_MT2TemplateRebin->FindBin(lastmt2val_hybrid-1);
//      if (newlastbin == 0) newlastbin = 1; // 1 is the lowest
//      if (verbose) cout<<"Rebinning moved lastbin_hybrid from "<<lastbin_hybrid<<" to "<<newlastbin<<". lastmt2val_hybrid="<<lastmt2val_hybrid<<endl;
//      lastbin_hybrid = newlastbin;
//      if (verbose) h_MT2TemplateRebin->Print("all");
      if (verbose) cout<<"Ratio for this control region is "<<ratioValue<<endl;

      double integratedYieldErr = 0;
      float integratedYield = CRyield->IntegralAndError(0,-1,integratedYieldErr);
      
      float integratedDen = integratedYield;
      double EM = 0, errEM=0;
      if (hDataEM) EM =  hDataEM->IntegralAndError(0, -1, errEM)*rSFOF;
      float integratedNum = integratedDen - EM;
      if (integratedNum < 0) integratedNum = 0;
      float integratedPurity = integratedNum/integratedDen;      
      // float integratedPurityErr = sqrt(integratedPurity*(1-integratedPurity)/integratedDen);// sqrt(e(1-e)/N)
      // this isn't a proportion (OF/SF are statistically independent regions). Makes no sense to do this
      // what we want is the error on (SF - R*OF). Three sources: dSF, OF*dR, and R*dOF
      // first comes from gmN error in the cards on the main CR yield
      // second comes from special RSFOF handling in cardmaker
      // third should be: R*dOF/(SF-R*dOF). Use proper poissonian error on OF yield
      errEM = ROOT::Math::gamma_quantile_c((1-0.6828)/2, int(EM)+1, 1) - EM;
      float integratedPurityErr = rSFOF*errEM / integratedNum * integratedPurity;

      if(integratedDen==0.0){
          // if CR is 0, assume purity of 1.0 and give it a big error (this basically assumes that SF=1 and OF=0)
          integratedPurity = 1.0;
          errEM = ROOT::Math::gamma_quantile_c((1-0.6828)/2, int(0)+1, 1) - 0;
          integratedPurityErr = rSFOF*errEM;
      }
      
      if (verbose) cout<<"Found SF="<<integratedYield<<" and OF="<<EM<<", so purity is "<<integratedPurity<<endl;

      for ( int ibin=1; ibin <= hZinv->GetNbinsX()+1; ++ibin ) {
	CRyieldCard->SetBinContent(ibin, integratedYield);
	CRyieldCard->SetBinError(ibin,   integratedYieldErr);
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, EM);
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, errEM);
	ratioCard->SetBinContent(ibin, ratioValue * h_MT2Template->GetBinContent(ibin));
        float err = 0.0;
        if(ratioValue>0.0 && h_MT2Template->GetBinContent(ibin)>0.0)
            err = ratioValue * h_MT2Template->GetBinContent(ibin) * sqrt(pow(ratioErr/ratioValue,2) + pow(h_MT2Template->GetBinError(ibin)/h_MT2Template->GetBinContent(ibin),2));
	ratioCard->SetBinError(ibin,   err);
	purityCard->SetBinContent(ibin, integratedPurity);
	purityCard->SetBinError(ibin,   integratedPurityErr);
      }

    }

    TH1D* ratioCard_lepeff_UP = (TH1D*)ratioCard->Clone("ratioCard_lepeff_UP");
    TH1D* ratioCard_lepeff_DN = (TH1D*)ratioCard->Clone("ratioCard_lepeff_DN");
    if(hDY_lepeff_UP) ratioCard_lepeff_UP->Scale(hDY->Integral() / hDY_lepeff_UP->Integral());
    if(hDY_lepeff_DN) ratioCard_lepeff_DN->Scale(hDY->Integral() / hDY_lepeff_DN->Integral());

    TH1D* ratioCard_trigeff_UP = (TH1D*)ratioCard->Clone("ratioCard_trigeff_UP");
    TH1D* ratioCard_trigeff_DN = (TH1D*)ratioCard->Clone("ratioCard_trigeff_DN");
    if(hDY_trigeff_UP) ratioCard_trigeff_UP->Scale(hDY->Integral() / hDY_trigeff_UP->Integral());
    if(hDY_trigeff_DN) ratioCard_trigeff_DN->Scale(hDY->Integral() / hDY_trigeff_DN->Integral());

    TH1D* ratioCard_ZNJet_UP = (TH1D*)ratioCard->Clone("ratioCard_ZNJet_UP");
    TH1D* ratioCard_ZNJet_DN = (TH1D*)ratioCard->Clone("ratioCard_ZNJet_DN");
    if(hDY_ZNJet_UP && hZinv_ZNJet_UP) ratioCard_ZNJet_UP->Scale(hDY->Integral() / hDY_ZNJet_UP->Integral() * hZinv_ZNJet_UP->Integral() / hZinv->Integral());
    if(hDY_ZNJet_DN && hZinv_ZNJet_DN) ratioCard_ZNJet_DN->Scale(hDY->Integral() / hDY_ZNJet_DN->Integral() * hZinv_ZNJet_DN->Integral() / hZinv->Integral());

    TH1D* ratioCard_renorm_UP = (TH1D*)ratioCard->Clone("ratioCard_renorm_UP");
    TH1D* ratioCard_renorm_DN = (TH1D*)ratioCard->Clone("ratioCard_renorm_DN");
    if(hDY_renorm_UP && hZinv_renorm_UP) ratioCard_renorm_UP->Scale(hDY->Integral() / hDY_renorm_UP->Integral() * hZinv_renorm_UP->Integral() / hZinv->Integral());
    if(hDY_renorm_DN && hZinv_renorm_DN) ratioCard_renorm_DN->Scale(hDY->Integral() / hDY_renorm_DN->Integral() * hZinv_renorm_DN->Integral() / hZinv->Integral());


    TH1D* hybridEstimate  = (TH1D*) CRyieldCard->Clone("hybridEstimate");
    hybridEstimate->Multiply(purityCard);
    hybridEstimate->Multiply(ratioCard);
    
    
    TH1D* h_lastbinHybrid = new TH1D("h_lastbinHybrid",";last bin",1,0,1);
    h_lastbinHybrid->SetBinContent(1,lastbin_hybrid);
    TH1D* h_lastmt2Hybrid = new TH1D("h_lastmt2Hybrid",";last M_{T2} value",1,0,1);
    h_lastmt2Hybrid->SetBinContent(1,lastmt2val_hybrid);

    pred->Write();
    Stat->Write();
    Syst->Write();
    purityMC->Write();
    purityData->Write();
    ratio->Write();
    CRyield->Write();

    ratioCard->Write();
    ratioCard_lepeff_UP->Write();
    ratioCard_lepeff_DN->Write();
    ratioCard_trigeff_UP->Write();
    ratioCard_trigeff_DN->Write();
    ratioCard_ZNJet_UP->Write();
    ratioCard_ZNJet_DN->Write();
    ratioCard_renorm_UP->Write();
    ratioCard_renorm_DN->Write();
    purityCard->Write();
    CRyieldCard->Write();
    h_lastbinHybrid->Write();
    hybridEstimate->Write();
    h_lastmt2Hybrid->Write();
    if (hDataEM) CRyieldEM->Write();
    if (hDataEM) CRyieldEMCard->Write();

    hDY->Write("h_mt2binsMCCR");
    hZinv->Write("h_mt2binsMCSR");

    if(!directoryDY.Contains("J")){
        // we want these for crdy (not saved for monojet, but they're the same as SR anyway)
        h_ht_LOW = (TH1D*) fData->Get(directoryDY+"/h_ht_LOW");
        h_ht_HI  = (TH1D*) fData->Get(directoryDY+"/h_ht_HI");
        h_njets_LOW = (TH1D*) fData->Get(directoryDY+"/h_njets_LOW");
        h_njets_HI  = (TH1D*) fData->Get(directoryDY+"/h_njets_HI");
        h_nbjets_LOW = (TH1D*) fData->Get(directoryDY+"/h_nbjets_LOW");
        h_nbjets_HI  = (TH1D*) fData->Get(directoryDY+"/h_nbjets_HI");
    }

    if(h_ht_LOW) h_ht_LOW->Write();
    if(h_ht_HI)  h_ht_HI->Write();
    if(h_njets_LOW) h_njets_LOW->Write();
    if(h_njets_HI)  h_njets_HI->Write();
    if(h_nbjets_LOW) h_nbjets_LOW->Write();
    if(h_nbjets_HI)  h_nbjets_HI->Write();


  } // loop over signal regions


  return;
}
Пример #14
0
//_______________________________________
void FitMCshape(AliDielectronSignalBase *sig)
{
  TFile mcFile(mcLineShapeFile);
  if (!mcFile.IsOpen()) {
    printf("mcMinv_LHC10e2 not found!!!\n");
    return;
  }
  TH1D *hMmc = (TH1D*)mcFile.Get("mcMinv");
  if (!hMmc) {
    printf("mcMinv not found!!\n");
    return;
  }
  hMmc->SetDirectory(0);
  hMmc->SetName("mcMinv");
  mcFile.Close();
  
  TH1* hMsub=sig->GetSignalHistogram();
  Double_t mb1=sig->GetIntegralMin();
  Double_t mb2=sig->GetIntegralMax();
  
  Double_t effInt = 0.;
  for(Int_t iBin=hMmc->FindBin(mb1); iBin<hMmc->FindBin(mb2); iBin++) {
    effInt += hMmc->GetBinContent(iBin);
  }
  effInt/=hMmc->Integral();
  printf("MC signal fraction in range %4.2f-%4.2f GeV: %5.3f \n",hMmc->GetBinLowEdge(hMmc->FindBin(mb1)),hMmc->GetBinLowEdge(hMmc->FindBin(mb2)+1),effInt);
 
  Float_t mcScale1=(hMsub->GetXaxis()->GetBinWidth(1)/hMmc->GetXaxis()->GetBinWidth(1))*
    hMsub->Integral(hMsub->FindBin(mb1),hMsub->FindBin(mb2))/
    hMmc->Integral(hMmc->FindBin(mb1),hMmc->FindBin(mb2));
  
  printf("1st guess of MC scale factor: %6.3f\n",mcScale1);
  
  Float_t mcScale=0.;
  Float_t chi2_min=100000.;
  Int_t iMin=0;
  Int_t ndf=0;
  
  for(Int_t i=0; i<20; i++){
    Float_t chi2=0.;
    Float_t scale=(0.4+0.05*(Float_t)i)*mcScale1;
    ndf=0;
    for(Int_t ib=1; ib<=hMsub->GetXaxis()->GetNbins(); ib++){
      Float_t data=(Float_t)hMsub->GetBinContent(ib);
      Float_t err=(Float_t)hMsub->GetBinError(ib);
      Float_t mc=scale*((Float_t)hMmc->GetBinContent(hMmc->FindBin(hMsub->GetBinCenter(ib))));
      if (err>0) {
        chi2 += ((data-mc)*(data-mc))/(err*err);
        ndf++;
      } else {
        //printf("bin %d Err: %6.3f, chi2: %6.1f\n",ib,err,chi2);
      }
    }
      //printf("%d scale factor: %6.3f, chi2: %6.1f\n",i,scale,chi2);
    if(chi2 < chi2_min){
      chi2_min = chi2;
      mcScale = scale;
      iMin=i;
    }
  }
  //Float_t chi2dof=chi2_min/(Float_t)(hMinv->GetXaxis()->GetNbins()-1);
  Float_t chi2dof=chi2_min/((Float_t)(ndf-1));
  printf("MC fit (i=%d): chi2/dof: %6.3f/%d, Scale: %7.4f \n",iMin,chi2_min,(ndf-1),mcScale);
  hMmc->SetTitle(Form("%f",chi2dof));
  
  //mcScale=IntData/IntMC;printf("Int Data, MC: %10.1f %10.1f, MC scale: %6.3f\n",IntData,IntMC,mcScale);
  
  hMmc->Scale(mcScale);
  hMmc->SetOption("sameHISTC");
  hMsub->GetListOfFunctions()->Add(hMmc);
}
Пример #15
0
void Smooth (TString sel) 
{

  const int nbins = 50;

  const int nvars=17;
  TString var[nvars] = { "C8", "M8", "C6", "M6", "MEt", "MEtSig", "CorrSumEt", "GoodHt", 
		      "M45bestall", "Chi2mass", "Chi2extall", "Mbbnoh", "DPbbnoh", 
		      "SumHED4", "SumHED6", "DP12", "MEtDP2" };
  TString pippo[nvars];
  TString pippotot[nvars];
  TString pippotth[nvars];
  TString pippototS[nvars];
  TString pippotthS[nvars];
  for ( int i=0; i<nvars; i++ ) { 
    pippo[i] = var[i]+sel; 
    pippotot[i]=var[i]+sel+"_bgr";
    pippotth[i]=var[i]+sel+"_sig";
    pippototS[i]=var[i]+sel+"_bgrS";
    pippotthS[i]=var[i]+sel+"_sigS";
  }
  
  const int nqcdsamples=8;
  TFile * QCD[nqcdsamples];     
  QCD[0] = new TFile("./root/et30_eta2.5/TDAna_QCD30-50_tk3.root");
  QCD[1] = new TFile("./root/et30_eta2.5/TDAna_QCD50-80_tk3.root");
  QCD[2] = new TFile("./root/et30_eta2.5/TDAna_QCD80-120_tk3.root");
  QCD[3] = new TFile("./root/et30_eta2.5/TDAna_QCD120-170_tk3.root");
  QCD[4] = new TFile("./root/et30_eta2.5/TDAna_QCD170-230_tk3.root");
  QCD[5] = new TFile("./root/et30_eta2.5/TDAna_QCD230-300_tk3.root");
  QCD[6] = new TFile("./root/et30_eta2.5/TDAna_QCD300-380_tk3.root");
  QCD[7] = new TFile("./root/et30_eta2.5/TDAna_QCD380incl_tk3.root");
  double QCDxs[nqcdsamples] = { 155929000., 20938850., 2949713., 499656., 100995.,  23855., 6391., 2821.};
  double NQCD[nqcdsamples] = { 86000., 78000., 104000., 96000., 100000., 102000., 112000., 102000.};


  const int nwsamples=11;
  TFile * W[nwsamples];
  W[0] = new TFile ("./root/et30_eta2.5/TDAna_W0w_tk3.root");
  W[1] = new TFile ("./root/et30_eta2.5/TDAna_W10w_tk3.root");
  W[2] = new TFile ("./root/et30_eta2.5/TDAna_W11w_tk3.root");
  W[3] = new TFile ("./root/et30_eta2.5/TDAna_W20w_tk3.root");
  W[4] = new TFile ("./root/et30_eta2.5/TDAna_W21w_tk3.root");
  W[5] = new TFile ("./root/et30_eta2.5/TDAna_W30w_tk3.root");
  W[6] = new TFile ("./root/et30_eta2.5/TDAna_W31w_tk3.root");
  W[7] = new TFile ("./root/et30_eta2.5/TDAna_W40w_tk3.root");
  W[8] = new TFile ("./root/et30_eta2.5/TDAna_W41w_tk3.root");
  W[9] = new TFile ("./root/et30_eta2.5/TDAna_W50w_tk3.root");
  W[10] = new TFile ("./root/et30_eta2.5/TDAna_W51w_tk3.root");
  double Wxs[nwsamples] = { 45000., 9200., 250., 2500., 225., 590., 100., 125., 40., 85., 40. };
  double NW[nwsamples] = { 88000., 40000., 100530., 99523., 105255., 79000., 
			   88258., 83038., 30796., 59022., 41865. };

  TFile * TTH = new TFile("./root/et30_eta2.5/TDAna_ttH_120_tk3.root");
  double TTHxs = 0.667 ;
  double NTTH = 62000.; // 1652000.; // 62000.;

  const int nttsamples=5;
  TFile * TT[nttsamples];
  TT[0] = new TFile("./root/et30_eta2.5/TDAna_TT0_tk3.root");
  TT[1] = new TFile("./root/et30_eta2.5/TDAna_TT1_tk3.root");
  TT[2] = new TFile("./root/et30_eta2.5/TDAna_TT2_tk3.root");
  TT[3] = new TFile("./root/et30_eta2.5/TDAna_TT3_tk3.root");
  TT[4] = new TFile("./root/et30_eta2.5/TDAna_TT4_tk3.root");
  // double TTxs[5] = { 619., 176., 34.,  6., 1.5 };  // from web
  double TTxs[nttsamples] = { 434., 162., 43., 10., 1.9 };     // from note
  double NTT[nttsamples] = { 57900., 66000., 98159., 14768., 5304. };

  double Lumfactor = 100000; // 100/fb of luminosity assumed in histograms

  TH1D * Histo_TOT[nvars];
  TH1D * Histo_TTH[nvars];
  TH1D * Histo_TOTS[nvars];
  TH1D * Histo_TTHS[nvars];
  for ( int i=0; i<nvars; i++ ) {
    cout << i << endl;
    TH1D * H = dynamic_cast<TH1D*>(TTH->Get(pippo[i]));
    double minx=H->GetBinLowEdge(1);
    double maxx=nbins*H->GetBinWidth(1);
    Histo_TOT[i] = new TH1D ( pippotot[i]," ", nbins, minx, maxx );
    Histo_TTH[i] = new TH1D ( pippotth[i]," ", nbins, minx, maxx );
    Histo_TOTS[i] = new TH1D ( pippototS[i]," ", nbins, minx, maxx );
    Histo_TTHS[i] = new TH1D ( pippotthS[i]," ", nbins, minx, maxx );
  }

  cout << "Starting loop on variables needing smoothing" << endl;

  // Loop on variables 
  // -----------------
  for ( int ivar=0; ivar<nvars; ivar++ ) {

    // Extract sum histograms with the right normalization and errors
    // --------------------------------------------------------------
    double totWW[nwsamples][nbins]={0.};
    double totW[nbins]={0.};
    double s2_totW[nbins]={0.};
    double totNW[nwsamples][nbins]={0.};
    for ( int i=0; i<nwsamples; i++ ) {
      cout << "Processing W file #" << i << " ..." << endl;
      TH1D * Histo = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]));
      TH1D * HistoW = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]+"W"));
      // For W, we need also total entries in histograms to add a
      // Poisson fluke contribution to total errors from matrix:
      // ----------------------------------------------------------
      TH1D * HistoN = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]+"N"));    
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	double t=Histo->GetBinContent(ibin);
	double s2t=HistoW->GetBinContent(ibin);
	double n=HistoN->GetBinContent(ibin);
	totWW[i][ibin-1]+=t*Wxs[i]/NW[i]*Lumfactor;
	s2_totW[ibin-1]+=s2t*pow(Wxs[i]/NW[i]*Lumfactor,2);
	totNW[i][ibin-1]+=n;
      }
    }
    // Once grandtotals of weights are computed for each bin, we can
    // add to the total s2 the Poisson contribution 1/sqrt(N) * T
    // -------------------------------------------------------------
    for ( int i=0; i<nwsamples; i++ ) {
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	totW[ibin-1]+=totWW[i][ibin-1];
	if ( totNW[i][ibin-1]>0 ) {
	  s2_totW[ibin-1]+=pow(totWW[i][ibin-1],2)/totNW[i][ibin-1];
	}
      }
    }
    
    double totWQCD[nqcdsamples][nbins]={0.};
    double totQCD[nbins]={0.};
    double s2_totQCD[nbins]={0.};
    double totNQCD[nqcdsamples][nbins]={0.};
    for ( int i=0; i<nqcdsamples; i++ ) {
      cout << "Processing QCD file #" << i << " ..." << endl;
      TH1D * Histo = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]));
      TH1D * HistoW = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]+"W"));
      // For QCD, we need also total entries in histograms to add a
      // Poisson fluke contribution to total errors from matrix:
      // ----------------------------------------------------------
      TH1D * HistoN = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]+"N"));    
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	double t=Histo->GetBinContent(ibin);
	double s2t=HistoW->GetBinContent(ibin);
	double n=HistoN->GetBinContent(ibin);
	totWQCD[i][ibin-1]+=t*QCDxs[i]/NQCD[i]*Lumfactor;
	s2_totQCD[ibin-1]+=s2t*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
	totNQCD[i][ibin-1]+=n;
      }
    }
    // Once grandtotals of weights are computed for each bin, we can
    // add to the total s2 the Poisson contribution 1/sqrt(N) * T
    // -------------------------------------------------------------
    for ( int i=0; i<nqcdsamples; i++ ) {
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	totQCD[ibin-1]+=totWQCD[i][ibin-1];
	if ( totNQCD[i][ibin-1]>0 ) {
	  s2_totQCD[ibin-1]+=pow(totWQCD[i][ibin-1],2)/totNQCD[i][ibin-1];
	}
      }
    }
    
    double totTT[nbins]={0.};
    double s2_totTT[nbins]={0.};
    for ( int i=0; i<nttsamples; i++ ) {
      cout << "Processing TT file #" << i << " ..." << endl;
      TH1D * Histo = dynamic_cast<TH1D*>(TT[i]->Get(pippo[ivar]));
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	double t=Histo->GetBinContent(ibin);
	totTT[ibin-1]+=t*TTxs[i]/NTT[i]*Lumfactor;
	s2_totTT[ibin-1]+=t*pow(TTxs[i]/NTT[i]*Lumfactor,2);
      }
    }
    double totTTH[nbins]={0.};
    double s2_totTTH[nbins]={0.};
    cout << "Processing TTH file " << " ..." << endl;
    TH1D * Histo = dynamic_cast<TH1D*>(TTH->Get(pippo[ivar]));
    for ( int ibin=1; ibin<=nbins; ibin++ ) {
      double t=Histo->GetBinContent(ibin);
      totTTH[ibin-1]+=t*TTHxs/NTTH*Lumfactor;
      s2_totTTH[ibin-1]+=t*pow(TTHxs/NTTH*Lumfactor,2);
    }
    
    // OK now fill total histograms
    // ----------------------------
    double total_sig=0.;
    double total_bgr=0.;
    double grandtot[nbins]={0.};
    double grandtote[nbins]={0.};
    for ( int ibin=1; ibin<=nbins; ibin++ ) {
      Histo_TTH[ivar]->SetBinContent(ibin,totTTH[ibin-1]);
      Histo_TTH[ivar]->SetBinError(ibin,sqrt(s2_totTTH[ibin-1]));
      Histo_TTHS[ivar]->SetBinContent(ibin,totTTH[ibin-1]);
      Histo_TTHS[ivar]->SetBinError(ibin,sqrt(s2_totTTH[ibin-1]));
      grandtot[ibin-1] = totQCD[ibin-1]+totTT[ibin-1]+totW[ibin-1];
      grandtote[ibin-1]= sqrt(s2_totQCD[ibin-1]+s2_totTT[ibin-1]+s2_totW[ibin-1]);
      Histo_TOT[ivar]->SetBinContent(ibin,grandtot[ibin-1]);
      Histo_TOT[ivar]->SetBinError(ibin,grandtote[ibin-1]);
      Histo_TOTS[ivar]->SetBinContent(ibin,grandtot[ibin-1]);
      Histo_TOTS[ivar]->SetBinError(ibin,grandtote[ibin-1]);
      total_sig+=totTTH[ibin-1];
      total_bgr+=grandtot[ibin-1];
    }

    // Pre-smoothing algorithm that levels down spikes
    // -----------------------------------------------
    double mean;
    double errmean;
    double delta_bgr=0.;
    for ( int ibin=0; ibin<nbins-2; ibin++ ) {
      double delta=fabs(grandtot[ibin]-grandtot[ibin+1]);
      if ( delta>3*grandtote[ibin] && grandtot[ibin]>0 ) {  // the signal is a bin way off from the previous
	// Avoid averaging with bins with large error
	if ( delta>3*grandtote[ibin+2] ) {
	  mean=(grandtot[ibin]+grandtot[ibin+2])/2.;
	  errmean=sqrt(pow(grandtote[ibin],2)+pow(grandtote[ibin+2],2))/2.;
	  cout << ivar << " " << ibin << " " << mean <<"+-" << errmean << " " << grandtot[ibin+1];
	  if ( mean>0 && fabs(grandtot[ibin+1]-mean)>3.*errmean ) {
	    delta_bgr += grandtot[ibin+1]-mean;
	    grandtot[ibin+1]=mean;
	    grandtote[ibin+1]=errmean;
	    cout << ": doing it " << mean << " " << errmean << " " << delta_bgr << endl;
	    cout << grandtot[ibin] << " " << grandtot[ibin+1] << " " << grandtot[ibin+2] << endl;
	  } else cout << ": not doing it." << endl;
	}
      }
    }
    // fix bin 0 if needed
    // -------------------
    mean=(grandtot[1]+grandtot[2])/2;
    errmean=sqrt(pow(grandtote[1],2)+pow(grandtote[2],2))/2.;
    if ( mean>0 & fabs(grandtot[0]-mean)>3.*errmean ) {
      delta_bgr += grandtot[0]-mean;
      grandtot[0]=mean;
      grandtote[0]=errmean;
    } 
    // fix last bin if needed
    // ----------------------
    mean=(grandtot[nbins-3]+grandtot[nbins-2])/2;
    errmean=sqrt(pow(grandtote[nbins-3],2)+pow(grandtote[nbins-2],2))/2;
    if ( mean>0 & fabs(grandtot[nbins-1]-mean)>3.*errmean ) {
      delta_bgr += grandtot[nbins-1]-mean;
      grandtot[nbins-1]=mean;
      grandtote[nbins-1]=errmean;
    } 
    // Renormalize bgr histogram
    // -------------------------
    cout << ivar << " " << ": delta=" << delta_bgr << endl;
    if ( delta_bgr>0 && total_bgr>delta_bgr ) {
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	Histo_TOTS[ivar]->SetBinContent(ibin,grandtot[ibin-1]*total_bgr/(total_bgr-delta_bgr));
	Histo_TOTS[ivar]->SetBinError(ibin,grandtote[ibin-1]*total_bgr/(total_bgr-delta_bgr));
      } 
    } 
    
    Histo_TOTS[ivar]->Smooth(1);
    Histo_TTHS[ivar]->Smooth(1);
    double sumtot=0.;
    double sumtth=0.;
    double sumtotS=0.;
    double sumtthS=0.;
    for ( int ibin=1; ibin<=nbins; ibin++ ) {
      sumtotS+=Histo_TOTS[ivar]->GetBinContent(ibin);
      sumtthS+=Histo_TTHS[ivar]->GetBinContent(ibin);
      sumtot+=Histo_TOT[ivar]->GetBinContent(ibin);
      sumtth+=Histo_TTH[ivar]->GetBinContent(ibin);
    }
    if ( sumtotS>0 ) Histo_TOTS[ivar]->Scale(1./sumtotS);
    if ( sumtthS>0 ) Histo_TTHS[ivar]->Scale(1./sumtthS);
    if ( sumtot>0 ) Histo_TOT[ivar]->Scale(1./sumtot);
    if ( sumtth>0 ) Histo_TTH[ivar]->Scale(1./sumtth);

  } // end of ivar loop

  cout << "Done, now plotting and writing histos." << endl;

  TString fname;
  fname="functionfile"+sel+".root";

  TFile * Smoothed = new TFile(fname,"RECREATE");
  Smoothed->cd();

  TCanvas * b1 = new TCanvas ("b1", "Kinematics comparison", 600, 600 );
  b1->Divide(3,3);
  for ( int ivar=0; ivar<9; ivar++ ) {
    b1->cd(ivar+1);
    Histo_TOTS[ivar]->SetMinimum(0.);
    Histo_TOTS[ivar]->Draw();
    Histo_TTHS[ivar]->SetLineColor(kBlue);
    Histo_TTHS[ivar]->Draw("PESAME");
  }
  b1->Print("./ps/Smooth_svsb_1.ps");
  TCanvas * b2 = new TCanvas ("b2", "Kinematics comparison", 600, 600 );
  b2->Divide(3,3);
  for ( int ivar=9; ivar<nvars; ivar++ ) {
    b2->cd(ivar-8);
    Histo_TOTS[ivar]->SetMinimum(0.);
    Histo_TOTS[ivar]->Draw();
    Histo_TTHS[ivar]->SetLineColor(kBlue);
    Histo_TTHS[ivar]->Draw("PESAME");
  }
  b2->Print("./ps/Smooth_svsb_2.ps");

  TCanvas * b3 = new TCanvas ("b3", "Kinematics comparison", 600, 600 );
  b3->Divide(3,3);
  for ( int ivar=0; ivar<9; ivar++ ) {
    b3->cd(ivar+1);
    Histo_TOT[ivar]->SetMinimum(0.);
    Histo_TOT[ivar]->SetLineColor(kRed);
    Histo_TOT[ivar]->Draw("PE");    
    Histo_TOTS[ivar]->Draw("PESAME");
    Histo_TOT[ivar]->Write();
    Histo_TTH[ivar]->Write();
    Histo_TOTS[ivar]->Write();
    Histo_TTHS[ivar]->Write();
  }
  b3->Print("./ps/Smooth_check_1.ps");
  TCanvas * b4 = new TCanvas ("b4", "Kinematics comparison", 600, 600 );
  b4->Divide(3,3);
  for ( int ivar=9; ivar<nvars; ivar++ ) {
    b4->cd(ivar-8);
    Histo_TOT[ivar]->SetMinimum(0.);
    Histo_TOT[ivar]->SetLineColor(kRed);
    Histo_TOT[ivar]->Draw("PE");    
    Histo_TOTS[ivar]->Draw("PESAME");
    Histo_TOT[ivar]->Write();
    Histo_TTH[ivar]->Write();
    Histo_TOTS[ivar]->Write();
    Histo_TTHS[ivar]->Write();
  }
  b4->Print("./ps/Smooth_check_2.ps");

  Smoothed->Close();

}
Пример #16
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();

   
       
}
Пример #17
0
void TP_eff_mu(TString fileName = "SingleMuon_Run2016_TP", // RooT file with TP otree for data 

 	  TString what = "IdIso", //what do you want to evaluated
 	  float iso = 0.1, //isolation cut to be used
	  float norm = 1 // luminosity normalization factor (1 for data) 
	  ) 
{

	gErrorIgnoreLevel = kFatal;

  // output inizialization 
  TString lepton = "Muon";
	TString OutFileName = fileName + "_" + lepton + "_" + what + "_IsoLt" + Form("%.2f", iso) + "_eff_Spring16";
	TFile * outputFile = new TFile(OutFileName+".root","recreate");

	// Title of axis in plots  
	TString yTitle = "Efficiency";
	TString xTitle = lepton+"  p_{T}[GeV]";
	TString xtit; 
	xtit = "m_{#mu#mu}[GeV]"; 

	//names of final graphs - suffix
	bool isData=false;
	if (fileName.Contains("SingleMuon")) isData = true;
  TString SampleName("_MC");
  if (isData) SampleName = "_Data";

  //open input file
	TFile * file = new TFile(fileName+".root");
  file->cd();
  TTree *t = (TTree*)(file->Get("TagProbe"));


  //binning inizialization

  int nEtaBins = 3;
	float etaBins[4] = {0,0.9,1.2,2.1};

	TString EtaBins[3] = {"EtaLt0p9",
				"Eta0p9to1p2",
				"EtaGt1p2"};

	float ptBins_def[8] = {10,15,20,25,30,40,60,1000};

	TString PtBins_def[7] = {"Pt10to15",
       "Pt15to20",
       "Pt20to25",
       "Pt25to30",
       "Pt30to40",
       "Pt40to60",
       "PtGt60"};

  float ptBinsTrig_def[17] = {10,
			  13,
			  16,
			  19,
			  22,
			  25,
			  28,
			  31,
			  34,
			  37,
			  40,
			  45,
			  50,
			  60,
			  70,
			  100,
				1000};

	TString PtBinsTrig_def[16] = {"Pt10to13",
		    "Pt13to16",
		    "Pt16to19",
		    "Pt19to22",
		    "Pt22to25",
		    "Pt25to28",
		    "Pt28to31",
		    "Pt31to34",
		    "Pt34to37",
		    "Pt37to40",
		    "Pt40to45",
		    "Pt45to50",
		    "Pt50to60",
		    "Pt60to70",
		    "Pt70to100",
		    "PtGt100"};

	int nPtBins = 16; if(what == "IdIso") nPtBins = 7;
	float * ptBins = new float[nPtBins+1];
	TString * PtBins = new TString[nPtBins];

	if(what == "IdIso"){
		for(int i=0; i<nPtBins; ++i){
			ptBins[i] = ptBins_def[i];
			PtBins[i] = PtBins_def [i];
		}
		ptBins[nPtBins] = ptBins_def[nPtBins];
	} else {
		for(int i=0; i<nPtBins; ++i){
			ptBins[i] = ptBinsTrig_def[i];
			PtBins[i] = PtBinsTrig_def[i];
		}
		ptBins[nPtBins] = ptBinsTrig_def[nPtBins];
	}


  //	create eta histogram with eta ranges associated to their names (eg. endcap, barrel)   ***** //

	TH1D * etaBinsH = new TH1D("etaBinsH", "etaBinsH", nEtaBins, etaBins);
  etaBinsH->Draw();
  etaBinsH->GetXaxis()->Set(nEtaBins, etaBins);
  for (int i=0; i<nEtaBins; i++){ etaBinsH->GetXaxis()->SetBinLabel(i+1, EtaBins[i]);}
  etaBinsH->Draw();


	//	create pt histogram_s with pt ranges associated to their names (eg. Pt10to13, ..)   ***** //

	TH1D * ptBinsH =  new TH1D("ptBinsH", "ptBinsH", nPtBins, ptBins);
  ptBinsH->Draw();
  ptBinsH->GetXaxis()->Set(nPtBins, ptBins);
  for (int i=0; i<nPtBins; i++){ ptBinsH->GetXaxis()->SetBinLabel(i+1, PtBins[i]);}
  ptBinsH->Draw();

  float ptBins_edges[nPtBins+1];

	for (int i=0; i<nPtBins; i++) { ptBins_edges[i]=ptBinsH->GetBinLowEdge(i+1); }
	ptBins_edges[nPtBins]= ptBinsH->GetBinLowEdge(nPtBins+1); 

  
	// define if in the fit of failing probes
  // the FSR component will be used in the 
  // signal function 
  bool fitWithFSR[nPtBins];

  for (int i=0; i<nPtBins; i++)  fitWithFSR[i] = true;

  if(what == "IdIso"){
   	fitWithFSR[0]=false;
    fitWithFSR[1]=false;
    fitWithFSR[5]=false;
    fitWithFSR[6]=false;
  } else{ for (int i=0; i<nPtBins; i++)  fitWithFSR[i] = false; }

	// building the histogram base name
  TString prefix = "ZMass";
  TString which = what; 
  if (what == "IdIso") which = "";
  which = "";
  TString histBaseName; 

  //definition of the passing and failing criterias

  TCut cut_flag_idiso_pass, cut_flag_hlt_pass, cut_flag_hlt_fail, cut_pt, cut_eta;

  if (what == "IdIso") {
  	cut_flag_idiso_pass = Form("id_probe == 1 && iso_probe < %f", iso);
  } else{
  		if(what == "hlt_1") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_1_probe == 0"; }
  		if(what == "hlt_2") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_2_probe == 0"; }
  		if(what == "hlt_3") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_3_probe == 0"; }
  		if(what == "hlt_4") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_4_probe == 0"; }
  		if(what == "hlt_5") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_5_probe == 0"; }
  		if(what == "hlt_6") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_6_probe == 0"; }
  		if(what == "hlt_7") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_7_probe == 0"; }
  		if(what == "hlt_8") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_8_probe == 0"; }
  		if(what == "hlt_9") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_9_probe == 0"; }
  		if(what == "hlt_10") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_10_probe == 0"; }
  		if(what == "hlt_11") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_11_probe == 0"; }
  		if(what == "hlt_12") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_12_probe == 0"; }
  		if(what == "hlt_13") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_13_probe == 0"; }
  		if(what == "hlt_14") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_14_probe == 0"; }
  		if(what == "hlt_15") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_15_probe == 0"; }
  		if(what == "hlt_16") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_16_probe == 0"; }
  		if(what == "hlt_17") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_17_probe == 0"; }
  		if(what == "hlt_18") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_18_probe == 0"; }
  		if(what == "hlt_19") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_19_probe == 0"; }
  		if(what == "hlt_20") {cut_flag_hlt_pass = "******"; cut_flag_hlt_fail = "hlt_20_probe == 0"; }
  	}

  //Definition of the output directory names and creation of it
	TString dir_name = "Muon_";
	dir_name += what;
	dir_name += Form("_IsoLt%.2f", iso);
	if (!isData) dir_name += "_MC";
	dir_name += "_eff";
	gSystem->mkdir(dir_name, kTRUE);

	for (int iEta = 0; iEta < nEtaBins; iEta++) { //loop on eta bins

		histBaseName = prefix+which+EtaBins[iEta];

		//eta cuts
		cut_eta = Form("abs(eta_probe)>= %f && abs(eta_probe)< %f", etaBins[iEta], etaBins[iEta+1]);

		TH1F * numeratorH   = new TH1F("numeratorH","",nPtBins,ptBins_edges);
		TH1F * denominatorH = new TH1F("denominatorH","",nPtBins,ptBins_edges);
	
	  for (int iPt=0; iPt<nPtBins; ++iPt) { //loop on pt bins

	  	//pt cuts
	  	cut_pt = Form("pt_probe > %f && pt_probe < %f", ptBins[iPt], ptBins[iPt+1]);

	  	TH1F * histPassOld = new TH1F("histPassOld","",250,50,300);
	  	TH1F * histFailOld = new TH1F("histFailOld","",250,50,300);
	  	
	  	//Drawing histogram of passing and failing probes
	  	if (what == "IdIso") {
		  	t->Draw("m_vis>>histPassOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_idiso_pass));
		  	t->Draw("m_vis>>histFailOld", "pu_weight*mcweight" + (cut_eta && cut_pt && !cut_flag_idiso_pass));
		  }else{
		  	t->Draw("m_vis>>histPassOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_hlt_pass && cut_flag_idiso_pass));
		  	t->Draw("m_vis>>histFailOld", "pu_weight*mcweight" + (cut_eta && cut_pt && cut_flag_hlt_fail && cut_flag_idiso_pass));
		  }

	  	int nBinsX = histPassOld->GetNbinsX();

	  	//lumi renormalization
	    for (int iB=1;iB<=nBinsX;++iB) {
	      histPassOld->SetBinContent(iB,norm*histPassOld->GetBinContent(iB));
	      histPassOld->SetBinError(iB,norm*histPassOld->GetBinError(iB));
	      histFailOld->SetBinContent(iB,norm*histFailOld->GetBinContent(iB));
	      histFailOld->SetBinError(iB,norm*histFailOld->GetBinError(iB));
	    }

	    float output[2];
	    TCanvas * c1 = new TCanvas("c1","",700,600);
	    TCanvas * c2 = new TCanvas("c2","",700,600);


	    //defining fit options
	    bool fitPass = true; 
	    bool fitFail = true;
	    bool rebinPass = false;
	    bool rebinFail = false;
	    if(what != "IdIso") {fitPass= false; fitFail = false;}

	    //fitting
	    FitPassAndFail(fileName,
	    	histBaseName+PtBins[iPt],
	    	xtit,
	    	histPassOld,
	    	histFailOld,
	    	fitPass,
	    	fitFail,
	    	fitWithFSR[iPt],
	    	rebinPass,
	    	rebinFail,
	    	c1,
	    	c2,
	    	output,
	    	dir_name);


	    c1->cd();
	    c1->Update();
	    c2->cd();
	    c2->Update();
	    numeratorH->SetBinContent(iPt+1,output[0]);
	    denominatorH->SetBinContent(iPt+1,output[0]+output[1]);

	  }

	  outputFile->cd();

	  //produce efficiencies plot
	  TGraphAsymmErrors * eff = new TGraphAsymmErrors();
	  eff->Divide(numeratorH,denominatorH);

	  eff->GetXaxis()->SetTitle(xTitle);
	  //  eff->GetXaxis()->SetRangeUser(10.01,59.99);
	  eff->GetYaxis()->SetRangeUser(0,1.0);
	  eff->GetXaxis()->SetRangeUser(0,99.99);
	  eff->GetYaxis()->SetTitle(yTitle);
	  eff->GetXaxis()->SetTitleOffset(1.1);
	  eff->GetXaxis()->SetNdivisions(510);
	  eff->GetYaxis()->SetTitleOffset(1.1);
	  eff->SetMarkerStyle(21);
	  eff->SetMarkerSize(1);
	  eff->SetMarkerColor(kBlue);
	  eff->SetLineWidth(2);
	  eff->SetLineColor(kBlue);
	  if(!isData){
	  	eff->SetMarkerColor(kRed);
	  	eff->SetLineColor(kRed);
	  }


	  TCanvas * canv = new TCanvas("canv","",700,600);
	  eff->Draw("APE");
	  canv->SetGridx();
	  canv->SetGridy();
	  canv->Update();

	  canv->SaveAs(dir_name + "/" + fileName+"_" + histBaseName + ".png");
	  eff->Write(histBaseName+SampleName);

/*	  for(int ip=0; ip<nPtBins; ++ip){
		cout<<"PtBins "<<ip<<" content: "<<numeratorH->GetBinContent(ip)/ denominatorH->GetBinContent(ip)<<endl;
	}*/

	}

	//closing
	outputFile->cd(); 
	etaBinsH->Write();
	outputFile->Close();

}
void ProcYields::Proc_hPhi(hel_t hel/*=UNPOL*/){
	Info(TString::Format("Proc_hPhi(%s)",helTitle[hel].Data()), "");

	TDirectory* dir_phi=NULL;
	if (hel==UNPOL)	{
		dir_phi = _dirQ2W->mkdir("hPhi");
	}else if(hel==POS||hel==NEG){
		dir_phi = _dirQ2W->mkdir(TString::Format("hPhi_%s",helTitle[hel].Data()));
	}

	TDirectory* dir_varset=NULL;
	for (Int_t iVarset=0;iVarset<nVARSET;iVarset++){
		dir_varset = dir_phi->mkdir(TString::Format("Varset%d", iVarset+1));
		dir_varset->cd();
		
		//!Get relevent h5D
		THnSparse* hY5D = NULL;
		if (hel==UNPOL)	{
			hY5D = (THnSparseF*)_dirQ2W->Get(TString::Format("hY5D/Varset%d/hY5D_FULL",iVarset+1));
			//! To make hphi from TH evts//hY5D = (THnSparseF*)_dirQ2W->Get(TString::Format("hY5D/Varset%d/hY5D_TH",iVarset+1));
		}else if (hel==POS||hel==NEG){
			hY5D = (THnSparseF*)_dirQ2W->Get(TString::Format("hY5D_%s/Varset%d/hY5D_FULL",helTitle[hel].Data(),iVarset+1));
			//! To make hphi from TH evts//hY5D = (THnSparseF*)_dirQ2W->Get(TString::Format("hY5D_%s/Varset%d/hY5D_TH",helTitle[hel].Data(),iVarset+1));
		}

		int nphibins = hY5D->GetAxis(PHI)->GetNbins();
		float phimin = hY5D->GetAxis(PHI)->GetXmin();
		float phimax = hY5D->GetAxis(PHI)->GetXmax();
		TH1D* hsinphi = new TH1D("hsinphi", "hsinphi", nphibins, phimin, phimax);
		for (int ibin = 0; ibin < hsinphi->GetNbinsX(); ibin++){
			Double_t phi = hsinphi->GetBinLowEdge(ibin+1) * TMath::DegToRad();
			hsinphi->SetBinContent(ibin+1, TMath::Sin(phi));
			hsinphi->SetBinError(ibin+1, 0);
		}

		//! Make hRvVar for each Var
		TDirectory* dir_var=NULL;
		for(Int_t iVar=0; iVar<nVAR; iVar++){
			if (iVar==ALPHA || iVar==PHI) continue; 
			dir_var = dir_varset->mkdir(varName[iVar].Data());
			dir_var->cd();

			//! Create hRvVar
			int nvarbins = hY5D->GetAxis(iVar)->GetNbins();
			float varmin = hY5D->GetAxis(iVar)->GetXmin();
			float varmax = hY5D->GetAxis(iVar)->GetXmax();
			//printf("numphibins:numvarbins = %d, %d\n", nphibins,nvarbins);
			TString xtitle = TString::Format("%s", varTitle[iVarset][iVar].Data());
			TString ytitle = TString::Format("hPR");
			TString title = TString::Format("%s vs %s [h=%s] %s", ytitle.Data(), xtitle.Data(), helTitle[hel].Data(), _Q2Wdirname);
			TH1F* hRvVar = new TH1F("hRvVar",title, nvarbins, varmin, varmax);
			hRvVar->SetXTitle(xtitle);
			hRvVar->SetYTitle(ytitle);

			//! Loop over number of bins in Var and make phi projections for each
			if (iVar==M1 || iVar==M2){
				for (int ivarbin=0; ivarbin<5; ivarbin++){
					hRvVar->SetBinContent(ivarbin+1, 20);
				}
			}else{
				for (int ivarbin=0; ivarbin<nvarbins; ivarbin++){
					Float_t varbin_lowedge = hY5D->GetAxis(iVar)->GetBinLowEdge(ivarbin+1);
					Float_t varbin_highedge = varbin_lowedge + hY5D->GetAxis(iVar)->GetBinWidth(ivarbin+1);
					//! Create Phi projection histogram
					hY5D->GetAxis(iVar)->SetRange(ivarbin+1, ivarbin+1);
					TH1D* hphi = (TH1D*)hY5D->Projection(PHI,"E");
					hphi->Sumw2();
					TString name = TString::Format("hphi_proj_%02d",ivarbin+1);
					TString title = TString::Format("#phi projection for %s = [%.2f,%.2f) | h=%s | top=%s | q2w = %s", 
						                            varTitle[iVarset][iVar].Data(), varbin_lowedge, varbin_highedge,
						                            helTitle[hel].Data(), _topList.Data(), _Q2Wdirname);
					hphi->SetName(name);
					hphi->SetTitle(title);


					//! Obtain Lum and VgFlux normalized Phi distribution
					float vgflux = getvgflux(_Wlow,_Q2low);
      				float factor = 1000000000;
      				float norm = LUM*vgflux*_user.Q2binw*_user.Wbinw*factor;
      				printf("[Wlow:Q2low:Q2binw:Wbinw]= %f:%f:%f:%f\n",_Wlow,_Q2low,_user.Q2binw,_user.Wbinw);
      				printf("norm = %f\n", norm);
      				TH1D* hphinorm = (TH1D*)hphi->Clone(name+"_norm");
      				hphinorm->Scale(1/norm);

					//! Apply Method 2. and obtain R
					/*TH1D* hphi_sinphi = (TH1D*)hphi->Clone(TString::Format("hphi_sinphi%d", ivarbin+1));
					hphi_sinphi->Multiply(hsinphi);*/
					TH1D* hphinorm_sinphi = (TH1D*)hphinorm->Clone(TString::Format("hphinorm_sinphi%d", ivarbin+1));
					hphinorm_sinphi->Multiply(hsinphi);


					Double_t integerr = 0.0;
					//! Note how Underflow and Overflow bins are explicity avoided when calling TH1::IntegralAndError()
					//Double_t integ = hphi_sinphi->IntegralAndError(1, hphi_sinphi->GetNbinsX(), integerr);
					Double_t integ = hphinorm_sinphi->IntegralAndError(1, hphinorm_sinphi->GetNbinsX(), integerr);
					hRvVar->SetBinContent(ivarbin+1, integ/TMath::Pi());
					hRvVar->SetBinError(ivarbin+1, integerr);
				}
			}
			
		}//end nVAR loop
	}//end nVARSET loop
	Info(TString::Format("Proc_hPhi(%s)",helTitle[hel].Data()), "done\n");
}
Пример #19
0
void DetermineAnchorsPP(const Char_t* inputDir, TString lPeriodName = "LHC18f", Int_t runNo, const Char_t* chunkName = "", Bool_t automaticMode=kFALSE) {
   //
   // In automatic mode the function does not request any standard input and creates anchor points if the fit was ok
   // using the anchor value determined automatically.
   // One must check the QA plots for individual run to make sure the automatic values are fine and eventually run this 
   // function again in manual mode.
   //
   
    Bool_t lUseDefaultAnchorPercentile = kFALSE;
    Double_t  lDefaultAnchorPercentile = 0.10;
    Double_t  lMinimumAnchorPercentile = 0.05;

    // open minimum bias OADB file
    TString lOADBfile = Form("OADB-%s-MB.root", lPeriodName.Data());

    cout << "Opening minimum bias info ... " << endl;
    TFile *foadb = new TFile( lOADBfile.Data(), "READ" );
    AliOADBContainer *lOADBcontainer = (AliOADBContainer*)foadb->Get("MultSel");

    // set percentile boundaries for the estimator histos
    // (based on what is implemented in the calibration)
    Double_t lDesiredBoundaries[1000];
    Long_t   lNDesiredBoundaries=0;
    lDesiredBoundaries[0] = 0.0;
    //From High To Low Multiplicity
    for( Int_t ib = 1; ib < 101; ib++) { // 100 bins  ] 0.0 , 0.1 ]
      lNDesiredBoundaries++;
      lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] + 0.01;
    }
    for( Int_t ib = 1; ib < 91; ib++) { // 90 bins ] 1.0 , 10. ]
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] + 0.1;
    }
    for( Int_t ib = 1; ib < 91; ib++) { // 90 bins ] 10.0 , 100.0 ]
        lNDesiredBoundaries++;
        lDesiredBoundaries[lNDesiredBoundaries] = lDesiredBoundaries[lNDesiredBoundaries-1] + 1.0;
    }
    
    FILE *fap = 0x0;

    // auxiliary objects
    TLegend *legEstimator = 0x0;
    //
    TLine *anchorLine = new TLine();
    anchorLine->SetLineStyle(2);
    //
    TLatex *latex = new TLatex();
    latex->SetTextFont(42);
    latex->SetTextSize(0.025);

    // constant function for the scaling factor determination
    TF1 *fpol0 = new TF1("fpol0", "[0]", 0.005, lMinimumAnchorPercentile);
    fpol0->SetLineStyle(3);
    fpol0->SetLineWidth(1);
    fpol0->SetLineColor(kBlack);
    TF1 *fpol0_hi = (TF1*)fpol0->Clone("fpol0_hi");
    TF1 *fpol0_lo = (TF1*)fpol0->Clone("fpol0_lo");
    //
    Int_t npar = 3;
    TF1 *fturnon = new TF1("fturnon", func_turnon, 0., 1., npar);
    fturnon->SetParameters(1., 0.1, -1.);
    fturnon->SetParLimits(1, lMinimumAnchorPercentile, 1.0);
    fturnon->SetParLimits(2, -1.e15, 0.);
    fturnon->SetLineColor(1);

    // open input AnalysisResults.root file for the VHM sample
    TString fileIdentifier = Form("%d", runNo);
    if(chunkName[0]!='\0') fileIdentifier = chunkName;
    TFile *fin = TFile::Open(Form("%s/AnalysisResults_%s.root", inputDir, fileIdentifier.Data()), "READ");
    TTree *treeEvent = (TTree*)fin->Get("MultSelection/fTreeEvent");

    cout << "   - run number....................: " << runNo << endl;

    // define estimator histo for this run
    TH1D* hEstimator = new TH1D(Form("hEstimator_%d", runNo), "", lNDesiredBoundaries, lDesiredBoundaries);
    hEstimator->Sumw2();
    hEstimator->GetXaxis()->SetTitle("V0M Percentile");
    hEstimator->GetYaxis()->SetTitle("Counts");
    hEstimator->SetStats(0);
    hEstimator->SetLineColor(kRed);

    // get corresponding calibration histogram from OADB
    AliOADBMultSelection* lOADB = (AliOADBMultSelection*)lOADBcontainer->GetObject( runNo, "Default" );
    if( (Int_t)lOADBcontainer->GetIndexForRun( runNo )<0 ) {
      cout << "   ---> Warning: no calibration histo found for this run - skipping..." << endl;
      return;
    }

    // set the pointer to the calib histo for this run
    hCalib = (TH1D*)lOADB->GetCalibHisto( "hCalib_V0M" );;
    //
    Double_t nall = treeEvent->Draw(Form("get_percentile(fAmplitude_V0A+fAmplitude_V0C)>>hEstimator_%d", runNo), 
                                        Form("fRunNumber==%d && fEvSel_Triggered && fEvSel_IsNotPileupInMultBins && fEvSel_PassesTrackletVsCluster && fEvSel_INELgtZERO && fEvSel_HasNoInconsistentVertices && TMath::Abs(fEvSel_VtxZ)<=10.0 && isSelectedHM(fEvSel_TriggerMask)", runNo),
                                        "goff"); 

    hEstimator->Scale(1., "width");
    Double_t nevents = (Double_t)hEstimator->GetEntries();
    cout << "   - number of events (selected)...: " << nevents << endl;

    // draw histogram
    TCanvas *cEstimator = new TCanvas(Form("cEstimator_%d", runNo), "Estimator Distribution", 10, 10, 1000, 750);
    cEstimator->SetRightMargin(0.05);
    cEstimator->SetTopMargin(0.11);

    hEstimator->GetXaxis()->SetRangeUser(0., 0.2);
    hEstimator->Draw("hist e0");
    latex->SetNDC();
    latex->SetTextSize(0.06);
    latex->DrawLatex(0.1, 0.93, Form("Run: %d", runNo));

    // first, fit a pol0 in the flat region (usually up to 0.05)
    hEstimator->Fit(fpol0, "RQ0");
    Double_t flat_top = fpol0->GetParameter(0);

    // get standard deviantion of bin contents in the flat region
    Double_t flat_top_stdev = 0.;
    for(Int_t ibin=1; ibin<=hEstimator->FindBin(lMinimumAnchorPercentile); ++ibin) {
      Double_t content = hEstimator->GetBinContent(ibin);
      Double_t   width = hEstimator->GetBinWidth(ibin);
      flat_top_stdev += TMath::Power((content-flat_top), 2.)*width;
    }
    flat_top_stdev = TMath::Sqrt(flat_top_stdev/lMinimumAnchorPercentile) / 2.;
    fpol0_hi->SetParameter(0, flat_top+flat_top_stdev);
    fpol0_lo->SetParameter(0, flat_top-flat_top_stdev);
        
    // now, fix the constant parameter in the turnon function
    fturnon->SetParameters(1., 0.1, -1.);
    fturnon->FixParameter(0, flat_top);
        
    // get the maximum range to perform the fit
    Double_t range_max = (hEstimator->GetBinLowEdge(hEstimator->FindLastBinAbove())) / 1.8;
    fturnon->SetRange(0.005, (range_max>0.1) ? range_max : 0.1);

    // get anchor percentile
    Double_t anchor_percentile = -1.;
    TString fitstatus = "";
    if(nevents>0) {
      TFitResultPtr fitr = hEstimator->Fit(fturnon, "RQM");
      fturnon->Draw("lsame");
      fitstatus = gMinuit->fCstatu;
    }
    cEstimator->Flush();
    cEstimator->Update();
    cout << "   - fit status....................: " << fitstatus << endl;
    if( !fitstatus.Contains("OK") ) {
      if(gROOT->IsBatch()) {
         cout << "   ---> Warning: fit failed! -- skipping this run..." << endl;
         if(!automaticMode) {
            fap = fopen(Form("temp/anchors/Anchor_%s_%d_VHM.txt", lPeriodName.Data(), runNo), "w");
            fprintf(fap, "%d %d %.2lf %lf\n", runNo, runNo, -1., -1.);
         }
         return;
      }
      
      if(!automaticMode) {
         cout << "   - Please, provide an anchor percentile to continue: " << endl;
         cout << "     (entering a negative value will skip this run)" << endl;
         cout << "     >>>> anchor percentile: "; 
         cin >> anchor_percentile;
         if(anchor_percentile<0.) {
            cout << "   ---> Warning: percentile provided is negative -- skipping this run..." << endl;
            fap = fopen(Form("temp/anchors/Anchor_%s_%d_VHM.txt", lPeriodName.Data(), runNo), "w");
            fprintf(fap, "%d %d %.2lf %lf\n", runNo, runNo, -1., -1.);
            return;
         }
      }
      else return;      // in automatic mode we do not create an anchor file
Пример #20
0
void drawQual(TFile * inf, TCanvas * can, Int_t ic, Float_t ymin, Float_t ymax, Int_t doLog, Float_t xmin=0, Float_t xmax=0)
{
	cout << "ic: " << ic << " ymin: " << ymin << " ymax " << ymax << " xmin " << xmin	<< " xmax " << xmax << endl;
	TH3F * hQual3D_precut_mc = (TH3F*)inf->FindObjectAny(Form("hTrkQual%dPreCut3D_mc80_c0to36",ic));
	TH3F * hQual3D_precut_data = (TH3F*)inf->FindObjectAny(Form("hTrkQual%dPreCut3D_dataj35_c0to36",ic));
	cout << hQual3D_precut_mc->GetName() << ": " << hQual3D_precut_mc << endl;
	cout << hQual3D_precut_data->GetName() << ": " << hQual3D_precut_data << endl;
	TH1D * hPtBin = (TH1D*)hQual3D_precut_data->Project3D("y");
	TH1D * hQual_precut_mc[10][8], * hQual_precut_data[10][8];
	Int_t colors[10] = {kBlack, kGray+2, kBlue+2,kCyan+2,kGreen+2,kYellow+2,kOrange+2,kRed};
	
	Int_t rebinFactor=2;
	for (Int_t p=0; p<=9; ++p){
		for (Int_t c=0; c<=7; ++c) {
			Int_t ptBin=p;
			Int_t cBin=c;
			hQual3D_precut_mc->GetYaxis()->SetRange(ptBin,ptBin);
			//hQual3D_precut_mc->GetZaxis()->SetRange(cBin,cBin+5);
			hQual3D_precut_data->GetYaxis()->SetRange(ptBin,ptBin);
			//hQual3D_precut_data->GetZaxis()->SetRange(cBin,cBin+5);

			hQual_precut_mc[p][c] = (TH1D*)hQual3D_precut_mc->Project3D("x");
			hQual_precut_mc[p][c]->SetName(Form("%s_p%d_c%d",hQual3D_precut_mc->GetName(),ptBin,cBin));
			hQual_precut_data[p][c] = (TH1D*)hQual3D_precut_data->Project3D("x");
			hQual_precut_data[p][c]->SetName(Form("%s_p%d_c%d",hQual3D_precut_data->GetName(),ptBin,cBin));
			//cout << Form("Project data %d: %.1f-%.1f GeV/c: ",ptBin, hPtBin->GetBinLowEdge(ptBin),hPtBin->GetBinLowEdge(ptBin+1)) << hQual_precut_data[p][c]->GetEntries() << endl;
			//rebin
			hQual_precut_data[p][c]->Rebin(rebinFactor);
			hQual_precut_mc[p][c]->Rebin(rebinFactor);
			// styles
			hQual_precut_mc[p][c]->SetMarkerColor(kRed-9);
			hQual_precut_mc[p][c]->SetLineColor(kRed-9);
			hQual_precut_mc[p][c]->SetMarkerStyle(kOpenSquare);
			hQual_precut_mc[p][c]->SetFillStyle(3001);
			hQual_precut_mc[p][c]->SetFillColor(kRed-9);
			hQual_precut_data[p][c]->SetMarkerColor(colors[c]);
			hQual_precut_mc[p][c]->Scale(1./hQual_precut_mc[p][c]->GetEntries()/rebinFactor);
			hQual_precut_data[p][c]->Scale(1./hQual_precut_data[p][c]->GetEntries()/rebinFactor);
			// set title
			fixedFontHist(hQual_precut_mc[p][c]);
			fixedFontHist(hQual_precut_data[p][c]);
			hQual_precut_mc[p][c]->SetYTitle("unit normalization");
			hQual_precut_data[p][c]->SetYTitle("unit normalization");
			// set axis
			if(xmin!=xmax) {
				hQual_precut_mc[p][c]->SetAxisRange(xmin,xmax,"X");
				hQual_precut_data[p][c]->SetAxisRange(xmin,xmax,"X");
			}
			hQual_precut_mc[p][c]->SetAxisRange(ymin,ymax,"Y");
			hQual_precut_data[p][c]->SetAxisRange(ymin,ymax,"Y");
		}
	}
	
	//can->Divide(5,1);
	Int_t centBin=0;
	Int_t ipad=1;
	for (Int_t p=3; p<=7; ++p) {
		can->cd(ipad);
		if (doLog==1) gPad->SetLogy();
		Int_t ptBin=p;
		cout << "ptBin: " << ptBin << endl;
		handsomeTH1(hQual_precut_data[ptBin][centBin]);
		hQual_precut_data[ptBin][centBin]->Draw("E");
		hQual_precut_mc[ptBin][centBin]->Draw("histsame");
		hQual_precut_data[ptBin][centBin]->Draw("Esame");
		cout << Form("%.1f-%.1f GeV/c: ",hPtBin->GetBinLowEdge(ptBin),hPtBin->GetBinLowEdge(ptBin+1)) << hQual_precut_data[ptBin][centBin]->GetEntries() << endl;
		++ipad;
	}
	can->cd(1);
  //TLegend *legdata = new TLegend(0.19,0.71,0.49,0.90);
  TLegend *legdata = new TLegend(0.26,0.72,0.56,0.92);
  legdata->SetFillStyle(0);
  legdata->SetBorderSize(0);
  legdata->SetTextSize(0.035);
	legdata->AddEntry(hQual_precut_data[0][0],"0-90%","");
  legdata->AddEntry(hQual_precut_data[0][0],"Data Jet35U","p");
  legdata->AddEntry(hQual_precut_mc[0][0],"MC, #hat{p}_{T} 80 GeV/c","p");
	legdata->Draw();
	
	ipad=1;
	for (Int_t p=3; p<=7; ++p) {
		can->cd(ipad);
		Int_t ptBin=p;
		cout << "ptBin leg: " << ptBin << endl;
		Float_t px=0.4,py=0.88;
		if (ipad==1) px=0.63;
		drawText(Form("%.1f - %.1f GeV/c",hPtBin->GetBinLowEdge(ptBin),hPtBin->GetBinLowEdge(ptBin+1)),px,py);
		++ipad;
	}
}
Пример #21
0
void Z0AccEff(int isData = 2, int yieldInt = 1, int iSpec = 3, int Weight =1)
{
  ////////  definitions of Switches   ///////////
  //  isData = 1 for Data
  //  isData = 2 for Simulation
  
    
  // iSpec = 1  pT spectra
  // iSpec = 2  Y spectra
  // iSpec = 3  Centrality Spectra
  
  //Weight = 1 for weighted histo
  //weight = 0  for non weighted histo



  ////////////////////////////////////////////////////////////
  gStyle->SetOptStat(0);
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0000); 

  // Fit ranges
  float mass_low, mass_high, mlow, mhigh;
  int nrebin;
  bool isLog, isFit;
  double MassZ0, WidthZ0;

  // High Mass range
  MassZ0 = 91.1876; WidthZ0 = 2.4952;
  mass_low = 60; mass_high = 120;  // Fit ranges Glb Glb
  //mass_low = 40; mass_high = 140;  // Fit ranges STA
  mlow = 0.0; mhigh = 200.0; nrebin = 80; isLog =0; isFit = 0; // draw ranges
  
  int whis = 1; // 1 for full all eta, 2 for barrel  //4 for trigger matched PAT
  
  //file one is good file

  TFile *fil1, *fil2;

  if (isData == 2) fil2 = new TFile("Z0_DataMixPt50_PatDiMuonPlots_All11Dec.root");
  //if (isData == 2) fil2 = new TFile("ReReco_DM_DiMuonPlot_All16Dec.root");
  if (isData == 2)  fil1 = new TFile("Z0HydPt50_PatDiMuonPlots_AllWOSel12Dec.root");

  // Pt bin sizes
  int Nptbin=1;
  double pt_bound[100] = {0};
  
  if(iSpec == 1) { 
    Nptbin = 3;
    pt_bound[0] = 0.0; pt_bound[1] = 6.0;
    pt_bound[2] = 12.0; pt_bound[3] = 100.0;
    
    if(isData == 2) {
      Nptbin = 25;
      // pt_bound[100] = {0.0,100.0,12.0,100.0};
      pt_bound[0] = 0;
      pt_bound[1] = 2;
      pt_bound[2] = 4;
      pt_bound[3] = 6;
      pt_bound[4] = 8;
      pt_bound[5] = 10;
      pt_bound[6] = 12;
      pt_bound[7] = 14;
      pt_bound[8] = 16;
      pt_bound[9] = 18;
      pt_bound[10] = 20;
      pt_bound[11] = 22;
      pt_bound[12] = 24;
      pt_bound[13] = 26;
      pt_bound[14] = 28;
      pt_bound[15] = 30;
      pt_bound[16] = 32;
      pt_bound[17] = 34;
      pt_bound[18] = 36;
      pt_bound[19] = 38;
      pt_bound[20] = 40;
      pt_bound[21] = 42;
      pt_bound[22] = 44;
      pt_bound[23] = 46;
      pt_bound[24] = 48;
      pt_bound[25] = 50;
    }
  }
  
  // Y bin sizes
  if(iSpec == 2) {
    Nptbin = 10;
    // pt_bound[100] = {-2.4,-1.0,-0.5,0.5,1.0,2.4}; 
    // pt_bound[100] = {-2.4,-1.0,-0.5,0.5,1.0,2.4}; 
    // pt_bound[100] = {-2.4,-2.1,-1.6,-1.1,-0.6,0,0.6,1.1,1.6,2.1,2.4}; 
    pt_bound[0] = -2.4; 
    pt_bound[1] = -2.1; 
    pt_bound[2] = -1.6; 
    pt_bound[3] = -1.1; 
    pt_bound[4] = -0.6; 
    pt_bound[5] =  0.0; 
    pt_bound[6] = 0.6; 
    pt_bound[7] = 1.1; 
    pt_bound[8] = 1.6; 
    pt_bound[9] = 2.1; 
    pt_bound[10] = 2.4; 

  }
  
  if(iSpec == 3) {
    if(isData == 2) { 
      Nptbin = 9;
      pt_bound[0] = 0.0;
      pt_bound[1] = 4.0;
      pt_bound[2] = 8.0;
      pt_bound[3] = 12.0;
      pt_bound[4] = 16.0;
      pt_bound[5] = 20.0;
      pt_bound[6] = 24.0;
      pt_bound[7] = 28.0;
      pt_bound[8] = 32.0;
      pt_bound[9] = 40.0;
    }
  }
  
  double PT[100], DelPT[100], mom_err[100];
  for (Int_t ih = 0; ih < Nptbin; ih++) {
    PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0;
    DelPT[ih] = pt_bound[ih+1] - pt_bound[ih];
    mom_err[ih] = DelPT[ih]/2.0;
  }
  
  float gen_pt[100], gen_ptError[100];
  float gen_ptS[100], gen_ptErrorS[100];
  
  if(isData==2){

    TH2D *genMass_1, *genMassS_1;

    if (iSpec == 1 &&  Weight==1 ) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsPtW");
    if (iSpec == 2 &&  Weight==1) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsYW");
    if (iSpec == 3 &&  Weight==1) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsCenW");
    
    if (iSpec == 1 &&  Weight==1) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsPtW");
    if (iSpec == 2 &&  Weight==1) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsYW");
    if (iSpec == 3 &&  Weight==1) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsCenW");
    
    if (iSpec == 1 &&  Weight==0) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsPt");
    if (iSpec == 2 &&  Weight==0) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsY");
    if (iSpec == 3 &&  Weight==0) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsCen");


    if (iSpec == 1 &&  Weight==0) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsPt");
    if (iSpec == 2 &&  Weight==0) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsY");
    if (iSpec == 3 &&  Weight==0) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsCen");

    TH1D *ptaxis = (TH1D*)genMass_1->ProjectionY("ptaxis");
    
    for (Int_t ih = 0; ih < Nptbin; ih++) {
      cout<<pt_bound[ih]<<"  "<<pt_bound[ih+1]<<endl;
      int pt_bin1 = ptaxis->FindBin(pt_bound[ih]+0.0000001);
      int pt_bin2 = ptaxis->FindBin(pt_bound[ih+1]+0.0000001);
      
      cout<< pt_bin1<<"  "<< pt_bin2<<endl; 
      TH1D * genMassVsPt = (TH1D*)genMass_1->ProjectionX("genMassVsPt", pt_bin1, pt_bin2-1);
      TH1D * genMassVsPtS = (TH1D*)genMassS_1->ProjectionX("genMassVsPtS", pt_bin1, pt_bin2-1);
      
      //does not work with weight
      //gen_pt[ih] = genMassVsPt->GetEntries();
      
      double genError,genErrorS;
      gen_pt[ih] = genMassVsPt->IntegralAndError(1,8000,genError);
      gen_ptError[ih]= genError;
      
      gen_ptS[ih] = genMassVsPtS->IntegralAndError(1,8000,genErrorS);
      gen_ptErrorS[ih]= genErrorS;
      
      cout<<" gen entries : "<< gen_pt[ih]<<endl;
      cout<<"genErro "<<genError<<"  "<< gen_ptError[ih]<<endl<<endl;
    }
  }
  
  // Efficiency
  float Eff_cat_1[100]; 
  float Eff_catS_1[100]; 
  
  float errEff_cat_1[100];
  float errEff_catS_1[100];
  
  float errEff_cat_S1[100], errEff_cat_S2[100];
  float errEff_catS_S1[100], errEff_catS_S2[100];
  
  char *Xname[100] = {" ", "p_{T}^{Dimuon} (GeV/c)", "rapidity", "centrality"};
  
  double yld_cat_1[100];
  double yld_catS_1[100];
  double cyld_cat_1[100];
  double cyld_catS_1[100];
  double eyld_cat_1[100];
  double eyld_catS_1[100];
  double ceyld_cat_1[100], ceyld_catS_1[100];

  char namePt_1[500];
  char namePt_1S[500];
  //char namePt_1B[500];
  char text[100];
  
  ///// Write the spectra 
  char fspectra[500];
  sprintf(fspectra,"fileSpecta%d.root", yieldInt);
  TFile *fileSpectra = new TFile(fspectra, "recreate");

  ///////////////////////////////////////////////////////////////////////
  // Category _1 
  TLegend *lcat_1;
  lcat_1 = new TLegend(.1, .82, .50, .93);
  lcat_1->SetName("lcat_1");
  lcat_1->SetBorderSize(0);
  lcat_1->SetFillStyle(0);
  lcat_1->SetFillColor(0);
  lcat_1->SetTextSize(0.032);
  //lcat_1->AddEntry(RBWPOL," CMS Preliminary", " ");
  //lcat_1->AddEntry(RBWPOL," PbPb #sqrt{s_{NN}} = 2.76 TeV ", " ");
  
  TLegend *legend_1[100];
  for(int i=0; i<100; i++) { 
    if(isFit) legend_1[i] = new TLegend(.62, .52, .91, 0.93 );
    if(!isFit) legend_1[i] = new TLegend(.62, .68, .91, 0.93 );
    legend_1[i]->SetBorderSize(0);
    legend_1[i]->SetFillStyle(0);
    legend_1[i]->SetFillColor(0);
    legend_1[i]->SetTextSize(0.032);
  }
  
  //for no cut
  //if(whis == 1 && iSpec == 1 ) TH2D *Z0Mass_1 = (TH2D*)fil1->Get("dimu");
  //if(whis == 2 && iSpec == 1) TH2D *Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsPtBRL");
  //if(whis == 4 && iSpec == 1 ) {
    //TH2D *Z0Mass_1 = (TH2D*)fil1->Get("diMuonsPATInvMassVsPt");
    //TH2D *Z0Mass_1 = (TH2D*)fil1->Get("diMuonsPATSTAInvMassVsPt");
  //}



  TH2D *Z0Mass_1, *Z0Mass_1S;

  //with weight

  if(iSpec == 1 &&  Weight==1 ) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsPtW");
  if(iSpec == 2 &&  Weight==1) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsYW");
  if(iSpec == 3 &&  Weight==1) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsCenW");


  //without weight
  if(iSpec == 1  &&  Weight==0) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsPt");
  if(iSpec == 2 &&  Weight==0) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsY");
  if(iSpec == 3 &&  Weight==0) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsCen");
      
  //with weight fil2
  if(iSpec == 1  &&  Weight==1) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsPtW");
  if(iSpec == 2 &&  Weight==1) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsYW");
  if(iSpec == 3 &&  Weight==1) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsCenW");

  //without weight fil2
  if(iSpec == 1 &&  Weight==0  ) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsPt");
  if(iSpec == 2 &&  Weight==0  ) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsY");
  if(iSpec == 3 &&  Weight==0  ) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsCen");
  
  TH1D *service = (TH1D*)Z0Mass_1->ProjectionY("service");
  int pt_bin_bound[100];
  TH1D *dimuonsGlobalInvMassVsPt[100],  *dimuonsGlobalInvMassVsPtS[100];
  
  TCanvas *CanvPt_1 = new TCanvas("CanvPt_1"," Z0 Yield Vs. Pt ", 40,40,1000,700);
  if (Nptbin == 2)  CanvPt_1->Divide(2,1);
  if (Nptbin == 3 || Nptbin == 4)  CanvPt_1->Divide(2,2);
  if (Nptbin == 5 || Nptbin == 6)  CanvPt_1->Divide(3,2);
  if (Nptbin == 9 || Nptbin == 10)  CanvPt_1->Divide(5,2);
  cout << endl << Xname[iSpec] << "    Yield      Mass (GeV)    Width (GeV)    GauWidth    chi2/ndf " << endl << endl; 
  //ih loop
  for (Int_t ih = 0; ih < Nptbin; ih++) 
    {
      CanvPt_1->cd(ih+1);
      gPad->SetTickx();
      gPad->SetTicky();
      
      // Project 1 D 
      pt_bin_bound[ih] = Z0Mass_1->GetYaxis()->FindBin(pt_bound[ih]+0.0000001);
      pt_bin_bound[ih+1] = Z0Mass_1->GetYaxis()->FindBin(pt_bound[ih+1]-0.0000001);
      sprintf(namePt_1,"Z0_1_pt_%d",ih);
      sprintf(namePt_1S,"Z0_1S_pt_%d",ih);
      
      //printf(namePt_1,"Z0_1_pt_%d",ih);
      //cout<<endl<<endl;
      //continue;
      
      dimuonsGlobalInvMassVsPt[ih] = (TH1D*)Z0Mass_1->ProjectionX(namePt_1, pt_bin_bound[ih], pt_bin_bound[ih+1]-1+1, "e");
      dimuonsGlobalInvMassVsPtS[ih] = (TH1D*)Z0Mass_1S->ProjectionX(namePt_1S, pt_bin_bound[ih], pt_bin_bound[ih+1]-1+1,"e");
      if(iSpec == 1 || iSpec == 2) {sprintf(text," %s [%.1f, %.1f]", Xname[iSpec], service->GetBinLowEdge(pt_bin_bound[ih]), 
					    service->GetBinLowEdge(pt_bin_bound[ih+1])+service->GetBinWidth(pt_bin_bound[ih+1]));}
      if(iSpec == 3) {sprintf(text," %s [%.1f, %.1f] %s", Xname[iSpec], 2.5*service->GetBinLowEdge(pt_bin_bound[ih]), 
			      2.5*(service->GetBinLowEdge(pt_bin_bound[ih+1])+service->GetBinWidth(pt_bin_bound[ih+1])), "%");}
      
      dimuonsGlobalInvMassVsPt[ih]->Rebin(nrebin);
      dimuonsGlobalInvMassVsPtS[ih]->Rebin(nrebin);
      
      float m_low = 60.0;
      float m_high = 120.0;
      
      TAxis *axs   = dimuonsGlobalInvMassVsPt[ih]->GetXaxis();
      int binlow = axs->FindBin(m_low);
      int binhi  = axs->FindBin(m_high);
      //      Double_t bin_size = (1.0*dimuonsGlobalInvMassVsPt[ih]->GetNbinsX())/(axs->GetXmax() - axs->GetXmin());
      //    Float_t int_sig = 0.0;
      //for(Int_t bin = binlow; bin<=binhi;bin++) {
      //int_sig+ = dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin);
      //}   
      double recerror,recerrorS;
      //double yld;
      double yld_1 = dimuonsGlobalInvMassVsPt[ih]->IntegralAndError(binlow, binhi, recerror);
      double yldS_1 = dimuonsGlobalInvMassVsPtS[ih]->IntegralAndError(binlow, binhi, recerrorS); 
      eyld_cat_1[ih] =recerror;
      eyld_catS_1[ih] =recerrorS;
      cout<< "yld " << yld_1 <<"  eyld_cat_1[ih]  "<< eyld_cat_1[ih]<<" rec error "<<recerror<<endl;
      
      yld_cat_1[ih] = yld_1;
      yld_catS_1[ih] = yldS_1;
      
      if(isLog) gPad->SetLogy(1);
      TColor *pal = new TColor();
      Int_t kblue = pal->GetColor(9,0,200);
      //      Int_t korange  = pal->GetColor(101, 42,  0);
      
      dimuonsGlobalInvMassVsPt[ih]->SetMarkerStyle(21);
      dimuonsGlobalInvMassVsPt[ih]->SetMarkerColor(kblue);
      dimuonsGlobalInvMassVsPt[ih]->SetLineColor(kblue);
      dimuonsGlobalInvMassVsPt[ih]->GetXaxis()->SetTitle("Dimuon mass (GeV/c^{2})");
      dimuonsGlobalInvMassVsPt[ih]->GetYaxis()->SetTitle("Events/(2 GeV/c^{2})");
      dimuonsGlobalInvMassVsPt[ih]->GetXaxis()->SetRangeUser(mlow,mhigh);
      dimuonsGlobalInvMassVsPt[ih]->DrawCopy("EPL");
      // fil2
      dimuonsGlobalInvMassVsPtS[ih]->SetMarkerStyle(8);
      dimuonsGlobalInvMassVsPtS[ih]->SetMarkerColor(46);
      dimuonsGlobalInvMassVsPtS[ih]->SetLineColor(46);
      //****** dimuonsGlobalInvMassVsPtS[ih]->DrawCopy("EPsame");
      //RBWPOL->SetLineColor(kblue);
      //backfun_1->SetLineColor(46);
      //backfun_1->SetLineWidth(1);
      //if(isFit) backfun_1->Draw("same");
      lcat_1->Draw("same"); 
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih],"Global-Global", " ");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," |y| < 2.4 ", "");  
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], text, "");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," Opposite Charge ", "LP");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPtS[ih]," Same Charge ", "LP");
      char label_1[512];
      //      char label_2[512], label_3[512], label_4[512];
      sprintf(label_1, "N=%1.2f #pm %1.2f ", yld_cat_1[ih], eyld_cat_1[ih]);
      //    sprintf(label_1, "N_{Z^{0}} = 27");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], label_1, "");
    }//ih loop
  cout << endl << endl;
  CanvPt_1->Print("Pt_Z0MassCat_1.png");
  
  TGraphErrors *Z0pt_cat_1 = new TGraphErrors(Nptbin, PT, yld_cat_1, mom_err, eyld_cat_1);
  Z0pt_cat_1->SetMarkerStyle(20);
  Z0pt_cat_1->SetMarkerColor(2);
  Z0pt_cat_1->GetXaxis()->SetTitle(Xname[iSpec]);
  Z0pt_cat_1->GetYaxis()->SetTitle("counts");

  new TCanvas;
  Z0pt_cat_1->SetMinimum(0.0);
  Z0pt_cat_1->SetName("Z0pt_cat_1");
  Z0pt_cat_1->Draw("AP");
  lcat_1->Draw("same"); 
  gPad->Print("Pt_Z0YieldCat_1.png");
  cout << endl << endl;
  Z0pt_cat_1->Write();
  lcat_1->Write();
  
  // Efficiency correction
  if(isData==2) 
    {
       ofstream fileout("correction.txt");
       cout << Xname[iSpec] << "   Eff_cat_1  " << endl;
       
       for (Int_t ih = 0; ih < Nptbin; ih++) {
      	//cout<<"gen_pt[ih];  "<<gen_pt[ih]<<endl;
	 Eff_cat_1[ih] = yld_cat_1[ih]/gen_pt[ih]; 
	 Eff_catS_1[ih] = yld_catS_1[ih]/gen_ptS[ih]; 
	 //eyld_cat_1[ih];
	 //gen_ptError[ih];
	 //cout<<endl<<endl<<endl;
	//cout<<"Eff_cat_1[ih] "<<Eff_cat_1[ih]<<endl;
	//cout<<"yld_cat_1[ih] "<< yld_cat_1[ih] <<endl;
	//cout<<"eyld_cat_1[ih] "<<eyld_cat_1[ih] <<endl;
	//cout<<"gen_pt[ih]    "<< gen_pt[ih] <<endl;
	//cout<<"gen_ptError[ih] "<< gen_ptError[ih]<<endl;
	 //Error for first graph
	 double errEff_cat_S1_1[100]={0},errEff_cat_S1_2[100]={0};
	 double errEff_cat_S2_1[100]={0},errEff_cat_S2_2[100]={0};
	 errEff_cat_S1_1[ih]= ( (Eff_cat_1[ih] * Eff_cat_1[ih]) /(gen_pt[ih] * gen_pt[ih]) );
	 errEff_cat_S1_2[ih]= (gen_ptError[ih] * gen_ptError[ih] ) - ( eyld_cat_1[ih] * eyld_cat_1[ih] );
	 errEff_cat_S1[ih]= (errEff_cat_S1_1[ih] * errEff_cat_S1_2[ih]);
	 //cout<<" errEff_cat_S1_1[ih] "<<	errEff_cat_S1_1[ih]<< " errEff_cat_S1_2[ih] "<<errEff_cat_S1_2[ih]<<endl;
	 errEff_cat_S2_1[ih]= ( (1 - Eff_cat_1[ih])* (1 - Eff_cat_1[ih]) ) / ( gen_pt[ih] * gen_pt[ih]);
	 errEff_cat_S2_2[ih]= (eyld_cat_1[ih] * eyld_cat_1[ih]);
	 errEff_cat_S2[ih]=errEff_cat_S2_1[ih]*errEff_cat_S2_2[ih];
	 //cout<<" errEff_cat_S2_1[ih] "<<	errEff_cat_S2_1[ih]<< " errEff_cat_S2_2[ih] "<<errEff_cat_S2_2[ih]<<endl;
	 //cout<<"errEff_cat_S1[ih]    "<<errEff_cat_S1[ih]<< " errEff_cat_S2[ih]   "<< errEff_cat_S2[ih]<<endl;	
	 errEff_cat_1[ih]=sqrt(errEff_cat_S1[ih] + errEff_cat_S2[ih]);
	 
	 //Error for second graph
	 double errEff_catS_S1_1[100]={0},errEff_catS_S1_2[100]={0};
	 double errEff_catS_S2_1[100]={0},errEff_catS_S2_2[100]={0};
	 errEff_catS_S1_1[ih]= ( (Eff_catS_1[ih] * Eff_catS_1[ih]) /(gen_ptS[ih] * gen_ptS[ih]) );
	 errEff_catS_S1_2[ih]= (gen_ptErrorS[ih] * gen_ptErrorS[ih] ) - (eyld_catS_1[ih] * eyld_catS_1[ih] );
	 errEff_catS_S1[ih]= (errEff_catS_S1_1[ih] * errEff_catS_S1_2[ih]);
	 errEff_catS_S2_1[ih]= ( (1 - Eff_catS_1[ih])* (1 - Eff_catS_1[ih]) ) / ( gen_ptS[ih] * gen_ptS[ih]);
	 errEff_catS_S2_2[ih]= (eyld_catS_1[ih] * eyld_catS_1[ih]);
	 errEff_catS_S2[ih]= errEff_catS_S2_1[ih]*errEff_catS_S2_2[ih];
	 errEff_catS_1[ih]=sqrt(errEff_catS_S1[ih] + errEff_catS_S2[ih]);
	 //Error for no weight
	 //errEff_cat_1[ih] =((Eff_cat_1[ih]*(1- Eff_cat_1[ih]))/gen_pt[ih]);
	 //Prashant error
	 //errEff_cat_1[ih] = eyld_cat_1[ih]/gen_pt[ih]; 
	 fileout << PT[ih] <<"   "<< Eff_cat_1[ih] << "   " << errEff_cat_1[ih] << endl; 
	 cout <<"    " << PT[ih] <<"    "<< Eff_cat_1[ih] << " +- " << errEff_cat_1[ih] << endl;
	 cyld_cat_1[ih] = Eff_cat_1[ih];
	 ceyld_cat_1[ih] = errEff_cat_1[ih];
	 cyld_catS_1[ih] = Eff_catS_1[ih];
	 ceyld_catS_1[ih] = errEff_catS_1[ih];
       }
    }
  
  TGraphErrors *Z0ptC_cat_1 = new TGraphErrors(Nptbin, PT, cyld_cat_1, mom_err, ceyld_cat_1);
  Z0ptC_cat_1->SetMarkerStyle(20);
  Z0ptC_cat_1->SetMarkerColor(2);
  Z0ptC_cat_1->GetXaxis()->SetTitle(Xname[iSpec]);
  Z0ptC_cat_1->GetYaxis()->SetTitle("Acc #times Eff");
  Z0ptC_cat_1->GetYaxis()->SetRangeUser(0,1.0);

  TGraphErrors *Z0ptC_catS_1 = new TGraphErrors(Nptbin, PT, cyld_catS_1, mom_err, ceyld_catS_1);
  Z0ptC_catS_1->SetMarkerStyle(8);
  Z0ptC_catS_1->SetMarkerColor(1);
  Z0ptC_catS_1->GetYaxis()->SetRangeUser(0,0.8);
  
  TLegend *legend_GP = new TLegend( 0.59,0.79,0.88,0.89);
  legend_GP->SetBorderSize(0);
  legend_GP->SetFillStyle(0);
  legend_GP->SetFillColor(0);
  legend_GP->SetTextSize(0.032);
  //legend_GP->AddEntry(Z0ptC_catS_1,"Pythia Gun in MB HI Data ", "");
  legend_GP->AddEntry(Z0ptC_catS_1,"Pythia Gun in MB Hydjet ", "");
  new TCanvas;
  Z0ptC_cat_1->SetMinimum(0.0);
  Z0ptC_cat_1->Draw("AP");
  //Z0ptC_catS_1->Draw("sameP");
  lcat_1->Draw("same"); 
  legend_GP->Draw("same");
  cout << endl << endl;
  Z0ptC_cat_1->Write();
}
Пример #22
0
void TTMnS2 () {
  
  const int nbins=400;
  
  TFile * QCD[8];     
  QCD[0] = new TFile("./root/TagMassVsTagNTrk_EXTRA_QCD_30-50_plots.root");
  QCD[1] = new TFile("./root/TagMassVsTagNTrk_EXTRA_QCD_50-80_plots.root");
  QCD[2] = new TFile("./root/TagMassVsTagNTrk_EXTRA_QCD_80-120_plots.root");
  QCD[3] = new TFile("./root/TagMassVsTagNTrk_EXTRA_QCD_120-170_plots.root");
  QCD[4] = new TFile("./root/TagMassVsTagNTrk_EXTRA_QCD_170-230_plots.root");
  QCD[5] = new TFile("./root/TagMassVsTagNTrk_EXTRA_QCD_230-300_plots.root");
  QCD[6] = new TFile("./root/TagMassVsTagNTrk_EXTRA_QCD_300-380_plots.root");
  QCD[7] = new TFile("./root/TagMassVsTagNTrk_EXTRA_QCD_380-incl_plots.root");
  double QCDxs[8] = { 155929000., 20938850., 2949713., 499656., 100995.,  23855., 6391., 2821.};
  // For extra QCD:
  double NQCD[8] = { 130000., 133096., 281096, 164000., 436000., 346000., 418000., 406000. };
  // For normal QCD:
  // double NQCD[8] = { 86000., 78000., 104000., 96000., 100000., 102000., 112000., 102000.};
  
  double Lumfactor = 100000; // 100/fb of luminosity assumed in histograms
  
  TH1D * H = dynamic_cast<TH1D*> (QCD[0]->Get("MTS2_0"));

  double minx=H->GetBinLowEdge(1);
  double maxx=nbins*H->GetBinWidth(1)+minx;
  TH1D * MT[8]; 
  TH1D * MN[8]; 
  for ( int i=0; i<8; i++ ) {
    char Ename[20];
    char Pname[20];
    sprintf ( Ename, "MTS2_%d", i );
    sprintf ( Pname, "MNS2_%d", i );
    MT[i] = new TH1D ( Ename, Ename, nbins, minx, maxx );
    MN[i] = new TH1D ( Pname, Pname, nbins, minx, maxx );
  }

  for ( int iN=0; iN<8; iN++ ) {
    char nameT[20];
    char nameN[20];
    sprintf ( nameT, "MTS2_%d", iN );
    sprintf ( nameN, "MNS2_%d", iN );
    double tot1[nbins]={0.};
    double s2_tot1[nbins]={0.};
    double tot2[nbins]={0.};
    double s2_tot2[nbins]={0.};
    for ( int i=0; i<8; i++ ) {
      MTtmp = dynamic_cast<TH1D*>(QCD[i]->Get(nameT));
      MNtmp = dynamic_cast<TH1D*>(QCD[i]->Get(nameN));
      cout << "Got histogram " << iN << endl;
      for ( int ibin=1; ibin<=nbins; ibin++ ) {
	double t1=MTtmp->GetBinContent(ibin);
	tot1[ibin-1]+=t1*QCDxs[i]/NQCD[i]*Lumfactor;
	s2_tot1[ibin-1]+=t1*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
	double t2=MNtmp->GetBinContent(ibin);
	tot2[ibin-1]+=t2*QCDxs[i]/NQCD[i]*Lumfactor;
	s2_tot2[ibin-1]+=t2*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
      }
    }
    if ( iN==7 ) {  // Fix split histogram for Nt=9 && >9
      sprintf ( nameT, "MTS2_%d", iN+1 );
      sprintf ( nameN, "MNS2_%d", iN+1);
      for ( int i=0; i<8; i++ ) {
	MTtmp = dynamic_cast<TH1D*>(QCD[i]->Get(nameT));
	MNtmp = dynamic_cast<TH1D*>(QCD[i]->Get(nameN));
	for ( int ibin=1; ibin<=nbins; ibin++ ) {
	  double t1=MTtmp->GetBinContent(ibin);
	  tot1[ibin-1]+=t1*QCDxs[i]/NQCD[i]*Lumfactor;
	  s2_tot1[ibin-1]+=t1*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
	  double t2=MNtmp->GetBinContent(ibin);
	  tot2[ibin-1]+=t2*QCDxs[i]/NQCD[i]*Lumfactor;
	  s2_tot2[ibin-1]+=t2*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
	}
      }
    }
    // Now renormalize histograms
    // --------------------------
    double i1=0.;
    double i2=0.;
    for ( int ibin=1; ibin<=nbins; ibin++ ) {
      i1+=tot1[ibin-1];
      i2+=tot2[ibin-1];
    }
    for ( int ibin=1; ibin<=nbins; ibin++ ) {
      MT[iN]->SetBinContent(ibin,tot1[ibin-1]/i1);
      MT[iN]->SetBinError(ibin,sqrt(s2_tot1[ibin-1])/i1);
      MN[iN]->SetBinContent(ibin,tot2[ibin-1]/i2);
      MN[iN]->SetBinError(ibin,sqrt(s2_tot2[ibin-1])/i2);
    }
  } // iN
  
  TCanvas * b = new TCanvas ("b", "Total Tag masses", 700, 700 );
  b->Divide(2,2);
  
  b->cd(1);
  b->GetPad(1)->SetLogy();
  MT[0]->SetMarkerStyle(20);
  MT[0]->SetMarkerSize(0.4);
  MT[0]->SetMarkerColor(kBlue);
  MT[0]->SetLineColor(kBlue);
  MT[0]->DrawCopy("PE");
  MT[1]->SetMarkerStyle(21);
  MT[1]->SetMarkerSize(0.4);
  MT[1]->SetMarkerColor(kRed);
  MT[1]->SetLineColor(kRed);
  MT[1]->DrawCopy("PESAME");
  MT[2]->SetMarkerStyle(24);
  MT[2]->SetMarkerSize(0.4);
  MT[2]->SetMarkerColor(kBlack);
  MT[2]->SetLineColor(kBlack);
  MT[2]->DrawCopy("PESAME");
  MT[3]->SetMarkerStyle(25);
  MT[3]->SetMarkerSize(0.4);
  MT[3]->SetMarkerColor(kGreen);
  MT[3]->SetLineColor(kGreen);
  MT[3]->DrawCopy("PESAME");
  b->cd(2);
  b->GetPad(2)->SetLogy();
  MT[4]->SetMarkerStyle(20);
  MT[4]->SetMarkerSize(0.4);
  MT[4]->SetMarkerColor(kBlue);
  MT[4]->SetLineColor(kBlue);
  MT[4]->DrawCopy("PE");
  MT[5]->SetMarkerStyle(21);
  MT[5]->SetMarkerSize(0.4);
  MT[5]->SetMarkerColor(kRed);
  MT[5]->SetLineColor(kRed);
  MT[5]->DrawCopy("PESAME");
  MT[6]->SetMarkerStyle(24);
  MT[6]->SetMarkerSize(0.4);
  MT[6]->SetMarkerColor(kBlack);
  MT[6]->SetLineColor(kBlack);
  MT[6]->DrawCopy("PESAME");
  MT[7]->SetMarkerStyle(25);
  MT[7]->SetMarkerSize(0.4);
  MT[7]->SetMarkerColor(kGreen);
  MT[7]->SetLineColor(kGreen);
  MT[7]->DrawCopy("PESAME");
  b->cd(3);
  b->GetPad(3)->SetLogy();
  MN[0]->SetMarkerStyle(20);
  MN[0]->SetMarkerSize(0.4);
  MN[0]->SetMarkerColor(kBlue);
  MN[0]->SetLineColor(kBlue);
  MN[0]->DrawCopy("PE");
  MN[1]->SetMarkerStyle(21);
  MN[1]->SetMarkerSize(0.4);
  MN[1]->SetMarkerColor(kRed);
  MN[1]->SetLineColor(kRed);
  MN[1]->DrawCopy("PESAME");
  MN[2]->SetMarkerStyle(24);
  MN[2]->SetMarkerSize(0.4);
  MN[2]->SetMarkerColor(kBlack);
  MN[2]->SetLineColor(kBlack);
  MN[2]->DrawCopy("PESAME");
  MN[3]->SetMarkerStyle(25);
  MN[3]->SetMarkerSize(0.4);
  MN[3]->SetMarkerColor(kGreen);
  MN[3]->SetLineColor(kGreen);
  MN[3]->DrawCopy("PESAME");
  b->cd(4);
  b->GetPad(4)->SetLogy();
  MN[4]->SetMarkerStyle(20);
  MN[4]->SetMarkerSize(0.4);
  MN[4]->SetMarkerColor(kBlue);
  MN[4]->SetLineColor(kBlue);
  MN[4]->DrawCopy("PE");
  MN[5]->SetMarkerStyle(21);
  MN[5]->SetMarkerSize(0.4);
  MN[5]->SetMarkerColor(kRed);
  MN[5]->SetLineColor(kRed);
  MN[5]->DrawCopy("PESAME");
  MN[6]->SetMarkerStyle(24);
  MN[6]->SetMarkerSize(0.4);
  MN[6]->SetMarkerColor(kBlack);
  MN[6]->SetLineColor(kBlack);
  MN[6]->DrawCopy("PESAME");
  MN[7]->SetMarkerStyle(25);
  MN[7]->SetMarkerSize(0.4);
  MN[7]->SetMarkerColor(kGreen);
  MN[7]->SetLineColor(kGreen);
  MN[7]->DrawCopy("PESAME");
  b->Print("./ps/TTMnS2.ps");
  
  // Close files
  // -----------
  TFile * File = new TFile ("TTMnS2.root","RECREATE");
  File->cd();
  for ( int i=0; i<8; i++ ) {
    MT[i]->Write();
    MN[i]->Write();
  }
  File->Close();
  
}
Пример #23
0
void Smooth (TString sel, double frac_true_err ) {

    // -C8 : maximum quality factor 1.1314+-0.00503415 at LR > 0.4
    // -M8 : maximum quality factor 1.03056+-0.00499927 at LR > 1.4
    // -C6 : maximum quality factor 1.18157+-0.00673922 at LR > 0.8
    // -M6 : maximum quality factor 1.01414+-0.00240137 at LR > 1.2
    // MEt : maximum quality factor 1.00301+-0.00088719 at LR > 0.8
    // -MEtSig : maximum quality factor 1.01873+-0.00367832 at LR > 1.4
    // -CorrSumEt : maximum quality factor 1.02956+-0.00487776 at LR > 1.4
    // GoodHt : maximum quality factor 1.05092+-0.00244139 at LR > 0.4
    // M45bestall : maximum quality factor 1.03104+-0.00370672 at LR > 1
    // -Chi2mass : maximum quality factor 1.13193+-0.00467282 at LR > 0.4
    // Chi2extall : maximum quality factor 1.07473+-0.00716133 at LR > 1.4
    // Mbbnoh : maximum quality factor 2.17059+-0.0321631 at LR > 0.8
    // DPbbnoh : maximum quality factor 1.30261+-0.0105512 at LR > 0.8
    // SumHED4 : maximum quality factor 1.08131+-0.00809236 at LR > 1.4
    // SumHED6 : maximum quality factor 1.09023+-0.0160105 at LR > 1.8
    // DP12 : maximum quality factor 2.29376+-0.0270215 at LR > 0.4
    // MEtDPM : maximum quality factor 1+-0.1 at LR > 0
    // -MEtDP1 : maximum quality factor 1.06697+-0.00357291 at LR > 0.4
    // MEtDP2 : maximum quality factor 1+-0.1 at LR > 0
    // -M45best : maximum quality factor 1.02626+-0.00341181 at LR > 1.2
    // -M_others : maximum quality factor 1.11418+-0.00859052 at LR > 1.4
    // -Et6 : maximum quality factor 1.02596+-0.00268856 at LR > 1

    const int nbins = 50;

    const int nvars=25;
    TString var[nvars] = { "C8", "M8", "C6", "M6", "MEt", "MEtSig", "CorrSumEt", "GoodHt",
                           "Hbestcomb", "Chi2mass", "Mbbnoh", "DPbbnoh",
                           "SumHED4", "SumHED6", "MEtDPM", "MEtDP1", "MEtDP2",
                           "M_others", "Et6", "Scprod", "Thdeta", "M5", "M3best", "Mwbest",
                           "TTMS1"
                         }

                         TString pippo[nvars];
    TString pippotot[nvars];
    TString pippotth[nvars];
    TString pippototS[nvars];
    TString pippotthS[nvars];
    for ( int i=0; i<nvars; i++ ) {
        pippo[i] = var[i]+sel;
        pippotot[i]=var[i]+sel+"_bgr";
        pippotth[i]=var[i]+sel+"_sig";
        pippototS[i]=var[i]+sel+"_bgrS";
        pippotthS[i]=var[i]+sel+"_sigS";
    }

    const int nqcdsamples=8;
    TFile * QCD[nqcdsamples];
    QCD[0] = new TFile("./root/TDAna_QCD30-50_tk3.root");
    QCD[1] = new TFile("./root/TDAna_QCD50-80_tk3.root");
    QCD[2] = new TFile("./root/TDAna_QCD80-120_tk3.root");
    QCD[3] = new TFile("./root/TDAna_QCD120-170_tk3.root");
    QCD[4] = new TFile("./root/TDAna_QCD170-230_tk3.root");
    QCD[5] = new TFile("./root/TDAna_QCD230-300_tk3.root");
    QCD[6] = new TFile("./root/TDAna_QCD300-380_tk3.root");
    QCD[7] = new TFile("./root/TDAna_QCD380incl_tk3.root");
    double QCDxs[nqcdsamples] = { 155929000., 20938850., 2949713., 499656., 100995.,  23855., 6391., 2821.};
    double NQCD[nqcdsamples] = { 86000., 78000., 104000., 96000., 100000., 102000., 112000., 102000.};


    const int nwsamples=11;
    TFile * W[nwsamples];
    W[0] = new TFile ("./root/TDAna_W0w_tk3.root");
    W[1] = new TFile ("./root/TDAna_W10w_tk3.root");
    W[2] = new TFile ("./root/TDAna_W11w_tk3.root");
    W[3] = new TFile ("./root/TDAna_W20w_tk3.root");
    W[4] = new TFile ("./root/TDAna_W21w_tk3.root");
    W[5] = new TFile ("./root/TDAna_W30w_tk3.root");
    W[6] = new TFile ("./root/TDAna_W31w_tk3.root");
    W[7] = new TFile ("./root/TDAna_W40w_tk3.root");
    W[8] = new TFile ("./root/TDAna_W41w_tk3.root");
    W[9] = new TFile ("./root/TDAna_W50w_tk3.root");
    W[10] = new TFile ("./root/TDAna_W51w_tk3.root");
    double Wxs[nwsamples] = { 45000., 9200., 250., 2500., 225., 590., 100., 125., 40., 85., 40. };
    double NW[nwsamples] = { 88000., 40000., 100530., 99523., 105255., 79000.,
                             88258., 83038., 30796., 59022., 41865.
                           };

    TFile * TTH = new TFile("./root/TDAna_ttH_120_tk3.root");
    double TTHxs = 0.667 ;
    double NTTH = 1000000.; // 62000.; // 1652000.; // 62000.;

    const int nttsamples=5;
    TFile * TT[nttsamples];
    TT[0] = new TFile("./root/TDAna_TT0_tk3.root");
    TT[1] = new TFile("./root/TDAna_TT1_tk3.root");
    TT[2] = new TFile("./root/TDAna_TT2_tk3.root");
    TT[3] = new TFile("./root/TDAna_TT3_tk3.root");
    TT[4] = new TFile("./root/TDAna_TT4_tk3.root");
    // double TTxs[5] = { 619., 176., 34.,  6., 1.5 };  // from web
    double TTxs[nttsamples] = { 434., 162., 43., 10., 1.9 };     // from note
    double NTT[nttsamples] = { 57900., 66000., 98159., 14768., 5304. };

    double Lumfactor = 100000; // 100/fb of luminosity assumed in histograms

    TH1D * Histo_TOT[nvars];
    TH1D * Histo_TTH[nvars];
    TH1D * Histo_TOTS[nvars];
    TH1D * Histo_TTHS[nvars];
    for ( int i=0; i<nvars; i++ ) {
        cout << i << endl;
        TH1D * H = dynamic_cast<TH1D*>(TTH->Get(pippo[i]));
        double minx=H->GetBinLowEdge(1);
        double maxx=nbins*H->GetBinWidth(1);
        Histo_TOT[i] = new TH1D ( pippotot[i],pippotot[i], nbins, minx, maxx );
        Histo_TTH[i] = new TH1D ( pippotth[i],pippotth[i], nbins, minx, maxx );
        Histo_TOTS[i] = new TH1D ( pippototS[i],pippototS[i], nbins, minx, maxx );
        Histo_TTHS[i] = new TH1D ( pippotthS[i],pippotthS[i], nbins, minx, maxx );
    }

    cout << "Starting loop on variables needing smoothing" << endl;

    // Loop on variables
    // -----------------
    for ( int ivar=0; ivar<nvars; ivar++ ) {

        // Extract sum histograms with the right normalization and errors
        // --------------------------------------------------------------
        double totWW[nwsamples][nbins]= {0.};
        double totW[nbins]= {0.};
        double s2_totW[nbins]= {0.};
        double totNW[nwsamples][nbins]= {0.};
        for ( int i=0; i<nwsamples; i++ ) {
            //cout << "Processing W file #" << i << " ..." << endl;
            TH1D * Histo = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]));
            TH1D * HistoW = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]+"W"));
            // For W, we need also total entries in histograms to add a
            // Poisson fluke contribution to total errors from matrix:
            // ----------------------------------------------------------
            TH1D * HistoN = dynamic_cast<TH1D*>(W[i]->Get(pippo[ivar]+"N"));
            for ( int ibin=1; ibin<=nbins; ibin++ ) {
                double t=Histo->GetBinContent(ibin);
                double s2t=HistoW->GetBinContent(ibin);
                double n=HistoN->GetBinContent(ibin);
                totWW[i][ibin-1]+=t*Wxs[i]/NW[i]*Lumfactor;
                s2_totW[ibin-1]+=s2t*pow(Wxs[i]/NW[i]*Lumfactor,2);
                totNW[i][ibin-1]+=n;
            }
        }
        // Once grandtotals of weights are computed for each bin, we can
        // add to the total s2 the Poisson contribution 1/sqrt(N) * T
        // -------------------------------------------------------------
        for ( int i=0; i<nwsamples; i++ ) {
            for ( int ibin=1; ibin<=nbins; ibin++ ) {
                totW[ibin-1]+=totWW[i][ibin-1];
                if ( totNW[i][ibin-1]>0 ) {
                    s2_totW[ibin-1]+=pow(totWW[i][ibin-1],2)/totNW[i][ibin-1];
                }
            }
        }

        double totWQCD[nqcdsamples][nbins]= {0.};
        double totQCD[nbins]= {0.};
        double s2_totQCD[nbins]= {0.};
        double totNQCD[nqcdsamples][nbins]= {0.};
        for ( int i=0; i<nqcdsamples; i++ ) {
            //cout << "Processing QCD file #" << i << " ..." << endl;
            TH1D * Histo = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]));
            TH1D * HistoW = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]+"W"));
            // For QCD, we need also total entries in histograms to add a
            // Poisson fluke contribution to total errors from matrix:
            // ----------------------------------------------------------
            TH1D * HistoN = dynamic_cast<TH1D*>(QCD[i]->Get(pippo[ivar]+"N"));
            for ( int ibin=1; ibin<=nbins; ibin++ ) {
                double t=Histo->GetBinContent(ibin);
                double s2t=HistoW->GetBinContent(ibin);
                double n=HistoN->GetBinContent(ibin);
                totWQCD[i][ibin-1]+=t*QCDxs[i]/NQCD[i]*Lumfactor;
                s2_totQCD[ibin-1]+=s2t*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
                totNQCD[i][ibin-1]+=n;
            }
        }
        // Once grandtotals of weights are computed for each bin, we can
        // add to the total s2 the Poisson contribution 1/sqrt(N) * T
        // -------------------------------------------------------------
        for ( int i=0; i<nqcdsamples; i++ ) {
            for ( int ibin=1; ibin<=nbins; ibin++ ) {
                totQCD[ibin-1]+=totWQCD[i][ibin-1];
                if ( totNQCD[i][ibin-1]>0 ) {
                    s2_totQCD[ibin-1]+=pow(totWQCD[i][ibin-1],2)/totNQCD[i][ibin-1];
                }
            }
        }

        double totTT[nbins]= {0.};
        double s2_totTT[nbins]= {0.};
        for ( int i=0; i<nttsamples; i++ ) {
            //cout << "Processing TT file #" << i << " ..." << endl;
            TH1D * Histo = dynamic_cast<TH1D*>(TT[i]->Get(pippo[ivar]));
            for ( int ibin=1; ibin<=nbins; ibin++ ) {
                double t=Histo->GetBinContent(ibin);
                totTT[ibin-1]+=t*TTxs[i]/NTT[i]*Lumfactor;
                s2_totTT[ibin-1]+=t*pow(TTxs[i]/NTT[i]*Lumfactor,2);
            }
        }
        double totTTH[nbins]= {0.};
        double s2_totTTH[nbins]= {0.};
        //cout << "Processing TTH file " << " ..." << endl;
        TH1D * Histo = dynamic_cast<TH1D*>(TTH->Get(pippo[ivar]));
        for ( int ibin=1; ibin<=nbins; ibin++ ) {
            double t=Histo->GetBinContent(ibin);
            totTTH[ibin-1]+=t*TTHxs/NTTH*Lumfactor;
            s2_totTTH[ibin-1]+=t*pow(TTHxs/NTTH*Lumfactor,2);
        }

        // OK now fill total histograms
        // ----------------------------
        double total_sig=0.;
        double total_bgr=0.;
        double grandtot[nbins]= {0.};
        double grandtote[nbins]= {0.};
        for ( int ibin=1; ibin<=nbins; ibin++ ) {
            Histo_TTH[ivar]->SetBinContent(ibin,totTTH[ibin-1]);
            Histo_TTH[ivar]->SetBinError(ibin,sqrt(s2_totTTH[ibin-1]));
            Histo_TTHS[ivar]->SetBinContent(ibin,totTTH[ibin-1]);
            Histo_TTHS[ivar]->SetBinError(ibin,sqrt(s2_totTTH[ibin-1]));
            grandtot[ibin-1] = totQCD[ibin-1]+totTT[ibin-1]+totW[ibin-1];
            grandtote[ibin-1]= sqrt(s2_totQCD[ibin-1]+s2_totTT[ibin-1]+s2_totW[ibin-1]);
            Histo_TOT[ivar]->SetBinContent(ibin,grandtot[ibin-1]);
            Histo_TOT[ivar]->SetBinError(ibin,grandtote[ibin-1]);
            Histo_TOTS[ivar]->SetBinContent(ibin,grandtot[ibin-1]);
            Histo_TOTS[ivar]->SetBinError(ibin,grandtote[ibin-1]);
            total_sig+=totTTH[ibin-1];
            total_bgr+=grandtot[ibin-1];
        }

        // Preliminary: we set to zero bins with less than 0.01% of the integral
        // ---------------------------------------------------------------------
        for ( int ibin=0; ibin<nbins; ibin++ ) {
            if ( grandtot[ibin]/total_bgr<0.0001 ) grandtot[ibin]=0.;
        }
        // Pre-pre-smoothing: kill bins with abnormally large errors,
        // replace with average of neighbors
        // ----------------------------------------------------------
        double averror=0.;
        double nav=0.;
        for ( int ibin=0; ibin<nbins; ibin++ ) {
            if ( grandtot[ibin]>0 && grandtote[ibin]>0 ) {
                averror+=grandtote[ibin]/grandtot[ibin];
                nav++;
            }
        }
        if ( nav>0 ) {
            averror=averror/nav;
            double err;
            double nlterr[100]= {0.};
            double max67pc;
            int i67=-1;
            for ( int i=0; i<100 && i67==-1; i++ ) {
                err=2*averror/100.*(double)i;
                for ( int ibin=0; ibin<nbins; ibin++ ) {
                    if ( grandtot[ibin]>0 && grandtote[ibin]>0 ) {
                        if ( grandtote[ibin]/grandtot[ibin]<err ) nlterr[i]++;
                    }
                }
                nlterr[i]=nlterr[i]/nav;
                if ( nlterr[i]>frac_true_err ) {
                    max67pc=err;
                    i67=i;
                }
            }
            cout << "var#" << ivar<< " averror=" << averror << " nav=" <<nav << " max67pc=" << max67pc << endl;

            // Ok now we know which bins to disregard. Let us correct them:
            // ------------------------------------------------------------
            int inext;
            int iprev;
            for ( int ibin=0; ibin<nbins; ibin++ ) {
                if ( grandtot[ibin]>0. && grandtote[ibin]>0. ) {
                    if ( grandtote[ibin]/grandtot[ibin]>2*max67pc ) { // consider this bin for smoothing
                        if ( ibin==0 ) {
                            inext=0;
                            // look at the three next ones
                            // ---------------------------
                            for ( int jbin=ibin+1; jbin<ibin+4 && inext==0; jbin++ ) {
                                if ( grandtot[jbin]>0. && grandtote[jbin]>0. ) {
                                    if ( grandtote[jbin]/grandtot[jbin]<2*max67pc ) inext=jbin;
                                }
                            }
                            if ( inext==0 ) inext=1;
                            iprev=inext;
                        } else if ( ibin<nbins-1 && ibin>0 ) {
                            iprev=ibin-1;
                            inext=0;
                            // look at the three next ones
                            // ---------------------------
                            for ( int jbin=ibin+1; jbin<ibin+4 && jbin<nbins && inext==0; jbin++ ) {
                                if ( grandtot[jbin]>0. && grandtote[jbin]>0. ) {
                                    if ( grandtote[jbin]/grandtot[jbin]<2*max67pc ) inext=jbin;
                                }
                            }
                            if ( inext==0 ) inext=iprev;
                        } else if ( ibin==nbins-1 ) {
                            iprev=ibin-1;
                            inext=ibin-1;
                        }
                        // Compute new value of bin, taking into account the prescription that
                        // when averaging, an average of x and zero is given value zero.
                        // Also, do not replace bins which are consistent with their neighbors
                        // within the errors in the average of the latter
                        // ------------------------------------------------------------------
                        if ( grandtot[iprev]>0. && grandtot[inext]>0. ) {
                            double av = (grandtot[iprev]+grandtot[inext])/2;
                            double s_av = sqrt((pow(grandtote[iprev],2)+pow(grandtote[inext],2))/4.);
                            if ( fabs(grandtot[ibin]-av)>s_av ) {
                                grandtot[ibin]=av;
                                grandtote[ibin]=s_av;
                            }
                        } else {
                            grandtot[ibin]=0.;
                            grandtote[ibin]=sqrt((pow(grandtote[iprev],2)+pow(grandtote[inext],2))/4.);
                        }
                    }
                }
            }
        }
        double total_bgr_s=0.;
        for ( int ibin=1; ibin<=nbins; ibin++ ) {
            total_bgr_s+=grandtot[ibin-1];
            Histo_TOTS[ivar]->SetBinContent(ibin,grandtot[ibin-1]);
            Histo_TOTS[ivar]->SetBinError(ibin,grandtote[ibin-1]);
        }

        // Now do the regular smoothing
        // ----------------------------
        //Histo_TOTS[ivar]->Smooth(1);
        //Histo_TTHS[ivar]->Smooth(1);
        double sumtot=0.;
        double sumtth=0.;
        double sumtotS=0.;
        double sumtthS=0.;
        for ( int ibin=1; ibin<=nbins; ibin++ ) {
            sumtotS+=Histo_TOTS[ivar]->GetBinContent(ibin);
            sumtthS+=Histo_TTHS[ivar]->GetBinContent(ibin);
            sumtot+=Histo_TOT[ivar]->GetBinContent(ibin);
            sumtth+=Histo_TTH[ivar]->GetBinContent(ibin);
        }
        if ( sumtotS>0 ) Histo_TOTS[ivar]->Scale(1./sumtotS);
        if ( sumtthS>0 ) Histo_TTHS[ivar]->Scale(1./sumtthS);
        if ( sumtot>0 ) Histo_TOT[ivar]->Scale(1./sumtot);
        if ( sumtth>0 ) Histo_TTH[ivar]->Scale(1./sumtth);

    } // end of ivar loop

    cout << "Done, now plotting and writing histos." << endl;

// File where smoothed histos are stored
// -------------------------------------
    TString fname;
    fname="functionfile" + sel + ".root";
    TFile * Smoothed = new TFile(fname,"RECREATE");
    Smoothed->cd();

    TCanvas * b1 = new TCanvas ("b1", "Kinematics comparison", 600, 600 );
    b1->Divide(2,4);
    for ( int ivar=0; ivar<8; ivar++ ) {
        b1->cd(ivar+1);
        Histo_TOTS[ivar]->SetMinimum(0.);
        Histo_TOTS[ivar]->Draw();
        Histo_TTHS[ivar]->SetLineColor(kBlue);
        Histo_TTHS[ivar]->Draw("PESAME");
    }
    b1->Print("./ps/Smooth_svsb_1.ps");
    TCanvas * b2 = new TCanvas ("b2", "Kinematics comparison", 600, 600 );
    b2->Divide(2,4);
    for ( int ivar=8; ivar<16; ivar++ ) {
        b2->cd(ivar-7);
        Histo_TOTS[ivar]->SetMinimum(0.);
        Histo_TOTS[ivar]->Draw();
        Histo_TTHS[ivar]->SetLineColor(kBlue);
        Histo_TTHS[ivar]->Draw("PESAME");
    }
    b2->Print("./ps/Smooth_svsb_2.ps");
    TCanvas * b3 = new TCanvas ("b3", "Kinematics comparison", 600, 600 );
    b3->Divide(2,4);
    for ( int ivar=16; ivar<nvars; ivar++ ) {
        b3->cd(ivar-15);
        Histo_TOTS[ivar]->SetMinimum(0.);
        Histo_TOTS[ivar]->Draw();
        Histo_TTHS[ivar]->SetLineColor(kBlue);
        Histo_TTHS[ivar]->Draw("PESAME");
    }
    b3->Print("./ps/Smooth_svsb_3.ps");

    TCanvas * c1 = new TCanvas ("c1", "Kinematics comparison", 600, 600 );
    c1->Divide(2,4);
    for ( int ivar=0; ivar<8; ivar++ ) {
        c1->cd(ivar+1);
        Histo_TOT[ivar]->SetMinimum(0.);
        Histo_TOT[ivar]->SetLineColor(kRed);
        Histo_TOT[ivar]->Draw("PE");
        Histo_TOTS[ivar]->Draw("PESAME");
        Histo_TOT[ivar]->Write();
        Histo_TTH[ivar]->Write();
        Histo_TOTS[ivar]->Write();
        Histo_TTHS[ivar]->Write();
    }
    c1->Print("./ps/Smooth_check_1.ps");
    TCanvas * c2 = new TCanvas ("c2", "Kinematics comparison", 600, 600 );
    c2->Divide(2,4);
    for ( int ivar=8; ivar<16; ivar++ ) {
        c2->cd(ivar-7);
        Histo_TOT[ivar]->SetMinimum(0.);
        Histo_TOT[ivar]->SetLineColor(kRed);
        Histo_TOT[ivar]->Draw("PE");
        Histo_TOTS[ivar]->Draw("PESAME");
        Histo_TOT[ivar]->Write();
        Histo_TTH[ivar]->Write();
        Histo_TOTS[ivar]->Write();
        Histo_TTHS[ivar]->Write();
    }
    c2->Print("./ps/Smooth_check_2.ps");
    TCanvas * c3 = new TCanvas ("c3", "Kinematics comparison", 600, 600 );
    c3->Divide(2,4);
    for ( int ivar=16; ivar<nvars; ivar++ ) {
        c3->cd(ivar-15);
        Histo_TOT[ivar]->SetMinimum(0.);
        Histo_TOT[ivar]->SetLineColor(kRed);
        Histo_TOT[ivar]->Draw("PE");
        Histo_TOTS[ivar]->Draw("PESAME");
        Histo_TOT[ivar]->Write();
        Histo_TTH[ivar]->Write();
        Histo_TOTS[ivar]->Write();
        Histo_TTHS[ivar]->Write();
    }
    c3->Print("./ps/Smooth_check_3.ps");

    Smoothed->Close();

}
Пример #24
0
void dataBin(TDirectory *din, TDirectory *dout) {

  float y1, y2;
  assert(sscanf(din->GetName(),"Eta_%f-%f",&y1,&y2)==2);
  sscanf(din->GetName(),"Eta_%f-%f",&y1,&y2);
  int iy = int((0.5*(y1+y2))/0.5);

  TH1D *hpt = (TH1D*)din->Get("hpt"); assert(hpt);

  // Read in text file
  if (_jp_algo=="AK7") {
    const int nchr = 2048;
    char chr[nchr];
    ifstream fs("fastnlo/InclusiveJets_Table_postCWR.txt", ios::in);
    assert(fs.is_open());
    fs.getline(chr, nchr);

    dout->cd();
    TH1D *h = (TH1D*)hpt->Clone("hdata2011");
    h->Reset();
    TH1D *hdw = (TH1D*)hpt->Clone("hdata2011_dw");
    hdw->Reset();
    TH1D *hup = (TH1D*)hpt->Clone("hdata2011_up");
    hup->Reset();
    while(fs.getline(chr, nchr)) {
  
      //cout << chr << endl;
      
      float ymin, ymax, xsec, err, err2, uncorr, np;
      int ptmin, ptmax;
      assert(sscanf(chr, "%f %f %d %d %f %f %f %f %f",
		    &ymin, &ymax, &ptmin, &ptmax,
		    &xsec, &err, &uncorr, &err2, &np)==9);
      sscanf(chr, "%f %f %d %d %f %f %f %f %f",
	     &ymin, &ymax, &ptmin, &ptmax,
	     &xsec, &err, &uncorr, &err2, &np);
    
      // sum up the uncertainty
      float foo;
      stringstream str(chr);
      for (int i = 0; i != 9; ++i) str >> foo; assert(foo==np);
      //assert(str >> foo);
      str >> foo;
      //assert(str >> foo); // lumierr
      str >> foo; // lumierr
      float eup, edw, sumedw(foo*foo), sumeup(foo*foo);
      while (str >> edw >> eup) {
	sumeup += pow(max(eup, -edw),2);
	sumedw += pow(min(eup, -edw),2);
      }
      eup = sqrt(sumeup);
      edw = sqrt(sumedw);
      
      if (fabs(ymin-y1)<0.1 && fabs(ymax-y2)<0.1) {
	int i = h->FindBin(0.5*(ptmin+ptmax));
	if (h->GetBinLowEdge(i)==ptmin &&
	    h->GetBinLowEdge(i+1)==ptmax) {
	  h->SetBinContent(i, xsec);
	  h->SetBinError(i, xsec*err);
	  hup->SetBinContent(i, xsec*(1+eup));
	  hup->SetBinError(i, xsec*(1+eup)*err);
	  hdw->SetBinContent(i, xsec*(1-edw));
	  hdw->SetBinError(i, xsec*(1-edw)*err);
	}
	else {
	  cout << "ymin = " << y1 << " ymax = " << y2 
	       << "ptmin = " << ptmin << " ptmax = " << ptmax
	       << " pt1 = " << h->GetBinLowEdge(i)
	       << " pt2 = " << h->GetBinLowEdge(i+1) << endl;
	}
      }

    } // while
  } // ak7

  if (_jp_algo=="AK5") {

    const int nchr = 2048;
    char chr[nchr];
    ifstream fs(Form("fastnlo/InclusiveJets2010_Table%d.txt",iy), ios::in);
    assert(fs.is_open());
    // remove header lines
    for (int i = 0; i != 10; ++i) fs.getline(chr, nchr);
    
    dout->cd();
    TH1D *h = (TH1D*)hpt->Clone("hdata2010");
    h->Reset();
    TH1D *hup = (TH1D*)hpt->Clone("hdata2010_up");
    hup->Reset();
    TH1D *hdw = (TH1D*)hpt->Clone("hdata2010_dw");
    hdw->Reset();
    while(fs.getline(chr, nchr)) {

      float xsec, err, err2, sys, sys2;
      float pt, ptmin, ptmax;
      assert(string(chr)=="" ||
	     sscanf(chr, "%f %f %f %f %f %f %f %f",
		    &pt, &ptmin, &ptmax,
		    &xsec, &err, &err2, &sys, &sys2)==8);
      if(string(chr)!="")
	sscanf(chr, "%f %f %f %f %f %f %f %f",
	       &pt, &ptmin, &ptmax,
	       &xsec, &err, &err2, &sys, &sys2);
    
      int i = h->FindBin(0.5*(ptmin+ptmax));
      if (h->GetBinLowEdge(i)==ptmin &&
	  h->GetBinLowEdge(i+1)==ptmax) {
	h->SetBinContent(i, xsec);
	h->SetBinError(i, err);
	hup->SetBinContent(i, xsec+sys);
	hup->SetBinError(i, err);
	hdw->SetBinContent(i, xsec+sys2);
	hdw->SetBinError(i, err);
      }
      else {
	cout << "ymin = " << y1 << " ymax = " << y2 
	     << "ptmin = " << ptmin << " ptmax = " << ptmax
	     << " pt1 = " << h->GetBinLowEdge(i)
	     << " pt2 = " << h->GetBinLowEdge(i+1) << endl;
      }
    } // while
  } // ak5


  // Read in text file (SMP-13-002)
  if (true) {
    const int nchr = 2048;
    char chr[nchr];
    ifstream fs(Form("fastnlo/InclusiveJets_Table_%s.txt",_jp_algo.c_str()));
    assert(fs.is_open());
    fs.getline(chr, nchr);

    dout->cd();
    TH1D *h = (TH1D*)hpt->Clone("hdata2013");
    h->Reset();
    TH1D *hdw = (TH1D*)hpt->Clone("hdata2013_dw");
    hdw->Reset();
    TH1D *hup = (TH1D*)hpt->Clone("hdata2013_up");
    hup->Reset();
    while(fs.getline(chr, nchr)) {
  
      float ymin, ymax, xsec, err, err2, uncorr, np;
      int ptmin, ptmax;
      assert(sscanf(chr, "%f %f %d %d %f %f %f %f %f",
		    &ymin, &ymax, &ptmin, &ptmax,
		    &xsec, &err, &uncorr, &err2, &np)==9);
      sscanf(chr, "%f %f %d %d %f %f %f %f %f",
	     &ymin, &ymax, &ptmin, &ptmax,
	     &xsec, &err, &uncorr, &err2, &np);
    
      // sum up the uncertainty
      float foo;
      stringstream str(chr);
      for (int i = 0; i != 9; ++i) str >> foo; assert(foo==np);
      //assert(str >> foo);
      str >> foo;
      //assert(str >> foo); // lumierr
      str >> foo; // lumierr
      float eup, edw, sumedw(foo*foo), sumeup(foo*foo);
      while (str >> edw >> eup) {
	sumeup += pow(max(eup, -edw),2);
	sumedw += pow(min(eup, -edw),2);
      }
      eup = sqrt(sumeup);
      edw = sqrt(sumedw);
      
      if (fabs(ymin-y1)<0.1 && fabs(ymax-y2)<0.1) {
	int i = h->FindBin(0.5*(ptmin+ptmax));
	if (h->GetBinLowEdge(i)==ptmin &&
	    h->GetBinLowEdge(i+1)==ptmax) {
	  h->SetBinContent(i, xsec);
	  h->SetBinError(i, xsec*err);
	  hup->SetBinContent(i, xsec*(1+eup));
	  hup->SetBinError(i, xsec*(1+eup)*err);
	  hdw->SetBinContent(i, xsec*(1-edw));
	  hdw->SetBinError(i, xsec*(1-edw)*err);
	}
	else {
	  cout << "ymin = " << y1 << " ymax = " << y2 
	       << "ptmin = " << ptmin << " ptmax = " << ptmax
	       << " pt1 = " << h->GetBinLowEdge(i)
	       << " pt2 = " << h->GetBinLowEdge(i+1) << endl;
	}
      }

    } // while
  } // ak7

}
Пример #25
0
int purityRandNorm(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 = 0;
  lastmt2val_hybrid = 200;
  TString name_emu = name + "emu";
  TString name_zinv = name;
  name_zinv.ReplaceAll("crdy", "sr");
  TH1D* hEMU   = (TH1D*) fData->Get(name_emu);    
  TH1D* hDY    = (TH1D*) fDY->Get(name);    
  TH1D* hZinv  = (TH1D*) fZinv->Get(name_zinv); 
  if (h_template == 0) {
    cout<<"ZinvMaker::purityAndRatio  :  could not find input template"<<endl;
    return lastbin_hybrid;
  }
  if (hDY == 0 || hZinv == 0) {
    cout<<"ZinvMaker::purityAndRatio  :  could not find DY or Zinv MC histogram"<<endl;
    return lastbin_hybrid;
  }
  if (hEMU) h_template->Add(hEMU, -1*rSFOF);

  // find the last bin
  for ( int ibin=1; ibin <= hDY->GetNbinsX(); ++ibin ) {
    float integratedYield = 0;
    integratedYield = hDY->Integral(ibin,-1);
    if (integratedYield < hybrid_nevent_threshold) {
      if (ibin == 1) lastbin_hybrid = 1;
      else {
	lastbin_hybrid = ibin-1;
	lastmt2val_hybrid = hDY->GetBinLowEdge(ibin);
      }
      break;
    }
  }

  // multiply R(Znn/Zll)
  TH1D* ratio =   (TH1D*) hZinv->Clone("ratio");
  ratio->Divide(hDY);

  h_template->Multiply(ratio);

  // 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->IntegralAndError(lastbin_hybrid, -1., integratedYieldErrZinv);
  float relativeErrorZinv = integratedYieldErrZinv/integratedYieldZinv;
  double integratedYieldErr = 0;
  float integratedYield = h_template->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->GetNbinsX(); ++ibin ) {

    if (ibin < lastbin_hybrid) continue;

    float kMT2 = hZinv->GetBinContent(ibin) / integratedYieldZinv;
    float err = sqrt( relativeError*relativeError + relativeErrorZinv*relativeErrorZinv);
    h_template->SetBinContent(ibin, integratedYield * kMT2);
    h_template->SetBinError(ibin, integratedYield * kMT2 * err );

  }

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

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


  return lastbin_hybrid;
}
Пример #26
0
void compareDressed_darko(std::string mcfilePostfix, 
			  std::string var1="h_ystar", 
			  float xmin=-9999, float xmax=-9999,
			  float ymin=0.8, float ymax=1.1,
			  bool logScale=false
			  )
{
  
  setTDRStyle();
  gStyle->SetOptStat(0);

  TH1D* h_numr;
  TH1D* h_deno;

  TH1D* h_both;

  char tempName[300];
 
  std::string mcfile_numr = "bare_exclusive1Jet_zPt40_" + mcfilePostfix;
  std::string mcfile_deno = "dressed_exclusive1Jet_zPt40_" + mcfilePostfix;
  std::string mcfile_both = "both_exclusive1Jet_zPt40_" + mcfilePostfix;

  std::string mcName_numr="Bare";
  std::string mcName_deno="Dressed";

  std::string header;
  std::string output;
  if(mcfile_numr.find("madgraph")!=std::string::npos)
    {
      header="Madgraph";
      output="madgraph";
    }
  else if(mcfile_numr.find("sherpa")!=std::string::npos)
    {
      header="Sherpa";
      output="sherpa";
    }
      
  if(mcfile_numr.find("electron")!=std::string::npos)
    {
      header+= " e";
      output+= "E";
    }
  else if(mcfile_numr.find("muon")!=std::string::npos)
    {
      header+= " #mu";
      output+= "Mu";
    }

 

  // first get the histogram files
  TFile *fmc1 = TFile::Open(mcfile_numr.data());
  cout << "Reading file 1: " << fmc1->GetName() << endl;

  TFile *fmc2 = TFile::Open(mcfile_deno.data());
  cout << "Reading file 2: " << fmc2->GetName() << endl;

  TFile *fmc3 = TFile::Open(mcfile_both.data());
  cout << "Reading file 3: " << fmc3->GetName() << endl;

  h_numr  = (TH1D*)(fmc1->FindObjectAny(var1.data()));
  h_deno  = (TH1D*)(fmc2->FindObjectAny(var1.data()));
  h_both  = (TH1D*)(fmc3->FindObjectAny(var1.data()));

  TH1D* hratio =(TH1D*) h_numr->Clone("hratio");
  hratio->SetYTitle(Form("%s/%s",mcName_numr.data(),mcName_deno.data()));
  hratio->SetLineColor(1);
  hratio->SetMarkerColor(1);

  h_numr->GetXaxis()->SetNdivisions(5);
  h_numr->GetYaxis()->SetDecimals();
  h_numr->SetTitleOffset(1.2,"Y");

  h_deno->GetXaxis()->SetNdivisions(5);
  h_deno->GetYaxis()->SetDecimals();
  h_deno->SetTitleOffset(1.2,"Y");

  hratio->GetXaxis()->SetNdivisions(5);
  hratio->GetYaxis()->SetDecimals();


  h_numr->SetLineColor(2);
  h_numr->SetMarkerColor(2);
  h_numr->SetMarkerSize(1);
  h_numr->SetMarkerStyle(24);


  h_deno->SetLineColor(4);
  h_deno->SetMarkerColor(4);
  h_deno->SetMarkerSize(1);
  h_deno->SetMarkerStyle(21);

  // if normalizing to the same area, set the scale 

  int binLo = -1;
  int binHi = -1;
  int nbins = h_numr->GetNbinsX();
  if(xmin>-9999.0 && xmax>-9999.0)
    {

      binLo = h_numr->FindBin(xmin);
      binHi = h_numr->FindBin(xmax)-1;

    }

  else
    {
      binLo = 1;
      binHi = nbins;
      xmin = h_numr->GetBinLowEdge(1);
      xmax = h_numr->GetBinLowEdge(nbins+1);
    }




  cout << "h_numr integral = "   << h_numr->Integral() << endl;;
  cout << "h_deno integral = " << h_deno->Integral() << endl;

  float area_h_deno = h_deno->Integral(binLo, binHi);

  h_numr->Sumw2();
  h_numr->Scale(1.0/area_h_deno);

  h_deno->Sumw2();
  h_deno->Scale(1.0/area_h_deno);

  h_both->Sumw2();
  h_both->Scale(1.0/area_h_deno);

  // now use formulas similar to Darko's for error calculation
  hratio->Reset();
  for(int i=1; i<=hratio->GetNbinsX();i++){
    
    double n_n = h_numr->GetBinContent(i);
    double n_d = h_deno->GetBinContent(i);
    
    if(n_d<1e-6)continue;

    double diff = n_n-n_d;

    double err_n = h_numr->GetBinError(i);
    double err_d = h_deno->GetBinError(i);

    double err_b = h_both->GetBinError(i);
    
    double err_y = sqrt(err_n*err_n - err_b*err_b);
    double err_z = sqrt(err_d*err_d - err_b*err_b);

    double value = n_n/n_d;
    
    double variance = 
      err_b*err_b*diff*diff/n_d/n_d + 
      err_y*err_y + 
      err_z*err_z*value*value;

    variance /= (n_d*n_d);

    if(variance < 0){cout << "bin " << i << " has an error in variance" << endl; continue;}
    
    variance = sqrt(variance);
    
    hratio->SetBinContent(i, value);
    hratio->SetBinError(i, variance);

  }


  for(int i=1;i<=hratio->GetNbinsX();i++)
    cout << "Bin " << i << " ( " << hratio->GetBinLowEdge(i) << "~" << hratio->GetBinLowEdge(i+1) << " ): " 
	 << h_numr->GetBinContent(i) << "/" << h_deno->GetBinContent(i) << " = " 
	 << hratio->GetBinContent(i) << " +- " << hratio->GetBinError(i) << endl;

  h_numr->GetXaxis()->SetRangeUser(xmin,xmax);
  h_deno->GetXaxis()->SetRangeUser(xmin,xmax);
  hratio->GetXaxis()->SetRangeUser(xmin,xmax);


  TCanvas* c1 = new TCanvas("c1","",700,1000);  
  c1->Divide(1,2,0.01,0);
  c1->cd(1);
  if(logScale)
    gPad->SetLogy(1);
  gPad->SetTopMargin(0.01);
  gPad->SetBottomMargin(0);
  gPad->SetRightMargin(0.04);

  
  float max_data  = h_numr->GetBinError(h_numr->GetMaximumBin()) + h_numr->GetMaximum();
  float max_mc    = h_deno->GetBinError(h_deno->GetMaximumBin()) + h_deno->GetMaximum();

  if(max_data > max_mc)
    {
      h_numr->Draw("e");
      h_deno->Draw("hesame");
    }
  else
    { h_deno->Draw("he");
      h_numr->Draw("esame");
    }


  float x1NDC = 0.7;
  float y1NDC = 0.620;
  float x2NDC = 0.9;
  float y2NDC = 0.956;

  TLegend* leg = new TLegend(x1NDC,y1NDC,x2NDC,y2NDC);
  
  leg->SetHeader(header.data());
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetTextSize(0.06);
  leg->SetBorderSize(0);
  leg->AddEntry(h_numr, mcName_numr.data());
  leg->AddEntry(h_deno, mcName_deno.data());
  leg->Draw("same");



  c1->cd(2);
  gStyle->SetStatW       (0.3);
  gStyle->SetStatH       (0.3);
  gStyle->SetStatX       (0.879447);
  gStyle->SetStatY       (0.939033);
  gStyle->SetStatFontSize(0.05);
  gStyle->SetStatBorderSize(0);
  gPad->SetRightMargin(0.04);
  gPad->SetTopMargin(0);
  gPad->SetBottomMargin(0.2);
  gPad->SetTickx();
  gStyle->SetOptFit(1);
  hratio->SetTitle("");
  hratio->SetMaximum(ymax);
  hratio->SetMinimum(ymin);
  hratio->SetTitleOffset(1.2,"Y");
  hratio->Draw("e1");
  TF1* fline = new TF1("fline","pol0");
  TLine* l2 = new TLine(xmin,1.,xmax,1.);
  l2->SetLineColor(4);
  l2->SetLineStyle(3);
  fline->SetLineWidth(3);
  fline->SetLineColor(kMagenta);
  fline->SetNpx(2500);
  if(var1.find("ystar")!=std::string::npos)
    hratio->Fit("fline","","",0,2.0);    
  else if(var1.find("jety")!=std::string::npos)
    hratio->Fit("fline","","",0,2.4);    
  else if(var1.find("mZ")== std::string::npos && 
     var1.find("zpt")== std::string::npos && 
     var1.find("jetpt")== std::string::npos)
    hratio->Fit("fline","","",0,2.2);
  l2->Draw("same");


  string dirName = "compareDressed";
  gSystem->mkdir(dirName.data());

  std::string filename;
  std::string remword  ="h_";
  std::string remword2 ="h";
  size_t pos  = var1.find(remword);
  if(pos!= std::string::npos)
    var1.replace(pos,remword2.length(),"");

  std::string psname = dirName + "/" + var1;
  if(output !="test")
    psname = dirName+ "/" + output + var1;
  else
    psname = dirName+ "/" + var1;
  filename = psname + ".eps";
  c1->Print(filename.data());
  filename = psname + ".gif";
  c1->Print(filename.data());
  filename = psname + ".pdf";
  c1->Print(filename.data());
  //   c1->Close();
}
Пример #27
0
void fitWm(const TString  outputDir,   // output directory
           const Double_t lumi,        // integrated luminosity (/fb)
	   const Double_t nsigma=0     // vary MET corrections by n-sigmas (nsigma=0 means nominal correction)
) {
  gBenchmark->Start("fitWm");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  // MET histogram binning and range
  const Int_t    NBINS   = 50;
  const Double_t METMAX  = 100;
  
  const Double_t PT_CUT  = 25;
  const Double_t ETA_CUT = 2.1;

  // file format for output plots
  const TString format("png"); 

    
  // recoil correction
  RecoilCorrector recoilCorr("../Recoil/ZmmData/fits.root");//, (!) uncomment to perform corrections to recoil from W-MC/Z-MC
                             //"../Recoil/WmpMC/fits.root",
			     //"../Recoil/WmmMC/fits.root",
			     //"../Recoil/ZmmMC/fits.root");
   
  // NNLO boson pT k-factors
  TFile nnloCorrFile("/data/blue/ksung/EWKAna/8TeV/Utils/Ratio.root");
  TH1D *hNNLOCorr = (TH1D*)nnloCorrFile.Get("RpT_B");
  
  //
  // input ntuple file names
  //
  enum { eData, eWmunu, eEWK, eAntiData, eAntiWmunu, eAntiEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/data_select.root"); typev.push_back(eData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/wm_select.root");   typev.push_back(eWmunu);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/ewk_select.root");  typev.push_back(eEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/top_select.root");  typev.push_back(eEWK);
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/data_select.root"); typev.push_back(eAntiData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/wm_select.root");   typev.push_back(eAntiWmunu);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/ewk_select.root");  typev.push_back(eAntiEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/top_select.root");  typev.push_back(eAntiEWK);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  //
  // Declare MET histograms
  //
  TH1D *hDataMet   = new TH1D("hDataMet","",  NBINS,0,METMAX); hDataMet->Sumw2();
  TH1D *hDataMetm  = new TH1D("hDataMetm","", NBINS,0,METMAX); hDataMetm->Sumw2();  
  TH1D *hDataMetp  = new TH1D("hDataMetp","", NBINS,0,METMAX); hDataMetp->Sumw2();
  TH1D *hWmunuMet  = new TH1D("hWmunuMet","", NBINS,0,METMAX); hWmunuMet->Sumw2();
  TH1D *hWmunuMetp = new TH1D("hWmunuMetp","",NBINS,0,METMAX); hWmunuMetp->Sumw2();
  TH1D *hWmunuMetm = new TH1D("hWmunuMetm","",NBINS,0,METMAX); hWmunuMetm->Sumw2();
  TH1D *hEWKMet    = new TH1D("hEWKMet", "",  NBINS,0,METMAX); hEWKMet->Sumw2();
  TH1D *hEWKMetp   = new TH1D("hEWKMetp", "", NBINS,0,METMAX); hEWKMetp->Sumw2();
  TH1D *hEWKMetm   = new TH1D("hEWKMetm", "", NBINS,0,METMAX); hEWKMetm->Sumw2();

  TH1D *hAntiDataMet   = new TH1D("hAntiDataMet","",  NBINS,0,METMAX); hAntiDataMet->Sumw2();
  TH1D *hAntiDataMetm  = new TH1D("hAntiDataMetm","", NBINS,0,METMAX); hAntiDataMetm->Sumw2();  
  TH1D *hAntiDataMetp  = new TH1D("hAntiDataMetp","", NBINS,0,METMAX); hAntiDataMetp->Sumw2();
  TH1D *hAntiWmunuMet  = new TH1D("hAntiWmunuMet","", NBINS,0,METMAX); hAntiWmunuMet->Sumw2();
  TH1D *hAntiWmunuMetp = new TH1D("hAntiWmunuMetp","",NBINS,0,METMAX); hAntiWmunuMetp->Sumw2();
  TH1D *hAntiWmunuMetm = new TH1D("hAntiWmunuMetm","",NBINS,0,METMAX); hAntiWmunuMetm->Sumw2();
  TH1D *hAntiEWKMet    = new TH1D("hAntiEWKMet", "",  NBINS,0,METMAX); hAntiEWKMet->Sumw2();
  TH1D *hAntiEWKMetp   = new TH1D("hAntiEWKMetp", "", NBINS,0,METMAX); hAntiEWKMetp->Sumw2();
  TH1D *hAntiEWKMetm   = new TH1D("hAntiEWKMetm", "", NBINS,0,METMAX); hAntiEWKMetm->Sumw2();

  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genVPt, genVPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  Float_t pfChIso, pfGamIso, pfNeuIso;
    
  TFile *infile=0;
  TTree *intree=0;

  //
  // Loop over files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	  assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);    // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);    // event number
    intree->SetBranchAddress("npv",      &npv);       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genVPt);    // GEN W boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genVPhi);   // GEN W boson phi (signal MC)   
    intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);    // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);     // Sum ET
    intree->SetBranchAddress("mt",       &mt);        // transverse mass
    intree->SetBranchAddress("u1",       &u1);        // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);        // perpendicular component of recoil
    intree->SetBranchAddress("q",        &q);	      // lepton charge
    intree->SetBranchAddress("lep",      &lep);       // lepton 4-vector
    intree->SetBranchAddress("pfChIso",  &pfChIso);
    intree->SetBranchAddress("pfGamIso", &pfGamIso);
    intree->SetBranchAddress("pfNeuIso", &pfNeuIso);
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(lep->Pt()        < PT_CUT)  continue;	
      if(fabs(lep->Eta()) > ETA_CUT) continue;
      
      if( (typev[ifile]==eAntiData || typev[ifile]==eAntiWmunu || typev[ifile]==eAntiEWK) &&
          (pfChIso+pfGamIso+pfNeuIso)>0.5*(lep->Pt()) ) 
	  continue;
      
      if(typev[ifile]==eData) {
        hDataMet->Fill(met);
	if(q>0) { hDataMetp->Fill(met); } 
	else    { hDataMetm->Fill(met); }
      
      } else if(typev[ifile]==eAntiData) {
        hAntiDataMet->Fill(met);
	if(q>0) { hAntiDataMetp->Fill(met); } 
	else    { hAntiDataMetm->Fill(met); }      
      
      } else {
        Double_t weight = 1;
        weight *= scale1fb*lumi;
	
	if(typev[ifile]==eWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
	
          Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
	  
          hWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hWmunuMetp->Fill(corrMet,weight); } 
	  else    { hWmunuMetm->Fill(corrMet,weight); }
        }
	if(typev[ifile]==eAntiWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();//gRandom->Gaus(lep->Pt(),0.5);
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
          
	  Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
          
	  hAntiWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hAntiWmunuMetp->Fill(corrMet,weight); } 
	  else    { hAntiWmunuMetm->Fill(corrMet,weight); }
        }
        if(typev[ifile]==eEWK) {
          hEWKMet->Fill(met,weight);
	  if(q>0) { hEWKMetp->Fill(met,weight); }
	  else    { hEWKMetm->Fill(met,weight); }
        }
        if(typev[ifile]==eAntiEWK) {
          hAntiEWKMet->Fill(met,weight);
	  if(q>0) { hAntiEWKMetp->Fill(met,weight); }
	  else    { hAntiEWKMetm->Fill(met,weight); }
        }
      }
    }
  }  
  delete infile;
  infile=0, intree=0;   
  
  //
  // Declare fit parameters for signal and background yields
  // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC
  //
  RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar cewk("cewk","cewk",0.1,0,5) ;
  cewk.setVal(hEWKMet->Integral()/hWmunuMet->Integral());
  cewk.setConstant(kTRUE);
  RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk));
  RooRealVar nAntiSig("nAntiSig","nAntiSig",0.05*(hAntiDataMet->Integral()),0,hAntiDataMet->Integral());
  RooRealVar nAntiQCD("nAntiQCD","nAntiQCD",0.9*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar dewk("dewk","dewk",0.1,0,5) ;
  dewk.setVal(hAntiEWKMet->Integral()/hAntiWmunuMet->Integral());
  dewk.setConstant(kTRUE);
  RooFormulaVar nAntiEWK("nAntiEWK","nAntiEWK","dewk*nAntiSig",RooArgList(nAntiSig,dewk));
  
  RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ;
  cewkp.setVal(hEWKMetp->Integral()/hWmunuMetp->Integral());
  cewkp.setConstant(kTRUE);
  RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp));
  RooRealVar nAntiSigp("nAntiSigp","nAntiSigp",0.05*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar nAntiQCDp("nAntiQCDp","nAntiQCDp",0.9*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar dewkp("dewkp","dewkp",0.1,0,5) ;
  dewkp.setVal(hAntiEWKMetp->Integral()/hAntiWmunuMetp->Integral());
  dewkp.setConstant(kTRUE);
  RooFormulaVar nAntiEWKp("nAntiEWKp","nAntiEWKp","dewkp*nAntiSigp",RooArgList(nAntiSigp,dewkp));
  
  RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ;
  cewkm.setVal(hEWKMetm->Integral()/hWmunuMetm->Integral());
  cewkm.setConstant(kTRUE);
  RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm));  
  RooRealVar nAntiSigm("nAntiSigm","nAntiSigm",0.05*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar nAntiQCDm("nAntiQCDm","nAntiQCDm",0.9*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar dewkm("dewkm","dewkm",0.1,0,5) ;
  dewkm.setVal(hAntiEWKMetm->Integral()/hAntiWmunuMetm->Integral());
  dewkm.setConstant(kTRUE);
  RooFormulaVar nAntiEWKm("nAntiEWKm","nAntiEWKm","dewkm*nAntiSigm",RooArgList(nAntiSigm,dewkm));

  //
  // Construct PDFs for fitting
  //
  RooRealVar pfmet("pfmet","pfmet",0,METMAX);
  pfmet.setBins(NBINS);
   
  // Signal PDFs
  RooDataHist wmunuMet ("wmunuMET", "wmunuMET", RooArgSet(pfmet),hWmunuMet);  RooHistPdf pdfWm ("wm", "wm", pfmet,wmunuMet, 1);
  RooDataHist wmunuMetp("wmunuMETp","wmunuMETp",RooArgSet(pfmet),hWmunuMetp); RooHistPdf pdfWmp("wmp","wmp",pfmet,wmunuMetp,1);
  RooDataHist wmunuMetm("wmunuMETm","wmunuMETm",RooArgSet(pfmet),hWmunuMetm); RooHistPdf pdfWmm("wmm","wmm",pfmet,wmunuMetm,1); 
  
  // EWK+top PDFs
  RooDataHist ewkMet ("ewkMET", "ewkMET", RooArgSet(pfmet),hEWKMet);  RooHistPdf pdfEWK ("ewk", "ewk", pfmet,ewkMet, 1);
  RooDataHist ewkMetp("ewkMETp","ewkMETp",RooArgSet(pfmet),hEWKMetp); RooHistPdf pdfEWKp("ewkp","ewkp",pfmet,ewkMetp,1); 
  RooDataHist ewkMetm("ewkMETm","ewkMETm",RooArgSet(pfmet),hEWKMetm); RooHistPdf pdfEWKm("ewkm","ewkm",pfmet,ewkMetm,1); 
  
  // QCD Pdfs
  CPepeModel1 qcd("qcd",pfmet);
  CPepeModel1 qcdp("qcdp",pfmet);
  CPepeModel1 qcdm("qcdm",pfmet);
  
  // Signal + Background PDFs
  RooAddPdf pdfMet ("pdfMet", "pdfMet", RooArgList(pdfWm,pdfEWK,*(qcd.model)),   RooArgList(nSig,nEWK,nQCD));  
  RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWmp,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp));
  RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWmm,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm));
    
  
  // Anti-Signal PDFs
  RooDataHist awmunuMet ("awmunuMET", "awmunuMET", RooArgSet(pfmet),hAntiWmunuMet);  RooHistPdf apdfWm ("awm", "awm", pfmet,awmunuMet, 1);
  RooDataHist awmunuMetp("awmunuMETp","awmunuMETp",RooArgSet(pfmet),hAntiWmunuMetp); RooHistPdf apdfWmp("awmp","awmp",pfmet,awmunuMetp,1);
  RooDataHist awmunuMetm("awmunuMETm","awmunuMETm",RooArgSet(pfmet),hAntiWmunuMetm); RooHistPdf apdfWmm("awmm","awmm",pfmet,awmunuMetm,1); 
  
  // Anti-EWK+top PDFs
  RooDataHist aewkMet ("aewkMET", "aewkMET", RooArgSet(pfmet),hAntiEWKMet);  RooHistPdf apdfEWK ("aewk", "aewk", pfmet,aewkMet, 1);
  RooDataHist aewkMetp("aewkMETp","aewkMETp",RooArgSet(pfmet),hAntiEWKMetp); RooHistPdf apdfEWKp("aewkp","aewkp",pfmet,aewkMetp,1); 
  RooDataHist aewkMetm("aewkMETm","aewkMETm",RooArgSet(pfmet),hAntiEWKMetm); RooHistPdf apdfEWKm("aewkm","aewkm",pfmet,aewkMetm,1); 
  
  // Anti-QCD Pdfs
  CPepeModel1 aqcd("aqcd",pfmet,qcd.a1);
  CPepeModel1 aqcdp("aqcdp",pfmet,qcdp.a1);
  CPepeModel1 aqcdm("aqcdm",pfmet,qcdm.a1);
  
  // Anti-selection PDFs
  RooAddPdf apdfMet ("apdfMet", "apdfMet", RooArgList(apdfWm,apdfEWK,*(aqcd.model)),   RooArgList(nAntiSig,nAntiEWK,nAntiQCD));  
  RooAddPdf apdfMetp("apdfMetp","apdfMetp",RooArgList(apdfWmp,apdfEWKp,*(aqcdp.model)),RooArgList(nAntiSigp,nAntiEWKp,nAntiQCDp));
  RooAddPdf apdfMetm("apdfMetm","apdfMetm",RooArgList(apdfWmm,apdfEWKm,*(aqcdm.model)),RooArgList(nAntiSigm,nAntiEWKm,nAntiQCDm));
  
  // PDF for simultaneous fit
  RooCategory rooCat("rooCat","rooCat");
  rooCat.defineType("Select");
  rooCat.defineType("Anti");
  
  RooSimultaneous pdfTotal("pdfTotal","pdfTotal",rooCat);
  pdfTotal.addPdf(pdfMet, "Select");
  pdfTotal.addPdf(apdfMet,"Anti");
  
  RooSimultaneous pdfTotalp("pdfTotalp","pdfTotalp",rooCat);
  pdfTotalp.addPdf(pdfMetp, "Select");
  pdfTotalp.addPdf(apdfMetp,"Anti");
  
  RooSimultaneous pdfTotalm("pdfTotalm","pdfTotalm",rooCat);
  pdfTotalm.addPdf(pdfMetm, "Select");
  pdfTotalm.addPdf(apdfMetm,"Anti");
  
  //
  // Perform fits
  //

  RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet), hDataMet);
  RooDataHist antiMet("antiMet", "antiMet", RooArgSet(pfmet), hAntiDataMet);
  RooDataHist dataTotal("dataTotal","dataTotal", RooArgList(pfmet), Index(rooCat),
                        Import("Select", dataMet),
                        Import("Anti",   antiMet));
  RooFitResult *fitRes = pdfTotal.fitTo(dataTotal,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetp("dataMetp", "dataMetp", RooArgSet(pfmet), hDataMetp);
  RooDataHist antiMetp("antiMetp", "antiMetp", RooArgSet(pfmet), hAntiDataMetp);
  RooDataHist dataTotalp("dataTotalp","dataTotalp", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetp),
                         Import("Anti",   antiMetp));
  RooFitResult *fitResp = pdfTotalp.fitTo(dataTotalp,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetm("dataMetm", "dataMetm", RooArgSet(pfmet), hDataMetm);
  RooDataHist antiMetm("antiMetm", "antiMetm", RooArgSet(pfmet), hAntiDataMetm);
  RooDataHist dataTotalm("dataTotalm","dataTotalm", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetm),
                         Import("Anti",   antiMetm));
  RooFitResult *fitResm = pdfTotalm.fitTo(dataTotalm,Extended(),Minos(kTRUE),Save(kTRUE));
    
  //
  // Use histogram version of fitted PDFs to make ratio plots
  // (Will also use PDF histograms later for Chi^2 and KS tests)
  //
  TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet));
  hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral());
  TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff");
  hMetDiff->SetMarkerStyle(kFullCircle);
  hMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet));
  hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral());
  TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff");
  hMetpDiff->SetMarkerStyle(kFullCircle);
  hMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet));
  hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral());
  TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff");
  hMetmDiff->SetMarkerStyle(kFullCircle); 
  hMetmDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfAntiMet = (TH1D*)(apdfMet.createHistogram("hPdfAntiMet", pfmet));
  hPdfAntiMet->Scale((nAntiSig.getVal()+nAntiEWK.getVal()+nAntiQCD.getVal())/hPdfAntiMet->Integral());
  TH1D *hAntiMetDiff = makeDiffHist(hAntiDataMet,hPdfAntiMet,"hAntiMetDiff");
  hAntiMetDiff->SetMarkerStyle(kFullCircle);
  hAntiMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfAntiMetp = (TH1D*)(apdfMetp.createHistogram("hPdfAntiMetp", pfmet));
  hPdfAntiMetp->Scale((nAntiSigp.getVal()+nAntiEWKp.getVal()+nAntiQCDp.getVal())/hPdfAntiMetp->Integral());
  TH1D *hAntiMetpDiff = makeDiffHist(hAntiDataMetp,hPdfAntiMetp,"hAntiMetpDiff");
  hAntiMetpDiff->SetMarkerStyle(kFullCircle);
  hAntiMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfAntiMetm = (TH1D*)(apdfMetm.createHistogram("hPdfAntiMetm", pfmet));
  hPdfAntiMetm->Scale((nAntiSigm.getVal()+nAntiEWKm.getVal()+nAntiQCDm.getVal())/hPdfAntiMetm->Integral());
  TH1D *hAntiMetmDiff = makeDiffHist(hAntiDataMetm,hPdfAntiMetm,"hAntiMetmDiff");
  hAntiMetmDiff->SetMarkerStyle(kFullCircle); 
  hAntiMetmDiff->SetMarkerSize(0.9);
   
  
  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.15);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.15);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  gStyle->SetTitleOffset(1.100,"Y");
  TGaxis::SetMaxDigits(3);
  
  char ylabel[100];  // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = 8 TeV",lumi*1000.);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = 8 TeV",lumi);
  
  // plot colors
  Int_t linecolorW   = kOrange-3;
  Int_t fillcolorW   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t linecolorQCD = kViolet+2;
  Int_t fillcolorQCD = kViolet-5;
  Int_t ratioColor   = kGray+2;
  
  //
  // Dummy histograms for TLegend
  // (I can't figure out how to properly pass RooFit objects...)
  //
  TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
  hDummyData->SetMarkerStyle(kFullCircle);
  hDummyData->SetMarkerSize(0.9);
  
  TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
  hDummyW->SetLineColor(linecolorW);
  hDummyW->SetFillColor(fillcolorW);
  hDummyW->SetFillStyle(1001);
  
  TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
  hDummyEWK->SetLineColor(linecolorEWK);
  hDummyEWK->SetFillColor(fillcolorEWK);
  hDummyEWK->SetFillStyle(1001);
  
  TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
  hDummyQCD->SetLineColor(linecolorQCD);
  hDummyQCD->SetFillColor(fillcolorQCD);
  hDummyQCD->SetFillStyle(1001);
   
  //
  // W MET plot
  //
  RooPlot *wmframe = pfmet.frame(Bins(NBINS)); 
  wmframe->GetYaxis()->SetNdivisions(505);
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMet.plotOn(wmframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMet.plotOn(wmframe,LineColor(linecolorW));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfWm)),LineColor(linecolorW),LineStyle(2));
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1));
  CPlot plotMet("fitmet",wmframe,"","",ylabel);
  plotMet.SetLegend(0.68,0.57,0.93,0.77);
  plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
  plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kFALSE,format,1);

  CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi");
  plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotMetDiff.SetYRange(-8,8);
  plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetDiff.Draw(c,kTRUE,format,2);
  
  plotMet.SetName("fitmetlog");
  plotMet.SetLogy();
  plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kTRUE,format,1);
    
  RooPlot *awmframe = pfmet.frame(Bins(NBINS));    
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMet.plotOn(awmframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMet.plotOn(awmframe,LineColor(linecolorW));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),LineColor(linecolorEWK));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),LineColor(linecolorQCD));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfWm)),LineColor(linecolorW),LineStyle(2));
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hAntiDataMet->GetBinWidth(1));
  CPlot plotAntiMet("fitantimet",awmframe,"","",ylabel);
  plotAntiMet.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotAntiMet.SetYRange(0.1,1.1*(hAntiDataMet->GetMaximum())); 
  plotAntiMet.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetDiff("fitantimet","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotAntiMetDiff.SetYRange(-8,8);
  plotAntiMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMet.SetName("fitantimetlog");
  plotAntiMet.SetLogy();
  plotAntiMet.SetYRange(1e-3*(hAntiDataMet->GetMaximum()),10*(hAntiDataMet->GetMaximum()));
  plotAntiMet.Draw(c,kTRUE,format,1);
    
  //
  // W+ MET plot
  //
  RooPlot *wmpframe = pfmet.frame(Bins(NBINS));
  wmpframe->GetYaxis()->SetNdivisions(505);
  dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetp.plotOn(wmpframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,LineColor(linecolorW));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfWmp)),LineColor(linecolorW),LineStyle(2));
  dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1));
  CPlot plotMetp("fitmetp",wmpframe,"","",ylabel);
  plotMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#nu","F");
  plotMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotMetp.SetYRange(0.1,1.1*(hDataMetp->GetMaximum()));
plotMetp.SetYRange(0.1,4100);
  plotMetp.Draw(c,kFALSE,format,1);

  CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi");
  plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor);
  plotMetpDiff.SetYRange(-8,8);
  plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetpDiff.Draw(c,kTRUE,format,2);
  
  plotMetp.SetName("fitmetplog");
  plotMetp.SetLogy();
  plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kTRUE,format,1);

  RooPlot *awmpframe = pfmet.frame(Bins(NBINS));    
  antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMetp.plotOn(awmpframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,LineColor(linecolorW));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),LineColor(linecolorEWK));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),LineColor(linecolorQCD));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfWmp)),LineColor(linecolorW),LineStyle(2));
  antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hAntiDataMetp->GetBinWidth(1));
  CPlot plotAntiMetp("fitantimetp",awmpframe,"","",ylabel);
  plotAntiMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#nu","F");
  plotAntiMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotAntiMetp.SetYRange(0.1,1.1*(hAntiDataMetp->GetMaximum()));
plotAntiMetp.SetYRange(0.1,1500);
  plotAntiMetp.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetpDiff("fitantimetp","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetpDiff.AddHist1D(hAntiMetpDiff,"EX0",ratioColor);
  plotAntiMetpDiff.SetYRange(-8,8);
  plotAntiMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetpDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMetp.SetName("fitantimetplog");
  plotAntiMetp.SetLogy();
  plotAntiMetp.SetYRange(1e-3*(hAntiDataMetp->GetMaximum()),10*(hAntiDataMetp->GetMaximum()));
  plotAntiMetp.Draw(c,kTRUE,format,1);
  
  //
  // W- MET plot
  //
  RooPlot *wmmframe = pfmet.frame(Bins(NBINS)); 
  wmmframe->GetYaxis()->SetNdivisions(505);
  dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetm.plotOn(wmmframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,LineColor(linecolorW));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfWmm)),LineColor(linecolorW),LineStyle(2));
  dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotMetm("fitmetm",wmmframe,"","",ylabel);
  plotMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#bar{#nu}","F");
  plotMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotMetm.SetYRange(0.1,1.1*(hDataMetm->GetMaximum()));
plotMetm.SetYRange(0.1,4100);
  plotMetm.Draw(c,kFALSE,format,1);

  CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi");
  plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor);
  plotMetmDiff.SetYRange(-8,8);
  plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetmDiff.Draw(c,kTRUE,format,2);
  
  plotMetm.SetName("fitmetmlog");
  plotMetm.SetLogy();
  plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kTRUE,format,1);

  RooPlot *awmmframe = pfmet.frame(Bins(NBINS)); 
  antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMetm.plotOn(awmmframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,LineColor(linecolorW));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),LineColor(linecolorEWK));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),LineColor(linecolorQCD));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfWmm)),LineColor(linecolorW),LineStyle(2));
  antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotAntiMetm("fitantimetm",awmmframe,"","",ylabel);
  plotAntiMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#bar{#nu}","F");
  plotAntiMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotAntiMetm.SetYRange(0.1,1.1*(hAntiDataMetm->GetMaximum()));
plotAntiMetm.SetYRange(0.1,1500);
  plotAntiMetm.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetmDiff("fitantimetm","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetmDiff.AddHist1D(hAntiMetmDiff,"EX0",ratioColor);
  plotAntiMetmDiff.SetYRange(-8,8);
  plotAntiMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetmDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMetm.SetName("fitantimetmlog");
  plotAntiMetm.SetLogy();
  plotAntiMetm.SetYRange(1e-3*(hAntiDataMetm->GetMaximum()),10*(hAntiDataMetm->GetMaximum()));
  plotAntiMetm.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  
  //
  // Write fit results
  //
  ofstream txtfile;
  char txtfname[100];    
  
  ios_base::fmtflags flags;
  
  Double_t chi2prob, chi2ndf;
  Double_t ksprob, ksprobpe;
  
  chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW");
  chi2ndf  = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW");
  ksprob   = hDataMet->KolmogorovTest(hPdfMet);
  ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX");
  sprintf(txtfname,"%s/fitresWm.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMet->Integral() << endl;
  txtfile << "  Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl;
  txtfile << "     QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl;
  txtfile << "   Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitRes);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();
  
  chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW");
  chi2ndf  = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW");
  ksprob   = hDataMetp->KolmogorovTest(hPdfMetp);
  ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX");  
  sprintf(txtfname,"%s/fitresWmp.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetp->Integral() << endl;
  txtfile << "  Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl;
  txtfile << "     QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl;
  txtfile << "   Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl;
  txtfile << endl; 
  txtfile.flags(flags);
  
  fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResp);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW");
  chi2ndf  = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW");
  ksprob   = hDataMetm->KolmogorovTest(hPdfMetm);
  ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX");  
  sprintf(txtfname,"%s/fitresWmm.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetm->Integral() << endl;
  txtfile << "  Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl;
  txtfile << "     QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl;
  txtfile << "   Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResm);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  makeHTML(outputDir);
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("fitWm");
}
Пример #28
0
Compare_QCD ( TString pippo ) 
{

  TFile * QCD[8];     
  QCD[0] = new TFile("./root/TDAna_QCD30-50_tk3.root");
  QCD[1] = new TFile("./root/TDAna_QCD50-80_tk3.root");
  QCD[2] = new TFile("./root/TDAna_QCD80-120_tk3.root");
  QCD[3] = new TFile("./root/TDAna_QCD120-170_tk3.root");
  QCD[4] = new TFile("./root/TDAna_QCD170-230_tk3.root");
  QCD[5] = new TFile("./root/TDAna_QCD230-300_tk3.root");
  QCD[6] = new TFile("./root/TDAna_QCD300-380_tk3.root");
  QCD[7] = new TFile("./root/TDAna_QCD380incl_tk3.root");
  double QCDxs[8] = { 155929000., 20938850., 2949713., 499656., 100995.,  23855., 6391., 2821.};
  double NQCD[8] = { 86000., 78000., 104000., 96000., 100000., 102000., 112000., 102000.};

  TFile * QCDOLD[8];     
  QCDOLD[0] = new TFile("./rootold/TDAna_QCD30-50_tk3.root");
  QCDOLD[1] = new TFile("./rootold/TDAna_QCD50-80_tk3.root");
  QCDOLD[2] = new TFile("./rootold/TDAna_QCD80-120_tk3.root");
  QCDOLD[3] = new TFile("./rootold/TDAna_QCD120-170_tk3.root");
  QCDOLD[4] = new TFile("./rootold/TDAna_QCD170-230_tk3.root");
  QCDOLD[5] = new TFile("./rootold/TDAna_QCD230-300_tk3.root");
  QCDOLD[6] = new TFile("./rootold/TDAna_QCD300-380_tk3.root");
  QCDOLD[7] = new TFile("./rootold/TDAna_QCD380incl_tk3.root");

  double Lumfactor = 100000.;

  TH1D * H = dynamic_cast<TH1D*>(QCD[0]->Get(pippo));
  double minx=H->GetBinLowEdge(1);
  double maxx=50.*H->GetBinWidth(1);
  TH1D * Histo_QCD = new TH1D ( pippo+"_QCD", "", 50, minx, maxx );
  TH1D * R_QCD = new TH1D ( pippo+"_QCD", "", 50, minx, maxx );
  TH1F * Histo_QCDOLD = new TH1F ( pippo+"_QCDOLD", "", 50, minx,maxx );

  // Extract sum histograms with the right normalization and errors
  // --------------------------------------------------------------
  double totQCD[50]={0.};
  double s2_totQCD[50]={0.};
  for ( int i=0; i<8; i++ ) {
    cout << "Processing QCD file #" << i << " ..." << endl;
    TH1D * Histo = dynamic_cast<TH1D*>(QCD[i]->Get(pippo));
    TH1D * HistoW = dynamic_cast<TH1D*>(QCD[i]->Get(pippo+"W"));
    for ( int ibin=1; ibin<=50; ibin++ ) {
      double t=Histo->GetBinContent(ibin);
      double s2t=HistoW->GetBinContent(ibin);
      totQCD[ibin-1]+=t*QCDxs[i]/NQCD[i]*Lumfactor;
      s2_totQCD[ibin-1]+=s2t*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
    }
  }
  double totQCDOLD[50]={0.};
  double totNQCDOLD[50]={0.};
  double s2_totQCDOLD[50]={0.};
  for ( int i=0; i<8; i++ ) {
    cout << "Processing QCD OLD file #" << i << " ..." << endl;
    TH1D * Histo = dynamic_cast<TH1D*>(QCDOLD[i]->Get(pippo));
    for ( int ibin=1; ibin<=50; ibin++ ) {
      double t=Histo->GetBinContent(ibin);
      totQCDOLD[ibin-1]+=t*QCDxs[i]/NQCD[i]*Lumfactor;
      totNQCDOLD[ibin-1]+=t;
      s2_totQCDOLD[ibin-1]+=t*pow(QCDxs[i]/NQCD[i]*Lumfactor,2);
    }
  }
  // Once grandtotals of weights are computed for each bin, we can
  // add to the total s2 the Poisson contribution 1/sqrt(N) * T
  // -------------------------------------------------------------
  for ( int ibin=1; ibin<=50; ibin++ ) {
    if ( totNQCDOLD[ibin-1]==0 ) totNQCDOLD[ibin-1]=1;
    s2_totQCD[ibin-1]+=pow(totQCD[ibin-1],2)/totNQCDOLD[ibin-1];
  }

  // OK now fill total histograms
  // ----------------------------
  double nQCD=0.;
  double s2_NQCD=0.;
  double nQCDOLD=0.;
  double s2_NQCDOLD=0.;
  for ( int ibin=1; ibin<=50; ibin++ ) {
    nQCD+=totQCD[ibin-1];
    s2_NQCD+=s2_totQCD[ibin-1];
    nQCDOLD+=totQCDOLD[ibin-1];
    s2_NQCDOLD+=s2_totQCDOLD[ibin-1];
    Histo_QCD->SetBinContent(ibin,totQCD[ibin-1]);
    Histo_QCDOLD->SetBinContent(ibin,totQCDOLD[ibin-1]);
    Histo_QCD->SetBinError(ibin,sqrt(s2_totQCD[ibin-1]));
    Histo_QCDOLD->SetBinError(ibin,sqrt(s2_totQCDOLD[ibin-1]));
    double R=1.;
    double s_R;
    if ( totQCDOLD[ibin-1]>0 && totQCD[ibin-1] ) {
      R = totQCDOLD[ibin-1]/totQCD[ibin-1];
      s_R = R*sqrt(s2_totQCD[ibin-1]/pow(totQCD[ibin-1],2)+
		   s2_totQCDOLD[ibin-1]/pow(totQCDOLD[ibin-1],2));
      cout << ibin-1 << " " << totQCD[ibin-1] << "+-" << sqrt(s2_totQCD[ibin-1])/totQCD[ibin-1] 
	   << " / " <<  totQCDOLD[ibin-1] <<  "+-" <<sqrt(s2_totQCDOLD[ibin-1])/totQCDOLD[ibin-1]  
	   << " = " << R << "+-" << s_R << endl;
    }
    R_QCD->SetBinContent(ibin,R);
    R_QCD->SetBinError(ibin,s_R);
  }
  cout << "Totals: N(seen) = " << nQCDOLD << "+-" << sqrt(s2_NQCDOLD) << endl;
  cout << "        N(pred) = " << nQCD    << "+-" << sqrt(s2_NQCD) << endl;

  TCanvas * b = new TCanvas ("b", "Kinematics comparison", 700, 700 );
  b->Divide(1,2);

  b->cd(1);
  //b->GetPad(1)->SetLogy();
  Histo_QCD->SetLineColor(kRed);
  Histo_QCD->Draw("PE");
  Histo_QCDOLD->SetLineColor(kBlue);
  Histo_QCDOLD->Draw("PESAME");
  b->cd(2);
  R_QCD->SetMinimum(0.);
  R_QCD->SetMaximum(4.);
  R_QCD->Draw("PE");

  b->Print(pippo+".ps");

}
Пример #29
0
void fit(const char *run="428211_429133_5s",
	 int key=1, int bmin=10, bool draw=true, bool pa=false) {
  int minentries=1000;
  gSystem->Exec( Form("mkdir -p %s/SEN%03d",run,key/128) );
  gSystem->Exec( Form("mkdir -p %s/SEN%03d",run,key/128) );
  int state = findstate(key);
  printf("state %d\n",state);
  // data
  TString inname = Form("%s/adc/HI_KEY%05d.root",run,key);
  TString outname = Form("HI_KEY%05d",key);
  TFile *file = new TFile( inname.Data() );
  cout << inname.Data() << endl;

  TH1D *out = (TH1D*) file->Get("out");
  double xfit_min=out->GetBinLowEdge(bmin);
  double xfit_max=122.5;
  int bmax = out->GetXaxis()->FindBin(xfit_max);
  int entries = out->Integral(bmin,bmax);
  if(entries<minentries) {
    cout << "not enough entries: ";
    cout << entries << endl;
    return;
  }

  // fit
  TCanvas *main = new TCanvas("main","main");
  int pkt=0;
  if(pa)
    pkt = (key%(8*4*12*64))/(4*12*64);
  TF1 *fitH = GetFit( Form("%s/SEN%03d/%s.dat",run,key/128,outname.Data()) ,pkt,xfit_min);
  out->Fit(fitH,"MELIR","",xfit_min,xfit_max);
  TF1 *MIPH1 = GetMIP(fitH,1,kCyan-3);
  TF1 *MIPH2 = GetMIP(fitH,2,kGreen-3);
  TF1 *MIPH3 = GetMIP(fitH,3,kOrange-3);
  TF1 *MIPH4 = GetMIP(fitH,4,kMagenta-3);
  TF1 *BGR = GetBGR(fitH,xfit_min);

  double amp = fitH->GetParameter(0);
  double eamp= fitH->GetParError(0);
  double lda = fitH->GetParameter(1);
  double elda= fitH->GetParError(1);
  double sg1 = fitH->GetParameter(2);
  double esg1= fitH->GetParError(2);
  double fr2 = fitH->GetParameter(3);
  double efr2= fitH->GetParError(3);
  double fr3 = fitH->GetParameter(4);
  double efr3= fitH->GetParError(4);
  double fr4 = fitH->GetParameter(5);
  double efr4= fitH->GetParError(5);
  double fr1 = 1 - fr2 - fr3 - fr4;
  double ncs = fitH->GetChisquare()/fitH->GetNDF();
  double ba = fitH->GetParameter(6);
  double eba= fitH->GetParError(6);
  double bsl = fitH->GetParameter(7);
  double ebsl= fitH->GetParError(7);

  // saving fit
  ofstream outfit;
  outfit.open( Form("%s/SEN%03d/%s.dat",run,key/128,outname.Data()) );
  outfit << amp << " " << eamp << endl;
  outfit << lda << " " << elda << endl;
  outfit << sg1 << " " << esg1 << endl;
  outfit << fr2 << " " << efr2 << endl;
  outfit << fr3 << " " << efr3 << endl;
  outfit << fr4 << " " << efr4 << endl;
  outfit << ba  << " " << eba  << endl;
  outfit << bsl << " " << ebsl << endl;
  outfit << ncs << endl;
  outfit.close();
  cout << "Parameters saved to ";
  cout << outname.Data() << ".dat" << endl;

  // draw
  if(!draw) return;

  gStyle->SetOptFit(0);
  gStyle->SetOptStat(0);
  out->Draw("HE");
  double ymax = out->GetBinContent( out->FindBin(xfit_min) )*1.5;
  out->GetYaxis()->SetRangeUser(0.5,ymax);
  out->GetXaxis()->SetRangeUser(-5,125);
  out->Sumw2();
  out->SetLineColor(kBlack);
  out->SetMarkerStyle(20);
  out->SetTitle("");
  out->GetXaxis()->SetTitle("ADC-PED (a.u.)");
  BGR->Draw("SAME");
  MIPH1->Draw("SAME");
  MIPH2->Draw("SAME");
  MIPH3->Draw("SAME");
  MIPH4->Draw("SAME");
  fitH->SetRange(xfit_min,xfit_max);
  fitH->Draw("SAME");
  TLatex *text = new TLatex();
  text->DrawLatex(0, (1.03*(ymax)), inname.Data() );
  text->DrawLatex(30, (0.83*(ymax)), Form("Entries  %d",entries) );
  text->DrawLatex(30, (0.73*(ymax)), Form("State  %d",state) );
  text->DrawLatex(30, (0.53*(ymax)), Form("#lambda  %.1f #pm %.1f",lda,elda) );
  text->DrawLatex(30, (0.43*(ymax)), Form("#sigma  %.1f #pm %.1f",sg1,esg1) );
  text->SetTextColor(kRed-3);
  text->DrawLatex(30, (0.63*(ymax)), Form("#Chi^{2} / NDF  %.2f",ncs) );
  text->SetTextColor(kBlue-3);
  text->DrawLatex(75, (0.73*(ymax)), Form("#Alpha  %.0f #pm %.0f",fitH->GetParameter(0),fitH->GetParError(0)) );
  text->SetTextColor(kCyan-3);
  text->DrawLatex(75, (0.63*(ymax)), Form("f_{1}  %.2f",fr1) );
  text->SetTextColor(kGreen-3);
  text->DrawLatex(75, (0.53*(ymax)), Form("f_{2}  %.2f #pm %.2f",fr2,efr2) );
  text->SetTextColor(kOrange-3);
  text->DrawLatex(75, (0.43*(ymax)), Form("f_{3}  %.2f #pm %.2f",fr3,efr3) );
  text->SetTextColor(kMagenta-3);
  text->DrawLatex(75, (0.33*(ymax)), Form("f_{4}  %.2f #pm %.2f",fr4,efr4) );
  text->SetTextColor(kGray);
  text->DrawLatex(75, (0.83*(ymax)), Form("b  %.2f",bsl) );
  text->SetTextColor(kBlack);
  text->SetTextSize(0.035);
  text->SetTextColor( kRed-3 );
  text->DrawLatex(30, (0.93*(ymax)), "e^{bx} + #Alpha ( f_{1} L_{1}(x) + f_{2} L_{2}(x) + f_{3} L_{3}(x) + f_{4} L_{4}(x))");
  main->SaveAs( Form("%s/SEN%03d/%s.eps",run,key/128,outname.Data()), "eps" );
  return;
}
Пример #30
0
void Find_Bpt()
{
  
  double BpT[100]={0},BpTEr[100]={0},JpT[100]={0};
  double BpTPlus[100]={0},BpTMinus[100]={0};
  
  //double a0 = 0.604865,a0Er = 0.00790439,a1 = 1.03837, a1Er = 0.00381658;
  //double a0 = 0.680535 ,a0Er =0.00465789 ,a1 =0.978251 , a1Er =0.0010945 ; //pol1
  //double a0 =0.767454,a0Er =0.00637919 ,a1 =0.926482, a1Er =0.00281732; // pol2

  // Acceptance
  //double a0 =0.627337,a0Er =0.0049568,a1 =1.02592, a1Er =0.0010564; // pol1
  //double a0 =0.742605,a0Er =0.00714768 ,a1 =0.957962, a1Er =0.00321474; // pol2

  //New Acceptance
  //double a0 = 0.718407,a0Er =0.0106664 ,a1 =1.1037, a1Er =0.00138381; //pol1
  double a0 =0.491983 ,a0Er =0.0178676 ,a1 =1.1242, a1Er =0.00296712; //pol1
  
  char OutTextFile[100]; 
  sprintf(OutTextFile,"Find_BpT.txt");
  ofstream dataFile(Form(OutTextFile),ios::app);

  for(int i=1;i<=30;i++)
    {
      BpT[i] = a0 + a1*i; 
      BpTPlus[i] = a0 + a0Er + (a1+a1Er)*i; 
      BpTMinus[i] = a0 - a0Er + (a1-a1Er)*i; 
      BpTEr[i] = (BpTPlus[i]-BpTMinus[i])/2.0;
      
      //dataFile<<setprecision(4);
      //if(i==1)dataFile<<" J/#psi pT  "<<" B pT   "<<endl;
      //dataFile<<i<<"    &"<<BpT[i]<<" /pm "<<BpTEr[i]<<endl;
      
      //cout<<i<<"    &"<<BpT[i]<<" /pm "<<BpTEr[i]<<endl;
      //cout<<"==============================================="<<endl;
    }
  
  // Pt bin sizes

  double pt_bound[100] = {0.0};
  double PT[100], DelPT[100];
  double YPT[100], DelYPT[100];

  int Nptbin = 20;
  double step =0.5;

  for (Int_t ih = 0; ih < Nptbin; ih++) {
    pt_bound[ih] = 1 + step*ih;
    pt_bound[ih+1] = 1 + step*(ih+1);
    PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0;
    DelPT[ih] = (pt_bound[ih+1] - pt_bound[ih])/2.0;
  }

  char namePt[500];
  char text[100],text1[100],text2[100];

  TFile *fpT = new TFile("hist1.root");
  //  TH2D *JPt_BPt = (TH2D*)fpT->Get("JpTBpTAccpt");
  TH2D *JPt_BPt = (TH2D*)fpT->Get("JpTBpT");
  
  new TCanvas;
  JPt_BPt->Draw("colz");

  TH1D *service = (TH1D*)JPt_BPt->ProjectionX("service");
  
  //service->Draw();
  //cout<<" service  "<<service<<endl;

  int pt_bin_bound[100];

  TH1D *ProfY_BPt[100];

  cout<<"  J/psi pT  " << "  B pT Mean  "<< "  BpT RMS  " <<endl;
  dataFile<<"  J/psi pT  " << "  B pT Mean  "<< "  BpT RMS  " <<endl;

  for (Int_t ih = 0; ih < Nptbin; ih++) {
  
    
    pt_bin_bound[ih] = service->FindBin(pt_bound[ih]);
    //cout<<" pt_bin_bound[ih]  "<<pt_bin_bound[ih]<<endl;
    
    pt_bin_bound[ih+1] = service->FindBin(pt_bound[ih+1]);
    //cout<<" pt_bin_bound[ih+1]  "<<pt_bin_bound[ih+1] -1<<endl;
    
    sprintf(namePt,"BPt_%d",ih);
    
    ProfY_BPt[ih] = (TH1D*)JPt_BPt->ProjectionY(namePt, pt_bin_bound[ih], pt_bin_bound[ih+1]-1);
    sprintf(text," %.1f-%.1f ",  service->GetBinLowEdge(pt_bin_bound[ih]), 
	      service->GetBinLowEdge(pt_bin_bound[ih+1]-1)+service->GetBinWidth(pt_bin_bound[ih+1]));
    
    dataFile<<setprecision(2);

    cout<< text <<"  "<< ProfY_BPt[ih]->GetMean()<<" /pm "<< ProfY_BPt[ih]->GetRMS()<< endl<<endl;

    YPT[ih] = ProfY_BPt[ih]->GetMean();
    DelYPT[ih] = ProfY_BPt[ih]->GetRMS();

    cout<< text <<"  "<< YPT[ih] <<" /pm "<<  DelYPT[ih]<< endl<<endl;

    sprintf(text1," %.1f ", YPT[ih]);
    sprintf(text2," %.1f ", DelYPT[ih]);
    dataFile<< text <<"  &"<< text1<<" /pm   "<< text2<< endl<<endl;

    /*
    if(ih ==1 || ih ==4 ||ih ==5 ||ih == 9 ||ih ==14 ||ih ==19 || ih ==29)
      {
	new TCanvas;
	ProfY_BPt[ih]->Draw();
      }
    */
  }
  
  dataFile.close();


  /* TGraphErrors *gr_BpTvsJpT = new TGraphErrors(Nptbin, PT, YPT, DelPT, DelYPT);
  TF1 *func_BpTvsJpT = new TF1("pol1", pol1, 0, 24, 2); 
  func_BpTvsJpT->SetLineColor(2);
  gr_BpTvsJpT->Fit("pol1","","",0,24);
  gr_BpTvsJpT->GetXaxis()->SetRangeUser(0,25);
  // gr_BpTvsJpT->GetYaxis()->SetRangeUser(0,25);
  gr_BpTvsJpT->Draw("ap");
  func_BpTvsJpT->Draw("same");
  */

  TGraphErrors *gr_BpTvsJpT = new TGraphErrors(Nptbin, PT, YPT, DelPT, DelYPT);
  TF1 *func_BpTvsJpT = new TF1("pol1", pol1, 0, 10, 2); 
  func_BpTvsJpT->SetLineColor(2);
  gr_BpTvsJpT->Fit("pol1","","",0,6);
  gr_BpTvsJpT->GetXaxis()->SetRangeUser(0,10);
  gr_BpTvsJpT->Draw("ap");
  func_BpTvsJpT->Draw("same");
}