示例#1
0
void Yield1S(){
  
  TFile *f = new TFile("Upsilon_2D_10ptbins.root");
  TH2D *H;
  H = (TH2D*)gFile->Get("fS1Yield");
  double tot(0.); double totE(0.); 
  
  ofstream OUT("Yield_1S.tex");
  OUT << "% ----------------------------------------------------------------------" << endl;
  OUT << "% -- Yields" << endl;
  
  for ( int x = 1; x <= H->GetNbinsX(); ++x ){
    OUT << Form("\\vdef{%iS_Rap_bin%iLowEdge} {\\ensuremath{ {%.1f } } }",1, x, H->GetXaxis()->GetBinLowEdge(x) ) << endl;
    if ( x == H->GetNbinsX() ) OUT << Form("\\vdef{%iS_Rap_bin%iHighEdge} {\\ensuremath{ {%.1f } } }",1 , x, H->GetXaxis()->GetBinUpEdge(x) ) << endl;
    //OUT << Form("\\vdef{%iS_bin%iContent} {\\ensuremath{ {%.0f } } }",1, x, H->GetBinContent(x) ) << endl;
    //OUT << Form("\\vdef{%iS_bin%iError} {\\ensuremath{ {%.0f } } }",1, x, H->GetBinError(x) ) << endl;
  }	
  
  for ( int x = 1; x <= H->GetNbinsY(); ++x ){
    OUT << Form("\\vdef{%iS_Pt_bin%iLowEdge} {\\ensuremath{ {%.1f } } }",1, x, H->GetYaxis()->GetBinLowEdge(x) ) << endl;
    if ( x == H->GetNbinsY() ) OUT << Form("\\vdef{%iS_Pt_bin%iHighEdge} {\\ensuremath{ {%.1f } } }",1 , x, H->GetYaxis()->GetBinUpEdge(x) ) << endl;
  }  
  
  for ( int x = 1; x <= H->GetNbinsX(); ++x ){
    for ( int y = 1; y <= H->GetNbinsY(); ++y ){
      OUT << Form("\\vdef{Yield%iS_bin%i_%iContent} {\\ensuremath{ {%.0f } } }",1, x, y, H->GetCellContent(x,y) ) << endl;
      OUT << Form("\\vdef{Yield%iS_bin%i_%iError} {\\ensuremath{ {%.0f } } }",1, x, y, H->GetCellError(x,y) ) << endl;
    }  
  }
  
  OUT.close();
  
}
示例#2
0
TMatrixD convertHistToMatrix(const TH2D& from)
{
    TMatrixD matrix(from.GetNbinsX(),from.GetNbinsY());
    for (int row=0; row<from.GetNbinsX();++row){
        for (int col=0; col<from.GetNbinsY(); ++col) {
            (matrix)[row][col]=(from).GetBinContent(row+1,col+1);
        }
    }
    return matrix;
}
示例#3
0
TH2D* GetJetCorrFunc2D_doublegaussian(int itrg, int jass)
{
                    TH2D* hcorr = (TH2D*)GetRawCorrFunc2D_ratio(itrg,jass);
                    TH2D* hcorr_clone = (TH2D*)hcorr->Clone(Form("corr_clone_itrg%d_jass%d",itrg,jass));
                    hcorr_clone->Reset();
		    for(int ietabin=1;ietabin<=hcorr->GetNbinsX();ietabin++)
		    {
                      TH1D* hcorrphi = (TH1D*)hcorr->ProjectionY(Form("corrphi_%d",ietabin),ietabin,ietabin,"e");  
                      float min = hcorrphi->GetMinimum();
                      hcorrphi->SetAxisRange(-1,1,"X");
                      float nearmax = hcorrphi->GetMaximum();
                      hcorrphi->SetAxisRange(PI-1,PI+1,"X");
                      float awaymax = hcorrphi->GetMaximum();

		      TF1* fitfunc = new TF1("fitfunc",doubleGaussian,-PI/2.,3.*PI/2.,5);		    
                      fitfunc->SetParameters(min,nearmax-min,0.3,awaymax-min,0.5);  
                      fitfunc->SetParLimits(0,0,100000);
                      fitfunc->SetParLimits(1,0,100000);
                      fitfunc->SetParLimits(2,0,100000);
                      fitfunc->SetParLimits(3,0,100000);
                      fitfunc->SetParLimits(4,0,100000);		    
		      for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit(Form("fitfunc_%d",ietabin),"RNO");                     
		      float level = fitfunc->GetParameter(0);

		      for(int iphibin=1;iphibin<=hcorr->GetNbinsY();iphibin++) 
                        hcorr_clone->SetBinContent(ietabin,iphibin,hcorr->GetBinContent(ietabin,iphibin)-level);                      
                      delete fitfunc;
		    }

                    float max = hcorr_clone->GetBinContent(hcorr_clone->GetMaximumBin());
                    hcorr_clone->SetAxisRange(ymin,max*1.3,"Z");
                    return hcorr_clone;
}
示例#4
0
TH2D* GetJetCorrFunc2D_ZYAM(int itrg, int jass)
{
                    TH2D* hcorr = (TH2D*)GetRawCorrFunc2D_ratio(itrg,jass);
                    TH2D* hcorr_clone = (TH2D*)hcorr->Clone(Form("corr_clone_itrg%d_jass%d",itrg,jass));
                    hcorr_clone->Reset();
		    for(int ietabin=1;ietabin<=hcorr->GetNbinsX();ietabin++)
		    {
                      TH1D* hcorrphi = (TH1D*)hcorr->ProjectionY(Form("corrphi_%d",ietabin),ietabin,ietabin,"e");  
                     // hcorrphi->SetAxisRange(0.35,1.57,"X");
                      double histminX = hcorrphi->GetBinCenter(hcorrphi->GetMinimumBin());
                      double histminY = hcorrphi->GetBinContent(hcorrphi->GetMinimumBin());
	   	      fitfunc = new TF1(Form("fitfunc_%d",ietabin),"[0]+[1]*(x-[2])*(x-[2])",0.6,1.2);		    
                      fitfunc->SetParameters(histminY,1,histminX);
                      fitfunc->SetParLimits(1,0,0.10000);
                  //    fitfunc->SetParLimits(2,0.35,1.57);
		      for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit(Form("fitfunc_%d",ietabin),"RNO");                     		  
		      float level = fitfunc->GetParameter(0);
		      for(int iphibin=1;iphibin<=hcorr->GetNbinsY();iphibin++) 
                        hcorr_clone->SetBinContent(ietabin,iphibin,hcorr->GetBinContent(ietabin,iphibin)-level);
		    }
                    
                    float max = hcorr_clone->GetBinContent(hcorr_clone->GetMaximumBin());
                    hcorr_clone->SetAxisRange(ymin,max*1.3,"Z");		    
                    return hcorr_clone;
}
示例#5
0
void Matching::postProcessing()
{
  for (unsigned int nsens = 0; nsens < _dutDevice->getNumSensors(); nsens++)
  {
    Mechanics::Sensor* sensor = _dutDevice->getSensor(nsens);

    TH2D* tot = _inPixelTot.at(nsens);
    TH2D* hits = _inPixelTracks.at(nsens);

    assert(hits->GetNbinsX() == tot->GetNbinsX() &&
           hits->GetNbinsY() == tot->GetNbinsY() &&
           "Matching: histograms should have the same number of bins");

    for (int nx = 1; nx <= tot->GetNbinsX(); nx++)
    {
      for (int ny = 1; ny <= tot->GetNbinsY(); ny++)
      {
        const unsigned int num = hits->GetBinContent(nx, ny);
        if (num == 0) continue;
        const double average = tot->GetBinContent(nx, ny) / (double)num;
        tot->SetBinContent(nx, ny, average);
      }
    }

    for (unsigned int axis = 0; axis < 2; axis++)
    {
      TH1D* dist = axis ? _matchDistX.at(nsens) :
                          _matchDistY.at(nsens);

      double pixelWidth = axis ? sensor->getPitchX() :
                                 sensor->getPitchY();
      double beamSigma = axis ? _refDevice->getSensor(0)->getPitchX() :
                                _refDevice->getSensor(0)->getPitchY();

      TF1* fit = Processors::fitPixelBeam(dist, pixelWidth, beamSigma, false);

      std::stringstream ss;
      ss << _dutDevice->getName() << sensor->getName() << "PixelBeamFit"
         << ( axis ? "X" : "Y") << _nameSuffix;
      _plotDir->WriteObject(fit, ss.str().c_str());
    }
  }
}
示例#6
0
void mytestreweight(){


  TFile*finput=new TFile("fworking.root");
  TH1D*hBPtFONLL=(TH1D*)finput->Get("hBPt");
  TH1D*hDPtFONLL=(TH1D*)finput->Get("hDPt");
  TH2D*hD=(TH2D*)finput->Get("hD");
  
   hD->SetXTitle("B p_{T} (GeV/c)");
   hD->SetYTitle("D^{0} p_{T} (GeV/c)");
   hBPtFONLL->SetXTitle("B p_{T} (GeV/c)");
   hDPtFONLL->SetXTitle("D p_{T} (GeV/c)");
  
  TH2D *hDreweight = (TH2D*)hD->Clone("hDreweight");
  TH1D *hBPtPythia = hD->ProjectionX("hBPtPythia");
  TH1D *hDPtPythia = hD->ProjectionY("hDPtPythia");

   for (int x=1;x<=hDreweight->GetNbinsX()+1;x++){  //loop over the B pt bins
      if (hBPtPythia->GetBinContent(x)==0) continue;
      double ratio = hBPtFONLL->GetBinContent(x)/hBPtPythia->GetBinContent(x);  // in each pt bin we calculate the ratio of pythiaB/FONLLB 
       
      for (int y=1;y<=hDreweight->GetNbinsY()+1;y++){   //loop over the D pt bins
         double ratio2 = ratio;                                              //copy the ratio for each B bin
         double val = hDreweight->GetBinContent(x,y)*ratio2;
         double valError = hDreweight->GetBinError(x,y)*ratio2;
	 hDreweight->SetBinContent(x,y,val);
	 hDreweight->SetBinError(x,y,valError);
      }   
   }

  TH1D *hBPtPythiaReweight = hDreweight->ProjectionX("hBPtPythiaReweight");
  TH1D *hDPtPythiaReweight = hDreweight->ProjectionY("hDPtPythiaReweight");
  
  hBPtPythiaReweight->Divide(hBPtFONLL);
   
  TCanvas*canvas=new TCanvas("canvas","canvas",1000,500);  
  canvas->SetLogy();
  canvas->Divide(3,1);
  canvas->cd(1);
  hBPtFONLL->Draw();
  canvas->cd(2);
  hBPtPythia->Draw();
  canvas->cd(3);
  hBPtPythiaReweight->Draw();

}
示例#7
0
void HitInfo::postProcessing()
{
  for (unsigned int nsens = 0; nsens < _device->getNumSensors(); nsens++)
  {
    TH2D* map = _totMap.at(nsens);
    TH2D* count = _totMapCnt.at(nsens);

    for (Int_t x = 1; x <= map->GetNbinsX(); x++)
    {
      for (Int_t y = 1; y <= map->GetNbinsY(); y++)
      {
        const double average = map->GetBinContent(x, y) / count->GetBinContent(x, y);
        map->SetBinContent(x, y, average);
      }
    }
  }
}
示例#8
0
TH2D* frameTH2D(TH2D *in){

	Double_t xw = in->GetXaxis()->GetBinWidth(0);
	Double_t yw = in->GetYaxis()->GetBinWidth(0);

	Int_t nx = in->GetNbinsX();
	Int_t ny = in->GetNbinsY();

	Double_t x0 = in->GetXaxis()->GetXmin();
	Double_t x1 = in->GetXaxis()->GetXmax();

	Double_t y0 = in->GetYaxis()->GetXmin();
	Double_t y1 = in->GetYaxis()->GetXmax();

	TH2D *framed = new TH2D(
			Form("%s framed",in->GetName()),
			Form("%s framed",in->GetTitle()),
			nx + 2, x0-xw, x1+xw,
			ny + 2, y0-yw, y1+yw
			);

	//Copy over the contents
	for(int ix = 1; ix <= nx ; ix++){
		for(int iy = 1; iy <= ny ; iy++){
			framed->SetBinContent(1+ix, 1+iy, in->GetBinContent(ix,iy));
		}
	}
	//Frame with huge values
	nx = framed->GetNbinsX();
	ny = framed->GetNbinsY();
	for(int ix = 1; ix <= nx ; ix++){
		framed->SetBinContent(ix,  1, 1000.);
		framed->SetBinContent(ix, ny, 1000.);
	}
	for(int iy = 2; iy <= ny-1 ; iy++){
		framed->SetBinContent( 1, iy, 1000.);
		framed->SetBinContent(nx, iy, 1000.);
	}

	return framed;
}
示例#9
0
void XS1S(){
  
  TFile *f = new TFile("Upsilon_2D_10ptbins.root");
  TH2D *H;
  H = (TH2D*)gFile->Get("fXS");
  double tot(0.); double totE(0.); 
  
  ofstream OUT("XS_1S.tex");
  OUT << "% ----------------------------------------------------------------------" << endl;
  OUT << "% -- XSections" << endl;
  
  for ( int x = 1; x <= H->GetNbinsX(); ++x ){
    for ( int y = 1; y <= H->GetNbinsY(); ++y ){
      OUT << Form("\\vdef{XS%iS_bin%i_%iContent} {\\ensuremath{ {%.4f } } }",1, x, y, H->GetCellContent(x,y) ) << endl;
      OUT << Form("\\vdef{XS%iS_bin%i_%iError} {\\ensuremath{ {%.4f } } }",1, x, y, H->GetCellError(x,y) ) << endl;
    }  
  }
  
  OUT.close();
  
}
示例#10
0
文件: root.cpp 项目: dnowatsc/rootana
std::pair<Matrix, Matrix> roothist_to_matrix(const TH2D & hist, bool transpose){
    int ngen = hist.GetNbinsY();
    int nreco = hist.GetNbinsX();
    if(transpose){
        swap(ngen, nreco);
    }
    
    Matrix m = Matrix(nreco, ngen);
    Matrix m_e = Matrix(nreco, ngen);
    
    for(int i=0; i<nreco; ++i){
        for(int j=0; j<ngen; ++j){
            int nx = i+1;
            int ny = j+1;
            if(transpose) swap(nx, ny);
            m(i,j) = hist.GetBinContent(nx, ny);
            m_e(i,j) = hist.GetBinError(nx, ny);
        }
    }
    return pair<Matrix, Matrix>(move(m), move(m_e));
}
示例#11
0
TH2D* GetJetCorrFunc2D_ZYA1(int itrg, int jass)
{
                    TH2D* hcorr = (TH2D*)GetRawCorrFunc2D_ratio(itrg,jass);
                    TH2D* hcorr_clone = (TH2D*)hcorr->Clone(Form("corr_clone_itrg%d_jass%d",itrg,jass));
                    hcorr_clone->Reset();
		    for(int ietabin=1;ietabin<=hcorr->GetNbinsX();ietabin++)
		    {
                      TH1D* hcorrphi = (TH1D*)hcorr->ProjectionY(Form("corrphi_%d",ietabin),ietabin,ietabin,"e");  
                      hcorrphi->SetAxisRange(0.5,2.0,"X");
                      double histminY = hcorrphi->GetMinimum();
		      fitfunc = new TF1("fitfunc","[0]+[1]*x",0.8,1.2);		    
                      fitfunc->SetParameters(histminY,0);
                      fitfunc->FixParameter(1,0);
		      for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit(Form("fitfunc_%d",ietabin),"RNO");                     
		      float level = fitfunc->GetParameter(0);
		      for(int iphibin=1;iphibin<=hcorrphi->GetNbinsY();iphibin++)
                        hcorr_clone->SetBinContent(ietabin,iphibin,hcorr->GetBinContent(ietabin,iphibin)-level);
                      delete fitfunc;
		    }

                    float max = hcorr_clone->GetBinContent(hcorr_clone->GetMaximumBin());
                    hcorr_clone->SetAxisRange(ymin,max*1.3,"Z");
                    return hcorr_clone;
}
void drawJetFragBalance_DRDiff(
			       TString inFileName=    "plot/jfhCorrEtaPtBin4RBin20v2_HCPR_J50U_djcalo_Cent0to30_Aj0to100_SubEtaRefl.root",
			       TString inFileNameHyPy="plot/jfhCorrEtaPtBin4RBin20v2_Hydjet_djcalo_Cent0to30_Aj0to100_SubEtaRefl.root",
    TString title = "test",
    Int_t drawMode=1,
			       Int_t doLeg=1,
bool cumulative = 1
    ) {
  TFile *f = new TFile(inFileName);
  TString inFileNameStrip(inFileName); inFileNameStrip.ReplaceAll(".root","");

  TH2D * hPtPNDR = (TH2D*) f->Get("hPtPNDR");
  TH2D * hPtPADR = (TH2D*) f->Get("hPtPADR");
  TH2D * hPtPNDRBg = (TH2D*) f->Get("hPtPNDRBg");
  TH2D * hPtPADRBg = (TH2D*) f->Get("hPtPADRBg");
  TH2D * hPtPNDRBgSub = (TH2D*)hPtPNDR->Clone(inFileNameStrip+"hPtPNDRBgSub");
  TH2D * hPtPADRBgSub = (TH2D*)hPtPADR->Clone(inFileNameStrip+"hPtPADRBgSub");
  hPtPNDRBgSub->Add(hPtPNDR,hPtPNDRBg,1,-1);
  hPtPADRBgSub->Add(hPtPADR,hPtPADRBg,1,-1);

  TFile *fhypy = new TFile(inFileNameHyPy);
  TH2D * hPtPNDRHyPy = (TH2D*) fhypy->Get("hPtPNDR");
  TH2D * hPtPADRHyPy = (TH2D*) fhypy->Get("hPtPADR");
  TH2D * hPtPNDRBgHyPy = (TH2D*) fhypy->Get("hPtPNDRBg");
  TH2D * hPtPADRBgHyPy = (TH2D*) fhypy->Get("hPtPADRBg");
  TH2D * hPtPNDRBgSubHyPy = (TH2D*)hPtPNDR->Clone(inFileNameStrip+"hPtPNDRBgSubHyPy");
  TH2D * hPtPADRBgSubHyPy = (TH2D*)hPtPADR->Clone(inFileNameStrip+"hPtPADRBgSubHyPy");
  hPtPNDRBgSubHyPy->Add(hPtPNDRHyPy,hPtPNDRBgHyPy,1,-1);
  hPtPADRBgSubHyPy->Add(hPtPADRHyPy,hPtPADRBgHyPy,1,-1);

  // Get Pt info
  Int_t numBinsPt=hPtPNDR->GetNbinsX();
  Int_t numBinsDR=hPtPNDR->GetNbinsY();
  TH1D * hPt = (TH1D*)hPtPNDR->ProjectionX("hPt");
  cout << "Pt bins: " << numBinsPt << endl;

  Double_t totPtBgSubNr=hPtPNDRBgSub->Integral();
  Double_t totPtBgSubAw=hPtPADRBgSub->Integral();

  Double_t totPtBgSubNrHyPy=hPtPNDRBgSubHyPy->Integral();
  Double_t totPtBgSubAwHyPy=hPtPADRBgSubHyPy->Integral();

  int ptUp = 2;
  TH1D * hDRBgSubNr = (TH1D*)hPtPNDRBgSub->ProjectionY(inFileNameStrip+"hDRBgSubNr",1,ptUp);
  TH1D * hDRBgSubAw = (TH1D*)hPtPADRBgSub->ProjectionY(inFileNameStrip+"hDRBgSubAw",1,ptUp);
  TH1D * hDRBgSubNrHyPy = (TH1D*)hPtPNDRBgSubHyPy->ProjectionY(inFileNameStrip+"hDRBgSubNrHyPy",1,ptUp);
  TH1D * hDRBgSubAwHyPy = (TH1D*)hPtPADRBgSubHyPy->ProjectionY(inFileNameStrip+"hDRBgSubAwHyPy",1,ptUp);
  // Print
  cout << Form("%.1f < p_{T} < %.1f GeV/c: ",hPt->GetBinLowEdge(1),hPt->GetBinLowEdge(ptUp+1)) << " SigSubBkg Integral - Nr: " << endl;
  cout << " Data - Nr: " << hDRBgSubNr->Integral() << " Aw: " << hDRBgSubAw->Integral() << endl;
  cout << " Pythia+Hydjet - Nr: " << hDRBgSubNrHyPy->Integral() << " Aw: " << hDRBgSubAwHyPy->Integral() << endl;

  if (drawMode==1) TCanvas * c6 = new TCanvas("c6","c6",500,500);
  hDRBgSubNr->Scale(1./totPtBgSubNr);
  hDRBgSubAw->Scale(1./totPtBgSubAw);
  hDRBgSubNrHyPy->Scale(1./totPtBgSubNrHyPy);
  hDRBgSubAwHyPy->Scale(1./totPtBgSubAwHyPy);

  if(cumulative){
     hDRBgSubNr = IntegrateFromLeft(hDRBgSubNr);
     hDRBgSubAw = IntegrateFromLeft(hDRBgSubAw);
     hDRBgSubNrHyPy = IntegrateFromLeft(hDRBgSubNrHyPy);
     hDRBgSubAwHyPy = IntegrateFromLeft(hDRBgSubAwHyPy);
  }

  // Set Styles
  hDRBgSubNr->SetMarkerStyle(kOpenSquare);
  mcStyle1(hDRBgSubNrHyPy);
  mcStyle2(hDRBgSubAwHyPy);
  hDRBgSubNrHyPy->SetMarkerStyle(0);
  hDRBgSubAwHyPy->SetMarkerStyle(0);
  // Draw
  hDRBgSubNrHyPy->SetTitle(";#DeltaR_{max};F(#DeltaR<#DeltaR_{max})");
  hDRBgSubNrHyPy->SetAxisRange(0,0.784,"X");
  hDRBgSubNrHyPy->SetAxisRange(0,0.7,"Y");
  if(!cumulative){
     hDRBgSubNrHyPy->SetAxisRange(0,0.1,"Y");
  }
  fixedFontHist(hDRBgSubNrHyPy);
  hDRBgSubNrHyPy->DrawCopy("Ehist");
  hDRBgSubAwHyPy->DrawCopy("Ehistsame");
  hDRBgSubNr->DrawCopy("Esame");
  hDRBgSubAw->DrawCopy("Esame");

  if (doLeg==1) {
     TLegend *leg = new TLegend(0.302407,0.67,0.7536548,0.9324599);
    leg->SetFillStyle(0);
    leg->SetBorderSize(0);
    leg->SetTextFont(63);
    leg->SetTextSize(16);
    leg->AddEntry(hDRBgSubNr,Form("%.1f < p_{T} < %.1f GeV/c",hPt->GetBinLowEdge(1),hPt->GetBinLowEdge(ptUp+1)),"");
    leg->AddEntry(hDRBgSubNr,"Data Leading Jet","pl");
    leg->AddEntry(hDRBgSubAw,"Data SubLeading Jet","pl");
    leg->AddEntry(hDRBgSubNrHyPy,"MC Leading Jet","l");
    leg->AddEntry(hDRBgSubAwHyPy,"MC SubLeading Jet","l");
    leg->Draw();
  }
}
void computeAccSelWe_Charge(const TString conf,       // input file
                     const TString outputDir,  // output directory
		     const Int_t   charge,      // 0 = inclusive, +1 = W+, -1 = W-
		     const Int_t   doPU,
		     const Int_t   doScaleCorr,
		     const Int_t   sigma
) {
  gBenchmark->Start("computeAccSelWe");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  const Double_t PT_CUT     = 25;
  const Double_t ETA_CUT    = 2.5;
  const Double_t ELE_MASS = 0.000511;

  const Double_t ETA_BARREL = 1.4442;
  const Double_t ETA_ENDCAP = 1.566;

  const Double_t VETO_PT   = 10;
  const Double_t VETO_ETA  = 2.5;

  const Double_t ECAL_GAP_LOW  = 1.4442;
  const Double_t ECAL_GAP_HIGH = 1.566;

  const Int_t BOSON_ID  = 24;
  const Int_t LEPTON_ID = 11;
 
  // efficiency files
  TString dataHLTEffName(   "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/MG/eff.root");
  TString zeeHLTEffName(    "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/CT/eff.root");
  TString dataGsfSelEffName("/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/MG/eff.root");
  TString zeeGsfSelEffName( "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/CT/eff.root");
  if(charge==1) {
    dataHLTEffName    = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/MGpositive/eff.root";
    zeeHLTEffName     = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/CTpositive/eff.root"; 
    dataGsfSelEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/MGpositive_FineBin/eff.root";
    zeeGsfSelEffName  = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/CTpositive/eff.root"; 
  }
  if(charge==-1) {
    dataHLTEffName    = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/MGnegative/eff.root";
    zeeHLTEffName     = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/CTnegative/eff.root";
    dataGsfSelEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/MGnegative_FineBin/eff.root";
    zeeGsfSelEffName  = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/CTnegative/eff.root";
  }

  const TString corrFiles = "../EleScale/76X_16DecRereco_2015_Etunc";

  EnergyScaleCorrection_class eleCorr( corrFiles.Data()); eleCorr.doScale= true; eleCorr.doSmearings =true;

  // load pileup reweighting file
  TFile *f_rw = TFile::Open("../Tools/puWeights_76x.root", "read");
  TH1D *h_rw = (TH1D*) f_rw->Get("puWeights");

  TFile *f_r9 = TFile::Open("../EleScale/transformation.root","read");
  TGraph* gR9EB = (TGraph*) f_r9->Get("transformR90");
  TGraph* gR9EE = (TGraph*) f_r9->Get("transformR91");

  TFile *f_hlt_data;
  TFile *f_hlt_mc;

  if(charge==1){
    f_hlt_data = TFile::Open("/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/Nominal/EleTriggerTF1_Data_Positive.root");
    f_hlt_mc   = TFile::Open("/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/Nominal/EleTriggerTF1_MC_Positive.root");
  }
  if(charge==-1){
    f_hlt_data = TFile::Open("/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/Nominal/EleTriggerTF1_Data_Negative.root");
    f_hlt_mc   = TFile::Open("/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/Nominal/EleTriggerTF1_MC_Negative.root");
  }
 
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  vector<TString> fnamev;  // file name per input file
  vector<TString> labelv;  // TLegend label per input file
  vector<Int_t>   colorv;  // plot color per input file
  vector<Int_t>   linev;   // plot line style per input file

  //
  // parse .conf file
  //
  ifstream ifs;
  ifs.open(conf.Data());
  assert(ifs.is_open());
  string line;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    
    string fname;
    Int_t color, linesty;
    stringstream ss(line);
    ss >> fname >> color >> linesty;
    string label = line.substr(line.find('@')+1);
    fnamev.push_back(fname);
    labelv.push_back(label);
    colorv.push_back(color);
    linev.push_back(linesty);
  }
  ifs.close();

  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  
  //
  // Get efficiency
  //
  TFile *dataHLTEffFile = new TFile(dataHLTEffName);
  CEffUser2D dataHLTEff;
  TH2D *hHLTErr=0, *hHLTErrB=0, *hHLTErrE=0;
  if(dataHLTEffName) {
    dataHLTEff.loadEff((TH2D*)dataHLTEffFile->Get("hEffEtaPt"),
                       (TH2D*)dataHLTEffFile->Get("hErrlEtaPt"),
                       (TH2D*)dataHLTEffFile->Get("hErrhEtaPt"));
    
    TH2D* h =(TH2D*)dataHLTEffFile->Get("hEffEtaPt");
    hHLTErr  = new TH2D("hHLTErr", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hHLTErrB = new TH2D("hHLTErrB","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hHLTErrE = new TH2D("hHLTErrE","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  }
  
  TFile *zeeHLTEffFile = new TFile(zeeHLTEffName);
  CEffUser2D zeeHLTEff;
  if(zeeHLTEffName) {
    zeeHLTEff.loadEff((TH2D*)zeeHLTEffFile->Get("hEffEtaPt"),
                      (TH2D*)zeeHLTEffFile->Get("hErrlEtaPt"),
                      (TH2D*)zeeHLTEffFile->Get("hErrhEtaPt"));
  }
  
  TFile *dataGsfSelEffFile = new TFile(dataGsfSelEffName);
  CEffUser2D dataGsfSelEff;
  TH2D *hGsfSelErr=0, *hGsfSelErrB=0, *hGsfSelErrE=0;
  if(dataGsfSelEffName) {
    dataGsfSelEff.loadEff((TH2D*)dataGsfSelEffFile->Get("hEffEtaPt"),
                       (TH2D*)dataGsfSelEffFile->Get("hErrlEtaPt"),
                       (TH2D*)dataGsfSelEffFile->Get("hErrhEtaPt"));
    
    TH2D* h =(TH2D*)dataGsfSelEffFile->Get("hEffEtaPt");
    hGsfSelErr  = new TH2D("hGsfSelErr", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hGsfSelErrB = new TH2D("hGsfSelErrB","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hGsfSelErrE = new TH2D("hGsfSelErrE","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  }
  
  TFile *zeeGsfSelEffFile = new TFile(zeeGsfSelEffName);
  CEffUser2D zeeGsfSelEff;
  if(zeeGsfSelEffName) {
    zeeGsfSelEff.loadEff((TH2D*)zeeGsfSelEffFile->Get("hEffEtaPt"),
                      (TH2D*)zeeGsfSelEffFile->Get("hErrlEtaPt"),
                      (TH2D*)zeeGsfSelEffFile->Get("hErrhEtaPt"));
  }
  
  // Data structures to store info from TTrees
  baconhep::TEventInfo    *info = new baconhep::TEventInfo();
  baconhep::TGenEventInfo *gen  = new baconhep::TGenEventInfo();
  TClonesArray *electronArr = new TClonesArray("baconhep::TElectron");
  TClonesArray *genPartArr  = new TClonesArray("baconhep::TGenParticle");
  TClonesArray *vertexArr  = new TClonesArray("baconhep::TVertex");
  
  TFile *infile=0;
  TTree *eventTree=0;

  // Variables to store acceptances and uncertainties (per input file)
  vector<Double_t> nEvtsv, nSelv, nSelBv, nSelEv;
  vector<Double_t> accv, accBv, accEv;
  vector<Double_t> accErrv, accErrBv, accErrEv;
  vector<Double_t> nSelCorrv, nSelBCorrv, nSelECorrv;
  vector<Double_t> nSelCorrVarv, nSelBCorrVarv, nSelECorrVarv;
  vector<Double_t> accCorrv, accBCorrv, accECorrv;
  vector<Double_t> accErrCorrv, accErrBCorrv, accErrECorrv;

  const baconhep::TTrigger triggerMenu("../../BaconAna/DataFormats/data/HLT_50nsGRun");
 
  // loop through files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {  

    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << " ..." << endl;
    infile = TFile::Open(fnamev[ifile]); 
    assert(infile);
  
    eventTree = (TTree*)infile->Get("Events"); assert(eventTree);  
    eventTree->SetBranchAddress("Info",             &info); TBranch *infoBr     = eventTree->GetBranch("Info");
    eventTree->SetBranchAddress("GenEvtInfo",        &gen); TBranch *genBr      = eventTree->GetBranch("GenEvtInfo");
    eventTree->SetBranchAddress("GenParticle",&genPartArr); TBranch *genPartBr  = eventTree->GetBranch("GenParticle");
    eventTree->SetBranchAddress("Electron",  &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron");
    eventTree->SetBranchAddress("PV",   &vertexArr); TBranch *vertexBr = eventTree->GetBranch("PV");

    nEvtsv.push_back(0);
    nSelv.push_back(0);
    nSelBv.push_back(0);
    nSelEv.push_back(0);
    nSelCorrv.push_back(0);
    nSelBCorrv.push_back(0);
    nSelECorrv.push_back(0);
    nSelCorrVarv.push_back(0);
    nSelBCorrVarv.push_back(0);
    nSelECorrVarv.push_back(0);
    
    for(Int_t iy=0; iy<=hHLTErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hHLTErr->GetNbinsX(); ix++) {
        hHLTErr ->SetBinContent(ix,iy,0);
        hHLTErrB->SetBinContent(ix,iy,0);
        hHLTErrE->SetBinContent(ix,iy,0);
      }
    }
    for(Int_t iy=0; iy<=hGsfSelErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hGsfSelErr->GetNbinsX(); ix++) {
        hGsfSelErr ->SetBinContent(ix,iy,0);
        hGsfSelErrB->SetBinContent(ix,iy,0);
        hGsfSelErrE->SetBinContent(ix,iy,0);
      }
    }

    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
//      if(ientry==10000) break;
      infoBr->GetEntry(ientry);
      genBr->GetEntry(ientry);      
      genPartArr->Clear(); genPartBr->GetEntry(ientry);
  
      if (charge==-1 && toolbox::flavor(genPartArr, -BOSON_ID)!=LEPTON_ID) continue;
      if (charge==1 && toolbox::flavor(genPartArr, BOSON_ID)!=-LEPTON_ID) continue;
      if (charge==0 && fabs(toolbox::flavor(genPartArr, BOSON_ID))!=LEPTON_ID) continue;
    
      vertexArr->Clear();
      vertexBr->GetEntry(ientry);
      double npv  = vertexArr->GetEntries();
      Double_t weight=gen->weight;
      if(doPU>0) weight*=h_rw->GetBinContent(h_rw->FindBin(info->nPUmean));

      nEvtsv[ifile]+=weight;
      
      // trigger requirement                
      if (!isEleTrigger(triggerMenu, info->triggerBits, kFALSE)) continue;
      
      // good vertex requirement
      if(!(info->hasGoodPV)) continue;
      
      electronArr->Clear();
      electronBr->GetEntry(ientry);
      Int_t nLooseLep=0;
      const baconhep::TElectron *goodEle=0;
      TLorentzVector vEle(0,0,0,0);
      TLorentzVector vElefinal(0,0,0,0);
      Bool_t passSel=kFALSE;
     
      for(Int_t i=0; i<electronArr->GetEntriesFast(); i++) {
        const baconhep::TElectron *ele = (baconhep::TElectron*)((*electronArr)[i]);
	vEle.SetPtEtaPhiM(ele->pt, ele->eta, ele->phi, ELE_MASS);
	
	//double ele_pt = gRandom->Gaus(ele->scEt*getEleScaleCorr(ele->scEta,0), getEleResCorr(ele->scEta,0));
        //double ele_pt = gRandom->Gaus(ele->scEt*getEleScaleCorr(ele->scEta,0), getEleResCorr(ele->scEta,0));

        // check ECAL gap
//        if(fabs(ele->scEta)>=ETA_BARREL && fabs(ele->scEta)<=ETA_ENDCAP) continue;
	if(fabs(vEle.Eta())>=ECAL_GAP_LOW && fabs(vEle.Eta())<=ECAL_GAP_HIGH) continue;
        if(doScaleCorr && (ele->r9 < 1.)){
            float eleSmear = 0.;

            float eleAbsEta   = fabs(vEle.Eta());
            float eleEt       = vEle.E() / cosh(eleAbsEta);
            bool  eleisBarrel = eleAbsEta < 1.4442;

            float eleR9Prime = ele->r9; // r9 corrections MC only
            if(eleisBarrel){
                      eleR9Prime = gR9EB->Eval(ele->r9);}
            else {
                      eleR9Prime = gR9EE->Eval(ele->r9);
            }

            double eleRamdom = gRandom->Gaus(0,1);
            eleSmear = eleCorr.getSmearingSigma(info->runNum, eleisBarrel, eleR9Prime, eleAbsEta, eleEt, 0., 0.);
            float eleSmearEP = eleCorr.getSmearingSigma(info->runNum, eleisBarrel, eleR9Prime, eleAbsEta, eleEt, 1., 0.);
            float eleSmearEM = eleCorr.getSmearingSigma(info->runNum, eleisBarrel, eleR9Prime, eleAbsEta, eleEt, -1., 0.);

            if(sigma==0){
              (vEle) *= 1. + eleSmear * eleRamdom;
            }else if(sigma==1){
              (vEle) *= 1. + eleSmearEP * eleRamdom;
            }else if(sigma==-1){
              (vEle) *= 1.  + eleSmearEM * eleRamdom;
            }
        }

        
//        if(fabs(ele->scEta) > VETO_ETA) continue;             // loose lepton |eta| cut
//        if(ele->scEt < VETO_PT)  continue;             // loose lepton pT cut
//        if(passEleLooseID(ele,info->rhoIso)) nLooseLep++;     // loose lepton selection
        if(fabs(vEle.Eta())    > VETO_ETA) continue;
        if(vEle.Pt()           < VETO_PT)  continue;
        if(passEleLooseID(ele, vEle, info->rhoIso)) nLooseLep++;

        if(nLooseLep>1) {  // extra lepton veto
          passSel=kFALSE;
          break;
        }

//        if(fabs(ele->scEta) > ETA_CUT && fabs(ele->eta) > ETA_CUT)       continue;  // lepton |eta| cut
//        if(ele->pt < PT_CUT && ele->scEt < PT_CUT)  	     continue;  // lepton pT cut
//        if(!passEleID(ele,info->rhoIso))     continue;  // lepton selection
        if(vEle.Pt()           < PT_CUT)     continue;  // lepton pT cut
        if(fabs(vEle.Eta())    > ETA_CUT)    continue;  // lepton |eta| cut
        if(!passEleID(ele, vEle, info->rhoIso))     continue;  // lepton selection

	if(!isEleTriggerObj(triggerMenu, ele->hltMatchBits, kFALSE, kFALSE)) continue;
        //if(!(ele->hltMatchBits[trigObjHLT])) continue;  // check trigger matching

	if(charge!=0 && ele->q!=charge) continue;  // check charge (if necessary)
        
	passSel=kTRUE;
        goodEle = ele;  
	vElefinal = vEle;
      }
      
      if(passSel) {
        
	/******** We have a W candidate! HURRAY! ********/
        Bool_t isBarrel = (fabs(vElefinal.Eta())<ETA_BARREL) ? kTRUE : kFALSE;

        Double_t corr=1;
        if(dataHLTEffFile && zeeHLTEffFile) {
//          Double_t effdata = dataHLTEff.getEff(vElefinal.Eta(), vElefinal.Pt());
//          Double_t effmc   = zeeHLTEff.getEff(vElefinal.Eta(), vElefinal.Pt());

	  char funcname[20];
	  sprintf(funcname, "fitfcn_%d", getEtaBinLabel(vElefinal.Eta()));
	  TF1 *fdt = (TF1*)f_hlt_data->Get(funcname);
	  TF1 *fmc = (TF1*)f_hlt_mc  ->Get(funcname);
	  Double_t effdata = fdt->Eval(TMath::Min(vElefinal.Pt(),119.0));
	  Double_t effmc   = fmc->Eval(TMath::Min(vElefinal.Pt(),119.0));
	  delete fdt;
	  delete fmc;

	  corr *= effdata/effmc;
        }
        if(dataGsfSelEffFile && zeeGsfSelEffFile) {
          Double_t effdata = dataGsfSelEff.getEff(vElefinal.Eta(), vElefinal.Pt());
          Double_t effmc   = zeeGsfSelEff.getEff(vElefinal.Eta(), vElefinal.Pt());
          corr *= effdata/effmc;
        }

        if(dataHLTEffFile && zeeHLTEffFile) {
          Double_t effdata = dataHLTEff.getEff(vElefinal.Eta(), vElefinal.Pt());
          Double_t effmc   = zeeHLTEff.getEff(vElefinal.Eta(), vElefinal.Pt());
          Double_t errdata = TMath::Max(dataHLTEff.getErrLow(vElefinal.Eta(), vElefinal.Pt()),dataHLTEff.getErrHigh(vElefinal.Eta(), vElefinal.Pt()));
          Double_t errmc   = TMath::Max(zeeHLTEff.getErrLow(vElefinal.Eta(), vElefinal.Pt()), zeeHLTEff.getErrHigh(vElefinal.Eta(), vElefinal.Pt()));
          Double_t err     = corr*sqrt(errdata*errdata/effdata/effdata+errmc*errmc/effmc/effmc);
          hHLTErr->Fill(vElefinal.Eta(),vElefinal.Pt(),err);
          if(isBarrel) hHLTErrB->Fill(vElefinal.Eta(),vElefinal.Pt(),err);
          else         hHLTErrE->Fill(vElefinal.Eta(),vElefinal.Pt(),err);
        }
        if(dataGsfSelEffFile && zeeGsfSelEffFile) {
          Double_t effdata = dataGsfSelEff.getEff(vElefinal.Eta(), vElefinal.Pt());
          Double_t effmc   = zeeGsfSelEff.getEff(vElefinal.Eta(), vElefinal.Pt());
          Double_t errdata = TMath::Max(dataGsfSelEff.getErrLow(vElefinal.Eta(), vElefinal.Pt()),dataGsfSelEff.getErrHigh(vElefinal.Eta(), vElefinal.Pt()));
          Double_t errmc   = TMath::Max(zeeGsfSelEff.getErrLow(vElefinal.Eta(), vElefinal.Pt()), zeeGsfSelEff.getErrHigh(vElefinal.Eta(), vElefinal.Pt()));
          Double_t err     = corr*sqrt(errdata*errdata/effdata/effdata+errmc*errmc/effmc/effmc);
          hGsfSelErr->Fill(vElefinal.Eta(),vElefinal.Pt(),err);
          if(isBarrel) hGsfSelErrB->Fill(vElefinal.Eta(),vElefinal.Pt(),err);
          else         hGsfSelErrE->Fill(vElefinal.Eta(),vElefinal.Pt(),err);
        }
        
	nSelv[ifile]+=weight;
	nSelCorrv[ifile]+=weight*corr;
	nSelCorrVarv[ifile]+=weight*weight*corr*corr;

  	if(isBarrel) { 
	  nSelBv[ifile]+=weight;
	  nSelBCorrv[ifile]+=weight*corr;
	  nSelBCorrVarv[ifile]+=weight*weight*corr*corr;
	  	
	} else { 
	  nSelEv[ifile]+=weight;
	  nSelECorrv[ifile]+=weight*corr;
	  nSelECorrVarv[ifile]+=weight*weight*corr*corr;
	}
      }
    }
    
    Double_t var=0, varB=0, varE=0;
    for(Int_t iy=0; iy<=hHLTErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hHLTErr->GetNbinsX(); ix++) {
        Double_t err;
	err=hHLTErr->GetBinContent(ix,iy);  var+=err*err;
        err=hHLTErrB->GetBinContent(ix,iy); varB+=err*err;
        err=hHLTErrE->GetBinContent(ix,iy); varE+=err*err;
      }
    }

    for(Int_t iy=0; iy<=hGsfSelErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hGsfSelErr->GetNbinsX(); ix++) {
        Double_t err;
	err=hGsfSelErr->GetBinContent(ix,iy);  var+=err*err;
	err=hGsfSelErrB->GetBinContent(ix,iy); varB+=err*err;
	err=hGsfSelErrE->GetBinContent(ix,iy); varE+=err*err;
      }
    }

    nSelCorrVarv[ifile]+=var;
    nSelBCorrVarv[ifile]+=varB;
    nSelECorrVarv[ifile]+=varE;
    
    // compute acceptances
    accv.push_back(nSelv[ifile]/nEvtsv[ifile]);   accErrv.push_back(sqrt(accv[ifile]*(1.+accv[ifile])/nEvtsv[ifile]));
    accBv.push_back(nSelBv[ifile]/nEvtsv[ifile]); accErrBv.push_back(sqrt(accBv[ifile]*(1.+accBv[ifile])/nEvtsv[ifile]));
    accEv.push_back(nSelEv[ifile]/nEvtsv[ifile]); accErrEv.push_back(sqrt(accEv[ifile]*(1.+accEv[ifile])/nEvtsv[ifile]));
    
    accCorrv.push_back(nSelCorrv[ifile]/nEvtsv[ifile]);   accErrCorrv.push_back(accCorrv[ifile]*sqrt(nSelCorrVarv[ifile]/nSelCorrv[ifile]/nSelCorrv[ifile] + 1./nEvtsv[ifile]));
    accBCorrv.push_back(nSelBCorrv[ifile]/nEvtsv[ifile]); accErrBCorrv.push_back(accBCorrv[ifile]*sqrt(nSelBCorrVarv[ifile]/nSelBCorrv[ifile]/nSelBCorrv[ifile] + 1./nEvtsv[ifile]));
    accECorrv.push_back(nSelECorrv[ifile]/nEvtsv[ifile]); accErrECorrv.push_back(accECorrv[ifile]*sqrt(nSelECorrVarv[ifile]/nSelECorrv[ifile]/nSelECorrv[ifile] + 1./nEvtsv[ifile]));
    
    delete infile;
    infile=0, eventTree=0;  
  }
  delete info;
  delete gen;
  delete electronArr;
  
    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  if(charge== 0) cout << " W -> e nu"  << endl;
  if(charge==-1) cout << " W- -> e nu" << endl;
  if(charge== 1) cout << " W+ -> e nu" << endl;
  cout << "  pT > " << PT_CUT << endl;
  cout << "  |eta| < " << ETA_CUT << endl;
  cout << "  Barrel definition: |eta| < " << ETA_BARREL << endl;
  cout << "  Endcap definition: |eta| > " << ETA_ENDCAP << endl;
  cout << endl;
  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    cout << "   ================================================" << endl;
    cout << "    Label: " << labelv[ifile] << endl;
    cout << "     File: " << fnamev[ifile] << endl;
    cout << endl;
    cout << "    *** Acceptance ***" << endl;
    cout << "     barrel: " << setw(12) << nSelBv[ifile] << " / " << nEvtsv[ifile] << " = " << accBv[ifile] << " +/- " << accErrBv[ifile];
    cout << "  ==eff corr==> " << accBCorrv[ifile] << " +/- " << accErrBCorrv[ifile] << endl;
    cout << "     endcap: " << setw(12) << nSelEv[ifile] << " / " << nEvtsv[ifile] << " = " << accEv[ifile] << " +/- " << accErrEv[ifile];
    cout << "  ==eff corr==> " << accECorrv[ifile] << " +/- " << accErrECorrv[ifile] << endl;
    cout << "      total: " << setw(12) << nSelv[ifile]  << " / " << nEvtsv[ifile] << " = " << accv[ifile]  << " +/- " << accErrv[ifile];
    cout << "  ==eff corr==> " << accCorrv[ifile]  << " +/- " << accErrCorrv[ifile] << endl;
    cout << endl;
  }
  
  char txtfname[100];
  sprintf(txtfname,"%s/sel.txt",outputDir.Data());
  ofstream txtfile;
  txtfile.open(txtfname);
  txtfile << "*" << endl;
  txtfile << "* SUMMARY" << endl;
  txtfile << "*--------------------------------------------------" << endl;
  if(charge== 0) txtfile << " W -> e nu"  << endl;
  if(charge==-1) txtfile << " W- -> e nu" << endl;
  if(charge== 1) txtfile << " W+ -> e nu" << endl;
  txtfile << "  pT > " << PT_CUT << endl;
  txtfile << "  |eta| < " << ETA_CUT << endl;
  txtfile << "  Barrel definition: |eta| < " << ETA_BARREL << endl;
  txtfile << "  Endcap definition: |eta| > " << ETA_ENDCAP << endl;
  txtfile << endl;
  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    txtfile << "   ================================================" << endl;
    txtfile << "    Label: " << labelv[ifile] << endl;
    txtfile << "     File: " << fnamev[ifile] << endl;
    txtfile << endl;
    txtfile << "    *** Acceptance ***" << endl;
    txtfile << "     barrel: " << setw(12) << nSelBv[ifile] << " / " << nEvtsv[ifile] << " = " << accBv[ifile] << " +/- " << accErrBv[ifile];
    txtfile << "  ==eff corr==> " << accBCorrv[ifile] << " +/- " << accErrBCorrv[ifile] << endl;
    txtfile << "     endcap: " << setw(12) << nSelEv[ifile] << " / " << nEvtsv[ifile] << " = " << accEv[ifile] << " +/- " << accErrEv[ifile];
    txtfile << "  ==eff corr==> " << accECorrv[ifile] << " +/- " << accErrECorrv[ifile] << endl;
    txtfile << "      total: " << setw(12) << nSelv[ifile]  << " / " << nEvtsv[ifile] << " = " << accv[ifile]  << " +/- " << accErrv[ifile];
    txtfile << "  ==eff corr==> " << accCorrv[ifile]  << " +/- " << accErrCorrv[ifile] << endl;
    txtfile << endl;
  }
  txtfile.close();  
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("computeAccSelWe"); 
}
示例#14
0
// infilename - root file with relevant histograms
// system - PP,APAP,PP
// status - Pass,Fail
// rWrite - 0-no,1-png,2-eps
// rPerformance - 0-no,1-yes (ALICE logo etc.)
// bin: 0 - all, 1- 0:5, 2- 5:10, etc
void drawDCA(const char* infilename, const char* system, const char* status, Int_t rWrite, Int_t rPerformance, int isMC, Int_t bin, Int_t ptrange)
{

    myOptions(0);

    gROOT->ForceStyle();
    gStyle->SetPalette(1.0);

    TDatime now;
    int iDate = now.GetDate();
    int iYear=iDate/10000;
    int iMonth=(iDate%10000)/100;
    int iDay=iDate%100;
    char* cMonth[12]={"Jan","Feb","Mar","Apr","May","Jun",
                      "Jul","Aug","Sep","Oct","Nov","Dec"};
    char cStamp1[25],cStamp2[25];
    sprintf(cStamp1,"%i %s %i",iDay, cMonth[iMonth-1], iYear);
    sprintf(cStamp2,"%i/%.2d/%i",iDay, iMonth, iYear);

    TFile *f = new TFile(infilename, "read");

    // DCA xy
    TH2D* DCAxy =(TH2D*)f->Get(Form("DCARPtcut%s1%stpcM%d","Pass", system,0));


    if (!bin) {
        int minMultBin = 0;
        int maxMultBin = 6; // 8
    }
    else {
        int minMultBin = bin-1;
        int maxMultBin = bin; // 8
    }

    // int minMultBin = 0;
    // int maxMultBin = 0; // 8

    double EvMultall = 0;

    for(int i = minMultBin; i<maxMultBin; i++) {

        TH2D* DCAxyN = (TH2D*)f->Get(Form("DCARPtcut%s1%stpcM%d",status, system,i));
        DCAxy->Add(DCAxyN);

        cout<<i<<" "<<DCAxyN->GetEntries()<<endl;

        //delete hEvMult;
    }


    if (!isMC) {
        TCanvas *c2 = new TCanvas("DCA xy prim", "DCA xy prim");
        c2->SetGridx();
        c2->SetGridy();
        c2->SetFillColor(10);
        c2->SetRightMargin(1.9);
        c2->SetLogz();

        DCAxy->GetXaxis()->SetTitle("DCA_{XY} (cm)");
        DCAxy->GetXaxis()->SetRangeUser(-5.0,5.0);
        DCAxy->GetYaxis()->SetTitle("#it{p}_{T} (GeV/#it{c})");
        // DCAxy->GetZaxis()->SetLabelSize(0.05);
        DCAxy->Draw("colz");
        postprocess(c2,Form("DCAxy%s",status),rWrite,rPerformance,system);

        // TCanvas *c4 = new TCanvas("DCA xy Projection X", "DCA xy Projection X");
        // c4->SetGridx();
        // c4->SetGridy();
        // c4->SetFillColor(10);
        // c4->SetRightMargin(1.9);
        // c4->SetLogy();

        gStyle->SetOptTitle(1);
        TCanvas *myCan = new TCanvas("myCan",cStamp1,600,400);
        myCan->Draw();
        myCan->cd();

        TPad *myPad = new TPad("myPad", "The pad",0,0,1,1);
        myPadSetUp(myPad,0.15,0.04,0.04,0.15);
        myPad->Draw();
        myPad->SetLogy();

        myPad->cd();

        if (ptrange == 0) {
            TH1D* pripp = (TH1D*)DCAxy->ProjectionX("zxc1",1,100);
            pripp->SetTitle("0.5 < #it{p}_{T} < 3 GeV/#it{c}");
        }
        else if (ptrange == 1) {
            TH1D* pripp = (TH1D*)DCAxy->ProjectionX("zxc1",15,33);
            pripp->SetTitle("0.5 < #it{p}_{T} < 1 GeV/#it{c}");
        }
        else if (ptrange == 2) {
            TH1D* pripp = (TH1D*)DCAxy->ProjectionX("zxc1",33,100);
            pripp->SetTitle("1 < #it{p}_{T} < 3 GeV/#it{c}");
        }

        pripp->SetYTitle("Number of Entries (normalized)");
        pripp->GetXaxis()->SetTitleSize(0.068);
        pripp->GetYaxis()->SetTitleSize(0.068);
        pripp->GetXaxis()->SetLabelSize(0.058);
        pripp->GetYaxis()->SetLabelSize(0.058);

        // pripp->SetLabelSize(0.05);
        // DCAxy->ProjectionX("asd",50,100)->SetYTitle("Number of Entries");
        // DCAxy->ProjectionX("asd",50,100)->SetTitle("1.0 < p_{T} < 2.0 GeV");
        // DCAxy->ProjectionX("asd",0,200)->SetTitle("");
        // DCAxy->ProjectionX("asd",50,100)->GetXaxis()->SetNdivisions(8);
        // DCAxy->ProjectionX("asd",50,100)->GetYaxis()->SetNdivisions(8);
        // DCAxy->ProjectionX("asd",50,100)->GetXaxis()->SetTitleSize(0.05);
        // DCAxy->ProjectionX("asd",50,100)->GetYaxis()->SetTitleSize(0.05);
        // DCAxy->ProjectionX("asd",50,100)->GetXaxis()->SetLabelSize(0.05);
        // DCAxy->ProjectionX("asd",50,100)->GetYaxis()->SetLabelSize(0.05);

        pripp->Draw("");

        //if (!isMC) {
        pripp->Scale(1./pripp->Integral());
        TFile* fout = new TFile("dca.root","update");
        pripp->SetName(Form("dcaxyMC%d",isMC));
        pripp->Write();
        //}

        postprocess(myCan,Form("DCAxy%sProX",status),rWrite,rPerformance,system);

    }
    else if (isMC) {

        TH2D* primp =(TH2D*)f->Get(Form("DCARPtcut%s1%stpcM%dprim","Pass", system,0));
        TH2D* weakp =(TH2D*)f->Get(Form("DCARPtcut%s1%stpcM%dweak","Pass", system,0));
        TH2D* matp =(TH2D*)f->Get(Form("DCARPtcut%s1%stpcM%dmat","Pass", system,0));

        // prim 2D
        TCanvas *c3prim = new TCanvas("DCA xy primary", "DCA xy primary");
        c3prim->SetGridx();
        c3prim->SetGridy();
        c3prim->SetFillColor(10);
        c3prim->SetRightMargin(1.9);
        c3prim->SetLogz();

        primp->GetXaxis()->SetTitle("DCA_{XY} (cm)");
        primp->GetXaxis()->SetRangeUser(-5.0,5.0);
        primp->GetYaxis()->SetTitle("#it{p}_{T} (GeV/#it{c})");
        primp->GetZaxis()->SetLabelSize(0.03);
        primp->Draw("colz");
        postprocess(c3prim,Form("DCAxy%s",status),rWrite,rPerformance,system);

        // weak 2D
        TCanvas *c3 = new TCanvas("DCA xy weak", "DCA xy weak");
        c3->SetGridx();
        c3->SetGridy();
        c3->SetFillColor(10);
        c3->SetRightMargin(1.9);
        c3->SetLogz();

        weakp->GetXaxis()->SetTitle("DCA_{XY} (cm)");
        weakp->GetXaxis()->SetRangeUser(-5.0,5.0);
        weakp->GetYaxis()->SetTitle("#it{p}_{T} (GeV/#it{c})");
        weakp->GetZaxis()->SetLabelSize(0.03);
        weakp->Draw("colz");
        postprocess(c3,Form("DCAxy%s",status),rWrite,rPerformance,system);

        // mat 2D
        TCanvas *c4 = new TCanvas("DCA xy mat", "DCA xy mat");
        c4->SetGridx();
        c4->SetGridy();
        c4->SetFillColor(10);
        c4->SetRightMargin(1.9);
        c4->SetLogz();

        matp->GetXaxis()->SetTitle("DCA_{XY} (cm)");
        matp->GetXaxis()->SetRangeUser(-5.0,5.0);
        matp->GetYaxis()->SetTitle("#it{p}_{T} (GeV/#it{c})");
        matp->GetZaxis()->SetLabelSize(0.03);
        matp->Draw("colz");
        postprocess(c4,Form("DCAxy%s",status),rWrite,rPerformance,system);


        // prim proj
        gStyle->SetOptTitle(1);

        TCanvas *myCan3prim = new TCanvas("myCan3prim",cStamp1);
        myCan3prim->Draw();
        myCan3prim->cd();

        TPad *myPad3prim = new TPad("myPad3prim", "The pad3prim",0,0,1,1);
        myPadSetUp(myPad3prim,0.15,0.04,0.04,0.15);
        myPad3prim->Draw();
        myPad3prim->SetLogy();

        myPad3prim->cd();

        TH1D* primpp = (TH1D*)primp->ProjectionX("zxc22",0,100);
        primpp->Draw("");

        cout << primpp->FindBin(-0.1) << endl;
        cout << primpp->FindBin(0.1) << endl;

        cout << "primary in cut- " << primpp->Integral(191,211) << endl;
        cout << "primary all- " << primpp->Integral(1,400) << endl;

        postprocess(myCan3prim,Form("DCAxy%sProX",status),rWrite,rPerformance,system);


        // weak proj
        TCanvas *myCan3 = new TCanvas("myCan3",cStamp1);
        myCan3->Draw();
        myCan3->cd();

        TPad *myPad3 = new TPad("myPad3", "The pad3",0,0,1,1);
        myPadSetUp(myPad3,0.15,0.04,0.04,0.15);
        myPad3->Draw();
        myPad3->SetLogy();

        myPad3->cd();

        TH1D* weakpp = (TH1D*)weakp->ProjectionX("zxc2",0,100);
        weakpp->Draw("");

        cout << "weak in cut- " << weakpp->Integral(191,211) << endl;
        cout << "weak all- " << weakpp->Integral(1,400) << endl;

        postprocess(myCan3,Form("DCAxy%sProX",status),rWrite,rPerformance,system);

        // mat proj
        gStyle->SetOptTitle(1);
        TCanvas *myCan4 = new TCanvas("myCan4",cStamp1);
        myCan4->Draw();
        myCan4->cd();

        TPad *myPad4 = new TPad("myPad4", "The pad4",0,0,1,1);
        myPadSetUp(myPad4,0.15,0.04,0.04,0.15);
        myPad4->Draw();
        myPad4->SetLogy();

        myPad4->cd();

        TH1D* matpp = (TH1D*)matp->ProjectionX("zxc3",0,100);
        matpp->Draw("");

        cout << "material in cut- " << matpp->Integral(191,211) << endl;
        cout << "material all- " << matpp->Integral(1,400) << endl;

        postprocess(myCan4,Form("DCAxy%sProX",status),rWrite,rPerformance,system);

        cout  << "in cut: " << endl;
        cout << "prim - " << primpp->Integral(191,211) / (primpp->Integral(191,211)+weakpp->Integral(191,211)+matpp->Integral(191,211)) << endl;
        cout << "weak - " << weakpp->Integral(191,211) / (primpp->Integral(191,211)+weakpp->Integral(191,211)+matpp->Integral(191,211)) << endl;
        cout << "mat - " << matpp->Integral(191,211) / (primpp->Integral(191,211)+weakpp->Integral(191,211)+matpp->Integral(191,211)) << endl;

        cout << endl << "in cut / all " << endl;
        cout << "prim - " << primpp->Integral(191,211) / primpp->Integral(1,400) << endl;
        cout << "weak - " << weakpp->Integral(191,211) / weakpp->Integral(1,400) << endl;
        cout << "mat - " << matpp->Integral(191,211) / matpp->Integral(1,400) << endl;


        // _____sum____

        TH2D* psum = new TH2D("psum","",400, -2.0, 2.0, 100,0.0,2.0);
        psum->GetXaxis()->SetTitle("DCA_{xy} (cm)");
        psum->GetYaxis()->SetTitle("Number of Entries (normalized)");
        psum->GetXaxis()->SetLimits(-2,2);


        for (int i = 0; i < primp->GetNbinsX(); i++) {
            for (int j = 0; j < primp->GetNbinsY(); j++) {
                psum->SetBinContent(i,j,primp->GetBinContent(i,j)+weakp->GetBinContent(i,j)+matp->GetBinContent(i,j));
            }
        }

        gStyle->SetOptStat(0);

        TCanvas *cansum = new TCanvas("cansum",cStamp1,600,400);
        cansum->Draw();
        cansum->cd();

        TPad *padsum = new TPad("padsum", "The pad4",0,0,1,1);
        myPadSetUp(padsum,0.15,0.04,0.04,0.15);
        padsum->Draw();
        padsum->SetLogy();

        padsum->cd();

        // TCanvas* cansum = new TCanvas("cansum","cansum");
        // cansum->SetLogy();
        //psum->Draw("colz");
        TH1D* asd0 = (TH1D*)psum->ProjectionX("zxc",0,100);

        // asd0->Scale(1./asd0->Integral());
        // TFile* fout = new TFile("dca.root","update");
        // asd0->SetName(Form("dcaxyMC%d",isMC));
        // asd0->Write();

        asd0->GetXaxis()->SetTitle("DCA_{xy} (cm)");
        asd0->GetYaxis()->SetTitle("Number of Entries (normalized)");
        //asd0->SetMaximum(5000);
        //asd0->SetMinimum(0.00008);
        asd0->GetXaxis()->SetNdivisions(8);
        asd0->GetYaxis()->SetNdivisions(8);
        //asd0->GetYaxis()->SetTitleOffset(1.4);
        asd0->GetXaxis()->SetTitleSize(0.068);
        asd0->GetYaxis()->SetTitleSize(0.068);
        asd0->GetXaxis()->SetLabelSize(0.058);
        asd0->GetYaxis()->SetLabelSize(0.058);
        asd0->SetFillColor(kBlack);

        Double_t norm = asd0->Integral();
        //asd0->Scale(1./norm);
        //asd0->SetMinimum(0.00007);

        asd0->SetMarkerSize(1.3);
        asd0->SetMarkerColor(kBlack);
        asd0->SetMarkerStyle(20);
        asd0->Draw("pc");

        primpp->SetFillColor(kGreen+2);
        //primpp->Scale(1./norm);
        primpp->SetMarkerSize(1.3);
        primpp->SetMarkerColor(kGreen+2);
        primpp->SetMarkerStyle(20);
        primpp->Draw("psame");

        matpp->SetFillColor(kRed);
        //matpp->Scale(1./norm);
        matpp->SetMarkerSize(1.3);
        matpp->SetMarkerColor(kRed);
        matpp->SetMarkerStyle(20);
        matpp->Draw("psame");

        weakpp->SetFillColor(kBlue);
        //weakpp->Scale(1./norm);
        weakpp->SetMarkerSize(1.3);
        weakpp->SetMarkerColor(kBlue);
        weakpp->SetMarkerStyle(20);
        weakpp->Draw("psame");



        // _____endofsum____


        TLegend *myLegend = new TLegend(0.6,0.6,0.89,0.89);
        myLegend->SetFillColor(10);
        myLegend->SetBorderSize(0);

        myLegend->AddEntry(asd0,"all","f");
        myLegend->AddEntry(primpp,"primary","f");
        myLegend->AddEntry(weakpp,"weak decay","f");
        myLegend->AddEntry(matpp,"material","f");
        //myLegend->Draw("same");


        // logo

        TLatex *sys = new TLatex(0.16,0.91,"AMPT Pb-Pb #sqrt{s_{NN}} = 2.76 TeV");
        sys->SetNDC();
        sys->SetTextFont(42);
        sys->SetTextSize(0.05);
        sys->SetTextColor(kRed+2);
        sys->Draw();

        TDatime now;
        int iDate = now.GetDate();
        int iYear=iDate/10000;
        int iMonth=(iDate%10000)/100;
        int iDay=iDate%100;
        char* cMonth[12]={"Jan","Feb","Mar","Apr","May","Jun",
                          "Jul","Aug","Sep","Oct","Nov","Dec"};
        char cStamp1[25],cStamp2[25];
        sprintf(cStamp1,"%i %s %i",iDay, cMonth[iMonth-1], iYear);
        sprintf(cStamp2,"%i/%.2d/%i",iDay, iMonth, iYear);


        TText *date = new TText(0.27,0.5,cStamp2);
        date->SetNDC();
        date->SetTextFont(42);
        date->SetTextSize(0.04);
        date->Draw();

        //           //Acquire canvas proportions
//                 Double_t AliLogo_LowX = 0.27;
//                 Double_t AliLogo_LowY = 0.6;
//                 Double_t AliLogo_Height = 0.22;
//                 //ALICE logo is a png file that is 821x798 pixels->should be wider than a square
//                 Double_t AliLogo_Width  = (821./798.) * AliLogo_Height * gPad->GetWh() / gPad->GetWw();

//                 TPad *myPadLogo = new TPad("myPadLogo", "Pad for ALICE Logo",AliLogo_LowX,AliLogo_LowY,AliLogo_LowX+AliLogo_Width,AliLogo_LowY+AliLogo_Height);
//                 //    myPadLogo->SetFillColor(2); // color to first figure out where is the pad then comment !
//                 myPadSetUp(myPadLogo,0,0,0,0);
//                 myPadLogo->SetFixedAspectRatio(1);
//                 myPadLogo->Draw();
//                 myPadLogo->cd();

// //                TASImage *myAliceLogo = new TASImage("alice_preliminary.eps");
//                 TASImage *myAliceLogo = new TASImage("alice_performance.eps");
// //		TASImage *myAliceLogo = new TASImage("alice_logo_transparent.png");
//                 myAliceLogo->Draw();

        DrawALICELogo(0,0.27,0.55,0.7,0.8);

//logo

        // postprocess(cansum,Form("DCAxyMC%s",status),rWrite,rPerformance,system);
        cansum->SaveAs("DCAxyMC.png");
        cansum->SaveAs("DCAxyMC.eps");
    }

//__________________________________________________


}
TCanvas* pHitSpecPosGen( )
{
  TCanvas* c = new TCanvas("cHitSpecPosGen","cHitSpecPosGen",1200,600);
  c->Divide(2,1);
  TVirtualPad* p; TH2D *h; TH2D *hAtPhi0;
  TText t; t.SetTextColor(4);

  p =c->cd(1); p->SetLogy(); p->SetGrid(0,1);
  h = (TH2D*)gROOT->FindObject("hHitSpec_PtVsPhiGen_Minus"); 
  hAtPhi0 = (TH2D*)gROOT->FindObject("hHitSpec_PtVsPhiGenAtPhi0_Minus"); 
  h->GetYaxis()->SetRange(4,33);
  h->GetXaxis()->SetNdivisions(505); h->GetXaxis()->SetLabelSize(0.04);
  h->DrawCopy("box");
  hAtPhi0->SetLineColor(2);
  hAtPhi0->DrawCopy("box same");
  t.DrawTextNDC(0.17,0.15, "BARREL MU MINUS");
  std::cout <<h->GetTitle() << std::endl;
  for (int iy = 1; iy <=h->GetNbinsY(); iy++) {
  std::cout <<" pt: " << h->GetYaxis()->GetBinLowEdge(iy);
  double xmin=100.;
  double xAtMax = 0.; double valAtMax = 0.;
  double xmax=-100.;
  for (int ix = 1; ix <=h->GetNbinsX(); ix++) {
     double val = h->GetBinContent(ix,iy); 
     double xbmin = h->GetXaxis()->GetBinLowEdge(ix);
     double xcent = h->GetXaxis()->GetBinCenter(ix);
     double xbmax = h->GetXaxis()->GetBinUpEdge(ix);
     if (val > valAtMax) { valAtMax = val; xAtMax = xcent; }
     if (val > 1 && (xbmin < xmin)) xmin = xbmin;    
     if (val > 1 && (xbmax > xmax)) xmax = xbmax;    
  }
  std::cout <<"  set DPHI0 = "<<1.025-xAtMax 
            <<"; set DPHI_MARGIN = " <<std::max( (xAtMax-xmin), (xmax-xAtMax))
<<";" << std::endl;
  }

  p =c->cd(2); p->SetLogy(); p->SetGrid(1,1);
  h = (TH2D*)gROOT->FindObject("hHitSpec_PtVsPhiGen_Plus"); 
  hAtPhi0 = (TH2D*)gROOT->FindObject("hHitSpec_PtVsPhiGenAtPhi0_Plus"); 
  h->GetYaxis()->SetRange(4,32);
  h->GetXaxis()->SetNdivisions(505); h->GetXaxis()->SetLabelSize(0.04);
  h->DrawCopy("box");
  hAtPhi0->SetLineColor(2);
  hAtPhi0->DrawCopy("box same");
  t.DrawTextNDC(0.17,0.15, "BARREL MU PLUS");
  std::cout <<h->GetTitle() << std::endl;
  for (int iy = 1; iy <=h->GetNbinsY(); iy++) {
  std::cout <<" pt: " << h->GetYaxis()->GetBinLowEdge(iy);
  double xmin=100.;
  double xAtMax = 0.; double valAtMax = 0.;
  double xmax=-100.;
  for (int ix = 1; ix <=h->GetNbinsX(); ix++) {
     double val = h->GetBinContent(ix,iy); 
     double xbmin = h->GetXaxis()->GetBinLowEdge(ix);
     double xcent = h->GetXaxis()->GetBinCenter(ix);
     double xbmax = h->GetXaxis()->GetBinUpEdge(ix);
     if (val > valAtMax) { valAtMax = val; xAtMax = xcent; }
     if (val > 1 && (xbmin < xmin)) xmin = xbmin;    
     if (val > 1 && (xbmax > xmax)) xmax = xbmax;    
  }
  std::cout <<"  set DPHI0 = "<<1.025-xAtMax 
            <<"; set DPHI_MARGIN = " <<std::max( (xAtMax-xmin), (xmax-xAtMax))
<<";" << std::endl;
  }

  return c;
}
示例#16
0
void computeCleoPdf()
{
  //TString fName = "CLEO_K3PiScan_2009";
  //TString hName = "deltachisq";

  //TString fName = "CLEO_K3PiScan_2014";
  //TString hName = "deltachisq";

  //TString fName = "CLEO_KSKpiScan_2012_FullDP";
  //TString hName = "loglik";

  //TString fName = "CLEO_KSKpiScan_2012_Kst";
  //TString hName = "loglik";

  //TString fName = "CLEO_KPiPi0Scan_2014";
  //TString hName = "deltachisq";

  TString fName = "CLEO_LHCb_K3PiScan_2015";
  TString hName = "deltachisq";

  //
  // START THE CONVERSION
  //
  TFile *fExpNll = new TFile(fName+".root", "ro");
  TH2D *hExpNll = (TH2D*)fExpNll->Get(hName);
  assert(hExpNll);

  int nX = hExpNll->GetNbinsX();
  int nY = hExpNll->GetNbinsY();

  // initialize a new histogram
  TH2D *hNew = new TH2D("hPdf", "hPdf",
	nX, hExpNll->GetXaxis()->GetXmin(), hExpNll->GetXaxis()->GetXmax(),
	nY, hExpNll->GetYaxis()->GetXmin()/180.*TMath::Pi(), hExpNll->GetYaxis()->GetXmax()/180.*TMath::Pi());
  for ( int ii=1; ii<nX; ii++ )
  for ( int jj=1; jj<nY; jj++ )
  {
    hNew->SetBinContent(ii, jj, 0);
  }

  TCanvas *c1 = new TCanvas("c1", "c1", 800, 400);
  c1->Divide(2,1);
  c1->cd(1);
  hExpNll->Draw("colz");

  // time the macro
  TStopwatch t;
  t.Start();

  float max = 0;
  float xMax = 0;
  float yMax = 0;
  float minEval = 1e6;

  for ( int i=1; i<=nX; i++ )
  for ( int j=1; j<=nY; j++ )
  {
    // exponentionate to turn chi2 into likelihood
    float eVal = hExpNll->GetBinContent(i,j);
    // hack for bad histogram
    if (eVal>9) eVal=9;
    if (eVal>0){
	    eVal = TMath::Exp(-eVal/2.);
	    hNew->SetBinContent(i, j, eVal);
    }
    // find coordinates of maximum in the physical region, R>0
    if ( max < eVal && hNew->GetXaxis()->GetBinCenter(i)>0 )
    {
	    xMax = hNew->GetXaxis()->GetBinCenter(i);
	    yMax = hNew->GetYaxis()->GetBinCenter(j);
	    max = eVal;
    }
    // find minimum likeilihood value in the tails - we'll set any zero bin to this minimum, usually around 1e-25
    if ( 0.0 < eVal && eVal < minEval ) minEval = eVal;
  }

  // set zero bins to minimum likelihood value found
  for ( int i=1; i<=nX; i++ )
  for ( int j=1; j<=nY; j++ )
  {
    if ( hNew->GetBinContent(i,j)<=0.0 ) hNew->SetBinContent(i, j, minEval);
  }

  hNew->Scale(1./hNew->Integral());

  t.Stop();
  t.Print();

  cout << "xMax = " << xMax << " yMax = " << yMax << endl;

  c1->cd(2);
  hNew->Draw("colz");

  cout << "saving histogram " << fName+"_pdf.root" << endl;
  TFile *fNew = new TFile(fName+"_pdf.root", "recreate");
  hNew->Write();
  fNew->Close();
}
示例#17
0
void run_HMx(){
  gROOT->LoadMacro("Fitter.cpp");

  // mass range
  double xmin = 50., xmax = 130.;

  // data
  TFile *data=new TFile("result_data_50_130.root");
  gDirectory->cd("Eff_Hist");

  const Int_t NBins = 31;
  const Int_t NBins_1D = 60;

  // get histogram before cut
  TH2D *before = (TH2D *)gROOT->FindObject("ZMass_vs_DetEta_Before_HMx_CC");
  TH2D *after = (TH2D *)gROOT->FindObject("ZMass_vs_DetEta_After_HMx_CC");

  Int_t NBins_X = before->GetNbinsX();
  Double_t Axis_XMin = before->GetXaxis()->GetXmin();
  Double_t Axis_XMax = before->GetXaxis()->GetXmax();

  if(NBins_X != NBins) {
    cout<<"NBins="<<NBins<<" while NBins_X="<<NBins_X<<" make sure they are the same"<<endl;
    exit;
  }

  Int_t NBins_Y = before->GetNbinsY();
  Double_t Axis_YMin = before->GetYaxis()->GetXmin();
  Double_t Axis_YMax = before->GetYaxis()->GetXmax();

  cout<<"HMx bin "<<NBins_X<<" from "<<Axis_XMin<<" to "<<Axis_XMax<<endl;
  cout<<"Mass bin "<<NBins_Y<<" from "<<Axis_YMin<<" to "<<Axis_YMax<<endl;

  // 1D histogram
  TH1D *before_mass[NBins], *after_mass[NBins], *diff_mass[NBins];
  double variable[NBins], variable_err[NBins];

  char name[50];
  for (int xbin = 0; xbin < NBins_X; xbin ++){
    sprintf(name, "%s%d", "before_", xbin);
    before_mass[xbin] = new TH1D(name, name, NBins_Y, Axis_YMin, Axis_YMax);
    sprintf(name, "%s%d", "after_", xbin);
    after_mass[xbin] = new TH1D(name, name, NBins_Y, Axis_YMin, Axis_YMax);
    sprintf(name, "%s%d", "diff_", xbin);
    diff_mass[xbin] = new TH1D(name, name, NBins_Y, Axis_YMin, Axis_YMax);

    variable[xbin] = before->GetXaxis()->GetBinCenter(xbin);
    variable_err[xbin] = 0.;

    for(int ybin=0; ybin < NBins_Y; ybin ++) {
      before_mass[xbin] -> SetBinContent(ybin, before->GetBinContent(xbin, ybin));
      after_mass[xbin] -> SetBinContent(ybin, after->GetBinContent(xbin, ybin));
      diff_mass[xbin] -> SetBinContent(ybin, before->GetBinContent(xbin, ybin)-after->GetBinContent(xbin, ybin));
    }
  }

  // signal
  TFile *mc = new TFile("pmcs.root");
  gDirectory->cd("smeared");
  TH2D *Sig_All = (TH2D *)gROOT->FindObject("smeared_ZMass_vs_DetEta_Before_HMx_CC");
  TH1D *Sig_before[NBins], *Sig_after[NBins];

  Int_t Sig_NBins_X = Sig_All->GetNbinsX();
  Double_t Sig_Axis_XMin = Sig_All->GetXaxis()->GetXmin();
  Double_t Sig_Axis_XMax = Sig_All->GetXaxis()->GetXmax();
  Int_t Sig_NBins_Y = before->GetNbinsY();
  Double_t Sig_Axis_YMin = before->GetYaxis()->GetXmin();
  Double_t Sig_Axis_YMax = before->GetYaxis()->GetXmax();

  if((NBins_X != Sig_NBins_X) || (NBins_Y != Sig_NBins_Y) || 
     (Axis_XMin != Sig_Axis_XMin) || (Axis_YMin != Sig_Axis_YMin) || 
     (Axis_XMax != Sig_Axis_XMax) || (Axis_YMax != Sig_Axis_YMax)) {
    cout<<"Different bin size between data and MC signal histogram, will exit now"<<endl;
    exit;
  }
  
  for (int xbin = 0; xbin < Sig_NBins_X; xbin ++){
    sprintf(name, "%s%d", "Sig_before_", xbin);
    Sig_before[xbin] = new TH1D(name, name, Sig_NBins_Y, Sig_Axis_YMin, Sig_Axis_YMax);
    sprintf(name, "%s%d", "Sig_after_", xbin);
    Sig_after[xbin] = new TH1D(name, name, Sig_NBins_Y, Sig_Axis_YMin, Sig_Axis_YMax);
    
    for(int ybin=0; ybin < Sig_NBins_Y; ybin ++) {
      Sig_before[xbin] -> SetBinContent(ybin, Sig_All->GetBinContent(xbin, ybin));
      Sig_after[xbin] -> SetBinContent(ybin, Sig_All->GetBinContent(xbin, ybin));
    }
  }

  cout<<"Sig HMx bin "<<Sig_NBins_X<<" from "<<Sig_Axis_XMin<<" to "<<Sig_Axis_XMax<<endl;
  cout<<"Sig Mass bin "<<Sig_NBins_Y<<" from "<<Sig_Axis_YMin<<" to "<<Sig_Axis_YMax<<endl;

  //
  // create a background histogram from the function
  //
  TF1 *func = new TF1("func", "[0] + [1]*x + [2]*x*x + [3]*x*x*x + [4]*x*x*x*x + [5]*x*x*x*x*x", Axis_YMin, Axis_YMax);
  func -> SetParameter(0, -28900.202091);
  func -> SetParameter(1, 1544.304929);
  func -> SetParameter(2, -31.665620);
  func -> SetParameter(3, 0.317247);
  func -> SetParameter(4, -0.001565);
  func -> SetParameter(5, 0.000003054);

  TH1D *QCDBkg_before[NBins], *QCDBkg_after[NBins];
  for(int ihist=0; ihist<NBins; ihist++) {
    sprintf(name, "%s%d", "QCDBkg_before_", ihist);
    QCDBkg_before[ihist] = new TH1D(name, name, Sig_NBins_Y, Sig_Axis_YMin, Sig_Axis_YMax);

    sprintf(name, "%s%d", "QCDBkg_after_", ihist);
    QCDBkg_after[ihist] = new TH1D(name, name, Sig_NBins_Y, Sig_Axis_YMin, Sig_Axis_YMax);
  }

  for(int ihist=0; ihist<NBins; ihist++) {
    for(int i=1; i<=QCDBkg_before[0]->GetNbinsX(); i++) {
      double center = QCDBkg_before[0]->GetBinCenter(i);
      
      if(center>xmin && center<xmax) {
	double bin_min = QCDBkg_before[0]->GetBinLowEdge(i);
	double bin_max = bin_min + QCDBkg_before[0]->GetBinWidth(i);	
	double integral = func->Integral(bin_min, bin_max);
	
	QCDBkg_before[ihist] -> SetBinContent(i, integral);
	QCDBkg_before[ihist] -> SetBinError(i, TMath::Sqrt(integral));
	QCDBkg_after[ihist] -> SetBinContent(i, integral);
	QCDBkg_after[ihist] -> SetBinError(i, TMath::Sqrt(integral));
      }
      
    } // for all bins
  } // for all QCD background histograms

  //
  // fitter
  //
  Fitter fitter;
  double diff_data[NBins], diff_mc[NBins], diff_bkg[NBins], diff_mc_err[NBins];
  double data_entry_after[NBins], mc_entry_after[NBins], bkg_entry_after[NBins], mc_err_after[NBins];


  double eff[NBins], eff_err[NBins], eff_withBkg[NBins], eff_err_withBkg[NBins];

  for(int i=0; i<NBins; i++) {    
    if(after_mass[i]->Integral()>10.) {
      fitter.Update(after_mass[i], Sig_after[i], QCDBkg_after[i], xmin, xmax);
      fitter.FitMass();
      fitter.Compare();      
      fitter.GetDataSignalBkg(data_entry_after[i], mc_entry_after[i], bkg_entry_after[i], mc_err_after[i]);
    }

    if(diff_mass[i]->Integral()>10.) {
      // no matter for signal and background shape here
      fitter.Update(diff_mass[i], Sig_before[i], QCDBkg_before[i], xmin, xmax);
      fitter.FitMass();
      fitter.Compare();      
      fitter.GetDataSignalBkg(diff_data[i], diff_mc[i], diff_bkg[i], diff_mc_err[i]);
    }

  } // for each histogram

  // plot efficiency
  TCanvas *eff_canvas = new TCanvas("eff_canvas","gerrors2",200,10,700,500);
  for(int i=0; i<NBins; i++) {
    if((mc_entry_after[i]+diff_mc[i])>1.) {  // at least one entry
      eff[i] = mc_entry_after[i]/(mc_entry_after[i]+diff_mc[i]);
      eff_err[i] = sqrt(mc_entry_after[i]*mc_entry_after[i]*diff_mc_err[i]*diff_mc_err[i] + 
			diff_mc[i]*diff_mc[i]*mc_err_after[i]*mc_err_after[i])/((diff_mc[i]+mc_entry_after[i])*(diff_mc[i]+mc_entry_after[i]));
      
      eff_withBkg[i] = data_entry_after[i]/(data_entry_after[i]+diff_data[i]);
      eff_err_withBkg[i] = sqrt(data_entry_after[i]*diff_data[i]*(data_entry_after[i]+diff_data[i]))/((data_entry_after[i]+diff_data[i])*(data_entry_after[i]+diff_data[i]));
    }
  }

  // draw a frame to define the range
  TH1F *hr = eff_canvas->DrawFrame(-3., 0, 3. ,1.5);
  hr->SetXTitle("X title");
  hr->SetYTitle("Eff");
  eff_canvas->GetFrame()->SetBorderSize(12);
  
  TGraphErrors *ge = new TGraphErrors(NBins, variable, eff, variable_err, eff_err);
  ge -> SetMarkerColor(kRed);
  ge -> Draw("P");

  TGraphErrors *ge2 = new TGraphErrors(NBins, variable, eff_withBkg, variable_err, eff_err_withBkg);
  ge2 -> SetMarkerColor(kBlue);
  ge2 -> Draw("P");

  //  TGraphErrors *ge3 = new TGraphErrors(NBins_1D, variable_1D, eff_1D, variable_err_1D, eff_err_1D);
  //  ge3 -> Draw("P");

  //  eff_canvas->Update();
}
示例#18
0
void run_alt_smooth(){
  gROOT->LoadMacro("Fitter.cpp");
  TPostScript *myps = new TPostScript("upara_eff_check022008_check.ps",111);
  // mass range
  double xmin = 50., xmax = 130.;
  
  // data
  TFile *data=new TFile("result_0221.root");
  gDirectory->cd("ZCand_Hist");
  
  const Int_t NBins = 15; //2 gev upara bins
  const Int_t NBinsX = 100; //1 gev mass bins
   
  TH2D *before = (TH2D *)gROOT->FindObject("ZCandUPara_V_Mass_NoCuts");
  TH2D *after = (TH2D *)gROOT->FindObject("ZCandUPara_V_Mass_BothWithGoodSpatialMatch_IsoHMxCut");
  
  //these x bins are mass
  int rbinpt = 4;
  before->RebinX(rbinpt);

  after->RebinX(rbinpt);
 
  //y bins are upara:
  int rbinupara = 8;
  before->RebinY(rbinupara);
  after->RebinY(rbinupara);
    
  Int_t NBins_X = before->GetNbinsX();
  Double_t Axis_XMin = before->GetXaxis()->GetXmin();
  Double_t Axis_XMax = before->GetXaxis()->GetXmax();
  
  if(NBins_X != NBinsX) {
    cout<<"NBins="<<NBinsX<<" while NBins_X="<<NBins_X<<" make sure they are the same"<<endl;
    exit;
  }
  
  Int_t NBins_Y = before->GetNbinsY();
  Double_t Axis_YMin = before->GetYaxis()->GetXmin();
  Double_t Axis_YMax = before->GetYaxis()->GetXmax();
  cout<<"Mass bin "<<NBins_Y<<" from "<<Axis_YMin<<" to "<<Axis_YMax<<endl;
  
  // 1D histogram
  TH1D *before_mass[NBins], *after_mass[NBins], *diff_mass[NBins], *bkgnd_mass[NBins];
  double variable[NBins], variable_err[NBins];
  
  char name[50];
  for (int ybin = 0; ybin <NBins_Y; ybin ++){   //include underflow, but doesnt go to upper limit. 
                                                 //not really a problem because there are few events there
                                                 //and we know the correct position anyway. 
    sprintf(name, "%s%d", "before_", ybin);
    before_mass[ybin] = new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax);
    sprintf(name, "%s%d", "after_", ybin);
    after_mass[ybin] = new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax);
    sprintf(name, "%s%d", "diff_", ybin);
    diff_mass[ybin] =  new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax);
    
    variable[ybin] = before->GetYaxis()->GetBinCenter(ybin);
    variable_err[ybin] = 1.0;
    
    for(int xbin=0; xbin < NBins_X; xbin ++) {
      
      cout<<"x,y: "<<xbin<<","<<ybin<<" before "<<before->GetBinContent(xbin, ybin)<<" after "<<after->GetBinContent(xbin, ybin)<<" diff " << (before->GetBinContent(xbin, ybin) - after->GetBinContent(xbin, ybin))<< endl;
      before_mass[ybin] -> SetBinContent(xbin, before->GetBinContent(xbin, ybin));
      after_mass[ybin] -> SetBinContent(xbin, after->GetBinContent(xbin, ybin));
      diff_mass[ybin]-> SetBinContent(xbin, (before->GetBinContent(xbin, ybin) - after->GetBinContent(xbin, ybin)) );
    }
   before_mass[ybin]->Draw();
  }
  
  // signal
  TFile *mc = new TFile("signal.root");
  gDirectory->cd("smeared");

  TH2D *sig2 = (TH2D *)gROOT->FindObject("smeared_hZcandMass_V_UPara_CCCC");
  sig2->RebinY(rbinupara);  //here x is the mass, y is upara
  //sig2->RebinX(rbinpt);  //here x is the mass, y is upara
  
  Int_t NBins_X = sig2->GetNbinsX();
  Double_t Axis_XMin = sig2->GetXaxis()->GetXmin();
  Double_t Axis_XMax = sig2->GetXaxis()->GetXmax();
   
  Int_t NBins_Y = sig2->GetNbinsY();
  Double_t Axis_YMin = sig2->GetYaxis()->GetXmin();
  Double_t Axis_YMax = sig2->GetYaxis()->GetXmax();
  cout<<"upara bin "<<NBins_Y<<" from "<<Axis_YMin<<" to "<<Axis_YMax<<endl;
  
  if(NBins_Y != NBins) {
    cout<<"NBins="<<NBins<<" while NBins_Y="<<NBins_Y<<" make sure they are the same"<<endl;
    exit;
  }
   
  cout<<"NBinsx="<<NBinsX<<" while NBins_X="<<NBins_X<<" make sure they are the same"<<endl;
  NBins_X = NBinsX;
  Axis_XMin = 50.;

  // 1D histogram
  TH1D *Sig_All[NBins];
  double variable[NBins], variable_err[NBins];
  TH1D *QCDBkg_All[NBins];
  
  //now for the bkg histogram:
  TFile *data=new TFile("result_bkg.root");
  gDirectory->cd("ZCand_Hist");
  TH2D *bkgnd = (TH2D *)gROOT->FindObject("ZCandUPara_V_Mass_0");
  bkgnd->RebinX(rbinupara); //upara is x
  bkgnd->RebinY(4); //mass is y. great
  //bkgnd->Draw("colz");

  char name[50];
  for (int ybin = 0; ybin < NBins_Y; ybin ++){
    sprintf(name, "%s%d", "sig_", ybin);
    Sig_All[ybin] = new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax); //note range
    //now is consistent with wmass analysis
    
    // variable[ybin] = sig2->GetYaxis()->GetBinCenter(ybin);
    //variable_err[ybin] = 0.;
    
    for(int xbin=50; xbin < 150; xbin ++) { //now is consistent with wmass analysis
      Sig_All[ybin] -> SetBinContent(xbin-50, sig2->GetBinContent(xbin,ybin)); //note order
    }  //pmcs ranges is from 0 to 150 instead of 50 to 150
    // Sig_All[ybin] -> Draw();

    sprintf(name, "%s%d", "bkgnd_", ybin);
    QCDBkg_All[ybin] = new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax);
    sprintf(name, "%s%d", "bkgnd_orig_", ybin);
    bkgnd_mass[ybin] = new TH1D(name, name, NBins_X, Axis_XMin, Axis_XMax);
    
    for(int xbin=0; xbin < NBins_X; xbin ++) {
      bkgnd_mass[ybin] -> SetBinContent((xbin), bkgnd->GetBinContent(ybin, xbin)); //note order
    }
    bkgnd_mass[ybin]->Sumw2();
    // bkgnd_mass[ybin]->Draw("pe");
    //TF1 *func = new TF1("func","[0] + [1]*x + [2]*x*x + [3]*x*x*x + [4]*x*x*x*x + [5]*x*x*x*x*x", Axis_YMin, Axis_YMax);
    //func -> SetParameters(-28900.202091,1544.3,-31.665,0.3172,0.00000305);
    TF1 *func = new TF1("func","landau", Axis_XMin, Axis_XMax);
    if (bkgnd_mass[ybin]->Integral()>10){
      bkgnd_mass[ybin]->Fit(func,"QN");//QN
    } else {
      cout<< " not enough events for bkgnd determination "<<endl;
      func -> SetParameters(3.93055e+02,5.64712e+01,3.26891e+00); 
      //this is for the bins < 25 GeV (for now) the parameters are from the 25-26 gev bin. 
    }
    //bkgnd_mass[xbin]->Draw();
    //QCDBkg_All[xbin] = (TH1D *)Sig_All[xbin]->Clone();
    
    for(int i=1; i<=QCDBkg_All[ybin]->GetNbinsX(); i++) {
      double center = QCDBkg_All[ybin]->GetBinCenter(i);
      
      QCDBkg_All[ybin] -> SetBinContent(i, 0);
      QCDBkg_All[ybin] -> SetBinError(i, 0);
      
      if(center>xmin && center<xmax) {
	double bin_min = QCDBkg_All[ybin]->GetBinLowEdge(i);
	double bin_max = bin_min + QCDBkg_All[ybin]->GetBinWidth(i);
	
	double integral = func->Integral(bin_min, bin_max);
	QCDBkg_All[ybin] -> SetBinContent(i, integral);
	QCDBkg_All[ybin] -> SetBinError(i, TMath::Sqrt(integral));
      }
    } // for all bins
    
    QCDBkg_All[ybin]->Sumw2();
    //  QCDBkg_All[ybin]->Draw();
     //Sig_All[ybin]->Draw();  
  }
  //bkgnd->Draw("colz");
  //TH1D *Sig_All = (TH1D *)gROOT->FindObject("smeared_hZcandMass_CCCC");
  
  //
  // fitter
  //
  Fitter fitter;
  double data_entry_before[NBins], mc_entry_before[NBins], mc_entry_diff[NBins], bkg_entry_before[NBins], mc_error_before[NBins], mc_error_diff[NBins];
  double data_entry_after[NBins], mc_entry_after[NBins], bkg_entry_after[NBins], mc_error_after[NBins];
  double eff[NBins], eff_err[NBins], deff[NBins], deff_err[NBins] ,reff[NBins], reff_err[NBins];
  double chisq1[NBins], chisq2[NBins];
  
  TCanvas *ctemp;
  int npad = 1;
  cout<< " nbins upara now "<<NBins<<endl;
  for(int i=0; i<NBins; i++) {  
    int cbin = 2;
    /*before_mass[i]->Rebin(cbin);
    after_mass[i]->Rebin(cbin);
    diff_mass[i]->Rebin(cbin);
    Sig_All[i]->Rebin(cbin);
    QCDBkg_All[i]->Rebin(cbin);
    */

    if (!(i%2)) {
      myps->NewPage();
      ctemp = new TCanvas("ctemp","ctemp",600,800);
      ctemp->Divide(2,2); 
      npad = 1;
      cout<<"NEWPAGE!!!"<<endl;
    }
    cout<<"=================================Starting number "<<i<<" =============================="<<endl;
    ctemp->cd(npad); 
    // before becomes diff 
    double sb = Sig_All[i]->Integral();
    double bb = QCDBkg_All[i]->Integral();
    cout<<diff_mass[i]->Integral()<<" "<< Sig_All[i]->Integral()<<" "<<QCDBkg_All[i]->Integral()<<endl;
    if(diff_mass[i]->Integral()>1. && Sig_All[i]->Integral()>2. && QCDBkg_All[i]->Integral()>1.) {
      cout<<"b mass "<<diff_mass[i]->Integral()<<endl;
      fitter.Update(diff_mass[i], Sig_All[i], QCDBkg_All[i], xmin, xmax);
      fitter.FitMass();
      fitter.Compare(ctemp);
      fitter.GetDataSignalBkg(data_entry_before[i], mc_entry_before[i], bkg_entry_before[i], mc_error_before[i], chisq1[i]);
    } else {
      diff_mass[i]->SetTitle("no fit");
      diff_mass[i]->Draw("pe");
      //Sig_All[i]->Scale(diff_mass[i]->Integral()/Sig_All[i]->Integral());
      Sig_All[i]->SetLineColor(kRed);
      Sig_All[i]->SetTitle("no fit");
      Sig_All[i]->Draw("hist && same");
      data_entry_before[i]=0.;
      mc_entry_before[i]=0.;
      bkg_entry_before[i]=0.;
      mc_error_before[i]=0.;
      
    }
    npad++;
    ctemp->cd(npad);
    if (Sig_All[i]->Integral()>0){
      Sig_All[i]->Scale(sb/Sig_All[i]->Integral());
    }
    if(QCDBkg_All[i]->Integral()>0){
      QCDBkg_All[i]->Scale(bb/QCDBkg_All[i]->Integral());
    }
    cout<<"---------------------------------------------------------------------------------here i am"<<endl;
    cout<<after_mass[i]->Integral()<<" "<< Sig_All[i]->Integral()<<" "<<QCDBkg_All[i]->Integral()<<endl;
    if(after_mass[i]->Integral()>1. && Sig_All[i]->Integral()>2. && QCDBkg_All[i]->Integral()>1.) {
      cout<<"---------------------------------------------------------------------------------here i am 2"<<endl;
      fitter.Update(after_mass[i], Sig_All[i], QCDBkg_All[i], xmin, xmax);
      fitter.FitMass();
      //ctemp->cd(npad);
      fitter.Compare(ctemp);
      fitter.GetDataSignalBkg(data_entry_after[i], mc_entry_after[i], bkg_entry_after[i], mc_error_after[i], chisq2[i]);
    } else {
      cout<<"-----------------------------------------------------------------------------------here i am 3"<<endl;
      after_mass[i]->SetTitle("no fit");
      after_mass[i]->Draw("pe");
      //Sig_All[i]->Scale(after_mass[i]->Integral()/Sig_All[i]->Integral());
      Sig_All[i]->SetLineColor(kRed);
      Sig_All[i]->SetTitle("no fit");
      Sig_All[i]->Draw("hist && same");
      data_entry_after[i]=0.;
      mc_entry_after[i]=0.;
      bkg_entry_after[i]=0.;
      mc_error_after[i]=0.;
      
    }
    npad++;

  } // for each histogram

  // plot efficiency

 myps->NewPage();
  TCanvas *eff_canvas = new TCanvas("eff","eff",600,600);


  eff_canvas->Divide(1,1);
    eff_canvas->cd(1);

  cout<<"double cccc_mc_entry_after["<<NBins<<"]={";
  for(int i=0; i<NBins; i++) {
    cout<<mc_entry_after[i]<<",";
  }
  cout<<"}"<<endl;
  cout<<"double cccc_mc_error_after["<<NBins<<"]={";
  for(int i=0; i<NBins; i++) {
    cout<<mc_error_after[i]<<",";
  }
  cout<<"}"<<endl;
  cout<<"double cccc_mc_entry_before["<<NBins<<"]={";
  for(int i=0; i<NBins; i++) {
    cout<<mc_entry_before[i]<<",";
  }
  cout<<"}"<<endl;
  cout<<"double cccc_mc_error_before["<<NBins<<"]={";
  for(int i=0; i<NBins; i++) {
    cout<<mc_error_before[i]<<",";
  }
  cout<<"}"<<endl;
  cout<<"double variable[NBins]={";
  for(int i=0; i<NBins; i++) {
    cout<<variable[i]<<",";
  }
  cout<<"}"<<endl;
  
  for(int i=0; i<NBins; i++) {
    if(mc_entry_before[i]>1.&&  mc_entry_after[i]>1.) {  // at least >one entry
      
      eff[i] = mc_entry_after[i]/(mc_entry_before[i] + mc_entry_after[i]);
      eff_err[i] = sqrt(mc_entry_before[i]*mc_entry_before[i]*mc_error_after[i]*mc_error_after[i]+ mc_entry_after[i]*mc_entry_after[i]*mc_error_before[i]*mc_error_before[i])/(mc_entry_before[i]+mc_entry_after[i])/(mc_entry_before[i]+mc_entry_after[i]);
      cout<<"what "<<i << " b "<<mc_entry_before[i]<<" a "<<mc_entry_after[i]<<" eff i "<<eff[i]<<" err i "<<eff_err[i] << " be "<<mc_error_before[i]<<" ae "<<mc_error_after[i]<<endl;    
      
    } else {
      eff[i] = 0;
      eff_err[i] = 0.05;
    }
  }
  
  TF1 *afunc = new TF1("afunc",fitf,-15,15,3);
  afunc->SetParameters(-1.0,0.010,0.74);
  
  //  TF1 *efffit2 = new TF1("efffit2","0.5 * [2] * (1. + TMath::Erf((x-[0])/(sqrt(2)*[1])))*(1. + TMath::Erf((x-[4])/(sqrt(2)*[3])))",15,55 );
  //  efffit2->SetParameters(23.,2.0,0.4,2.0,20.);
  TGraphErrors *ge = new TGraphErrors(NBins, variable, eff, variable_err, eff_err);
  ge->GetYaxis()->SetRangeUser(0.4,0.9);
  ge->SetMarkerColor(kRed);
  ge->SetMarkerSize(2);
  ge->SetLineColor(kRed);
  ge->GetXaxis()->SetTitle("Electron U_{||} [GeV]");
  ge->GetYaxis()->SetTitle("Efficiency");
  ge->GetYaxis()->SetTitleOffset(1.4);
  ge->SetTitle("Z->ee Candidates, U_{||} Eff."); 
  
  ge->Fit("afunc","R");
  
  TF1 *apol1 = new TF1("apol1","[0] + [1]*x", -20. ,0.);
  ge -> Draw("AP");
  //  ge->Fit("apol1","R");
  // apol1->Draw("same");
  TF1 *bpol1 = new TF1("bpol1","[0] + [1]*x", 0. ,20.);
  // ge->Fit("bpol1","R");
  //bpol1->Draw("same");
  

  // eff_canvas->Update();
  
  // eff_canvas->cd(2);
  eff_canvas->SaveAs("upara_out_new.eps");


  for(int i=0; i<NBins; i++) {
    if(data_entry_before[i]>1. && data_entry_after[i]>1.) {// at least one entry
      cout<<"what 2 "<<data_entry_before[i]<<" "<<data_entry_after[i]<< " "<<i<<endl;
      deff[i] = data_entry_after[i]/(data_entry_before[i]+data_entry_after[i]);
      deff_err[i] = sqrt(data_entry_before[i]*data_entry_before[i]*mc_error_after[i]*mc_error_after[i]
			 + data_entry_after[i]*data_entry_after[i]*mc_error_before[i]*mc_error_before[i])
	/(data_entry_before[i]+data_entry_after[i])/(data_entry_before[i]+data_entry_after[i]);
      //for this you really should have plain binominal errors (no background subtraction here)
    } else {
      deff[i] = 0;
      deff_err[i] = 0.05;
    }
  }
  
  
  TGraphErrors *de = new TGraphErrors(NBins, variable, deff, variable_err, deff_err);
  de->GetYaxis()->SetRangeUser(0.4,0.9);
  de->SetMarkerColor(kBlue);
  de->SetMarkerSize(2);
  de->SetLineColor(kBlue);
  //de->Fit("efffit2","RME");
  //de -> Draw("SAME");
  
  //eff_canvas->Update();
  
  //now get full MC "answer":
  /*
  TFile *data=new TFile("/rooms/porcelain/tandeen/WMASS/output/FULL/Zee/UPARAEFF/result_MCzee_upara_1.root");
  gDirectory->cd("ZCand_Hist");
  TH1D *before2 = (TH1D *)gROOT->FindObject("ZCandUPara_NoCuts");
  TH1D *after2 = (TH1D *)gROOT->FindObject("ZCandUPara_BothWithGoodSpatialMatch_IsoHMxCut");  
  before2->Rebin(8);
  after2->Rebin(8);
  
  TGraphAsymmErrors *effb = new TGraphAsymmErrors();
  effb->BayesDivide(after2,before2,""); //"debug"
  // effb->Fit("pol1","","",0,15);
  
  effb->Draw("same");
  effb->Fit("pol1","","",-20,0);
  double thep0 = pol1->GetParameter(0);
  double thep1 = pol1->GetParameter(1);
  cout<<"p0 "<<thep0<<" p1 "<<thep0<<endl;
  effb->Fit("pol1","","",0,20);
  //TF1 *cpol1 = new TF1("cpol1","[0] + [1]*x", -20. ,0.);
  //cout<<"cpol"<<endl;
  //effb->Fit("cpol1","R");
  //cpol1->Draw("same");
  TF1 *dpol1 = new TF1("dpol1","[0] + [1]*x", -20. , 0.);
  dpol1->SetParameters(thep0,thep1);
  //cout<<"dpol"<<endl;
  //effb->Fit("dpol1","R");
  dpol1->Draw("same");

  //effb->SetTitle(ZCandUPara_BothWithGoodSpatialMatch_IsoHMxCut->GetTitle());
  //effb->GetXaxis()->SetTitle("trk deteta");
  */
  /*
  eff_canvas->cd(3);
  
  for(int i=0; i<NBins; i++) {
    if(eff[i]>0. && deff[i]>0.) {// at least one entry
      reff[i] = eff[i]/deff[i]; 
      //reff_err[i] = sqrt(data_entry_before[i]*data_entry_before[i]*mc_error_after[i]*mc_error_after[i]+ data_entry_after[i]*data_entry_after[i]*mc_error_before[i]*mc_error_before[i])/(data_entry_before[i]+data_entry_after[i])/(data_entry_before[i]+data_entry_after[i]);
    } else {
      reff[i] = 1.0;
      //reff_err[i] = 0.1;
    }
  }

  TGraphErrors *erat = new TGraphErrors(NBins, variable, reff, variable_err, eff_err);
  erat->GetXaxis()->SetRangeUser(10,70);
  erat->SetMarkerColor(kRed);
  erat->SetMarkerSize(2);
  erat->SetLineColor(kRed);
  erat -> Draw("AP");
  */


  eff_canvas->Update();

  myps->NewPage();
  TCanvas *chi_canvas = new TCanvas("eff","eff",600,800);
  

  chi_canvas->Divide(1,2);
  chi_canvas->cd(1);
  
  TGraph *chi1 = new TGraph(NBins, variable, chisq1);
  // de->GetYaxis()->SetRangeUser(0.4,0.9);
  //de->SetMarkerColor(kBlue);
  //de->SetMarkerSize(2);
  //de->SetLineColor(kBlue);
  //de->Fit("efffit2","RME");
  chi1-> Draw("A*");
   

  chi_canvas->cd(2);

  TGraph *chi2 = new TGraphErrors(NBins, variable, chisq2);
  //de->GetYaxis()->SetRangeUser(0.4,0.9);
  
  //de->SetMarkerColor(kBlue);
  //de->SetMarkerSize(2);
  //de->SetLineColor(kBlue);
  //de->Fit("efffit2","RME");
  chi2 -> Draw("A*");
  
  chi_canvas->Update();


  myps->Close();
}
示例#19
0
void plotXY(){
  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetHistMinimumZero(kFALSE);

  Int_t status = gSystem->Load("../rootils_C.so");
  std::cout << "status: " << status << std::endl;

  // TString dir("allStat_6hits/");
  // TString dir("allStat_noWeiBug/");
  TString dir("./");

  //Agguanta gli istogrammi
  TFile * SimF = new TFile(dir+"Sim_XY.root");
  TH2D * SimH = (TH2D*) SimF->Get("Sim_XY");;
  //
  TFile * MCF = new TFile(dir+"MC_XY.root");
  TH2D * MCH = (TH2D*) MCF->Get("MC_XY");;
  //
  //  TFile * MCFsF = new TFile(dir+"rMCFs_XY.root");
  //  TH2D * MCFsH = (TH2D*) MCFsF->Get("rMCFs_XY");;
  //
  TFile * FakeF = new TFile(dir+"MCFake_XY.root");
  TH2D * FakeH = (TH2D*) FakeF->Get("MCFake_XY");;
  //
  TFile * DataF = new TFile(dir+"Data_XY.root");
  TH2D * DataH = (TH2D*) DataF->Get("Data_XY");;
  //
  //  TFile * DataFsF = new TFile(dir+"rDataFs_XY.root");
  //  TH2D * DataFsH = (TH2D*) DataFsF->Get("rDataFs_XY");;
  //
  
  cout << MCH->GetEntries() << " " << MCH->GetEffectiveEntries() << " " << MCH->Integral() << endl;
  cout << DataH->GetEntries() << " " << DataH->GetEffectiveEntries() << " " << DataH->Integral() << endl;

  //Normalize to plot entries
  SimH->Scale(1./SimH->Integral()); 
  MCH->Scale(1./MCH->Integral());
  FakeH->Scale(1./FakeH->Integral());
  DataH->Scale(1./DataH->Integral());

  cout << MCH->GetEntries() << " " << MCH->GetEffectiveEntries() << " " << MCH->Integral() << endl;
  cout << DataH->GetEntries() << " " << DataH->GetEffectiveEntries() << " " << DataH->Integral() << endl;

  //Max
  Double_t simMax=SimH->GetMaximum();
  Double_t simPxlMax=GetMaxWithinRadius(SimH, 15.);
  Double_t simPxlInt=GetIntWithinRZ(SimH, 15., 0.);
  Double_t MCMax=MCH->GetMaximum();
  Double_t MCPxlMax=GetMaxWithinRadius(MCH, 15.);
  Double_t MCPxlInt=GetIntWithinRZ(MCH, 15., 0.);
  Double_t DataMax=DataH->GetMaximum();
  Double_t DataPxlMax=GetMaxWithinRadius(DataH, 15.);
  Double_t DataPxlInt=GetIntWithinRZ(DataH, 15., 0.);
  Double_t mAx=max(MCMax,DataMax);


  std::cout << " max     >>>> mc " << MCMax << " data " << DataMax << " Sim " << simMax << std::endl;
  std::cout << " pxl max >>>> mc " << MCPxlMax << " data " << DataPxlMax << " Sim " << simPxlMax << std::endl;
  std::cout << " pxl int >>>> mc " << MCPxlInt << " data " << DataPxlInt << " Sim " << simPxlInt << std::endl;

  // This would be need to normalize SimH to the pixel region material (taking into account that SimH and DataH/MCH have different binning!)
  //
  //  SimH->Scale(DataPxlInt*(DataH->GetXaxis()->GetBinWidth(1)*DataH->GetYaxis()->GetBinWidth(1))/simPxlInt/(SimH->GetXaxis()->GetBinWidth(1)*SimH->GetYaxis()->GetBinWidth(1)));
  // I prefer to have Sim plots and Data/MC plot to look similar by appropriately scaling the SimH range, not by scaling the histo

  mAx=0.001;
  //  mAx=0.011;
  //  mAx=0.15*0.5*(MCPxlMax+DataPxlMax);

  Double_t simRangeScale = 1./(DataPxlInt*(DataH->GetXaxis()->GetBinWidth(1)*DataH->GetYaxis()->GetBinWidth(1))/simPxlInt/(SimH->GetXaxis()->GetBinWidth(1)*SimH->GetYaxis()->GetBinWidth(1)));

  std::cout << simRangeScale << endl;
  std::cout << (DataH->GetXaxis()->GetBinWidth(1)*DataH->GetYaxis()->GetBinWidth(1)) << endl;
  std::cout << (SimH->GetXaxis()->GetBinWidth(1)*SimH->GetYaxis()->GetBinWidth(1)) << endl;

  SimH->SetMaximum(mAx*simRangeScale); 
  MCH->SetMaximum(mAx);  
  DataH->SetMaximum(mAx);

  //

  makeColorTable();

  Plot2D(SimH, "#gamma conv., MC Truth", dir);
  Plot2D(MCH, "#gamma conv., MC Reco #sqrt{s}=8TeV", dir);
  Plot2D(DataH, "#gamma conv., Data #sqrt{s}=8TeV", dir);

  //

  /*
  TH2D *MCCoarse = MCH->Rebin2D(2,2,"MCCoarse");
  TH2D *DataCoarse = DataH->Rebin2D(2,2,"DataCoarse");
  */

  /*
  cout << MCCoarse->GetEntries() << " " << MCCoarse->GetEffectiveEntries() << endl;
  cout << DataCoarse->GetEntries() << " " << DataCoarse->GetEffectiveEntries() << endl;
  */

  /*
  TH2D *diff = new TH2D("diff","diff", MCCoarse->GetNbinsX(),-60.,60.,MCCoarse->GetNbinsY(),-60.,60.);
  for (Int_t iBin = 0; iBin < MCCoarse->GetNbinsX(); iBin++){
    for (Int_t jBin = 0; jBin < MCCoarse->GetNbinsY(); jBin++){
      Double_t mc = MCCoarse->GetBinContent(iBin+1, jBin+1); 
      Double_t data = DataCoarse->GetBinContent(iBin+1, jBin+1); 
      cout << mc << " " << data << endl;
      if ( mc ) diff->SetBinContent(iBin+1,jBin+1,0.5+(mc-data)/mc);
    }
  }
  */

  MCH->Rebin2D(2,2);
  DataH->Rebin2D(2,2);

  TH2D *diff = new TH2D("diff","diff", MCH->GetNbinsX(),-60.,60.,MCH->GetNbinsY(),-60.,60.);
  for (Int_t iBin = 0; iBin < MCH->GetNbinsX(); iBin++){
    for (Int_t jBin = 0; jBin < MCH->GetNbinsY(); jBin++){
      Double_t mc = MCH->GetBinContent(iBin+1, jBin+1); 
      Double_t data = DataH->GetBinContent(iBin+1, jBin+1); 
      if ( mc+data ) {
      if ( ! mc ) mc=0.0000001;
      Double_t val = data/mc;
      //      Double_t val = (mc-data)/mc;
      Double_t valup = 1.2;
      Double_t vallo = 0.8;
      Double_t offset = 0.;
      if ( val > valup ) diff->SetBinContent(iBin+1,jBin+1,offset+valup);
      if ( val < vallo ) diff->SetBinContent(iBin+1,jBin+1,offset+vallo);
      if ( val > vallo && val < valup ) diff->SetBinContent(iBin+1,jBin+1,offset+val);
      }
    }
  }


  diff->SetMinimum(0.);
  diff->SetMaximum(2.);

  makeColorTableRB();

  Plot2D(diff,"pippo", dir);

}
///
/// Expand the Cleo PDF by Gaussian rise and decay beyond the
/// physical boundaries of kD: [0,1] -> [-0.4, 0.6]. This means
/// twice as many bins.
///
void computeCleoPdfWithGaussianRise()
{
  TString fName = "CLEO_K3PiScan_2009";
  TString hName = "deltachisq";
  
  TFile *fExpNll = new TFile(fName+".root", "ro");
  TH2D *hExpNll = (TH2D*)fExpNll->Get(hName);
  assert(hExpNll);

  int nX = hExpNll->GetNbinsX()*2.0;
  int nY = hExpNll->GetNbinsY();
  
  // initialize a new 2D histotram
  TH2D *hNew = new TH2D("hPdf", "hPdf", nX, -0.4, 1.6, nY, 0, 2.*TMath::Pi());
  for ( int ii=1; ii<nX; ii++ )
  for ( int jj=1; jj<nY; jj++ )
  {
    hNew->SetBinContent(ii, jj, 0);
  }
    
  TCanvas *c1 = new TCanvas("c1", "c1", 800, 400);
  c1->Divide(2,1);
  c1->cd(1);
  hExpNll->Draw("colz");
  
  // time the macro
  TStopwatch t;
  t.Start();
  
  Double_t integral = 0;
  Double_t max = 0;
  Double_t xMax = 0;
  Double_t yMax = 0;
  int xBinOffset = 0.4 / hExpNll->GetXaxis()->GetBinWidth(1);
  for ( int i=1; i<=nX; i++ )
  for ( int j=1; j<=nY; j++ )
  {
    Double_t eVal = 0.0;
    if ( hNew->GetXaxis()->GetBinCenter(i)<0 )
    {
      // gaussian with width = half of kD 1 sigma error
      Double_t scale = hExpNll->GetBinContent(1,j);
      scale = TMath::Exp(-scale/2.);
      eVal = TMath::Gaus(hNew->GetXaxis()->GetBinCenter(i), 0.0, 0.26/2, false) * scale;
    }
    else if ( hNew->GetXaxis()->GetBinCenter(i)>1 )
    {
      Double_t scale = hExpNll->GetBinContent(hExpNll->GetNbinsX(),j);
      scale = TMath::Exp(-scale/2.);
      eVal = TMath::Gaus(hNew->GetXaxis()->GetBinCenter(i), 1.0, 0.26/2, false) * scale;      
    }
    else
    {
      eVal = hExpNll->GetBinContent(i-xBinOffset,j);
      eVal = TMath::Exp(-eVal/2.);
    }
    hNew->SetBinContent(i, j, eVal);
    if ( max < eVal)
    {
      xMax = hNew->GetXaxis()->GetBinCenter(i);
      yMax = hNew->GetYaxis()->GetBinCenter(j);
      max = eVal;
    }
    integral += eVal;
  }

  hNew->Scale(1./integral);

  t.Stop();
  t.Print();

  cout << "xMax = " << xMax << " yMax = " << yMax << endl; 
  
  c1->cd(2);
  hNew->Draw("colz");
  
  TString newFileName = fName+"_GaussianRise_pdf2.root";
  cout << "saving histogram " << newFileName << endl;
  TFile *fNew = new TFile(newFileName, "recreate");
  hNew->Write();
  fNew->Close();
}
void run_radius_correction ()
{
    TStopwatch timer;
    timer.Start();

    gStyle->SetPalette(1,0);
    gStyle->SetHistLineWidth(2);

    // ----  Load libraries   -------------------------------------------------
    gROOT->LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C");
    basiclibs();
    gROOT->LoadMacro("$VMCWORKDIR/macro/rich/cbmlibs.C");
    cbmlibs();

   // gROOT->LoadMacro("$VMCWORKDIR/macro/rich/setstyle.C");
   // setphdStyle();
    SetStyles();

    char fileMC[200], fileRec[200];

    sprintf(fileMC,"/d/cbm02/slebedev/rich/JUL09/correction/mc.00.root");
    cout<<fileMC<<endl;
    TFile *f1 = new TFile(fileMC,"R");
    TTree* t1 = f1->Get("cbmsim");
    TFolder *fd1 = f1->Get("cbmroot");
    TClonesArray* fMCTracks = (TClonesArray*) fd1->FindObjectAny("MCTrack");
    t1->SetBranchAddress(fMCTracks->GetName(),&fMCTracks);

    sprintf(fileRec, "/d/cbm02/slebedev/rich/JUL09/correction/reco.00.root");
    TFile *f = new TFile(fileRec,"R");
    TTree* t = f->Get("cbmsim");
    TFolder *fd = f->Get("cbmout");
    TClonesArray *fRichRings = (TClonesArray*) fd->FindObjectAny("RichRing");
    t->SetBranchAddress(fRichRings->GetName(),&fRichRings);
    TClonesArray *fRichMatches = (TClonesArray*) fd->FindObjectAny("RichRingMatch");
    t->SetBranchAddress(fRichMatches->GetName(),&fRichMatches);

    //Int_t fNofBinsX = 40;
    //Int_t fNofBinsY = 50;
    Int_t fNofBinsX = 25;
    Int_t fNofBinsY = 25;
    ///A axis
    TH2D* fh_axisAXYCount;
    TH2D* fh_axisAXYW;
    TH2D* fh_axisAXY;
    TH2D* fh_axisASigma;
    TH2D* mapaxisAXY;


    ///B axis
    TH2D* fh_axisBXYCount;
    TH2D* fh_axisBXYW;
    TH2D* fh_axisBXY;
    TH2D* fh_axisBSigma;
    TH2D* mapaxisBXY;

    mapaxisAXY = new TH2D("fh_mapaxisAXY","dA distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);
    mapaxisBXY = new TH2D("fh_mapaxisBXY","dB distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisAXYCount = new TH2D("fh_axisAXYCount","A Count",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisAXYW = new TH2D("fh_axisAXYW","",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisBXYCount = new TH2D("fh_axisBXYCount","B Count",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisBXYW = new TH2D("fh_axisBXYW","",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisAXY = new TH2D("fh_axisAXY","A distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisBXY = new TH2D("fh_axisBXY","B distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);

    Double_t fMinAaxis = 4.5;
    Double_t fMaxAaxis = 7.5;

    ///Set Mean value of A and B axeses, Compact RICH
    //Double_t fMeanAaxis = 5.06;
    //Double_t fMeanBaxis = 4.65;

    ///Set Mean value of A and B axeses, Large RICH
    Double_t fMeanAaxis = 6.17;
    Double_t fMeanBaxis = 5.6;

    Int_t nEvents=t->GetEntries();
    cout<<" nEvents ="<<nEvents<<endl;
    for(Int_t ievent=0;ievent<nEvents; ievent++ ) {
        cout<<"ievent = "<<ievent;
        CbmRichRing *ring=NULL;
        CbmRichRingMatch *match=NULL;
        t->GetEntry(ievent);
        t1->GetEntry(ievent);
        Int_t nofRings = fRichRings->GetEntries();
        cout<<"  nofRings = "<<nofRings;
        cout<<"  nofMatches = "<< fRichMatches->GetEntries() ;
        cout<<"  nofMCTracks = "<<fMCTracks->GetEntries() << endl;

        for(Int_t iRing=0; iRing < nofRings; iRing++){
            ring = (CbmRichRing*)fRichRings->At(iRing);
            if (!ring) continue;
            match = (CbmRichRingMatch*)fRichMatches->At(iRing);
            if (!match) continue;

            Int_t trackId = match->GetMCTrackID();
            if (trackId == -1) continue;
            if (trackId > fMCTracks->GetEntries()) continue;

            CbmMCTrack* mcTrack = (CbmMCTrack*)fMCTracks->At(trackId);
            if (!mcTrack) continue;
            Int_t pdg = TMath::Abs(mcTrack->GetPdgCode());
            Int_t motherId = mcTrack->GetMotherId();
            if (pdg != 11) continue;
            if (motherId != -1) continue;

            Double_t radius = ring->GetRadius();
            Double_t axisA = ring->GetAaxis();
            Double_t axisB = ring->GetBaxis();
            Double_t centerX = ring->GetCenterX();
            Double_t centerY = ring->GetCenterY();

            if (axisA > fMaxAaxis || axisB > fMaxAaxis) continue;
            if (axisA < fMinAaxis || axisB < fMinAaxis) continue;

            fh_axisAXYW->Fill(centerX, centerY, axisA);
            fh_axisAXYCount->Fill(centerX, centerY);

            fh_axisBXYW->Fill(centerX, centerY, axisB);
            fh_axisBXYCount->Fill(centerX, centerY);
        } //iRing
    } //iEvent

    fh_axisAXY->Divide(fh_axisAXYW,fh_axisAXYCount);
    fh_axisBXY->Divide(fh_axisBXYW,fh_axisBXYCount);


///create two correction maps
    for (Int_t iX = 1; iX < mapaxisAXY->GetNbinsX() + 1; iX++){
        for (Int_t iY = 1; iY < mapaxisAXY->GetNbinsY() + 1; iY++){
        	if (fh_axisAXYCount->GetBinContent(iX, iY) != 0){
        		mapaxisAXY->SetBinContent(iX, iY, fMeanAaxis - fh_axisAXY->GetBinContent(iX, iY) );
        	} else {
        		mapaxisAXY->SetBinContent(iX, iY, -99999999.);
        	}

        	if (fh_axisBXYCount->GetBinContent(iX, iY) != 0){
        		mapaxisBXY->SetBinContent(iX, iY, fMeanBaxis - fh_axisBXY->GetBinContent(iX, iY) );
        	} else {
        		mapaxisBXY->SetBinContent(iX, iY, -99999999.);
        	}
        }
    }

    c1_0 = new TCanvas("c1_0","c1_0",10,10,600,600);
    c1_0->Divide(1,2);
    c1_0->cd(1);
    fh_axisAXYCount->Draw("COLZ");
    c1_0->cd(2);
    fh_axisBXYCount->Draw("COLZ");

    c1 = new TCanvas("c1","c1",10,10,600,600);
    c1->Divide(1,2);
    c1->cd(1);
    fh_axisAXY->SetMinimum(5.0);
    fh_axisAXY->SetMaximum(6.4);
    fh_axisAXY->Draw("COLZ");
    c1->cd(2);
    fh_axisBXY->SetMinimum(5.0);
    fh_axisBXY->SetMaximum(6.0);
    fh_axisBXY->Draw("COLZ");

    c2 = new TCanvas("c2","c2",10,10,600,600);
    c2->Divide(1,2);
    c2->cd(1);
    mapaxisAXY->SetMinimum(-0.5);
    mapaxisAXY->SetMaximum(0.5);
    mapaxisAXY->Draw("COLZ");
    c2->cd(2);
    mapaxisBXY->SetMinimum(-0.5);
    mapaxisBXY->SetMaximum(0.5);
    mapaxisBXY->Draw("COLZ");


///// Check correction procedure
    TH1D* fh_Abefore = new TH1D("fh_Abefore","A before;A, [cm];yield", 300, 0., 9.);;
    TH1D* fh_Bbefore= new TH1D("fh_Bbefore","B before;B, [cm];yield", 300, 0., 9.);;

    TH1D* fh_A = new TH1D("fh_A","A after;A, [cm];yield", 300, 0., 9.);;
    TH1D* fh_B = new TH1D("fh_B","B after;B, [cm];yield", 300, 0., 9.);;

    cout <<"Check correction procedure......" << endl;
    for(Int_t ievent=0;ievent<nEvents;ievent++ ) {
        CbmRichRing *ring=NULL;
       // if (ievent % 100 == 0) cout << ievent << "   ";
        //t1->GetEntry(ievent);
        t->GetEntry(ievent);
        t1->GetEntry(ievent);
        Int_t nofRings = fRichRings->GetEntries();

        for(Int_t iRing=0; iRing < nofRings; iRing++){

            ring = (CbmRichRing*)fRichRings->At(iRing);
            if (!ring) continue;
            match = (CbmRichRingMatch*)fRichMatches->At(iRing);
            if (!match) continue;

            Int_t trackId = match->GetMCTrackID();
            if (trackId == -1) continue;
            if (trackId > fMCTracks->GetEntries()) continue;

            CbmMCTrack* mcTrack = (CbmMCTrack*)fMCTracks->At(trackId);
            if (!mcTrack) continue;
            Int_t pdg = TMath::Abs(mcTrack->GetPdgCode());
            Int_t motherId = mcTrack->GetMotherId();
            if (pdg != 11) continue;
            if (motherId != -1) continue;

            Double_t axisA = ring->GetAaxis();
            Double_t axisB = ring->GetBaxis();
            if (axisA > fMaxAaxis || axisB > fMaxAaxis) continue;
            if (axisA < fMinAaxis || axisB < fMinAaxis) continue;

            Double_t radius = ring->GetRadius();
            Double_t centerX = ring->GetCenterX();
            Double_t centerY = ring->GetCenterY();
            Double_t axisAbefore = ring->GetAaxis();
            Double_t axisBbefore = ring->GetBaxis();
            fh_Abefore->Fill(axisAbefore);
            fh_Bbefore->Fill(axisBbefore);

            Double_t axisA = ring->GetAaxis();
            Double_t axisB = ring->GetBaxis() ;

            axisA += mapaxisAXY->GetBinContent(mapaxisAXY->FindBin(centerX,centerY));
            axisB += mapaxisBXY->GetBinContent(mapaxisBXY->FindBin(centerX,centerY));

            fh_A->Fill(axisA);
            fh_B->Fill(axisB);
        } //iRing
    }//iEvent


  //  gStyle->SetOptStat(0);
    c3 = new TCanvas("c3","c3",10,10,600,600);
    c3->Divide(2,2);
    c3->cd(1);
    fh_Abefore->Scale(1./fh_Abefore->Integral());
    fh_Abefore->SetMaximum(fh_Abefore->GetMaximum()*1.3);
    fh_Abefore->Draw();
    fh_Abefore->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_Abefore->Fit("gaus");
    Double_t sigmaAb = fh_Abefore->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtAb[30];
    sprintf(sigmaTxtAb,"sigma = %.3f",sigmaAb);
    TText* txtAb = new TText(4.3, fh_Abefore->GetMaximum()*0.85, sigmaTxtAb);
    txtAb->SetTextSize(0.1);
    txtAb->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);

    c3->cd(2);
    fh_Bbefore->Scale(1./fh_Bbefore->Integral());
    fh_Bbefore->SetMaximum(fh_Bbefore->GetMaximum()*1.3);
    fh_Bbefore->Draw();
    fh_Bbefore->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_Bbefore->Fit("gaus");
    Double_t sigmaBb = fh_Bbefore->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtBb[30];
    sprintf(sigmaTxtBb,"sigma = %.3f",sigmaBb);
    TText* txtBb = new TText(4.3, fh_Bbefore->GetMaximum()*0.85, sigmaTxtBb);
    txtBb->SetTextSize(0.1);
    txtBb->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);

    c3->cd(3);
    fh_A->Scale(1./fh_A->Integral());
    fh_A->SetMaximum(fh_A->GetMaximum()*1.3);
    fh_A->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_A->Draw();
    fh_A->Fit("gaus");
    Double_t sigmaA = fh_A->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtA[30];
    sprintf(sigmaTxtA,"sigma = %.3f",sigmaA);
    TText* txtA = new TText(4.3, fh_A->GetMaximum()*0.85, sigmaTxtA);
    txtA->SetTextSize(0.1);
    txtA->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);

    c3->cd(4);
    fh_B->Scale(1./fh_B->Integral());
    fh_B->SetMaximum(fh_B->GetMaximum()*1.3);
    fh_B->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_B->Draw();
    fh_B->Fit("gaus");
    Double_t sigmaB = fh_B->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtB[30];
    sprintf(sigmaTxtB,"sigma = %.3f",sigmaB);
    TText* txtB = new TText(4.3, fh_B->GetMaximum()*0.85, sigmaTxtB);
    txtB->SetTextSize(0.1);
    txtB->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);


