Example #1
0
void zeeAnaDiff(TH1D* hsee, TCut addCut,TH1D* hseeMc) {
  
  TFile *f1=new TFile(fname1.Data());
  TTree *zp = (TTree*)f1->Get("tz");
  zp->AddFriend("yEvt=yongsunHiEvt"       ,fname1.Data());
  zp->AddFriend("ySkim=yongsunSkimTree"   ,fname1.Data());
  zp->AddFriend("yHlt=yongsunHltTree"     ,fname1.Data());
  zp->AddFriend("tgj",                     fname1.Data());
  
  TH1D* hmass = new TH1D("hmass",";inv. mass (GeV);event fraction",34,30,200);
  hmass->Sumw2();

  zp->Draw("invm>>hmass",addCut && "isEle1==1 && isEle2==1");
  TH1D* htemp = (TH1D*)hsee->Clone("htemp");   htemp->Reset();
  zp->Draw("see1>>htemp",addCut && "isEle1==1 && isEle2==1" && "invm>80 && invm<100" );
  hsee->Reset();
  hsee->Add(htemp);
  handsomeTH1(hmass,2);
  scaleInt(hmass);
  
  TH1D* htempMC;
  TFile *f1mc;
  TTree *zpmc ;
  f1mc=new TFile(fname1MC.Data());
  zpmc = (TTree*)f1mc->Get("tz");
  zpmc->AddFriend("yEvt=yongsunHiEvt"       ,fname1MC.Data());
  zpmc->AddFriend("ySkim=yongsunSkimTree"   ,fname1MC.Data());
  zpmc->AddFriend("yHlt=yongsunHltTree"     ,fname1MC.Data());
  zpmc->AddFriend("yPho=yongsunPhotonTree"     ,fname1MC.Data());
  zpmc->AddFriend("tgj",                     fname1MC.Data());
  hseeMc->Sumw2();
  htempMC = (TH1D*)hseeMc->Clone("htempMc");   htempMC->Reset();
  TH1D* hmassMC = new TH1D("hmassMC11",";inv. mass (GeV);event fraction",34,30,200);
  hmassMC->Sumw2();
  zpmc->Draw("invm>>hmassMC11",Form("(%s) *yPho.ncoll",addCut.GetTitle()));
  zpmc->Draw("see1>>htempMc",Form("(%s) *yPho.ncoll", (addCut && "invm>80 && invm<100").GetTitle()) );
  hseeMc->Reset();
  hseeMc->Add(htempMC);
  handsomeTH1(hmassMC,1);
  scaleInt(hmassMC);
  
  
  hmassMC->SetAxisRange(0,0.6,"Y");
  hmassMC->DrawCopy();
  hmass->DrawCopy("same");                                                                                             
  TLegend* leg1 =  new TLegend(0.5580645,0.5381356,0.8923387,0.7648305,NULL,"brNDC");
  easyLeg(leg1,"Z->ee mass");
  leg1->AddEntry(hmass,"DATA","pl");
  leg1->AddEntry(hmassMC,"MC","pl");
  leg1->Draw();
  
}
Example #2
0
// ============================================================================
StatusCode Gaudi::Utils::Histos::fromXml
( TH1D& result , const std::string& input )
{
  //
  result.Reset() ;                                 // RESET old histogram
  //
  _Xml<TH1D> _xml ;
  std::auto_ptr<TH1D> histo =  _xml ( input ) ;
  if ( 0 == histo.get() ) { return StatusCode::FAILURE ; }        // RETURN
  //
  result.Reset() ;
  histo->Copy ( result ) ;
  //
  return StatusCode::SUCCESS ;
}
void  makeGaussianSignals(SigData_t& m_sigdata)
{
  //std::vector<TH1D *> vgsh(NUMCHAN);
  std::vector<TH1D *> vcdfh(NUMCHAN);

  if( m_sigdata.find("gs") == m_sigdata.end() ) {
    cerr << "Gaussian signal data not found, not making CDF signal!" << endl;
    return;
  }

  for (int ichan=0; ichan<NUMCHAN; ichan++) {
    TH1D *cdfh;

    TString channame(channames[ichan]);
    TString name;

    TH1D * gsh = m_sigdata["gs"].at(ichan);

    assert(gsh) ;

#if 0
    name = "Signalgs_"+channame;
    gsh = (TH1D *)tch->Clone(name.Data());

    assert(gsh);

    gsh->SetTitle("Gaussian signal");
    
    gsh->Reset();

    TF1 *g = (TF1 *)gROOT->GetFunction("gaus");
    g->SetParameters(1,gaussian_mean_mass_gev,gaussian_mass_sigma_gev);
    gsh->FillRandom("gaus",100000);

    // norm to 1pb signal with 1/fb integrated luminosity
    double norm = 1000 * gseffxacc[ichan]/gsh->Integral(0,gsh->GetNbinsX()+1,"width");

    //gsh->Scale(norm/eff_fudgefactor); // kludge: pre-undo the fudge in the next module
    gsh->Scale(norm);

    vgsh[ichan] = gsh;
#endif

    // New CDF bump, same as Gauss but set to CDF (obs/theor)*(LHC theor) = 3.43pb
    cdfh = (TH1D *)gsh->Clone("CDFbump");

    cdfh->Scale(3.43);

    vcdfh[ichan] = cdfh;

    cdfh->Draw();

    gsh->Draw("same");

  } // channel loop

  //m_sigdata["gs"]  = vgsh;
  m_sigdata["cdf"] = vcdfh;
}                                                           // makeGaussianSignals
Example #4
0
File: fft.C Project: svn2github/Go4
///////////////////////////////////////////////////////////////////
//////// Go4 GUI example script fft.C
//          J.Adamczewski, gsi, 30 May 2012
// NOTE: to be run in Go4 GUI local command line only!
//       NEVER call this script in remote analysis process!!!
/////// Functionality:
// perfroms fft on histogram of name1 using the option as explained in root TVirtualFFT:FFT
/////// Usage:
// The draw flag switches if the results are displayed each time this macro is called
// if display is switched off, the result histogram is just updated in browser and existing displays
///////
Bool_t fft(const char* name1, Option_t*  opt = "R2C M", Bool_t draw=kTRUE)
{
   if(TGo4AbstractInterface::Instance()==0 || go4!=TGo4AbstractInterface::Instance()) {
      std::cout <<"FATAL: Go4 gui macro executed outside Go4 GUI!! returning." << std::endl;
      return kFALSE;
   }
   TString newname;
   TString fullname1 = go4->FindItem(name1);
   TObject* ob1 = go4->GetObject(fullname1,1000); // 1000=timeout to get object from analysis in ms

   if ((ob1==0) || !ob1->InheritsFrom("TH1")) {
     std::cout <<"fft could not get histogram "<<fullname1 << std::endl;
     return kFALSE;
   }

   if(ob1->InheritsFrom("TH2") || ob1->InheritsFrom("TH3")){  // 2d
      std::cout <<"fft does not support 2d/3d histogram "<<fullname1 << std::endl;
      return kFALSE;
   }

   TH1* his1=(TH1*)ob1;
   TString n1=his1->GetName();
   TString t1=his1->GetTitle();
   newname.Form("_fft_%s",opt);
   TString finalname = n1+newname;
   TString finaltitle = t1+newname;


   // do fft here:
   Int_t N = his1->GetNbinsX();
   TH1D* result = new TH1D(finalname, finaltitle,N,0,N);
   result->SetName(finalname);
   result->SetTitle(finaltitle);
   result->Reset("");
   Double_t *in = new Double_t[N];
   // since we do not know type of input histo, we copy contents to Double array:
   for(Int_t ix=0; ix<N;++ix)
   {
      in[ix]=his1->GetBinContent(ix+1);
   }
   TVirtualFFT *thefft = TVirtualFFT::FFT(1, &N, opt);
   thefft->SetPoints(in);
   thefft->Transform();
   Double_t re, im;
   for (Int_t i=0; i<N; i++) {
      thefft->GetPointComplex(i, re, im);
      result->SetBinContent(i+1,TMath::Sqrt(re*re + im*im));
   }
   result->SetDirectory(0);

   TString rname = go4->SaveToMemory("FFT", result, kTRUE);
   std::cout<< "Saved result histogram to " << rname.Data() <<std::endl;
   if(draw){
      ViewPanelHandle vpanel = go4->StartViewPanel();
      go4->DrawItem(rname, vpanel);
   }
   return kTRUE;
}
TH1D* merge(TH1D* bg1, TH1D* bg2, TH1D* signal)
{
  TList *list = new TList;
  list->Add(bg1);
  list->Add(bg2);
  list->Add(signal);
  ostringstream newname; newname << signal->GetName() << "_merged";
  TH1D* newsignal = (TH1D*)signal->Clone(newname.str().c_str());
  newsignal->Reset();
  newsignal->Merge(list);
  return newsignal;
}
Example #6
0
void getseePhoMC(TH1D* hsee, TCut addCut){

  TFile *f1=new TFile(fPho.Data());
  TTree *photon1 = (TTree*)f1->Get("yongsunPhotonTree");
  photon1->AddFriend("yEvt=yongsunHiEvt"       ,fPho.Data());
  photon1->AddFriend("ySkim=yongsunSkimTree"   ,fPho.Data());
  photon1->AddFriend("yHlt=yongsunHltTree"     ,fPho.Data());
  photon1->AddFriend("tgj",                     fPho.Data());
 
  TH1D* htemp = (TH1D*)hsee->Clone("htemp");  htemp->Reset();
  photon1->Draw("sigmaIetaIeta>>htemp",Form("(%s) *ncoll",addCut.GetTitle()));
  hsee->Reset();
  hsee->Add(htemp);
}
Example #7
0
TH1D* mergeSys( TH1D* h1, TH1D* h2) {

  TH1D* hres = (TH1D*)h1->Clone(Form("%s_merged",h1->GetName()) );
  hres->Reset();
  Int_t nBins = h1->GetNbinsX();
  for ( Int_t j=1; j<=nBins ;j++)
    {
      float y1 =  h1->GetBinContent(j);
      float y2 =  h2->GetBinContent(j);
      hres->SetBinContent(j,  sqrt(  y1*y1 + y2*y2) );
      hres->SetBinError(j,  0.00001);
    }
  return hres;
}
Example #8
0
//_____________________________________________________________________________
TH1D *SetRMS(TH2D *h2, const TString s)
{
  TH1D *h = h2->ProjectionX(s.Data()); h->Reset();
  for (Int_t kx=1; kx<=h2->GetNbinsX(); kx++) {
    TH1D *hTmp = h2->ProjectionY(Form("hTmp_%d",kx), kx, kx);

    if (hTmp->Integral()<=0.)
      h->SetBinContent(kx, 0.);
    else
      h->SetBinContent(kx, hTmp->GetRMS());

      cout << h->GetBinContent(kx) << endl;
    delete hTmp; hTmp = 0;
  }

  return h;
}
Example #9
0
// Rebin first histogram to match the second
TH1D *tools::Rebin(const TH1D *h, const TH1D* href) {

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

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

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

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

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

  return hre;
} // Rebin
Example #10
0
TH1D *LPFilter( TH1D *hin , Double_t Cend  ) {

    if (Cend==-1.0) Cend = CPF ; 
    Double_t RCns = 50. * Cend * 1.e-3 ;
    Double_t At = hin->GetBinCenter(2) - hin->GetBinCenter(1) ;
    Double_t alfa = At/(RCns + At) ;
    TH1D *hout = (TH1D *) hin->Clone(); hout->Reset();
    hout->SetTitle( Form("C=%d pF",TMath::Nint(Cend)) ) ;
    hout->SetName( Form("C=%d pF",TMath::Nint(Cend)) ) ;

    hout->SetBinContent(1, hin->GetBinContent(1) );
    for ( Int_t i=2 ; i<=hin->GetNbinsX() ; i++ ) {
      Double_t val = (1.0-alfa)*hout->GetBinContent(i-1) + alfa*hin->GetBinContent(i) ; 
      hout->SetBinContent(i,val);
    }
    
    return hout ;
    
}
void make(TDirectory & out, TObject * o) {
  TDirectory * dir;
  TH1F * th1f;
  TH1D * th1d;
  TH2F * th2f;
  TH2D * th2d;
  out.cd();
  if((dir = dynamic_cast<TDirectory*>(o)) != 0) {
    TDirectory * outDir = out.mkdir(dir->GetName(), dir->GetTitle());
    TIter next(dir->GetListOfKeys());
    TKey *key;
    while( (key = dynamic_cast<TKey*>(next())) ) {
      string className(key->GetClassName());
      string name(key->GetName());
      TObject * obj = dir->Get(name.c_str());
      if(obj == 0) {
	cerr <<"error: key " << name << " not found in directory " << dir->GetName() << endl;
	exit(-1);
      }
      make(*outDir, obj);
    }
  } else if((th1f = dynamic_cast<TH1F*>(o)) != 0) {
    TH1F *h = (TH1F*) th1f->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th1d = dynamic_cast<TH1D*>(o)) != 0) {
    TH1D *h = (TH1D*) th1d->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2f = dynamic_cast<TH2F*>(o)) != 0) {
    TH2F *h = (TH2F*) th2f->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2d = dynamic_cast<TH2D*>(o)) != 0) {
    TH2D *h = (TH2D*) th2d->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  }
}
Example #12
0
void TrkClosure(
    int anaMode=0, // 0=pt, 1=eta, 2=dphi, 3=xi
    TString outdir="fig/trkcorrv14_closure"
)
{
    TH1::SetDefaultSumw2();
    gSystem->mkdir(outdir,kTRUE);

    bool doCorr=true;
    float maxEta=2.4;
    float ptmin=0.5,ptmax=200;
    TString mod="Forest2_MergedGeneral";
    TrackingCorrections trkCorr("Forest2STAv14",mod);
    trkCorr.AddSample("trkcorr/IterTrkCorrv14XSec/IterTrkCorrv14XSec_hy18dj80to100_akPu3Calo_100_-1_-1000_genJetMode0.root",80);
    trkCorr.Init();

//   TFile * inf = new TFile("output_hy18dj100_fv27_ntv1_corrv14_akPu3PF_100_-1_-1000_saveTrk1_jmin100_tmin1_genJetMode0.root");
    TFile * inf = new TFile("output_hy18dj80_fv27_ntv1_corrv14_akPu3PF_100_-1_-1000_saveTrk1_jmin100_tmin1_genJetMode0.root");
//    TFile * inf = new TFile("output_sigdj80_fv27_ntv1_akPu3PF_100_-1_-1000_saveTrk1_jmin100_tmin1_genJetMode0_corrhi.root");
//    TFile * inf = new TFile("output_sigdj80_fv27_ntv1_akPu3PF_100_-1_-1000_saveTrk1_jmin100_tmin1_genJetMode0_corrppv14jetfinexsec.root");
//     TFile * inf = new TFile("output_sigdj80_fv27_ntv1_corrv14_akPu3PF_100_-1_-1000_saveTrk1_jmin100_tmin1_genJetMode0.root");
    TTree * t = (TTree*)inf->Get("tgj");

    //////////////////////////////////////////
    // Analysis Setup
    //////////////////////////////////////////
    TString tag=Form("trkClos%d_0to12_jpt100_pthat80",anaMode);
    TCut sel = "cBin<12&&pt1>100";
//     TString tag=Form("trkClos%d_pp_jpt100_pthat80",anaMode);
//     TCut sel = "pt1>100";
    TCut genpSel = "";
    TCut trkSel = "";
//     TCut genpSel = "simAsso==1||simAsso==2";
//     TCut trkSel = "trkAsso==1||trkAsso==2";
    TString trkWt = "trkWt";

    float nEvt = t->GetEntries(sel);
    cout << sel << ": " << nEvt << " events" << endl;

    Compare cmp("cmp","");
    TH1D * hGenp, *hTrk, *hTrkCorr;
    float xmin=1, xmax=119.9;
    bool doLogx=true, doLogy=true;
    TString genVar, trkVar;
    TCut finalGenSel,finalTrkSel;
    if (anaMode==0) {
        TH1D * hPtBin = (TH1D*)trkCorr.ptBin_->Clone("hPtBin");
        hPtBin->Reset();
        hPtBin->SetAxisRange(0.5,179.9,"X");
        hGenp = (TH1D*)trkCorr.ptBin_->Clone("hGenp");
        hTrk = (TH1D*)trkCorr.ptBin_->Clone("hTrk");
        hTrkCorr = (TH1D*)trkCorr.ptBin_->Clone("hTrkCorr");
        cmp.Legend(0.24,0.23,0.7,0.4);
        cmp.leg->AddEntry(hTrk,Form("|#eta| < %.1f",maxEta),"");
        tag += Form("_eta%.0f",maxEta*10);
        genVar="simPt";
        trkVar="trkPt";
        finalGenSel = sel&&genpSel&&Form("abs(simEta)<%.2f",maxEta);
        finalTrkSel = sel&&trkSel&&Form("abs(trkEta)<%.2f",maxEta);
    } else if (anaMode==1) {
        TH1D * hEtaBin = (TH1D*)trkCorr.etaBin_->Clone("hEtaBin");
        hEtaBin->Reset();
        hGenp = (TH1D*)hEtaBin->Clone("hGenp");
        hTrk = (TH1D*)hEtaBin->Clone("hTrk");
        hTrkCorr = (TH1D*)hEtaBin->Clone("hTrkCorr");
        doLogx=false;
        doLogy=false;
        cmp.Legend(0.19,0.76,0.65,0.93);
        cmp.leg->AddEntry(hTrk,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax),"");
        tag += Form("_pt%.0f",ptmin);
        genVar="simEta";
        trkVar="trkEta";
        finalGenSel = sel&&genpSel&&Form("simPt>=%.2f&&simPt<%.2f",ptmin,ptmax);
        finalTrkSel = sel&&trkSel&&Form("trkPt>=%.2f&&trkPt<%.2f",ptmin,ptmax);
    } else if (anaMode==2) {
        TH1D * hBin = new TH1D("hBin",";#Delta#phi(trk,jet1)",25,0,3.14159);
        hGenp = (TH1D*)hBin->Clone("hGenp");
        hTrk = (TH1D*)hBin->Clone("hTrk");
        hTrkCorr = (TH1D*)hBin->Clone("hTrkCorr");
        doLogx=false;
        doLogy=true;
        cmp.Legend(0.19,0.76,0.65,0.93);
        cmp.leg->AddEntry(hTrk,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax),"");
        tag += Form("_pt%.0f",ptmin);
        genVar="acos(cos(simPhi-phi1))";
        trkVar="acos(cos(trkPhi-phi1))";
        finalGenSel = sel&&genpSel&&Form("simPt>=%.2f&&simPt<%.2f",ptmin,ptmax);
        finalTrkSel = sel&&trkSel&&Form("trkPt>=%.2f&&trkPt<%.2f",ptmin,ptmax);
    } else if (anaMode==3) {
        TH1D * hBin = new TH1D("hBin",";#xi=1/ln(z)",12,0,6);
        hGenp = (TH1D*)hBin->Clone("hGenp");
        hTrk = (TH1D*)hBin->Clone("hTrk");
        hTrkCorr = (TH1D*)hBin->Clone("hTrkCorr");
        doLogx=false;
        doLogy=false;
        cmp.Legend(0.19,0.76,0.65,0.93);
        cmp.leg->AddEntry(hTrk,Form("%.1f < p_{T} < %.1f GeV/c",ptmin,ptmax),"");
        tag += Form("_pt%.0f",ptmin);
        genVar="log(pt1/simPt)";
        trkVar="log(pt1/trkPt)";
        finalGenSel = sel&&genpSel&&Form("simPt>=%.2f&&simPt<%.2f&&(simAsso==1||simAsso==2)",ptmin,ptmax);
        finalTrkSel = sel&&trkSel&&Form("trkPt>=%.2f&&trkPt<%.2f&&(trkAsso==1||trkAsso==2)",ptmin,ptmax);
    }
    if (anaMode>0) {
        xmin= hGenp->GetBinLowEdge(1);
        xmax= hGenp->GetBinLowEdge(hGenp->GetNbinsX());
    }

    // Legend
    cmp.leg->AddEntry(hTrk,"Raw Trk","p");
    if (doCorr) cmp.leg->AddEntry(hTrkCorr,"Corr. Trk","p");
    cmp.leg->AddEntry(hGenp,"Gen. Particle","l");

    //////////////////////////////////////////
    // Run Analysis
    //////////////////////////////////////////
    cout << genVar << ": " << finalGenSel << endl;
    cout << trkVar << ": " << finalTrkSel << endl;
    if (doCorr) cout << "Corr: " << (finalTrkSel)*trkWt << endl;
    t->Draw(genVar+">>hGenp",finalGenSel,"goff");
    t->Draw(trkVar+">>hTrk",finalTrkSel,"goff");
    if (doCorr) t->Draw(trkVar+">>hTrkCorr",(finalTrkSel)*trkWt);

    hGenp->Scale(1./nEvt);
    hTrk->Scale(1./nEvt);
    hTrkCorr->Scale(1./nEvt);

    //////////////////////////////////////////
    // Draw
    //////////////////////////////////////////
    TCanvas * c2 = new TCanvas("c2","c2",800,400);
    c2->Divide(2,1);
    c2->cd(1);
    hGenp->SetLineColor(2);
    hTrk->SetMarkerStyle(kOpenCircle);
    normHist(hGenp,-1,true);
    normHist(hTrk,-1,true);
    normHist(hTrkCorr,-1,true);
    if (doLogx) gPad->SetLogx();
    if (doLogy) gPad->SetLogy();
    else hGenp->SetAxisRange(0,hGenp->GetMaximum()*1.4,"Y");
    if (anaMode==0) hGenp->SetAxisRange(xmin,xmax,"X");
    hGenp->Draw("hist");
    hTrk->Draw("sameE");
    if (doCorr) hTrkCorr->Draw("sameE");
    cmp.leg->Draw();

    c2->cd(2);
    TH1D * hTrkRat = (TH1D*)hTrk->Clone("hTrkRat");
    hTrkRat->Divide(hGenp);
    TH1D * hTrkCorrRat = (TH1D*)hTrkCorr->Clone("hTrkCorrRat");
    if (doCorr) hTrkCorrRat->Divide(hGenp);
    if (doLogx) gPad->SetLogx();
    if (anaMode==0) hTrkRat->SetAxisRange(xmin,xmax,"X");
    hTrkRat->SetAxisRange(0.,2,"Y");
    TLine * l1 = new TLine(xmin,1,xmax,1);
    l1->SetLineStyle(2);
    hTrkRat->Draw("E");
    l1->Draw();
    if (doCorr) hTrkCorrRat->Draw("sameE");

    c2->Print(Form("%s/%s.gif",outdir.Data(),tag.Data()));
    c2->Print(Form("%s/%s.pdf",outdir.Data(),tag.Data()));
    c2->Print(Form("%s/%s.C",outdir.Data(),tag.Data()));
}
void drawSys_merged() {
  //  TH1::SetDefaultSumw2();
    gStyle -> SetOptStat(0);
    const int kPPcentral = 1;
    const int kPPperipheral =2 ;
    const int kHIcentral =  3;
    const int kHIperipheral = 4;
    const int kPADATA = 5;
    const int kPAMC = 6;

  TH1D* dNdJetPt[7][5]; // [collision] [ ptbin]  [Before/After variation]
  TH1D* dNdJetPtSys[7][5]; // [collision] [ ptbin]  [Before/After variation]
  TH1D* dNdJetPtSysIaa[7][5]; // [collision] [ ptbin]  [Before/After variation]
  TH1D* meanJetPt[7];   // [collision] [Before/After variation]
  TH1D* meanJetPtSys[7];   // [collision] [Before/After variation]
  TH1D* meanRjg[7];
  TH1D* meanRjgSys[7];
  
  TH1D* bmeanJetPt[7];   // [collision] [Before/After variation]
  TH1D* bmeanJetPtSys[7];   // [collision] [Before/After variation]
  TH1D* bmeanRjg[7];
  TH1D* bmeanRjgSys[7];
  
  TFile * f = new TFile("../resultHistograms_ppSmeared10030.root");
  bmeanJetPt[1]  =(TH1D*)f->Get(Form("meanJetPt_pp"));
  bmeanRjg[1]  =(TH1D*)f->Get(Form("meanRjg_pp"));
  for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
    dNdJetPt[1][ipt] = (TH1D*)f->Get(Form("dNdJetPt_pp_ptBin%d", ipt ));
  }  

  f   = new TFile("../resultHistograms_ppSmeared13099.root");
  bmeanJetPt[2]  =(TH1D*)f->Get(Form("meanJetPt_pp"));
  bmeanRjg[2]  =(TH1D*)f->Get(Form("meanRjg_pp"));
  for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
    dNdJetPt[2][ipt] = (TH1D*)f->Get(Form("dNdJetPt_pp_ptBin%d", ipt ));
  }  
  
  // pbpb
  f =   new TFile("../resultHistograms_jetResCorrection.root");
  bmeanJetPt[3]  =(TH1D*)f->Get(Form("meanJetPt_pbpb_centralityBin1"));
  bmeanRjg[3]  =(TH1D*)f->Get(Form("meanRjg_pbpb_centralityBin1"));
  for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
    dNdJetPt[3][ipt] = (TH1D*)f->Get(Form("dNdJetPt_pbpb_centralityBin1_ptBin%d", ipt ));
  }
  bmeanJetPt[4]  =(TH1D*)f->Get(Form("meanJetPt_pbpb_centralityBin2"));
  bmeanRjg[4]  =(TH1D*)f->Get(Form("meanRjg_pbpb_centralityBin2"));
  for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
    dNdJetPt[4][ipt] = (TH1D*)f->Get(Form("dNdJetPt_pbpb_centralityBin2_ptBin%d", ipt ));
  }
  // pPb
  f =   new TFile("../resultHistograms_jetResCorrection.root");
  bmeanJetPt[5]  =(TH1D*)f->Get(Form("meanJetPt_ppb"));
  bmeanRjg[5]  =(TH1D*)f->Get(Form("meanRjg_ppb"));
  for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
    dNdJetPt[5][ipt] = (TH1D*)f->Get(Form("dNdJetPt_ppb_ptBin%d", ipt ));
  }
  
  f =   new TFile("../resultHistograms_MC_recoIsoPhoton.root");
  bmeanJetPt[6]  =(TH1D*)f->Get(Form("meanJetPt_ppb"));
  bmeanRjg[6]  =(TH1D*)f->Get(Form("meanRjg_ppb"));
  for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
    dNdJetPt[6][ipt] = (TH1D*)f->Get(Form("dNdJetPt_ppb_ptBin%d", ipt ));
  }  
  
  
  TFile* fSys = new TFile("../merged/relativeSys_merged.root");
  
  bmeanJetPtSys[1]  =(TH1D*)fSys->Get("meanJetPt_pp_uncertainty_merged");
  bmeanRjgSys[1]  =(TH1D*)fSys->Get(Form("meanRjg_pp_uncertainty_merged"));
  for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
    dNdJetPtSysIaa[1][ipt] = (TH1D*)fSys->Get(Form("dNdJetPt_IaaBin_pp_ptBin%d_uncertainty_merged",  ipt ));
  }
  bmeanJetPtSys[2] = (TH1D*)bmeanJetPtSys[1]->Clone(Form("%s_2",bmeanJetPtSys[1]->GetName()));
  bmeanRjgSys[2] = (TH1D*)bmeanRjgSys[1]->Clone(Form("%s_2",bmeanRjgSys[1]->GetName()));
  for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
    dNdJetPtSysIaa[2][ipt] = (TH1D*)dNdJetPtSysIaa[1][ipt]->Clone(Form("%s_2",dNdJetPtSysIaa[1][ipt]->GetName()));
  }
  bmeanJetPtSys[3]  =(TH1D*)fSys->Get("meanJetPt_pbpb_centralityBin1_uncertainty_merged");
  bmeanRjgSys[3]  =(TH1D*)fSys->Get(Form("meanRjg_pbpb_centralityBin1_uncertainty_merged"));
  for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
    dNdJetPtSysIaa[3][ipt] = (TH1D*)fSys->Get(Form("dNdJetPt_IaaBin_pbpb_centralityBin1_ptBin%d_uncertainty_merged",  ipt ));
  }
  bmeanJetPtSys[4]  =(TH1D*)fSys->Get("meanJetPt_pbpb_centralityBin2_uncertainty_merged");
  bmeanRjgSys[4]  =(TH1D*)fSys->Get(Form("meanRjg_pbpb_centralityBin2_uncertainty_merged"));
  for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
    dNdJetPtSysIaa[4][ipt] = (TH1D*)fSys->Get(Form("dNdJetPt_IaaBin_pbpb_centralityBin2_ptBin%d_uncertainty_merged",  ipt ));
  }
  bmeanJetPtSys[5]  =(TH1D*)fSys->Get("meanJetPt_ppb_uncertainty_merged");
  bmeanRjgSys[5]  =(TH1D*)fSys->Get(Form("meanRjg_ppb_uncertainty_merged"));
  for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
    dNdJetPtSysIaa[5][ipt] = (TH1D*)fSys->Get(Form("dNdJetPt_IaaBin_ppb_ptBin%d_uncertainty_merged",  ipt ));
  }


  
  // transplant the uncertainty  
  for ( int coll = 1 ; coll<=5 ; coll++) {
    for ( int ipt = 1 ; ipt <=nPtBin ; ipt++) {
      dNdJetPtSys[coll][ipt] = (TH1D*) dNdJetPt[coll][ipt]->Clone(Form("dNdJetPtSys_coll%d_ipt%d",coll,ipt));
      dNdJetPtSys[coll][ipt]->Reset();
      for ( int ibin = 1 ; ibin<= dNdJetPtSys[coll][ipt]->GetNbinsX() ; ibin++) {
	float xx = dNdJetPtSys[coll][ipt]->GetBinCenter(ibin);
	float yy = dNdJetPtSysIaa[coll][ipt]->GetBinContent ( dNdJetPtSysIaa[coll][ipt]->FindBin(xx) );
	if ( yy>1 ) yy = 1;
	dNdJetPtSys[coll][ipt]->SetBinContent(ibin,yy);

      }
    }
  }

  for(int icoll=1; icoll<=6; icoll++){
      meanJetPt[icoll] = new TH1D(Form("%s_corrected", bmeanJetPt[icoll]->GetName()), "", nPtBin, ptBinPaDraw);
      meanRjg[icoll] = new TH1D(Form("%s_corrected", bmeanRjg[icoll]->GetName()), "", nPtBin, ptBinPaDraw);
      if(icoll<6){
          meanJetPtSys[icoll] = new TH1D(Form("%s_corrected", bmeanJetPtSys[icoll]->GetName()), "", nPtBin, ptBinPaDraw);
          meanRjgSys[icoll] = new TH1D(Form("%s_corrected", bmeanRjgSys[icoll]->GetName()), "", nPtBin, ptBinPaDraw);
      }
  }

  for(int icoll=1; icoll<=6; icoll++){ 
      meanPtHist(bmeanJetPt[icoll], meanJetPt[icoll]);    
      meanPtHist(bmeanRjg[icoll],  meanRjg[icoll]); 
      if(icoll<6){
          meanPtHist(bmeanJetPtSys[icoll],meanJetPtSys[icoll]) ;  
          meanPtHist(bmeanRjgSys[icoll], meanRjgSys[icoll]); 
      }
  } 

  // RJG!!
  TCanvas* c2 = new TCanvas("c1","",1000,500);
  c2->Divide(2,1);
  c2->cd(2);
  handsomeTH1(meanRjg[1],1);
  //  drawSys(TH1 *h,TH1 *sys, Int_t theColor= kYellow, Int_t fillStyle = -1, Int_t lineStyle = -1)
  TH1D* tempR = new TH1D("tempR",";p_{T}^{#gamma};R_{j#gamma}",100,40,130);
  tempR->Reset();  
  handsomeTH1(tempR,0);
  tempR->SetAxisRange(0,1.2,"Y");
  tempR->Draw();
  drawSys(meanRjg[1], meanRjgSys[1], kGreen);
  drawSys(meanRjg[3], meanRjgSys[3]);
  meanRjg[1]->Draw("same");
  handsomeTH1(meanRjg[3],2 );