/// Write correction map to the file
    TFile *file = new TFile("radius_correction_map.root", "recreate");
    mapaxisAXY->Write();
    mapaxisBXY->Write();
    file->Close();

}
示例#22
0
void addn2() {

  // open existing f1:

  char* fn[99];
  int ni;

  // SR90 maps, mod D003

  ni = -1;
  ni++; fn[ni] = "SR90-map-00a.root";
  ni++; fn[ni] = "SR90-map-00b.root";
  ni++; fn[ni] = "SR90-map-01a.root";
  ni++; fn[ni] = "SR90-map-01b.root";
  ni++; fn[ni] = "SR90-map-02.root";
  ni++; fn[ni] = "SR90-map-03.root";
  ni++; fn[ni] = "SR90-map-05a.root";
  ni++; fn[ni] = "SR90-map-05b.root";
  ni++; fn[ni] = "SR90-map-07a.root";
  ni++; fn[ni] = "SR90-map-07b.root";
  ni++; fn[ni] = "SR90-map-07c.root";
  ni++; fn[ni] = "SR90-map-07d.root";

  // direct X-rays 9.4.2014 module D0003

  ni = -1;
  ni++; fn[ni] = "X-ray-20-modtd40000.root";
  ni++; fn[ni] = "X-ray-20-vthr60-modtd1000.root";
  ni++; fn[ni] = "X-ray-27-vthr60-modtd1000.root";
  ni++; fn[ni] = "X-ray-35-modtd40000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-close-modtd65000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-midpos-0p1mA-modtd10000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-midpos-halfcur-modtd40000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-modtd40000.root";

  int nmax = ni;

  TFile f1(fn[0]);

  if( f1.IsZombie() ) {
    cout << "Error opening " << fn[0] << endl;
    return;
  }
  cout << "opened " << fn[0] << endl;

  //--------------------------------------------------------------------
  // create f0:

  TFile f0("fileA.root", "RECREATE");
  cout << "created ";
  gDirectory->pwd();

  /*
  TFile options:  
  NEW or CREATE   create a new file and open it for writing,
                  if the file already exists the file is
                  not opened.
  RECREATE        create a new file, if the file already
                  exists it will be overwritten.
  UPDATE          open an existing file for writing.
                  if no file exists, it is created.
  READ            open an existing file for reading (default).
  NET             used by derived remote file access
                  classes, not a user callable option
  WEB             used by derived remote http access
                  class, not a user callable option
  "" (default), READ is assumed.
  */

  //--------------------------------------------------------------------
  // copy f1 to f0:

  f1.cd();

  cout << "keys:\n";
  f1.GetListOfKeys()->Print();

  cout << "pwd: ";
  f1.pwd();

  cout << "ls: \n";
  f1.ls();

  // f1 has sub-dir:

  cout << "First: " << f1.GetListOfKeys()->First()->GetName() << endl;
  cout << "First: " << f1.GetListOfKeys()->First()->ClassName() << endl;
  char* dir1 = f1.GetListOfKeys()->First()->GetName();
  cout << "cd to " << dir1 << endl;
  f1.cd( dir1 );
  cout << "we are in ";
  gDirectory->pwd();

  gDirectory->ReadAll(); // load histos

  TList * lst = gDirectory->GetList();
  cout << lst->GetName() << endl;
  cout << lst->GetTitle() << endl;
  cout << "size    " << lst->GetSize() << endl;
  cout << "entries " << lst->GetEntries() << endl;
  cout << "last    " << lst->LastIndex() << endl;

  TIterator *iter = lst->MakeIterator();
  int ii = 0;
  TObject *obj;
  TH1D *h;
  TH1D *h0;
  TH2D *H;
  TH2D *H0;

  while( obj = iter->Next() ){
    ii++;
    cout << setw(4) << ii << ": ";
    cout << obj->ClassName() << " ";
    cout << obj->InheritsFrom("TH1D") << " ";
    cout << obj->GetName() << " \"";
    cout << obj->GetTitle() << "\"";
    cout << endl;
    //    if( obj->ClassName() == "TH1D" ){
    if( obj->InheritsFrom("TH1D") ){
      h = (TH1D*) obj;
      cout << "       1D";
      cout << h->GetNbinsX() << " bins, ";
      cout << h->GetEntries() << " entries, ";
      cout << h->GetSumOfWeights() << " inside, ";
      cout << h->GetBinContent(0) << " under, ";
      cout << h->GetBinContent(h->GetNbinsX()+1) << " over";
      cout << endl;

      f0.cd(); // output file

      //      TH1D* h0 = (TH1D*) h->Clone();
      h0 = h; // copy
      h0->Write(); // write to file f0
      
      f1.cd(); // back to file 1 for the loop
    }
    else{

      if( obj->InheritsFrom("TH2D") ){

	H = (TH2D*) obj;
	cout << "       2D";
	cout << H->GetNbinsX() << " bins, ";
	cout << H->GetEntries() << " entries, ";
	cout << H->GetSumOfWeights() << " inside, ";
	cout << H->GetBinContent(0) << " under, ";
	cout << H->GetBinContent(H->GetNbinsX()+1) << " over";
	cout << endl;
	
	f0.cd(); // output file
	
	H0 = H; // copy
	H0->Write(); // write to file f0
	
	f1.cd(); // back to file 1 for the loop
      }
      else cout << "other class " << obj->ClassName() << endl;
    }
  }
  cout << "copied " << ii << endl;
  cout << "f1 " << f1.GetName() << " close = " << f1.Close() << endl;
    
  f0.cd();
  cout << "we are in ";
  gDirectory->pwd();

  cout << "f0 " << f0.GetName() << " size  = " << f0.GetSize() << endl;

  cout << "f0 " << f0.GetName() << " write = " << f0.Write() << endl;

  cout << "f0 " << f0.GetName() << " size  = " << f0.GetSize() << endl;

  cout << "f0 " << f0.GetName() << " close = " << f0.Close() << endl;

  f0.Delete();

  //--------------------------------------------------------------------
  // list of files 2:

  bool lAB = true;

  for( int nn = 1; nn <= nmax; ++nn ){

    cout << "\n\n";
    cout << "loop " << nn << ": fn = " << fn[nn] << endl;
    cout << "lAB = " << lAB << endl;

    if( lAB ) { // A+2 -> B
      char* fn3 = "fileA.root";
      char* fn4 = "fileB.root";
    }
    else{ // B+2 -> A
      char* fn3 = "fileB.root";
      char* fn4 = "fileA.root";
    }

    // create f4:

    TFile f4( fn4, "recreate" );
    if( f4.IsZombie() ) {
      cout << "Error creating f4\n";
      return;
    }
    cout << "created f4   = " << f4.GetName() << endl;

    // re-open as f3:

    TFile f3( fn3 );
    if( f3.IsZombie() ) {
      cout << "Error opening f3\n";
      return;
    }
    cout << "re-opened f3 = " << f3.GetName() << endl;

    lAB = !lAB;
    cout << "lAB = " << lAB << " for next loop\n";

    cout << "f4 = " << f4.GetName() << endl;
    cout << "f3 = " << f3.GetName() << endl;

    f3.cd();
    gDirectory->ReadAll(); // load histos into f3 memory

    //    cout << "f3 list size = " << gDirectory->GetList()->GetSize() << endl;
    cout << "f3 list size = " << gDirectory->GetList()->GetSize() << endl;

    TFile f2(fn[nn]);
    //    TFile *f2 = new TFile(fn[nn]);

    if( f2.IsZombie() ) {
    //    if( f2 == NULL ) {
      cout << "Error opening " << fn[nn] << endl;
      return;
    }
    cout << "opened " << fn[nn] << endl;

    // f2 has sub-dir:

    f2.cd( f2.GetListOfKeys()->First()->GetName() );
    cout << "we are in ";
    gDirectory->pwd();

    gDirectory->ReadAll(); // load histos into f2 memory

    // loop over f2:

    cout << "f2 list size = " << gDirectory->GetList()->GetSize() << endl;

    int jj = 0;
    TObject *ob2;
    TH1D *h2;
    TH1D *h3;
    TH2D *H2;
    TH2D *H3;

    TIterator *ite2 = gDirectory->GetList()->MakeIterator();

    while( ob2 = ite2->Next() ){

      jj++;

      //      if( jj > 9 ) continue;

      cout << jj << ". ";
      cout << "ob2 is ";
      cout << ob2->GetName() << " ";
      cout << ob2->ClassName() << " ";
      cout << ob2->GetTitle();
      cout << endl;

      if( ob2->InheritsFrom("TH1D") ) {

	h2 = (TH1D*) ob2;
	cout << "h2 " << h2->GetName() << "  " << h2->GetNbinsX() << " bins\n";
	cout << "h2 " << h2->GetName() << "  " << h2->GetEntries() << " entries\n";
	char* hnm2 = h2->GetName();

	// search in f3:

	cout << "search for " << hnm2 << " in f3\n";
	f3.cd();
	cout << "we are in ";
	gDirectory->pwd();
	
	h3 = (TH1D*) gDirectory->GetList()->FindObject(hnm2);
	if( h3 == NULL ) {
	  cout << "h3 is null\n" ;
	  continue;
	}
	
	cout << "found h3 = ";
	cout << h3->GetName() << "  ";
	cout << h3->ClassName() << "  ";
	cout << h3->GetTitle();
	cout << endl;
	cout << "h3  " << h3->GetName() << "  " << h3->GetNbinsX() << " bins\n";
	cout << "h3  " << h3->GetName() << "  " << h3->GetEntries() << " entries\n";

	// add:

	f4.cd();
	cout << "we are in ";
	gDirectory->pwd();
	//TH1D h4 = *h3 + *h2;
	TH1D* h4 = (TH1D*) h3->Clone();
	h4->Add(h2);
	
	cout << "h4  " << h4->GetEntries() << " entries\n";
	cout << "h4  ";
	cout << h4->GetName() << " ";
	cout << h4->ClassName() << " ";
	cout << h4->GetTitle();
	cout << endl;
	cout << "h4 dir " << h4->GetDirectory()->GetName() << endl;
	cout << "f4 size " << f4.GetSize() << endl;

	// back to f2 for next iter:

	f2.cd( f2.GetListOfKeys()->First()->GetName() );

      }//1D

      if( ob2->InheritsFrom("TH2D") ) {

	H2 = (TH2D*) ob2;
	cout << "H2 " << H2->GetName() << "  " << H2->GetNbinsX() << " bins\n";
	cout << "H2 " << H2->GetName() << "  " << H2->GetEntries() << " entries\n";
	char* Hnm2 = H2->GetName();

	// search in f3:

	cout << "search for " << Hnm2 << " in f3\n";
	f3.cd();
	cout << "we are in ";
	gDirectory->pwd();
	
	H3 = (TH2D*) gDirectory->GetList()->FindObject(Hnm2);
	if( H3 == NULL ) {
	  cout << "H3 is null\n" ;
	  continue;
	}
	
	cout << "found H3 = ";
	cout << H3->GetName() << "  ";
	cout << H3->ClassName() << "  ";
	cout << H3->GetTitle();
	cout << endl;
	cout << "H3  " << H3->GetName() << "  " << H3->GetNbinsX() << " bins\n";
	cout << "H3  " << H3->GetName() << "  " << H3->GetEntries() << " entries\n";

	// add:

	f4.cd();
	cout << "we are in ";
	gDirectory->pwd();

	TH2D* H4 = (TH2D*) H3->Clone();
	H4->Add(H2);
	
	cout << "H4  " << H4->GetEntries() << " entries\n";
	cout << "H4  ";
	cout << H4->GetName() << " ";
	cout << H4->ClassName() << " ";
	cout << H4->GetTitle();
	cout << endl;
	cout << "H4 dir " << H4->GetDirectory()->GetName() << endl;
	cout << "f4 size " << f4.GetSize() << endl;

	// back to f2 for next iter:

	f2.cd( f2.GetListOfKeys()->First()->GetName() );
      }//2D

    } //while

    cout << "processed " << jj << endl;
    cout << "f4 " << f4.GetName() << " size " << f4.GetSize() << endl;

    //  cout << "f4 map:\n";
    //  f4.Map();

    cout << "f4 " << f4.GetName() << " write = " << f4.Write() << endl;

    cout << "f4 " << f4.GetName() << " size  = " << f4.GetSize() << endl;
    
  }// loop over files 2

  cout << endl;
  cout << "combined " << nmax + 1 << " files\n";
  cout << "Final file is " << f4.GetName() << endl;

  f2.Close();
  f3.Close();
  f4.Close();

}
示例#23
0
void sysError(
    TString inFileName="jfh_HCPR_J50U_Cent30to100_Aj0to100_SubEtaRefl.root",
    Int_t compMode = 0, // Compare mode: 0 reco-genSig, 1 reco-genAll, 3 genAll-genSig, 4 calo_genp-allGen
    Int_t sysMode = 0, // Plot mode: 0 for simple plot, 1 for difference
    TString outdir = ".",
    TString title = "test"
    ) {
  // ===============================================
  // Inputs
  // ===============================================
  TFile *f = new TFile(inFileName);
  TString inFileNameStrip(inFileName); inFileNameStrip.ReplaceAll(".root","");
  TString inFileNameGen(inFileName);
  if (compMode==0) { 
    inFileNameGen.ReplaceAll("djcalo","djcalo_genp");
    inFileNameGen.ReplaceAll("HydjetAll","HydjetSig");
  }
  if (compMode==1) inFileNameGen.ReplaceAll("djcalo","djcalo_genp");
  else if (compMode==3) inFileNameGen.ReplaceAll("HydjetAll","HydjetSig");
  else if (compMode==5) inFileNameGen.ReplaceAll("djcalo_genp","djgen");
  TFile *fgen = new TFile(inFileNameGen);
  TString inFileNameStripGen(inFileNameGen); inFileNameStripGen.ReplaceAll(".root","");
  cout << "==========================================================" << endl;
  cout << "Compare: " << inFileName << endl
       << "         vs " << endl
       << "         " << inFileNameGen << endl;
  cout << "==========================================================" << endl;

  // ===============================================
  // Setup
  // ===============================================
  TString tag=Form("sysError_%s_%s_%d_%d",inFileNameStrip.Data(),title.Data(),compMode,sysMode);

  // ===============================================
  // Analyze
  // ===============================================
  TH2D * hPtPNDR = (TH2D*) f->Get("hPtPNDR");
  TH2D * hPtPADR = (TH2D*) f->Get("hPtPADR");
  TH2D * hPtPNDRBg = (TH2D*) f->Get("hPtPNDRBg");
  TH2D * hPtPADRBg = (TH2D*) f->Get("hPtPADRBg");
  TH2D * hPtPNDRSub = (TH2D*)hPtPNDR->Clone(tag+"hPtPNDRSub");
  TH2D * hPtPADRSub = (TH2D*)hPtPADR->Clone(tag+"hPtPADRSub");
  hPtPNDRSub->Add(hPtPNDR,hPtPNDRBg,1,-1);
  hPtPADRSub->Add(hPtPADR,hPtPADRBg,1,-1);

  TH2D * hPtPNDRGen = (TH2D*) fgen->Get("hPtPNDR");
  TH2D * hPtPADRGen = (TH2D*) fgen->Get("hPtPADR");
  TH2D * hPtPNDRBgGen = (TH2D*) fgen->Get("hPtPNDRBg");
  TH2D * hPtPADRBgGen = (TH2D*) fgen->Get("hPtPADRBg");
  TH2D * hPtPNDRSubGen = (TH2D*)hPtPNDRGen->Clone(tag+"hPtPNDRSub");
  TH2D * hPtPADRSubGen = (TH2D*)hPtPADRGen->Clone(tag+"hPtPADRSub");
  hPtPNDRSubGen->Add(hPtPNDRGen,hPtPNDRBgGen,1,-1);
  hPtPADRSubGen->Add(hPtPADRGen,hPtPADRBgGen,1,-1);

  // ===============================================
  // Draw
  // ===============================================
  // Get Pt info
  Int_t numPtBins=hPtPNDR->GetNbinsX();
  TH1D * hPt = (TH1D*)hPtPNDR->ProjectionX("hPt");
  /*
  cout << "Pt bins: " << numPtBins << endl;
  for (Int_t i=0; i<numPtBins+2; ++i) {
    cout << "Pt Bin " << i << " Low Edge: " << hPt->GetBinLowEdge(i) << endl;
  }
  */

  // What pt bins to draw
  const Int_t numPtBinsDraw=3;

  TCanvas * c6 = new TCanvas("c"+tag,"c"+tag,1400,500);
  c6->Divide(3,1);
  for (Int_t i=0; i<numPtBinsDraw; ++i) {
    Int_t iBeg,iEnd;
    if (i==0) { iBeg=2; iEnd=3;}
    if (i==1) { iBeg=4; iEnd=4;}
    if (i==2) { iBeg=5; iEnd=numPtBins;}
    cout << "Bin: " << iBeg <<  " to " << iEnd << endl;
    TH1D * hNr = (TH1D*)hPtPNDRSub->ProjectionY(tag+Form("hPNDRSub_%d_%d",iBeg,iEnd),iBeg,iEnd);
    TH1D * hAw = (TH1D*)hPtPADRSub->ProjectionY(tag+Form("hPADRSub_%d_%d",iBeg,iEnd),iBeg,iEnd);
    TH1D * hNrGen = (TH1D*)hPtPNDRSubGen->ProjectionY(tag+Form("hPNDRSubGen_%d_%d",iBeg,iEnd),iBeg,iEnd);
    TH1D * hAwGen = (TH1D*)hPtPADRSubGen->ProjectionY(tag+Form("hPADRSubGen_%d_%d",iBeg,iEnd),iBeg,iEnd);
    if (sysMode==1) {
      hNr->Add(hNrGen,-1);
      hAw->Add(hAwGen,-1);
    }
    if (sysMode==2) {
      hNr->Divide(hNrGen);
      hAw->Divide(hAwGen);
    }
    // Print
    cout << Form("%.1f < P_{T} < %.1f GeV: ",hPt->GetBinLowEdge(iBeg),hPt->GetBinLowEdge(iEnd+1))
      << " SigSubBkg Integral - Nr: " << hNr->Integral() << " Aw: " << hAw->Integral() << endl
      << " Gen - Nr: " << hNrGen->Integral() << " Aw: " << hAwGen->Integral() << endl;
    // Styles
    hNr->SetMarkerColor(kRed);
    hNr->SetLineColor(kRed);
    hAw->SetMarkerColor(kBlue);
    hAw->SetLineColor(kBlue);
    hAwGen->SetLineStyle(2);
    // Axis Range
    if (sysMode==0) {
      hNr->SetYTitle("Background Subtracted Signal (GeV/c)");
      hNr->SetAxisRange(-5,60,"Y");
    }
    if (sysMode==2) {
      hNr->SetAxisRange(-2,6,"Y");
    }
    // Axis Label
    if (compMode==0) {
      if (sysMode==1) {
	hNr->SetYTitle("(Reco Trk)-(Sig GenP) (GeV/c)");
	//hNr->SetAxisRange(-20,20,"Y");
      }
      if (sysMode==2) {
	hNr->SetYTitle("(Reco Trk)/(Sig GenP) (GeV/c)");
      }
    }
    if (compMode==3) {
      if (sysMode==1) {
	hNr->SetYTitle("All GenP - Sig GenP (GeV/c)");
	//hNr->SetAxisRange(-3,3,"Y");
      }
      if (sysMode==2) {
	hNr->SetYTitle("(All GenP)/(Sig GenP) (GeV/c)");
      }
    }
    hNr->SetXTitle("#Delta R");
    hNr->SetAxisRange(0,0.79999,"X");
    hNr->SetTitleOffset(1.5,"X");
    hNr->GetXaxis()->CenterTitle();
    hNr->GetYaxis()->CenterTitle();
    c6->cd(i+1);
    // Fit
    if (sysMode>0) {
      TF1 * f0 = new TF1("f0","pol0");
      f0->SetLineStyle(2);
      f0->SetLineWidth(1);
      hNr->Fit("f0");
      hAw->Fit("f0");
    }
    // Draw to Inspect
    hNr->Draw();
    hAw->Draw("same");
    if (sysMode==0) {
      hNrGen->Draw("hist same");
      hAwGen->Draw("hist same");
    }
    if (sysMode==0||sysMode==1) {
      TLine *l = new TLine(0,0,0.8,0);
      l->Draw();
    }
    if (sysMode==2) {
      TLine *l = new TLine(0,1,0.8,1);
      l->Draw();
    }
    
    TLegend *leg = new TLegend(0.35,0.7,0.85,0.94);
    leg->SetBorderSize(0);
    leg->SetFillStyle(0);
    leg->AddEntry(hNr,Form("%.1f < P_{T} < %.1f GeV",hPt->GetBinLowEdge(iBeg),hPt->GetBinLowEdge(iEnd+1)),"");
    if (sysMode==0) {
      if (compMode==0) {
	leg->AddEntry(hNr,"Leading (RecoTrk)","pl");
	leg->AddEntry(hNrGen,"Leading (Sig. GenP)","l");
	leg->AddEntry(hAw,"SubLeading (RecoTrk)","pl");
	leg->AddEntry(hAwGen,"SubLeading (Sig. GenP)","l");
      }
      if (compMode==1) {
	leg->AddEntry(hNr,"Leading (RecoTrk)","pl");
	leg->AddEntry(hNrGen,"Leading (All GenP)","l");
	leg->AddEntry(hAw,"SubLeading (RecoTrk)","pl");
	leg->AddEntry(hAwGen,"SubLeading (All GenP)","l");
      }
    }
    if (sysMode>0) {
      leg->AddEntry(hNr,"Leading","pl");
      leg->AddEntry(hAw,"SubLeading","pl");
    }
    leg->SetTextSize(0.05);
    leg->Draw();
  }

  // ===============================================
  // Save
  // ===============================================
  c6->Print(Form("%s/%s.gif",outdir.Data(),tag.Data()));
  c6->Print(Form("%s/%s.eps",outdir.Data(),tag.Data()));
  c6->Print(Form("%s/%s.C",outdir.Data(),tag.Data()));
}
示例#24
0
int createBadChannelMap()
{
  std::cout << "Number of bad channels from OCDB: " << badChannels.size() << std::endl;
    
    TFile *badFile = TFile::Open("BadMap_LHC11a_pp2760.root", "READ");
    
    TH2D *badMap = (TH2D*)badFile->Get("PHOS_BadMap_mod3");
    
    
    for(Int_t x = 0; x < badMap->GetNbinsX(); x++)
    {
      for(Int_t z = 0; z < badMap->GetNbinsY(); z++)
      {
	if(x<16) 
	{
  	  Int_t relId[4];
	  relId[0] = 3;
	  relId[1] = 0;
	  relId[2] = x+1;
	  relId[3] = z+1;
	  Int_t absId = 0;
	  geoUtils->RelToAbsNumbering(relId, absId);
	  badChannels.push_back(absId);
	}
	//if(badMap->GetBinContent(x,z) == 1)
	if(0)
	{
	  Int_t relId[4];
	  relId[0] = 3;
	  relId[1] = 0;
	  relId[2] = x;
	  relId[3] = z;
	  Int_t absId = 0;
	  geoUtils->RelToAbsNumbering(relId, absId);
	  badChannels.push_back(absId);
	}
      }
    }
    badMap = (TH2D*)badFile->Get("PHOS_BadMap_mod2");
    
    
    for(Int_t x = 0; x < badMap->GetNbinsX(); x++)
    {
      for(Int_t z = 0; z < badMap->GetNbinsY(); z++)
      {
	if(x < 16 && z >=14)
	{
	  Int_t relId[4];
	  relId[0] = 3;
	  relId[1] = 0;
	  relId[2] = x+1;
	  relId[3] = z+1;
	  Int_t absId = 0;
	  geoUtils->RelToAbsNumbering(relId, absId);
	  badChannels.push_back(absId);
	  
	}
	if(x >=32 && x < 48)
	{
	  Int_t relId[4];
	  relId[0] = 3;
	  relId[1] = 0;
	  relId[2] = x+1;
	  relId[3] = z+1;
	  Int_t absId = 0;
	  geoUtils->RelToAbsNumbering(relId, absId);
	  badChannels.push_back(absId);
	}
	//if(badMap->GetBinContent(x,z) == 1)
	if(0)
	{
	  Int_t relId[4];
	  relId[0] = 2;
	  relId[1] = 0;
	  relId[2] = x;
	  relId[3] = z;
	  Int_t absId = 0;
	  geoUtils->RelToAbsNumbering(relId, absId);
	  badChannels.push_back(absId);
	}
      }
    }
    badMap = (TH2D*)badFile->Get("PHOS_BadMap_mod1");
    
    
    for(Int_t x = 0; x < badMap->GetNbinsX(); x++)
    {
      for(Int_t z = 0; z < badMap->GetNbinsY(); z++)
      {
	//if(badMap->GetBinContent(x,z) == 1)
	if(0)
	{
	  Int_t relId[4];
	  relId[0] = 1;
	  relId[1] = 0;
	  relId[2] = x;
	  relId[3] = z;
	  Int_t absId = 0;
	  geoUtils->RelToAbsNumbering(relId, absId);
	  badChannels.push_back(absId);
	}
      }
    }
    std::cout << "New number of bad channels: " << badChannels.size() << std::endl;
    
    
    return 0;
}
示例#25
0
void computeAccSelWm(const TString conf,       // input file
                     const TString outputDir,  // output directory
		     const Int_t   charge,      // 0 = inclusive, +1 = W+, -1 = W-
		     const Int_t   doPU
) {
  gBenchmark->Start("computeAccSelWm");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  const Double_t PT_CUT     = 25;
  const Double_t ETA_CUT    = 2.4;
  const Double_t ETA_BARREL = 1.2;
  const Double_t ETA_ENDCAP = 1.2;

  const Double_t VETO_PT   = 10;
  const Double_t VETO_ETA  = 2.4;

  const Int_t BOSON_ID  = 24;
  const Int_t LEPTON_ID = 13;
  
  // efficiency files
  TString dataHLTEffName("/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuHLTEff/MG/eff.root");
  TString zmmHLTEffName( "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuHLTEff/CT/eff.root");
  TString dataSelEffName("/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuSITEff/MG/eff.root");
  TString zmmSelEffName( "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuSITEff/CT/eff.root");
  TString dataTrkEffName("/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/MG/eff.root");
  TString zmmTrkEffName( "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/CT/eff.root");
  TString dataStaEffName("/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/MG/eff.root");
  TString zmmStaEffName( "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/CT/eff.root");
  if(charge==1) {
    dataHLTEffName ="/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuHLTEff/MG/eff.root";
    zmmHLTEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuHLTEff/CT/eff.root";
    dataSelEffName ="/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuSITEff/MG/eff.root";
    zmmSelEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuSITEff/CT/eff.root";
    dataTrkEffName ="/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/MG/eff.root";
    zmmTrkEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/CT/eff.root";
    dataStaEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/MG/eff.root";
    zmmStaEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/CT/eff.root";
  }
  if(charge==-1) {
    dataHLTEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuHLTEff/MG/eff.root";
    zmmHLTEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuHLTEff/CT/eff.root";
    dataSelEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuSITEff/MG/eff.root";
    zmmSelEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuSITEff/CT/eff.root";
    dataTrkEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/MG/eff.root";
    zmmTrkEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/CT/eff.root";
    dataStaEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/MG/eff.root";
    zmmStaEffName = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/MuStaEff/CT/eff.root";
  }

  // load pileup reweighting file
  TFile *f_rw = TFile::Open("../Tools/pileup_rw_76X.root", "read");
  TH1D *h_rw = (TH1D*) f_rw->Get("h_rw_golden");


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  vector<TString> fnamev;  // file name per input file
  vector<TString> labelv;  // TLegend label per input file
  vector<Int_t>   colorv;  // plot color per input file
  vector<Int_t>   linev;   // plot line style per input file

  //
  // parse .conf file
  //
  ifstream ifs;
  ifs.open(conf.Data());
  assert(ifs.is_open());
  string line;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    
    string fname;
    Int_t color, linesty;
    stringstream ss(line);
    ss >> fname >> color >> linesty;
    string label = line.substr(line.find('@')+1);
    fnamev.push_back(fname);
    labelv.push_back(label);
    colorv.push_back(color);
    linev.push_back(linesty);
  }
  ifs.close();

  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  
  //
  // Get efficiency
  //
  TFile *dataHLTEffFile = new TFile(dataHLTEffName);
  CEffUser2D dataHLTEff;
  TH2D *hHLTErr=0, *hHLTErrB=0, *hHLTErrE=0;
  if(dataHLTEffFile) {    
    dataHLTEff.loadEff((TH2D*)dataHLTEffFile->Get("hEffEtaPt"), 
                       (TH2D*)dataHLTEffFile->Get("hErrlEtaPt"),
		       (TH2D*)dataHLTEffFile->Get("hErrhEtaPt"));
    
    TH2D* h =(TH2D*)dataHLTEffFile->Get("hEffEtaPt");
    hHLTErr  = new TH2D("hHLTErr", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hHLTErrB = new TH2D("hHLTErrB","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hHLTErrE = new TH2D("hHLTErrE","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  }
  
  TFile *zmmHLTEffFile = new TFile(zmmHLTEffName);
  CEffUser2D zmmHLTEff;
  if(zmmHLTEffFile) {
    zmmHLTEff.loadEff((TH2D*)zmmHLTEffFile->Get("hEffEtaPt"),
                      (TH2D*)zmmHLTEffFile->Get("hErrlEtaPt"),
                      (TH2D*)zmmHLTEffFile->Get("hErrhEtaPt"));
  }
  
  TFile *dataSelEffFile = new TFile(dataSelEffName);
  CEffUser2D dataSelEff;
  TH2D *hSelErr=0, *hSelErrB=0, *hSelErrE=0;
  if(dataSelEffFile) {
    dataSelEff.loadEff((TH2D*)dataSelEffFile->Get("hEffEtaPt"),
                       (TH2D*)dataSelEffFile->Get("hErrlEtaPt"),
                       (TH2D*)dataSelEffFile->Get("hErrhEtaPt"));
    
    TH2D* h =(TH2D*)dataSelEffFile->Get("hEffEtaPt");
    hSelErr  = new TH2D("hSelErr", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hSelErrB = new TH2D("hSelErrB","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hSelErrE = new TH2D("hSelErrE","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  }
  
  TFile *zmmSelEffFile = new TFile(zmmSelEffName);
  CEffUser2D zmmSelEff;
  if(zmmSelEffFile) {
    zmmSelEff.loadEff((TH2D*)zmmSelEffFile->Get("hEffEtaPt"),
                      (TH2D*)zmmSelEffFile->Get("hErrlEtaPt"),
                      (TH2D*)zmmSelEffFile->Get("hErrhEtaPt"));
  }
  
  TFile *dataTrkEffFile = new TFile(dataTrkEffName);
  CEffUser2D dataTrkEff;
  TH2D *hTrkErr=0, *hTrkErrB=0, *hTrkErrE=0;
  if(dataTrkEffFile) {
    dataTrkEff.loadEff((TH2D*)dataTrkEffFile->Get("hEffEtaPt"),
                       (TH2D*)dataTrkEffFile->Get("hErrlEtaPt"),
                       (TH2D*)dataTrkEffFile->Get("hErrhEtaPt"));
    
    TH2D* h =(TH2D*)dataTrkEffFile->Get("hEffEtaPt");
    hTrkErr  = new TH2D("hTrkErr", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hTrkErrB = new TH2D("hTrkErrB","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hTrkErrE = new TH2D("hTrkErrE","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  }
  
  TFile *zmmTrkEffFile = new TFile(zmmTrkEffName);
  CEffUser2D zmmTrkEff;
  if(zmmTrkEffFile) {
    zmmTrkEff.loadEff((TH2D*)zmmTrkEffFile->Get("hEffEtaPt"),
                      (TH2D*)zmmTrkEffFile->Get("hErrlEtaPt"),
                      (TH2D*)zmmTrkEffFile->Get("hErrhEtaPt"));
  }
  
  TFile *dataStaEffFile = new TFile(dataStaEffName);
  CEffUser2D dataStaEff;
  TH2D *hStaErr=0, *hStaErrB=0, *hStaErrE=0;
  if(dataStaEffFile) {
    dataStaEff.loadEff((TH2D*)dataStaEffFile->Get("hEffEtaPt"),
                       (TH2D*)dataStaEffFile->Get("hErrlEtaPt"),
                       (TH2D*)dataStaEffFile->Get("hErrhEtaPt"));
    
    TH2D* h =(TH2D*)dataStaEffFile->Get("hEffEtaPt");
    hStaErr  = new TH2D("hStaErr", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hStaErrB = new TH2D("hStaErrB","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
    hStaErrE = new TH2D("hStaErrE","",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                      h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  }
  
  TFile *zmmStaEffFile = new TFile(zmmStaEffName);
  CEffUser2D zmmStaEff;
  if(zmmStaEffFile) {
    zmmStaEff.loadEff((TH2D*)zmmStaEffFile->Get("hEffEtaPt"),
                      (TH2D*)zmmStaEffFile->Get("hErrlEtaPt"),
                      (TH2D*)zmmStaEffFile->Get("hErrhEtaPt"));
  }
  
  // Data structures to store info from TTrees
  baconhep::TEventInfo   *info = new baconhep::TEventInfo();
  baconhep::TGenEventInfo *gen = new baconhep::TGenEventInfo();
  TClonesArray     *genPartArr = new TClonesArray("baconhep::TGenParticle");
  TClonesArray        *muonArr = new TClonesArray("baconhep::TMuon");
  TClonesArray *vertexArr  = new TClonesArray("baconhep::TVertex");
  
  TFile *infile=0;
  TTree *eventTree=0;

  // Variables to store acceptances and uncertainties (per input file)
  vector<Double_t> nEvtsv, nSelv, nSelBv, nSelEv;
  vector<Double_t> accv, accBv, accEv;
  vector<Double_t> accErrv, accErrBv, accErrEv;
  vector<Double_t> nSelCorrv, nSelBCorrv, nSelECorrv;
  vector<Double_t> nSelCorrVarv, nSelBCorrVarv, nSelECorrVarv;
  vector<Double_t> accCorrv, accBCorrv, accECorrv;
  vector<Double_t> accErrCorrv, accErrBCorrv, accErrECorrv;

  const baconhep::TTrigger triggerMenu("../../BaconAna/DataFormats/data/HLT_50nsGRun");
  
  //
  // loop through files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {  

    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << " ..." << endl;
    infile = TFile::Open(fnamev[ifile]); 
    assert(infile);
  
    eventTree = (TTree*)infile->Get("Events"); assert(eventTree);  
    eventTree->SetBranchAddress("Info",             &info); TBranch *infoBr    = eventTree->GetBranch("Info");
    eventTree->SetBranchAddress("GenEvtInfo",        &gen); TBranch *genBr     = eventTree->GetBranch("GenEvtInfo");
    eventTree->SetBranchAddress("GenParticle",&genPartArr); TBranch *genPartBr = eventTree->GetBranch("GenParticle");
    eventTree->SetBranchAddress("Muon",          &muonArr); TBranch *muonBr    = eventTree->GetBranch("Muon"); 
    eventTree->SetBranchAddress("PV",   &vertexArr); TBranch *vertexBr = eventTree->GetBranch("PV");

    nEvtsv.push_back(0);
    nSelv.push_back(0);
    nSelBv.push_back(0);
    nSelEv.push_back(0);
    nSelCorrv.push_back(0);
    nSelBCorrv.push_back(0);
    nSelECorrv.push_back(0);
    nSelCorrVarv.push_back(0);
    nSelBCorrVarv.push_back(0);
    nSelECorrVarv.push_back(0);
    
    for(Int_t iy=0; iy<=hHLTErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hHLTErr->GetNbinsX(); ix++) {
        hHLTErr ->SetBinContent(ix,iy,0);
        hHLTErrB->SetBinContent(ix,iy,0);
        hHLTErrE->SetBinContent(ix,iy,0);
      }
    }
    for(Int_t iy=0; iy<=hSelErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hSelErr->GetNbinsX(); ix++) {
        hSelErr ->SetBinContent(ix,iy,0);
        hSelErrB->SetBinContent(ix,iy,0);
        hSelErrE->SetBinContent(ix,iy,0);
      }
    }
    for(Int_t iy=0; iy<=hTrkErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hTrkErr->GetNbinsX(); ix++) {
        hTrkErr ->SetBinContent(ix,iy,0);
        hTrkErrB->SetBinContent(ix,iy,0);
        hTrkErrE->SetBinContent(ix,iy,0);
      }
    }
    for(Int_t iy=0; iy<=hStaErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hStaErr->GetNbinsX(); ix++) {
        hStaErr ->SetBinContent(ix,iy,0);
        hStaErrB->SetBinContent(ix,iy,0);
        hStaErrE->SetBinContent(ix,iy,0);
      }
    }    
    
    //
    // loop over events
    //    
    for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
    //for(UInt_t ientry=0; ientry<1000000; ientry++) {
      genBr->GetEntry(ientry);
      infoBr->GetEntry(ientry);
      genPartArr->Clear(); genPartBr->GetEntry(ientry);

      if (charge==-1 && toolbox::flavor(genPartArr, BOSON_ID)!=LEPTON_ID) continue;
      if (charge==1 && toolbox::flavor(genPartArr, BOSON_ID)!=-LEPTON_ID) continue;
      if (charge==0 && fabs(toolbox::flavor(genPartArr, BOSON_ID))!=LEPTON_ID) continue;
      /*TLorentzVector *vec=new TLorentzVector(0,0,0,0);
      TLorentzVector *lep1=new TLorentzVector(0,0,0,0);
      TLorentzVector *lep2=new TLorentzVector(0,0,0,0);
      toolbox::fillGen(genPartArr, BOSON_ID, vec, lep1, lep2,1);*/
      
      vertexArr->Clear();
      vertexBr->GetEntry(ientry);
      double npv  = vertexArr->GetEntries();
      Double_t weight=gen->weight;
      if(doPU>0) weight*=h_rw->GetBinContent(h_rw->FindBin(info->nPUmean));

      nEvtsv[ifile]+=weight;
      
      // trigger requirement               
      if (!isMuonTrigger(triggerMenu, info->triggerBits)) continue;
   
      // good vertex requirement
      if(!(info->hasGoodPV)) continue;
    
      muonArr->Clear();
      muonBr->GetEntry(ientry);
      Int_t nLooseLep=0;
      const baconhep::TMuon *goodMuon=0;
      Bool_t passSel=kFALSE;
      for(Int_t i=0; i<muonArr->GetEntriesFast(); i++) {
  	const baconhep::TMuon *mu = (baconhep::TMuon*)((*muonArr)[i]);

        if(fabs(mu->eta) > VETO_ETA) continue; // loose lepton |eta| cut
        if(mu->pt	 < VETO_PT)  continue; // loose lepton pT cut
        if(passMuonLooseID(mu)) nLooseLep++;   // loose lepton selection
        if(nLooseLep>1) {  // extra lepton veto
          passSel=kFALSE;
          break;
        }
        
        if(fabs(mu->eta) > ETA_CUT)         continue;  // lepton |eta| cut
        if(mu->pt < PT_CUT)		    continue;  // lepton pT cut	
        if(!passMuonID(mu))		    continue;  // lepton selection
	if(!isMuonTriggerObj(triggerMenu, mu->hltMatchBits, kFALSE)) continue;
	
	if(charge!=0 && mu->q!=charge) continue;  // check charge (if necessary)
	
	passSel=kTRUE;
	goodMuon=mu;
      }
      
      if(passSel) {
        
	/******** We have a W candidate! HURRAY! ********/
        
	Bool_t isBarrel = (fabs(goodMuon->eta)<ETA_BARREL) ? kTRUE : kFALSE;
        
	// data/MC scale factor corrections
	Double_t corr=1;
	if(dataHLTEffFile && zmmHLTEffFile) {
	  Double_t effdata = dataHLTEff.getEff(goodMuon->eta, goodMuon->pt);
	  Double_t effmc   = zmmHLTEff.getEff(goodMuon->eta, goodMuon->pt);
	  corr *= effdata/effmc;
	}
	if(dataSelEffFile && zmmSelEffFile) {
	  Double_t effdata = dataSelEff.getEff(goodMuon->eta, goodMuon->pt);
	  Double_t effmc   = zmmSelEff.getEff(goodMuon->eta, goodMuon->pt);
	  corr *= effdata/effmc;
	}
	if(dataTrkEffFile && zmmTrkEffFile) {
	  Double_t effdata = dataTrkEff.getEff(goodMuon->eta, goodMuon->pt);
	  Double_t effmc   = zmmTrkEff.getEff(goodMuon->eta, goodMuon->pt);
	  //corr *= effdata/effmc;
	}
	if(dataStaEffFile && zmmStaEffFile) {
	  Double_t effdata = dataStaEff.getEff(goodMuon->eta, goodMuon->pt);
	  Double_t effmc   = zmmStaEff.getEff(goodMuon->eta, goodMuon->pt);
	  corr *= effdata/effmc;
	}
	
	// scale factor uncertainties
	if(dataHLTEffFile && zmmHLTEffFile) {
	  Double_t effdata = dataHLTEff.getEff(goodMuon->eta, goodMuon->pt);
	  Double_t effmc   = zmmHLTEff.getEff(goodMuon->eta, goodMuon->pt);	  
	  Double_t errdata = TMath::Max(dataHLTEff.getErrLow(goodMuon->eta, goodMuon->pt),dataHLTEff.getErrHigh(goodMuon->eta, goodMuon->pt));
	  Double_t errmc   = TMath::Max(zmmHLTEff.getErrLow(goodMuon->eta, goodMuon->pt), zmmHLTEff.getErrHigh(goodMuon->eta, goodMuon->pt));
	  Double_t err     = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata+errmc*errmc/effmc/effmc);
	  hHLTErr->Fill(goodMuon->eta,goodMuon->pt,err);
	  if(isBarrel) hHLTErrB->Fill(goodMuon->eta,goodMuon->pt,err);
	  else         hHLTErrE->Fill(goodMuon->eta,goodMuon->pt,err);
	}
	if(dataSelEffFile && zmmSelEffFile) {
	  Double_t effdata = dataSelEff.getEff(goodMuon->eta, goodMuon->pt);
	  Double_t effmc   = zmmSelEff.getEff(goodMuon->eta, goodMuon->pt);	  
	  Double_t errdata = TMath::Max(dataSelEff.getErrLow(goodMuon->eta, goodMuon->pt),dataSelEff.getErrHigh(goodMuon->eta, goodMuon->pt));
	  Double_t errmc   = TMath::Max(zmmSelEff.getErrLow(goodMuon->eta, goodMuon->pt), zmmSelEff.getErrHigh(goodMuon->eta, goodMuon->pt));
	  Double_t err     = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata+errmc*errmc/effmc/effmc);
	  hSelErr->Fill(goodMuon->eta,goodMuon->pt,err);
	  if(isBarrel) hSelErrB->Fill(goodMuon->eta,goodMuon->pt,err);
	  else         hSelErrE->Fill(goodMuon->eta,goodMuon->pt,err);
	}
	if(dataTrkEffFile && zmmTrkEffFile) {
	  Double_t effdata = dataTrkEff.getEff(goodMuon->eta, goodMuon->pt);
	  Double_t effmc   = zmmTrkEff.getEff(goodMuon->eta, goodMuon->pt);	  
	  Double_t errdata = TMath::Max(dataTrkEff.getErrLow(goodMuon->eta, goodMuon->pt),dataTrkEff.getErrHigh(goodMuon->eta, goodMuon->pt));
	  Double_t errmc   = TMath::Max(zmmTrkEff.getErrLow(goodMuon->eta, goodMuon->pt), zmmTrkEff.getErrHigh(goodMuon->eta, goodMuon->pt));
	  Double_t err     = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata+errmc*errmc/effmc/effmc);
	  /* if(goodMuon->eta>1.2 && goodMuon->eta<2.1) 
	    {
	      err=0.0013;
	      }*/
	  hTrkErr->Fill(goodMuon->eta,goodMuon->pt,err);
	  if(isBarrel) hTrkErrB->Fill(goodMuon->eta,goodMuon->pt,err);
	  else         hTrkErrE->Fill(goodMuon->eta,goodMuon->pt,err);
	}
	if(dataStaEffFile && zmmStaEffFile) {
	  Double_t effdata = dataStaEff.getEff(goodMuon->eta, goodMuon->pt);
	  Double_t effmc   = zmmStaEff.getEff(goodMuon->eta, goodMuon->pt);	  
	  Double_t errdata = TMath::Max(dataStaEff.getErrLow(goodMuon->eta, goodMuon->pt),dataStaEff.getErrHigh(goodMuon->eta, goodMuon->pt));
	  Double_t errmc   = TMath::Max(zmmStaEff.getErrLow(goodMuon->eta, goodMuon->pt), zmmStaEff.getErrHigh(goodMuon->eta, goodMuon->pt));
	  Double_t err     = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata+errmc*errmc/effmc/effmc);
	  hStaErr->Fill(goodMuon->eta,goodMuon->pt,err);
	  if(isBarrel) hStaErrB->Fill(goodMuon->eta,goodMuon->pt,err);
	  else         hStaErrE->Fill(goodMuon->eta,goodMuon->pt,err);
	}
	
	nSelv[ifile]+=weight;
	nSelCorrv[ifile]+=weight*corr;
	nSelCorrVarv[ifile]+=weight*weight*corr*corr;
  	if(isBarrel) { 
	  nSelBv[ifile]+=weight;
	  nSelBCorrv[ifile]+=weight*corr;
	  nSelBCorrVarv[ifile]+=weight*weight*corr*corr;
	  	
	} else { 
	  nSelEv[ifile]+=weight;
	  nSelECorrv[ifile]+=weight*corr;
	  nSelECorrVarv[ifile]+=weight*weight*corr*corr;
	}
      }
    }
    
    Double_t var=0, varB=0, varE=0;
    for(Int_t iy=0; iy<=hHLTErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hHLTErr->GetNbinsX(); ix++) {
        Double_t err;
	err=hHLTErr->GetBinContent(ix,iy);  var+=err*err;
        err=hHLTErrB->GetBinContent(ix,iy); varB+=err*err;
        err=hHLTErrE->GetBinContent(ix,iy); varE+=err*err;
      }
    }
    for(Int_t iy=0; iy<=hSelErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hSelErr->GetNbinsX(); ix++) {
        Double_t err;
	err=hSelErr->GetBinContent(ix,iy);  var+=err*err;
	err=hSelErrB->GetBinContent(ix,iy); varB+=err*err;
	err=hSelErrE->GetBinContent(ix,iy); varE+=err*err;
      }
    }
    for(Int_t iy=0; iy<=hTrkErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hTrkErr->GetNbinsX(); ix++) {
        Double_t err;
	err=hTrkErr->GetBinContent(ix,iy);  var+=0;//err*err;
        err=hTrkErrB->GetBinContent(ix,iy); varB+=0;//err*err;
        err=hTrkErrE->GetBinContent(ix,iy); varE+=0;//err*err;
      }
    }
    for(Int_t iy=0; iy<=hStaErr->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hStaErr->GetNbinsX(); ix++) {
        Double_t err;
	err=hStaErr->GetBinContent(ix,iy);  var+=err*err;
	err=hStaErrB->GetBinContent(ix,iy); varB+=err*err;
	err=hStaErrE->GetBinContent(ix,iy); varE+=err*err;
      }
    }
    nSelCorrVarv[ifile]+=var;
    nSelBCorrVarv[ifile]+=varB;
    nSelECorrVarv[ifile]+=varE;
    
    // compute acceptances
    accv.push_back(nSelv[ifile]/nEvtsv[ifile]);   accErrv.push_back(sqrt(accv[ifile]*(1.+accv[ifile])/nEvtsv[ifile]));
    accBv.push_back(nSelBv[ifile]/nEvtsv[ifile]); accErrBv.push_back(sqrt(accBv[ifile]*(1.+accBv[ifile])/nEvtsv[ifile]));
    accEv.push_back(nSelEv[ifile]/nEvtsv[ifile]); accErrEv.push_back(sqrt(accEv[ifile]*(1.+accEv[ifile])/nEvtsv[ifile]));
    
    accCorrv.push_back(nSelCorrv[ifile]/nEvtsv[ifile]);   accErrCorrv.push_back(accCorrv[ifile]*sqrt(nSelCorrVarv[ifile]/(nSelCorrv[ifile]*nSelCorrv[ifile]) + 1./nEvtsv[ifile]));
    accBCorrv.push_back(nSelBCorrv[ifile]/nEvtsv[ifile]); accErrBCorrv.push_back(accBCorrv[ifile]*sqrt(nSelBCorrVarv[ifile]/nSelBCorrv[ifile]/nSelBCorrv[ifile] + 1./nEvtsv[ifile]));
    accECorrv.push_back(nSelECorrv[ifile]/nEvtsv[ifile]); accErrECorrv.push_back(accECorrv[ifile]*sqrt(nSelECorrVarv[ifile]/(nSelECorrv[ifile]*nSelECorrv[ifile]) + 1./nEvtsv[ifile]));
   
    delete infile;
    infile=0, eventTree=0;  
  }
  delete info;
  delete gen;
  delete muonArr;
  
    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  if(charge== 0) cout << " W -> mu nu"  << endl;
  if(charge==-1) cout << " W- -> mu nu" << endl;
  if(charge== 1) cout << " W+ -> mu nu" << endl;
  cout << "  pT > " << PT_CUT << endl;
  cout << "  |eta| < " << ETA_CUT << endl;
  cout << "  Barrel definition: |eta| < " << ETA_BARREL << endl;
  cout << "  Endcap definition: |eta| > " << ETA_ENDCAP << endl;
  cout << endl;
  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    cout << "   ================================================" << endl;
    cout << "    Label: " << labelv[ifile] << endl;
    cout << "     File: " << fnamev[ifile] << endl;
    cout << endl;
    cout << "    *** Acceptance ***" << endl;
    cout << "     barrel: " << setw(12) << nSelBv[ifile] << " / " << nEvtsv[ifile] << " = " << accBv[ifile] << " +/- " << accErrBv[ifile];
    cout << "  ==eff corr==> " << accBCorrv[ifile] << " +/- " << accErrBCorrv[ifile] << endl;
    cout << "     endcap: " << setw(12) << nSelEv[ifile] << " / " << nEvtsv[ifile] << " = " << accEv[ifile] << " +/- " << accErrEv[ifile];
    cout << "  ==eff corr==> " << accECorrv[ifile] << " +/- " << accErrECorrv[ifile] << endl;
    cout << "      total: " << setw(12) << nSelv[ifile]  << " / " << nEvtsv[ifile] << " = " << accv[ifile]  << " +/- " << accErrv[ifile];
    cout << "  ==eff corr==> " << accCorrv[ifile]  << " +/- " << accErrCorrv[ifile] << endl;
    cout << endl;
  }
  
  char txtfname[100];
  sprintf(txtfname,"%s/sel.txt",outputDir.Data());
  ofstream txtfile;
  txtfile.open(txtfname);
  txtfile << "*" << endl;
  txtfile << "* SUMMARY" << endl;
  txtfile << "*--------------------------------------------------" << endl;
  if(charge== 0) txtfile << " W -> mu nu"  << endl;
  if(charge==-1) txtfile << " W- -> mu nu" << endl;
  if(charge== 1) txtfile << " W+ -> mu nu" << endl;
  txtfile << "  pT > " << PT_CUT << endl;
  txtfile << "  |eta| < " << ETA_CUT << endl;
  txtfile << "  Barrel definition: |eta| < " << ETA_BARREL << endl;
  txtfile << "  Endcap definition: |eta| > " << ETA_ENDCAP << endl;
  txtfile << endl;
  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    txtfile << "   ================================================" << endl;
    txtfile << "    Label: " << labelv[ifile] << endl;
    txtfile << "     File: " << fnamev[ifile] << endl;
    txtfile << endl;
    txtfile << "    *** Acceptance ***" << endl;
    txtfile << "     barrel: " << setw(12) << nSelBv[ifile] << " / " << nEvtsv[ifile] << " = " << accBv[ifile] << " +/- " << accErrBv[ifile];
    txtfile << "  ==eff corr==> " << accBCorrv[ifile] << " +/- " << accErrBCorrv[ifile] << endl;
    txtfile << "     endcap: " << setw(12) << nSelEv[ifile] << " / " << nEvtsv[ifile] << " = " << accEv[ifile] << " +/- " << accErrEv[ifile];
    txtfile << "  ==eff corr==> " << accECorrv[ifile] << " +/- " << accErrECorrv[ifile] << endl;
    txtfile << "      total: " << setw(12) << nSelv[ifile]  << " / " << nEvtsv[ifile] << " = " << accv[ifile]  << " +/- " << accErrv[ifile];
    txtfile << "  ==eff corr==> " << accCorrv[ifile]  << " +/- " << accErrCorrv[ifile] << endl;
    txtfile << endl;
  }
  txtfile.close();  
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("computeAccSelWm"); 
}