//  meanRjg[3]->SetMarkerStyle(24);
  meanRjg[3]->Draw("same");
  if ( 1==1 ){ 
    TLegend *ly = new  TLegend(0.4937249,0.262193,0.8493139,0.4740574,NULL,"brNDC");    
    easyLeg(ly,"2.76TeV");
    ly->AddEntry(meanRjg[3],"PbPb 0-30%","p");
    ly->AddEntry(meanRjg[1],"pp (smeared)","p");
    ly->Draw();
  }


  c2->cd(1);
  tempR->Draw();
  handsomeTH1(meanRjg[2],1 );
  drawSys(meanRjg[2], meanRjgSys[2], kGreen);
  drawSys(meanRjg[4], meanRjgSys[4]);
  meanRjg[2]->Draw("same");
  handsomeTH1(meanRjg[4],2 );
  meanRjg[4]->SetMarkerStyle(24);
  meanRjg[4]->Draw("same");
  if ( 1==1 ){ 
    TLegend *ly = new  TLegend(0.4937249,0.262193,0.8493139,0.4740574,NULL,"brNDC");    
    easyLeg(ly,"2.76TeV");
    ly->AddEntry(meanRjg[4],"PbPb 30-100%","p");
    ly->AddEntry(meanRjg[2],"pp (smeared)","p");
    ly->Draw();
  }
  c2->SaveAs("pT_depedence_rjg_pp_pbpb.pdf");

  
  TCanvas* c2pa = new TCanvas("c1pa","",500,500);
  handsomeTH1(meanRjg[1],1);
  //  drawSys(TH1 *h,TH1 *sys, Int_t theColor= kYellow, Int_t fillStyle = -1, Int_t lineStyle = -1)                         
  //  tempR->Draw();
  TH1D* tempJ = new TH1D("tempJ",";p_{T}^{#gamma}; <p_{T}^{Jet}>",100,40,130);
  tempJ->Reset();
  handsomeTH1(tempJ,0);
  tempJ->SetAxisRange(0,100,"Y");
  tempJ->Draw();
  drawSys(meanJetPt[5], meanJetPtSys[5], kYellow);
  handsomeTH1(meanJetPt[5],2);
  handsomeTH1(meanJetPt[6],1);
  meanJetPt[5]->Draw("same");
  meanJetPt[6]->Draw("same");
  if ( 1==1 ) {
    TLegend *ly = new TLegend(0.4484643,0.3088445,0.9140673,0.50102941,NULL,"brNDC");
    easyLeg(ly,"5.02TeV pPb");
    ly->AddEntry(meanJetPt[5],"DATA","p");
    ly->AddEntry(meanJetPt[6],"PYTHIA+HIJING","p");
    ly->Draw();
  }
  c2pa->SaveAs("pT_dependence_rjg_pA_figure1.pdf");

  TCanvas* c3pa = new TCanvas("c3pa","",500,500);
  tempR->Draw();
  drawSys(meanRjg[5], meanRjgSys[5], kYellow);
  handsomeTH1(meanRjg[5],2);
  handsomeTH1(meanRjg[6],1);
  meanRjg[5]->Draw("same");
  meanRjg[6]->Draw("same");
  if ( 1==1 ) {
    TLegend *ly = new TLegend(0.4484643,0.3088445,0.9140673,0.50102941,NULL,"brNDC");
    easyLeg(ly,"5.02TeV pPb");
    ly->AddEntry(meanRjg[5],"DATA","p");
    ly->AddEntry(meanRjg[6],"PYTHIA+HIJING","p");
    ly->Draw();
  }  
  c3pa->SaveAs("pT_dependence_jetPt_pA_figure2.pdf");

  TCanvas* c3 = new TCanvas("c3","",1000,500);
  c3->Divide(2,1);
  c3->cd(2);
  handsomeTH1(meanJetPt[1],1);
  //  drawSys(TH1 *h,TH1 *sys, Int_t theColor= kYellow, Int_t fillStyle = -1, Int_t lineStyle = -1)                                                       
   tempJ->Draw();
  drawSys(meanJetPt[1], meanJetPtSys[1], kGreen);
  drawSys(meanJetPt[3], meanJetPtSys[3]);
  meanJetPt[1]->Draw("same");
  handsomeTH1(meanJetPt[3],2 );
  meanJetPt[3]->Draw("same");
  if ( 1==1 ){
    TLegend *ly = new  TLegend(0.4937249,0.262193,0.8493139,0.4740574,NULL,"brNDC");
    easyLeg(ly,"2.76TeV");
    ly->AddEntry(meanJetPt[3],"PbPb 0-30%","p");
    ly->AddEntry(meanJetPt[1],"pp (smeared)","p");
    ly->Draw();
  }
  
  c3->cd(1);
  tempJ->Draw();
  handsomeTH1(meanJetPt[2],1 );
//  meanJetPt[2]->Draw();
  drawSys(meanJetPt[2], meanJetPtSys[2], kGreen);
  drawSys(meanJetPt[4], meanJetPtSys[4]);
  meanJetPt[2]->Draw("same");
  handsomeTH1(meanJetPt[4],2 );
  meanJetPt[4]->SetMarkerStyle(24);
  meanJetPt[4]->Draw("same");
  if ( 1==1 ){
    TLegend *ly = new  TLegend(0.4937249,0.262193,0.8493139,0.4740574,NULL,"brNDC");
    easyLeg(ly,"2.76TeV");
    ly->AddEntry(meanJetPt[4],"PbPb 30-100%","p");
    ly->AddEntry(meanJetPt[2],"pp (smeared)","p");
    ly->Draw();
  }
  c3->SaveAs("pT_dependence_jetPt_pp_pbpb.pdf");
  
  TH1D* hTempPt = new TH1D("hTemp",";p_{T}^{#gamma} (GeV);",200,10,300);
  TCanvas* c5 = new TCanvas("c5","",1200,700);
  makeMultiPanelCanvas(c5,nPtBin,2,0.0,0.0,0.2,0.15,0.02);
  for ( int ipt = 1 ; ipt<=nPtBin  ; ipt++) {
    c5->cd(ipt+nPtBin);
    // draw pp                                                                                                                                           
    hTempPt->SetXTitle("p_{T}^{Jet} (GeV)");
    hTempPt->SetYTitle("#frac{dN}{dp_{T}} #frac{1}{N}");
    hTempPt->SetAxisRange(10,150,"X");
    //        hTempPt->SetAxisRange(0,0.025,"Y");                                                                                                        
    hTempPt->SetAxisRange(0,0.07,"Y");
    handsomeTH1(hTempPt,0);
    hTempPt->DrawCopy();

    drawSys(dNdJetPt[1][ipt], dNdJetPtSys[1][ipt], kGreen);
    drawSys(dNdJetPt[3][ipt], dNdJetPtSys[3][ipt], kYellow);
    handsomeTH1(dNdJetPt[3][ipt],2);
    dNdJetPt[1][ipt]->Draw("same");
    dNdJetPt[3][ipt]->Draw("same");
    if ( ipt == 1 ) {
      TLegend *ly = new TLegend(0.4484643,0.6988445,0.9140673,0.9102941,NULL,"brNDC");
      easyLeg(ly,"2.76TeV");
      ly->AddEntry(meanJetPt[1],"PbPb 0-30%","p");
      ly->AddEntry(meanJetPt[3],"pp (smeared)","p");
      ly->Draw();
    }
 

    c5->cd(ipt);
    hTempPt->DrawCopy();

    drawSys(dNdJetPt[2][ipt], dNdJetPtSys[2][ipt], kGreen);
    drawSys(dNdJetPt[4][ipt], dNdJetPtSys[4][ipt], kYellow);
    handsomeTH1(dNdJetPt[4][ipt],2);
    dNdJetPt[4][ipt]->SetMarkerStyle(24);
    dNdJetPt[2][ipt]->Draw("same");
    dNdJetPt[4][ipt]->Draw("same");
    if ( ipt==1 ){
      TLegend *ly = new TLegend(0.4484643,0.5088445,0.9140673,0.75102941,NULL,"brNDC");
      easyLeg(ly,"2.76TeV");
      ly->AddEntry(meanJetPt[4],"PbPb 30-100%","p");
      ly->AddEntry(meanJetPt[2],"pp (smeared)","p");
      ly->Draw();
    }

    double dx1=0.15;
    if ( ipt == nPtBin )
      drawText(Form("p_{T}^{#gamma} > %dGeV, ", (int)ptBin[ipt-1]), 0.12+dx1+0.25,0.85,1,15);//yeonju 130823                                           
    else
      drawText(Form("%dGeV < p_{T}^{#gamma} < %dGeV, ", (int)ptBin[ipt-1], (int)ptBin[ipt]), 0.12+dx1,0.85,1,15);//yeonju 130823                       

    
  }
  c5->SaveAs("pT_dependence_jetPt_pp_pbpb_distribution.pdf");

  TCanvas* c5pa = new TCanvas("c5pa","",1200,350);
  makeMultiPanelCanvas(c5pa,nPtBin,1,0.0,0.0,0.2,0.15,0.02);
  for ( int ipt = 1 ; ipt<=nPtBin  ; ipt++) {
    c5pa->cd(ipt);
    // draw pp                                                                                                                                           
    hTempPt->SetXTitle("p_{T}^{Jet} (GeV)");
    hTempPt->SetYTitle("#frac{dN}{dp_{T}} #frac{1}{N}");
    hTempPt->SetAxisRange(10,150,"X");
    //        hTempPt->SetAxisRange(0,0.025,"Y");                                                                                                        
    hTempPt->SetAxisRange(0,0.07,"Y");
    handsomeTH1(hTempPt,0);
    hTempPt->DrawCopy();

    drawSys(dNdJetPt[5][ipt], dNdJetPtSys[5][ipt], kYellow);
    handsomeTH1(dNdJetPt[5][ipt],2);
    dNdJetPt[6][ipt]->Draw("same");
    dNdJetPt[5][ipt]->Draw("same");
    if ( ipt == 1 ) {
      TLegend *ly = new TLegend(0.4855983,0.5529059,0.9512013,0.7645899,NULL,"brNDC");
      easyLeg(ly,"5.02TeV pPb");
      ly->AddEntry(meanJetPt[5],"Data","p");
      ly->AddEntry(meanJetPt[6],"PYTHIA+HIJING","p");
      ly->Draw();
    }
    double dx1=0.15;
    if ( ipt == nPtBin )
      drawText(Form("p_{T}^{#gamma} > %dGeV, ", (int)ptBin[ipt-1]), 0.12+dx1+0.25,0.85,1,15);//yeonju 130823                                           
    else
      drawText(Form("%dGeV < p_{T}^{#gamma} < %dGeV, ", (int)ptBin[ipt-1], (int)ptBin[ipt]), 0.12+dx1,0.85,1,15);//yeonju 130823                       
    
    
  }
  c5pa->SaveAs("pT_dependence_jetPt_pA_distribution.pdf");
  
  
  
}
Example #14
0
///////////////////////
// Begin Main function:
void mkROOTsmEl() {


    //////////////////////////////////////
    // Set MC normalization scale factors:
    const double intLUMI = 19166;

// WA+jets norm - data driven : 1.07391 +- 0.137
    const double WAJets_scale  = 1.07391 * 9.37246 * intLUMI/1049473;
    const double WAJetsPT100_scale   = 1.07391 * 0.423028445 *intLUMI/369309; // V
    const double ZAJets_scale  = 0.63196 * intLUMI/979207;
    const double ZZ_scale      = 8.059 * intLUMI/9702850;

    const double ttbarA_scale  = 1.44 * intLUMI/604113;
    const double SToppS_scale  = 1.75776  * intLUMI/139974;
    const double SToppT_scale  = 30.0042  * intLUMI/1935066;
    const double SToppTW_scale = 11.1773  * intLUMI/493458;
    const double STopS_scale   = 3.89394  * intLUMI/259960;
    const double STopT_scale   = 55.531  * intLUMI/3758221;
    const double STopTW_scale  = 11.1773  * intLUMI/497657;

    const double WWA_scale     = 2.1*0.01362 * intLUMI/198777;
    const double WWA2_scale    = 2.1*0.01409 * intLUMI/199183;
    const double WZA_scale     = 2.1*0.00578008 * intLUMI/497450;


    ///////////////////////////////////////////////////////////////////////////////////
    // Specify what kinematical distribution to observe, as well as histogram settings:
    plotVar_t pv = {"masslvjja",190,1060,10,3,"M_{l#nujj#gamma} (GeV/c^2)"};
    if ( !strlen(pv.plotvar) ) break;
    std::cout << TString(pv.plotvar) << "\t"<<pv.MINRange<<"\t" << pv.MAXRange<<"\t" << pv.NBINS<<"\tTHE CUT " << endl;


    ////////////////////////////////
    // Specify event selection cuts:
    TCut the_cut("effwt*puwt*(iPhoton12>-1 && i12Jet1>-1 && i12Jet2>-1 && abs(W_electron_eta)<2.5 && W_electron_pt>30 && event_met_pfmet>35. && W_mt>30 && abs(Photon_Eta[iPhoton12])<1.4442 && Photon_Et[iPhoton12]>30.&& Photon_dRlep[iPhoton12] > 0.5 && JetPFCor_dRpho12[i12Jet1]>0.5 && JetPFCor_dRpho12[i12Jet2]>0.5 && abs(JetPFCor_dphiMET[i12Jet1])>0.4 && abs(JetPFCor_dphiMET[i12Jet2])>0.4 && JetPFCor_bDiscriminatorCSV[i12Jet1]<0.679 && JetPFCor_bDiscriminatorCSV[i12Jet2]<0.679 && abs(JetPFCor_Eta[i12Jet1]-JetPFCor_Eta[i12Jet2])<1.4 && c2jMass12>70. && c2jMass12<100. && abs(91.1876-massla)>10. &&((i12Jet3>-1)? JetPFCor_dRpho12[i12Jet3]>0.5: 1 )&&((i12Jet4>-1)? JetPFCor_dRpho12[i12Jet4]>0.5: 1 ))");
//mva2jWWAelA1>0.2
    TCut the_cutPlj("effwt*puwt*(iPhoton12plj>-1 && i12Jet1plj>-1 && i12Jet2plj>-1 && abs(W_electron_eta)<2.5 && W_electron_pt>30 && event_met_pfmet>35. && W_mt>30 &&  abs(Photon_Eta[iPhoton12plj])<1.44421 && Photon_Et[iPhoton12plj]>30. && Photon_dRlep[iPhoton12plj] > 0.5 && JetPFCor_dRpho12plj[i12Jet1plj]>0.5 && JetPFCor_dRpho12plj[i12Jet2plj]>0.5 &&  abs(JetPFCor_dphiMET[i12Jet1plj])>0.4 && abs(JetPFCor_dphiMET[i12Jet2plj])>0.4 && JetPFCor_bDiscriminatorCSV[i12Jet1plj]<0.679 &&  JetPFCor_bDiscriminatorCSV[i12Jet2plj]<0.679 && abs(JetPFCor_Eta[i12Jet1plj]-JetPFCor_Eta[i12Jet2plj])<1.4 && c2jMass12plj<100. && c2jMass12plj>70. && abs(91.1876-massla)>10. &&((i12Jet3plj>-1)? JetPFCor_dRpho12plj[i12Jet3plj]>0.5: 1 )&&((i12Jet4plj>-1)? JetPFCor_dRpho12plj[i12Jet4plj]>0.5: 1 ))");

    TCut the_cutQCD(TString(the_cut)+TString("*(W_electron_pfIsoEA>0.3)"));

// ! no need for extra PUwt stat err. sumw2 is enough
    TCut WA23Jcut(TString(the_cut)+TString("*((W_Photon_pt_gen>115)? 0. : 1.) "));
    TCut WA23JPT100cut(TString(the_cut)+TString("*((W_Photon_pt_gen>115)? 1. : 0.) "));


    //////////////////////////////////////////////////////////////////
    // Specify Fake-Photon contribution function (fake rate function):
    TCut fkPhoton_cut(TString(the_cutPlj)+TString("*(0.01373795 + 308.9628/(Photon_Et[(iPhoton12plj>-1)? iPhoton12plj : 0]^2.29711))"));
    TCut fkPhoton_cutUp(TString(fkPhoton_cut)+TString("*(1+((Photon_Et[(iPhoton12plj>-1)? iPhoton12plj : 0]<50.)? 0.12 : ((Photon_Et[(iPhoton12plj>-1)? iPhoton12plj : 0]<75.)? 0.14 : ((Photon_Et[(iPhoton12plj>-1)? iPhoton12plj : 0]<90.)? 0.23 : ((Photon_Et[(iPhoton12plj>-1)? iPhoton12plj : 0]<135.)? 0.22 : 0.39)))))"));
    TCut fkPhoton_cutDown(TString(fkPhoton_cut)+TString("*(1-((Photon_Et[(iPhoton12plj>-1)? iPhoton12plj : 0]<50.)? 0.12 : ((Photon_Et[(iPhoton12plj>-1)? iPhoton12plj : 0]<75.)? 0.14 : ((Photon_Et[(iPhoton12plj>-1)? iPhoton12plj : 0]<90.)? 0.23 : ((Photon_Et[(iPhoton12plj>-1)? iPhoton12plj : 0]<135.)? 0.22 : 0.39)))))"));


    ///////////////////////////
    // Create output ROOT file:
    TFile f("el_WWA_WZA_Mlvjja.root", "RECREATE");


    //////////////////////////////////////////////////
    // Create file pointers for each sample ROOT file:
    TFile *fin2,*fqcd,*wwaShape_file,*wwa2Shape_file,*wzaShape_file,*zzShape_file,*wajetsShape_file,*wajetsPT100Shape_file,*ttbara_file,*zajets_file,*stops_file,*stopt_file,*stoptW_file,*stopps_file,*stoppt_file,*stopptW_file;


    //////////////////////////////
    // Open each sample ROOT file:
    fin2 = new TFile("InData_New/RD_WenuJets_DataAllSingleElectronTrigger_GoldenJSON_19p2invfb.root");
    fqcd = new TFile("InData_New/RDQCD_WenuJets_DataAll_GoldenJSON_19p2invfb.root");
    wwaShape_file = new TFile("InData_New/RD_el_qq_wpwma_wp_qq_wm_lvl.root");
    wwa2Shape_file = new TFile("InData_New/RD_el_qq_wpwma_wp_lvl_wm_qq.root");
    wzaShape_file = new TFile("InData_New/RD_el_WZA_CMSSW532.root");
    zzShape_file = new TFile("InData_New/RD_el_ZZ_CMSSW532.root");
    wajetsShape_file = new TFile("InData_New/RD_el_WAp23Jets.root");
    wajetsPT100Shape_file = new TFile("InData_New/RD_el_WAp23Jets_PT100_CMSSW532.root");
    ttbara_file = new TFile("InData_New/RD_el_TTbarAJets.root");
    zajets_file = new TFile("InData_New/RD_el_ZAp23J_CMSSW532.root");
    stops_file = new TFile("InData_New/RD_el_STopS_T_CMSSW532.root");
    stopt_file = new TFile("InData_New/RD_el_STopT_T_CMSSW532.root");
    stoptW_file = new TFile("InData_New/RD_el_STopTW_T_CMSSW532.root");
    stopps_file =  new TFile("InData_New/RD_el_STopS_Tbar_CMSSW532.root");
    stoppt_file =  new TFile("InData_New/RD_el_STopT_Tbar_CMSSW532.root");
    stopptW_file =  new TFile("InData_New/RD_el_STopTW_Tbar_CMSSW532.root");


    ///////////////////////////////////////////////////
    // Retrieve ROOT tree with kinematic distributions:
    TTree* treedata = (TTree*) fin2->Get("WJet");
    TTree* treeqcd = (TTree*) fqcd->Get("WJet");
    TTree* treewwa    = (TTree*)    wwaShape_file->Get("WJet");
    TTree* treewwa2    = (TTree*)    wwa2Shape_file->Get("WJet");
    TTree* treewza    = (TTree*)    wzaShape_file->Get("WJet");
    TTree* treezz    = (TTree*)    zzShape_file->Get("WJet");
    TTree* treewaj    = (TTree*) wajetsShape_file->Get("WJet");
    TTree* treewajPT100    = (TTree*) wajetsPT100Shape_file->Get("WJet");
    TTree* treettba   = (TTree*)      ttbara_file->Get("WJet");
    TTree* treezaj    = (TTree*)      zajets_file->Get("WJet");
    TTree* treests   = (TTree*)      stops_file->Get("WJet");
    TTree* treestt   = (TTree*)      stopt_file->Get("WJet");
    TTree* treestw   = (TTree*)     stoptW_file->Get("WJet");
    TTree* tree64 = (TTree*) stopps_file->Get("WJet");
    TTree* tree65 = (TTree*) stoppt_file->Get("WJet");
    TTree* tree66 = (TTree*) stopptW_file->Get("WJet");


    ////////////////////////////////////////////////////////////
    // Create kinematic-distribution histograms for each sample:
    TH1* data_obs  = new TH1D("data_obs",  "data_obs",  pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1fkdata  = new TH1D("th1fkdata",  "th1fkdata",  pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1fkdata_fkphotuncUp  = new TH1D("th1fkdata_fkphotuncUp",  "th1fkdata_fkphotuncUp",  pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1fkdata_fkphotuncDown  = new TH1D("th1fkdata_fkphotuncDown",  "th1fkdata_fkphotuncDown",  pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1qcd  = new TH1D("th1qcd",  "th1qcd",  pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1wwa = new TH1D("th1wwa", "th1wwa", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1wwa2 = new TH1D("th1wwa2", "th1wwa2", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1wza = new TH1D("th1wza", "th1wza", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1zz = new TH1D("th1zz", "th1zz", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1wajets  = new TH1D("th1wajets",  "th1wajets",  pv.NBINS ,pv.MINRange,pv.MAXRange);
    TH1* th1wajetsPT100  = new TH1D("th1wajetsPT100",  "th1wajetsPT100",  pv.NBINS ,pv.MINRange,pv.MAXRange);
    TH1* th1Top = new TH1D("th1Top", "th1Top", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1zajets = new TH1D("th1zajets", "th1zajets", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1stops = new TH1D("th1stops", "th1stops", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1stopt = new TH1D("th1stopt", "th1stopt", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1stoptw = new TH1D("th1stoptw", "th1stoptw", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1stopps = new TH1D("th1stopps", "th1stopps", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1stoppt = new TH1D("th1stoppt", "th1stoppt", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1stopptw = new TH1D("th1stopptw", "th1stopptw", pv.NBINS, pv.MINRange, pv.MAXRange);
    TH1* th1stop = new TH1D("th1stop", "th1stop", pv.NBINS, pv.MINRange, pv.MAXRange);


    /////////////////////////////////////////////////////////////////////////
    // Specify histograms to store Sum of Squares of Weights for each sample:
    data_obs->Sumw2();
    th1fkdata->Sumw2();
    th1fkdata_fkphotuncUp->Sumw2();
    th1fkdata_fkphotuncDown->Sumw2();
    th1qcd->Sumw2();
    th1wwa->Sumw2();
    th1wwa2->Sumw2();
    th1wza->Sumw2();
    th1zz->Sumw2();
    th1wajets->Sumw2();
    th1wajetsPT100->Sumw2();
    th1zajets->Sumw2();
    th1Top->Sumw2();
    th1stops->Sumw2();
    th1stopt->Sumw2();
    th1stoptw->Sumw2();
    th1stopps->Sumw2();
    th1stoppt->Sumw2();
    th1stopptw->Sumw2();


    ///////////////////////////////////////////////////////////////////////////////////
    // Fill kinematical distribution for each sample according to event selection cuts:
    std::cout<<"\nFill Data Histogram..."<<std::endl;
    treedata->Draw(TString(pv.plotvar)+TString(">>data_obs"), the_cut, "goff");
    data_obs->AddBinContent(pv.NBINS,data_obs->GetBinContent(pv.NBINS+1));
    data_obs->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill Fake Photon Histogram..."<<std::endl;
    treedata->Draw(TString(pv.plotvar)+TString(">>th1fkdata"), fkPhoton_cut, "goff");
    th1fkdata->AddBinContent(pv.NBINS,th1fkdata->GetBinContent(pv.NBINS+1));
    th1fkdata->SetBinContent(pv.NBINS+1,0.);

    treedata->Draw(TString(pv.plotvar)+TString(">>th1fkdata_fkphotuncUp"), fkPhoton_cutUp, "goff");
    th1fkdata_fkphotuncUp->AddBinContent(pv.NBINS,th1fkdata_fkphotuncUp->GetBinContent(pv.NBINS+1));
    th1fkdata_fkphotuncUp->SetBinContent(pv.NBINS+1,0.);

    treedata->Draw(TString(pv.plotvar)+TString(">>th1fkdata_fkphotuncDown"), fkPhoton_cutDown, "goff");
    th1fkdata_fkphotuncDown->AddBinContent(pv.NBINS,th1fkdata_fkphotuncDown->GetBinContent(pv.NBINS+1));
    th1fkdata_fkphotuncDown->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill QCD Histogram..."<<std::endl;
    treeqcd->Draw(TString(pv.plotvar)+TString(">>th1qcd"), the_cutQCD, "goff");
    th1qcd->AddBinContent(pv.NBINS,th1qcd->GetBinContent(pv.NBINS+1));
    th1qcd->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill SM WWA Histogram..."<<std::endl;
    treewwa->Draw(TString(pv.plotvar)+TString(">>th1wwa"), the_cut, "goff");
    th1wwa->AddBinContent(pv.NBINS,th1wwa->GetBinContent(pv.NBINS+1));
    th1wwa->SetBinContent(pv.NBINS+1,0.);
    treewwa2->Draw(TString(pv.plotvar)+TString(">>th1wwa2"), the_cut, "goff");
    th1wwa2->AddBinContent(pv.NBINS,th1wwa2->GetBinContent(pv.NBINS+1));
    th1wwa2->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill WZA Histogram..."<<std::endl;
    treewza->Draw(TString(pv.plotvar)+TString(">>th1wza"), the_cut, "goff");
    th1wza->AddBinContent(pv.NBINS,th1wza->GetBinContent(pv.NBINS+1));
    th1wza->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill ZZ Histogram..."<<std::endl;
    treezz->Draw(TString(pv.plotvar)+TString(">>th1zz"), the_cut, "goff");
    th1zz->AddBinContent(pv.NBINS,th1zz->GetBinContent(pv.NBINS+1));
    th1zz->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill WA+Jets Histogram..."<<std::endl;
    treewaj->Draw(TString(pv.plotvar)+TString(">>th1wajets"), WA23Jcut, "goff");
    th1wajets->AddBinContent(pv.NBINS,th1wajets->GetBinContent(pv.NBINS+1));
    th1wajets->SetBinContent(pv.NBINS+1,0.);

    treewajPT100->Draw(TString(pv.plotvar)+TString(">>th1wajetsPT100"), WA23JPT100cut, "goff");
    th1wajetsPT100->AddBinContent(pv.NBINS,th1wajetsPT100->GetBinContent(pv.NBINS+1));
    th1wajetsPT100->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill ttbar+A Histogram..."<<std::endl;
    treettba->Draw(TString(pv.plotvar)+TString(">>th1Top"), the_cut, "goff");
    th1Top->AddBinContent(pv.NBINS,th1Top->GetBinContent(pv.NBINS+1));
    th1Top->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill ZA+Jets Histogram..."<<std::endl;
    treezaj->Draw(TString(pv.plotvar)+TString(">>th1zajets"), the_cut, "goff");
    th1zajets->AddBinContent(pv.NBINS,th1zajets->GetBinContent(pv.NBINS+1));
    th1zajets->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill STopS Histogram..."<<std::endl;
    treests->Draw(TString(pv.plotvar)+TString(">>th1stops"), the_cut, "goff");
    th1stops->AddBinContent(pv.NBINS,th1stops->GetBinContent(pv.NBINS+1));
    th1stops->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill STopT Histogram..."<<std::endl;
    treestt->Draw(TString(pv.plotvar)+TString(">>th1stopt"), the_cut, "goff");
    th1stopt->AddBinContent(pv.NBINS,th1stopt->GetBinContent(pv.NBINS+1));
    th1stopt->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill STopTW Histogram..."<<std::endl;
    treestw->Draw(TString(pv.plotvar)+TString(">>th1stoptw"), the_cut, "goff");
    th1stoptw->AddBinContent(pv.NBINS,th1stoptw->GetBinContent(pv.NBINS+1));
    th1stoptw->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill STopPS Histogram..."<<std::endl;
    tree64->Draw(TString(pv.plotvar)+TString(">>th1stopps"), the_cut, "goff");
    th1stopps->AddBinContent(pv.NBINS,th1stopps->GetBinContent(pv.NBINS+1));
    th1stopps->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill STopPT Histogram..."<<std::endl;
    tree65->Draw(TString(pv.plotvar)+TString(">>th1stoppt"), the_cut, "goff");
    th1stoppt->AddBinContent(pv.NBINS,th1stoppt->GetBinContent(pv.NBINS+1));
    th1stoppt->SetBinContent(pv.NBINS+1,0.);

    std::cout<<"Fill STopPTW Histogram..."<<std::endl;
    tree66->Draw(TString(pv.plotvar)+TString(">>th1stopptw"), the_cut, "goff");
    th1stopptw->AddBinContent(pv.NBINS,th1stopptw->GetBinContent(pv.NBINS+1));
    th1stopptw->SetBinContent(pv.NBINS+1,0.);


    /////////////////////////
    // Normalize each sample:
    std::cout<<"\nScale Histograms..."<<std::endl;
    th1Top->Scale(ttbarA_scale);
    th1stops->Scale(STopS_scale);
    th1stopt->Scale(STopT_scale);
    th1stoptw->Scale(STopTW_scale);
    th1stopps->Scale(SToppS_scale);
    th1stoppt->Scale(SToppT_scale);
    th1stopptw->Scale(SToppTW_scale);
    th1wajets->Scale(WAJets_scale);
    th1wajetsPT100->Scale(WAJetsPT100_scale);
    th1wwa->Scale(WWA_scale);
    th1wwa2->Scale(WWA2_scale);
    th1wza->Scale(WZA_scale);
    th1zz->Scale(ZZ_scale);
    th1zajets->Scale(ZAJets_scale);


    ///////////////////////////
    // Combine certain samples:
    th1stop->Add(th1stopptw,1);
    th1stop->Add(th1stoppt,1);
    th1stop->Add(th1stopps,1);
    th1stop->Add(th1stoptw,1);
    th1stop->Add(th1stopt,1);
    th1stop->Add(th1stops,1);

    th1wwa->Add(th1wwa2,1);
    th1wajets->Add(th1wajetsPT100,1);


    ///////////////////////////////////////////////////////////////
    // Combine all background + SM WWA samples for QCD Estimations:
    TH1D *background = (TH1D*)th1wajets->Clone("background");
    background->Reset();
    background->Add(th1fkdata,1);
    background->Add(th1Top,1);
    background->Add(th1stop,1);
    background->Add(th1wajets,1);
    background->Add(th1zajets,1);
    background->Add(th1zz,1);
    background->Add(th1wwa,1);
    background->Add(th1wza,1);

    float qcd_scale=0;
    if(th1qcd->Integral()>0 ) {
        qcd_scale = 0.0637*background->Integral()/th1qcd->Integral();
        th1qcd->Scale(qcd_scale);
        background->Add(th1qcd,1);
    }

    /*
    std::cout << "\nSample Contribution:" << std::endl;
    std::cout << "WWA: " << th1wwa->Integral() << std::endl;
    std::cout << "Top: " << th1Top->Integral() << std::endl;
    std::cout << "Single Top: " << th1stop->Integral() << std::endl;
    std::cout << "WA+Jets: " << th1wajets->Integral() << std::endl;
    std::cout << "ZA+Jets: " << th1zajets->Integral() << std::endl;
    std::cout << "WZA: " << th1wza->Integral() << std::endl;
    std::cout << "ZZ: " << th1zz->Integral() << std::endl;
    std::cout << "Fake Photons: " << th1fkdata->Integral() << std::endl;
    std::cout << "Data: " << data_obs->Integral() << std::endl;
    std::cout << "QCD: " << th1qcd->Integral() << std::endl;

    std::cout << "\nSample Contribution:" << std::endl;
    std::cout << "Top: " << th1Top->GetBinError(1) << std::endl;
    std::cout << "WA+Jets: " << th1wajets->GetBinError(1) << std::endl;
    std::cout << "ZA+Jets: " << th1zajets->GetBinError(1) << std::endl;
    std::cout << "WZA: " << th1wza->GetBinError(1) << std::endl;
    std::cout << "ZZ: " << th1zz->GetBinError(1) << std::endl;
    std::cout << "Fake Photons: " << th1fkdata->GetBinError(1) << std::endl;
    std::cout << "Data: " << data_obs->GetBinError(1) << std::endl;
    */


    ///////////////////////////////////////////////////////////////
    // Combine SM WVA samples for Signal:
    TH1D *signal_SM = (TH1D*)th1wwa->Clone("signal_SM");
    signal_SM->Add(th1wza,1);


    ////////////////////////
    // Set histogram labels:
    const double BINWIDTH = ((pv.MAXRange-pv.MINRange)/pv.NBINS);
    char tmpc[100];
    sprintf(tmpc,"Events / %.1f GeV",BINWIDTH);
    if (pv.slog==1)    sprintf(tmpc,"Events / %.1f",BINWIDTH);
    if (pv.slog==2)    sprintf(tmpc,"Events / %.2f",BINWIDTH);
    if (pv.slog==3)    sprintf(tmpc,"Events / %.0f GeV",BINWIDTH);
    if (pv.slog==6)    sprintf(tmpc,"Events / %.2f rad",BINWIDTH);

    data_obs->SetYTitle(tmpc);
    data_obs->GetXaxis()->SetTitle(pv.xlabel);
    data_obs->GetYaxis()->CenterTitle(true);


    //////////////////////////////////////////////////////////
    // Save Observed Data, Background (+ SM WWA), Background +
    // Uncertainty, Background - Uncertainty, Anomalous Signal
    // histograms to output ROOT file:
    std::cout<<"Save Histograms..."<<std::endl;
    f.cd();
    data_obs->Write();
    th1fkdata->Write();
    th1fkdata_fkphotuncUp->Write();
    th1fkdata_fkphotuncDown->Write();
    th1Top->Write();
    th1stop->Write();
    th1wajets->Write();
    th1zz->Write();
    th1zajets->Write();
    th1qcd->Write();
    th1wwa->Write();
    th1wza->Write();
    signal_SM->Write();

}// End Main function
Example #15
0
void toyMC_bkgTemp(int runIeta=-1, int runIpt=-1) {

    cout << "ROOT version = " << gROOT->GetVersion() << endl;
    //   gSystem->mkdir("toysPlot");
    char tmp[1000];


    TH1D* htoyResult_pull[nEtaBin][nPtBin];
    TH1D* htoyResult_bias[nEtaBin][nPtBin];

    TFile *fsumFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/proj_comb_comb3Iso_template.root");
    TFile* finFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/template_comb3Iso_template.root");
    TFile* zeeFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/anadipho_Zee_Vg_3pb.root");
    TH1D* hTemplate = (TH1D*)finFile->FindObjectAny("h_EB_comb3Iso_EGdata_pt21");
    hTemplate->Reset();


    char* dec[2] = {"EB","EE"};
    for(int ieta=0; ieta<nEtaBin; ieta++) {
        for(int ipt=0; ipt < nPtBin; ipt++) {

            htoyResult_pull[ieta][ipt] = new TH1D(Form("hpull_%s_pt_%d",
                                                  dec[ieta],
                                                  (int)fBinsPt[ipt]),
                                                  "",50,-5.0,5.0);


            htoyResult_bias[ieta][ipt] = new TH1D(Form("hbias_%s_pt_%d",
                                                  dec[ieta],
                                                  (int)fBinsPt[ipt]),
                                                  "",100,-0.5,0.5);


        }
    }



    TH1D* hfit_sig;
    TH1D* hfit_bkg;

    TH1D* hTemplate_S[nEtaBin][nPtBin];
    TH1D* hTemplate_B[nEtaBin][nPtBin];
    TH1D* hZeeTemplate_S[nEtaBin];
    TH1D* hdata_data[nEtaBin][nPtBin];
    TH1D* htemp;
    TH1D* hTemplate_ShiftB[nEtaBin][nPtBin];

    for(int ieta=0; ieta< nEtaBin; ieta++) {

        // getting a different signal template
        if(ieta==0) {
            sprintf(tmp,"h_%s_combIso",dec[ieta]);
            cout << "looking for histogram " << tmp << " in file " <<
                 zeeFile->GetName() << endl;
            hZeeTemplate_S[ieta]= (TH1D*)zeeFile->FindObjectAny(tmp);
            hZeeTemplate_S[ieta]->Rebin(REBINNINGS_TEMP);
        }
        else {
            sprintf(tmp,"h_%s_comb3Iso_sig_sum_SIG",dec[ieta]); //no pt dep.
            cout << "looking for histogram " << tmp << " in file " <<
                 fsumFile->GetName() << endl;
            hZeeTemplate_S[ieta]= (TH1D*)fsumFile->FindObjectAny(tmp);
            hZeeTemplate_S[ieta]->Rebin(REBINNINGS_TEMP);
        }

        for(int ipt=0; ipt < nPtBin; ipt++) {

            if(runIeta>=0 && ieta!=runIeta)continue;
            if(runIpt>=0 && ipt!=runIpt)continue;

            // getting histograms from data root file
            sprintf(tmp,"h_%s_comb3Iso_EGdata_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            cout << "looking for histogram " << tmp << " in file " <<
                 finFile->GetName() << endl;
            hdata_data[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
            hdata_data[ieta][ipt]->Rebin(REBINNINGS_DATA);

            // filling unbinned data
            htemp = (TH1D*)hdata_data[ieta][ipt]->Clone("htemp");
            htemp->Reset();


            sprintf(tmp,"h_%s_comb3Iso_sig_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            cout << "looking for histogram " << tmp << " in file " <<
                 finFile->GetName() << endl;
            hTemplate_S[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
            hTemplate_S[ieta][ipt]->Rebin(REBINNINGS_TEMP);

            if(ieta==0 && fBinsPt[ipt]>=50)
                sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],50);
            else if(ieta==0 )
                sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            else if(ieta==1 && fBinsPt[ipt]>=60)
                sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],60);
            else if(ieta==1)
                sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            cout << "looking for histogram " << tmp << " in file " <<
                 finFile->GetName() << endl;
            hTemplate_B[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
            hTemplate_B[ieta][ipt]->Rebin(REBINNINGS_TEMP);

            // getting a different background template
            if(ieta==0 && fBinsPt[ipt]>=50)
                sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],50);
            else if(ieta==0 )
                sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            else if(ieta==1 && fBinsPt[ipt]>=60)
                sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],60);
            else if(ieta==1)
                sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            cout << "looking for histogram " << tmp << " in file " <<
                 finFile->GetName() << endl;
            hTemplate_ShiftB[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);

            hTemplate_ShiftB[ieta][ipt]->Rebin(REBINNINGS_TEMP);



            const int NRETURN = 3*NPAR;
            Double_t myFitPar[NRETURN]= {0};
            Double_t* FuncFitResult;
            FuncFitResult = Ifit("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/EGdata_comb3Iso_et.dat",
                                 hZeeTemplate_S[ieta],hTemplate_ShiftB[ieta][ipt],
                                 hdata_data[ieta][ipt], myFitPar,
                                 (int)fBinsPt[ipt], dec[ieta],2);

            Double_t nsig_input    = FuncFitResult[0];
            Double_t nsigerr_input = FuncFitResult[1];
            Double_t nbkg_input    = FuncFitResult[2];
            Double_t nbkgerr_input = FuncFitResult[3];
            Double_t nsig_input5GeV = FuncFitResult[4];
            Double_t nsigerr_input5GeV = FuncFitResult[5];

            // force the parameters since EE pt=40 fails
            if(ieta==1 && ipt==5)
            {
                nsig_input = 3172.0;
                nbkg_input = 10031.0;
                nsig_input5GeV = 3158.7;

                Double_t tempPar[NRETURN]= {
                    22517.049862,
                    0.900766,
                    0.044772,
                    0.191920,
                    313.878244,
                    -0.545069,
                    -0.281830,
                    0.026143,
                    2.549494,
                    0.,
                    0.,
                    22517.049862,
                    0.900766,
                    0.044772,
                    0.191920,
                    313.878244,
                    -0.545069,
                    -0.281830,
                    0.026143,
                    2.549494,
                    0.,
                    0.,
                    22517.049862,
                    0.900766,
                    0.044772,
                    0.191920,
                    313.878244,
                    -0.545069,
                    -0.281830,
                    0.026143,
                    2.549494,
                    0.,
                    0.
                };

                for(int ipar=0; ipar <NRETURN; ipar++)
                    myFitPar[ipar] = tempPar[ipar];
            } // end if EE, Et=40 GeV


            Double_t sigFitPar[NPAR]= {0};
            for(int ipar=0; ipar<NPAR; ipar++)
                sigFitPar[ipar] = myFitPar[ipar];

            Double_t bkgFitPar[NPAR]= {0};
            for(int ipar=0; ipar<NPAR; ipar++)
                bkgFitPar[ipar] = myFitPar[ipar+NPAR];


            Double_t sumFitPar[NPAR]= {0};
            for(int ipar=0; ipar<NPAR; ipar++)
                sumFitPar[ipar] = myFitPar[ipar+NPAR*2];


            TF1* fsig = new TF1("fsig", exp_conv, fit_lo, fit_hi, 11);
            fsig->SetParameters(sigFitPar);
            fsig->SetParameter(0,1.0);


            mySigPDFnorm = fsig->Integral(fit_lo,fit_hi);
            cout << "mySigPDFnorm = " << mySigPDFnorm << endl;

            TF1* fbkg = new TF1("fbkg", expinv_power, fit_lo, fit_hi, 11);
            fbkg->SetParameters(bkgFitPar);
            fbkg->SetParameter(4,1.0);
            cout << "Current parameter = " << fbkg->GetParameter(5) << endl;

            myBkgPDFnorm = fbkg->Integral(fit_lo, fit_hi);
            cout << "myBkgPDFnorm = " << myBkgPDFnorm << endl;

            TF1* fsum = new TF1("fsum",mysum_norm, fit_lo, fit_hi,11);
            fsum->SetParameters(sumFitPar);


            nsig_input = fNsigPt[ieta][ipt];

            cout << "Using nsig_input = " << nsig_input << endl;
            cout << "Using nbkg_input = " << nbkg_input << endl;
            cout << "Using nsig_input5GeV = " << nsig_input5GeV << endl;

            fsum->SetParameter(0, nsig_input*hdata_data[ieta][ipt]->GetBinWidth(2));
            fsum->SetParameter(4, nbkg_input*hdata_data[ieta][ipt]->GetBinWidth(2));
            fsum->SetLineColor(2);
            fsum->SetNpx(2500);

            //        cout << "fsum integral = " << fsum->Integral(fit_lo,fit_hi) << endl;
            //        for(int ipar=0; ipar<NPAR; ipar++)cout << "fsum par " << ipar << " = " << fsum->GetParameter(ipar) << endl;

//       FILE *infile =  fopen("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/EGdata_comb3Iso_et.dat","r");
//       Double_t xdata, xdata1, xdata2; // combined isolation, pt, eta
//       int flag = 1;
//       while (flag!=-1){
// 	flag =fscanf(infile,"%f %f %f",&xdata, &xdata1, &xdata2);
// 	if( xdata1 >= fBinsPt[ipt] && xdata1 < fBinsPt[ipt+1] && xdata<20.) {
// 	  if((ieta==0 && TMath::Abs(xdata2)<1.5) ||
// 	     (ieta==1 && TMath::Abs(xdata2)>1.5) ) {
// 	    htemp->Fill(xdata);
// 	  }
// 	}
//       }// keep reading files as long as text exists


//       TCanvas* myCanvas = new TCanvas("myCanvas","myCanvas");
//       htemp->Draw();
//       fsum->Draw("same");


            //        // loops over toys
            for(int iexp=0; iexp<NEXP; iexp++) {

                TH1D* htoyMC_data = (TH1D*)hdata_data[ieta][ipt]->Clone("htoyMC_data");
                htoyMC_data->Reset();

                TH1D* htoyMC_sig  = (TH1D*)hZeeTemplate_S[ieta]->Clone("htoyMC_sig");

                TH1D* htoyMC_bkg  = (TH1D*)hTemplate_B[ieta][ipt]->Clone("htoyMC_bkg");




                UInt_t nowSeed = (unsigned long)gSystem->Now();
                gRandom->SetSeed(nowSeed);
                int nsiggen  = gRandom->Poisson(nsig_input);
                int nbkggen  = gRandom->Poisson(nbkg_input);
                int ndata = nsiggen + nbkggen;

                // reset toy MC data
                htoyMC_data->Reset();
                ofstream fout;
                std::string toyData = Form("/tmp/syu/changeBkgTemptoy_%d_%d.dat",ieta,ipt);

                fout.open(toyData.data());
                for(int ieve=0; ieve < nsiggen; ieve++)
                {
                    Double_t xvalue = fsig->GetRandom(fit_lo,fit_hi);
                    fout << xvalue << " " <<
                         0.5*(fBinsPt[ipt]+fBinsPt[ipt+1]) << " " << fBinsEta[ieta] << endl;
                    htoyMC_data->Fill(xvalue);
                }

                for(int ieve=0; ieve < nbkggen; ieve++)
                {
                    Double_t xvalue = fbkg->GetRandom(fit_lo,fit_hi);
                    fout << xvalue << " " <<
                         0.5*(fBinsPt[ipt]+fBinsPt[ipt+1]) << " " << fBinsEta[ieta] << endl;
                    htoyMC_data->Fill(xvalue);
                }

                fout.close();


                Double_t* toyFitResult;
                Double_t toyMyFitPar[NRETURN]= {0};

                toyFitResult =  Ifit(toyData.data(),
                                     htoyMC_sig, htoyMC_bkg,
                                     htoyMC_data, toyMyFitPar,
                                     (int)fBinsPt[ipt], dec[ieta],2);

                Double_t nsigtoyfit    = toyFitResult[0];
                Double_t errnsigtoyfit = toyFitResult[1];
                Double_t nbkgtoyfit    = toyFitResult[2];
                Double_t errnbkgtoyfit = toyFitResult[3];
                Double_t nsigtoyfit_5GeV = toyFitResult[4];
                Double_t errnsigtoyfit_5GeV = toyFitResult[5];


                if(errnsigtoyfit < 1e-6 || errnbkgtoyfit < 1e-6 ||
                        nsigtoyfit < 1e-6 || nbkgtoyfit < 1e-6 ||
                        nsig_input < 1e-6 || fabs(nsigtoyfit - nsig_input)<1e-4)continue;


                Double_t toySumFitPar[NPAR]= {0};
                for(int ipar=0; ipar<NPAR; ipar++)
                    toySumFitPar[ipar] = toyMyFitPar[ipar+NPAR*2];


//  	fsum->SetParameters(toySumFitPar);
//  	fsum->SetParameter(0, nsigtoyfit*hdata_data[ieta][ipt]->GetBinWidth(2));
//  	fsum->SetParameter(4, nbkgtoyfit*hdata_data[ieta][ipt]->GetBinWidth(2));
                fsum->SetParameter(0, (Double_t)nsiggen*hdata_data[ieta][ipt]->GetBinWidth(2));
                fsum->SetParameter(4, (Double_t)nbkggen*hdata_data[ieta][ipt]->GetBinWidth(2));

                // 	if(iexp%20==0){
                TCanvas* myCanvas = new TCanvas("myCanvas","SHIT");
                htoyMC_data->SetMaximum(htoyMC_data->GetMaximum()*1.5);
                htoyMC_data->Draw();
                fsum->Draw("same");
// 	 	  myCanvas->Print(Form("toysPlot/fit_%03i.gif",iexp));
// 	 	  delete myCanvas;
                // 	}

                // 	 cout << "fsum integral = " << fsum->Integral(-1,20) << endl;
                // 	 for(int ipar=0; ipar<NPAR; ipar++)cout << "fsum par " << ipar << " = " << fsum->GetParameter(ipar) << endl;


                Double_t pull = (nsigtoyfit - nsig_input)/errnsigtoyfit;
                Double_t bias = (nsigtoyfit - nsig_input)/nsig_input;


                htoyResult_pull[ieta][ipt]->Fill(pull);
                htoyResult_bias[ieta][ipt]->Fill(bias);


            } // end loops of toys

            delete fsig;
            delete fbkg;


        } // end of loop over pt bins


    }


    TFile* outFile = new TFile(Form("changBkgTemp_%s_pt%d.root",
                                    dec[runIeta], (int)fBinsPt[runIpt]),
                               "recreate");

    for(int ieta=0; ieta < nEtaBin; ieta++) {
        for(int ipt=0; ipt < nPtBin; ipt++) {

            if(htoyResult_pull[ieta][ipt]->GetEntries()>0)
                htoyResult_pull[ieta][ipt]->Write();

            if(htoyResult_bias[ieta][ipt]->GetEntries()>0)
                htoyResult_bias[ieta][ipt]->Write();
        }
    }

    outFile->Close();

}
void compareDressed_darko(std::string mcfilePostfix, 
			  std::string var1="h_ystar", 
			  float xmin=-9999, float xmax=-9999,
			  float ymin=0.8, float ymax=1.1,
			  bool logScale=false
			  )
{
  
  setTDRStyle();
  gStyle->SetOptStat(0);

  TH1D* h_numr;
  TH1D* h_deno;

  TH1D* h_both;

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

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

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

 

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

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

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

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

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

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

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

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


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


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

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

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

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

    }

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




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

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

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

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

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

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

    double diff = n_n-n_d;

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

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

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

    variance /= (n_d*n_d);

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

  }


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

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


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

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

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


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

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



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


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

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

  std::string psname = dirName + "/" + var1;
  if(output !="test")
    psname = dirName+ "/" + output + var1;
  else
    psname = dirName+ "/" + var1;
  filename = psname + ".eps";
  c1->Print(filename.data());
  filename = psname + ".gif";
  c1->Print(filename.data());
  filename = psname + ".pdf";
  c1->Print(filename.data());
  //   c1->Close();
}
Example #17
0
void drawResults(bool drawSinglePanels = false) {
  // const int kPPcentral = 1;
  // const int kPPperipheral =2 ;
  // const int kHIcentral =  3;
  // const int kHIperipheral = 4;
  // const int kPADATA = 5;
  // const int kPAMC = 6;
  //const int nPtBin = 4;
  // double ptBin[nPtBin+1] = {40, 50,60,80,9999};

  TH1D* meanJetPt[8];   // [collision] [Before/After variation]
  TH1D* meanJetPtSys[8];   // [collision] [Before/After variation]

  TH1D* meanXjg[8];   // [collision] [Before/After variation]
  TH1D* meanXjgSys[8];   // [collision] [Before/After variation]

  TH1D* meanRjg[8];
  TH1D* meanRjgSys[8];

  TFile * f = new TFile("../resultHistograms/resultHistograms_ppSmeared10030.root");
  meanJetPt[1]  =(TH1D*)f->Get(Form("meanJetPt_pp"));
  meanXjg[1]    =(TH1D*)f->Get(Form("meanXjg_pp"));
  meanRjg[1]  =(TH1D*)f->Get(Form("meanRjg_pp"));

  f   = new TFile("../resultHistograms/resultHistograms_ppSmeared13099.root");
  meanJetPt[2]  =(TH1D*)f->Get(Form("meanJetPt_pp"));
  meanXjg[2]    =(TH1D*)f->Get(Form("meanXjg_pp"));
  meanRjg[2]  =(TH1D*)f->Get(Form("meanRjg_pp"));

  // pbpb
  f =   new TFile("../resultHistograms/resultHistograms_nominal_vtxCentWeighted.root");

  meanJetPt[7]  =(TH1D*)f->Get(Form("meanJetPt_pp"));
  meanXjg[7]  =(TH1D*)f->Get(Form("meanXjg_pp"));
  meanRjg[7]  =(TH1D*)f->Get(Form("meanRjg_pp"));

  meanJetPt[3]  =(TH1D*)f->Get(Form("meanJetPt_pbpb_centralityBin1"));
  meanXjg[3]  =(TH1D*)f->Get(Form("meanXjg_pbpb_centralityBin1"));
  meanRjg[3]  =(TH1D*)f->Get(Form("meanRjg_pbpb_centralityBin1"));

  meanJetPt[4]  =(TH1D*)f->Get(Form("meanJetPt_pbpb_centralityBin2"));
  meanXjg[4]  =(TH1D*)f->Get(Form("meanXjg_pbpb_centralityBin2"));
  meanRjg[4]  =(TH1D*)f->Get(Form("meanRjg_pbpb_centralityBin2"));

  // pPb
  meanJetPt[5]  =(TH1D*)f->Get(Form("meanJetPt_ppb"));
  meanXjg[5]  =(TH1D*)f->Get(Form("meanXjg_ppb"));
  meanRjg[5]  =(TH1D*)f->Get(Form("meanRjg_ppb"));

  f =   new TFile("../resultHistograms/resultHistograms_MCrecoIso_vtxCentWeighted.root"); //pythia+hijing
  meanJetPt[6]  =(TH1D*)f->Get(Form("meanJetPt_ppb"));
  meanXjg[6]  =(TH1D*)f->Get(Form("meanXjg_ppb"));
  meanRjg[6]  =(TH1D*)f->Get(Form("meanRjg_ppb"));


  TFile* fSys = new TFile("../relativeSys/relativeSys_merged.root");

  meanJetPtSys[1]  =(TH1D*)fSys->Get("meanJetPt_pp_uncertainty_merged");
  meanRjgSys[1]  =(TH1D*)fSys->Get(Form("meanRjg_pp_uncertainty_merged"));
  meanXjgSys[1]  =(TH1D*)fSys->Get(Form("meanXjg_pp_uncertainty_merged"));

  meanJetPtSys[2] = (TH1D*)meanJetPtSys[1]->Clone(Form("%s_2",meanJetPtSys[1]->GetName()));
  meanRjgSys[2] = (TH1D*)meanRjgSys[1]->Clone(Form("%s_2",meanRjgSys[1]->GetName()));
  meanXjgSys[2] = (TH1D*)meanXjgSys[1]->Clone(Form("%s_2",meanXjgSys[1]->GetName()));

  meanJetPtSys[3]  =(TH1D*)fSys->Get("meanJetPt_pbpb_centralityBin1_uncertainty_merged");
  meanXjgSys[3]  =(TH1D*)fSys->Get(Form("meanXjg_pbpb_centralityBin1_uncertainty_merged"));
  meanRjgSys[3]  =(TH1D*)fSys->Get(Form("meanRjg_pbpb_centralityBin1_uncertainty_merged"));

  meanJetPtSys[4]  =(TH1D*)fSys->Get("meanJetPt_pbpb_centralityBin2_uncertainty_merged");
  meanXjgSys[4]  =(TH1D*)fSys->Get(Form("meanXjg_pbpb_centralityBin2_uncertainty_merged"));
  meanRjgSys[4]  =(TH1D*)fSys->Get(Form("meanRjg_pbpb_centralityBin2_uncertainty_merged"));

  meanJetPtSys[5]  =(TH1D*)fSys->Get("meanJetPt_ppb_uncertainty_merged");
  meanXjgSys[5]  =(TH1D*)fSys->Get(Form("meanXjg_ppb_uncertainty_merged"));
  meanRjgSys[5]  =(TH1D*)fSys->Get(Form("meanRjg_ppb_uncertainty_merged"));


  // RJG!!
  TCanvas* c2; 
  //c2->Divide(3,1);
  if( !drawSinglePanels)
  {
    c2 = new TCanvas("c1","",1300,500);
    makeMultiPanelCanvas(c2,3,1,0.0,0.0, 0.15, 0.15, 0.025);
  }
  else
  {
    c2 = new TCanvas("c1","",1450,500);
    c2->Divide(3,1);
    //makeMultiPanelCanvas(c2,3,1,0.2,0.2, 0.15, 0.15, 0.025);
  }
  c2->cd(3);
  handsomeTH1(meanRjg[1],1,1,21);
  //  drawSys(TH1 *h,TH1 *sys, Int_t theColor= newYellow, Int_t fillStyle = -1, Int_t lineStyle = -1)
  TH1D* tempR = new TH1D("tempR",";p_{T}^{#gamma} (GeV);R_{J#gamma}",1000,40,130);
  tempR->Reset();
  handsomeTH1(tempR,0);
  //tempR->SetAxisRange(0,1.2,"Y");
  tempR->SetAxisRange(0,1.0,"Y");
  tempR->SetAxisRange(40.01,109.99,"X");
  tempR->GetYaxis()->SetNdivisions(505);
  tempR->Draw();
  drawSys(meanRjg[1], meanRjgSys[1], kGreen,3001);
  drawSys(meanRjg[3], meanRjgSys[3]);
  handsomeTH1(meanRjg[1],1,1,21);
  meanRjg[1]->DrawCopy("same");
  handsomeTH1(meanRjg[3],2,1,20);
  meanRjg[3]->DrawCopy("same");
  meanRjg[1]->SetFillStyle(3001);
  meanRjg[1]->SetFillColor(kGreen);
  meanRjg[3]->SetFillColor(90);
  meanRjg[3]->SetFillStyle(1001);
  meanRjg[1]->SetLineColor(0);
  meanRjg[3]->SetLineColor(0);
  if ( 1==1 ){
    TLegend *ly = new  TLegend(0.4,0.2,0.75,0.4,NULL,"brNDC");
    //easyLeg(ly,"2.76TeV");
    easyLeg(ly);
    ly->AddEntry(meanRjg[3],"PbPb 0-30%","fp");
    ly->AddEntry(meanRjg[1],"Smeared pp reference","fp");
    ly->Draw();
  }
  if(!drawSinglePanels)
    drawCMSppPbPbDist(0.04,0.9);
  else
    drawCMSppPbPbDist(0.2,0.9);


  c2->cd(2);
  tempR->Draw();
  drawSys(meanRjg[2], meanRjgSys[2], kGreen,3001);
  drawSys(meanRjg[4], meanRjgSys[4]);
  //  meanRjg[2]->SetMarkerStyle(25);
  handsomeTH1(meanRjg[2],1,1,25);
  meanRjg[2]->DrawCopy("same");
  handsomeTH1(meanRjg[4],2,1,24);
  //  meanRjg[4]->SetMarkerStyle(24);
  meanRjg[4]->DrawCopy("same");
  meanRjg[2]->SetFillStyle(3001);
  meanRjg[2]->SetFillColor(kGreen);
  meanRjg[4]->SetFillColor(90);
  meanRjg[4]->SetFillStyle(1001);
  meanRjg[2]->SetLineColor(0);
  meanRjg[4]->SetLineColor(0);
  if ( 1==1 ){
    TLegend *ly = new  TLegend(0.4,0.2,0.75,0.4,NULL,"brNDC");
    easyLeg(ly);
    ly->AddEntry(meanRjg[4],"PbPb 30-100%","fp");
    ly->AddEntry(meanRjg[2],"Smeared pp reference","fp");
    ly->Draw();
  }
  if(!drawSinglePanels)
    drawCMSppPbPbDist(0.04,0.9);
  else
    drawCMSppPbPbDist(0.2,0.9);

  c2->cd(1);
  tempR->SetAxisRange(40,109.99,"X");
  tempR->DrawCopy();
  tempR->SetAxisRange(40.01,109.99,"X");
  drawSys(meanRjg[5], meanRjgSys[5], newYellow);
  drawSys(meanRjg[7], meanRjgSys[2], kGreen, 3001);
  //  handsomeTH1(meanRjg[5],9,1,34);
  handsomeTH1(meanRjg[5],2,1,34);
  handsomeTH1(meanRjg[6],1,1,25);
  handsomeTH1(meanRjg[7],1,1);
  meanRjg[6]->DrawCopy("same");
  meanRjg[7]->DrawCopy("same");
  meanRjg[5]->DrawCopy("same");
  meanRjg[7]->SetFillStyle(3001);
  meanRjg[7]->SetFillColor(kGreen);
  meanRjg[5]->SetFillColor(90);
  meanRjg[5]->SetFillStyle(1001);
  meanRjg[7]->SetLineColor(0);
  meanRjg[5]->SetLineColor(0);

  if ( 1==1 ) {
    TLegend *ly = new TLegend(0.5,0.2,0.85,0.42,NULL,"brNDC");//0.4,0.2,0.75,0.4
    easyLeg(ly);
    ly->AddEntry(meanRjg[5],"pPb DATA","fp");
    ly->AddEntry(meanRjg[7],"pp DATA (2.76 TeV)","fp");
    ly->AddEntry(meanRjg[6],"PYTHIA+HIJING","p");
    ly->Draw();
  }
  drawCMSpPbDist(0.2,0.9);
  
  c2->SaveAs("pT_dependence_rjg_pp_pbpb.pdf");
  c2->SaveAs("pT_dependence_rjg_pp_pbpb.gif");
  //c2->SaveAs("pT_dependence_rjg_pp_pbpb.png");

  // ppPbPb meanJetPt
  TCanvas* c3 = new TCanvas("c3","",1300,500);
  if(!drawSinglePanels)
    makeMultiPanelCanvas(c3,3,1,0.0,0.0, 0.15, 0.15, 0.025);
  else
    c3->Divide(3,1);
    //makeMultiPanelCanvas(c3,3,1,0.2,0.2, 0.15, 0.15, 0.025);
  c3->cd(1);
  handsomeTH1(meanRjg[1],1);
  //  drawSys(TH1 *h,TH1 *sys, Int_t theColor= newYellow, Int_t fillStyle = -1, Int_t lineStyle = -1)
  //  tempR->Draw();
  TH1D* tempJ = new TH1D("tempJ",";p_{T}^{#gamma}; <p_{T}^{Jet}>",10000,40,130);
  tempJ->Reset();
  handsomeTH1(tempJ,0);
  tempJ->SetAxisRange(40.01,109.99,"Y");
  tempJ->SetAxisRange(40.,109.99,"X");
  tempJ->DrawCopy();
  tempJ->SetAxisRange(40.01,109.99,"X");
  drawSys(meanJetPt[5], meanJetPtSys[5], newYellow);
  drawSys(meanJetPt[7], meanJetPtSys[1], kGreen,3001);
  //  handsomeTH1(meanJetPt[5],9,1,34);
  handsomeTH1(meanJetPt[5],2,1,34);
  handsomeTH1(meanJetPt[6],1,1,25);
  handsomeTH1(meanJetPt[7],1,1);
  meanJetPt[6]->DrawCopy("same");
  meanJetPt[7]->DrawCopy("same");
  meanJetPt[5]->DrawCopy("same");
  if ( 1==1 ) {
    TLegend *ly = new TLegend(0.53,0.18,0.88,0.4,NULL,"brNDC");
    easyLeg(ly);
    ly->AddEntry(meanJetPt[5],"pPb DATA","p");
    ly->AddEntry(meanJetPt[7],"pp DATA (2.76 TeV)","p");
    ly->AddEntry(meanJetPt[6],"PYTHIA+HIJING","p");
    ly->Draw();
  }
  drawCMSpPbDist(0.2,0.9);

  
  c3->cd(3);
  handsomeTH1(meanJetPt[1],1,1,21);
  //  drawSys(TH1 *h,TH1 *sys, Int_t theColor= newYellow, Int_t fillStyle = -1, Int_t lineStyle = -1)
  tempJ->Draw();
  drawSys(meanJetPt[3], meanJetPtSys[3]);
  drawSys(meanJetPt[1], meanJetPtSys[1], kGreen,3001);
  handsomeTH1(meanJetPt[3],2 );
  meanJetPt[1]->Draw("same");
  meanJetPt[3]->Draw("same");
  if ( 1==1 ){
    TLegend *ly = new  TLegend(0.58,0.18,0.93,0.4,NULL,"brNDC");
    easyLeg(ly);
    ly->AddEntry(meanJetPt[3],"PbPb 0-30%","p");
    ly->AddEntry(meanJetPt[1],"pp (smeared)","p");
    ly->Draw();
  }
  drawCMSppPbPbDist(0.1,0.9);

  c3->cd(2);
  tempJ->Draw();
  drawSys(meanJetPt[2], meanJetPtSys[2], kGreen,3001);
  drawSys(meanJetPt[4], meanJetPtSys[4]);
  //  meanJetPt[2]->SetMarkerStyle(25);
  meanJetPt[2]->Draw("same");
  handsomeTH1(meanJetPt[4],2 );
  //  meanJetPt[4]->SetMarkerStyle(24);
  meanJetPt[4]->Draw("same");
  if ( 1==1 ){
    TLegend *ly = new  TLegend(0.58,0.18,0.93,0.4,NULL,"brNDC");
    easyLeg(ly);
    ly->AddEntry(meanJetPt[4],"PbPb 30-100%","p");
    ly->AddEntry(meanJetPt[2],"pp (smeared)","p");
    ly->Draw();
  }
  drawCMSppPbPbDist(0.1,0.9);
  c3->SaveAs("pT_dependence_jetPt_pp_pbpb.pdf");
  c3->SaveAs("pT_dependence_jetPt_pp_pbpb.gif");
  //c3->SaveAs("pT_dependence_jetPt_pp_pbpb.png");


  // mean xjg
  TCanvas* c7; 
  if(!drawSinglePanels)
  {
    c7 = new TCanvas("c7","",1300,500);
    makeMultiPanelCanvas(c7,3,1,0.0,0.0, 0.15, 0.15, 0.025);
  }
  else
  {
    c7 = new TCanvas("c7","",1450,500);
    c7->Divide(3,1);
    //makeMultiPanelCanvas(c7,3,1,0.2,0.2, 0.15, 0.15, 0.025);
  }
  c7->cd(3);
  handsomeTH1(meanXjg[1],1,1,24);
  //  drawSys(TH1 *h,TH1 *sys, Int_t theColor= newYellow, Int_t fillStyle = -1, Int_t lineStyle = -1)
  TH1D* tempX = new TH1D("tempX",";p_{T}^{#gamma} (GeV);<X_{J#gamma}>;",10000,40,130);
  tempX->Reset();
  handsomeTH1(tempX,0);
  tempX->SetAxisRange(0.6,1.1,"Y");
  tempX->SetAxisRange(40.01,109.99,"X");
  tempX->GetYaxis()->SetNdivisions(606);
  tempX->Draw();
  drawSys(meanXjg[3], meanXjgSys[3]);
  drawSys(meanXjg[1], meanXjgSys[1], kGreen,3001);
  //  meanXjg[1]->SetMarkerStyle(21);
  handsomeTH1(meanXjg[1],1,1,21);
  meanXjg[1]->DrawCopy("same");
  handsomeTH1(meanXjg[3],2,1,20);
  meanXjg[3]->DrawCopy("same");
  meanXjg[1]->SetFillStyle(3001);
  meanXjg[1]->SetFillColor(kGreen);
  meanXjg[3]->SetFillColor(90);
  meanXjg[3]->SetFillStyle(1001);
  meanXjg[1]->SetLineColor(0);
  meanXjg[3]->SetLineColor(0);

  Float_t xpos = 0.022;
  if(drawSinglePanels)
    xpos = 0.15;
  if ( 1==1 ){
    TLegend *ly = new TLegend(xpos,0.1861745,0.578901,0.3788434,NULL,"brNDC");
    easyLeg(ly);
    ly->AddEntry(meanXjg[3],"PbPb 0-30%","fp");
    ly->AddEntry(meanXjg[1],"Smeared pp reference","fp");
    ly->Draw();
  }
  drawCMSppPbPbDist(0.6,0.9);


  c7->cd(2);
  tempX->Draw();
  drawSys(meanXjg[4], meanXjgSys[4]);
  drawSys(meanXjg[2], meanXjgSys[2], kGreen,3001);
  //  meanXjg[2]->SetMarkerStyle(25);
  handsomeTH1(meanXjg[2],1,1,25);
  meanXjg[2]->DrawCopy("same");
  handsomeTH1(meanXjg[4],2,1,24 );
  //  meanXjg[4]->SetMarkerStyle(24);
  meanXjg[4]->DrawCopy("same");
  meanXjg[2]->SetFillStyle(3001);
  meanXjg[2]->SetFillColor(kGreen);
  meanXjg[4]->SetFillColor(90);
  meanXjg[4]->SetFillStyle(1001);
  meanXjg[2]->SetLineColor(0);
  meanXjg[4]->SetLineColor(0);

  if ( 1==1 ){
    TLegend *ly = new TLegend(xpos,0.1861745,0.578901,0.3788434,NULL,"brNDC");
    easyLeg(ly);
    ly->AddEntry(meanXjg[4],"PbPb 30-100%","fp");
    ly->AddEntry(meanXjg[2],"Smeared pp reference","fp");
    ly->Draw();
  }
  drawCMSppPbPbDist(0.6,0.9);

  c7->cd(1);
  tempX->SetAxisRange(40.0,109.99,"X");
  tempX->DrawCopy();
  tempX->SetAxisRange(40.01,109.99,"X");
  drawSys(meanXjg[5], meanXjgSys[5], newYellow);
  drawSys(meanXjg[7], meanXjgSys[2], kGreen, 3001);
  //  handsomeTH1(meanXjg[5],9,1,34);
  handsomeTH1(meanXjg[5],2,1,34);
  handsomeTH1(meanXjg[6],1,1,25);
  handsomeTH1(meanXjg[7],1,1);
  meanXjg[6]->DrawCopy("same");
  meanXjg[7]->DrawCopy("same");
  meanXjg[5]->DrawCopy("same");
  meanXjg[7]->SetFillStyle(3001);
  meanXjg[7]->SetFillColor(kGreen);
  meanXjg[5]->SetFillColor(90);
  meanXjg[5]->SetFillStyle(1001);
  meanXjg[7]->SetLineColor(0);
  meanXjg[5]->SetLineColor(0);

  if ( 1==1 ) {
    TLegend *ly = new TLegend(0.1722123,0.1861,0.4788343,0.3788,NULL,"brNDC");
    easyLeg(ly);
    ly->AddEntry(meanXjg[5],"pPb DATA","fp");
    ly->AddEntry(meanXjg[7],"pp DATA (2.76 TeV)","fp");    
    ly->AddEntry(meanXjg[6],"PYTHIA+HIJING","p");
    ly->Draw();
  }
  drawCMSpPbDist(0.65,0.90);
  
  c7->SaveAs("pT_dependence_meanXjg_pp_pbpb.pdf");
  c7->SaveAs("pT_dependence_meanXjg_pp_pbpb.gif");
  //c7->SaveAs("pT_dependence_meanXjg_pp_pbpb.png");

  // TCanvas* c10 = new TCanvas("c10","",1200,350);
  // makeMultiPanelCanvas(c10,nPtBin,1,0.0,0.0,0.2,0.15,0.02);
  // for ( int ipt = 1 ; ipt<=nPtBin  ; ipt++) {
  //   c10->cd(ipt);

  //   hTempPt->SetAxisRange(20,200,"X");
  //   hTempPt->SetAxisRange(0,2.5,"Y");
  //   hTempPt->SetYTitle("Yield^{JeT} Ratio");
  //   handsomeTH1(hTempPt,0);
  //   hTempPt->DrawCopy();
  //   IaaRatio[4][ipt] = (TH1D*)Iaa[4][ipt]->Clone(Form("%s_ratio",Iaa[4][ipt]->GetName()) );
  //   IaaRatio[4][ipt]->Divide(Iaa[2][ipt]);
  //   IaaRatioSys[4][ipt] = mergeSys( IaaSys[2][ipt], IaaSys[4][ipt]) ;

  //   drawSys(IaaRatio[4][ipt], IaaRatioSys[4][ipt], newYellow);
  //   jumSun(20,1,200,1);
  //   handsomeTH1(IaaRatio[4][ipt],2);
  //   IaaRatio[4][ipt]->SetMarkerStyle(24);
  //   IaaRatio[4][ipt]->Draw("same");
  //   double dx1=0.15;
  //   drawText(Form("p_{T}^{#gamma} > %dGeV ", (int)ptBin[ipt-1]), 0.12+dx1+0.25,0.85,1,15);//yeonju 130823
  //   drawText(Form("(PbPb)/(pp smeared)  30-100%%"), 0.12+dx1+0.05,0.69,1,15);//yeonju 130823
  // }

  // c10->SaveAs("pT_dependence_iAA_ratio2.pdf");



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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

        TLine *l = new TLine(0,1,90,1);
        l->SetLineStyle(2);
        l->Draw("same");
    }
    c1->SaveAs(Form("ratiovseff.png"));
    c1->SaveAs(Form("ratiovseff.pdf"));
}
Example #19
0
void sqrtByFill(){


	//OPTIONS AND CUTS______________
	bool useBlueBeam = true;
	bool useYellowBeam = true;
	bool randomizeSpin = false;
	bool fullEta = true;
	
	double PI = 3.14159265359;
	
	//LOAD LIBS_____________________
	cout << "\n";
	gROOT->Macro("StRoot/LoadLibs.C");
	gSystem->Load("pionPair");
	cout << " loading of pionPair library done" << endl;
	//______________________________
	
	
	//SET UP INPUT FILE_____________
	TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOut_Full_4_2/allPairs_4_2.root");
	
	string outFileName = "./resultsNew_4_22/pairsFrom4_2ByFill.root"; 
	
	
	
  //______________________________
	
	
	//SET UP TREE TO RECEIVE INPUT__
	pionPair* pair1 = new pionPair();
	TTree* pairTree = infile->Get("pionPairTree");
	pairTree->SetBranchAddress("pionPair", &pair1);
	//______________________________
	
	
	

	
	double histMin = -PI;
	double histMax =  PI;
	const int binNumber = 16;
	
	TH1D * hNumberUp   = new TH1D("hNumberUp","hNumberUp",binNumber,histMin,histMax);
	TH1D * hNumberDown = new TH1D("hNumberDown","hNumberDown",binNumber,histMin,histMax);
	TH1D * hAut = new TH1D("Aut","Aut",binNumber,histMin,histMax);

	
	TH1D* polOfBin[16];
	for (int i = 0; i < 16; i++)
	{
		stringstream ss;
		ss << i;
				
		string fullname = "hPolOfBin_phiSRbin_" + ss.str();
		cout << fullname << endl;
		
		polOfBin[i] = new TH1D(fullname.c_str(),fullname.c_str(),25,0,1);
		
	}
	
	
	
	//BEAM POLARIZATION_____________
	ifstream polFile;
	polFile.open("/star/u/klandry/ucladisk/2012IFF/BeamPolarization2012.txt");
	
	
	map<int, double> polarizationOfFill_Y;
	map<int, double> polErrOfFill_Y;
	
	map<int, double> polarizationOfFill_B;
	map<int, double> polErrOfFill_B;
	
	
	
	int    fill;
	int    beamE;
	int    startT;
	string plusminus;
	
	double pAvrgBlue;
	double pErrAvrgBlue;
	
	double pInitialBlue;
	double pErrInitialBlue;
	double dPdTBlue;
	double dPdTErrBlue;
	
	double pAvrgYellow;
	double pErrAvrgYellow;
	
	double pInitialYellow;
	double pErrInitialYellow;
	double dPdTYellow;
	double dPdTErrYellow;
	
	string header;
	
	for (int i=0; i<19; i++){polFile >> header;}
	
	while (!polFile.eof())
	{
		
		polFile >> fill;
		polFile >> beamE;
		polFile >> startT;
		
		polFile >> pAvrgBlue;
		polFile >> plusminus;
		polFile >> pErrAvrgBlue;
		
		polFile >> pInitialBlue;
		polFile >> plusminus;
		polFile >> pErrInitialBlue;
		
		polFile >> dPdTBlue;
		polFile >> plusminus;
		polFile >> dPdTErrBlue;
		
		polFile >> pAvrgYellow;
		polFile >> plusminus;
		polFile >> pErrAvrgYellow;
		
		polFile >> pInitialYellow;
		polFile >> plusminus;
		polFile >> pErrInitialYellow;
		
		polFile >> dPdTYellow;
		polFile >> plusminus;
		polFile >> dPdTErrYellow;
		
		
		polarizationOfFill_B[fill] = pAvrgBlue/100.;
		polErrOfFill_B[fill] = pErrAvrgBlue/100.;
		
		polarizationOfFill_Y[fill] = pAvrgYellow/100.;
		polErrOfFill_Y[fill] = pErrAvrgYellow/100.;
		
	}
	
	double avgPolOfBinUp[binNumber];
	double polOfBinSumUp[binNumber];
	
	double avgPerrorOfBinUp[binNumber];
	double pErrorOfBinUp[binNumber];
	
	double avgPolOfBinDown[binNumber];
	double polOfBinSumDown[binNumber];
	
	double avgPerrorOfBinDown[binNumber];
	double pErrorOfBinDown[binNumber];
	
	for (int i=0; i<binNumber; i++)
	{
		avgPolOfBinUp[i] = 0;
		polOfBinSumUp[i] = 0;
		
		avgPerrorOfBinUp[i] = 0;
		pErrorOfBinUp[i] = 0;
		
		avgPolOfBinDown[i] = 0;
		polOfBinSumDown[i] = 0;
		
		avgPerrorOfBinDown[i] = 0;
		pErrorOfBinDown[i] = 0;
		
	}
	
	
	
	//CUTS__________________________
	double lowLimitPt    = ptBinStart[0];
	double hiLimitPt     = ptBinEnd[4];
	double lowLimitEta   = etaBinStart[3];  //set up do only do eta bin 3
	double hiLimitEta    = etaBinEnd[3];
	double lowLimitMass  = massBinStart[0];
	double hiLimitMass   = massBinEnd[4];
	
	
	
	
	//______________________________
	//   ======================================================================
	//============================================================================
	//START ANALYSIS==============================================================
	//============================================================================
	//   ======================================================================
	//*
	cout << "\n";
	cout << "<----STARTING ANALYSIS---->" << endl;
  cout << "\n";
	cout << pairTree->GetEntries() << " pairs to analyze" << endl;
	
	
	
	int blueFillNo;
	int yellowFillNo;
	
	int phiSRbin;
	
	
	vector<double> fillAsyms;
	vector<double> fillAsymsE;
	vector<double> fillVec;
	
	TLorentzVector sum;
	TLorentzVector sumY;
	TLorentzVector sumB;
	
	//random number for randomizing spin.
	//set seed to zero to gaurenty unique numbers each time.
	TRandom3 r;
	r.SetSeed(0);
	
	int rand5 = 0;
	int rand6 = 0;
	int rand9 = 0;
	int rand10 = 0;
	
	
	int totalPairsFinal = 0;
	int blueD = 0;
	int blueU = 0;
	int yellowD = 0;
	int yellowU = 0;
	
	int pionStarNumber = 0;
	int runsProcessed = 0;
	
	double currentFillNo = 0;
	double currentRunNo = 0;

	
	for (int iPair = pionStarNumber; iPair < pairTree->GetEntries(); iPair++)
	{
		
		if (iPair%10000 == 0) {cout << "processing pair number " << iPair << endl;}
		//if (iPair == pionStarNumber+300000){break;}
		
		pairTree->GetEntry(iPair);
		
		//if (runsProcessed > 4){break;} 
		
		
		if (pair1->runInfo().beamFillNumber(1) != currentFillNo && currentFillNo != 0 && currentFillNo != 16427)
		//if (pair1->runInfo().runId() != currentRunNo && currentRunNo != 0)
		{
			runsProcessed++;

			cout << "runsProcessed " << runsProcessed << endl;
			
			double* asym = new double();
			double* asymE = new double();
			calcAsyms(hAut, hNumberUp, hNumberDown, polOfBin, asym, asymE);
						
			fillAsyms.push_back(*asym);
			fillAsymsE.push_back(*asymE);
			fillVec.push_back(runsProcessed);
			
			hNumberUp->Reset();
			hNumberDown->Reset();
			hAut->Reset();
			
			for (int i=0; i<binNumber; i++)
			{
				polOfBin[i]->Reset();
			}
			
			
		}
		else if (currentRunNo == 16427)
		{
			//fillAsyms.push_back(*asym);
			//fillAsymsE.push_back(*asymE);
			//fillVec.push_back(runsProcessed);
			
			hNumberUp->Reset();
			hNumberDown->Reset();
			hAut->Reset();
			
			for (int i=0; i<binNumber; i++)
			{
				polOfBin[i]->Reset();
			}
			
		
		}
		
		
		currentRunNo = pair1->runInfo().runId();
		currentFillNo = pair1->runInfo().beamFillNumber(1);
		
		if (pair1->withinRadius(0.05, 0.3))
		{
			
			bool triggerFired = false;
			bool fromKaon = false;
			bool passInitialCut_B = false;
			bool passInitialCut_Y = false;
			bool passDCAcut = false;
			
			StTriggerId trigId = pair1->triggerIds();
			
			//JP0,JP1,JP2,AJP
			if (trigId.isTrigger(370601) || trigId.isTrigger(370611) || trigId.isTrigger(370621) || trigId.isTrigger(370641))
			{
				triggerFired = true;
			}
			
			//BHT0VPD,BHT1VPD,BHT2BBC,BHT2
			if (trigId.isTrigger(370501) || trigId.isTrigger(370511) || trigId.isTrigger(370522) || trigId.isTrigger(370531))
			{
				triggerFired = true;
			}
			
			
			if (triggerFired)
			{
				
				blueFillNo   = pair1->runInfo().beamFillNumber(1); //1 = blue beam
				yellowFillNo = pair1->runInfo().beamFillNumber(0); //0 = yellow beam 
				
				sum = pair1->piPlusLV() + pair1->piMinusLV();
				sumB = sum; //blue beam.
				
				
				//yellow beam must rotate around y axis by pi so the eta cut can be the same for both beams. 				
				sumY = sum;
				sumY.RotateY(PI);

				if (sumB.Pt() >= lowLimitPt && sumB.Pt() <= hiLimitPt && sumB.M() >= lowLimitMass && sumB.M() <= hiLimitMass && sumB.Eta() >= lowLimitEta && sumB.Eta() <= hiLimitEta)
				{
					passInitialCut_B = true;
				}
				if (sumY.Pt() >= lowLimitPt && sumY.Pt() <= hiLimitPt && sumY.M() >= lowLimitMass && sumY.M() <= hiLimitMass && sumY.Eta() >= lowLimitEta && sumY.Eta() <= hiLimitEta)
				{
					passInitialCut_Y = true;
				}
				
				if (passInitialCut_B && useBlueBeam)
				{
					//BLUE BEAM SPIN UP: spin bin 9 and 10
					if (pair1->spinBit() == 9 || pair1->spinBit() == 10)
					{						
						hNumberUp->Fill(pair1->phiSR('b'));
						phiSRbin = hNumberUp->FindBin(pair1->phiSR('b'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_B[blueFillNo]);
						/*if (iPair > 39000)
						{
							cout << "polarization = " << polarizationOfFill_B[blueFillNo] << "  " << blueFillNo << endl;
						}*/
						
						
					}
					
					//BLUE BEAM SPIN DOWN: spin bin 5 and 6
					if (pair1->spinBit() == 5 || pair1->spinBit() == 6)
					{
						hNumberDown->Fill(pair1->phiSR('b'));
						phiSRbin = hNumberDown->FindBin(pair1->phiSR('b'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_B[blueFillNo]);
						
					}
				}//done with blue beam
				
				if (passInitialCut_Y && useYellowBeam)
				{
					//YELLOW BEAM SPIN UP: spin bin 6 and 10
					if (pair1->spinBit() == 6 || pair1->spinBit() == 10)
					{
						hNumberUp->Fill(pair1->phiSR('y'));
						phiSRbin = hNumberUp->FindBin(pair1->phiSR('y'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_Y[yellowFillNo]);
						
					}						
					
					//YELLOW BEAM SPIN DOWN: spin bit 5 and 9
					if (pair1->spinBit() == 5 || pair1->spinBit() == 9)
					{
						hNumberDown->Fill(pair1->phiSR('y'));
						phiSRbin = hNumberDown->FindBin(pair1->phiSR('y'));
						
						polOfBin[phiSRbin-1]->Fill(polarizationOfFill_Y[yellowFillNo]);
					}
				}//done with yellow beam
			}//end trigger check
		}//end radius check
		
		
	}//end pion tree loop
	
	
	cout << "out of tree loop" << endl;
	
	
	cout << fillAsyms.size() << endl;
	
	
	TGraphErrors* gAsymVsFill = new TGraphErrors(fillAsyms.size(), &fillVec[0], &fillAsyms[0], 0, &fillAsymsE[0]);
	
	gAsymVsFill->Draw("AP");
	
	TFile* outFile = new TFile(outFileName.c_str(),"recreate");

	gAsymVsFill->Write();

}
void getTemplate(int ppHI, TH1D* h1, TString fname1, int isoChoice, float isoCut, int iTemp, int lowCent, int highCent, TCut addCut,bool onlygjEvents, float specialSbCut, float theShift) { 
 
  char fnamePho30[500] = "skimmed/yskim_qcdAllPhoton30_allCent_nMix10_v4.root";
  float nEvtPho30    =  45000;
  char fnamePho50[500] = "skimmed/yskim_qcdAllPhoton50_allCent_nMix10_v4.root";
  float nEvtPho50     = 45188;
  char fnamePho80[500] = "skimmed/barrelHiforestv2_qcdAllPhoton80_allCent.root";
  float nEvtPho80     = 45308;
    
  char fnameEmj80[500] = "barrelHiForestPhoton_MCemJet80_41007events.root";
  char fnameEmj120[500] = "barrelHiForestPhoton_MCemJet120_25308events.root";
  char fnameEmj80_cent10[500] = "barrelHiForestPhoton_emJet80_cent10_10016evnts.root";
  char fnameEmj120_cent10[500] = "barrelHiForestPhoton_emJet120_cent10_9540Evts.root";
  
  
  char fnamePho30pp[500] = "mcbarrelHiForestPhoton_AllQCDPhoton30_PP7TeV.root";

   
   double csDij80 = 9.869e-5;
   float nEvtEmj80     = 41007;
   float effEmj80     = 0.204;
   float weightEmj80 = csDij80*effEmj80/nEvtEmj80;
   float nEvtEmj120     = 25308;
   double csDij120 = 1.127e-5;
   float effEmj120     = 0.54;
   float weightEmj120 = csDij120*effEmj120/nEvtEmj120;
   
   float nEvtEmj80_cent10      = 9540;
   float nEvtEmj120_cent10     = 10016;
   float weightEmj80_cent10 = csDij80*effEmj80/nEvtEmj80_cent10;
   float weightEmj120_cent10 = csDij120*effEmj120/nEvtEmj120_cent10;
   
   
   TCut evtSelCut = "tgj.anaEvtSel";
   if ( ppHI ==kPP ) evtSelCut = "";


   TCut centCut     = Form("yEvt.hiBin >= %d && yEvt.hiBin<= %d",lowCent,highCent);
   if ( ppHI ==kPP ) centCut = "";
   
   TCut noEleCut   = "isEle ==0";
   
   TCut photonJetCut  = "tgj.photonEt>50  &&  tgj.jetEt>30";
   TCut dphiCut= "acos(cos(tgj.photonPhi-tgj.jetPhi))>2.748893";
   TCut lPhotCut= "leading==1";
   TCut hoeCut ="hadronicOverEm<0.1";
   TCut islandButCut = " seedTime != 0";
   TCut generalCutMC   = lPhotCut && centCut && noEleCut && hoeCut && addCut &&islandButCut;
   if (onlygjEvents)
      generalCutMC = generalCutMC && photonJetCut && dphiCut;
    
   TCut generalCutData = generalCutMC && evtSelCut;
   if (onlygjEvents)
     generalCutData = generalCutData && photonJetCut && dphiCut;
   

   TCut srIsoCut = getIsoCut(isoChoice,isoCut);

   TCut finalCut="";
   if ( iTemp == kData )
     finalCut = generalCutData && srIsoCut ;
   else if ( iTemp == kSig )
     finalCut = generalCutMC && genMatchCut1  && srIsoCut ;
   else if ( iTemp == kSBB )
     finalCut = generalCutData && sbIsoCut;
   else if ( iTemp == kMCBsr )
     finalCut = generalCutMC && srIsoCut;
   else if ( iTemp == kMCBsb )
     finalCut = generalCutMC && sbIsoCut;
   else if ( iTemp == kSBBpp )
     finalCut = generalCutData && sbIsoPPCut;

   if ( (isoChoice == kSumIso3) && ( iTemp == kSBB )) {
     finalCut = generalCutMC && (TCut)(Form(" (cc4+cr4+ct4PtCut20)/0.9 > %f &&  (cc4+cr4+ct4PtCut20)/0.9 < %f",(float)specialSbCut,(float)(specialSbCut+10.))) ;
      if ( specialSbCut == -1 ) 
	finalCut = generalCutMC && "(cc4+cr4+ct4PtCut20)/0.9 > 10 &&  (cc4+cr4+ct4PtCut20)/0.9 < 20";
      //cout << " special cut : " << Form("( (cc4+cr4+ct4PtCut20)/0.9 > %f) && ( (cc4+cr4+ct4PtCut20)/0.9 < %f)",(float)specialSbCut,(float)(specialSbCut+10)) << " is used " << endl;
   }
   multiTreeUtil* photon1 = new multiTreeUtil();
   
   float csPho30 = 1.59e-6;
   float csPho50 = 7.67e-7;
   float csPho80 = 1.72e-7;
   float weightPho50 = csPho50/nEvtPho50;
   float weightPho80 = csPho80/nEvtPho80;
   float weightPho30 = csPho30/nEvtPho30;

   TString weightBit = "";
   if ( ppHI == kHI) {
     if ( iTemp  == kSig) {
       photon1->addFile( fnamePho30,  "yongsunPhotonTree", "ptHat>30 && ptHat<50" , weightPho30- weightPho50);
       photon1->addFile( fnamePho50,  "yongsunPhotonTree", "ptHat>50 && ptHat<80" , weightPho50 - weightPho80);
       photon1->addFile( fnamePho80,  "yongsunPhotonTree", "ptHat<80" , weightPho80);
       weightBit = "tgj.reweight";
     }
     else if ( (iTemp == kSBB) || (iTemp == kData) )  {
       // if this is data
       photon1->addFile( fname1 , "yongsunPhotonTree", "" ,1);
       weightBit = "";
     }
     
     else if ( (iTemp == kMCBsr) || (iTemp == kMCBsb)){
       photon1->addFile(fnameEmj80,  "yongsunPhotonTree", "" , weightEmj80);
       photon1->addFile(fnameEmj120, "yongsunPhotonTree", "" , weightEmj120);
       photon1->addFile(fnameEmj80_cent10,  "yongsunPhotonTree", "yEvt.hiBin<4" , weightEmj80_cent10);
       photon1->addFile(fnameEmj120_cent10,  "yongsunPhotonTree", "yEvt.hiBin<4" , weightEmj120_cent10);
       weightBit = "tgj.reweight";
     }
   }
   if ( ppHI == kPP) {
     if ( iTemp  == kSig) {
       photon1->addFile( fnamePho30pp,  "yongsunPhotonTree", "" , weightPho30);
       weightBit = "";
     }
     else if ( (iTemp == kSBB) || (iTemp == kData) || (iTemp == kSBBpp) ) {
       photon1->addFile( fname1 , "yongsunPhotonTree", "" ,1);
       weightBit = "";
     }
   }
   
   photon1->AddFriend("yEvt=yongsunHiEvt");
   //   photon1->AddFriend("yJet=yongsunJetakPu3PF");
   photon1->AddFriend("tgj");
   
   
   h1->Reset();
   h1->Sumw2();
   TH1D* htemp = (TH1D*)h1->Clone("htemp");
   htemp->Reset();
   htemp->Sumw2();
   cout << "cut = " << finalCut.GetTitle() <<  endl;

   photon1->Draw2(htemp,  Form("sigmaIetaIeta+%f",theShift),   finalCut,  weightBit);
   cout << " this is it" << endl;
   //  cout << " MC final Cut = " << finalCut.GetTitle() <<endl;
   TH1D* hcBins = new TH1D("hncoll","",40,-.5,39.5);
   if ( iTemp == kData ) {
      cout << "Data entries = "<<  htemp->Integral() << endl;
      //   cout << "cut = " << finalCut.GetTitle() <<  endl;
      photon1->Draw2(hcBins,  "yEvt.hiBin",   finalCut);
   }
   
   h1->Add(htemp);
   htemp->Reset();
   
      
   delete photon1;
   
   
}
Example #21
0
TCanvas* DrawComparison(TH1D* prediction, TH1D* selection, TString Title, TString LumiTitle, TString xTitle, bool isData)
{
   double MinX = selection->GetXaxis()->GetXmin();
   double MaxX = selection->GetXaxis()->GetXmax();
   double MaxY = selection->GetMaximum();
   double YRangeMax = MaxY;
   TString titlePrediction;
   TString titleSelection;
   TString RatioTitle;
   
   if( isData ){
      titlePrediction = "Data";
      titleSelection = "MC";
      RatioTitle = "(Data-MC)/MC";
   }
   else {
      titlePrediction = "Data-driven Pred. from MC";
      titleSelection = "MC Expectation";
      RatioTitle = "(Pred-MC)/MC";
   }

   //static Int_t c_LightBrown   = TColor::GetColor( "#D9D9CC" );
   static Int_t c_LightGray    = TColor::GetColor( "#DDDDDD" );

   prediction->SetAxisRange(MinX, MaxX, "X");
   prediction->GetYaxis()->SetRangeUser(0.005, YRangeMax);
   prediction->SetMarkerStyle(20);
   prediction->SetMarkerSize(0.9);
   prediction->SetMarkerColor(kBlack);
   prediction->SetXTitle(xTitle);
   prediction->SetYTitle("Events");
   selection->SetAxisRange(MinX, MaxX, "X");
   selection->GetYaxis()->SetRangeUser(0.05, YRangeMax);
   // selection->SetFillColor(c_LightBrown);
   selection->SetFillColor(c_LightGray);
   selection->SetTitle("");
   selection->SetXTitle(xTitle);
   selection->SetYTitle("Events");
   TCanvas *c = new TCanvas("ca", "Comparison and ratio of two histos", 700, 700);
   TPad *pad1 = new TPad("pad1a", "pad1a", 0, 0.35, 1, 1);
   //pad1->SetLogy();
   pad1->SetBottomMargin(0);
   pad1->Draw();
   pad1->cd();
  
   selection->DrawCopy("hist");
   prediction->Draw("same");
   selection->SetFillColor(kAzure-3);
   selection->SetFillStyle(3354);
   selection->DrawCopy("e2same");
   selection->SetFillStyle(1001);
   //  selection->SetFillColor(c_LightBrown);
   selection->SetFillColor(c_LightGray);

   TLegend* leg1 = new TLegend(0.48, 0.63, 0.95, 0.83);
   leg1->SetFillStyle(0);
   leg1->SetLineStyle(1);
   leg1->SetTextFont(42);
   leg1->SetTextSize(0.04);
   leg1->AddEntry(selection, titleSelection, "lf");
   leg1->AddEntry(prediction, titlePrediction, "lep");
   leg1->Draw("same");
 
   TPaveText* pt = new TPaveText(0.11, 0.98, 0.95, 0.86, "NDC");
   pt->SetBorderSize(0);
   pt->SetFillStyle(0);
   pt->SetTextAlign(12);
   pt->SetTextSize(0.045);
   pt->AddText(Title);
   pt->AddText(LumiTitle);
   pt->Draw();
   c->cd();
   TPad *pad2 = new TPad("pad2a", "pad2a", 0, 0, 1, 0.35);
   pad2->SetTopMargin(0);
   pad2->Draw();
   pad2->cd();
   TH1D* r = new TH1D(*selection);
   r->SetTitle("");
   r->SetLabelSize(0.08, "XYZ");
   r->SetLabelOffset(0.01, "XYZ");
   r->SetTitleSize(0.09, "XYZ");
   r->SetTitleOffset(0.65, "Y");
   r->SetTickLength(0.05);
   r->SetYTitle(RatioTitle);
   r->SetStats(0);
   r->SetMarkerStyle(20);
   r->SetMarkerSize(0.9);
   r->SetMarkerColor(kBlack);
   r->Reset();
   r->Add(prediction, 1);
   r->Add(selection, -1);
   r->Divide(selection);
   r->SetMaximum(1.2);
   r->SetMinimum(-1.2);
   r->Draw("ep");
   TLine l;
   l.DrawLine(MinX, 0., MaxX, 0.);
   c->cd();
   return c;
}
Example #22
0
void drawDCAcontamination(){
gStyle->SetOptStat(0);
    TFile * file = TFile::Open("/Users/sandrobjelogrlic/Analysis/HFCorrelations/Results/MCCE/83_12022015/10f7a/AnalysisResults.root");
    
    TDirectoryFile * dir = (TDirectoryFile*)file->Get("PWGHF_HFCJ_SE_EffY_DEffY_vsPt_32_bins_SE_RECO_reco_2_348_sigmas");
    TList * list = (TList*)dir->Get("OutputMCSE_RECO");
    
    TH1D * isPhysPrimDCA = (TH1D*)list->FindObject("isPhysPrimDCA");
    TH1D * isSecondaryDCA = (TH1D*)list->FindObject("isSecondaryDCA");
    
    isPhysPrimDCA->GetXaxis()->SetRangeUser(0,2);
    
    isPhysPrimDCA->SetLineColor(2);
    isSecondaryDCA->SetLineColor(4);
     isPhysPrimDCA->SetTitle("; DCA_{XY} (cm); Counts");
    isPhysPrimDCA->GetYaxis()->SetTitleOffset(1.2);
    
    TPaveText * PaveText = new TPaveText(0.5,0.55,0.8,0.7,"NDC");
    PaveText->SetBorderSize(0);
    PaveText->SetFillColor(0);
    PaveText->SetName("pave");
   // PaveText->AddText("THIS THESIS");
   // PaveText->AddText(" ");
    PaveText->AddText("Phytia, pp #sqrt{s} = 7 TeV");
    //PaveText->AddText(" ");
   // PaveText->AddText("Fraction of Primary tracks as funct");
    
    TLine * cut = new TLine(0.25,0,0.25,10000000);
    cut->SetLineStyle(2);
    
    TLegend * legend = new TLegend(0.4,0.7,0.8,0.85);
    //  TLegend * legend = new TLegend(0.1, 1.2*DStarPeak->GetBinContent(DStarPeak->GetMaximumBin()),0.4, 1.6*DStarPeak->GetBinContent(DStarPeak->GetMaximumBin()));
    legend->SetFillColor(0);
    legend->SetTextSize(0.03);
    
    legend->SetBorderSize(0);
    legend->AddEntry(isPhysPrimDCA,"Primary tracks","l");
    legend->AddEntry(isSecondaryDCA,"Secondary tracks","l");
    legend->AddEntry(cut,"Standard cut, DCA_{XY} < 0.25 cm","l");
    //legend->AddEntry(h_Perugia2011,"Pythia, Perugia 2011 tune","lep");
    
    
    
    
    TCanvas * c1 = new TCanvas("c1","c1",0,0,1000,1000);
    c1->cd();
    c1->SetLogy();
    isPhysPrimDCA->Draw();
    isSecondaryDCA->Draw("same");
    legend->Draw("same");
    PaveText->Draw("same");
    cut->Draw("same");
    
    
    
   // cout << "Integral is " << getIntegral(DCA,isPhysPrimDCA) << endl;
    TLegend * legend2 = new TLegend(0.4,0.7,0.8,0.85);
    //  TLegend * legend = new TLegend(0.1, 1.2*DStarPeak->GetBinContent(DStarPeak->GetMaximumBin()),0.4, 1.6*DStarPeak->GetBinContent(DStarPeak->GetMaximumBin()));
    legend2->SetFillColor(0);
    legend2->SetTextSize(0.03);
    
    legend2->SetBorderSize(0);
 
    legend2->AddEntry(cut,"Standard cut, DCA_{XY} < 0.25 cm","l");
    
    TPaveText * PaveText2 = new TPaveText(0.5,0.3,0.8,0.5,"NDC");
    PaveText2->SetBorderSize(0);
    PaveText2->SetFillColor(0);
    PaveText2->SetName("pave2");
    // PaveText->AddText("THIS THESIS");
    // PaveText->AddText(" ");
    PaveText2->AddText("PYTHIA, pp #sqrt{s} = 7 TeV");
    TH1D * contamination = (TH1D*)isPhysPrimDCA->Clone("contamination");
    contamination->Reset();
    contamination->SetTitle("; DCA_{XY} (cm); Purity");
    
    contamination->GetYaxis()->SetRangeUser(0.8,1.05);
    contamination->GetXaxis()->SetRangeUser(0,1);
    contamination->SetLineColor(1);
    contamination->SetLineWidth(2);
    contamination->GetYaxis()->SetTitleOffset(1.4);


    Double_t dcavalue = 0;
    
    for(Int_t k=0; k<2000; k++){
     
        dcavalue += 0.001;
        contamination->SetBinContent(k+1,getPurity(dcavalue,isPhysPrimDCA,isSecondaryDCA));
    }
    
    TLine * cut2 = new TLine(0.25,0.8,0.25,1.05);
    cut2->SetLineStyle(2);
    
    TCanvas * c2 = new TCanvas("c2","c2",0,0,1000,1000); c2->cd();
    contamination->Draw();
    PaveText2->Draw("same");
    cut2->Draw("same");
    legend2->Draw("same");
    
    
     c1->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/DCADistrib.pdf");
     c1->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/DCADistrib.eps");
    c1->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/DCADistrib.png");
     c1->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/DCADistrib.root");
    c2->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/purity.pdf");
     c2->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/purity.png");
     c2->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/purity.eps");
     c2->SaveAs("/Users/sandrobjelogrlic/PhD_Thesis/Figures/Chapter_3/purity.root");
   
}
Example #23
0
void comparisonJetMCData(string plot,int rebin){
  string tmp;

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

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


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

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

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


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

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

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

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


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



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

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

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

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

    data->Draw("E1");


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

    /// Tau 

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

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

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

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

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

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


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

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

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

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

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


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

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

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

      hsum->Add(qcdTotEM);

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

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

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

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

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

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

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

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

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

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


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

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


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

    CanvPlot->Update();

	


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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    cold=false;
    }
  }
  return;
}
Example #24
0
void extractFlowVZERO(Int_t icentr,const char *type,Int_t arm,Float_t pTh,Bool_t isMC,Int_t addbin){
  LoadLib();

  char name[100];
  snprintf(name,100,"AnalysisResults%s.root",type);
  if(!fo) fo = new TFile(name);

  new TCanvas();

  Int_t cMin[] = {0,5,10,20,30,40,50,60,70};
  Int_t cMax[] = {5,10,20,30,40,50,60,70,80};

  if(kNUOcorr){ // Compute correction for NUO in TOF
    compareTPCTOF(icentr,0,arm,pTh,addbin);
//     compareTPCTOF(icentr,1,arm,pTh,addbin);
//     compareTPCTOF(icentr,2,arm,pTh,addbin);
//     compareTPCTOF(icentr,3,arm,pTh,addbin);
//     compareTPCTOF(icentr,4,arm,pTh,addbin);
  }

  TProfile *pAll;
  pAll=extractFlowVZEROsingle(icentr,0,arm,0,pTh,addbin,"all",0,1);
  pAll->SetMarkerStyle(24);
  TProfile *pPiTOF,*pPiTPC,*pPiTPC2;
  pPiTOF=extractFlowVZEROsingle(icentr,1,arm,0,pTh,addbin,"piTOF",1,1);
  pPiTPC=extractFlowVZEROsingle(icentr,1,arm,0,pTh,addbin,"piTPC",0,0);
  pPiTPC2=extractFlowVZEROsingle(icentr,1,arm,0,pTh,addbin,"piTPC2",2,2);
  pPiTPC->Add(pPiTPC2);

  TH1D *hPi = pPiTOF->ProjectionX("hPi");
  hPi->SetLineColor(4);
  hPi->SetMarkerColor(4);
  hPi->SetMarkerStyle(20);
  for(Int_t i=1;i <=hPi->GetNbinsX();i++){
    Float_t x = hPi->GetBinCenter(i);
    if(x < 0.2){
      hPi->SetBinContent(i,0);
      hPi->SetBinError(i,0);
    }
    else if(x < 0.5){
      hPi->SetBinContent(i,pPiTPC->GetBinContent(i));
      hPi->SetBinError(i,pPiTPC->GetBinError(i));      
    }
    else{
      if(kNUOcorr){
	hPi->SetBinContent(i,pPiTOF->GetBinContent(i) + hNUO[0]->GetBinContent(i));
	hPi->SetBinError(i,pPiTOF->GetBinError(i));      
      }
      else{
	hPi->SetBinContent(i,pPiTOF->GetBinContent(i));
	hPi->SetBinError(i,pPiTOF->GetBinError(i));      
      }
    }
  }

  TProfile *pElTOF,*pElTPC,*pElTPC2;
  pElTOF=extractFlowVZEROsingle(icentr,4,arm,0,pTh,addbin,"piTOF",1,1);
  pElTPC=extractFlowVZEROsingle(icentr,4,arm,0,pTh,addbin,"piTPC",0,0);
  pElTPC2=extractFlowVZEROsingle(icentr,4,arm,0,pTh,addbin,"piTPC2",2,2);
  pElTPC->Add(pElTPC2);

  TH1D *hEl = pElTOF->ProjectionX("hEl");
  hEl->SetLineColor(6);
  hEl->SetMarkerColor(6);
  hEl->SetMarkerStyle(20);
  for(Int_t i=1;i <=hEl->GetNbinsX();i++){
    Float_t x = hEl->GetBinCenter(i);
    if(x < 0.2){
      hEl->SetBinContent(i,0);
      hEl->SetBinError(i,0);
    }
    else if(x < 0.3){
      hEl->SetBinContent(i,pElTPC->GetBinContent(i));
      hEl->SetBinError(i,pElTPC->GetBinError(i));      
    }
    else{
      if(kNUOcorr){
	hEl->SetBinContent(i,pElTOF->GetBinContent(i) + hNUO[0]->GetBinContent(i));
	hEl->SetBinError(i,pElTOF->GetBinError(i));      
      }
      else{
	hEl->SetBinContent(i,pElTOF->GetBinContent(i));
	hEl->SetBinError(i,pElTOF->GetBinError(i));      
      }
    }
  }

  TProfile *pKTOF,*pKTPC,*pKTPC2;
  pKTOF=extractFlowVZEROsingle(icentr,2,arm,0,pTh,addbin,"kaTOF",1,1);
  pKTPC=extractFlowVZEROsingle(icentr,2,arm,0,pTh,addbin,"kaTPC",0,0);
  pKTPC2=extractFlowVZEROsingle(icentr,2,arm,0,pTh,addbin,"kaTPC2",2,2);
  pKTPC->Add(pKTPC2);

  TH1D *hK = pKTOF->ProjectionX("hKa");
  hK->SetLineColor(1);
  hK->SetMarkerColor(1);
  hK->SetMarkerStyle(21);
  for(Int_t i=1;i <=hK->GetNbinsX();i++){
    Float_t x = hK->GetBinCenter(i);
    if(x < 0.25){
      hK->SetBinContent(i,0);
      hK->SetBinError(i,0);
    }
    else if(x < 0.45){
      hK->SetBinContent(i,pKTPC->GetBinContent(i));
      hK->SetBinError(i,pKTPC->GetBinError(i));      
    }
    else{
      if(kNUOcorr){
	hK->SetBinContent(i,pKTOF->GetBinContent(i) + hNUO[0]->GetBinContent(i));
	hK->SetBinError(i,pKTOF->GetBinError(i));      
      }
      else{
	hK->SetBinContent(i,pKTOF->GetBinContent(i));
	hK->SetBinError(i,pKTOF->GetBinError(i));      
      }
    }
  }

  TProfile *pPrTOF,*pPrTOF2,*pPrTPC,*pPrTPC2;
  pPrTOF=extractFlowVZEROsingle(icentr,3,arm,0,pTh,addbin,"prTOF",1,1,-1,-1);
  pPrTOF2=extractFlowVZEROsingle(icentr,3,arm,0,pTh,addbin,"prTOF2",1,1,-1,1);
  pPrTPC=extractFlowVZEROsingle(icentr,3,arm,0,pTh,addbin,"prTPC",0,0,-1,-1);
  pPrTPC2=extractFlowVZEROsingle(icentr,3,arm,0,pTh,addbin,"prTPC2",2,2,-1,-1);
  pPrTPC->Add(pPrTPC2);

  TH1D *hPr = pPrTOF->ProjectionX("hPr");
  hPr->SetLineColor(2);
  hPr->SetMarkerColor(2);
  hPr->SetMarkerStyle(22);
  for(Int_t i=1;i <=hPr->GetNbinsX();i++){
    Float_t x = hPr->GetBinCenter(i);
    if(x < 0.3){
      hPr->SetBinContent(i,0);
      hPr->SetBinError(i,0);
    }
    else if(x < 1.0){
      hPr->SetBinContent(i,pPrTPC->GetBinContent(i));
      hPr->SetBinError(i,pPrTPC->GetBinError(i));      
    }
    else{
      if(x < 3){
	if(kNUOcorr){
	  hPr->SetBinContent(i,pPrTOF->GetBinContent(i) + hNUO[0]->GetBinContent(i));
	  hPr->SetBinError(i,pPrTOF->GetBinError(i));      
	}
	else{
	  hPr->SetBinContent(i,pPrTOF->GetBinContent(i));
	  hPr->SetBinError(i,pPrTOF->GetBinError(i));      
	}
      }
      else{
	if(kNUOcorr){
	  hPr->SetBinContent(i,pPrTOF2->GetBinContent(i) + hNUO[0]->GetBinContent(i));
	  hPr->SetBinError(i,pPrTOF2->GetBinError(i));      
	}
	else{
	  hPr->SetBinContent(i,pPrTOF2->GetBinContent(i));
	  hPr->SetBinError(i,pPrTOF2->GetBinError(i));      
	}
      }
    }
  }
  
  pAll->Draw();
  hPi->Draw("SAME");
  hK->Draw("SAME");
  hPr->Draw("SAME");


  char name[100];


  // PID correction
  if(kPIDcorr){
    TFile *fPidTOF = new TFile("$ALICE_ROOT/PWGCF/FLOW/other/BayesianPIDcontTPCTOF.root");
    TFile *fPidTPC = new TFile("$ALICE_ROOT/PWGCF/FLOW/other/BayesianPIDcontTPC.root");
    // pi histos
    sprintf(name,"Pi_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiPi=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pi_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiEl=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pi_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiKa=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pi_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiPr=(TH1D *) fPidTOF->Get(name);
    TH1D *hPidAll = new TH1D(*hPidPiPi);
    hPidAll->Add(hPidPiKa);
    hPidAll->Add(hPidPiPr);
    hPidAll->Add(hPidPiEl);
    hPidPiPi->Divide(hPidAll);
    hPidPiKa->Divide(hPidAll);
    hPidPiPr->Divide(hPidAll);
    hPidPiEl->Divide(hPidAll);

    sprintf(name,"Pi_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiPiTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pi_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiElTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pi_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiKaTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pi_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPiPrTPC=(TH1D *) fPidTPC->Get(name);
    hPidAll->Reset();
    hPidAll->Add(hPidPiPiTPC);
    hPidAll->Add(hPidPiKaTPC);
    hPidAll->Add(hPidPiPrTPC);
    hPidAll->Add(hPidPiElTPC);
    hPidPiPiTPC->Divide(hPidAll);
    hPidPiKaTPC->Divide(hPidAll);
    hPidPiPrTPC->Divide(hPidAll);
    hPidPiElTPC->Divide(hPidAll);

    // K histos
    sprintf(name,"Ka_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaPi=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Ka_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaEl=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Ka_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaKa=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Ka_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaPr=(TH1D *) fPidTOF->Get(name);
    hPidAll->Reset();
    hPidAll->Add(hPidKaPi);
    hPidAll->Add(hPidKaKa);
    hPidAll->Add(hPidKaPr);
    hPidAll->Add(hPidKaEl);
    hPidKaPi->Divide(hPidAll);
    hPidKaKa->Divide(hPidAll);
    hPidKaPr->Divide(hPidAll);
    hPidKaEl->Divide(hPidAll);

    sprintf(name,"Ka_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaPiTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Ka_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaElTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Ka_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaKaTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Ka_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidKaPrTPC=(TH1D *) fPidTPC->Get(name);
    hPidAll->Reset();
    hPidAll->Add(hPidKaPiTPC);
    hPidAll->Add(hPidKaKaTPC);
    hPidAll->Add(hPidKaPrTPC);
    hPidAll->Add(hPidKaElTPC);
    hPidKaPiTPC->Divide(hPidAll);
    hPidKaKaTPC->Divide(hPidAll);
    hPidKaPrTPC->Divide(hPidAll);
    hPidKaElTPC->Divide(hPidAll);

    // pr histos
    sprintf(name,"Pr_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrPi=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pr_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrEl=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pr_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrKa=(TH1D *) fPidTOF->Get(name);
    sprintf(name,"Pr_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrPr=(TH1D *) fPidTOF->Get(name);
    hPidAll->Reset();
    hPidAll->Add(hPidPrPi);
    hPidAll->Add(hPidPrKa);
    hPidAll->Add(hPidPrPr);
    hPidAll->Add(hPidPrEl);
    hPidPrPi->Divide(hPidAll);
    hPidPrKa->Divide(hPidAll);
    hPidPrPr->Divide(hPidAll);
    hPidPrEl->Divide(hPidAll);

    sprintf(name,"Pr_IDas_Picentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrPiTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pr_IDas_Elcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrElTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pr_IDas_Kacentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrKaTPC=(TH1D *) fPidTPC->Get(name);
    sprintf(name,"Pr_IDas_Prcentr%i_pth%4.2f",icentr,pTh);
    TH1D *hPidPrPrTPC=(TH1D *) fPidTPC->Get(name);
    hPidAll->Reset();
    hPidAll->Add(hPidPrPiTPC);
    hPidAll->Add(hPidPrKaTPC);
    hPidAll->Add(hPidPrPrTPC);
    hPidAll->Add(hPidPrElTPC);
    hPidPrPiTPC->Divide(hPidAll);
    hPidPrKaTPC->Divide(hPidAll);
    hPidPrPrTPC->Divide(hPidAll);
    hPidPrElTPC->Divide(hPidAll);
 
    for(Int_t k=1;k <=hPi->GetNbinsX();k++){
      Float_t pt = hPi->GetBinCenter(k);
      Float_t xPi=hPi->GetBinContent(k)*hPidPiPi->Interpolate(pt) + hK->GetBinContent(k)*hPidPiKa->Interpolate(pt) + hPr->GetBinContent(k)*hPidPiPr->Interpolate(pt) + hEl->GetBinContent(k)*hPidPiEl->Interpolate(pt);
      if(pt < 0.5)
	xPi=hPi->GetBinContent(k)*hPidPiPiTPC->Interpolate(pt) + hK->GetBinContent(k)*hPidPiKaTPC->Interpolate(pt) + hPr->GetBinContent(k)*hPidPiPrTPC->Interpolate(pt) + hEl->GetBinContent(k)*hPidPiElTPC->Interpolate(pt);
      Float_t xKa=hPi->GetBinContent(k)*hPidKaPi->Interpolate(pt) + hK->GetBinContent(k)*hPidKaKa->Interpolate(pt) + hPr->GetBinContent(k)*hPidKaPr->Interpolate(pt) + hEl->GetBinContent(k)*hPidKaEl->Interpolate(pt);
      if(pt < 0.45)
	xKa=hPi->GetBinContent(k)*hPidKaPiTPC->Interpolate(pt) + hK->GetBinContent(k)*hPidKaKaTPC->Interpolate(pt) + hPr->GetBinContent(k)*hPidKaPrTPC->Interpolate(pt) + hEl->GetBinContent(k)*hPidKaElTPC->Interpolate(pt);
      Float_t xPr=hPi->GetBinContent(k)*hPidPrPi->Interpolate(pt) + hK->GetBinContent(k)*hPidPrKa->Interpolate(pt) + hPr->GetBinContent(k)*hPidPrPr->Interpolate(pt) + hEl->GetBinContent(k)*hPidPrEl->Interpolate(pt);
      if(pt < 1)
	xPr=hPi->GetBinContent(k)*hPidPrPiTPC->Interpolate(pt) + hK->GetBinContent(k)*hPidPrKaTPC->Interpolate(pt) + hPr->GetBinContent(k)*hPidPrPrTPC->Interpolate(pt) + hEl->GetBinContent(k)*hPidPrElTPC->Interpolate(pt);

      hPi->SetBinContent(k,hPi->GetBinContent(k)*2 - xPi);
      hK->SetBinContent(k,hK->GetBinContent(k)*2 - xKa);
      hPr->SetBinContent(k,hPr->GetBinContent(k)*2 - xPr);    
    }
  }


  // antiproton Feed down
  TProfile *pFromLambda = extractFlowVZEROsingle(icentr,11,arm,0,pTh,addbin,"pFromLambda",1,1);
  TProfile *piFromK = extractFlowVZEROsingle(icentr,12,arm,0,pTh,addbin,"piFromK",1,1,1,1);
  TProfile *pFromLambda2 = extractFlowVZEROsingle(icentr,11,arm,0,0.6,addbin,"pFromLambdanoPID",0,1);
  TProfile *piFromK2 = extractFlowVZEROsingle(icentr,12,arm,0,0.6,addbin,"piFromKnoPID",0,1);
  TProfile *piFromK3 = extractFlowVZEROsingle(icentr,12,arm,0,0.6,addbin,"piFromKnoPIDtof",1,1);

  TH1D *hFeedSyst = NULL;

  if(kFEEDcorr){
    hFeedSyst = new TH1D(*hPr);
    hFeedSyst->SetName("hFeedSyst");
    hFeedSyst->Reset();
    for(Int_t k=1;k <=hPr->GetNbinsX();k++){
      Float_t contam = 3.23174e-01 * TMath::Exp(- 9.46743e-01 *  hPr->GetBinCenter(k));
      Float_t corr = contam * pFromLambda->GetBinContent(k)/(1-contam);
      Float_t corrErr = contam * pFromLambda->GetBinError(k)/(1-contam);
      Float_t value = hPr->GetBinContent(k)/(1-contam) - corr;
      Float_t valueErr = hPr->GetBinError(k)/(1-contam);

      hFeedSyst->SetBinContent(k,hPr->GetBinContent(k) - value);
      hFeedSyst->SetBinContent(k,sqrt(corrErr*corrErr + valueErr*valueErr - hPr->GetBinError(k)*hPr->GetBinError(k)));

      hPr->SetBinContent(k,value);
      hPr->SetBinError(k,sqrt(corrErr*corrErr + valueErr*valueErr));

    }
    hFeedSyst->Divide(hPr);
  }
    
  // write output
  snprintf(name,100,"results%03i-%03iv%i_pTh%3.1f%s.root",cMin[icentr],cMax[icentr+addbin],arm,pTh,type);
  TFile *fout = new TFile(name,"RECREATE");
  pAll->ProjectionX()->Write();
  hPi->Write();
  hK->Write();
  hPr->Write();
  if(isMC){
    TH1D *pTmp = extractFlowVZEROsingle(icentr,0,arm,1,pTh,addbin,"allMC",1,1,-1,1)->ProjectionX();
    pTmp->SetLineColor(6);
    pTmp->SetMarkerColor(6);
    pTmp->SetMarkerStyle(24);
    pTmp->Write();
    pTmp = extractFlowVZEROsingle(icentr,1,arm,1,pTh,addbin,"piMC",1,1,-1,1)->ProjectionX();
    pTmp->SetLineColor(4);
    pTmp->SetMarkerColor(4);
    pTmp->SetMarkerStyle(24);
    pTmp->Write();
    pTmp = extractFlowVZEROsingle(icentr,2,arm,1,pTh,addbin,"kaMC",1,1,-1,1)->ProjectionX();
    pTmp->SetLineColor(1);
    pTmp->SetMarkerColor(1);
    pTmp->SetMarkerStyle(25);
    pTmp->Write();
    pTmp = extractFlowVZEROsingle(icentr,3,arm,1,pTh,addbin,"prMC",1,1,-1,-1)->ProjectionX();
    pTmp->SetLineColor(2);
    pTmp->SetMarkerColor(2);
    pTmp->SetMarkerStyle(26);
    pTmp->Write();
  }
  extractFlowVZEROsingle(icentr,2,arm,0,pTh,addbin,"kProf")->Write();
  extractFlowVZEROsingle(icentr,9,arm,0,pTh,addbin,"ks",0,1,1,1)->Write();
  extractFlowVZEROsingle(icentr,9,arm,0,pTh,addbin,"ksMy",0,1,-1,-1)->Write();
  extractFlowVZEROsingle(icentr,10,arm,0,pTh,addbin,"lambda")->Write();
  pFromLambda->Write();
  piFromK->Write();
  pFromLambda2->Write();
  piFromK2->Write();
  piFromK3->Write();
  if(hFeedSyst) hFeedSyst->Write();
  fout->Close();
}
void compareDataStackMC(std::string histoName,
                        std::string inputFile="inputFile.txt", bool update=false,
                        double xmin=-9999.0, double xmax=-9999.0,int rebin=1)
{

    //---------------------------------------------------------------------------
    // read in the MC root files
    //---------------------------------------------------------------------------
    std::string mcName[]= {
        "Dimuon Data",
        "DY+jets",
        "t#bar{t} +jets",
        "WW",
        "WZ"
    };

    std::string leptonName="test";
    double lumi =5000;

    if(inputFile.find("electron")!= std::string::npos) {
        leptonName="electron";
        lumi = 5200.7;
        mcName[0]="DiElectron Data";
    }
    else if(inputFile.find("muon")!= std::string::npos) {
        leptonName="muon";
        lumi = 5204.7;
    }

    cout << "Data luminosity = " << lumi << endl;

    std::vector<MCFile> myMCFiles;
    std::string dataFile;

    FILE *fTable = fopen(inputFile.data(),"r");

    int flag=1;
    while (flag!=-1) {
        // first reading input file
        char filename[500];
        flag=fscanf(fTable,"%s",filename);

        char tmp[1000];
        // read in x-section
        flag=fscanf(fTable,"%s",tmp);
        double cross=atof(tmp);

        // read in number of events
        flag=fscanf(fTable,"%s",tmp);
        double nevt=atof(tmp);

        double scale =lumi*cross/nevt;

        MCFile tempMCfile;
        tempMCfile.filename = filename;
        tempMCfile.scaleFactor = scale;

        if(flag!=-1 && cross>1e-6)
        {
            myMCFiles.push_back(tempMCfile);
            cout << tempMCfile.filename << "\t" << tempMCfile.scaleFactor << endl;
        }
        else if(flag!=-1) // is data
        {
            dataFile = filename;
        }
    }

    const unsigned int nfiles = myMCFiles.size();
    cout << "Data file = " << dataFile << endl;
    cout << "Reading " << nfiles << " files" << endl;

    if(nfiles==0)
    {
        cout << "There is no file for me to process!" << endl;
        return;
    }

    //-------------------------------------------------------------------------------
    // Declaring histograms to be used
    //-------------------------------------------------------------------------------

    // local histograms
    THStack *hs = new THStack(Form("%s_stack",histoName.data()),"");

    // for local debugging
    TH1D* h_deno[nfiles];
    int COLORCODE[]= {
        kRed-7,
        kRed-10,
        kRed-6,
        kMagenta-2,
        kMagenta-6,
        kBlue-7,
        kBlue-9
    };

    cout << "opening " << myMCFiles[0].filename << endl;
    TFile *f1 = TFile::Open(myMCFiles[0].filename.data());

    TH1D* h_template = (TH1D*)(f1->Get(Form("%s",histoName.data())));
    h_template->Reset();

    TH1D* h_all = (TH1D*)h_template->Clone(Form("%s_all",histoName.data()));
    h_all -> Reset();

    TFile *fdata = TFile::Open(dataFile.data());

    TH1D* h_data= (TH1D*)(fdata->Get(Form("%s",histoName.data())));
    h_data-> SetName(Form("%s_data",histoName.data()));

    h_data->Draw();

    //-------------------------------------------------------------------------------
    // combine
    //-------------------------------------------------------------------------------


    for(int ifile=nfiles-1; ifile>=0; ifile--) {

        cout << "File " << ifile << endl;
        TFile *f_temp = TFile::Open(myMCFiles[ifile].filename.data());
        cout << "opening " << myMCFiles[ifile].filename << endl;


        h_deno[ifile] = (TH1D*)(f_temp->Get(Form("%s",histoName.data())));
        h_deno[ifile] -> SetName(Form("h_deno_%d",ifile));
        h_deno[ifile] -> SetTitle(f_temp->GetName());
        h_deno[ifile] -> Rebin(rebin);
        h_deno[ifile] -> SetLineColor(COLORCODE[ifile]);
        h_deno[ifile] -> SetFillColor(COLORCODE[ifile]);
        h_deno[ifile] -> SetFillStyle(1001);
        h_deno[ifile] -> SetMarkerColor(COLORCODE[ifile]);
        h_deno[ifile] -> Sumw2();
        double weight = myMCFiles[ifile].scaleFactor;
        h_deno[ifile] -> Scale(weight);
        if(ifile==nfiles-1)
        {
            h_all    -> Rebin(rebin);
            h_all    -> Sumw2();
        }

        h_all    -> Add(h_deno[ifile]);
        hs       -> Add(h_deno[ifile]);

        // to be used with TEfficiency methods
        cout << h_deno[ifile]->GetEntries() << endl;
    } // end of loop over files

    float x1NDC = 0.620968;
    float y1NDC = 0.684322;
    float x2NDC = 0.762097;
    float y2NDC = 0.898305;

    TLegend* leg = new TLegend(x1NDC,y1NDC,x2NDC,y2NDC);
    leg->SetFillColor(0);
    leg->SetFillStyle(0);
    leg->SetTextSize(0.04);
    leg->SetBorderSize(0);
    leg->AddEntry(h_data,mcName[0].data());
    for(int i=0; i < nfiles; i++)
        leg->AddEntry(h_deno[i], mcName[i+1].data());

    int maxBin = h_data->GetMaximumBin();
    double max = h_data->GetMaximum()+h_data->GetBinError(maxBin);
    double maxmc = hs->GetMaximum();

    if(maxmc>max)max=maxmc;

    h_data->SetMaximum(1.1*max);

    TCanvas* c1 = new TCanvas("c1",inputFile.data(),0,0,500,500);
    h_data->SetMarkerSize(1);
    h_data->SetMarkerStyle(24);
    h_data->SetTitle("");
    h_data->Draw("e");
    if(xmin>-9999 && xmax>-9999) {
        h_data->GetXaxis()->SetRangeUser(xmin,xmax);
    }
    cout << "Data integral = " << h_data->Integral() << endl;
    hs->Draw("histsame");
    h_data->Draw("esame");
    leg->Draw("same");


    std::string dirName = "compareDataMC_" + leptonName;
    gSystem->mkdir(dirName.data());

    std::string filename;
    std::string psname ;
    psname = dirName+ "/overlay_" + histoName;
    filename = psname + ".eps";
    c1->Print(filename.data());
    filename = psname + ".gif";
    c1->Print(filename.data());
    filename = psname + ".pdf";
    c1->Print(filename.data());


    // study the ratios

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

    h_data->Draw("e");
    if(xmin>-9999 && xmax>-9999) {
        h_data->GetXaxis()->SetRangeUser(xmin,xmax);
    }
    cout << h_data->GetName() << " integral = " << h_data->Integral() << endl;
    hs->Draw("histsame");
    h_data->Draw("esame");
    leg->Draw("same");


    c2->cd(2);
    gStyle->SetStatW       (0.3);
    gStyle->SetStatH       (0.3);
    gStyle->SetStatX       (0.879447);
    gStyle->SetStatY       (0.939033);
    gStyle->SetStatFontSize(0.05);
    gStyle->SetStatBorderSize(0);
    gPad->SetRightMargin(0.04);
    gPad->SetTopMargin(0);
    gPad->SetBottomMargin(0.2);
    gPad->SetTickx();
    gStyle->SetOptFit(1);

    TH1D* hratio = (TH1D*)h_data->Clone("hratio");
    hratio->Reset();
    hratio->Divide(h_data,h_all,1.0,1.0);
    hratio->SetTitle("");
    hratio->SetMaximum(1.5);
    hratio->SetMinimum(0.5);
    hratio->SetTitleOffset(1.2,"Y");
    hratio->GetXaxis()->SetTitle(h_data->GetXaxis()->GetTitle());
    hratio->Draw("e1");

    cout << "( " << h_data->GetBinContent(maxBin) << "+-" << h_data->GetBinError(maxBin) << " )/("
         << h_all->GetBinContent(maxBin) << "+-" << h_all->GetBinError(maxBin) <<  ")= "
         << hratio->GetBinContent(maxBin) << "+-" << hratio->GetBinError(maxBin) << endl;

    psname = dirName+ "/ratio_" + histoName;
    filename = psname + ".eps";
    c2->Print(filename.data());
    filename = psname + ".gif";
    c2->Print(filename.data());
    filename = psname + ".pdf";
    c2->Print(filename.data());


    std::string remword  =".txt";
    size_t pos  = inputFile.find(remword);

    if(pos!= std::string::npos)
        inputFile.replace(pos,remword.length(),"");

    std::string command = "recreate";

    if(update)command ="update";

    TFile* outFile = new TFile(Form("combined_%s.root",inputFile.data()),command.data());
    h_all->Write();
    hs->Write();
    h_data->Write();
    outFile->Close();


}
double* IfitBin(TH1D* dataInput, TH1D* sigTemplate, TH1D* bkgTemplate)
{
   // Start TFractionFitter
   double Spara(0), eSpara(0);
   double Bpara(0), eBpara(0);
   TObjArray *mc = new TObjArray(2);
   mc->Add(sigTemplate);
   mc->Add(bkgTemplate);

   TFractionFitter *fitTemplate = new TFractionFitter(dataInput, mc);
   fitTemplate->Constrain(0, 0.0, 1.0);
   fitTemplate->Constrain(1, 0.0, 1.0);
   int status = fitTemplate->Fit();
   cout<<" Fitting status = "<<status<<endl;
   if (status == 0) {
      fitTemplate->GetResult(0, Spara, eSpara);
      fitTemplate->GetResult(1, Bpara, eBpara);

      cout<<" Fitting result = "<<endl;
      cout<<"               Chi2 = "<<fitTemplate->GetChisquare()<<endl;
      cout<<"                NDF = "<<fitTemplate->GetNDF()<<endl;
      cout<<"               Prob = "<<fitTemplate->GetProb()<<endl;
      cout<<"      Signal fraction     = "<<Spara<<"; Error = "<<eSpara<<endl;
      cout<<"      Background fraction = "<<Bpara<<"; Error = "<<eBpara<<endl;
   }

   TH1D *FitResultReal = (TH1D*)sigTemplate->Clone();
   TH1D *FitResultFake = (TH1D*)bkgTemplate->Clone();
   TH1D *FitResultAll  = (TH1D*)dataInput->Clone();
   FitResultReal->SetName("ResultReal");
   FitResultFake->SetName("ResultFake");
   FitResultAll->SetName("ResultAll");
   FitResultReal->Scale(1./FitResultReal->Integral()*Spara*dataInput->Integral());
   FitResultFake->Scale(1./FitResultFake->Integral()*Bpara*dataInput->Integral());
   FitResultAll->Reset();
   FitResultAll->Add(FitResultReal);
   FitResultAll->Add(FitResultFake);
   
   TCanvas *c1 = new TCanvas("c1", "", 600, 400);
   c1->cd();
   FitResultAll->SetXTitle("#sigma_{i#etai#eta}");
   FitResultAll->SetYTitle("Number of photons");
   FitResultAll->SetMinimum(0);
   FitResultAll->SetMaximum(FitResultAll->GetMaximum()*1.4);
   FitResultAll->SetLineColor(1);
   FitResultAll->SetLineWidth(2);
   FitResultAll->Draw();
   dataInput->SetMarkerStyle(21);
   dataInput->SetMarkerSize(0.7);
   dataInput->SetLineColor(1);
   dataInput->SetLineWidth(2);
   dataInput->Draw("PE1same");
   FitResultReal->SetLineColor(2);
   FitResultReal->SetFillColor(2);
   FitResultReal->SetFillStyle(3002);
   FitResultReal->Draw("same");
   FitResultFake->SetLineColor(4);
   FitResultFake->SetFillColor(4);
   FitResultFake->SetFillStyle(3004);
   FitResultFake->Draw("same");
   TLegend *leg1 = new TLegend(0.5,0.5,0.9,0.85);
   char text[200];
   leg1->SetFillColor(0);
   leg1->SetShadowColor(0);
   leg1->SetFillStyle(0);
   leg1->SetBorderSize(0);
   leg1->SetLineColor(0);
   sprintf(text,"Data: %5.1f events", dataInput->Integral());
   leg1->AddEntry(dataInput, text, "pl");
   sprintf(text,"Fitted: %5.1f events", FitResultAll->Integral());
   leg1->AddEntry(FitResultAll, text, "l");
   sprintf(text,"Signal %5.1f #pm %5.1f events", FitResultReal->Integral(), eSpara/Spara*FitResultReal->Integral());
   leg1->AddEntry(FitResultReal, text, "f");
   sprintf(text,"Background %5.1f #pm %5.1f events", FitResultFake->Integral(), eBpara/Bpara*FitResultFake->Integral());
   leg1->AddEntry(FitResultFake, text, "f");
   leg1->Draw();

   return;
}
Example #27
0
void drawSpecClosure(
    // HI
    TString infname="histff_tv12hydjuq80repass_j4_j2t2_et90_0601Closure_c0to12_a0to100.root"
    // pp
    //TString infname="histff_tv11_dj80mattpfgmv1_ak3pf_j2t2_an0509trk5.root"
    )
{
  TFile * inf = new TFile(infname);
  TString outdir = "out/20110601";
  gSystem->mkdir(outdir,true);
  TString outname = infname;
  outname.ReplaceAll(".root","");

  Bool_t doRebin = false;

  // Histograms
  TH1D * hSpec_ref = (TH1D*)inf->FindObjectAny("hGenSpecCorr0");
	cout << hSpec_ref << " " << hSpec_ref->GetName() << " " << hSpec_ref->GetEntries() << endl;
  TH1D * hSpec_corr[3], *hSpec_rat[3];
  for (Int_t lv=0; lv<3; ++lv) {
    hSpec_corr[lv] = (TH1D*)inf->FindObjectAny(Form("hRecSpecCorr%d",lv));
		cout << hSpec_corr[lv] << " " << hSpec_corr[lv]->GetName() << " " << hSpec_corr[lv]->GetEntries() << endl;
  }
  // styles
  hSpec_ref->SetLineColor(kRed);
  hSpec_corr[0]->SetMarkerStyle(kOpenSquare);

  // rebin
  if (doRebin) {
    for (Int_t lv=0; lv<3; ++lv) {
      hSpec_corr[lv]->Rebin(2);
      hSpec_corr[lv]->Scale(0.5);
    }
    hSpec_ref->Rebin(2);
    hSpec_ref->Scale(0.5);
  }

  // ratio
  for (Int_t lv=0; lv<3; ++lv) {
    hSpec_rat[lv] = (TH1D*)hSpec_corr[lv]->Clone(Form("%s_rat",hSpec_corr[lv]->GetName()));
    hSpec_rat[lv]->Divide(hSpec_ref);
  }

  // draw
  TCanvas * c2 = new TCanvas("c2","c2",500,900);
	TH1D * hFrame = (TH1D*)hSpec_ref->Clone("hFrame");
	hFrame->Reset();
  hFrame->SetTitle(";Trk p_{T};dN/dp_{T}");
  hFrame->SetAxisRange(10,100,"X");
  hFrame->SetAxisRange(2e-5,5e1,"Y");	
  handsomeTH1(hFrame);
  c2->Divide(1,2);
  c2->cd(1);
  gPad->SetLogy();
	hFrame->Draw("p");
  hSpec_ref->Draw("same hist");
  hSpec_corr[0]->Draw("sameE");
  hSpec_corr[2]->Draw("sameE");
  c2->cd(2);
  hSpec_rat[0]->SetTitle(";Trk p_{T};ratio");
  hSpec_rat[0]->SetAxisRange(10,100,"X");
  hSpec_rat[0]->SetAxisRange(0,2,"Y");
  handsomeTH1(hSpec_rat[0]);
  hSpec_rat[0]->Draw("E");
  hSpec_rat[2]->Draw("sameE");
  TLine * l = new TLine(10,1,120,1);
  l->SetLineStyle(2);
  l->Draw();

  c2->cd(1);
  TLegend *leg = new TLegend(0.52,0.65,0.91,0.91);
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->SetTextSize(0.035);
  leg->AddEntry(hSpec_ref,"PYTHIA+HYDJET 0-30%","");
  leg->AddEntry(hSpec_ref,"hiGoodTight","");
  leg->AddEntry(hSpec_ref,"Trk |#eta|<1","");
  leg->AddEntry(hSpec_ref,"Gen. Charged","l");
  leg->AddEntry(hSpec_corr[0],"Raw Reco","p");
  leg->AddEntry(hSpec_corr[2],"Corrected Reco","p");
  leg->Draw();

  c2->Print(outdir+"/Spectra_closure_"+outname+".gif");
}
Example #28
0
void dataBin(TDirectory *din, TDirectory *dout) {

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

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

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

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

    } // while
  } // ak7

  if (_jp_algo=="AK5") {

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

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


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

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

    } // while
  } // ak7

}
void photonTemplateProducer(int cutOpt=3, int ppHI = kHI, int isoChoice = kSumIso, int isoCut = -100, bool onlygjEvents=false, float specialSbCut=10, float mcSigShift=0, float sbBkgShift=0) {
  
  CutAndBinCollection cab;
  cab.setCuts(cutOpt);
  int nPtBin = cab.getNPtBin();
  vector<double> ptBinVector = cab.getPtBin();
  double ptBin[100];
  for ( int i = 0 ; i<=nPtBin ;i++) {
    ptBin[i] = ptBinVector[i];
  }
  
  int nCentBin = cab.getNCentBin();
  vector<double> centBinVector = cab.getCentBin();
  double centBin[100];
  for ( int i = 0 ; i<=nCentBin ;i++) {
    centBin[i] = centBinVector[i];
  }
  
  TString pphiLabel = "";
  if ( ppHI == kPP) pphiLabel = "pp";
  
  TCanvas* c1[5];
    
   TH1D* hData[5][5];
   TH1D* hSig[5][5];
   TH1D* hBkg[5][5];
   
   //   TH1D* hDatapp[5];
   //   TH1D* hSigpp[5];
   //   TH1D* hBkgpp[5];
   
   TH1D* hBkgMCsr[5][5];
   TH1D* hBkgMCsb[5][5];
      
   TH1D* rawSpectra[5];
   TH1D* finSpectra[5];
    
   TH2D* hPurity2D = new TH2D("hPurity2D",";pT(GeV);Centrality bin",nPtBin,ptBin,nCentBin,centBin);
   
   int nCent(-1);
   if ( ppHI == kHI ) nCent = nCentBin;
   if ( ppHI == kPP ) nCent = 1;
   
   for ( int icent = 1 ; icent<=nCent ; icent++) {
      rawSpectra[icent] = new TH1D(Form("rawSpec_icent%d_%s",icent,getIsoLabel(isoChoice).Data()),"",nPtBin,ptBin);
   }

   
   for (int ipt = 1; ipt <= nPtBin ; ipt++) { 
      c1[ipt] = new TCanvas(Form("c1_ipt%d",ipt),"",700,700);
      if ( ppHI == kHI )  makeMultiPanelCanvas(c1[ipt],nCent/2,2,0.0,0.0,0.2,0.15,0.02);

      TCut ptCut = Form("corrPt>%.2f && corrPt<%.2f",(float)ptBin[ipt-1],(float)ptBin[ipt]); 
      

      for ( int icent = 1 ; icent<=nCent ; icent++) { 
	 int lowCent =  centBinVector[icent-1];    
	 int highCent = centBinVector[icent]-1;
	 
	 hData[icent][ipt]  = new TH1D(Form("hData_cent%d_pt%d",icent,ipt),";shower shape (#sigma_{#eta#eta});Entries per photon candidate;",25,0,0.025);
	 hSig[icent][ipt]   = (TH1D*)hData[icent][ipt]->Clone(Form("hSig_cent%d_pt%d",icent,ipt));
	 hBkg[icent][ipt]   = (TH1D*)hData[icent][ipt]->Clone(Form("hBkg_cent%d_pt%d",icent,ipt));
	 hBkgMCsr[icent][ipt] = (TH1D*)hData[icent][ipt]->Clone(Form("hBkgMCsr_cent%d_pt%d",icent,ipt));
	 hBkgMCsb[icent][ipt] =(TH1D*)hData[icent][ipt]->Clone(Form("hBkgMCsb_cent%d_pt%d",icent,ipt));
	
	 TString fNamedata = fNameHIdata;
	 if ( ppHI == kPP ) fNamedata = fNamePPdata;
	 
	 getTemplate(ppHI, hSig[icent][ipt],"meaningless",isoChoice,isoCut, kSig,lowCent,highCent,ptCut,onlygjEvents,specialSbCut,mcSigShift);
	 getTemplate(ppHI, hData[icent][ipt],fNamedata ,isoChoice,isoCut, kData,lowCent,highCent,ptCut,onlygjEvents,specialSbCut);
	 if ( ppHI == kHI) {
	   getTemplate(ppHI, hBkg[icent][ipt], fNamedata ,isoChoice,isoCut, kSBB,lowCent,highCent,ptCut,onlygjEvents,specialSbCut,sbBkgShift);
	 }
	 if ( ppHI == kPP)
           getTemplate(ppHI, hBkg[icent][ipt], fNamedata ,isoChoice,isoCut, kSBBpp,lowCent,highCent,ptCut,onlygjEvents,specialSbCut);
	 
      }
            
      
      for ( int icent = 1 ; icent<=nCent ; icent++) {
	int lowerCent = centBinVector[icent-1];
	int upperCent =centBinVector[icent]-1;
	 
	 c1[ipt]->cd(nCent - icent+1);
	 fitResult fitr = doFit ( hSig[icent][ipt], hBkg[icent][ipt], hData[icent][ipt], 0.005,0.025);
	 if ( icent== nCent) drawPatch(0,0,0.05,0.14,0,1001, "ndc");
	 
	 cout << " shift = " << mcSigShift << endl;
	 cout << " purity = " << fitr.purity010 << endl;

	 
	 if ( ptBin[ipt]> 200)
	    drawText(Form(" E_{T}^{#gamma} > %d GeV", (int)ptBin[ipt-1]),0.5680963,0.529118);
	 else
	    drawText(Form("%d - %d GeV", (int)ptBin[ipt-1], (int)ptBin[ipt]),0.5680963,0.529118);
	 
	 if ( ppHI == kHI) {
	   drawText(Form("%.0f%% - %.0f%%", float((float)lowerCent*2.5), float((float)(upperCent+1)*2.5)),0.5680963,0.4369118);
	 }
	 else if ( ppHI == kPP) {
	   drawText("7TeV pp",0.5680963,0.4369118);
         }
	 
	 
	 
	 if ( (icent == nCent) || (icent == 2)) 
	   drawText(Form("Purity(#sigma_{#eta#eta} < 0.01) : %.0f%%", (float)fitr.purity010*100),0.5680963,0.3569118,1,15);
	 else 
	   drawText(Form("Purity(#sigma_{#eta#eta} < 0.01) : %.0f%%", (float)fitr.purity010*100),0.4980963,0.3569118,1,15);
	 
	 drawText(Form("#pm %.0f%% (stat)", float( 100. * fitr.purity010 * (float)fitr.nSigErr / (float)fitr.nSig ) ),0.6680963,0.2869118,1,15);
	 
	 
	 hPurity2D->SetBinContent(ipt,icent,fitr.purity010);
	 hPurity2D->SetBinError  (ipt,icent,fitr.purity010* fitr.nSigErr/fitr.nSig);

	 rawSpectra[icent]->SetBinContent( ipt, fitr.nSig);
	 rawSpectra[icent]->SetBinError(   ipt,fitr.nSigErr);

	 TString aa = "";
	 if (isoChoice == kSumIso)  aa = "Sum Iso Method";
	 if (isoChoice == k3dIso)   aa = "3d Cut Method";
	 if (isoChoice == kFisher)  aa = "Fisher Method";
	 
	 if ( (ppHI == kHI)  && ( icent==nCent -1) )
	   drawText(aa.Data(),0.1980963,0.8569118,1,20);
	 else if ( ppHI == kPP) 
	   drawText(aa.Data(),0.1980963,0.8569118,1,20);
	 
	 if ( icent<= 2) drawPatch(0,0,0.05,0.14,0,1001, ndcOpt);
	 //	 drawPatch(0.9,0.05,1.01,0.14,0,1001,ndcOpt);
	 if  ( (ppHI == kPP) && ( mcSigShift != 0 )) 
           drawText(Form("Signal template shifted by %f",mcSigShift),0.1980963,0.7569118,1,15);
	 if  ( (ppHI == kHI) && ( mcSigShift != 0 ) && (icent==3))
	   drawText(Form("Signal template shifted by %f",mcSigShift),0.1980963,0.7569118,1,15);


      }   
      
      TString ppLabel ="";  
      if ( ppHI == kPP) ppLabel = "_pp";
      TString shiftLabel="";
      if ( mcSigShift != 0 )  shiftLabel = Form("_%fSigShifted",(float)mcSigShift);
      c1[ipt]->SaveAs(Form("fittingPurity%s_%s_pt%d%s.pdf",ppLabel.Data(), getIsoLabel(isoChoice).Data(),ipt,shiftLabel.Data()));

   }
   
   // efficiency plots          
   TCanvas* c2  = new TCanvas("c2","",700,700); //100 + nCent_std*300,400);
   if ( ppHI == kHI) makeMultiPanelCanvas(c2,nCent/2,2,0.0,0.0,0.2,0.15,0.02);
   
   TH1D* heff[7][5];
   TH1D* heffGj[5];
   TH1D* heffDphi[5];
   TH1D* effSingleBin = new TH1D("effSingleBin","",1,60,100000);
   TGraphAsymmErrors* geff[7][5];
   TGraphAsymmErrors* gSingleBin = new TGraphAsymmErrors();
   TGraphAsymmErrors* geffGj[5];
   TGraphAsymmErrors* geffDphi[5];
   
   for (int icent = 1; icent <=nCent; icent++) {
     for ( int iid=1 ; iid<=5; iid++) {
       heff[icent][iid] = new TH1D(Form("heff_icent%d_id%d",icent,iid),";photon E_{T} (GeV);Efficiency",nPtBin, ptBin);
       if ( isoChoice == kSumIso2)
	 heff[icent][iid]->SetName(Form("heff_icent%d_id%d_isoCut%d",icent,iid,(int)isoCut));
       if ( isoChoice == kSumIso3)
	 heff[icent][iid]->SetName(Form("heff_icent%d_id%d_sbIsoCut%d",icent,iid,(int)specialSbCut));
       
       geff[icent][iid] = new TGraphAsymmErrors();
       geff[icent][iid]->SetName(Form("geff_%s",heff[icent][iid]->GetName()));
     }
     heffGj[icent]   = new TH1D(Form("heff_icent%d_Gj",  icent),";x_J#gamma;Efficiency",10,0,2);
     heffDphi[icent] = new TH1D(Form("heff_icent%d_Dphi",icent),";#Delta#phi of pair;Efficiency",9,0.3141592,3.141592);
     geffGj[icent] = new TGraphAsymmErrors();
     geffDphi[icent] = new TGraphAsymmErrors();

   }
   
   TCut srIsoCut = getIsoCut(isoChoice,isoCut);
   int nId=4;
   for (int icent = 1; icent <=nCent ; icent++) {
     int lowCent = centBinVector[icent-1];
     int highCent = centBinVector[icent]-1;
     TCut centCut      = Form("yEvt.hiBin >= %d && yEvt.hiBin<= %d",lowCent,highCent);
     if ( ppHI == kPP ) centCut = "";
     getEff("genMatchedPt",heff[icent][1],geff[icent][1],centCut, "swissCrx<0.90 && seedTime<4");
     getEff("genMatchedPt",heff[icent][2],geff[icent][2],centCut, "swissCrx<0.90 && seedTime<4 && hadronicOverEm<0.1");
     getEff("genMatchedPt",heff[icent][3],geff[icent][3],centCut, "swissCrx<0.90 && seedTime<4 && hadronicOverEm<0.1" && srIsoCut);
     getEff("genMatchedPt",heff[icent][4],geff[icent][4],centCut, "swissCrx<0.90 && seedTime<4 && hadronicOverEm<0.1 && sigmaIetaIeta<0.010"&& srIsoCut);
     effSingleBin->Reset();
     getEff("genMatchedPt",effSingleBin, gSingleBin, centCut, "swissCrx<0.90 && seedTime<4 && hadronicOverEm<0.1" && srIsoCut);
     
     
     cout << " here Gj" << endl;
     getEff("yJet.jtpt/photonEt",heffGj[icent],geffGj[icent], centCut && " genIso<5 && abs(genMomId)<=22 && photonEt>60 && abs(yJet.jteta)<2 && yJet.jtpt>30 && acos(cos(photonPhi-yJet.jtphi))>2.749", "hovere<0.1 && sigmaIetaIeta<0.010 && (cc4+cr4+ct4PtCut20)/0.9<1",true);
     getEff("acos(cos(photonPhi-yJet.jtphi))",heffDphi[icent],geffDphi[icent],centCut && " genIso<5 && abs(genMomId)<=22 && photonEt>60 && abs(yJet.jteta)<2 && yJet.jtpt>30", "hovere<0.1 && sigmaIetaIeta<0.010 && (cc4+cr4+ct4PtCut20)/0.9<1",true);
   }
   
   for (int icent = 1; icent <=nCent; icent++) {
     for ( int iid=1 ; iid<=nId ; iid++) {
       handsomeTH1(heff[icent][iid],ycolor[iid]);
       handsomeTGraph(geff[icent][iid],ycolor[iid]);
     }
   }
   

   
   
   
   TH1D* htmp = (TH1D*)heff[1][1]->Clone("htmp");
   htmp->Reset();
   htmp->SetAxisRange(0,1.3,"Y");
   htmp->SetYTitle("Efficiency");
   handsomeTH1(htmp);
   
   for (int icent = 1; icent <=nCent; icent++) {
      int lowerCent = centBinVector[icent-1];
      int upperCent = centBinVector[icent]-1;
      if ( ppHI == kHI) c2->cd(nCent - icent + 1);
      htmp->DrawCopy();
      for ( int iid=1 ; iid<=nId ; iid++) {
         heff[icent][iid]->Draw("p same");
         geff[icent][iid]->Draw("p");
	 
      }
      if ( ( icent == nCent ) ||   ( ppHI == kPP)  )
         {
            TLegend* leg1 =  new TLegend(0.25,0.20,0.95,0.55,NULL,"brNDC");
            easyLeg(leg1,"Photon ID efficiency");
            leg1->AddEntry(heff[icent][1],"spike rejection","lp");
            leg1->AddEntry(heff[icent][2],"+ H/E < 0.1","lp");
	    if (isoChoice == kSumIso)
	      leg1->AddEntry(heff[icent][3],"+ SumIso cut","lp");
	    if (isoChoice == kFisher) 
	      leg1->AddEntry(heff[icent][3],"+ Fisher cut","lp");
	    leg1->AddEntry(heff[icent][4],"+ #sigma_{#eta#eta} <0.010","lp");
            leg1->Draw();
         }
      drawText(Form("%.0f%% - %.0f%%", float((float)lowerCent*2.5), float((float)(upperCent+1)*2.5)),0.5680963,0.8369118);
      if ( icent<=2) drawPatch(0,0,0.05,0.14,0,1001,ndcOpt);
      //  drawPatch(0.9,0.05,1.01,0.14,0,1001,ndcOpt);
      
   }
   
   
   c2->SaveAs(Form("photonID_efficiency_%s.pdf",getIsoLabel(isoChoice).Data()));  

   TCanvas* c2b  = new TCanvas("c2b","",1000,500); //100 + nCent_std*300,400);                                             
   c2b->Divide(2,1);
   c2b->cd(1);
   TH1D* htmpG = (TH1D*)heffGj[1]->Clone("htmpG");
   htmpG->Reset();
   htmpG->SetAxisRange(0,1.3,"Y");
   htmpG->SetYTitle("Efficiency");
   handsomeTH1(htmpG);   
      
   TLegend* legCent = new TLegend(0.4657258,0.2245763,1,0.4512712,NULL,"brNDC");
   easyLeg(legCent,"Centrality");
   if (isoChoice == kSumIso)  easyLeg(legCent,"SumIso Method");
   if (isoChoice == kFisher)  easyLeg(legCent,"Fisher Method");
   cout<< " heffGj "<< endl << endl<< endl;
   for (int icent = 1; icent <=nCent; icent++) {
     handsomeTH1(heffGj[icent],ycolor[icent]);
     heffGj[icent]->Fit("pol1");
     heffGj[icent]->GetFunction("pol1")->SetLineColor(ycolor[icent]);
     heffGj[icent]->GetFunction("pol1")->SetLineStyle(7);
   }
   htmpG->DrawCopy();
   for (int icent = 1; icent <=nCent; icent++) {
     heffGj[icent]->Draw("same");
     int lowerCent = centBinVector[icent-1];     int upperCent = centBinVector[icent]-1;
     legCent->AddEntry(heffGj[icent],Form("%.0f%% - %.0f%%", float((float)lowerCent*2.5), float((float)(upperCent+1)*2.5)),"pl");
   }
   legCent->Draw();

   c2b->cd(2);
   TH1D* htmpDp = new TH1D("htmpDp",";#Delta#phi of pair;Efficiency",10,0,3.14);
   htmpDp->Reset();
   htmpDp->SetAxisRange(0,1.3,"Y");
   htmpDp->SetYTitle("Efficiency");
   handsomeTH1(htmpDp);
   cout << " heffDphi " << endl << endl << endl ;
   for (int icent = 1; icent <=nCent; icent++) {
     handsomeTH1(heffDphi[icent],ycolor[icent]);
     heffDphi[icent]->Fit("pol1");
     heffDphi[icent]->GetFunction("pol1")->SetLineColor(ycolor[icent]);
     heffDphi[icent]->GetFunction("pol1")->SetLineStyle(7);
   }
   htmpDp->DrawCopy();
   for (int icent = 1; icent <=nCent; icent++) {
     heffDphi[icent]->Draw("same");
   }
   legCent->Draw();
   
   c2b->SaveAs(Form("photonID_efficiency_%s_2.pdf",getIsoLabel(isoChoice).Data()));
   
   
   TCanvas* c3 = new TCanvas("cPurity","",500,500);

   TH1D* hPurity[10];
   for (int icent = 1; icent <=nCent; icent++) {
     hPurity[icent] = (TH1D*)hPurity2D->ProjectionX(Form("purity1D_icent%d",icent),icent,icent);
     hPurity[icent]->Fit("pol1");
     hPurity[icent]->GetFunction("pol1")->SetLineColor(ycolor[icent]);
     hPurity[icent]->GetFunction("pol1")->SetLineStyle(7);
   }
   TH1D* tempPurity = (TH1D*)hPurity[1]->Clone("purityTemp");
   tempPurity->Reset();
   handsomeTH1(tempPurity,1);
   tempPurity->SetXTitle("pT (Gev)");
   tempPurity->SetYTitle("Purity");
   tempPurity->SetAxisRange(0.45,1.2,"Y");

   tempPurity->Draw();
   for (int icent = 1; icent <=nCent; icent++) {
     handsomeTH1(hPurity[icent],ycolor[icent]);
     hPurity[icent]->Draw("same");
   }
   TLegend* legPurity = new TLegend(0.4657258,0.2245763,1,0.4512712,NULL,"brNDC");
   easyLeg(legPurity,"Purity");
   if (isoChoice == kSumIso)  easyLeg(legPurity,"SumIso Method");
   if (isoChoice == kFisher)  easyLeg(legPurity,"Fisher Method");
   for (int icent = 1; icent <=nCent; icent++){
     int lowerCent = centBinVector[icent-1];     int upperCent = centBinVector[icent]-1;
     legPurity->AddEntry(hPurity[icent],Form("%.0f%% - %.0f%%", float((float)lowerCent*2.5), float((float)(upperCent+1)*2.5)),"pl");
   }
   legPurity->Draw();
   
   if ( !onlygjEvents) 
     drawText("inclusive photon",0.25,0.2);
   
   c3->SaveAs(Form("purity_%s.pdf",getIsoLabel(isoChoice).Data()));
  
   
   TCanvas* c4 = new TCanvas("efficiencyCorrection","",1000,500);
   c4->Divide(2,1);
   c4->cd(1);
   for (int icent = 1; icent <=nCent; icent++) {
      TH1ScaleByWidth(rawSpectra[icent]);    // divide by width
      finSpectra[icent] = (TH1D*)rawSpectra[icent]->Clone(Form("finSpec_icent%d_%s",icent,getIsoLabel(isoChoice).Data()));
      if ( isoChoice == kSumIso2)
	 finSpectra[icent]->SetName(Form("finSpec_icent%d_%s_isoCut%d",icent,getIsoLabel(isoChoice).Data(),(int)isoCut));
      if ( isoChoice == kSumIso3)
         finSpectra[icent]->SetName(Form("finSpec_icent%d_%s_sbisoCut%d",icent,getIsoLabel(isoChoice).Data(),(int)specialSbCut));
      
      finSpectra[icent]->Divide(heff[icent][3]);
      handsomeTH1(finSpectra[icent],ycolor[icent]);
   }
   // TAA and centrality 
   //

   TFile outf = TFile(cab.getPurityFileName(),"recreate");
   hPurity2D->Write();
   for ( int icent=1 ; icent<=nCent ; icent++) {
      heff[icent][3]->Write();
      heff[icent][4]->Write();
      finSpectra[icent]->Write();
      hPurity[icent]->Write();
      for (int ipt = 1; ipt <= nPtBin ; ipt++) {
	hData[icent][ipt]->Write();
      }
      //      hBkgMCRatioFit[icent][1]->Write();

   }



   outf.Close();
}
void createGlauberTree(Int_t nEvents,
                       const char *outFileName) 
{
  AliPDG::AddParticlesToPdgDataBase();
  TDatabasePDG::Instance();

  // Run loader
  TFolder *folder = new TFolder("myfolder","myfolder");
  AliRunLoader* rl = new AliRunLoader(folder);
  rl->MakeHeader();
  rl->MakeStack();
  AliStack* stack = rl->Stack();
  //AliHeader* rheader = rl->GetHeader();

  AliGenHijing *genHi = new AliGenHijing(-1);
  genHi->SetStack(stack);
  genHi->SetEnergyCMS(2760);
  genHi->SetReferenceFrame("CMS");
  genHi->SetProjectile("A", 208, 82);
  genHi->SetTarget    ("A", 208, 82);
  genHi->SetPtHardMin (2.3);
  genHi->SetImpactParameterRange(0.,30);
  genHi->SetJetQuenching(0); // enable jet quenching
  genHi->SetShadowing(1);    // enable shadowing
  genHi->SetDecaysOff(1);    // neutral pion and heavy particle decays switched off
  genHi->Init();

  MyHeader  *myheader = new MyHeader;
  MyResponse *myresp  = new MyResponse;

  TFile *outFile = TFile::Open(outFileName, "RECREATE");
  outFile->SetCompressionLevel(5);
  TDirectory::TContext context(outFile);

  TTree *tree = new TTree("glaubertree", "Glauber tree");
  tree->Branch("header",&myheader, 32*1024, 99);
  tree->Branch("response",&myresp, 32*1024, 99);

  TNtuple *ntuple = new TNtuple("gnt", "Glauber ntuple", "npart:ncoll:b");

  Double_t etas[] = {-10,-5,-4,-3,-2,-1,0,1,2,3,4,5,10};
  TH1D *hNEta = new TH1D("hNeta","",12,etas);
  TH1D *hEtEta = new TH1D("hEteta","",12,etas);

  // create events and fill them
  for (Int_t iEvent = 0; iEvent < nEvents; ++iEvent) {

    cout << "Event " << iEvent+1 << "/" << nEvents << endl;;
    stack->Reset();
    hNEta->Reset();
    hEtEta->Reset();
    genHi->Generate();
  
    AliStack *s = genHi->GetStack();
    const TObjArray *parts = s->Particles();
    Int_t nents = parts->GetEntries();
    for (Int_t i = 0; i<nents; ++i) {
      TParticle *p = (TParticle*)parts->At(i);
      //p->Print();
      TParticlePDG *pdg = p->GetPDG(1);
      Int_t c = (Int_t)(TMath::Abs(pdg->Charge()));
      if (c!=0) {
        hNEta->Fill(p->Eta());
        hEtEta->Fill(p->Eta(),p->Pt());
      }
    }

    AliGenHijingEventHeader *h = (AliGenHijingEventHeader*)genHi->CollisionGeometry();
    myheader->fNATT = nents;
    myheader->fEATT = h->TotalEnergy();
    myheader->fJATT = h->HardScatters();
    myheader->fNT   = h->TargetParticipants();
    myheader->fNP   = h->ProjectileParticipants();
    myheader->fN00  = h->NwNw();
    myheader->fN01  = h->NwN();
    myheader->fN10  = h->NNw();
    myheader->fN11  = h->NN();
    myheader->fBB   = h->ImpactParameter();
    myheader->fRP   = h->ReactionPlaneAngle();
    myheader->fPSn  = h->ProjSpectatorsn();
    myheader->fPSp  = h->ProjSpectatorsp();
    myheader->fTSn  = h->TargSpectatorsn();
    myheader->fTSp  = h->TargSpectatorsn();

    myresp->fEtch0p = hEtEta->GetBinContent(hEtEta->FindBin(0.5));
    myresp->fEtch1p = hEtEta->GetBinContent(hEtEta->FindBin(1.5));
    myresp->fEtch2p = hEtEta->GetBinContent(hEtEta->FindBin(2.5));
    myresp->fEtch3p = hEtEta->GetBinContent(hEtEta->FindBin(3.5));
    myresp->fEtch4p = hEtEta->GetBinContent(hEtEta->FindBin(4.5));
    myresp->fEtch5p = hEtEta->GetBinContent(hEtEta->FindBin(5.5));
    myresp->fEtchrp = hEtEta->GetBinContent(hEtEta->FindBin(10.5));
    myresp->fEtch0n = hEtEta->GetBinContent(hEtEta->FindBin(-0.5));
    myresp->fEtch1n = hEtEta->GetBinContent(hEtEta->FindBin(-1.5));
    myresp->fEtch2n = hEtEta->GetBinContent(hEtEta->FindBin(-2.5));
    myresp->fEtch3n = hEtEta->GetBinContent(hEtEta->FindBin(-3.5));
    myresp->fEtch4n = hEtEta->GetBinContent(hEtEta->FindBin(-4.5));
    myresp->fEtch5n = hEtEta->GetBinContent(hEtEta->FindBin(-5.5));
    myresp->fEtchrn = hEtEta->GetBinContent(hEtEta->FindBin(-10.5));
    myresp->fNch0p  = hNEta->GetBinContent(hNEta->FindBin(0.5));
    myresp->fNch1p  = hNEta->GetBinContent(hNEta->FindBin(1.5));
    myresp->fNch2p  = hNEta->GetBinContent(hNEta->FindBin(2.5));
    myresp->fNch3p  = hNEta->GetBinContent(hNEta->FindBin(3.5));
    myresp->fNch4p  = hNEta->GetBinContent(hNEta->FindBin(4.5));
    myresp->fNch5p  = hNEta->GetBinContent(hNEta->FindBin(5.5));
    myresp->fNchrp  = hNEta->GetBinContent(hNEta->FindBin(10.5));
    myresp->fNch0n  = hNEta->GetBinContent(hNEta->FindBin(-0.5));
    myresp->fNch1n  = hNEta->GetBinContent(hNEta->FindBin(-1.5));
    myresp->fNch2n  = hNEta->GetBinContent(hNEta->FindBin(-2.5));
    myresp->fNch3n  = hNEta->GetBinContent(hNEta->FindBin(-3.5));
    myresp->fNch4n  = hNEta->GetBinContent(hNEta->FindBin(-4.5));
    myresp->fNch5n  = hNEta->GetBinContent(hNEta->FindBin(-5.5));
    myresp->fNchrn  = hNEta->GetBinContent(hNEta->FindBin(-10.5));

    tree->Fill();

    if (ntuple) {
      Int_t np = h->TargetParticipants() + h->ProjectileParticipants();
      Int_t nc = h->NwNw() + h->NwN() + h->NNw() + h->NN();
      Double_t b = h->ImpactParameter();
      ntuple->Fill(np,nc,b);
    }

  } // end of event loop

  tree->Write();
  ntuple->Write();
  outFile->Close();
}